File size: 1,082 Bytes
23590ba ceda7cb 6432060 23590ba 981b713 6432060 981b713 6432060 981b713 6432060 ceda7cb 6432060 ceda7cb 6432060 4943521 ceda7cb 9225a67 6432060 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import os
import json
import asyncio
import websockets
from fastapi import FastAPI, WebSocket
from vosk import Model, KaldiRecognizer
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.websocket("/ws")
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:
print("🔴 Kết nối WebSocket đóng")
finally:
print(f"✅ Văn bản cuối cùng: {result_text.strip()}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
|