Teera commited on
Commit
c5027b2
·
verified ·
1 Parent(s): be08f8c
Files changed (6) hide show
  1. .env +9 -0
  2. app.py +235 -70
  3. llm_client.py +77 -0
  4. prompts.py +65 -0
  5. readme.md +0 -0
  6. requirements.txt +4 -0
.env ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ SPEECH_KEY="4CcN3sox1gfqI81AOhFHIYZwGusC6frPa1kSO32gIjjPSCFxke0EJQQJ99CBACYeBjFXJ3w3AAAYACOGd9oM"
2
+ SPEECH_ENDPOINT="https://eastus.api.cognitive.microsoft.com/"
3
+ SPEECH_REGION="eastus"
4
+
5
+ # Azure OpenAI
6
+ AZURE_OPENAI_KEY="8wKFXqTCFBDBZ8eMj1ePBxVF0XMUbH9H50XXuV3ReJ0ZpAMrRfCcJQQJ99BEACHYHv6XJ3w3AAAAACOGqdEB"
7
+ AZURE_OPENAI_ENDPOINT="https://teera-maz475y3-eastus2.cognitiveservices.azure.com/"
8
+ AZURE_OPENAI_API_VERSION="2024-12-01-preview"
9
+ AZURE_OPENAI_DEPLOYMENT="gpt-5.2-chat"
app.py CHANGED
@@ -1,70 +1,235 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
68
-
69
- if __name__ == "__main__":
70
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
llm_client.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Azure OpenAI client wrapper for LLM-based analysis.
3
+ """
4
+
5
+ import os
6
+ import json
7
+ from openai import AzureOpenAI
8
+ from dotenv import load_dotenv
9
+ from prompts import FOOTBALL_ANALYSIS_SYSTEM_PROMPT, FOOTBALL_ANALYSIS_USER_PROMPT
10
+
11
+ load_dotenv()
12
+
13
+ AZURE_OPENAI_KEY = os.getenv("AZURE_OPENAI_KEY")
14
+ AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT")
15
+ AZURE_OPENAI_API_VERSION = os.getenv("AZURE_OPENAI_API_VERSION", "2024-12-01-preview")
16
+ AZURE_OPENAI_DEPLOYMENT = os.getenv("AZURE_OPENAI_DEPLOYMENT", "gpt-5.2-chat")
17
+
18
+
19
+ def get_openai_client():
20
+ """Create and return an Azure OpenAI client."""
21
+ return AzureOpenAI(
22
+ api_key=AZURE_OPENAI_KEY,
23
+ azure_endpoint=AZURE_OPENAI_ENDPOINT,
24
+ api_version=AZURE_OPENAI_API_VERSION,
25
+ )
26
+
27
+
28
+ def analyze_football_content(transcript: str) -> dict:
29
+ """
30
+ Send transcribed text to Azure OpenAI for football content analysis.
31
+
32
+ Args:
33
+ transcript: The transcribed speech text.
34
+
35
+ Returns:
36
+ A dict with categorized football data (teams, leagues, sentiment, etc.)
37
+ """
38
+ if not transcript or not transcript.strip():
39
+ return {"error": "ไม่มีข้อความให้วิเคราะห์"}
40
+
41
+ client = get_openai_client()
42
+
43
+ user_message = FOOTBALL_ANALYSIS_USER_PROMPT.format(transcript=transcript)
44
+
45
+ try:
46
+ response = client.chat.completions.create(
47
+ model=AZURE_OPENAI_DEPLOYMENT,
48
+ messages=[
49
+ {"role": "system", "content": FOOTBALL_ANALYSIS_SYSTEM_PROMPT},
50
+ {"role": "user", "content": user_message},
51
+ ],
52
+ max_completion_tokens=4096,
53
+ )
54
+
55
+ content = response.choices[0].message.content.strip()
56
+
57
+ # Clean up markdown code fences if the model wraps JSON in ```json ... ```
58
+ if content.startswith("```"):
59
+ content = content.split("\n", 1)[1] # Remove first line (```json)
60
+ content = content.rsplit("```", 1)[0] # Remove last ```
61
+ content = content.strip()
62
+
63
+ result = json.loads(content)
64
+ return result
65
+
66
+ except json.JSONDecodeError:
67
+ return {
68
+ "error": "LLM ตอบกลับมาไม่ใช่ JSON ที่ถูกต้อง",
69
+ "raw_response": content,
70
+ }
71
+ except Exception as e:
72
+ return {"error": f"เกิดข้อผิดพลาด: {str(e)}"}
73
+
74
+
75
+ def format_analysis_result(result: dict) -> str:
76
+ """Format the analysis result as a pretty JSON string for display."""
77
+ return json.dumps(result, ensure_ascii=False, indent=2)
prompts.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Prompt templates for LLM-based football content analysis.
3
+ """
4
+
5
+ FOOTBALL_ANALYSIS_SYSTEM_PROMPT = """คุณเป็น AI ผู้เชี่ยวชาญด้านการวิเคราะห์เนื้อหาฟุตบอล
6
+ หน้าที่ของคุณคือวิเคราะห์ข้อความที่ถอดเสียงมา (transcript) แล้วจัดหมวดหมู่ข้อมูลเกี่ยวกับฟุตบอล
7
+
8
+ คุณต้องตอบกลับเป็น JSON เท่านั้น ตามโครงสร้างนี้:
9
+
10
+ {
11
+ "teams_mentioned": [
12
+ {
13
+ "name": "ชื่อทีม (ภาษาอังกฤษ)",
14
+ "name_th": "ชื่อทีม (ภาษาไทย ถ้ามี)",
15
+ "context": "บริบทที่พูดถึงทีมนี้โดยย่อ"
16
+ }
17
+ ],
18
+ "leagues_mentioned": [
19
+ {
20
+ "name": "ชื่อลีก (ภาษาอังกฤษ)",
21
+ "name_th": "ชื่อลีก (ภาษาไทย ถ้ามี)",
22
+ "country": "ประเทศ"
23
+ }
24
+ ],
25
+ "players_mentioned": [
26
+ {
27
+ "name": "ชื่อนักเตะ",
28
+ "team": "ทีมที่สังกัด (ถ้าระบุได้)",
29
+ "context": "บริบทที่พูดถึง"
30
+ }
31
+ ],
32
+ "topics": ["หัวข้อที่พูดถึง เช่น ผลการแข่งขัน, ตลาดการย้ายทีม, อาการบาดเจ็บ, ..."],
33
+ "sentiment": {
34
+ "overall": "positive | negative | neutral | mixed",
35
+ "score": 0.0,
36
+ "details": "อธิบายเหตุผลโดยย่อ"
37
+ },
38
+ "match_info": {
39
+ "is_match_discussed": true,
40
+ "home_team": "ทีมเหย้า (ถ้ามี)",
41
+ "away_team": "ทีมเยือน (ถ้ามี)",
42
+ "score": "ผลสกอร์ (ถ้ามี)",
43
+ "competition": "รายการแข่งขัน (ถ้ามี)"
44
+ },
45
+ "summary": "สรุปเนื้อหาโดยย่อ 1-2 ประโยค",
46
+ "confidence": 0.0,
47
+ "is_football_content": true
48
+ }
49
+
50
+ กฎ:
51
+ 1. ถ้าเนื้อหาไม่เกี่ยวกับฟุตบอลเลย ให้ตั้ง "is_football_content" เป็น false และใส่ข้อมูลที่เกี่ยวข้องน้อยที่สุด
52
+ 2. "sentiment.score" อยู่ในช่วง -1.0 (ลบมาก) ถึง 1.0 (บวกมาก), 0.0 คือ neutral
53
+ 3. "confidence" อยู่ในช่วง 0.0-1.0 แสดงความมั่นใจในการวิเคราะห์
54
+ 4. ตอบเป็น JSON เท่านั้น ห้ามมีข้อความอื่นนอกเหนือจาก JSON
55
+ 5. ถ้าไม่มีข้อมูลในฟิลด์ใด ให้ใส่ null หรือ array ว่าง []
56
+ 6. พยายามระบุชื่อเป็นภาษาอังกฤษมาตรฐานเสมอ (เช่น "Liverpool", ไม่ใช่ "ลิเวอร์พูล" อย่างเดียว)
57
+ """
58
+
59
+ FOOTBALL_ANALYSIS_USER_PROMPT = """วิเคราะห์ข้อความที่ถอดเสียงมานี้:
60
+
61
+ ---
62
+ {transcript}
63
+ ---
64
+
65
+ ตอบเป็น JSON ตามโครงสร้างที่กำหนด"""
readme.md ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ azure-cognitiveservices-speech
2
+ python-dotenv
3
+ gradio
4
+ openai