Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
-
import asyncio
|
| 4 |
-
import websockets
|
| 5 |
from fastapi import FastAPI, WebSocket
|
| 6 |
from vosk import Model, KaldiRecognizer
|
|
|
|
| 7 |
|
|
|
|
| 8 |
MODEL_PATH = "model/vosk-model"
|
| 9 |
if not os.path.exists(MODEL_PATH):
|
| 10 |
raise Exception("❌ Model Vosk không tìm thấy!")
|
|
@@ -12,6 +12,7 @@ if not os.path.exists(MODEL_PATH):
|
|
| 12 |
print("✅ Đang tải model Vosk...")
|
| 13 |
model = Model(MODEL_PATH)
|
| 14 |
|
|
|
|
| 15 |
app = FastAPI()
|
| 16 |
|
| 17 |
@app.websocket("/ws")
|
|
@@ -22,17 +23,20 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 22 |
|
| 23 |
try:
|
| 24 |
while True:
|
| 25 |
-
message = await websocket.
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
finally:
|
| 34 |
print(f"✅ Văn bản cuối cùng: {result_text.strip()}")
|
| 35 |
|
| 36 |
if __name__ == "__main__":
|
| 37 |
-
import uvicorn
|
| 38 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
|
|
|
|
|
|
| 3 |
from fastapi import FastAPI, WebSocket
|
| 4 |
from vosk import Model, KaldiRecognizer
|
| 5 |
+
import uvicorn
|
| 6 |
|
| 7 |
+
# Kiểm tra model
|
| 8 |
MODEL_PATH = "model/vosk-model"
|
| 9 |
if not os.path.exists(MODEL_PATH):
|
| 10 |
raise Exception("❌ Model Vosk không tìm thấy!")
|
|
|
|
| 12 |
print("✅ Đang tải model Vosk...")
|
| 13 |
model = Model(MODEL_PATH)
|
| 14 |
|
| 15 |
+
# Tạo app FastAPI
|
| 16 |
app = FastAPI()
|
| 17 |
|
| 18 |
@app.websocket("/ws")
|
|
|
|
| 23 |
|
| 24 |
try:
|
| 25 |
while True:
|
| 26 |
+
message = await websocket.receive()
|
| 27 |
+
|
| 28 |
+
if isinstance(message, bytes): # Kiểm tra nếu dữ liệu là bytes
|
| 29 |
+
if rec.AcceptWaveform(message):
|
| 30 |
+
result = json.loads(rec.Result())
|
| 31 |
+
text = result.get("text", "")
|
| 32 |
+
result_text += text + " "
|
| 33 |
+
await websocket.send_json({"text": text})
|
| 34 |
+
else:
|
| 35 |
+
await websocket.send_json({"error": "Dữ liệu không hợp lệ"})
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"🔴 Kết nối WebSocket đóng: {e}")
|
| 38 |
finally:
|
| 39 |
print(f"✅ Văn bản cuối cùng: {result_text.strip()}")
|
| 40 |
|
| 41 |
if __name__ == "__main__":
|
|
|
|
| 42 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|