Lowking commited on
Commit
c0a08a3
·
verified ·
1 Parent(s): 8bc3c32

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -102
app.py CHANGED
@@ -1,11 +1,9 @@
1
- from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from gradio_client import Client, handle_file
4
  import tempfile
5
  import wave
6
- import base64
7
  import os
8
- import json
9
 
10
  app = FastAPI()
11
 
@@ -16,42 +14,28 @@ app.add_middleware(
16
  allow_headers=["*"],
17
  )
18
 
19
- # ==========================================
20
- # 🔗 連結核心大腦
21
- # ==========================================
22
  asr_client = Client("https://ai-labs.ilrdf.org.tw/sapolita-kaldi/")
23
- trans_client = Client("https://ai-labs.ilrdf.org.tw/kari-seejiq-tnpusu-ai-hmjil/")
24
- tts_client = Client("https://ai-labs.ilrdf.org.tw/hnang-kari-ai-asi-sluhay/")
25
-
26
- def parse_dialect(dialect_result):
27
- if isinstance(dialect_result, dict) and 'value' in dialect_result:
28
- return dialect_result['value']
29
- elif isinstance(dialect_result, list) and len(dialect_result) > 0:
30
- return dialect_result[0]
31
- return dialect_result
32
 
33
  @app.get("/")
34
  async def root():
35
- return {"status": "running", "message": "16 族全能雙語神獸正在運行中!"}
36
 
37
- # ==========================================
38
- # 🐉 核心進化:雅美語即時雙語字幕 (長句累積版)
39
- # ==========================================
40
  @app.websocket("/ws/subtitle")
41
  async def websocket_subtitle(websocket: WebSocket):
42
  await websocket.accept()
43
  audio_buffer = bytearray()
44
- print("📢 雅美語即時字幕專線已啟動")
45
 
46
  try:
47
  while True:
48
  audio_chunk = await websocket.receive_bytes()
49
  audio_buffer.extend(audio_chunk)
50
 
51
- # 🚀 關鍵修正:將門檻拉高到 260,000 bytes (大約累積 3 秒鐘的聲音)
52
- # 讓大腦有足夠的上下文來辨識出完整的單字
53
- if len(audio_buffer) >= 260000:
54
- print(f"📦 累積音訊達標: {len(audio_buffer)} bytes,準備辨識...")
55
 
56
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav:
57
  with wave.open(temp_wav.name, 'wb') as wav_file:
@@ -61,93 +45,34 @@ async def websocket_subtitle(websocket: WebSocket):
61
  wav_file.writeframes(audio_buffer)
62
  temp_path = temp_wav.name
63
 
64
- ind_text, zh_text = "", ""
65
  try:
66
- # 1. 官方 ASR 辨識
67
- asr_res = asr_client.predict(
68
  dialect_id="formosan_tao",
69
  audio_data=handle_file(temp_path),
70
  api_name="/automatic_speech_recognition"
71
  )
72
-
73
- if asr_res:
74
- ind_text = str(asr_res).strip()
75
-
76
- print(f"🧠 ASR 原始結果: '{ind_text}'")
77
-
78
- # 過濾無意義的雜訊符號
79
- noise_list = ["", ".", "...", "。", "<unk>"]
80
-
81
- # 2. MT 翻譯
82
- if ind_text not in noise_list:
83
- d_code = parse_dialect(trans_client.predict(ethnicity="雅美", api_name="/lambda"))
84
- zh_res = trans_client.predict(text=ind_text, src_lang=d_code, tgt_lang="zho_Hant", api_name="/translate")
85
- if zh_res:
86
- zh_text = str(zh_res).strip()
87
- print(f"🚀 [雙語辨識成功] 族語: {ind_text} | 中文: {zh_text}")
88
- else:
89
- ind_text = ""
90
- zh_text = ""
91
- print("🤷‍♂️ 只聽到雜音或停頓,跳過翻譯。")
92
 
 
 
 
 
 
 
93
  except Exception as e:
94
- print(f"⚠️ API 處理失敗: {e}")
 
95
 
96
- # 發送最終雙語結果
97
- await websocket.send_json({
98
- "status": "recognizing",
99
- "indigenous": ind_text,
100
- "chinese": zh_text
101
- })
102
-
103
  audio_buffer = bytearray()
104
  if os.path.exists(temp_path): os.remove(temp_path)
105
  else:
106
- # 緩衝中狀態回報
107
- if len(audio_buffer) % 65000 == 0:
108
- await websocket.send_json({"status": "buffering", "text": "🟢 神獸正在聆聽完整句子..."})
 
 
 
109
  except WebSocketDisconnect:
110
- print("❌ 專線斷線")
111
- except Exception as e:
112
- print(f"💥 發生錯誤: {e}")
113
-
114
- # ==========================================
115
- # 📚 保留您最順暢的 16 族 REST 功能
116
- # ==========================================
117
- @app.post("/translate")
118
- async def translate(data: dict):
119
- source_text, direction, ethnicity = data.get("text"), data.get("direction", "zh2indigenous"), data.get("ethnicity", "太魯閣")
120
- try:
121
- api_n = "/translate_1" if direction in ["zh2indigenous", "中翻族"] else "/translate"
122
- lam_n = "/lambda_1" if "/translate_1" in api_n else "/lambda"
123
- d_code = parse_dialect(trans_client.predict(ethnicity=ethnicity, api_name=lam_n))
124
- src_l, tgt_l = ("zho_Hant", d_code) if "zh2" in direction else (d_code, "zho_Hant")
125
- result = trans_client.predict(text=source_text, src_lang=src_l, tgt_lang=tgt_l, api_name=api_n)
126
- return {"result": result}
127
- except Exception as e: return {"result": str(e)}
128
-
129
- @app.post("/get_speakers")
130
- async def get_speakers(data: dict):
131
- try:
132
- result = tts_client.predict(ethnicity=data.get("ethnicity", "太魯閣"), api_name="/lambda")
133
- speakers = [c[0] if isinstance(c, list) else c for c in result['choices']] if isinstance(result, dict) else result
134
- return {"speakers": speakers}
135
- except Exception as e: return {"error": str(e)}
136
-
137
- @app.post("/synthesize")
138
- async def synthesize(data: dict):
139
- try:
140
- text, eth, req_spk = data.get("text", ""), data.get("ethnicity", "太魯閣"), data.get("speaker", "太魯閣_男聲")
141
- spk_choices = tts_client.predict(ethnicity=eth, api_name="/lambda")
142
- full_list = [c[0] if isinstance(c, list) else c for c in spk_choices['choices']]
143
- target_speaker = req_spk if req_spk in full_list else full_list[0]
144
- audio_path = tts_client.predict(ref=target_speaker, gen_text_input=text[:300], api_name="/default_speaker_tts")
145
- with open(audio_path, "rb") as f: encoded = base64.b64encode(f.read()).decode('utf-8')
146
- os.remove(audio_path)
147
- return {"audio_base64": encoded, "mime_type": "audio/wav"}
148
- except Exception as e: raise HTTPException(status_code=500, detail=str(e))
149
-
150
- if __name__ == "__main__":
151
- import uvicorn
152
- # Hugging Face Spaces 必須使用 7860 埠號
153
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from gradio_client import Client, handle_file
4
  import tempfile
5
  import wave
 
6
  import os
 
7
 
8
  app = FastAPI()
9
 
 
14
  allow_headers=["*"],
15
  )
16
 
17
+ # 🔗 只連結 ASR 大腦
 
 
18
  asr_client = Client("https://ai-labs.ilrdf.org.tw/sapolita-kaldi/")
 
 
 
 
 
 
 
 
 
19
 
20
  @app.get("/")
21
  async def root():
22
+ return {"status": "ASR Test Mode Ready"}
23
 
 
 
 
24
  @app.websocket("/ws/subtitle")
25
  async def websocket_subtitle(websocket: WebSocket):
26
  await websocket.accept()
27
  audio_buffer = bytearray()
28
+ print("📢 ASR 測試專線已連線")
29
 
30
  try:
31
  while True:
32
  audio_chunk = await websocket.receive_bytes()
33
  audio_buffer.extend(audio_chunk)
34
 
35
+ # ✨ 調整門檻:累積約 3.5 秒音訊 (約 150,000 bytes)
36
+ # 這是為了給 Kaldi 足夠的長度辨識出單字,避免一直回傳點點
37
+ if len(audio_buffer) >= 150000:
38
+ print(f"🧠 音訊累積達標 ({len(audio_buffer)} bytes),呼叫 ASR...")
39
 
40
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav:
41
  with wave.open(temp_wav.name, 'wb') as wav_file:
 
45
  wav_file.writeframes(audio_buffer)
46
  temp_path = temp_wav.name
47
 
 
48
  try:
49
+ # 🚀 直接調用 ASR API
50
+ result = asr_client.predict(
51
  dialect_id="formosan_tao",
52
  audio_data=handle_file(temp_path),
53
  api_name="/automatic_speech_recognition"
54
  )
55
+ raw_text = str(result).strip()
56
+ print(f"✨ ASR 原始結果: '{raw_text}'")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ # 直接回傳原始結果,不做任何過濾
59
+ await websocket.send_json({
60
+ "status": "recognizing",
61
+ "indigenous": f"原始 ASR: {raw_text}",
62
+ "chinese": "測試模式:暫不翻譯"
63
+ })
64
  except Exception as e:
65
+ print(f"❌ ASR 呼叫出錯: {e}")
66
+ await websocket.send_json({"status": "error", "text": f"ASR 錯誤: {str(e)}"})
67
 
 
 
 
 
 
 
 
68
  audio_buffer = bytearray()
69
  if os.path.exists(temp_path): os.remove(temp_path)
70
  else:
71
+ # 緩衝進度顯示
72
+ if len(audio_buffer) % 30000 == 0:
73
+ await websocket.send_json({
74
+ "status": "buffering",
75
+ "text": f"🟢 收集音訊中... ({len(audio_buffer)} / 150000)"
76
+ })
77
  except WebSocketDisconnect:
78
+ print("❌ 連線中斷")