Teera commited on
Commit
8b1d8cc
·
verified ·
1 Parent(s): c5027b2
Files changed (1) hide show
  1. app.py +233 -235
app.py CHANGED
@@ -1,235 +1,233 @@
1
- import os
2
- import sys
3
- import azure.cognitiveservices.speech as speechsdk
4
- from dotenv import load_dotenv
5
-
6
- load_dotenv()
7
-
8
- SPEECH_KEY = os.getenv("SPEECH_KEY")
9
- SPEECH_REGION = os.getenv("SPEECH_REGION", "eastus")
10
-
11
-
12
- def create_speech_config(language="th-TH"):
13
- """Create a SpeechConfig with the given language."""
14
- config = speechsdk.SpeechConfig(
15
- subscription=SPEECH_KEY,
16
- region=SPEECH_REGION,
17
- )
18
- config.speech_recognition_language = language
19
- return config
20
-
21
-
22
- def transcribe_from_mic():
23
- """Transcribe from the local microphone (CLI mode)."""
24
- speech_config = create_speech_config("th-TH")
25
- audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
26
- recognizer = speechsdk.SpeechRecognizer(
27
- speech_config=speech_config,
28
- audio_config=audio_config,
29
- )
30
-
31
- print("🎤 Listening... Speak into your microphone.")
32
- result = recognizer.recognize_once()
33
-
34
- if result.reason == speechsdk.ResultReason.RecognizedSpeech:
35
- print("✅ Recognized: " + result.text)
36
- elif result.reason == speechsdk.ResultReason.NoMatch:
37
- print("❌ No speech could be recognized: " + str(result.no_match_details))
38
- elif result.reason == speechsdk.ResultReason.Canceled:
39
- cancellation_details = result.cancellation_details
40
- print("⚠️ Speech recognition canceled: " + str(cancellation_details.reason))
41
- if cancellation_details.reason == speechsdk.CancellationReason.Error:
42
- print("Error details: " + str(cancellation_details.error_details))
43
- print("Did you set the speech resource key and region?")
44
-
45
-
46
- def transcribe_audio_file(audio_path, language="th-TH"):
47
- """Transcribe an audio file using Azure Speech SDK."""
48
- if audio_path is None:
49
- return "⚠️ กรุณาอัดเสียงก่อน"
50
-
51
- speech_config = create_speech_config(language)
52
- audio_config = speechsdk.audio.AudioConfig(filename=audio_path)
53
- recognizer = speechsdk.SpeechRecognizer(
54
- speech_config=speech_config,
55
- audio_config=audio_config,
56
- )
57
-
58
- # Use continuous recognition to get the full transcript
59
- all_results = []
60
- done = False
61
-
62
- def on_recognized(evt):
63
- if evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
64
- all_results.append(evt.result.text)
65
-
66
- def on_canceled(evt):
67
- nonlocal done
68
- done = True
69
-
70
- def on_stopped(evt):
71
- nonlocal done
72
- done = True
73
-
74
- recognizer.recognized.connect(on_recognized)
75
- recognizer.canceled.connect(on_canceled)
76
- recognizer.session_stopped.connect(on_stopped)
77
-
78
- recognizer.start_continuous_recognition()
79
-
80
- import time
81
- while not done:
82
- time.sleep(0.1)
83
-
84
- recognizer.stop_continuous_recognition()
85
-
86
- if all_results:
87
- return "\n".join(all_results)
88
- else:
89
- return "❌ ไม่สามารถถอดเสียงได้ — ลองพูดดังขึ้นหรือตรวจสอบไมค์"
90
-
91
-
92
- def transcribe_and_analyze(audio_path, language):
93
- """Transcribe audio, then analyze with LLM. Returns (transcript, analysis_json)."""
94
- transcript = transcribe_audio_file(audio_path, language)
95
-
96
- if transcript.startswith("❌") or transcript.startswith("⚠️"):
97
- return transcript, ""
98
-
99
- from llm_client import analyze_football_content, format_analysis_result
100
- result = analyze_football_content(transcript)
101
- analysis_json = format_analysis_result(result)
102
-
103
- return transcript, analysis_json
104
-
105
-
106
- def analyze_text_only(transcript):
107
- """Analyze existing transcript text without re-transcribing."""
108
- if not transcript or not transcript.strip():
109
- return "⚠️ กรุณาใส่ข้อความก่อน"
110
-
111
- from llm_client import analyze_football_content, format_analysis_result
112
- result = analyze_football_content(transcript)
113
- return format_analysis_result(result)
114
-
115
-
116
- def run_web():
117
- """Run the Gradio web UI."""
118
- import gradio as gr
119
-
120
- with gr.Blocks(
121
- title="ASR - Football Analysis",
122
- theme=gr.themes.Soft(
123
- primary_hue=gr.themes.colors.indigo,
124
- secondary_hue=gr.themes.colors.purple,
125
- neutral_hue=gr.themes.colors.slate,
126
- ),
127
- css="""
128
- .gradio-container {
129
- max-width: 900px !important;
130
- margin: auto !important;
131
- }
132
- """,
133
- ) as app:
134
-
135
- gr.Markdown(
136
- """
137
- # ⚽ Football Speech Analyzer
138
- ### ถอดเสียงพูด + วิเคราะห์เนื้อหาฟุตบอลด้วย AI
139
- ---
140
- """
141
- )
142
-
143
- with gr.Row():
144
- language = gr.Dropdown(
145
- choices=[
146
- ("🇹🇭 ไทย", "th-TH"),
147
- ("🇺🇸 English", "en-US"),
148
- ("🇯🇵 日本語", "ja-JP"),
149
- ("🇨🇳 中文", "zh-CN"),
150
- ("🇰🇷 한국어", "ko-KR"),
151
- ],
152
- value="th-TH",
153
- label="ภาษา",
154
- interactive=True,
155
- )
156
-
157
- gr.Markdown("### 🎤 อัดเสียงจากไมค์")
158
- audio_input = gr.Audio(
159
- sources=["microphone", "upload"],
160
- type="filepath",
161
- label="กดปุ่มอัดเสียง หรืออัปโหลดไฟล์เสียง",
162
- )
163
-
164
- with gr.Row():
165
- transcribe_btn = gr.Button(
166
- "✨ ถอดเสียงอย่างเดียว",
167
- variant="secondary",
168
- size="lg",
169
- )
170
- full_btn = gr.Button(
171
- "⚽ ถอดเสียง + วิเคราะห์ฟุตบอล",
172
- variant="primary",
173
- size="lg",
174
- )
175
-
176
- gr.Markdown("### 📝 ข้อความที่ถอดได้")
177
- output_text = gr.Textbox(
178
- label="Transcript",
179
- lines=6,
180
- show_copy_button=True,
181
- placeholder="ผลการถอดเสียงจะแสดงที่นี่...",
182
- )
183
-
184
- gr.Markdown("### 🧠 ผลวิเคราะห์จาก AI")
185
- with gr.Row():
186
- analyze_btn = gr.Button(
187
- "🔄 วิเคราะห์ข้อความข้างบนอีกครั้ง",
188
- variant="secondary",
189
- size="sm",
190
- )
191
-
192
- analysis_output = gr.Code(
193
- label="Football Analysis (JSON)",
194
- language="json",
195
- lines=20,
196
- )
197
-
198
- # --- Events ---
199
-
200
- # Transcribe only
201
- transcribe_btn.click(
202
- fn=transcribe_audio_file,
203
- inputs=[audio_input, language],
204
- outputs=output_text,
205
- )
206
-
207
- # Transcribe + Analyze
208
- full_btn.click(
209
- fn=transcribe_and_analyze,
210
- inputs=[audio_input, language],
211
- outputs=[output_text, analysis_output],
212
- )
213
-
214
- # Re-analyze existing transcript
215
- analyze_btn.click(
216
- fn=analyze_text_only,
217
- inputs=output_text,
218
- outputs=analysis_output,
219
- )
220
-
221
- # Auto-transcribe + analyze on recording stop
222
- audio_input.stop_recording(
223
- fn=transcribe_and_analyze,
224
- inputs=[audio_input, language],
225
- outputs=[output_text, analysis_output],
226
- )
227
-
228
- app.launch(server_name="127.0.0.1", server_port=7860)
229
-
230
-
231
- if __name__ == "__main__":
232
- if "--cli" in sys.argv:
233
- transcribe_from_mic()
234
- else:
235
- run_web()
 
