Skip to content

Latest commit

Β 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ SafeBite AI – Street Food Hygiene Rating System

SafeBite AI FastAPI React YOLOv8 MongoDB TailwindCSS

An AI-powered platform that analyzes street food stall images/videos to generate automated hygiene and food safety ratings.

Suitable for: Final Year Engineering Projects β€’ Hackathons β€’ IEEE Research Papers β€’ Startup MVPs


πŸ“‹ Table of Contents

  1. Features
  2. Tech Stack
  3. Project Structure
  4. Quick Start
  5. Backend Setup
  6. Frontend Setup
  7. AI Model Integration
  8. Model Training Pipeline
  9. API Reference
  10. Deployment
  11. Architecture
  12. Contributing

✨ Features

πŸ”¬ AI Hygiene Analysis

  • Object Detection (YOLOv8): Detects waste, gloves, masks, food items, cooking utensils, garbage bins, oil containers, smoke
  • Cleanliness Classification (CNN/ResNet50): Classifies stalls as Clean / Moderate / Unsafe
  • Hygiene Scoring Engine: 5 sub-scores + overall hygiene score (out of 10)
  • AI Recommendations: Natural language hygiene improvement suggestions

πŸ“€ Upload & Processing

  • Drag-and-drop image/video upload
  • Live webcam capture and analysis
  • Real-time CCTV analysis mode (WebSocket)
  • Supports: JPG, PNG, WebP, MP4, AVI

πŸ“Š Analytics Dashboard

  • Annotated image with bounding boxes
  • Hygiene metrics (Radar chart, Bar chart)
  • Historical trend analysis
  • Safety status: Safe / Moderate Risk / Unsafe

πŸ“„ Report Generation

  • Downloadable PDF inspection reports
  • Detected issues with timestamps
  • Annotated images embedded in PDF
  • AI-generated recommendations

πŸ–₯️ Admin Panel

  • All analyzed stalls with search/filter
  • Aggregate analytics
  • JSON/CSV export
  • Risk distribution charts

πŸš€ Advanced Features

  • Live webcam detection (WebSocket)
  • GPS/location tagging support
  • Vendor risk heatmap (Leaflet.js)
  • Multilingual-ready architecture
  • Municipality inspection mode

πŸ› οΈ Tech Stack

Layer Technology Purpose
Frontend React 18 + Vite SPA framework
Styling TailwindCSS 3.4 UI styling
Animations Framer Motion Page/component animations
Charts Recharts Data visualization
State Zustand Global state management
Backend FastAPI (Python 3.10+) REST API server
Database MongoDB + Motor Async document storage
Computer Vision OpenCV Image preprocessing & annotation
Object Detection YOLOv8 (Ultralytics) Object detection
Classification PyTorch + ResNet50 Cleanliness classification
PDF ReportLab Report generation
Real-time WebSocket Live camera analysis

πŸ“ Project Structure

