tudeplom commited on
Commit
fe652f1
·
verified ·
1 Parent(s): e6d9ada

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -12
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
  import json
3
  from fastapi import FastAPI, WebSocket
 
4
  from vosk import Model, KaldiRecognizer
5
  import uvicorn
6
 
@@ -15,7 +16,16 @@ model = Model(MODEL_PATH)
15
  # Tạo app FastAPI
16
  app = FastAPI()
17
 
18
- @app.websocket("/ws")
 
 
 
 
 
 
 
 
 
19
  async def websocket_endpoint(websocket: WebSocket):
20
  await websocket.accept()
21
  rec = KaldiRecognizer(model, 16000)
@@ -23,20 +33,16 @@ async def websocket_endpoint(websocket: WebSocket):
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)
 
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
6
  import uvicorn
7
 
 
16
  # Tạo app FastAPI
17
  app = FastAPI()
18
 
19
+ # Cấu hình CORS để hỗ trợ WebSocket
20
+ app.add_middleware(
21
+ CORSMiddleware,
22
+ allow_origins=["*"], # Cho phép tất cả nguồn
23
+ allow_credentials=True,
24
+ allow_methods=["*"],
25
+ allow_headers=["*"],
26
+ )
27
+
28
+ @app.websocket("/") # WebSocket endpoint phải là "/" trên Hugging Face
29
  async def websocket_endpoint(websocket: WebSocket):
30
  await websocket.accept()
31
  rec = KaldiRecognizer(model, 16000)
 
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"🔴 Kết nối WebSocket đóng: {e}")
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)