File size: 1,773 Bytes
23590ba
 
cac01fd
29951cd
fe652f1
23590ba
3b61113
23590ba
3b61113
981b713
 
29951cd
981b713
29951cd
981b713
 
3b61113
6432060
 
fe652f1
 
 
 
 
 
 
 
 
29951cd
6432060
 
ceda7cb
 
6432060
29951cd
 
ceda7cb
6432060
29951cd
fe652f1
 
 
 
29951cd
 
 
 
3b61113
29951cd
cac01fd
4943521
29951cd
ceda7cb
9225a67
cac01fd
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import os
import json
import asyncio
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from vosk import Model, KaldiRecognizer
import uvicorn

# Kiểm tra model
MODEL_PATH = "model/vosk-model"
if not os.path.exists(MODEL_PATH):
    raise Exception("\u274c Model Vosk không tìm thấy!")

print("\u2705 Đang tải model Vosk...")
model = Model(MODEL_PATH)

# Tạo app FastAPI
app = FastAPI()

# Cấu hình CORS để hỗ trợ WebSocket
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Cho phép tất cả nguồn
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.websocket("/ws")  # Đường dẫn WebSocket
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    rec = KaldiRecognizer(model, 16000)
    result_text = ""

    print("\U0001F535 Client đã kết nối WebSocket!")
    
    try:
        while True:
            message = await websocket.receive_bytes()  # Nhận dữ liệu
            if rec.AcceptWaveform(message):
                result = json.loads(rec.Result())
                text = result.get("text", "")
                result_text += text + " "
                await websocket.send_json({"text": text})  # Gửi kết quả
                print(f"\U0001F4E4 Gửi kết quả: {text}")
    except WebSocketDisconnect:
        print("\U0001F534 Client đã ngắt kết nối!")
    except Exception as e:
        print(f"\u274c Lỗi WebSocket: {e}")
        await websocket.close(code=1011, reason="Lỗi xử lý dữ liệu")
    finally:
        print(f"\u2705 Văn bản cuối cùng: {result_text.strip()}")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)