safebite-ai/
β”œβ”€β”€ πŸ“‚ backend/                    # FastAPI backend
β”‚   β”œβ”€β”€ main.py                    # Application entry point
β”‚   β”œβ”€β”€ config.py                  # Settings & env config
β”‚   β”œβ”€β”€ requirements.txt           # Python dependencies
β”‚   β”œβ”€β”€ .env                       # Active environment (git-ignored)
β”‚   β”œβ”€β”€ .env.example               # Environment template
β”‚   β”œβ”€β”€ πŸ“‚ api/
β”‚   β”‚   └── πŸ“‚ routes/
β”‚   β”‚       β”œβ”€β”€ upload.py          # File upload endpoints
β”‚   β”‚       β”œβ”€β”€ analysis.py        # Analysis report endpoints
β”‚   β”‚       β”œβ”€β”€ reports.py         # PDF report endpoints
β”‚   β”‚       β”œβ”€β”€ admin.py           # Admin panel endpoints
β”‚   β”‚       └── realtime.py        # WebSocket live analysis
β”‚   β”œβ”€β”€ πŸ“‚ db/
β”‚   β”‚   β”œβ”€β”€ database.py            # MongoDB + in-memory fallback
β”‚   β”‚   └── models.py              # Pydantic data models
β”‚   β”œβ”€β”€ πŸ“‚ services/
β”‚   β”‚   β”œβ”€β”€ ai_pipeline.py         # Main AI orchestrator
β”‚   β”‚   β”œβ”€β”€ yolo_detector.py       # YOLOv8 object detection
β”‚   β”‚   β”œβ”€β”€ cleanliness_classifier.py  # CNN classification
β”‚   β”‚   β”œβ”€β”€ scoring_engine.py      # Hygiene scoring
β”‚   β”‚   β”œβ”€β”€ recommendation_engine.py   # AI recommendations
β”‚   β”‚   └── pdf_generator.py       # ReportLab PDF generator
β”‚   └── πŸ“‚ utils/
β”‚       └── image_processor.py     # OpenCV utilities
β”‚
β”œβ”€β”€ πŸ“‚ frontend/                   # React + Vite frontend
β”‚   β”œβ”€β”€ index.html                 # HTML entry point
β”‚   β”œβ”€β”€ package.json               # Node dependencies
β”‚   β”œβ”€β”€ vite.config.js             # Vite configuration
β”‚   β”œβ”€β”€ tailwind.config.js         # TailwindCSS config
β”‚   β”œβ”€β”€ postcss.config.js          # PostCSS config
β”‚   └── πŸ“‚ src/
β”‚       β”œβ”€β”€ main.jsx               # React root
β”‚       β”œβ”€β”€ App.jsx                # Router + layout
β”‚       β”œβ”€β”€ index.css              # Global styles + design system
β”‚       β”œβ”€β”€ πŸ“‚ api/
β”‚       β”‚   └── client.js          # Axios API client
β”‚       β”œβ”€β”€ πŸ“‚ store/
β”‚       β”‚   └── useStore.js        # Zustand state store
β”‚       β”œβ”€β”€ πŸ“‚ components/
β”‚       β”‚   β”œβ”€β”€ Navbar.jsx
β”‚       β”‚   β”œβ”€β”€ UploadZone.jsx
β”‚       β”‚   β”œβ”€β”€ AnalysisProgress.jsx
β”‚       β”‚   β”œβ”€β”€ HygieneScoreCard.jsx
β”‚       β”‚   β”œβ”€β”€ DetectionOverlay.jsx
β”‚       β”‚   β”œβ”€β”€ MetricsGrid.jsx
β”‚       β”‚   β”œβ”€β”€ RecommendationCard.jsx
β”‚       β”‚   β”œβ”€β”€ Charts.jsx
β”‚       β”‚   β”œβ”€β”€ ReportDownload.jsx
β”‚       β”‚   β”œβ”€β”€ AdminTable.jsx
β”‚       β”‚   β”œβ”€β”€ LiveCamera.jsx
β”‚       β”‚   └── ThemeToggle.jsx
β”‚       └── πŸ“‚ pages/
β”‚           β”œβ”€β”€ Home.jsx           # Landing page
β”‚           β”œβ”€β”€ Upload.jsx         # Upload interface
β”‚           β”œβ”€β”€ Analysis.jsx       # Processing status
β”‚           β”œβ”€β”€ Dashboard.jsx      # Results dashboard
β”‚           β”œβ”€β”€ Admin.jsx          # Admin panel
β”‚           └── Reports.jsx        # Report history
β”‚
β”œβ”€β”€ πŸ“‚ ai_models/                  # AI model training
β”‚   β”œβ”€β”€ train_yolo.py              # YOLOv8 training script
β”‚   β”œβ”€β”€ train_classifier.py        # CNN training script
β”‚   β”œβ”€β”€ dataset_structure.md       # Dataset documentation
β”‚   └── πŸ“‚ data/                   # Training datasets (add your own)
β”‚       β”œβ”€β”€ yolo_dataset/
β”‚       └── classifier_dataset/
β”‚
β”œβ”€β”€ πŸ“‚ sample_data/                # Sample dataset structure
β”‚   β”œβ”€β”€ README.md
β”‚   β”œβ”€β”€ images/                    # Add sample images here
β”‚   └── labels/                    # Sample YOLO labels
β”‚
└── README.md                      # This file

⚑ Quick Start

Prerequisites

  • Python 3.10 or higher
  • Node.js 18 or higher
  • MongoDB (optional β€” app works with in-memory fallback)
  • Git

1-Minute Setup

# Clone / navigate to the project
cd c:\Users\Varun\Documents\RVCE\food

# Terminal 1: Start Backend
cd backend
python -m venv venv
.\venv\Scripts\Activate.ps1
pip install -r requirements.txt
uvicorn main:app --reload --port 8000

# Terminal 2: Start Frontend
cd frontend
npm install
npm run dev

🐍 Backend Setup

Environment Configuration

Copy .env.example to .env and configure:

# MongoDB (optional - falls back to in-memory storage)
MONGO_URI=mongodb://localhost:27017/safebite

# Security
SECRET_KEY=your-super-secret-key-change-in-production

