CoolFace
Apppublic

n1wan7ha/ConstructionSafetyMonitor-YOLOv8

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
App README

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

text
.
|-- app.py
|-- Dockerfile
|-- inference.py
|-- README.md
|-- requirements.txt
|-- data/
|   `-- test_image.jpg
|-- models/
|   `-- best.pt
`-- notebooks/
    `-- training_notebook.ipynb

Problem 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:

  1. 1.Standard rule: Every worker detected anywhere in the frame must wear a hard hat (helmet).
  2. 2.High-risk zone rule: A geometric polygon (defined in inference.py as 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. [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, and shoes.
  • 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, and helmet achieved 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, and non-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

  1. 1.Create or open the Hugging Face Space.
  2. 2.Make sure the Space type is Docker.
  3. 3.Push this repository to the Space remote.
  4. 4.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.

  1. 1.Build the image:
bash
docker build -t safety-monitor .
  1. 1.Run the container (choose your OS command):

Mac/Linux:

bash
docker run -v $(pwd):/app safety-monitor

Windows PowerShell:

powershell
docker run -v ${PWD}:/app safety-monitor

Windows Command Prompt:

bat
docker run -v "%cd%":/app safety-monitor

Option 2: Local Python Environment

  1. 1.Ensure Python 3.9+ is installed.
  2. 2.Create and activate a virtual environment.

Windows PowerShell:

powershell
py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1

Mac/Linux:

bash
python3 -m venv .venv
source .venv/bin/activate
  1. 1.Install dependencies:
bash
pip install -r requirements.txt
  1. 1.Ensure your test image is located at data/test_image.jpg (or update the filename in inference.py).
  2. 2.Run inference:
bash
python inference.py

The 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.

  1. 1.Create venv:
powershell
py -3.12 -m venv .venv
  1. 1.Activate venv:
powershell
.\.venv\Scripts\Activate.ps1
  1. 1.Upgrade pip:
powershell
python -m pip install --upgrade pip
  1. 1.Install requirements:
powershell
python -m pip install -r requirements.txt
  1. 1.Run app:
powershell
python .\inference.py
  1. 1.Verify success:
powershell
Write-Output "EXIT:$LASTEXITCODE"
Get-Item .\output_result.jpg | Select-Object Length, LastWriteTime

Expected result:

  • Exit code is 0
  • output_result.jpg exists 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.jpg is present.

Docker

  • Build stalls or times out at exporting to image:
  • Docker storage pressure is likely high. Clean up:
bash
  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).