JaweriaGenAI commited on
Commit
b469735
Β·
verified Β·
1 Parent(s): eafff78

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -103
app.py CHANGED
@@ -1,116 +1,90 @@
1
- import os
2
  import gradio as gr
3
- import whisper
4
- import requests
5
- import json, uuid, re
 
6
  from datetime import datetime
7
- from pydub import AudioSegment
8
- import emoji
9
-
10
- # Keys and model
11
- GROQ_KEY = os.getenv("GROQ_API_KEY")
12
- MODEL = whisper.load_model("base")
13
-
14
- # Emoji filter
15
- ALLOWED = {"😊", "πŸ˜„", "πŸ‘", "πŸ€–", "✨", "πŸŽ‰", "πŸ’¬", "πŸ™Œ", "😎", "πŸ“’", "🧠", "βœ…"}
16
- def filter_emojis(text):
17
- return "".join(c if c not in emoji.EMOJI_DATA or c in ALLOWED else "" for c in text)
18
-
19
- # Save system
20
- CHAT_DIR = "saved_chats"
21
- os.makedirs(CHAT_DIR, exist_ok=True)
22
-
23
- def save_chat_manual(history):
24
- if not history: return
25
- prompt = re.sub(r"[^\w\s]", "", history[-2]["content"])[:30] or "Chat"
26
- timestamp = datetime.now().strftime("%b %d %Y %H-%M-%S")
27
- fname = f"{prompt} - {timestamp} - {uuid.uuid4().hex[:6]}.json"
28
- with open(os.path.join(CHAT_DIR, fname), "w", encoding="utf-8") as f:
 
 
 
29
  json.dump(history, f, indent=2, ensure_ascii=False)
 
30
 
31
- def list_saved_chats():
32
- return sorted(os.listdir(CHAT_DIR))
 
 
33
 
34
- def load_chat(fname):
 
 
35
  try:
36
- with open(os.path.join(CHAT_DIR, fname), "r", encoding="utf-8") as f:
37
- hist = json.load(f)
38
- return hist, hist
39
- except:
40
- return [], []
41
-
42
- # LLM chat
43
- def chat_with_groq(user_input, history):
44
- try:
45
- messages = [{"role": "system", "content": "You are Neobot, a helpful assistant."}]
46
- messages += history + [{"role": "user", "content": user_input}]
47
- res = requests.post(
48
- "https://api.groq.com/openai/v1/chat/completions",
49
- headers={"Authorization": f"Bearer {GROQ_KEY}", "Content-Type": "application/json"},
50
- json={"model": "llama3-70b-8192", "messages": messages}
51
- )
52
- reply = res.json()["choices"][0]["message"]["content"]
53
- reply = filter_emojis(reply)
54
- history += [{"role": "user", "content": user_input}, {"role": "assistant", "content": reply}]
55
- return "", history, history
56
  except Exception as e:
57
- error = f"❌ Error: {e}"
58
- history += [{"role": "assistant", "content": error}]
59
- return "", history, history
60
 
61
- # Transcribe audio
62
- def transcribe(audio_path):
63
- if not audio_path: return ""
64
- try:
65
- temp_wav = f"{uuid.uuid4()}.wav"
66
- AudioSegment.from_file(audio_path).export(temp_wav, format="wav")
67
- result = MODEL.transcribe(temp_wav)
68
- os.remove(temp_wav)
69
- return result["text"]
70
- except:
71
- return "❌ Transcription failed"
72
-
73
- # UI
74
  with gr.Blocks(css="""
75
- body { background-color: white; font-family: 'Segoe UI', sans-serif; }
76
- .gr-button { background-color: #f7f7f7; border-radius: 8px; }
77
- .gr-chatbot { border: 1px solid #ccc; border-radius: 12px; }
78
- .scroll-sidebar button { margin: 2px 0; width: 100%; text-align: left; border-radius: 6px; background: white; transition: background 0.2s; }
79
- .scroll-sidebar button:hover { background: #eee; }
80
  """) as demo:
81
 
82
  state = gr.State([])
 
 
 
 
 
 
 
 
 
 
83
  with gr.Row():
84
- with gr.Column(scale=1):
85
- gr.Markdown("### πŸ“ Saved Chats")
86
- chat_list = gr.Column(elem_id="scroll-sidebar") # Without 'scroll'
87
- save_btn = gr.Button("πŸ’Ύ Save Chat")
88
- refresh_btn = gr.Button("πŸ”„ Refresh")
89
- with gr.Column(scale=3):
90
- gr.Markdown("## πŸ€– Neobot Chat")
91
- bot = gr.Chatbot(height=400)
92
- with gr.Row():
93
- input_box = gr.Textbox(placeholder="Type a message or record one...", scale=6, show_label=False)
94
- send_btn = gr.Button("πŸš€ Send")
95
- voice_input = gr.Audio(label="πŸŽ™οΈ Record Voice", type="filepath")
96
-
97
- # Chat actions
98
- send_btn.click(chat_with_groq, inputs=[input_box, state], outputs=[input_box, bot, state])
99
- input_box.submit(chat_with_groq, inputs=[input_box, state], outputs=[input_box, bot, state])
100
- voice_input.change(transcribe, inputs=voice_input, outputs=[input_box])
101
- save_btn.click(lambda hist: save_chat_manual(hist), inputs=[state], outputs=[])
102
-
103
- # Sidebar buttons
104
- def render_chat_buttons():
105
- btns = []
106
- for f in list_saved_chats():
107
- def load_fn(fname=f): return load_chat(fname)
108
- btn = gr.Button(f[:-5])
109
- btn.click(load_fn, outputs=[bot, state])
110
- btns.append(btn)
111
- return btns
112
-
113
- refresh_btn.click(render_chat_buttons, outputs=[chat_list])
114
- demo.load(render_chat_buttons, outputs=[chat_list])
115
-
116
- demo.launch()
 
 
1
  import gradio as gr
