LowellDouluri/helmet-detection-backend
0
This microservice powers helmet detection with YOLO (rider + head coverage), TrOCR-based number-plate recognition, and a flask-socketio channel that keeps the Flutter live view in sync. The repo already includes the YOLO weight (models/best.pt) and the tracker helper.
Environment
HOST(default0.0.0.0): address the server binds to so the HTTP + WebSocket listeners are reachable from Spaces.PORT(default7860): injected by Hugging Face Spaces;app.pywill read it automatically.YOLO_MODEL_PATH: override the path to the YOLO weights if you need to swap custom.ptfiles.TROCR_MODEL_NAME: transformer checkpoints (defaultmicrosoft/trocr-small-printed); keep this on Spaces to avoid re-downloading during startup.TROCR_LOCAL_ONLY: set to1on Spaces once the model cache is populated to force local loading (0is the default for local development).SOCKET_IO_ASYNC_MODE: the asynchronous engine forflask_socketio;eventletis the only supported value in Spaces’ container environment.DEBUG_SAVE_IMAGES: when0(recommended), debug screenshots are not saved. Turn1locally if you need to inspect intermediate crops.FORCE_CPU: set to1on GPU-constrained Spaces tiers to keep inference on CPU; default is0.TEMP_UPLOAD_DIR: custom path for temporary uploads/merged videos (defaults totemp_uploads/).
Create a .env file (see .env.example) to override any of the defaults above before running locally. On Spaces, configure the same variables using the web UI or huggingface-cli so the container matches the production environment. The Dockerfile already installs opencv, Pillow, and the GPU/CPU compatible dependencies listed in requirements.txt.
Local development
- Clone the repo and create a virtual environment:
python -m venv .venv && .venv/Scripts/activate. - Install pinned dependencies:
pip install -r requirements.txt. - Copy
.env.exampleto.env, adjust values as needed (the defaults already match Spaces expectations), and ensure themodels/directory is available locally. - Run
python app.py. The server preloads YOLO + TrOCR (protected byinit_models()), listens onHOST/PORT, and exposes/health,/process,/process_video,/upload_chunk,/merge_chunks,/process/status/<job_id>, and the/frameWebSocket event. - Use
curl http://localhost:<PORT>/healthto confirm readiness before pointing your Flutter app to the backend.
API behavior
POST /process(async) – Accepts the base64 image payload, schedules inference in the background, and immediately returnsjobId/status. Poll/process/status/<job_id>until the job reachescompletedorfailed. Results are retained for ~1 hour (JOB_TTL_SECONDS) before being evicted.GET /process/status/<job_id>– Returns the latest job status, timestamps, final response, or error if the worker crashed.POST /predict(sync) – Mirrors the previous endpoint behavior; useful only when you can tolerate the ~45-second Hugging Face timeout (e.g., locally or from other clients that can handle the delay). Spaces’s 45-second window is why the async/process//statusworkflow is the default for Flutter.
Hugging Face Spaces deployment
- Push the folder’s contents (including
models/andrequirements.txt) into a Hugging Face Space that uses thedockerSDK; the includedDockerfileis already tuned for Spaces’ port bindings and installs the same system dependencies used locally. - Set the Space’s environment variables (via UI or
huggingface-cli repo push) to match production needs, for exampleTROCR_LOCAL_ONLY=1andSOCKET_IO_ASYNC_MODE=eventlet. The Space will always providePORT, so leave that unset locally if you rely on the defaults. - Monitor the Space’s build logs; once the container starts it executes
python app.py, which binds to0.0.0.0and accepts both HTTP and SocketIO connections on the injected port. - Test
/healthand/processthrough the Space URL; adjustDEBUG_SAVE_IMAGESonly temporarily since those artifacts can be large.
Deployment Steps
- Prepare the repo – keep
app.py,tracker.py,models/,.env.example,requirements.txt,Dockerfile, andREADME.mdcommitted; remove unneeded assets (debug images) until you know you need them. - Create/verify `.env` locally (copy from
.env.example), setDEBUG_SAVE_IMAGES=0,FORCE_CPU=0, and confirmHOST=0.0.0.0. - Push to a Hugging Face Space (create with
huggingface-cli repo create <space-name> --space-type dockeror use the UI) by git adding/pushing the backend directory. - Configure required env vars on the Space (e.g.,
TROCR_LOCAL_ONLY=1,SOCKET_IO_ASYNC_MODE=eventlet, optionally override the model paths). - Validate the deployment by curling the Space URL’s
/healthendpoint and triggering/process; use the Flutter app’s WebSocket to ensure live updates arrive.