# CORS
ALLOWED_ORIGINS=http://localhost:5173

# File storage
UPLOAD_DIR=uploads

# AI Model paths (optional - uses mock AI if not found)
MODEL_PATH=ai_models/weights/yolov8n.pt
CLASSIFIER_PATH=ai_models/weights/safebite_classifier.pt

Install Dependencies

cd backend
python -m venv venv
.\venv\Scripts\Activate.ps1
pip install -r requirements.txt

Note on torch/torchvision: If you have a CUDA GPU, install the CUDA version:

pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118

Run the Server

# Development (auto-reload)
uvicorn main:app --reload --port 8000

# Production
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

MongoDB Setup (Optional)

The app works without MongoDB using an in-memory store. To enable MongoDB:

  1. Install MongoDB: https://www.mongodb.com/try/download/community
  2. Start MongoDB service
  3. Set MONGO_URI=mongodb://localhost:27017/safebite in .env

βš›οΈ Frontend Setup

Install Dependencies

cd frontend
npm install

Development Server

npm run dev
# Opens at http://localhost:5173
# API calls are proxied to http://localhost:8000

Production Build

npm run build
# Output in frontend/dist/

πŸ€– AI Model Integration

Current Status: Smart Mock Mode

By default, the application runs in Smart Mock Mode β€” the AI pipeline uses OpenCV-based analysis to generate realistic hygiene detections and scores without requiring trained model weights. This makes the app fully demo-ready out of the box.

Enabling Real YOLOv8 Model

  1. Download pretrained YOLOv8 weights:
# Auto-downloads on first use
# Or manually download from: https://github.com/ultralytics/assets/releases
  1. For custom-trained weights, set in backend/.env:
MODEL_PATH=ai_models/weights/your_trained_model.pt
  1. Restart the backend server.

Enabling Real CNN Classifier

  1. Train the classifier (see Model Training Pipeline below)
  2. Set in backend/.env:
CLASSIFIER_PATH=ai_models/weights/safebite_classifier.pt

πŸ‹οΈ Model Training Pipeline

1. Prepare Dataset

Follow the guide in ai_models/dataset_structure.md.

For YOLOv8:

ai_models/data/yolo_dataset/
β”œβ”€β”€ images/train/   # ~2000 images
β”œβ”€β”€ images/val/     # ~500 images
└── labels/train/   # YOLO format .txt files
    labels/val/

For CNN Classifier:

ai_models/data/classifier_dataset/
β”œβ”€β”€ train/clean/       # ~1000 images
β”œβ”€β”€ train/moderate/    # ~1000 images
β”œβ”€β”€ train/unsafe/      # ~1000 images
└── val/clean/, moderate/, unsafe/

2. Train YOLOv8 Object Detector

cd ai_models
python train_yolo.py --epochs 50 --batch 16 --img 640

Options:

Flag Default Description
--epochs 50 Training epochs
--batch 16 Batch size
--img 640 Image size
--model yolov8n.pt Base model (n/s/m/l/x)
--device auto cuda/cpu

Best weights saved to: ai_models/weights/safebite_yolo_best.pt

3. Train CNN Cleanliness Classifier

cd ai_models
python train_classifier.py --head-epochs 5 --fine-tune-epochs 25 --batch 32 --model resnet50

Options:

Flag Default Description
--head-epochs 5 Warm-up epochs for classifier head
--fine-tune-epochs 25 Fine-tuning epochs after unfreezing the backbone
--batch 32 Batch size
--lr 0.0001 Learning rate
--fine-tune-lr 0.00001 Learning rate for full-model fine-tuning
--patience 5 Early stopping patience on validation macro-F1
--min-delta 0.001 Minimum F1 improvement needed to reset patience
--label-smoothing 0.05 Label smoothing for the loss
--model resnet50 Architecture (resnet50/efficientnet_b0/mobilenet_v3)
--freeze False Freeze backbone layers
--no-augment False Disable data augmentation

Trained model saved to: ai_models/weights/safebite_classifier.pt

4. Update Backend Config

MODEL_PATH=ai_models/weights/safebite_yolo_best.pt
CLASSIFIER_PATH=ai_models/weights/safebite_classifier.pt

πŸ“‘ API Reference

Base URL: http://localhost:8000/api

Upload

Method Endpoint Description
POST /upload Upload image/video for analysis
GET /upload/{id}/status Check processing status

Analysis

Method Endpoint Description
GET /analysis/{id} Get full analysis report
GET /analysis/history Paginated report history
DELETE /analysis/{id} Delete report

Reports

