feat: #35 add FastAPI backend for ML models + add unit tests for streamlit app - #75
Open
Senthil455 wants to merge 2 commits into
Open
feat: #35 add FastAPI backend for ML models + add unit tests for streamlit app#75Senthil455 wants to merge 2 commits into
Senthil455 wants to merge 2 commits into
Conversation
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR addresses two issues:
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