websocket.py
source api websocket orchestration
File Path: src/api/websocket.py
Purpose: WebSocket router and task orchestrator for live sign detection sessions.
Overview
This module defines the /live-signs WebSocket endpoint. It uses a producer-consumer pattern to handle real-time video streams. For each connection, it:
- Creates an
asyncio.Queueto buffer decoded frames. - Spawns a
producer_handlertask to receive and decode frames. - Spawns a
consumer_handlertask to process frames and send predictions. - Monitors both tasks and ensures clean resource teardown on disconnect.
Routes
ws_live_signs(websocket)
Route: WS /live-signs
Description: Main entry point for live sign detection.
- Workflow:
- Accepts connection.
- Initializes a shared
asyncio.Queue(maxsize=MAX_SIGN_FRAMES). - Runs
producer_handlerandconsumer_handlerconcurrently usingasyncio.create_task. - Waits for either task to complete (usually via disconnect or error).
- Cleanup: Cancels pending tasks, closes MediaPipe models, and triggers garbage collection.
Relationships
- Depends On:
- live_processing.py - For the actual handler logic and
MAX_SIGN_FRAMES. - utils.py - For logging.
- live_processing.py - For the actual handler logic and
- Used By:
- main.py - Included in the main FastAPI application router.
Implementation Details
The core processing logic formerly in this module has been moved to live_processing.py to improve modularity and testability. This file now focuses strictly on WebSocket lifecycle management.