Luigi commited on
Commit
516e9a4
·
1 Parent(s): af5741d

improve exception handling

Browse files
Files changed (1) hide show
  1. app/main.py +15 -4
app/main.py CHANGED
@@ -3,6 +3,7 @@ from fastapi.staticfiles import StaticFiles
3
  from fastapi.responses import HTMLResponse
4
  from app.asr_worker import create_recognizer, stream_audio, finalize_stream
5
  import json
 
6
 
7
  app = FastAPI()
8
 
@@ -37,7 +38,10 @@ async def websocket_endpoint(websocket: WebSocket):
37
  if stream and recognizer:
38
  print(f"[INFO main] Client disconnected (code={data.get('code')}). Flushing final transcript...")
39
  final = finalize_stream(stream, recognizer)
40
- await websocket.send_json({"final": final})
 
 
 
41
  break
42
  continue
43
 
@@ -95,6 +99,13 @@ async def websocket_endpoint(websocket: WebSocket):
95
  print(f"[ERROR main] Unexpected exception: {e}")
96
  if stream and recognizer:
97
  final = finalize_stream(stream, recognizer)
98
- await websocket.send_json({"final": final})
99
- await websocket.close()
100
- print("[INFO main] WebSocket closed, cleanup complete.")
 
 
 
 
 
 
 
 
3
  from fastapi.responses import HTMLResponse
4
  from app.asr_worker import create_recognizer, stream_audio, finalize_stream
5
  import json
6
+ from starlette.websockets import WebSocketDisconnect
7
 
8
  app = FastAPI()
9
 
 
38
  if stream and recognizer:
39
  print(f"[INFO main] Client disconnected (code={data.get('code')}). Flushing final transcript...")
40
  final = finalize_stream(stream, recognizer)
41
+ try:
42
+ await websocket.send_json({"final": final})
43
+ except (WebSocketDisconnect, RuntimeError):
44
+ pass
45
  break
46
  continue
47
 
 
99
  print(f"[ERROR main] Unexpected exception: {e}")
100
  if stream and recognizer:
101
  final = finalize_stream(stream, recognizer)
102
+ try:
103
+ await websocket.send_json({"final": final})
104
+ except (WebSocketDisconnect, RuntimeError):
105
+ pass
106
+ # Ensure connection is closed
107
+ try:
108
+ await websocket.close()
109
+ except:
110
+ pass
111
+ print("[INFO main] WebSocket closed, cleanup complete.")