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
- Features
- Tech Stack
- Project Structure
- Quick Start
- Backend Setup
- Frontend Setup
- AI Model Integration
- Model Training Pipeline
- API Reference
- Deployment
- Architecture
- Contributing
- 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
- Drag-and-drop image/video upload
- Live webcam capture and analysis
- Real-time CCTV analysis mode (WebSocket)
- Supports: JPG, PNG, WebP, MP4, AVI
- Annotated image with bounding boxes
- Hygiene metrics (Radar chart, Bar chart)
- Historical trend analysis
- Safety status: Safe / Moderate Risk / Unsafe
- Downloadable PDF inspection reports
- Detected issues with timestamps
- Annotated images embedded in PDF
- AI-generated recommendations
- All analyzed stalls with search/filter
- Aggregate analytics
- JSON/CSV export
- Risk distribution charts
- Live webcam detection (WebSocket)
- GPS/location tagging support
- Vendor risk heatmap (Leaflet.js)
- Multilingual-ready architecture
- Municipality inspection mode
| 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 |
| ReportLab | Report generation | |
| Real-time | WebSocket | Live camera analysis |
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
- Python 3.10 or higher
- Node.js 18 or higher
- MongoDB (optional β app works with in-memory fallback)
- Git
# 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- Frontend: http://localhost:5173
- Backend API: http://localhost:8000
- API Docs (Swagger): http://localhost:8000/api/docs
- API Docs (ReDoc): http://localhost:8000/api/redoc
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.ptcd backend
python -m venv venv
.\venv\Scripts\Activate.ps1
pip install -r requirements.txtNote 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
# Development (auto-reload)
uvicorn main:app --reload --port 8000
# Production
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4The app works without MongoDB using an in-memory store. To enable MongoDB:
- Install MongoDB: https://www.mongodb.com/try/download/community
- Start MongoDB service
- Set
MONGO_URI=mongodb://localhost:27017/safebitein.env
cd frontend
npm installnpm run dev
# Opens at http://localhost:5173
# API calls are proxied to http://localhost:8000npm run build
# Output in frontend/dist/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.
- Download pretrained YOLOv8 weights:
# Auto-downloads on first use
# Or manually download from: https://github.com/ultralytics/assets/releases- For custom-trained weights, set in
backend/.env:
MODEL_PATH=ai_models/weights/your_trained_model.pt- Restart the backend server.
- Train the classifier (see Model Training Pipeline below)
- Set in
backend/.env:
CLASSIFIER_PATH=ai_models/weights/safebite_classifier.ptFollow 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/
cd ai_models
python train_yolo.py --epochs 50 --batch 16 --img 640Options:
| 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
cd ai_models
python train_classifier.py --head-epochs 5 --fine-tune-epochs 25 --batch 32 --model resnet50Options:
| 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
MODEL_PATH=ai_models/weights/safebite_yolo_best.pt
CLASSIFIER_PATH=ai_models/weights/safebite_classifier.pt| Method | Endpoint | Description |
|---|---|---|
POST |
/upload |
Upload image/video for analysis |
GET |
/upload/{id}/status |
Check processing status |
| Method | Endpoint | Description |
|---|---|---|
GET |
/analysis/{id} |
Get full analysis report |
GET |
/analysis/history |
Paginated report history |
DELETE |
/analysis/{id} |
Delete report |
| Method | Endpoint | Description |
|---|---|---|
GET |
/reports/{id}/pdf |
Download PDF report |
GET |
/reports/list |
List all reports |
| Method | Endpoint | Description |
|---|---|---|
GET |
/admin/analytics |
Aggregate analytics |
GET |
/admin/stalls |
All stall records |
GET |
/admin/export |
Export all data as JSON |
| Protocol | Endpoint | Description |
|---|---|---|
WS |
/ws/live |
Real-time camera frame analysis |
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']}")# 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:| 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 |
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βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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) β β
β ββββββββββββββββ ββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| 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 | |
| 0.0 β 3.9 | π¨ Unsafe |
- "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."
- Fork the repository
- Create feature branch:
git checkout -b feature/amazing-feature - Commit changes:
git commit -m 'Add amazing feature' - Push:
git push origin feature/amazing-feature - Open Pull Request
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