n1wan7ha/ConstructionSafetyMonitor-YOLOv8
Construction Safety Monitor - AI/ML Inference System
Author: Niwantha Sithumal
This repository contains the code, data logic, and model weights for an automated construction site safety monitor.
The system uses a custom-trained YOLOv8n object detection model combined with geometric inference logic to enforce zone-based safety compliance in real time.
Project Structure
.
|-- app.py
|-- Dockerfile
|-- inference.py
|-- README.md
|-- requirements.txt
|-- data/
| `-- test_image.jpg
|-- models/
| `-- best.pt
`-- notebooks/
`-- training_notebook.ipynbProblem Framing and Safety Rules
While baseline models simply detect equipment, true safety monitoring requires spatial context. This system enforces safety through zone-based high-risk enforcement:
- Standard rule: Every worker detected anywhere in the frame must wear a hard hat (
helmet). - High-risk zone rule: A geometric polygon (defined in
inference.pyas the lower half of the frame) represents an active work zone. If a worker's coordinates fall within this high-risk zone, they must be wearing both a hard hat (helmet) and a high-visibility vest (vest).
Violation flagging: The system generates a human-readable alert (for example, Worker 1 [Zone: High-Risk]: VIOLATION - Missing Vest) and annotates the output image.
Data Collection and Curation
To ensure robust detection, a completely custom dataset was curated.
- Source images: 91 highly diverse images gathered to reflect various lighting conditions, indoor and outdoor sites, and both safe and unsafe worker behaviors.
- Annotation: 1,400 precise bounding box annotations were drawn manually.
- Taxonomy (7 classes): To allow advanced rule creation and strict negative enforcement, 7 classes were defined:
person,helmet,vest,bare-arms,gloves,non-helmet, andshoes. - Augmentation and splitting: The dataset was expanded to 495 images using horizontal flipping, brightness adjustments (-21% to +21%), and slight blurring (up to 0.8 px) to simulate poor camera quality. The data split was 87% train, 8% validation, and 4% test.
Model Selection and Training
- Architecture: YOLOv8 Nano (
yolov8n.pt) was selected. In real-world construction scenarios, models often run on edge devices (for example, CCTV units with limited compute). Nano provides a practical speed and accuracy balance. - Environment: The model was trained in Google Colab using a T4 GPU.
- Hyperparameters: Trained for 50 epochs with image size 640 x 640. Full training curves, loss plots, and environment setup are available in
notebooks/training_notebook.ipynb.
Honest Evaluation and Results
- Strengths: The model performs well on core classes required by the safety logic.
person,vest, andhelmetachieved solid mAP50 scores, allowing reliable PPE-to-worker mapping. It also avoids false positives on regular clothing. - Weaknesses and failure cases: The model struggles with smaller, high-variance classes such as
gloves,bare-arms, andnon-helmet(mAP50 roughly 0.10 to 0.21). - Future improvements: For better small-item detection (especially gloves), next steps include SAHI-based slicing during training, increasing epochs to 150+, and expanding close-up hand imagery.
Hugging Face Space
This repository is configured to run as a Hugging Face Docker Space.
The Space entry point is app.py, which provides an image upload UI for running the safety model in the browser.
To deploy updates to the Space, push the repo contents to your Hugging Face Space remote. The Space will build from Dockerfile and install dependencies from requirements.txt.
Setup and Execution
Hugging Face Spaces Deployment
- Create or open the Hugging Face Space.
- Make sure the Space type is Docker.
- Push this repository to the Space remote.
- Wait for the build to finish, then open the app.
The web app lets you upload a site image and returns the annotated result plus a compliance report.
Option 1: Docker Deployment
To ensure reproducibility and avoid local dependency conflicts across operating systems, use the provided Dockerfile.
- Build the image:
docker build -t safety-monitor .- Run the container (choose your OS command):
Mac/Linux:
docker run -v $(pwd):/app safety-monitorWindows PowerShell:
docker run -v ${PWD}:/app safety-monitorWindows Command Prompt:
docker run -v "%cd%":/app safety-monitorOption 2: Local Python Environment
- Ensure Python 3.9+ is installed.
- Create and activate a virtual environment.
Windows PowerShell:
py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1Mac/Linux:
python3 -m venv .venv
source .venv/bin/activate- Install dependencies:
pip install -r requirements.txt- Ensure your test image is located at
data/test_image.jpg(or update the filename ininference.py). - Run inference:
python inference.pyThe script prints a compliance report in the terminal and saves the annotated result as output_result.jpg.
A to Z Install and Verification (Windows PowerShell)
These are the exact commands used to validate a clean setup in this repository.
- Create venv:
py -3.12 -m venv .venv- Activate venv:
.\.venv\Scripts\Activate.ps1- Upgrade pip:
python -m pip install --upgrade pip- Install requirements:
python -m pip install -r requirements.txt- Run app:
python .\inference.py- Verify success:
Write-Output "EXIT:$LASTEXITCODE"
Get-Item .\output_result.jpg | Select-Object Length, LastWriteTimeExpected result:
- Exit code is
0 output_result.jpgexists and has a recent timestamp
Dependency Note
requirements.txt includes torch<2.6 to keep model loading behavior compatible with ultralytics==8.1.0 and the provided models/best.pt checkpoint.
Troubleshooting
Local Python
- Error loading model with
Weights only load failed: - Confirm dependencies were installed from
requirements.txt. - Confirm you are inside the project virtual environment before running
python inference.py. Error: Could not read image.:- Ensure the image path passed to
run_safety_inference()exists. - If using defaults, ensure
data/test_image.jpgis present.
Docker
- Build stalls or times out at
exporting to image: - Docker storage pressure is likely high. Clean up:
docker builder prune -af
docker image prune -af
docker system prune -af --volumes- Restart Docker Desktop.
- Retry build:
docker build -t safety-monitor . - If builds remain slow, consider running Docker on a local non-OneDrive path (OneDrive sync overhead can affect layer export performance).
