Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,13 +5,9 @@ import tempfile
|
|
| 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,12 +15,8 @@ app.add_middleware(
|
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
| 22 |
-
@app.get("/")
|
| 23 |
-
async def root():
|
| 24 |
-
return {"message": "16 族語 AI 神獸大腦(雅美語 ASR 完整版)正在運行中!"}
|
| 25 |
-
|
| 26 |
# ==========================================
|
| 27 |
-
# 🔗 連結原語會 AI
|
| 28 |
# ==========================================
|
| 29 |
def safe_client_init(url, name):
|
| 30 |
try:
|
|
@@ -34,12 +26,10 @@ def safe_client_init(url, name):
|
|
| 34 |
print(f"⚠️ {name} 連線失敗: {e}")
|
| 35 |
return None
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 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 |
|
| 42 |
-
#
|
| 43 |
def parse_dialect(dialect_result):
|
| 44 |
if isinstance(dialect_result, dict) and 'value' in dialect_result:
|
| 45 |
return dialect_result['value']
|
|
@@ -48,135 +38,83 @@ def parse_dialect(dialect_result):
|
|
| 48 |
return dialect_result
|
| 49 |
|
| 50 |
# ==========================================
|
| 51 |
-
# 🐉 功能
|
| 52 |
# ==========================================
|
| 53 |
@app.websocket("/ws/subtitle")
|
| 54 |
async def websocket_subtitle(websocket: WebSocket):
|
| 55 |
await websocket.accept()
|
| 56 |
-
print("📢 神獸
|
| 57 |
-
|
| 58 |
audio_buffer = bytearray()
|
| 59 |
|
| 60 |
try:
|
| 61 |
while True:
|
| 62 |
-
# 1. 接收來自 Chrome 的音訊碎片
|
| 63 |
audio_chunk = await websocket.receive_bytes()
|
| 64 |
audio_buffer.extend(audio_chunk)
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
if len(audio_buffer) >
|
| 68 |
-
print(f"🧠 緩衝達標
|
| 69 |
|
| 70 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav:
|
| 71 |
with wave.open(temp_wav.name, 'wb') as wav_file:
|
| 72 |
-
wav_file.setnchannels(1)
|
| 73 |
-
wav_file.setsampwidth(2)
|
| 74 |
-
wav_file.setframerate(44100)
|
| 75 |
wav_file.writeframes(audio_buffer)
|
| 76 |
temp_path = temp_wav.name
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
|
|
|
| 80 |
if asr_client:
|
| 81 |
try:
|
| 82 |
-
#
|
| 83 |
-
|
| 84 |
dialect_id="formosan_tao",
|
| 85 |
audio_data=handle_file(temp_path),
|
| 86 |
api_name="/automatic_speech_recognition"
|
| 87 |
)
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
# 3. 回傳
|
| 97 |
await websocket.send_json({
|
| 98 |
"status": "recognizing",
|
| 99 |
-
"
|
| 100 |
-
"
|
| 101 |
})
|
| 102 |
|
| 103 |
audio_buffer = bytearray()
|
| 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": "🟢 神獸正在聽雅美語..."
|
| 112 |
-
})
|
| 113 |
|
| 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")
|
| 132 |
-
dialect_code = parse_dialect(dialect_result)
|
| 133 |
-
result = trans_client.predict(text=source_text, src_lang="zho_Hant", tgt_lang=dialect_code, api_name="/translate_1")
|
| 134 |
-
else:
|
| 135 |
-
dialect_result = trans_client.predict(ethnicity=ethnicity, api_name="/lambda")
|
| 136 |
-
dialect_code = parse_dialect(dialect_result)
|
| 137 |
-
result = trans_client.predict(text=source_text, src_lang=dialect_code, tgt_lang="zho_Hant", api_name="/translate")
|
| 138 |
-
return {"result": result}
|
| 139 |
-
except Exception as e:
|
| 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 |
-
|
| 181 |
-
print(f"🎬 正在啟動 16 族全能超級大腦 (Port {port})...")
|
| 182 |
-
uvicorn.run(app, host="0.0.0.0", port=port)
|
|
|
|
| 5 |
import wave
|
| 6 |
import base64
|
| 7 |
import os
|
|
|
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
app.add_middleware(
|
| 12 |
CORSMiddleware,
|
| 13 |
allow_origins=["*"],
|
|
|
|
| 15 |
allow_headers=["*"],
|
| 16 |
)
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# ==========================================
|
| 19 |
+
# 🔗 連結原語會 AI 大腦 (ASR + 翻譯)
|
| 20 |
# ==========================================
|
| 21 |
def safe_client_init(url, name):
|
| 22 |
try:
|
|
|
|
| 26 |
print(f"⚠️ {name} 連線失敗: {e}")
|
| 27 |
return None
|
| 28 |
|
| 29 |
+
asr_client = safe_client_init("https://ai-labs.ilrdf.org.tw/sapolita-kaldi/", "語音辨識")
|
| 30 |
+
trans_client = safe_client_init("https://ai-labs.ilrdf.org.tw/kari-seejiq-tnpusu-ai-hmjil/", "翻譯")
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# 解析語言代碼的小工具
|
| 33 |
def parse_dialect(dialect_result):
|
| 34 |
if isinstance(dialect_result, dict) and 'value' in dialect_result:
|
| 35 |
return dialect_result['value']
|
|
|
|
| 38 |
return dialect_result
|
| 39 |
|
| 40 |
# ==========================================
|
| 41 |
+
# 🐉 核心功能:雙語即時字幕
|
| 42 |
# ==========================================
|
| 43 |
@app.websocket("/ws/subtitle")
|
| 44 |
async def websocket_subtitle(websocket: WebSocket):
|
| 45 |
await websocket.accept()
|
| 46 |
+
print("📢 神獸雙語專線已建立")
|
|
|
|
| 47 |
audio_buffer = bytearray()
|
| 48 |
|
| 49 |
try:
|
| 50 |
while True:
|
|
|
|
| 51 |
audio_chunk = await websocket.receive_bytes()
|
| 52 |
audio_buffer.extend(audio_chunk)
|
| 53 |
|
| 54 |
+
# 累積約 2.5 秒音訊 (調低門檻讓反應快一點)
|
| 55 |
+
if len(audio_buffer) > 120000:
|
| 56 |
+
print(f"🧠 緩衝達標,開始雙語處理...")
|
| 57 |
|
| 58 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav:
|
| 59 |
with wave.open(temp_wav.name, 'wb') as wav_file:
|
| 60 |
+
wav_file.setnchannels(1)
|
| 61 |
+
wav_file.setsampwidth(2)
|
| 62 |
+
wav_file.setframerate(44100)
|
| 63 |
wav_file.writeframes(audio_buffer)
|
| 64 |
temp_path = temp_wav.name
|
| 65 |
|
| 66 |
+
indigenous_text = ""
|
| 67 |
+
chinese_text = ""
|
| 68 |
+
|
| 69 |
if asr_client:
|
| 70 |
try:
|
| 71 |
+
# 1. 雅美語辨識
|
| 72 |
+
asr_result = asr_client.predict(
|
| 73 |
dialect_id="formosan_tao",
|
| 74 |
audio_data=handle_file(temp_path),
|
| 75 |
api_name="/automatic_speech_recognition"
|
| 76 |
)
|
| 77 |
+
indigenous_text = str(asr_result).strip()
|
| 78 |
+
|
| 79 |
+
# 2. 如果辨識出文字,立即翻譯成中文
|
| 80 |
+
if indigenous_text and indigenous_text != "...":
|
| 81 |
+
print(f"✨ 辨識到雅美語: {indigenous_text}")
|
| 82 |
+
if trans_client:
|
| 83 |
+
# 獲取雅美語代碼並翻譯
|
| 84 |
+
dialect_code = parse_dialect(trans_client.predict(ethnicity="雅美", api_name="/lambda"))
|
| 85 |
+
translation = trans_client.predict(
|
| 86 |
+
text=indigenous_text,
|
| 87 |
+
src_lang=dialect_code,
|
| 88 |
+
tgt_lang="zho_Hant",
|
| 89 |
+
api_name="/translate"
|
| 90 |
+
)
|
| 91 |
+
chinese_text = str(translation)
|
| 92 |
+
print(f"🧧 翻譯結果: {chinese_text}")
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"⚠️ 處理失敗: {e}")
|
| 96 |
|
| 97 |
+
# 3. 回傳雙語 JSON
|
| 98 |
await websocket.send_json({
|
| 99 |
"status": "recognizing",
|
| 100 |
+
"indigenous": indigenous_text if indigenous_text else "...",
|
| 101 |
+
"chinese": chinese_text if chinese_text else "正在翻譯中...",
|
| 102 |
})
|
| 103 |
|
| 104 |
audio_buffer = bytearray()
|
| 105 |
if os.path.exists(temp_path):
|
| 106 |
os.remove(temp_path)
|
| 107 |
else:
|
| 108 |
+
# 緩衝心跳
|
| 109 |
if len(audio_buffer) % 40 == 0:
|
| 110 |
+
await websocket.send_json({"status": "buffering", "text": "🟢 神獸正在聽雅美語..."})
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
except WebSocketDisconnect:
|
| 113 |
+
print("❌ 斷線")
|
| 114 |
except Exception as e:
|
| 115 |
print(f"⚠️ 系統錯誤: {e}")
|
| 116 |
|
| 117 |
+
# (保持其餘 translate, synthesize API 不變以便相容舊功能)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
if __name__ == "__main__":
|
| 119 |
import uvicorn
|
| 120 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|