|
|
import os |
|
|
import json |
|
|
from fastapi import FastAPI, WebSocket |
|
|
from fastapi.middleware.cors import CORSMiddleware |
|
|
from vosk import Model, KaldiRecognizer |
|
|
import uvicorn |
|
|
|
|
|
|
|
|
MODEL_PATH = "model/vosk-model" |
|
|
if not os.path.exists(MODEL_PATH): |
|
|
raise Exception("❌ Model Vosk không tìm thấy!") |
|
|
|
|
|
print("✅ Đang tải model Vosk...") |
|
|
model = Model(MODEL_PATH) |
|
|
|
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
|
app.add_middleware( |
|
|
CORSMiddleware, |
|
|
allow_origins=["*"], |
|
|
allow_credentials=True, |
|
|
allow_methods=["*"], |
|
|
allow_headers=["*"], |
|
|
) |
|
|
|
|
|
@app.websocket("/") |
|
|
async def websocket_endpoint(websocket: WebSocket): |
|
|
await websocket.accept() |
|
|
rec = KaldiRecognizer(model, 16000) |
|
|
result_text = "" |
|
|
|
|
|
try: |
|
|
while True: |
|
|
message = await websocket.receive_bytes() |
|
|
if rec.AcceptWaveform(message): |
|
|
result = json.loads(rec.Result()) |
|
|
text = result.get("text", "") |
|
|
result_text += text + " " |
|
|
await websocket.send_json({"text": text}) |
|
|
except Exception as e: |
|
|
print(f"🔴 Kết nối WebSocket đóng: {e}") |
|
|
finally: |
|
|
print(f"✅ Văn bản cuối cùng: {result_text.strip()}") |
|
|
|
|
|
if __name__ == "__main__": |
|
|
uvicorn.run(app, host="0.0.0.0", port=7860) |