Lowking commited on
Commit
c416575
·
verified ·
1 Parent(s): e16882a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -33
app.py CHANGED
@@ -21,7 +21,7 @@ app.add_middleware(
21
 
22
  @app.get("/")
23
  async def root():
24
- return {"message": "16 族語 AI 神獸大腦(全功能完整版)正在運行中!"}
25
 
26
  # ==========================================
27
  # 🔗 連結原語會 AI 實驗室 (三大核心大腦)
@@ -31,12 +31,11 @@ def safe_client_init(url, name):
31
  print(f"🧬 正在連線至 {name} 大腦: {url}")
32
  return Client(url)
33
  except Exception as e:
34
- print(f"⚠️ {name} 連線暫時失敗,錯誤原因: {e}")
35
  return None
36
 
37
  # ✨ 升級為最新 Kaldi ASR 引擎
38
- asr_client = safe_client_init("https://ai-labs.ilrdf.org.tw/sapolita-kaldi/", "語音辨識(Kaldi)")
39
- # 翻譯與 TTS 保持原有連線
40
  trans_client = safe_client_init("https://ai-labs.ilrdf.org.tw/kari-seejiq-tnpusu-ai-hmjil/", "翻譯(MT)")
41
  tts_client = safe_client_init("https://ai-labs.ilrdf.org.tw/hnang-kari-ai-asi-sluhay/", "語音合成(TTS)")
42
 
@@ -64,9 +63,9 @@ async def websocket_subtitle(websocket: WebSocket):
64
  audio_chunk = await websocket.receive_bytes()
65
  audio_buffer.extend(audio_chunk)
66
 
67
- # 2. 累積約 3.5 秒音訊後處理 (解決 Line 80 語法結構問題)
68
- if len(audio_buffer) > 160000:
69
- print(f"🧠 緩衝達標,準備辨識雅美語...")
70
 
71
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav:
72
  with wave.open(temp_wav.name, 'wb') as wav_file:
@@ -77,18 +76,19 @@ async def websocket_subtitle(websocket: WebSocket):
77
  temp_path = temp_wav.name
78
 
79
  detected_text = ""
 
80
  if asr_client:
81
  try:
82
- # 🚀 鎖定雅美語 (formosan_tao) 與正確 API 端點
83
  result = asr_client.predict(
84
  dialect_id="formosan_tao",
85
  audio_data=handle_file(temp_path),
86
  api_name="/automatic_speech_recognition"
87
  )
88
  detected_text = str(result)
89
- print(f"✨ 雅美語辨識結果: {detected_text}")
90
  except Exception as asr_err:
91
- print(f"⚠️ ASR 辨識出錯: {asr_err}")
92
  detected_text = "辨識中..."
93
  else:
94
  detected_text = "ASR 大腦未就位"
@@ -104,8 +104,8 @@ async def websocket_subtitle(websocket: WebSocket):
104
  if os.path.exists(temp_path):
105
  os.remove(temp_path)
106
  else:
107
- # 緩衝中,保持連線心跳 (改善 image_8c5a43.png 的反饋)
108
- if len(audio_buffer) % 20 == 0:
109
  await websocket.send_json({
110
  "status": "buffering",
111
  "text": "🟢 神獸正在聽雅美語..."
@@ -114,20 +114,18 @@ async def websocket_subtitle(websocket: WebSocket):
114
  except WebSocketDisconnect:
115
  print("❌ 神獸斷線")
116
  except Exception as e:
117
- print(f"⚠️ 即時處理錯誤: {e}")
118
 
119
  # ==========================================
120
- # 📚 功能二:16 族雙向文字翻譯 (完整補回)
121
  # ==========================================
122
  @app.post("/translate")
123
  async def translate(data: dict):
124
  if not trans_client:
125
  return {"result": "翻譯大腦尚未就緒"}
126
-
127
  source_text = data.get("text")
128
  direction = data.get("direction", "zh2indigenous")
129
  ethnicity = data.get("ethnicity", "太魯閣")
130
-
131
  try:
132
  if direction in ["zh2trv", "zh2indigenous", "中翻族"]:
133
  dialect_result = trans_client.predict(ethnicity=ethnicity, api_name="/lambda_1")
@@ -142,50 +140,43 @@ async def translate(data: dict):
142
  return {"result": f"翻譯出錯: {str(e)}"}
143
 
144
  # ==========================================
145
- # 📋 功能三:獲取 16 族配音員名單 (完整補回)
146
  # ==========================================
147
  @app.post("/get_speakers")
148
  async def get_speakers(data: dict):
149
  if not tts_client:
150
- return {"error": "語音大腦尚未就緒"}
151
- ethnicity = data.get("ethnicity", "太魯閣")
152
  try:
153
- result = tts_client.predict(ethnicity=ethnicity, api_name="/lambda")
154
  speakers = [c[0] if isinstance(c, list) else c for c in result['choices']] if isinstance(result, dict) else result
155
  return {"speakers": speakers}
156
  except Exception as e:
157
  return {"error": str(e)}
158
 
159
  # ==========================================
160
- # 🎵 功能四:16 族語音合成 (完整補回)
161
  # ==========================================
162
  @app.post("/synthesize")
163
  async def synthesize(data: dict):
164
  if not tts_client:
165
  raise HTTPException(status_code=503, detail="語音大腦未就緒")
166
-
167
- text = data.get("text", "")
168
- ethnicity = data.get("ethnicity", "太魯閣")
169
- requested_speaker = data.get("speaker", "太魯閣_男聲")
170
-
171
  try:
 
 
 
172
  speaker_choices = tts_client.predict(ethnicity=ethnicity, api_name="/lambda")
173
  full_list = [c[0] if isinstance(c, list) else c for c in speaker_choices['choices']]
174
  target_speaker = requested_speaker if requested_speaker in full_list else full_list[0]
175
-
176
  audio_filepath = tts_client.predict(ref=target_speaker, gen_text_input=text[:300], api_name="/default_speaker_tts")
177
-
178
- with open(audio_filepath, "rb") as audio_file:
179
- encoded_audio = base64.b64encode(audio_file.read()).decode('utf-8')
180
-
181
  os.remove(audio_filepath)
182
- return {"audio_base64": encoded_audio, "mime_type": "audio/wav", "speaker_used": target_speaker}
183
  except Exception as e:
184
  raise HTTPException(status_code=500, detail=str(e))
185
 
186
  if __name__ == "__main__":
187
  import uvicorn
188
- # 強制使用 7860 埠號以符合 Hugging Face 規範
189
  port = int(os.environ.get("PORT", 7860))
190
  print(f"🎬 正在啟動 16 族全能超級大腦 (Port {port})...")
191
  uvicorn.run(app, host="0.0.0.0", port=port)
 
21
 
22
  @app.get("/")
23
  async def root():
24
+ return {"message": "16 族語 AI 神獸大腦(雅美語 ASR 完整版)正在運行中!"}
25
 
26
  # ==========================================
27
  # 🔗 連結原語會 AI 實驗室 (三大核心大腦)
 
31
  print(f"🧬 正在連線至 {name} 大腦: {url}")
32
  return Client(url)
33
  except Exception as e:
34
+ print(f"⚠️ {name} 連線失敗: {e}")
35
  return None
36
 
37
  # ✨ 升級為最新 Kaldi ASR 引擎
38
+ asr_client = safe_client_init("https://ai-labs.ilrdf.org.tw/sapolita-kaldi/", "語音辨識(ASR)")
 
39
  trans_client = safe_client_init("https://ai-labs.ilrdf.org.tw/kari-seejiq-tnpusu-ai-hmjil/", "翻譯(MT)")
40
  tts_client = safe_client_init("https://ai-labs.ilrdf.org.tw/hnang-kari-ai-asi-sluhay/", "語音合成(TTS)")
41
 
 
63
  audio_chunk = await websocket.receive_bytes()
64
  audio_buffer.extend(audio_chunk)
65
 
66
+ # 2. 累積約 2.5 秒音訊後處理 (調低門檻至 100,000 bytes,反應更快)
67
+ if len(audio_buffer) > 100000:
68
+ print(f"🧠 緩衝達標 ({len(audio_buffer)} bytes),辨識雅美語中...")
69
 
70
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav:
71
  with wave.open(temp_wav.name, 'wb') as wav_file:
 
76
  temp_path = temp_wav.name
77
 
78
  detected_text = ""
79
+ # ✨ 語法修正區:確保 try/except 配對正確
80
  if asr_client:
81
  try:
82
+ # 🚀 鎖定雅美語專用代碼 (formosan_tao)
83
  result = asr_client.predict(
84
  dialect_id="formosan_tao",
85
  audio_data=handle_file(temp_path),
86
  api_name="/automatic_speech_recognition"
87
  )
88
  detected_text = str(result)
89
+ print(f"✨ 辨識結果: {detected_text}")
90
  except Exception as asr_err:
91
+ print(f"⚠️ ASR 辨識錯誤: {asr_err}")
92
  detected_text = "辨識中..."
93
  else:
94
  detected_text = "ASR 大腦未就位"
 
104
  if os.path.exists(temp_path):
105
  os.remove(temp_path)
106
  else:
107
+ # 緩衝中,每收到一定資料發送一次心跳
108
+ if len(audio_buffer) % 40 == 0:
109
  await websocket.send_json({
110
  "status": "buffering",
111
  "text": "🟢 神獸正在聽雅美語..."
 
114
  except WebSocketDisconnect:
115
  print("❌ 神獸斷線")
116
  except Exception as e:
117
+ print(f"⚠️ 系統錯誤: {e}")
118
 
119
  # ==========================================
120
+ # 📚 功能二:16 族雙向文字翻譯
121
  # ==========================================
122
  @app.post("/translate")
123
  async def translate(data: dict):
124
  if not trans_client:
125
  return {"result": "翻譯大腦尚未就緒"}
 
126
  source_text = data.get("text")
127
  direction = data.get("direction", "zh2indigenous")
128
  ethnicity = data.get("ethnicity", "太魯閣")
 
129
  try:
130
  if direction in ["zh2trv", "zh2indigenous", "中翻族"]:
131
  dialect_result = trans_client.predict(ethnicity=ethnicity, api_name="/lambda_1")
 
140
  return {"result": f"翻譯出錯: {str(e)}"}
141
 
142
  # ==========================================
143
+ # 📋 功能三:獲取配音員名單
144
  # ==========================================
145
  @app.post("/get_speakers")
146
  async def get_speakers(data: dict):
147
  if not tts_client:
148
+ return {"error": "語音大腦未就緒"}
 
149
  try:
150
+ result = tts_client.predict(ethnicity=data.get("ethnicity", "太魯閣"), api_name="/lambda")
151
  speakers = [c[0] if isinstance(c, list) else c for c in result['choices']] if isinstance(result, dict) else result
152
  return {"speakers": speakers}
153
  except Exception as e:
154
  return {"error": str(e)}
155
 
156
  # ==========================================
157
+ # 🎵 功能四:語音合成 (TTS)
158
  # ==========================================
159
  @app.post("/synthesize")
160
  async def synthesize(data: dict):
161
  if not tts_client:
162
  raise HTTPException(status_code=503, detail="語音大腦未就緒")
 
 
 
 
 
163
  try:
164
+ text = data.get("text", "")
165
+ ethnicity = data.get("ethnicity", "太魯閣")
166
+ requested_speaker = data.get("speaker", "太魯閣_男聲")
167
  speaker_choices = tts_client.predict(ethnicity=ethnicity, api_name="/lambda")
168
  full_list = [c[0] if isinstance(c, list) else c for c in speaker_choices['choices']]
169
  target_speaker = requested_speaker if requested_speaker in full_list else full_list[0]
 
170
  audio_filepath = tts_client.predict(ref=target_speaker, gen_text_input=text[:300], api_name="/default_speaker_tts")
171
+ with open(audio_filepath, "rb") as f:
172
+ encoded_audio = base64.b64encode(f.read()).decode('utf-8')
 
 
173
  os.remove(audio_filepath)
174
+ return {"audio_base64": encoded_audio, "mime_type": "audio/wav"}
175
  except Exception as e:
176
  raise HTTPException(status_code=500, detail=str(e))
177
 
178
  if __name__ == "__main__":
179
  import uvicorn
 
180
  port = int(os.environ.get("PORT", 7860))
181
  print(f"🎬 正在啟動 16 族全能超級大腦 (Port {port})...")
182
  uvicorn.run(app, host="0.0.0.0", port=port)