JaweriaGenAI commited on
Commit
50e3328
Β·
verified Β·
1 Parent(s): 1e4e287

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -64
app.py CHANGED
@@ -18,7 +18,7 @@ def filter_emojis(text):
18
  return "".join(char if char not in emoji.EMOJI_DATA or char in allowed_emojis else "" for char in text)
19
 
20
  def chat_with_groq(message, history):
21
- messages = [{"role": "system", "content": "You are NovaBot πŸ€– – helpful, professional, and emoji-friendly."}]
22
  messages += history + [{"role": "user", "content": message}]
23
 
24
  headers = {
@@ -36,29 +36,29 @@ def chat_with_groq(message, history):
36
  reply = filter_emojis(raw_reply)
37
 
38
  history += [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
 
 
 
 
 
 
 
 
 
 
39
  return "", history, history
40
 
41
  def transcribe_audio(audio_path):
42
  if audio_path is None or not os.path.exists(audio_path):
43
- return "⚠️ No audio input."
44
  try:
45
  temp_wav = f"{uuid.uuid4()}.wav"
46
  AudioSegment.from_file(audio_path).export(temp_wav, format="wav")
47
  result = whisper_model.transcribe(temp_wav)
48
  os.remove(temp_wav)
49
  return result["text"]
50
- except Exception as e:
51
- return f"❌ Transcription error: {e}"
52
-
53
- def save_session(history):
54
- prompt = next((m["content"] for m in history if m["role"] == "user"), "chat")
55
- title = re.sub(r"[^\w\s]", "", prompt).strip()
56
- title = " ".join(title.split()[:6])
57
- timestamp = datetime.now().strftime("%b %d %Y %H-%M")
58
- filename = f"{title} - {timestamp}.json"
59
- with open(filename, "w", encoding="utf-8") as f:
60
- json.dump(history, f, indent=2, ensure_ascii=False)
61
- return f"βœ… Saved `{filename[:-5]}`"
62
 
63
  def list_saved_files():
64
  return sorted([f[:-5] for f in os.listdir() if f.endswith(".json")])
@@ -68,9 +68,9 @@ def load_chat(name):
68
  try:
69
  with open(filename, "r", encoding="utf-8") as f:
70
  history = json.load(f)
71
- return history, history, f"βœ… Loaded `{name}`"
72
- except Exception as e:
73
- return [], [], f"❌ Load error: {e}"
74
 
75
  # Gradio Interface
76
  with gr.Blocks(css="""
@@ -82,50 +82,4 @@ textarea, input[type='text'] {
82
  border: 1px solid #ccc; padding: 10px 15px; height: 48px;
83
  }
84
  .gr-button {
85
- background-color: #eaeaea !important; color: #000 !important;
86
- border: 1px solid #ccc !important; border-radius: 8px;
87
- }
88
- .gr-button:hover { background-color: #ddd !important; cursor: pointer; }
89
- .gr-dropdown { background-color: #fff !important; color: #000 !important; max-height: 200px; overflow-y: auto; }
90
- h1, h2, h3, .gr-markdown { color: #000 !important; }
91
- """) as demo:
92
-
93
- state = gr.State([])
94
-
95
- with gr.Row():
96
- with gr.Column(scale=1):
97
- gr.Markdown("## πŸ—‚οΈ Chats")
98
- new_chat_btn = gr.Button("πŸ†• New Chat")
99
- saved_dropdown = gr.Dropdown(label="πŸ“‚ Saved Conversations", choices=list_saved_files(), interactive=True)
100
- load_btn = gr.Button("πŸ“₯ Load Chat")
101
- save_btn = gr.Button("πŸ’Ύ Save Chat")
102
- save_msg = gr.Markdown()
103
- load_msg = gr.Markdown()
104
-
105
- with gr.Column(scale=3):
106
- gr.Markdown("# πŸ€– NovaBot")
107
- chatbot = gr.Chatbot(label="NovaBot Chat", height=400, type="messages")
108
-
109
- with gr.Row():
110
- chat_input = gr.Textbox(placeholder="Type your message...", scale=8, show_label=False)
111
- record_btn = gr.Button("πŸŽ™οΈ", scale=1)
112
- upload_btn = gr.File(file_types=[".mp3", ".wav", ".m4a"], label="πŸ“ Upload", visible=False)
113
-
114
- send_btn = gr.Button("Send πŸš€")
115
- recording = gr.Audio(type="filepath", visible=False)
116
-
117
- # Events
118
- send_btn.click(chat_with_groq, inputs=[chat_input, state], outputs=[chat_input, chatbot, state])
119
- chat_input.submit(chat_with_groq, inputs=[chat_input, state], outputs=[chat_input, chatbot, state])
120
- recording.change(transcribe_audio, inputs=recording, outputs=chat_input)
121
- upload_btn.change(transcribe_audio, inputs=upload_btn, outputs=chat_input)
122
-
123
- record_btn.click(lambda: gr.update(visible=True), None, recording)
124
-
125
- new_chat_btn.click(fn=lambda: ("", [], []), outputs=[chat_input, chatbot, state])
126
- save_btn.click(fn=save_session, inputs=[state], outputs=[save_msg])
127
- save_btn.click(fn=list_saved_files, outputs=[saved_dropdown])
128
- load_btn.click(fn=load_chat, inputs=[saved_dropdown], outputs=[chatbot, state, load_msg])
129
- demo.load(fn=list_saved_files, outputs=[saved_dropdown])
130
-
131
- demo.launch()
 
18
  return "".join(char if char not in emoji.EMOJI_DATA or char in allowed_emojis else "" for char in text)
19
 
20
  def chat_with_groq(message, history):
21
+ messages = [{"role": "system", "content": "You are Neobot – professional, helpful, accurate, and to-the-point."}]
22
  messages += history + [{"role": "user", "content": message}]
23
 
24
  headers = {
 
36
  reply = filter_emojis(raw_reply)
37
 
38
  history += [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
39
+
40
+ # Auto-save
41
+ prompt = next((m["content"] for m in history if m["role"] == "user"), "chat")
42
+ title = re.sub(r"[^\w\s]", "", prompt).strip()
43
+ title = " ".join(title.split()[:5]) or "Chat"
44
+ timestamp = datetime.now().strftime("%b %d")
45
+ filename = f"{title} - {timestamp}.json"
46
+ with open(filename, "w", encoding="utf-8") as f:
47
+ json.dump(history, f, indent=2, ensure_ascii=False)
48
+
49
  return "", history, history
50
 
51
  def transcribe_audio(audio_path):
52
  if audio_path is None or not os.path.exists(audio_path):
53
+ return ""
54
  try:
55
  temp_wav = f"{uuid.uuid4()}.wav"
56
  AudioSegment.from_file(audio_path).export(temp_wav, format="wav")
57
  result = whisper_model.transcribe(temp_wav)
58
  os.remove(temp_wav)
59
  return result["text"]
60
+ except Exception:
61
+ return "❌ Error transcribing."
 
 
 
 
 
 
 
 
 
 
62
 
63
  def list_saved_files():
64
  return sorted([f[:-5] for f in os.listdir() if f.endswith(".json")])
 
68
  try:
69
  with open(filename, "r", encoding="utf-8") as f:
70
  history = json.load(f)
71
+ return history, history
72
+ except:
73
+ return [], []
74
 
75
  # Gradio Interface
76
  with gr.Blocks(css="""
 
82
  border: 1px solid #ccc; padding: 10px 15px; height: 48px;
83
  }
84
  .gr-button {
85
+ background-col