Skip to content

feat: #35 add FastAPI backend for ML models + add unit tests for streamlit app - #75

Open
Senthil455 wants to merge 2 commits into
safe-cam:mainfrom
Senthil455:main
Open

feat: #35 add FastAPI backend for ML models + add unit tests for streamlit app#75
Senthil455 wants to merge 2 commits into
safe-cam:mainfrom
Senthil455:main

Conversation

@Senthil455

@Senthil455 Senthil455 commented Jun 16, 2026

Copy link
Copy Markdown

Summary

This PR addresses two issues:

  1. 💡 [FEATURE REQUEST] - create the Fast-API for the models #35 — Adds a standalone FastAPI backend for all ML detection models (callable from JavaScript)
  2. 🧪 [TEST] - add the unit test cases for the streamlit app #65 — Adds comprehensive unit tests for the Streamlit web app

FastAPI Backend (fixes #35)

A standalone FastAPI application that exposes all CCTV detection models via REST endpoints, keeping the API code fully separate from the web UI.

Architecture

api/main.py — FastAPI app (CORS, lifespan, error handling)
api/config.py — Settings (model paths, MongoDB URI, CORS origins)
api/schemas.py — Pydantic request/response models
api/models.py — Lazy model loader with graceful fallback
api/requirements.txt — Dependencies
api/routers/health.py — GET /health
api/routers/detection.py — POST /api/detect/* (image, video, gunshot)
api/routers/auth.py — POST /api/auth/* (login, register)
api/services/detector.py — Core detection pipeline
api/tests/ — 15 fully-mocked tests

API Endpoints

GET / — Service info
GET /health — Health check (model + DB status)
POST /api/detect/ — Upload image + run detection tasks
POST /api/detect/batch — Upload video + process frames
POST /api/detect/gunshot — Upload audio + detect gunshot
POST /api/auth/login — User authentication
POST /api/auth/register — User registration

Detection capabilities

Vehicle Detection (YOLOv8m), License Plate Detection, Fire/Smoke Detection, Accident Detection, Face Detection (Haar cascade), Gunshot Detection (TF/Keras)

Key features

CORS enabled — callable from any JavaScript frontend
Lazy model loading — graceful degradation if models are unavailable
Configurable — all settings via api/config.py or environment variables
15 unit tests — all mocked, no real dependencies required


Streamlit App Tests (fixes #65)

37 unit tests across 12 test classes covering all critical paths in web/streamlit.py:

Category: Coverage
Indian Plate Regex: Valid/invalid formats
send_email: Success, default address
login: Success, wrong password, not found, missing field, DB error
register_user: Success, custom role, duplicate username/email, write failure
predict_gunshot: Detected, not detected, model None
match_wanted_face: Match, no match, empty DB, missing field, DeepFace error, multi-doc
extract_audio / audio_to_mel_spectrogram: Pipeline verification
logout: State clear + rerun
process_frame / process_batch_frames: Empty, single/multi models, face variants, invalid plate


CI

Updated CI workflow to run both test suites on push/PR for Python 3.10 and 3.11.

Other Fixes

Cleaned up merge-conflict artifacts in .gitignore
Added .pytest_cache/ to .gitignore

Fixes safe-cam#65

- Add 37 unit tests across 12 test classes covering:
  - Indian plate regex validation (valid/invalid formats)
  - Email notification sending (success + default address)
  - User login (success, wrong password, user not found, missing field, connection error)
  - User registration (success, custom role/plan, duplicate username, duplicate email, DB failure)
  - Gunshot detection (detected, not detected, model unavailable)
  - Wanted face matching (match found, no match, empty DB, missing image field, DeepFace error, multi-document)
  - Audio extraction from video
  - Mel spectrogram conversion
  - Logout (session clear + rerun)
  - Frame processing (no tasks, vehicle only, vehicle+fire, face detection variants, invalid plate handling)
  - Batch frame processing (no tasks, vehicle detection, face detection, all detection types)
- Add conftest.py with mock infrastructure (sys.modules-level mocking for ultralytics, tensorflow, torch, deepface, cv2, librosa, pymongo, pytesseract, streamlit)
- Add __init__.py for tests package
- Update GitHub CI workflow to run tests on push/PR for Python 3.10/3.11
- Add pytest and pytest-mock to web/requirements.txt
Creates a standalone FastAPI application that exposes the CCTV
surveillance detection models via REST endpoints callable from
JavaScript, keeping the API code fully separate from the web UI.

Directory structure:
  api/
  ├── __init__.py
  ├── main.py              # FastAPI app with CORS, lifespan, error handler
  ├── config.py            # Settings (model paths, MongoDB, CORS, server)
  ├── schemas.py           # Pydantic request/response models
  ├── models.py            # Lazy model loader with graceful fallback
  ├── requirements.txt     # FastAPI-specific dependencies
  ├── routers/
  │   ├── __init__.py
  │   ├── health.py        # GET /health — model & DB status
  │   ├── detection.py     # POST /api/detect/* — detection endpoints
  │   └── auth.py          # POST /api/auth/* — login & register
  ├── services/
  │   ├── __init__.py
  │   └── detector.py      # Core detection pipeline + box extraction
  └── tests/
      ├── __init__.py
      ├── conftest.py       # Mocks for all model/audio dependencies
      └── test_api.py       # 15 tests across all endpoints

Endpoints:
  - GET  /                    Service info
  - GET  /health              Health check (model + DB status)
  - POST /api/detect/          Image detection (all 5 model types)
  - POST /api/detect/batch     Video frame batch processing
  - POST /api/detect/gunshot  Gunshot detection from audio
  - POST /api/auth/login       User login
  - POST /api/auth/register    User registration

Key design decisions:
  - CORS enabled for all origins (callable from any JS frontend)
  - Models loaded lazily on first use; failure returns graceful error
  - Model paths are configurable via api/config.py → Settings
  - All endpoints validated with Pydantic schemas
  - Comprehensive test suite with mocked dependencies (15 tests)
  - CI workflow updated to run both web/ and api/ tests

Also fixes:
  - Cleaned up merge-conflict artifacts in .gitignore
  - Added .pytest_cache/ to .gitignore
@Senthil455 Senthil455 changed the title 🧪 [TEST] add comprehensive unit tests for the streamlit app ✨ feat: #35 add FastAPI backend for ML models + 🧪 add unit tests for streamlit app Jun 16, 2026
@Senthil455 Senthil455 changed the title ✨ feat: #35 add FastAPI backend for ML models + 🧪 add unit tests for streamlit app feat: #35 add FastAPI backend for ML models + add unit tests for streamlit app Jun 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🧪 [TEST] - add the unit test cases for the streamlit app 💡 [FEATURE REQUEST] - create the Fast-API for the models

1 participant