general_chatbot / app.py
JaweriaGenAI's picture
Update app.py
f33a336 verified
raw
history blame
4.48 kB
import gradio as gr
import os, json, re, uuid
from datetime import datetime
from pydub import AudioSegment
import whisper
import requests
# πŸ” API key
groq_key = "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" # Replace with your actual Groq key
# 🧠 Load Whisper locally
whisper_model = whisper.load_model("base") # Use "small"/"medium"/"large" for better results
# πŸ’¬ Chat using Groq
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}]
headers = {
"Authorization": f"Bearer {groq_key}",
"Content-Type": "application/json"
}
payload = {
"model": "llama3-70b-8192",
"messages": messages
}
response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=payload)
reply = response.json()["choices"][0]["message"]["content"]
history += [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
return "", history, history
# πŸŽ™οΈ Transcribe voice to text
def transcribe_audio(audio_path):
if audio_path is None or not os.path.exists(audio_path):
return "⚠️ No audio recorded."
try:
temp_wav = f"{uuid.uuid4()}.wav"
AudioSegment.from_file(audio_path).export(temp_wav, format="wav")
result = whisper_model.transcribe(temp_wav)
os.remove(temp_wav)
return result["text"]
except Exception as e:
return f"❌ Transcription error: {e}"
# πŸ’Ύ Save/load
def save_session(history):
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])
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"βœ… Saved `{filename[:-5]}`"
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"❌ Load error: {e}"
# πŸŒ™ Gradio UI
with gr.Blocks(css="""
body {background-color: #111 !important; color: white;}
.gr-chatbot-message {background-color: #222 !important; color: white !important; border-radius: 6px;}
input[type='text'], textarea, select, .gr-textbox {background-color: #222 !important; color: white !important;}
.gr-button {background-color: #007acc !important; color: white !important;}
""") as demo:
state = gr.State([])
gr.Markdown("<h1 style='text-align:center; color:#00ccff;'>✨ JAWERIA'SBOT πŸ€–</h1>")
gr.Markdown("<div style='text-align:center;'>Speak or type β€” your assistant listens and replies with text πŸ’¬</div>")
chatbot = gr.Chatbot(type="messages", height=350)
chat_input = gr.Textbox(label="πŸ’¬ Message", placeholder="Type or speak your message...")
send_btn = gr.Button("Send πŸš€")
with gr.Row():
voice_input = gr.Audio(label="🎀 Speak", type="filepath", interactive=True)
voice_btn = gr.Button("πŸŽ™οΈ Transcribe to Text")
with gr.Row():
new_chat_btn = gr.Button("πŸ†• New")
save_btn = gr.Button("πŸ’Ύ Save")
saved_dropdown = gr.Dropdown(label="πŸ“‚ Load Saved", choices=list_saved_files())
load_btn = gr.Button("πŸ“₯ Load")
save_msg = gr.Markdown()
load_msg = gr.Markdown()
# πŸ”— Bind actions
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_btn.click(transcribe_audio, inputs=[voice_input], outputs=[chat_input])
new_chat_btn.click(fn=lambda: ("", [], []), outputs=[chat_input, chatbot, state])
save_btn.click(fn=save_session, inputs=[state], outputs=[save_msg])
save_btn.click(fn=list_saved_files, outputs=[saved_dropdown])
load_btn.click(fn=load_chat, inputs=[saved_dropdown], outputs=[chatbot, state, load_msg])
demo.load(fn=list_saved_files, outputs=[saved_dropdown])
demo.launch()