JaweriaGenAI commited on
Commit
e841288
Β·
verified Β·
1 Parent(s): aa9cd89

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -26
app.py CHANGED
@@ -1,13 +1,13 @@
1
  import os
2
  import gradio as gr
3
- import requests
4
  import whisper
 
5
  import json, uuid, re
6
  from datetime import datetime
7
  from pydub import AudioSegment
8
  import emoji
9
 
10
- # Load keys and model
11
  GROQ_KEY = os.getenv("GROQ_API_KEY")
12
  MODEL = whisper.load_model("base")
13
 
@@ -16,18 +16,19 @@ 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 chats
20
  CHAT_DIR = "saved_chats"
21
  os.makedirs(CHAT_DIR, exist_ok=True)
22
 
23
- def save_chat(history):
24
- title = re.sub(r"[^\w\s]", "", history[-2]["content"])[:30] or "Chat"
 
25
  timestamp = datetime.now().strftime("%b %d %Y %H-%M-%S")
26
- fname = f"{title} - {timestamp} - {uuid.uuid4().hex[:6]}.json"
27
  with open(os.path.join(CHAT_DIR, fname), "w", encoding="utf-8") as f:
28
  json.dump(history, f, indent=2, ensure_ascii=False)
29
 
30
- def list_chats():
31
  return sorted(os.listdir(CHAT_DIR))
32
 
33
  def load_chat(fname):
@@ -35,7 +36,7 @@ def load_chat(fname):
35
  with open(os.path.join(CHAT_DIR, fname), "r", encoding="utf-8") as f:
36
  hist = json.load(f)
37
  return hist, hist
38
- except Exception:
39
  return [], []
40
 
41
  # LLM chat
@@ -51,7 +52,6 @@ def chat_with_groq(user_input, history):
51
  reply = res.json()["choices"][0]["message"]["content"]
52
  reply = filter_emojis(reply)
53
  history += [{"role": "user", "content": user_input}, {"role": "assistant", "content": reply}]
54
- save_chat(history)
55
  return "", history, history
56
  except Exception as e:
57
  error = f"❌ Error: {e}"
@@ -71,29 +71,46 @@ def transcribe(audio_path):
71
  return "❌ Transcription failed"
72
 
73
  # UI
74
- with gr.Blocks() as demo:
 
 
 
 
 
 
 
75
  state = gr.State([])
76
  with gr.Row():
77
  with gr.Column(scale=1):
78
- gr.Markdown("### Saved Chats")
79
- dropdown = gr.Dropdown(choices=list_chats(), label="Load chat")
80
- load_btn = gr.Button("πŸ“‚ Load")
81
- new_btn = gr.Button("πŸ†• New Chat")
82
  with gr.Column(scale=3):
83
- gr.Markdown("## πŸ€– Neobot")
84
  bot = gr.Chatbot(height=400)
85
- input_box = gr.Textbox(placeholder="Type or upload voice...", scale=8, show_label=False)
86
- send = gr.Button("πŸš€ Send")
87
- audio = gr.Audio(label="🎀 Voice Input", type="filepath")
88
- upload = gr.File(file_types=[".mp3", ".wav"], label="Upload Audio")
89
 
90
- # Events
91
- send.click(chat_with_groq, inputs=[input_box, state], outputs=[input_box, bot, state])
92
  input_box.submit(chat_with_groq, inputs=[input_box, state], outputs=[input_box, bot, state])
93
- audio.change(transcribe, inputs=audio, outputs=[input_box])
94
- upload.change(transcribe, inputs=upload, outputs=[input_box])
95
- load_btn.click(lambda fname: load_chat(fname), inputs=[dropdown], outputs=[bot, state])
96
- new_btn.click(lambda: ("", [], []), outputs=[input_box, bot, state])
97
- demo.load(lambda: gr.update(choices=list_chats()), outputs=[dropdown])
 
 
 
 
 
 
 
 
 
 
98
 
99
  demo.launch()
 
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
 
 
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):
 
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
 
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}"
 
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", scroll=True)
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()