Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
|
|
|
| 3 |
from fastapi import FastAPI, WebSocket
|
| 4 |
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
from vosk import Model, KaldiRecognizer
|
|
@@ -25,24 +26,30 @@ app.add_middleware(
|
|
| 25 |
allow_headers=["*"],
|
| 26 |
)
|
| 27 |
|
| 28 |
-
@app.websocket("/") #
|
| 29 |
async def websocket_endpoint(websocket: WebSocket):
|
| 30 |
await websocket.accept()
|
| 31 |
rec = KaldiRecognizer(model, 16000)
|
| 32 |
result_text = ""
|
| 33 |
|
|
|
|
|
|
|
| 34 |
try:
|
| 35 |
while True:
|
| 36 |
message = await websocket.receive_bytes() # Nhận bytes từ WebSocket
|
|
|
|
|
|
|
| 37 |
if rec.AcceptWaveform(message):
|
| 38 |
result = json.loads(rec.Result())
|
| 39 |
text = result.get("text", "")
|
| 40 |
result_text += text + " "
|
| 41 |
-
await websocket.send_json({"text": text})
|
|
|
|
| 42 |
except Exception as e:
|
| 43 |
-
print(f"🔴
|
|
|
|
| 44 |
finally:
|
| 45 |
print(f"✅ Văn bản cuối cùng: {result_text.strip()}")
|
| 46 |
|
| 47 |
if __name__ == "__main__":
|
| 48 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
+
import asyncio
|
| 4 |
from fastapi import FastAPI, WebSocket
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
from vosk import Model, KaldiRecognizer
|
|
|
|
| 26 |
allow_headers=["*"],
|
| 27 |
)
|
| 28 |
|
| 29 |
+
@app.websocket("/ws") # Phải là "/ws" (không phải "/")
|
| 30 |
async def websocket_endpoint(websocket: WebSocket):
|
| 31 |
await websocket.accept()
|
| 32 |
rec = KaldiRecognizer(model, 16000)
|
| 33 |
result_text = ""
|
| 34 |
|
| 35 |
+
print("🔵 Client đã kết nối WebSocket!")
|
| 36 |
+
|
| 37 |
try:
|
| 38 |
while True:
|
| 39 |
message = await websocket.receive_bytes() # Nhận bytes từ WebSocket
|
| 40 |
+
print(f"📩 Nhận dữ liệu ({len(message)} bytes)")
|
| 41 |
+
|
| 42 |
if rec.AcceptWaveform(message):
|
| 43 |
result = json.loads(rec.Result())
|
| 44 |
text = result.get("text", "")
|
| 45 |
result_text += text + " "
|
| 46 |
+
await websocket.send_json({"text": text}) # Gửi kết quả về client
|
| 47 |
+
print(f"📤 Gửi kết quả: {text}")
|
| 48 |
except Exception as e:
|
| 49 |
+
print(f"🔴 Lỗi WebSocket: {e}")
|
| 50 |
+
await websocket.close(code=1011, reason="Lỗi xử lý dữ liệu")
|
| 51 |
finally:
|
| 52 |
print(f"✅ Văn bản cuối cùng: {result_text.strip()}")
|
| 53 |
|
| 54 |
if __name__ == "__main__":
|
| 55 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|