| |
| from fastapi import FastAPI, WebSocket, WebSocketDisconnect |
| from inference import VideoProcessor |
| import threading |
| import queue |
| import asyncio |
| import json |
|
|
| app = FastAPI() |
|
|
| @app.websocket("/ws/inference") |
| async def websocket_endpoint(websocket: WebSocket): |
| await websocket.accept() |
| processor = VideoProcessor() |
| result_queue = queue.Queue() |
| |
| try: |
| |
| data = await websocket.receive_text() |
| config = json.loads(data) |
| rtsp_url = config.get("url") |
| |
| print(f"Received request for: {rtsp_url}") |
| |
| |
| |
| process_thread = threading.Thread( |
| target=processor.start_processing, |
| args=(rtsp_url, result_queue) |
| ) |
| process_thread.start() |
|
|
| |
| while True: |
| |
| try: |
| |
| result = result_queue.get_nowait() |
| await websocket.send_json(result) |
| except queue.Empty: |
| |
| await asyncio.sleep(0.1) |
| |
| |
| if not process_thread.is_alive(): |
| await websocket.send_json({"status": "Processing finished"}) |
| break |
|
|
| except WebSocketDisconnect: |
| print("Client disconnected") |
| processor.running = False |
| process_thread.join() |
| except Exception as e: |
| print(f"Error: {e}") |
| processor.running = False |