JaweriaGenAI commited on
Commit
f33a336
Β·
verified Β·
1 Parent(s): 1c8c2c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -22
app.py CHANGED
@@ -1,34 +1,111 @@
1
  import gradio as gr
2
- import google.generativeai as genai
3
- import os
 
 
 
4
 
5
- # Get API key from Hugging Face secrets
6
- genai.configure(api_key=os.environ["GEMINI_API_KEY"])
7
- model = genai.GenerativeModel("gemini-pro")
8
 
9
- def gemini_chat(user_input):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  try:
11
- if not user_input.strip():
12
- return "Please type something."
13
- response = model.generate_content(user_input)
14
- return response.text
15
  except Exception as e:
16
- return f"⚠️ Error: {str(e)}"
17
 
 
18
  with gr.Blocks(css="""
19
- .gradio-container { max-width: 700px; margin: auto; font-family: 'Segoe UI', sans-serif; }
20
- .title { font-size: 2em; color: white; background-color: #1f2937; padding: 20px; border-radius: 12px; text-align: center; margin-bottom: 10px; }
21
- .textbox { border-radius: 12px; }
 
22
  """) as demo:
23
-
24
- gr.Markdown("<div class='title'>πŸ€– Welcome to Jaweria'sBot</div>")
25
-
 
 
 
 
 
 
 
 
 
 
 
 
26
  with gr.Row():
27
- user_input = gr.Textbox(placeholder="Type your message here...", lines=2, label="You", elem_classes=["textbox"])
28
-
29
- submit_btn = gr.Button("Send", variant="primary")
30
- response_output = gr.Textbox(label="Jaweria'sBot", interactive=False, lines=6, elem_classes=["textbox"])
 
 
31
 
32
- submit_btn.click(fn=gemini_chat, inputs=user_input, outputs=response_output)
 
 
 
 
 
 
 
 
33
 
34
  demo.launch()
 
1
  import gradio as gr
2
+ import os, json, re, uuid
3
+ from datetime import datetime
4
+ from pydub import AudioSegment
5
+ import whisper
6
+ import requests
7
 
8
+ # πŸ” API key
9
+ groq_key = "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" # Replace with your actual Groq key
 
10
 
11
+ # 🧠 Load Whisper locally
12
+ whisper_model = whisper.load_model("base") # Use "small"/"medium"/"large" for better results
13
+
14
+ # πŸ’¬ Chat using Groq
15
+ def chat_with_groq(message, history):
16
+ messages = [{"role": "system", "content": "You are JAWERIA'SBOT πŸ€– – cheerful, emoji-savvy, and sleek."}]
17
+ messages += history + [{"role": "user", "content": message}]
18
+
19
+ headers = {
20
+ "Authorization": f"Bearer {groq_key}",
21
+ "Content-Type": "application/json"
22
+ }
23
+
24
+ payload = {
25
+ "model": "llama3-70b-8192",
26
+ "messages": messages
27
+ }
28
+
29
+ response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=payload)
30
+ reply = response.json()["choices"][0]["message"]["content"]
31
+
32
+ history += [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
33
+ return "", history, history
34
+
35
+ # πŸŽ™οΈ Transcribe voice to text
36
+ def transcribe_audio(audio_path):
37
+ if audio_path is None or not os.path.exists(audio_path):
38
+ return "⚠️ No audio recorded."
39
+ try:
40
+ temp_wav = f"{uuid.uuid4()}.wav"
41
+ AudioSegment.from_file(audio_path).export(temp_wav, format="wav")
42
+ result = whisper_model.transcribe(temp_wav)
43
+ os.remove(temp_wav)
44
+ return result["text"]
45
+ except Exception as e:
46
+ return f"❌ Transcription error: {e}"
47
+
48
+ # πŸ’Ύ Save/load
49
+ def save_session(history):
50
+ prompt = next((m["content"] for m in history if m["role"] == "user"), "chat")
51
+ title = re.sub(r"[^\w\s]", "", prompt).strip()
52
+ title = " ".join(title.split()[:6])
53
+ timestamp = datetime.now().strftime("%b %d %Y %H-%M")
54
+ filename = f"{title} - {timestamp}.json"
55
+ with open(filename, "w", encoding="utf-8") as f:
56
+ json.dump(history, f, indent=2, ensure_ascii=False)
57
+ return f"βœ… Saved `{filename[:-5]}`"
58
+
59
+ def list_saved_files():
60
+ return sorted([f[:-5] for f in os.listdir() if f.endswith(".json")])
61
+
62
+ def load_chat(name):
63
+ filename = f"{name}.json"
64
  try:
65
+ with open(filename, "r", encoding="utf-8") as f:
66
+ history = json.load(f)
67
+ return history, history, f"βœ… Loaded `{name}`"
 
68
  except Exception as e:
69
+ return [], [], f"❌ Load error: {e}"
70
 
71
+ # πŸŒ™ Gradio UI
72
  with gr.Blocks(css="""
73
+ body {background-color: #111 !important; color: white;}
74
+ .gr-chatbot-message {background-color: #222 !important; color: white !important; border-radius: 6px;}
75
+ input[type='text'], textarea, select, .gr-textbox {background-color: #222 !important; color: white !important;}
76
+ .gr-button {background-color: #007acc !important; color: white !important;}
77
  """) as demo:
78
+
79
+ state = gr.State([])
80
+
81
+ gr.Markdown("<h1 style='text-align:center; color:#00ccff;'>✨ JAWERIA'SBOT πŸ€–</h1>")
82
+ gr.Markdown("<div style='text-align:center;'>Speak or type β€” your assistant listens and replies with text πŸ’¬</div>")
83
+
84
+ chatbot = gr.Chatbot(type="messages", height=350)
85
+ chat_input = gr.Textbox(label="πŸ’¬ Message", placeholder="Type or speak your message...")
86
+
87
+ send_btn = gr.Button("Send πŸš€")
88
+
89
+ with gr.Row():
90
+ voice_input = gr.Audio(label="🎀 Speak", type="filepath", interactive=True)
91
+ voice_btn = gr.Button("πŸŽ™οΈ Transcribe to Text")
92
+
93
  with gr.Row():
94
+ new_chat_btn = gr.Button("πŸ†• New")
95
+ save_btn = gr.Button("πŸ’Ύ Save")
96
+ saved_dropdown = gr.Dropdown(label="πŸ“‚ Load Saved", choices=list_saved_files())
97
+ load_btn = gr.Button("πŸ“₯ Load")
98
+ save_msg = gr.Markdown()
99
+ load_msg = gr.Markdown()
100
 
101
+ # πŸ”— Bind actions
102
+ send_btn.click(chat_with_groq, inputs=[chat_input, state], outputs=[chat_input, chatbot, state])
103
+ chat_input.submit(chat_with_groq, inputs=[chat_input, state], outputs=[chat_input, chatbot, state])
104
+ voice_btn.click(transcribe_audio, inputs=[voice_input], outputs=[chat_input])
105
+ new_chat_btn.click(fn=lambda: ("", [], []), outputs=[chat_input, chatbot, state])
106
+ save_btn.click(fn=save_session, inputs=[state], outputs=[save_msg])
107
+ save_btn.click(fn=list_saved_files, outputs=[saved_dropdown])
108
+ load_btn.click(fn=load_chat, inputs=[saved_dropdown], outputs=[chatbot, state, load_msg])
109
+ demo.load(fn=list_saved_files, outputs=[saved_dropdown])
110
 
111
  demo.launch()