general_chatbot / app.py
JaweriaGenAI's picture
Update app.py
2b9aa83 verified
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()