Spaces:
Running
Running
import os | |
import gradio as gr | |
import json, re | |
import openai | |
from datetime import datetime | |
import whisper | |
import requests | |
from pydub import AudioSegment | |
# π Groq API setup | |
os.environ["OPENAI_API_KEY"] = "your-groq-key-here" # Replace with your actual key! | |
openai.api_key = os.environ["OPENAI_API_KEY"] | |
openai.api_base = "https://api.groq.com/openai/v1" | |
model = whisper.load_model("base") | |
# π¬ Chat function | |
def chat_with_groq(message, history): | |
messages = [{"role": "system", "content": "You are JAWERIA'SBOT π€ β cheerful, emoji-savvy, and sleek."}] | |
messages += history + [{"role": "user", "content": message}] | |
try: | |
response = openai.ChatCompletion.create(model="llama3-70b-8192", messages=messages) | |
reply = response["choices"][0]["message"]["content"] | |
except Exception as e: | |
reply = f"β Error: {e}" | |
history += [{"role": "user", "content": message}, {"role": "assistant", "content": reply}] | |
return "", history, history | |
# πΎ Save chat session with readable filename | |
def save_session(history): | |
if not history: return "β No chat to save" | |
prompt = next((m["content"] for m in history if m["role"] == "user"), "chat") | |
title = re.sub(r"[^\w\s]", "", prompt).strip() | |
title = " ".join(title.split()[:6]) or "Chat" | |
timestamp = datetime.now().strftime("%b %d %Y %H-%M") | |
filename = f"{title} - {timestamp}.json" | |
with open(filename, "w", encoding="utf-8") as f: | |
json.dump(history, f, indent=2, ensure_ascii=False) | |
return f"β Chat saved as: {filename[:-5]}" | |
# π Loadable sessions | |
def list_saved_files(): | |
return sorted([f[:-5] for f in os.listdir() if f.endswith(".json")]) | |
def load_chat(name): | |
filename = f"{name}.json" | |
try: | |
with open(filename, "r", encoding="utf-8") as f: | |
history = json.load(f) | |
return history, history, f"β Loaded {name}" | |
except Exception as e: | |
return [], [], f"β Could not load {name}: {e}" | |
# ποΈ Audio-to-text | |
def transcribe_audio(file): | |
if not file: return "" | |
temp_path = "temp.wav" | |
AudioSegment.from_file(file).export(temp_path, format="wav") | |
result = model.transcribe(temp_path) | |
os.remove(temp_path) | |
return result["text"] | |
# π UI | |
with gr.Blocks(css=""" | |
body { background-color: #111; color: white; font-family: 'Segoe UI', sans-serif; } | |
.gr-button { background-color: #00aaff; color: white; border-radius: 8px; } | |
input[type='text'] { background-color: #222; color: white; border: 1px solid #555; border-radius: 10px; padding: 8px; } | |
.gr-chatbot-message { background-color: #222; border-radius: 12px; margin-bottom: 4px; padding: 6px; } | |
""") as demo: | |
state = gr.State([]) | |
gr.Markdown("## β¨ JAWERIA'SBOT π€", elem_id="title") | |
gr.Markdown("Ask boldly, explore endlessly. JAWERIA'SBOT is always listening π") | |
chatbot = gr.Chatbot(height=400) | |
with gr.Row(): | |
chat_input = gr.Textbox(placeholder="Type here or use voice...", scale=6, show_label=False) | |
send_btn = gr.Button("π Send", scale=1) | |
with gr.Row(): | |
voice_file = gr.File(file_types=[".mp3", ".wav"], label="ποΈ Upload Voice") | |
new_chat_btn = gr.Button("π New Chat") | |
save_btn = gr.Button("πΎ Save Chat") | |
status_msg = gr.Markdown() | |
saved_files_dropdown = gr.Dropdown(label="π Saved Chats", choices=list_saved_files(), interactive=True) | |
load_btn = gr.Button("π₯ Load Chat") | |
# π Hooks | |
send_btn.click(chat_with_groq, inputs=[chat_input, state], outputs=[chat_input, chatbot, state]) | |
chat_input.submit(chat_with_groq, inputs=[chat_input, state], outputs=[chat_input, chatbot, state]) | |
voice_file.change(transcribe_audio, inputs=[voice_file], outputs=[chat_input]) | |
new_chat_btn.click(fn=lambda: ("", [], []), outputs=[chat_input, chatbot, state]) | |
save_btn.click(fn=save_session, inputs=[state], outputs=[status_msg]) | |
save_btn.click(fn=list_saved_files, outputs=[saved_files_dropdown]) | |
load_btn.click(fn=load_chat, inputs=[saved_files_dropdown], outputs=[chatbot, state, status_msg]) | |
demo.launch() |