Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,15 +1,16 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from gradio_client import Client
|
| 4 |
import base64
|
| 5 |
import os
|
|
|
|
|
|
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
app.add_middleware(
|
| 14 |
CORSMiddleware,
|
| 15 |
allow_origins=["*"],
|
|
@@ -17,13 +18,18 @@ app.add_middleware(
|
|
| 17 |
allow_headers=["*"],
|
| 18 |
)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
# ==========================================
|
| 21 |
-
# 🔗 連結原語會 AI 實驗室 (
|
| 22 |
# ==========================================
|
| 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 |
-
# 🛠️ 解析字典檔的小工具
|
| 27 |
def parse_dialect(dialect_result):
|
| 28 |
if isinstance(dialect_result, dict) and 'value' in dialect_result:
|
| 29 |
return dialect_result['value']
|
|
@@ -32,117 +38,60 @@ def parse_dialect(dialect_result):
|
|
| 32 |
return dialect_result
|
| 33 |
|
| 34 |
# ==========================================
|
| 35 |
-
#
|
| 36 |
# ==========================================
|
| 37 |
-
@app.
|
| 38 |
-
async def
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
ethnicity = data.get("ethnicity", "太魯閣") # ✨ 關鍵升級:動態接收族別
|
| 42 |
|
| 43 |
try:
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
dialect_result = trans_client.predict(ethnicity=ethnicity, api_name="/lambda_1")
|
| 48 |
-
dialect_code = parse_dialect(dialect_result)
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
src_lang="zho_Hant",
|
| 53 |
-
tgt_lang=dialect_code,
|
| 54 |
-
api_name="/translate_1"
|
| 55 |
-
)
|
| 56 |
-
else:
|
| 57 |
-
# 【族翻中】
|
| 58 |
-
dialect_result = trans_client.predict(ethnicity=ethnicity, api_name="/lambda")
|
| 59 |
-
dialect_code = parse_dialect(dialect_result)
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
api_name="/translate"
|
| 66 |
-
)
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
except Exception as e:
|
| 71 |
-
print(f"
|
| 72 |
-
return {"result": f"API 呼叫失敗: {str(e)}"}
|
| 73 |
|
| 74 |
# ==========================================
|
| 75 |
-
#
|
| 76 |
# ==========================================
|
| 77 |
-
@app.post("/get_speakers")
|
| 78 |
-
async def get_speakers(data: dict):
|
| 79 |
-
ethnicity = data.get("ethnicity", "太魯閣")
|
| 80 |
-
try:
|
| 81 |
-
result = tts_client.predict(ethnicity=ethnicity, api_name="/lambda")
|
| 82 |
-
if isinstance(result, dict) and 'choices' in result:
|
| 83 |
-
speakers = [c[0] if isinstance(c, list) else c for c in result['choices']]
|
| 84 |
-
else:
|
| 85 |
-
speakers = result
|
| 86 |
-
return {"speakers": speakers}
|
| 87 |
-
except Exception as e:
|
| 88 |
-
print(f"❌ 獲取名單失敗: {e}")
|
| 89 |
-
return {"error": str(e)}
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
#
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
text = data.get("text", "")
|
| 97 |
ethnicity = data.get("ethnicity", "太魯閣")
|
| 98 |
-
requested_speaker = data.get("speaker", "太魯閣_男聲")
|
| 99 |
-
|
| 100 |
-
if not text:
|
| 101 |
-
raise HTTPException(status_code=400, detail="請提供文字")
|
| 102 |
-
|
| 103 |
-
sanitized_text = text.replace("!", "!").replace("?", "?").replace(",", ",").replace("。", ".")
|
| 104 |
-
sanitized_text = sanitized_text.replace(":", ":").replace("(", "(").replace(")", ")")
|
| 105 |
-
|
| 106 |
try:
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
if requested_speaker in full_list:
|
| 113 |
-
target_speaker = requested_speaker
|
| 114 |
else:
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
audio_filepath = tts_client.predict(
|
| 120 |
-
ref=target_speaker,
|
| 121 |
-
gen_text_input=sanitized_text[:300],
|
| 122 |
-
api_name="/default_speaker_tts"
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
if not os.path.exists(audio_filepath):
|
| 126 |
-
raise Exception("音檔生成失敗")
|
| 127 |
-
|
| 128 |
-
with open(audio_filepath, "rb") as audio_file:
|
| 129 |
-
encoded_audio = base64.b64encode(audio_file.read()).decode('utf-8')
|
| 130 |
-
|
| 131 |
-
try: os.remove(audio_filepath)
|
| 132 |
-
except: pass
|
| 133 |
-
|
| 134 |
-
return {
|
| 135 |
-
"audio_base64": encoded_audio,
|
| 136 |
-
"mime_type": "audio/wav",
|
| 137 |
-
"speaker_used": target_speaker
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
except Exception as e:
|
| 141 |
-
|
| 142 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 143 |
|
| 144 |
-
|
| 145 |
-
import uvicorn
|
| 146 |
-
port = int(os.environ.get("PORT", 8000))
|
| 147 |
-
print(f"🎬 正在啟動 16 族全能超級大腦 (Port {port})...")
|
| 148 |
-
uvicorn.run(app, host="0.0.0.0", port=port)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from gradio_client import Client
|
| 4 |
import base64
|
| 5 |
import os
|
| 6 |
+
import json
|
| 7 |
+
import asyncio
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
+
# ==========================================
|
| 12 |
+
# ⚙️ 基礎設定與 CORS
|
| 13 |
+
# ==========================================
|
|
|
|
| 14 |
app.add_middleware(
|
| 15 |
CORSMiddleware,
|
| 16 |
allow_origins=["*"],
|
|
|
|
| 18 |
allow_headers=["*"],
|
| 19 |
)
|
| 20 |
|
| 21 |
+
@app.get("/")
|
| 22 |
+
async def root():
|
| 23 |
+
return {"message": "神獸方案:即時字幕實驗室大腦運作中!"}
|
| 24 |
+
|
| 25 |
# ==========================================
|
| 26 |
+
# 🔗 連結原語會 AI 實驗室 (三大腦連線)
|
| 27 |
# ==========================================
|
| 28 |
trans_client = Client("https://ai-labs.ilrdf.org.tw/kari-seejiq-tnpusu-ai-hmjil/")
|
| 29 |
tts_client = Client("https://ai-labs.ilrdf.org.tw/hnang-kari-ai-asi-sluhay/")
|
| 30 |
+
# ✨ 新增:ASR 語音辨識大腦 (假設接口相同,之後可調整)
|
| 31 |
+
asr_client = Client("https://ai-labs.ilrdf.org.tw/kari-sluhay-ai-hmjil/")
|
| 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 |
+
# 🐉 神獸方案:即時字幕 WebSocket 接口
|
| 42 |
# ==========================================
|
| 43 |
+
@app.websocket("/ws/subtitle")
|
| 44 |
+
async def websocket_subtitle(websocket: WebSocket):
|
| 45 |
+
await websocket.accept()
|
| 46 |
+
print("📢 神獸連線:即時字幕專線已建立")
|
|
|
|
| 47 |
|
| 48 |
try:
|
| 49 |
+
while True:
|
| 50 |
+
# 1. 接收來自 Chrome 的二進位音訊數據
|
| 51 |
+
audio_chunk = await websocket.receive_bytes()
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# 【技術挑戰點】:目前的音訊是 PCM 碎片,需要暫存或轉換格式才能送 ASR
|
| 54 |
+
# 目前我們先模擬回傳,確保連線暢通
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# 假設性流程:
|
| 57 |
+
# 1. 將音訊碎片寫入暫存檔
|
| 58 |
+
# 2. 调用 asr_client 進行語音轉文字 (ASR)
|
| 59 |
+
# 3. 调用 trans_client 進行翻譯 (MT)
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
# 暫時回傳模擬文字給前端 content.js 顯示
|
| 62 |
+
response_data = {
|
| 63 |
+
"status": "recognizing",
|
| 64 |
+
"text": "辨識中...", # 未來這裡會放 ASR+MT 的結果
|
| 65 |
+
"bytes_received": len(audio_chunk)
|
| 66 |
+
}
|
| 67 |
+
await websocket.send_json(response_data)
|
| 68 |
+
|
| 69 |
+
except WebSocketDisconnect:
|
| 70 |
+
print("❌ 神獸斷線:使用者關閉了即時字幕")
|
| 71 |
except Exception as e:
|
| 72 |
+
print(f"⚠️ 即時處理發生錯誤: {e}")
|
|
|
|
| 73 |
|
| 74 |
# ==========================================
|
| 75 |
+
# 📚 原有功能:1.0 版翻譯、TTS (保持不動,確保相容)
|
| 76 |
# ==========================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
@app.post("/translate")
|
| 79 |
+
async def translate(data: dict):
|
| 80 |
+
# ... (您的原本代碼,略)
|
| 81 |
+
source_text = data.get("text")
|
| 82 |
+
direction = data.get("direction", "zh2indigenous")
|
|
|
|
| 83 |
ethnicity = data.get("ethnicity", "太魯閣")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
try:
|
| 85 |
+
if direction in ["zh2trv", "zh2indigenous", "中翻族"]:
|
| 86 |
+
dialect_result = trans_client.predict(ethnicity=ethnicity, api_name="/lambda_1")
|
| 87 |
+
dialect_code = parse_dialect(dialect_result)
|
| 88 |
+
result = trans_client.predict(text=source_text, src_lang="zho_Hant", tgt_lang=dialect_code, api_name="/translate_1")
|
|
|
|
|
|
|
|
|
|
| 89 |
else:
|
| 90 |
+
dialect_result = trans_client.predict(ethnicity=ethnicity, api_name="/lambda")
|
| 91 |
+
dialect_code = parse_dialect(dialect_result)
|
| 92 |
+
result = trans_client.predict(text=source_text, src_lang=dialect_code, tgt_lang="zho_Hant", api_name="/translate")
|
| 93 |
+
return {"result": result}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
except Exception as e:
|
| 95 |
+
return {"result": f"API 呼叫失敗: {str(e)}"}
|
|
|
|
| 96 |
|
| 97 |
+
# ... (其餘 get_speakers 與 synthesize 代碼維持不變)
|
|
|
|
|
|
|
|
|
|
|
|