1
+ import os
2
+ import sys
3
+ import azure.cognitiveservices.speech as speechsdk
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+
8
+ SPEECH_KEY = os.getenv("SPEECH_KEY")
9
+ SPEECH_REGION = os.getenv("SPEECH_REGION", "eastus")
10
+
11
+
12
+ def create_speech_config(language="th-TH"):
13
+ """Create a SpeechConfig with the given language."""
14
+ config = speechsdk.SpeechConfig(
15
+ subscription=SPEECH_KEY,
16
+ region=SPEECH_REGION,
17
+ )
18
+ config.speech_recognition_language = language
19
+ return config
20
+
21
+
22
+ def transcribe_from_mic():
23
+ """Transcribe from the local microphone (CLI mode)."""
24
+ speech_config = create_speech_config("th-TH")
25
+ audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
26
+ recognizer = speechsdk.SpeechRecognizer(
27
+ speech_config=speech_config,
28
+ audio_config=audio_config,
29
+ )
30
+
31
+ print("🎤 Listening... Speak into your microphone.")
32
+ result = recognizer.recognize_once()
33
+
34
+ if result.reason == speechsdk.ResultReason.RecognizedSpeech:
35
+ print("✅ Recognized: " + result.text)
36
+ elif result.reason == speechsdk.ResultReason.NoMatch:
37
+ print("❌ No speech could be recognized: " + str(result.no_match_details))
38
+ elif result.reason == speechsdk.ResultReason.Canceled:
39
+ cancellation_details = result.cancellation_details
40
+ print("⚠️ Speech recognition canceled: " + str(cancellation_details.reason))
41
+ if cancellation_details.reason == speechsdk.CancellationReason.Error:
42
+ print("Error details: " + str(cancellation_details.error_details))
43
+ print("Did you set the speech resource key and region?")
44
+
45
+
46
+ def transcribe_audio_file(audio_path, language="th-TH"):
47
+ """Transcribe an audio file using Azure Speech SDK."""
48
+ if audio_path is None:
49
+ return "⚠️ กรุณาอัดเสียงก่อน"
50
+
51
+ speech_config = create_speech_config(language)
52
+ audio_config = speechsdk.audio.AudioConfig(filename=audio_path)
53
+ recognizer = speechsdk.SpeechRecognizer(
54
+ speech_config=speech_config,
55
+ audio_config=audio_config,
56
+ )
57
+
58
+ # Use continuous recognition to get the full transcript
59
+ all_results = []
60
+ done = False
61
+
62
+ def on_recognized(evt):
63
+ if evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
64
+ all_results.append(evt.result.text)
65
+
66
+ def on_canceled(evt):
67
+ nonlocal done
68
+ done = True
69
+
70
+ def on_stopped(evt):
71
+ nonlocal done
72
+ done = True
73
+
74
+ recognizer.recognized.connect(on_recognized)
75
+ recognizer.canceled.connect(on_canceled)
76
+ recognizer.session_stopped.connect(on_stopped)
77
+
78
+ recognizer.start_continuous_recognition()
79
+
80
+ import time
81
+ while not done:
82
+ time.sleep(0.1)
83
+
84
+ recognizer.stop_continuous_recognition()
85
+
86
+ if all_results:
87
+ return "\n".join(all_results)
88
+ else:
89
+ return "❌ ไม่สามารถถอดเสียงได้ — ลองพูดดังขึ้นหรือตรวจสอบไมค์"
90
+
91
+
92
+ def transcribe_and_analyze(audio_path, language):
93
+ """Transcribe audio, then analyze with LLM. Returns (transcript, analysis_json)."""
94
+ transcript = transcribe_audio_file(audio_path, language)
95
+
96
+ if transcript.startswith("❌") or transcript.startswith("⚠️"):
97
+ return transcript, ""
98
+
99
+ from llm_client import analyze_football_content, format_analysis_result
100
+ result = analyze_football_content(transcript)
101
+ analysis_json = format_analysis_result(result)
102
+
103
+ return transcript, analysis_json
104
+
105
+
106
+ def analyze_text_only(transcript):
107
+ """Analyze existing transcript text without re-transcribing."""
108
+ if not transcript or not transcript.strip():
109
+ return "⚠️ กรุณาใส่ข้อความก่อน"
110
+
111
+ from llm_client import analyze_football_content, format_analysis_result
112
+ result = analyze_football_content(transcript)
113
+ return format_analysis_result(result)
114
+
115
+
116
+ def run_web():
117
+ """Run the Gradio web UI."""
118
+ import gradio as gr
119
+
120
+ with gr.Blocks(
121
+ title="ASR - Football Analysis",
122
+ theme=gr.themes.Soft(
123
+ primary_hue=gr.themes.colors.indigo,
124
+ secondary_hue=gr.themes.colors.purple,
125
+ neutral_hue=gr.themes.colors.slate,
126
+ ),
127
+ css="""
128
+ .gradio-container {
129
+ max-width: 900px !important;
130
+ margin: auto !important;
131
+ }
132
+ """,
133
+ ) as app:
134
+
135
+ gr.Markdown(
136
+ """
137
+ # ⚽ Football Speech Analyzer
138
+ ### ถอดเสียงพูด + วิเคราะห์เนื้อหาฟุตบอลด้วย AI
139
+ ---
140
+ """
141
+ )
142
+
143
+ with gr.Row():
144
+ language = gr.Dropdown(
145
+ choices=[
146
+ ("🇹🇭 ไทย", "th-TH"),
147
+ ("🇺🇸 English", "en-US"),
148
+ ("🇯🇵 日本語", "ja-JP"),
149
+ ("🇨🇳 中文", "zh-CN"),
150
+ ("🇰🇷 한국어", "ko-KR"),
151
+ ],
152
+ value="th-TH",
153
+ label="ภาษา",
154
+ interactive=True,
155
+ )
156
+
157
+ gr.Markdown("### 🎤 อัดเสียงจากไมค์")
158
+ audio_input = gr.Audio(
159
+ sources=["microphone", "upload"],
160
+ type="filepath",
161
+ label="กดปุ่มอัดเสียง หรืออัปโหลดไฟล์เสียง",
162
+ )
163
+
164
+ with gr.Row():
165
+ transcribe_btn = gr.Button(
166
+ "✨ ถอดเสียงอย่างเดียว",
167
+ variant="secondary",
168
+ size="lg",
169
+ )
170
+ full_btn = gr.Button(
171
+ "⚽ ถอดเสียง + วิเคราะห์ฟุตบอล",
172
+ variant="primary",
173
+ size="lg",
174
+ )
175
+
176
+ gr.Markdown("### 📝 ข้อความที่ถอดได้")
177
+ output_text = gr.Textbox(
178
+ label="Transcript",
179
+ lines=6,
180
+ show_copy_button=True,
181
+ placeholder="ผลการถอดเสียงจะแสดงที่นี่...",
182
+ )
183
+
184
+ gr.Markdown("### 🧠 ผลวิเคราะห์จาก AI")
185
+ with gr.Row():
186
+ analyze_btn = gr.Button(
187
+ "🔄 วิเคราะห์ข้อความข้างบนอีกครั้ง",
188
+ variant="secondary",
189
+ size="sm",
190
+ )
191
+
192
+ analysis_output = gr.Code(
193
+ label="Football Analysis (JSON)",
194
+ language="json",
195
+ lines=20,
196
+ )
197
+
198
+ # --- Events ---
199
+
200
+ # Transcribe only
201
+ transcribe_btn.click(
202
+ fn=transcribe_audio_file,
203
+ inputs=[audio_input, language],
204
+ outputs=output_text,
205
+ )
206
+
207
+ # Transcribe + Analyze
208
+ full_btn.click(
209
+ fn=transcribe_and_analyze,
210
+ inputs=[audio_input, language],
211
+ outputs=[output_text, analysis_output],
212
+ )
213
+
214
+ # Re-analyze existing transcript
215
+ analyze_btn.click(
216
+ fn=analyze_text_only,
217
+ inputs=output_text,
218
+ outputs=analysis_output,
219
+ )
220
+
221
+ # Auto-transcribe + analyze on recording stop
222
+ audio_input.stop_recording(
223
+ fn=transcribe_and_analyze,
224
+ inputs=[audio_input, language],
225
+ outputs=[output_text, analysis_output],
226
+ )
227
+
228
+ app.launch()
229
+
230
+
231
+
232
+ if __name__ == "__main__":
233
+ run_web()