nguyenbh commited on
Commit
c2df150
·
1 Parent(s): 81ef463
Files changed (2) hide show
  1. app.py +781 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import os
4
+ import ssl
5
+ import base64
6
+ import urllib.request
7
+ import tempfile
8
+ import soundfile
9
+ from datetime import datetime
10
+ from typing import Dict, List, Optional, Tuple
11
+ import edge_tts
12
+ from langdetect import detect
13
+
14
+
15
+ # Custom CSS for better styling
16
+ CUSTOM_CSS = """
17
+ /* General styling */
18
+ .container {
19
+ max-width: 900px;
20
+ margin: auto;
21
+ }
22
+
23
+ /* Header styling */
24
+ #header {
25
+ text-align: center;
26
+ padding: 20px;
27
+ margin-bottom: 30px;
28
+ }
29
+
30
+ /* Component styling */
31
+ .input-section {
32
+ background: var(--background-fill-primary);
33
+ padding: 20px;
34
+ border-radius: 10px;
35
+ margin-bottom: 20px;
36
+ }
37
+
38
+ .output-section {
39
+ background: var(--background-fill-primary);
40
+ padding: 20px;
41
+ border-radius: 10px;
42
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
43
+ }
44
+
45
+ /* Note styling */
46
+ .note-card {
47
+ background: var(--background-fill-primary);
48
+ padding: 15px;
49
+ margin: 10px 0;
50
+ border-radius: 8px;
51
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
52
+ }
53
+
54
+ /* Adaptive text colors for both themes */
55
+ .output-section .prose {
56
+ color: var(--body-text-color) !important;
57
+ }
58
+
59
+ .output-section p,
60
+ .output-section h1,
61
+ .output-section h2,
62
+ .output-section h3,
63
+ .output-section h4,
64
+ .output-section h5,
65
+ .output-section h6 {
66
+ color: var(--body-text-color) !important;
67
+ }
68
+
69
+ /* Ensure Markdown content uses theme colors */
70
+ .output-section .markdown-body {
71
+ color: var(--body-text-color) !important;
72
+ background-color: var(--background-fill-primary) !important;
73
+ }
74
+
75
+ /* Style blockquotes and code blocks */
76
+ .output-section blockquote {
77
+ border-left: 3px solid var(--border-color-primary);
78
+ color: var(--body-text-color);
79
+ background: var(--background-fill-secondary);
80
+ }
81
+
82
+ .output-section code {
83
+ color: var(--body-text-color);
84
+ background: var(--background-fill-secondary);
85
+ }
86
+ """
87
+
88
+ # Create a light theme
89
+ LIGHT_THEME = gr.themes.Default(
90
+ primary_hue="blue",
91
+ secondary_hue="blue",
92
+ neutral_hue="slate",
93
+ font=["Source Sans Pro", "ui-sans-serif", "system-ui", "sans-serif"],
94
+ font_mono=["JetBrains Mono", "ui-monospace", "Consolas", "monospace"],
95
+ )
96
+
97
+ MULTILINGUAL_SYSYTEM_PROMPTS = {
98
+ 'english': {
99
+ 'system': """You are a world class AI assistant. From users' collection of random thoughts, you need to organize into a clear, concise, and actionable format. Please structure them into the following categories that STRICTLY follows this format:
100
+ 🧠 Main Idea/Theme – Summarize the central topic.
101
+
102
+ ✅ Actionable Steps – Break down what can be done next.
103
+
104
+ ❓ Open Questions – Highlight any uncertainties or areas that need further exploration.
105
+
106
+ Here are thoughts:""",
107
+ 'summarize': "Summarize the text above."
108
+ },
109
+ 'chinese': {
110
+ 'system': """你是一位世界级的AI助手。你需要将用户的随想整理成清晰、简洁和可行的格式。请严格按照以下格式将内容分类:
111
+ 🧠 主要想法/主题 – 总结核心话题。
112
+
113
+ ✅ 可行步骤 – 分解下一步可以做什么。
114
+
115
+ ❓ 开放性问题 – 突出任何不确定性或需要进一步探索的领域。
116
+
117
+ 以下是想法:""",
118
+ 'summarize': "总结上述文本。"
119
+ },
120
+ 'german': {
121
+ 'system': """Sie sind ein erstklassiger KI-Assistent. Sie müssen die zufälligen Gedanken der Benutzer in ein klares, prägnantes und umsetzbares Format bringen. Bitte strukturieren Sie die Inhalte streng nach folgendem Format:
122
+ 🧠 Hauptidee/Thema – Fassen Sie das zentrale Thema zusammen.
123
+
124
+ ✅ Umsetzbare Schritte – Schlüsseln Sie auf, was als nächstes getan werden kann.
125
+
126
+ ❓ Offene Fragen – Heben Sie Unklarheiten oder Bereiche hervor, die weiterer Erforschung bedürfen.
127
+
128
+ Hier sind die Gedanken:""",
129
+ 'summarize': "Fassen Sie den obigen Text zusammen."
130
+ },
131
+ 'french': {
132
+ 'system': """Vous êtes un assistant IA de classe mondiale. Vous devez organiser les pensées aléatoires des utilisateurs dans un format clair, concis et exploitable. Veuillez structurer le contenu en respectant strictement le format suivant:
133
+ 🧠 Idée/Thème principal – Résumez le sujet central.
134
+
135
+ ✅ Étapes exploitables – Décomposez ce qui peut être fait ensuite.
136
+
137
+ ❓ Questions ouvertes – Mettez en évidence les incertitudes ou les domaines nécessitant une exploration plus approfondie.
138
+
139
+ Voici les pensées :""",
140
+ 'summarize': "Résumez le texte ci-dessus."
141
+ },
142
+ 'italian': {
143
+ 'system': """Sei un assistente IA di classe mondiale. Devi organizzare i pensieri casuali degli utenti in un formato chiaro, conciso e pratico. Si prega di strutturare il contenuto seguendo rigorosamente questo formato:
144
+ 🧠 Idea/Tema principale – Riassumi l'argomento centrale.
145
+
146
+ ✅ Passi attuabili – Scomponi cosa si può fare dopo.
147
+
148
+ ❓ Domande aperte – Evidenzia eventuali incertezze o aree che necessitano di ulteriore esplorazione.
149
+
150
+ Ecco i pensieri:""",
151
+ 'summarize': "Riassumi il testo sopra."
152
+ },
153
+ 'japanese': {
154
+ 'system': """あなたは世界クラスのAIアシスタントです。ユーザーのランダムな考えを、明確で簡潔で実行可能な形式に整理する必要があります。以下の形式に厳密に従って内容を構造化してください:
155
+ 🧠 メインアイデア/テーマ – 中心的なトピックを要約します。
156
+
157
+ ✅ 実行可能なステップ – 次に何ができるかを分解します。
158
+
159
+ ❓ オープンな質問 – 不確実性や更なる探求が必要な領域を強調します。
160
+
161
+ 以下が考えです:""",
162
+ 'summarize': "上記のテキストを要約してください。"
163
+ },
164
+ 'spanish': {
165
+ 'system': """Eres un asistente de IA de clase mundial. Necesitas organizar los pensamientos aleatorios de los usuarios en un formato claro, conciso y procesable. Por favor, estructure el contenido siguiendo estrictamente este formato:
166
+ 🧠 Idea/Tema principal – Resume el tema central.
167
+
168
+ ✅ Pasos procesables – Desglose lo que se puede hacer a continuación.
169
+
170
+ ❓ Preguntas abiertas – Destaca cualquier incertidumbre o áreas que necesiten más exploración.
171
+
172
+ Aquí están los pensamientos:""",
173
+ 'summarize': "Resume el texto anterior."
174
+ },
175
+ 'portuguese': {
176
+ 'system': """Você é um assistente de IA de classe mundial. Você precisa organizar os pensamentos aleatórios dos usuários em um formato claro, conciso e acionável. Por favor, estruture o conteúdo seguindo rigorosamente este formato:
177
+ 🧠 Ideia/Tema principal – Resuma o tópico central.
178
+
179
+ ✅ Passos acionáveis – Detalhe o que pode ser feito a seguir.
180
+
181
+ ❓ Questões em aberto – Destaque quaisquer incertezas ou áreas que precisam de mais exploração.
182
+
183
+ Aqui estão os pensamentos:""",
184
+ 'summarize': "Resuma o texto acima."
185
+ }
186
+ }
187
+
188
+ class VoiceNotesApp:
189
+ def __init__(self):
190
+ # Azure endpoint configuration
191
+ # self.azure_url = os.getenv("AZURE_ENDPOINT")
192
+ # self.api_key = os.getenv("AZURE_API_KEY")
193
+ self.azure_url = "https://nguyenbach-9897-westus3-covns.westus3.inference.ml.azure.com/score"
194
+ self.api_key = "uABZxEGiK6iXlBWsvy7xOEJ1zCmeLkvSHuf6wEykfqtf4I7KbbWiJQQJ99BBAAAAAAAAAAAAINFRAZML2JhK"
195
+
196
+ # Initialize sample audio files
197
+ self.sample_audios = {
198
+ "English - Weekend Plan": "content/english.weekend.plan.wav",
199
+ "Chinese - Kids & Work": "content/chinese.kid.work.mp3",
200
+ "German - Vacation Planning": "content/german.vacation.work.mp3",
201
+ "French - Random Thoughts": "content/french.random.vacation.mp3",
202
+ "Italian - Daily Life": "content/italian.daily.life.mp3",
203
+ "Japanese - Seattle Trip Report": "content/japanese.seattle.trip.report.mp3",
204
+ "Spanish - Soccer Class": "content/spanish.soccer.class.mp3",
205
+ "Portuguese - Buying House & Friends": "content/portugese.house.friends.mp3"
206
+ }
207
+
208
+ # Initialize storage
209
+ self.notes_file = "voice_notes.json"
210
+ self.notes = self.load_notes()
211
+
212
+ def load_notes(self):
213
+ if os.path.exists(self.notes_file):
214
+ with open(self.notes_file, 'r') as f:
215
+ notes = json.load(f)
216
+ # Sort notes by timestamp in descending order (most recent first)
217
+ return sorted(notes, key=lambda x: x['timestamp'], reverse=True)
218
+ return []
219
+
220
+ def save_notes(self):
221
+ with open(self.notes_file, 'w') as f:
222
+ json.dump(self.notes, f, indent=2)
223
+
224
+ def encode_base64_from_file(self, file_path):
225
+ """Encode file content to base64 string and determine MIME type."""
226
+ file_extension = os.path.splitext(file_path)[1].lower()
227
+
228
+ # Map file extensions to MIME types
229
+ if file_extension in ['.jpg', '.jpeg']:
230
+ mime_type = "image/jpeg"
231
+ elif file_extension == '.png':
232
+ mime_type = "image/png"
233
+ elif file_extension == '.gif':
234
+ mime_type = "image/gif"
235
+ elif file_extension in ['.bmp', '.tiff', '.webp']:
236
+ mime_type = f"image/{file_extension[1:]}"
237
+ elif file_extension == '.flac':
238
+ mime_type = "audio/flac"
239
+ elif file_extension == '.wav':
240
+ mime_type = "audio/wav"
241
+ elif file_extension == '.mp3':
242
+ mime_type = "audio/mpeg"
243
+ elif file_extension in ['.m4a', '.aac']:
244
+ mime_type = "audio/aac"
245
+ elif file_extension == '.ogg':
246
+ mime_type = "audio/ogg"
247
+ else:
248
+ mime_type = "application/octet-stream"
249
+
250
+ # Read and encode file content
251
+ with open(file_path, "rb") as file:
252
+ encoded_string = base64.b64encode(file.read()).decode('utf-8')
253
+
254
+ return encoded_string, mime_type
255
+
256
+ def call_azure_endpoint(self, data):
257
+ """Call Azure ML endpoint with the given data."""
258
+ parameters = {"temperature": 0.0}
259
+ data["input_data"]["parameters"] = parameters
260
+
261
+ def allowSelfSignedHttps(allowed):
262
+ # bypass the server certificate verification on client side
263
+ if allowed and not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None):
264
+ ssl._create_default_https_context = ssl._create_unverified_context
265
+
266
+ allowSelfSignedHttps(True)
267
+ body = str.encode(json.dumps(data))
268
+
269
+ if not self.api_key:
270
+ raise Exception("A key should be provided to invoke the endpoint")
271
+
272
+ headers = {'Content-Type': 'application/json', 'Authorization': ('Bearer ' + self.api_key)}
273
+
274
+ req = urllib.request.Request(self.azure_url, body, headers)
275
+
276
+ try:
277
+ response = urllib.request.urlopen(req)
278
+ result = response.read().decode('utf-8')
279
+ return result
280
+ except urllib.error.HTTPError as error:
281
+ print("The request failed with status code: " + str(error.code))
282
+ print(error.info())
283
+ print(error.read().decode("utf8", 'ignore'))
284
+ return f"Error: {error.code}"
285
+
286
+ def transcribe_audio(self, audio_input):
287
+ """Convert speech to text using Azure endpoint"""
288
+ try:
289
+ # Encode audio file to base64
290
+ encoded_audio, mime_type = self.encode_base64_from_file(audio_input)
291
+
292
+ # Prepare the request payload
293
+ speech_prompt = "Based on the attached audio, generate a comprehensive text transcription of the spoken content."
294
+ payload = {
295
+ "input_data": {
296
+ "input_string": [
297
+ {
298
+ "role": "user",
299
+ "content": [
300
+ {
301
+ "type": "text",
302
+ "text": speech_prompt
303
+ },
304
+ {
305
+ "type": "audio_url",
306
+ "audio_url": {
307
+ "url": f"data:{mime_type};base64,{encoded_audio}"
308
+ }
309
+ }
310
+ ]
311
+ }
312
+ ]
313
+ }
314
+ }
315
+
316
+ # Call Azure endpoint
317
+ response_json = self.call_azure_endpoint(payload)
318
+
319
+ # Parse response
320
+ try:
321
+ response_data = json.loads(response_json)
322
+ # Extract the actual response text
323
+ if isinstance(response_data, dict) and "output" in response_data:
324
+ transcription = response_data["output"]
325
+ else:
326
+ transcription = response_json
327
+ except:
328
+ transcription = response_json
329
+
330
+ print(f"Debug transcription:\n{transcription}")
331
+
332
+ return transcription
333
+ except Exception as e:
334
+ print(f"Transcription error: {str(e)}")
335
+ return f"Error transcribing: {str(e)}"
336
+
337
+ def summarize_text(self, text):
338
+ """Generate a summary in the detected language using Azure endpoint"""
339
+ if not text:
340
+ return "No text to summarize"
341
+
342
+ try:
343
+ # First, detect language
344
+ detected_language = detect(text)
345
+
346
+ # Map detected language to supported languages
347
+ language_mapping = {
348
+ 'en': 'english',
349
+ 'zh-cn': 'chinese',
350
+ 'de': 'german',
351
+ 'fr': 'french',
352
+ 'it': 'italian',
353
+ 'ja': 'japanese',
354
+ 'es': 'spanish',
355
+ 'pt': 'portuguese'
356
+ }
357
+
358
+ # Default to English if language not supported
359
+ selected_language = language_mapping.get(detected_language, 'english')
360
+
361
+ print(f"Detected language: {detected_language} ; Selected language: {selected_language} ; Text: {text}")
362
+
363
+ # Generate summary in detected language
364
+ prompts = MULTILINGUAL_SYSYTEM_PROMPTS[selected_language]
365
+
366
+ # Prepare the request payload for summarization
367
+ payload = {
368
+ "input_data": {
369
+ "input_string": [
370
+ {
371
+ "role": "system",
372
+ "content": [
373
+ {
374
+ "type": "text",
375
+ "text": prompts["system"]
376
+ }
377
+ ]
378
+ },
379
+ {
380
+ "role": "user",
381
+ "content": [
382
+ {
383
+ "type": "text",
384
+ "text": text
385
+ }
386
+ ]
387
+ },
388
+ {
389
+ "role": "user",
390
+ "content": [
391
+ {
392
+ "type": "text",
393
+ "text": prompts["summarize"]
394
+ }
395
+ ]
396
+ }
397
+ ]
398
+ }
399
+ }
400
+
401
+ # Call Azure endpoint
402
+ response_json = self.call_azure_endpoint(payload)
403
+
404
+ # Parse response
405
+ try:
406
+ response_data = json.loads(response_json)
407
+ # Extract the actual response text
408
+ if isinstance(response_data, dict) and "output" in response_data:
409
+ summary = response_data["output"]
410
+ else:
411
+ summary = response_json
412
+ except:
413
+ summary = response_json
414
+
415
+ print(f"Debug summary:\n{summary}")
416
+
417
+ return summary, selected_language
418
+ except Exception as e:
419
+ print(f"Summarization error: {str(e)}")
420
+ return f"Error summarizing: {str(e)}", "english"
421
+
422
+ def format_note_display(self, note):
423
+ """Format note for display in a Gradio interface"""
424
+ return f"""## 📝 Summary
425
+ {note['summary']}
426
+
427
+ ---
428
+
429
+ ## 🎙️ Transcription
430
+ {note['transcription']}
431
+
432
+ ---
433
+
434
+ ## 🕒 Timestamp
435
+ **{note['timestamp']}**
436
+
437
+ ---
438
+
439
+ ## 🌐 Detected Language
440
+ **{note['language']}**"""
441
+
442
+ def search_notes(self, query):
443
+ """Search through notes content"""
444
+ if not query:
445
+ return self.list_all_notes()
446
+
447
+ matching_notes = []
448
+ query = query.lower()
449
+
450
+ for note in self.notes:
451
+ if (query in note['transcription'].lower() or
452
+ query in note['summary'].lower()):
453
+ matching_notes.append(note)
454
+
455
+ if not matching_notes:
456
+ return "No matching notes found"
457
+
458
+ return "\n\n---\n\n".join([self.format_note_display(note) for note in matching_notes])
459
+
460
+ def list_all_notes(self):
461
+ """Return all notes in formatted string"""
462
+ if not self.notes:
463
+ return "No notes found"
464
+
465
+ # Notes are already sorted by timestamp in load_notes()
466
+ return "\n\n---\n\n".join([self.format_note_display(note) for note in self.notes])
467
+
468
+ def process_note(self, audio, progress=gr.Progress()):
469
+ """Process audio input and generate note with summary"""
470
+ if audio is None:
471
+ return "Please record or upload an audio file.", None, "❌ No audio provided"
472
+
473
+ try:
474
+ # Start processing
475
+ progress(0, desc="Starting audio processing...")
476
+
477
+ # Transcribe audio (25% of progress)
478
+ progress(0.25, desc="Transcribing audio...")
479
+ transcription = self.transcribe_audio(audio)
480
+
481
+ # Generate summary (35% more progress)
482
+ progress(0.60, desc="Generating summary...")
483
+ summary, selected_language = self.summarize_text(transcription)
484
+
485
+ # Create and save note (25% more progress)
486
+ progress(0.85, desc="Saving note...")
487
+ note = {
488
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
489
+ "transcription": transcription,
490
+ "summary": summary,
491
+ "language": selected_language
492
+ }
493
+
494
+ # Save note
495
+ self.notes.append(note)
496
+ self.save_notes()
497
+
498
+ # Complete
499
+ progress(1.0, desc="Complete!")
500
+ return self.format_note_display(note), audio, "✅ Processing complete!"
501
+
502
+ except Exception as e:
503
+ return str(e), None, f"❌ Error: {str(e)}"
504
+
505
+ async def text_to_speech(self, text, detected_lang):
506
+ """Convert text to speech using Edge TTS with language-specific voices"""
507
+ if not text.strip():
508
+ return None
509
+
510
+ # Map of language codes to Edge TTS voices
511
+ voice_mapping = {
512
+ 'english': 'en-US-RogerNeural', # English
513
+ 'chinese': 'zh-CN-XiaoxiaoNeural', # Chinese
514
+ 'german': 'de-DE-KatjaNeural', # German
515
+ 'french': 'fr-FR-HenriNeural', # French
516
+ 'italian': 'it-IT-DiegoNeural', # Italian
517
+ 'japanese': 'ja-JP-KeitaNeural', # Japanese
518
+ 'spanish': 'es-ES-XimenaNeural', # Spanish
519
+ 'portuguese': 'pt-BR-AntonioNeural', # Portuguese
520
+ }
521
+
522
+ # Default to English if language not supported
523
+ voice = voice_mapping.get(detected_lang, 'en-US-EricNeural')
524
+
525
+ try:
526
+ communicate = edge_tts.Communicate(text, voice)
527
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
528
+ tmp_path = tmp_file.name
529
+ await communicate.save(tmp_path)
530
+ return tmp_path
531
+ except Exception as e:
532
+ print(f"TTS Error: {str(e)}")
533
+ return None
534
+
535
+ def create_interface(self):
536
+ """Create an enhanced Gradio interface with improved styling and layout"""
537
+ # Preload English sample
538
+ default_audio_path = self.sample_audios["English - Weekend Plan"]
539
+ # Read the audio file for proper initialization
540
+ try:
541
+ audio_data, sample_rate = soundfile.read(default_audio_path)
542
+ default_audio = (sample_rate, audio_data)
543
+ except Exception as e:
544
+ print(f"Error loading default audio: {e}")
545
+ default_audio = None
546
+
547
+ # Create the layout with tabs
548
+ with gr.Blocks(
549
+ css=CUSTOM_CSS,
550
+ theme=LIGHT_THEME,
551
+ title="Thoughts Organizer"
552
+ ) as interface:
553
+ # Header section
554
+ with gr.Row(elem_id="header"):
555
+ gr.Markdown(
556
+ """
557
+ # 🎙️ Thoughts Organizer with Phi-4-Multimodal
558
+ ### Transform your spoken thoughts into organized, actionable insights
559
+
560
+ Capture, organize, and act on your spoken thoughts with AI-powered voice notes in multiple languages, including English, Chinese, German, French, Italian, Japanese, Spanish, and Portuguese.
561
+ """
562
+ )
563
+
564
+ # Main content tabs
565
+ with gr.Tabs():
566
+ # Record New Note Tab
567
+ with gr.Tab("📝 New Note", id="new_note"):
568
+ with gr.Column(elem_classes="input-section"):
569
+ # Audio input with clear instructions
570
+ gr.Markdown("### Record or Upload Your Voice Note")
571
+ audio_input = gr.Audio(
572
+ sources=["microphone", "upload"],
573
+ type="filepath",
574
+ label="",
575
+ interactive=True,
576
+ show_download_button=True,
577
+ value=default_audio
578
+ )
579
+
580
+ with gr.Row():
581
+ sample_audio = gr.Dropdown(
582
+ choices=list(self.sample_audios.keys()),
583
+ label="Select a sample audio to try",
584
+ value="English - Weekend Plan"
585
+ )
586
+ # Process button with loading state
587
+ process_btn = gr.Button("🔄 Process Note", variant="primary")
588
+ clear_btn = gr.Button("🗑️ Clear", variant="secondary")
589
+
590
+ # Add progress bar
591
+ progress_bar = gr.Progress()
592
+
593
+ with gr.Column(elem_classes="output-section"):
594
+ # Status message display
595
+ processing_status = gr.Markdown(label="Status", value="Ready to process...")
596
+ # Note output display
597
+ note_display = gr.Markdown(label="")
598
+
599
+ # Add TTS playback controls
600
+ with gr.Row():
601
+ play_btn = gr.Button("🔊 Listen Note", variant="secondary")
602
+ tts_audio = gr.Audio(label="TTS Output", visible=True, interactive=False)
603
+
604
+ # Enhanced All Notes Tab
605
+ with gr.Tab("📚 All Notes", id="all_notes"):
606
+ with gr.Column():
607
+ # Search box
608
+ search_box = gr.Textbox(
609
+ label="🔍 Search Notes",
610
+ placeholder="Enter keywords to search...",
611
+ show_label=True
612
+ )
613
+
614
+ # Refresh button for notes
615
+ refresh_btn = gr.Button("🔄 Refresh Notes")
616
+
617
+ # All notes display
618
+ all_notes_display = gr.Markdown()
619
+
620
+ # Function to load sample audio
621
+ def load_sample(sample_name):
622
+ if not sample_name:
623
+ return None
624
+ try:
625
+ audio_path = self.sample_audios[sample_name]
626
+ audio_data, sample_rate = soundfile.read(audio_path)
627
+ return (sample_rate, audio_data)
628
+ except Exception as e:
629
+ print(f"Error loading sample audio: {e}")
630
+ return None
631
+
632
+ # Automatically load sample when selected
633
+ sample_audio.change(
634
+ fn=load_sample,
635
+ inputs=[sample_audio],
636
+ outputs=[audio_input],
637
+ api_name="load_sample"
638
+ )
639
+
640
+ def process_and_get_note(audio, progress=gr.Progress()):
641
+ try:
642
+ note_text, _, status = self.process_note(audio, progress)
643
+ # Return both the note text and updated all notes display
644
+ all_notes = self.list_all_notes()
645
+ return note_text, all_notes, status
646
+ except Exception as e:
647
+ error_msg = f"❌ Error processing note: {str(e)}"
648
+ return "", "", error_msg
649
+
650
+ # Update the process button click event
651
+ process_btn.click(
652
+ fn=process_and_get_note,
653
+ inputs=[audio_input],
654
+ outputs=[note_display, all_notes_display, processing_status],
655
+ api_name="process_note"
656
+ )
657
+
658
+ # Function to handle TTS playback
659
+ async def play_note(note_text):
660
+ if not note_text:
661
+ return None
662
+
663
+ try:
664
+ # Extract the detected language from the note display
665
+ lang_section = note_text.split("Detected Language")[-1].strip()
666
+ detected_lang = lang_section.strip('*').strip()
667
+
668
+ # Extract the summary section (everything before the first ---)
669
+ summary_section = note_text.split("---")[0].strip()
670
+
671
+ # Remove Markdown headers (#)
672
+ cleaned_text = summary_section.replace('#', '')
673
+
674
+ # Remove emojis and section labels
675
+ cleaned_text = cleaned_text.replace('📝 Summary', '').strip()
676
+
677
+ # Remove all special characters except basic punctuation
678
+ # Keep: letters, numbers, spaces, and basic punctuation
679
+ clean_chars = []
680
+ for char in cleaned_text:
681
+ if (char.isalnum() or
682
+ char.isspace() or
683
+ char in '.,!?-:;()[]{}"\''):
684
+ clean_chars.append(char)
685
+
686
+ cleaned_text = ''.join(clean_chars)
687
+
688
+ # Remove multiple spaces
689
+ cleaned_text = ' '.join(cleaned_text.split())
690
+
691
+ print(f"Debug - Original text: {summary_section}")
692
+ print(f"Debug - Cleaned text: {cleaned_text}")
693
+
694
+ audio_path = await self.text_to_speech(cleaned_text, detected_lang)
695
+ return audio_path
696
+
697
+ except Exception as e:
698
+ print(f"Error in play_note: {str(e)}")
699
+ return None
700
+
701
+ # Update event handlers
702
+ play_btn.click(
703
+ fn=play_note,
704
+ inputs=[note_display],
705
+ outputs=[tts_audio],
706
+ api_name="play_note"
707
+ )
708
+
709
+ # Clear button functionality
710
+ def clear_all():
711
+ # Return default/empty values for all components
712
+ return None, "", "Ready to process...", ""
713
+
714
+ clear_btn.click(
715
+ fn=clear_all,
716
+ inputs=[],
717
+ outputs=[
718
+ audio_input, # Clear audio input
719
+ note_display, # Clear note display
720
+ processing_status, # Reset status message
721
+ all_notes_display # Clear all notes display
722
+ ]
723
+ )
724
+
725
+ def refresh_notes():
726
+ # Reload notes from disk
727
+ self.notes = self.load_notes()
728
+ # Return updated notes display
729
+ return self.list_all_notes()
730
+
731
+ refresh_btn.click(
732
+ fn=refresh_notes,
733
+ inputs=[],
734
+ outputs=[all_notes_display],
735
+ api_name="refresh_notes"
736
+ )
737
+ # Add search functionality
738
+ search_box.change(
739
+ fn=self.search_notes,
740
+ inputs=[search_box],
741
+ outputs=[all_notes_display],
742
+ api_name="search_notes"
743
+ )
744
+
745
+ # Instructions and tips
746
+ with gr.Accordion("ℹ️ Tips & Instructions", open=False):
747
+ gr.Markdown(
748
+ """
749
+ ### How to Use:
750
+ 1. **Record or Upload**: Use the microphone to record directly or upload an audio file
751
+ 2. **Process**: Click 'Process Note' to convert your voice note into organized text
752
+ 3. **Review**: View your processed note with main ideas, action items, and questions
753
+ 4. **Listen**: Click the '🔊 Play Note' button to hear the summary read aloud
754
+ 5. **Browse**: Switch to 'All Notes' tab to view your note history
755
+
756
+ ### Features:
757
+ - 🎙️ Record or upload voice notes
758
+ - 📝 Automatic transcription
759
+ - 🧠 Smart organization of ideas
760
+ - 📚 Historical note tracking
761
+ """
762
+ )
763
+ # Footer
764
+ with gr.Column(elem_classes="output-section"):
765
+ gr.Markdown("Powered by Microsoft [Phi-4 multimodal model](https://aka.ms/phi-4-multimodal/azure) on Azure AI. © 2025")
766
+
767
+ return interface
768
+
769
+ def run_app():
770
+ # Create app instance
771
+ app = VoiceNotesApp()
772
+
773
+ # Launch Gradio interface
774
+ interface = app.create_interface()
775
+ interface.launch(
776
+ share=True,
777
+ server_name="0.0.0.0",
778
+ )
779
+
780
+
781
+ run_app()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ edge-tts==7.0.0
2
+ azure-ai-inference==1.0.0b9
3
+ azureml-inference-server-http==1.0.0
4
+ soundfile
5
+ langdetect