2
+ import openai
3
+ import os
4
+ import json
5
+ import re
6
  from datetime import datetime
7
+
8
+ # πŸ” Groq API setup
9
+ os.environ["OPENAI_API_KEY"] = "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" # Replace with your actual key
10
+ openai.api_key = os.environ["OPENAI_API_KEY"]
11
+ openai.api_base = "https://api.groq.com/openai/v1"
12
+
13
+ # πŸ’¬ Chat function
14
+ def chat_with_groq(message, history):
15
+ messages = [{"role": "system", "content": "You are JAWERIA'SBOT πŸ€– – cheerful, emoji-savvy, and sleek."}]
16
+ messages += history
17
+ messages.append({"role": "user", "content": message})
18
+ response = openai.ChatCompletion.create(model="llama3-70b-8192", messages=messages)
19
+ reply = response["choices"][0]["message"]["content"]
20
+ history.append({"role": "user", "content": message})
21
+ history.append({"role": "assistant", "content": reply})
22
+ return "", history, history
23
+
24
+ # πŸ’Ύ Save chat session with readable filename
25
+ def save_session(history):
26
+ prompt = next((m["content"] for m in history if m["role"] == "user"), "chat")
27
+ title = re.sub(r"[^\w\s]", "", prompt).strip()
28
+ title = " ".join(title.split()[:6])
29
+ timestamp = datetime.now().strftime("%b %d %Y %H-%M")
30
+ filename = f"{title} - {timestamp}.json"
31
+ with open(filename, "w", encoding="utf-8") as f:
32
  json.dump(history, f, indent=2, ensure_ascii=False)
33
+ return f"βœ… Chat saved as: {filename[:-5]}"
34
 
35
+ # πŸ“œ List saved chats for dropdown
36
+ def list_saved_files():
37
+ files = [f[:-5] for f in os.listdir() if f.endswith(".json")]
38
+ return sorted(files)
39
 
40
+ # πŸ“₯ Load selected chat
41
+ def load_chat(name):
42
+ filename = f"{name}.json"
43
  try:
44
+ with open(filename, "r", encoding="utf-8") as f:
45
+ history = json.load(f)
46
+ return history, history, f"βœ… Loaded {name}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  except Exception as e:
48
+ return [], [], f"❌ Could not load {name}: {e}"
 
 
49
 
50
+ # πŸŒ’ Dark-themed UI
 
 
 
 
 
 
 
 
 
 
 
 
51
  with gr.Blocks(css="""
52
+ body {background-color: #111 !important; color: white;}
53
+ .gr-chatbot-message {background-color: #222 !important; color: white !important; border-radius: 8px; padding: 6px;}
54
+ input[type='text'] {background-color: #222 !important; color: white !important; border: 1px solid #555;}
55
+ .gr-button {background-color: #007acc !important; color: white !important; border-radius: 6px;}
 
56
  """) as demo:
57
 
58
  state = gr.State([])
59
+
60
+ gr.Markdown("<h1 style='text-align:center; color:#00ccff;'>✨ JAWERIA'SBOT πŸ€–</h1>")
61
+ gr.Markdown("<div style='text-align:center;'>Ask boldly, explore endlessly. JAWERIA'SBOT is always listening 🌌</div>")
62
+
63
+ chatbot = gr.Chatbot(type="messages") # πŸ”• No label shown
64
+
65
+ with gr.Row():
66
+ chat_input = gr.Textbox(placeholder="Type your message... 😊", show_label=False, scale=8)
67
+ send_btn = gr.Button("Send πŸš€", scale=2)
68
+
69
  with gr.Row():
70
+ new_chat_btn = gr.Button("πŸ†• Start New Chat")
71
+ save_btn = gr.Button("πŸ’Ύ Save Chat")
72
+
73
+ save_msg = gr.Markdown()
74
+ load_msg = gr.Markdown()
75
+
76
+ saved_files_dropdown = gr.Dropdown(label="πŸ“‚ Saved Chats", choices=list_saved_files(), interactive=True, allow_custom_value=False)
77
+ load_btn = gr.Button("πŸ“₯ Load Selected Chat")
78
+
79
+ # πŸš€ Message interactions
80
+ send_btn.click(chat_with_groq, inputs=[chat_input, state], outputs=[chat_input, chatbot, state])
81
+ chat_input.submit(chat_with_groq, inputs=[chat_input, state], outputs=[chat_input, chatbot, state])
82
+
83
+ new_chat_btn.click(fn=lambda: ("", [], []), outputs=[chat_input, chatbot, state])
84
+
85
+ save_btn.click(fn=save_session, inputs=[state], outputs=[save_msg])
86
+ save_btn.click(fn=list_saved_files, outputs=[saved_files_dropdown]) # πŸ” Refresh dropdown after saving
87
+
88
+ load_btn.click(fn=load_chat, inputs=[saved_files_dropdown], outputs=[chatbot, state, load_msg])
89
+
90
+ demo.launch()