Method Endpoint Description
GET /reports/{id}/pdf Download PDF report
GET /reports/list List all reports

Admin

Method Endpoint Description
GET /admin/analytics Aggregate analytics
GET /admin/stalls All stall records
GET /admin/export Export all data as JSON

WebSocket

Protocol Endpoint Description
WS /ws/live Real-time camera frame analysis

Example: Upload and Get Report

import requests

# Upload image
with open("stall.jpg", "rb") as f:
    response = requests.post(
        "http://localhost:8000/api/upload",
        files={"file": f}
    )
    report_id = response.json()["report_id"]

# Poll status
import time
while True:
    status = requests.get(f"http://localhost:8000/api/upload/{report_id}/status").json()
    if status["status"] == "completed":
        break
    time.sleep(1)

# Get full report
report = requests.get(f"http://localhost:8000/api/analysis/{report_id}").json()
print(f"Overall Score: {report['scores']['overall']}/10")
print(f"Safety Status: {report['safety_status']}")

🚒 Deployment

Docker (Recommended)

# backend/Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# docker-compose.yml
version: "3.9"
services:
  backend:
    build: ./backend
    ports: ["8000:8000"]
    environment:
      - MONGO_URI=mongodb://mongo:27017/safebite
    depends_on: [mongo]

  frontend:
    build: ./frontend
    ports: ["80:80"]

  mongo:
    image: mongo:7
    volumes: ["mongo_data:/data/db"]

volumes:
  mongo_data:

Cloud Deployment

Platform Service Notes
Railway Backend + MongoDB 1-click deploy
Render Backend API Free tier available
Vercel Frontend Optimal for React
Netlify Frontend Free tier
AWS EC2 Full stack For production
Google Cloud Run Containerized Serverless

Environment Variables (Production)

MONGO_URI=mongodb+srv://user:pass@cluster.mongodb.net/safebite
SECRET_KEY=<generate-with-openssl-rand-hex-32>
ALLOWED_ORIGINS=https://your-frontend-domain.com

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     Frontend (React)                     β”‚
β”‚  Upload β†’ Analysis Progress β†’ Dashboard β†’ Admin Panel    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                        β”‚ REST API / WebSocket
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Backend (FastAPI)                      β”‚
β”‚                                                          β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ Routers β”‚  β”‚         AI Pipeline                   β”‚  β”‚
β”‚  β”‚ upload  β”‚β†’β”‚  1. OpenCV Preprocessing               β”‚  β”‚
β”‚  β”‚ analysisβ”‚  β”‚  2. YOLOv8 Object Detection           β”‚  β”‚
β”‚  β”‚ reports β”‚  β”‚  3. CNN Cleanliness Classification    β”‚  β”‚
β”‚  β”‚ admin   β”‚  β”‚  4. Scoring Engine (5 categories)     β”‚  β”‚
β”‚  β”‚ ws/live β”‚  β”‚  5. Recommendation Engine             β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚  6. Image Annotation                  β”‚  β”‚
β”‚               β”‚  7. PDF Generation (ReportLab)        β”‚  β”‚
β”‚               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                                          β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚   MongoDB    β”‚         β”‚    File Storage         β”‚    β”‚
β”‚  β”‚ (or in-mem)  β”‚         β”‚  uploads/ (images, PDF) β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“Š Hygiene Scoring

Category Weight Factors
Stall Cleanliness 25% Dirty surfaces, overall image quality
Worker Hygiene 25% Gloves, masks, bare-hand handling
Waste Management 20% Waste proximity, garbage bin overflow
Oil Quality 15% Oil container detection, dark coloration
Cooking Safety 15% Smoke levels, utensil cleanliness
Score Range Safety Status
7.0 – 10.0 βœ… Safe
4.0 – 6.9 ⚠️ Moderate Risk
0.0 – 3.9 🚨 Unsafe

πŸ”¬ AI Recommendations (Examples)

  • "Cooking area contains exposed waste near food preparation zone. Immediate removal required."
  • "Worker detected handling food without protective gloves. Hygiene violation observed."
  • "Cooking oil appears overused due to dark coloration. Oil replacement recommended."
  • "Excessive smoke detected near cooking area. Adequate ventilation improvement needed."
  • "Cooking surface shows signs of contamination. Immediate sanitization required."

🀝 Contributing

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push: git push origin feature/amazing-feature
  5. Open Pull Request

πŸ“„ License

MIT License β€” Free to use for academic, research, and commercial purposes.


Built with ❀️ for a safer street food ecosystem

SafeBite AI β€” Protecting Public Health through Artificial Intelligence

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages