Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,9 +5,13 @@ import tempfile
|
|
| 5 |
import wave
|
| 6 |
import base64
|
| 7 |
import os
|
|
|
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
app.add_middleware(
|
| 12 |
CORSMiddleware,
|
| 13 |
allow_origins=["*"],
|
|
@@ -15,27 +19,42 @@ app.add_middleware(
|
|
| 15 |
allow_headers=["*"],
|
| 16 |
)
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# ==========================================
|
| 19 |
-
# 🔗 連結核心大腦
|
| 20 |
# ==========================================
|
| 21 |
def safe_client_init(url, name):
|
| 22 |
try:
|
| 23 |
-
print(f"🧬 正在
|
| 24 |
return Client(url)
|
| 25 |
except Exception as e:
|
| 26 |
-
print(f"⚠️ {name}
|
| 27 |
return None
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# ==========================================
|
| 33 |
-
# 🐉 雙語即時專線
|
| 34 |
# ==========================================
|
| 35 |
@app.websocket("/ws/subtitle")
|
| 36 |
async def websocket_subtitle(websocket: WebSocket):
|
| 37 |
await websocket.accept()
|
| 38 |
-
print("📢
|
| 39 |
audio_buffer = bytearray()
|
| 40 |
|
| 41 |
try:
|
|
@@ -43,9 +62,9 @@ async def websocket_subtitle(websocket: WebSocket):
|
|
| 43 |
audio_chunk = await websocket.receive_bytes()
|
| 44 |
audio_buffer.extend(audio_chunk)
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
if len(audio_buffer) >
|
| 48 |
-
print(f"🧠
|
| 49 |
|
| 50 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav:
|
| 51 |
with wave.open(temp_wav.name, 'wb') as wav_file:
|
|
@@ -58,28 +77,28 @@ async def websocket_subtitle(websocket: WebSocket):
|
|
| 58 |
ind_text = ""
|
| 59 |
zh_text = ""
|
| 60 |
|
|
|
|
| 61 |
if asr_client:
|
| 62 |
try:
|
| 63 |
-
# 1.
|
| 64 |
-
|
| 65 |
dialect_id="formosan_tao",
|
| 66 |
audio_data=handle_file(temp_path),
|
| 67 |
api_name="/automatic_speech_recognition"
|
| 68 |
)
|
| 69 |
-
ind_text = str(
|
| 70 |
-
print(f"✨ AI 聽到了: {ind_text}")
|
| 71 |
|
| 72 |
-
# 2. 如果辨識出文字,立刻
|
| 73 |
-
if ind_text and ind_text != "...":
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
except Exception as e:
|
| 84 |
print(f"⚠️ ASR/MT 處理失敗: {e}")
|
| 85 |
ind_text = "[AI 思考中...]"
|
|
@@ -88,18 +107,66 @@ async def websocket_subtitle(websocket: WebSocket):
|
|
| 88 |
await websocket.send_json({
|
| 89 |
"status": "recognizing",
|
| 90 |
"indigenous": ind_text if ind_text else "...",
|
| 91 |
-
"chinese": zh_text if zh_text else "正在
|
| 92 |
})
|
| 93 |
|
| 94 |
audio_buffer = bytearray()
|
| 95 |
if os.path.exists(temp_path): os.remove(temp_path)
|
| 96 |
else:
|
| 97 |
-
# 傳送緩衝
|
| 98 |
if len(audio_buffer) % 40 == 0:
|
| 99 |
-
await websocket.send_json({
|
| 100 |
-
"status": "buffering",
|
| 101 |
-
"text": "🟢 神獸正在傾聽雅美語..."
|
| 102 |
-
})
|
| 103 |
|
| 104 |
except WebSocketDisconnect:
|
| 105 |
-
print("❌
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import wave
|
| 6 |
import base64
|
| 7 |
import os
|
| 8 |
+
import json
|
| 9 |
|
| 10 |
app = FastAPI()
|
| 11 |
|
| 12 |
+
# ==========================================
|
| 13 |
+
# ⚙️ 基礎設定與 CORS (確保擴充功能可連線)
|
| 14 |
+
# ==========================================
|
| 15 |
app.add_middleware(
|
| 16 |
CORSMiddleware,
|
| 17 |
allow_origins=["*"],
|
|
|
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
| 22 |
+
@app.get("/")
|
| 23 |
+
async def root():
|
| 24 |
+
return {"message": "16 族語 AI 神獸大腦(雅美語雙語版)完全體運行中!"}
|
| 25 |
+
|
| 26 |
# ==========================================
|
| 27 |
+
# 🔗 連結原語會 AI 實驗室 (三大核心大腦)
|
| 28 |
# ==========================================
|
| 29 |
def safe_client_init(url, name):
|
| 30 |
try:
|
| 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 辨識引擎
|
| 38 |
+
asr_client = safe_client_init("https://ai-labs.ilrdf.org.tw/sapolita-kaldi/", "語音辨識(ASR)")
|
| 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 |
+
|
| 43 |
+
# 🛠️ 解析字典檔的小工具
|
| 44 |
+
def parse_dialect(dialect_result):
|
| 45 |
+
if isinstance(dialect_result, dict) and 'value' in dialect_result:
|
| 46 |
+
return dialect_result['value']
|
| 47 |
+
elif isinstance(dialect_result, list):
|
| 48 |
+
return dialect_result[0]
|
| 49 |
+
return dialect_result
|
| 50 |
|
| 51 |
# ==========================================
|
| 52 |
+
# 🐉 功能一:雙語即時字幕專線 (核心修正)
|
| 53 |
# ==========================================
|
| 54 |
@app.websocket("/ws/subtitle")
|
| 55 |
async def websocket_subtitle(websocket: WebSocket):
|
| 56 |
await websocket.accept()
|
| 57 |
+
print("📢 雅美語雙語專線已開啟")
|
| 58 |
audio_buffer = bytearray()
|
| 59 |
|
| 60 |
try:
|
|
|
|
| 62 |
audio_chunk = await websocket.receive_bytes()
|
| 63 |
audio_buffer.extend(audio_chunk)
|
| 64 |
|
| 65 |
+
# 累積約 2.5 秒音訊 (110,000 bytes)
|
| 66 |
+
if len(audio_buffer) > 110000:
|
| 67 |
+
print(f"🧠 緩衝達標,辨識雅美語中...")
|
| 68 |
|
| 69 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav:
|
| 70 |
with wave.open(temp_wav.name, 'wb') as wav_file:
|
|
|
|
| 77 |
ind_text = ""
|
| 78 |
zh_text = ""
|
| 79 |
|
| 80 |
+
# 🚀 辨識與翻譯連鎖反應
|
| 81 |
if asr_client:
|
| 82 |
try:
|
| 83 |
+
# 1. 雅美語辨識 (使用 Tao 代碼)
|
| 84 |
+
asr_res = asr_client.predict(
|
| 85 |
dialect_id="formosan_tao",
|
| 86 |
audio_data=handle_file(temp_path),
|
| 87 |
api_name="/automatic_speech_recognition"
|
| 88 |
)
|
| 89 |
+
ind_text = str(asr_res).strip()
|
|
|
|
| 90 |
|
| 91 |
+
# 2. 如果辨識出文字,立刻翻中文
|
| 92 |
+
if ind_text and ind_text != "..." and trans_client:
|
| 93 |
+
# 雅美語翻譯代碼 tao_Latn
|
| 94 |
+
zh_res = trans_client.predict(
|
| 95 |
+
text=ind_text,
|
| 96 |
+
src_lang="tao_Latn",
|
| 97 |
+
tgt_lang="zho_Hant",
|
| 98 |
+
api_name="/translate"
|
| 99 |
+
)
|
| 100 |
+
zh_text = str(zh_res)
|
| 101 |
+
print(f"✨ 雙語成功: {ind_text} -> {zh_text}")
|
| 102 |
except Exception as e:
|
| 103 |
print(f"⚠️ ASR/MT 處理失敗: {e}")
|
| 104 |
ind_text = "[AI 思考中...]"
|
|
|
|
| 107 |
await websocket.send_json({
|
| 108 |
"status": "recognizing",
|
| 109 |
"indigenous": ind_text if ind_text else "...",
|
| 110 |
+
"chinese": zh_text if zh_text else "正在翻譯中..."
|
| 111 |
})
|
| 112 |
|
| 113 |
audio_buffer = bytearray()
|
| 114 |
if os.path.exists(temp_path): os.remove(temp_path)
|
| 115 |
else:
|
| 116 |
+
# 傳送緩衝中狀態,維持連線
|
| 117 |
if len(audio_buffer) % 40 == 0:
|
| 118 |
+
await websocket.send_json({"status": "buffering", "text": "🟢 神獸正在聽雅美語..."})
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
except WebSocketDisconnect:
|
| 121 |
+
print("❌ 斷線")
|
| 122 |
+
|
| 123 |
+
# ==========================================
|
| 124 |
+
# 📚 功能二:16 族雙向文字翻譯
|
| 125 |
+
# ==========================================
|
| 126 |
+
@app.post("/translate")
|
| 127 |
+
async def translate(data: dict):
|
| 128 |
+
if not trans_client: return {"result": "翻譯大腦未就緒"}
|
| 129 |
+
text = data.get("text")
|
| 130 |
+
direction = data.get("direction", "zh2indigenous")
|
| 131 |
+
ethnicity = data.get("ethnicity", "雅美")
|
| 132 |
+
try:
|
| 133 |
+
if direction in ["zh2indigenous", "中翻族"]:
|
| 134 |
+
dialect_code = parse_dialect(trans_client.predict(ethnicity=ethnicity, api_name="/lambda_1"))
|
| 135 |
+
result = trans_client.predict(text=text, src_lang="zho_Hant", tgt_lang=dialect_code, api_name="/translate_1")
|
| 136 |
+
else:
|
| 137 |
+
dialect_code = parse_dialect(trans_client.predict(ethnicity=ethnicity, api_name="/lambda"))
|
| 138 |
+
result = trans_client.predict(text=text, src_lang=dialect_code, tgt_lang="zho_Hant", api_name="/translate")
|
| 139 |
+
return {"result": result}
|
| 140 |
+
except Exception as e: return {"result": f"翻譯錯誤: {e}"}
|
| 141 |
+
|
| 142 |
+
# ==========================================
|
| 143 |
+
# 📋 功能三:語音合成與名單
|
| 144 |
+
# ==========================================
|
| 145 |
+
@app.post("/get_speakers")
|
| 146 |
+
async def get_speakers(data: dict):
|
| 147 |
+
if not tts_client: return {"error": "語音大腦未就緒"}
|
| 148 |
+
try:
|
| 149 |
+
result = tts_client.predict(ethnicity=data.get("ethnicity", "雅美"), api_name="/lambda")
|
| 150 |
+
speakers = [c[0] if isinstance(c, list) else c for c in result['choices']] if isinstance(result, dict) else result
|
| 151 |
+
return {"speakers": speakers}
|
| 152 |
+
except Exception as e: return {"error": str(e)}
|
| 153 |
+
|
| 154 |
+
@app.post("/synthesize")
|
| 155 |
+
async def synthesize(data: dict):
|
| 156 |
+
if not tts_client: raise HTTPException(status_code=503, detail="大腦未就緒")
|
| 157 |
+
try:
|
| 158 |
+
speaker_choices = tts_client.predict(ethnicity=data.get("ethnicity", "雅美"), api_name="/lambda")
|
| 159 |
+
full_list = [c[0] if isinstance(c, list) else c for c in speaker_choices['choices']]
|
| 160 |
+
target_speaker = data.get("speaker", "雅美語_男聲")
|
| 161 |
+
if target_speaker not in full_list: target_speaker = full_list[0]
|
| 162 |
+
|
| 163 |
+
audio_path = tts_client.predict(ref=target_speaker, gen_text_input=data.get("text", "")[:300], api_name="/default_speaker_tts")
|
| 164 |
+
with open(audio_path, "rb") as f:
|
| 165 |
+
encoded = base64.b64encode(f.read()).decode('utf-8')
|
| 166 |
+
os.remove(audio_path)
|
| 167 |
+
return {"audio_base64": encoded, "mime_type": "audio/wav"}
|
| 168 |
+
except Exception as e: raise HTTPException(status_code=500, detail=str(e))
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
import uvicorn
|
| 172 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|