Skip to content
manavdhamecha77Public

About

TraceNet is an AI-driven descriptive search system for smart city CCTV footage

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

229 Commits

Folders and files

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

Repository files navigation

πŸ” TraceNet β€” AI-Driven Descriptive Search for Smart City CCTV

Hackathon Submission Β· Problem Statement ERH26_PS_07 β€” Digital Forensics / AI Video Analytics

TraceNet is an AI-powered forensic surveillance platform that transforms passive CCTV infrastructure into an active investigative tool. Instead of an officer manually scrubbing through hours of footage, they type a natural-language description of a person or vehicle and get ranked, time-stamped, explainable results across an entire camera network β€” in seconds.

"Man in a red jacket carrying a black backpack near Gate 3 after 5 PM."

The platform is designed for the day-to-day operational reality of a police surveillance team β€” prioritising speed of investigation, evidentiary integrity, human-in-the-loop confirmation, and a forensic command-centre aesthetic built for shift-long use.


πŸ“ System Architecture

Pipeline Flow Architecture

The diagram below shows the 7 functional subsystems that form the TraceNet processing pipeline β€” from raw camera feed all the way to investigative search results and multi-camera command intelligence.

TraceNet Pipeline Flow Architecture

# Subsystem Core Function
01 Streaming & Ingestion RTSP/SRT live feeds + batch video ingest with forensic SHA-256 hashing
02 Vision YOLOv11 object detection Β· ByteTrack multi-object tracking Β· Motion & trajectory extraction
03 Identity & Semantic Intelligence CLIP visual embeddings Β· BLIP auto-captioning Β· LLM scene reasoning Β· Cross-camera Re-ID
04 Threat & Event Intelligence Loitering / dwell-time Β· Theft / chain-snatching Β· Assault/fight Β· Abandoned objects Β· Suspect reappearance
05 Search & Forensics NL query search Β· Visual / missing-person reverse photo search Β· Evidence export with integrity manifest
06 Command & Multi-Camera Intelligence Security command centre Β· GIS pursuit map Β· Pursuit Wave predictive camera handoff Β· Real-time alerts
07 Security, Privacy & Evidence Integrity Secure communication Β· Immutable audit logs Β· Chain-of-custody SHA-256 verification

🎯 Feature Overview

πŸ”΅ Ingestion & Preprocessing

  • Batch video upload β€” supports .mp4, .avi, .mov
  • Live WebRTC streaming β€” WHIP/WHEP via MediaMTX, proxied through the backend; phones/edge cameras broadcast from the backend-served edge camera app at https://<LAN-IP>:8443/camera-app (see docs/live-streaming.md)
  • FFmpeg transcoding β€” standardises all inputs to 720p / 10 FPS H.264
  • OpenCV 4-FPS timeline-proportional frame sampling β€” zero disk-write overhead
  • SHA-256 forensic intake hash on every uploaded asset for chain-of-custody
  • Progressive ingestion status β€” pending β†’ transcoding β†’ preprocessed β†’ indexing β†’ complete with live progress bars
  • System Job queue β€” clickable status pill in topbar shows active pipeline jobs

🟣 Detection & Tracking

  • YOLOv8/v11 person + vehicle detection with custom-trained weights (best.pt)
  • ByteTrack consistent cross-frame track IDs via supervision library
  • Tracklet extraction β€” frame range, timestamp, best bounding-box crop, confidence score
  • CLIP 512-dim visual embedding per tracklet (best-crop)
  • BLIP auto-captioning per tracklet (Salesforce/blip-image-captioning-base)
  • Annotated video export β€” server-side bounding-box render to MP4

🟒 Search & Investigation (/search)

  • Natural language text search β€” CLIP text embedding β†’ Qdrant vector similarity β†’ ranked results
  • Reverse photo search β€” drag-and-drop reference image β†’ CLIP image-to-image similarity
  • Multi-filter matrix β€” camera nodes, time range, object type (person / vehicle)
  • Explainability panel β€” per-result "Why this matched" breakdown (CLIP score, detector confidence, caption overlap, unverified terms, applied filters)
  • Hot-Target tagging β€” pin any result as a pursuit target directly from search
  • SHA-256 evidence export β€” client-side hashed compliance report download
  • Search audit logging β€” every query logged to SQLite search_logs with operator ID, timestamp, result count
  • Per-video scoped search β€” CLIP search limited to a single video in the Video Detail view

🟑 Alert Center (/alerts)

  • Unified Alert Dashboard β€” filterable by type, camera, acknowledgement status; bulk-acknowledge
  • Loitering / Dwell-Time Detection β€” user-drawn polygon zones, configurable dwell threshold (seconds), bottom-centre tracking, grace-gap deduplication
  • Outdoor Theft / Chain-Snatching Detection β€” state-machine analyser, spatiotemporal proximity / fall / chase vectors, forensic evidence frame extraction, SUSPECT/VICTIM label mapping
  • Physical Assault Detection β€” YOLO class-based detection, 7-day statistics, per-frame confidence timeline drill-down
  • Abandoned Object Detection β€” configurable abandon time and visitor-radius parameters
  • Operator acknowledgement stamp β€” operator ID + timestamp on every resolved alert
  • Real-time alert badge β€” sidebar unacknowledged count with live polling

πŸ”΄ Pursuit & Multi-Camera Intelligence (/targets)

  • Hot Targets registry β€” label, priority (NORMAL / HIGH / CRITICAL), status (active / resolved), reappearance tracking
  • Journey Map β€” interactive Leaflet multi-camera trajectory scrubber with timeline step navigation
  • Pursuit Wave HUD β€” floating predictive downstream-camera handoff panel; monitors adjacent nodes in real-time
  • Cross-camera Re-ID β€” CLIP embedding similarity through spatial graph DAG trajectory engine
  • Tag from search or video detail β€” one-click pursuit target assignment anywhere in the platform

🟣 Live Streaming

  • LiveCameraView (/cameras/:id/live) β€” real-time WHEP player with canvas annotation overlay, pair-code QR system, skeleton pose keypoints, telemetry sparklines (FPS, inference ms, latency), chunk pipeline logs
  • Edge Camera App (/camera-app, served by the backend over HTTPS) β€” pair a phone with a 6-digit code; live loop runs the vehicle/pedestrian detector only, every recorded chunk is checked into the camera's archive and run through the full indexing pipeline

πŸ”΅ Forensic Reports (/api/v1/reports)

  • Automated PDF crime report generation β€” per-alert incident reports with severity classification, evidence frame attachments, chain-of-custody tagging, assigned operator fields
  • Compliance audit trail β€” GET /audit/search-history, GET /audit/alert-history, GET /audit/compliance-report
  • Evidence export with integrity hash β€” SHA-256 signed compliance bundles downloadable from Search page

🟒 AI Copilot (Ctrl+K)

  • Global search bar β€” launches from anywhere in the app
  • Full-screen AI overlay β€” multi-session conversation sidebar with history
  • Ollama support β€” local models (qwen2.5:3b) for fully offline operation
  • Cloud LLM support β€” OpenAI, Groq, DeepSeek, OpenRouter via configurable API key
  • MCP tool calling β€” domain-locked assistant can query the live search API, alert system, and camera registry
  • Session persistence β€” conversation history survives overlay open/close via sessionStorage
  • Quick prompt chips β€” pre-loaded investigative queries on the Dashboard

🟣 ML Admin (Admin-Gated)

  • Detector Model Registry (/models) β€” upload .pt weights, auto-parse YOLO class names, per-camera assignment, execution logs
  • CLIP Embedding Config (/embedding-models) β€” model swap configuration
  • YOLO Fine-Tuning (/finetuning) β€” training job submission, live polling, history log
  • Role-based gating β€” LOCKED / UNLOCKED sidebar toggle restricts ML admin routes from officer view

🟑 HCI & Operator Experience

  • Forensic Command Centre dark-mode aesthetic (default)
  • Alt+1..5 global keyboard shortcuts for rapid navigation
  • Toast notification system replacing all native alert() / confirm() dialogs
  • ErrorBoundary wrapping all routes β€” crash isolation per-route
  • Standardised formatDisplayDate() across all timestamps
  • Breadcrumb navigation for all 11+ routes
  • Collapsible sidebar with icon-only collapsed mode

πŸ› οΈ Tech Stack

Backend

Layer Technology
API Framework FastAPI + Pydantic + Uvicorn
Database ORM SQLAlchemy + SQLite (drishti.db) with startup auto-migrations
Video Processing OpenCV (cv2), FFmpeg (ffmpeg-python)
Object Detection Ultralytics YOLOv8/v11 (best.pt)
Object Tracking ByteTrack via supervision library
Visual Embeddings CLIP (open-clip-torch, ViT-B/32)
Auto-Captioning BLIP (transformers, Salesforce/blip-image-captioning-base)
Vector Database Qdrant (local persistent client)
Live Streaming MediaMTX (WHIP / WHEP / SRT / RTMP)
PDF Reports ReportLab
Logging Loguru
ML Framework PyTorch β‰₯ 2.5, torchvision β‰₯ 0.20

Frontend

Layer Technology
Framework React 18 + TypeScript + Vite
Styling TailwindCSS
Routing React Router v7
Maps Leaflet + react-leaflet
Icons Lucide React
Live Streaming WebRTC (WHIP / WHEP native browser APIs)
HTTP Native fetch (centralised via src/config/api.ts)

πŸ“ Repository Structure

TraceNet/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ main.py                  # FastAPI entrypoint + startup auto-migration runner
β”‚   β”‚   β”œβ”€β”€ api/                     # All API routers (22 files)
β”‚   β”‚   β”‚   β”œβ”€β”€ cameras.py           # Camera CRUD
β”‚   β”‚   β”‚   β”œβ”€β”€ upload.py            # Video ingest + background processing pipeline
β”‚   β”‚   β”‚   β”œβ”€β”€ search.py            # NL + photo search endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ alerts.py            # Loitering / theft / assault / abandoned alerts
β”‚   β”‚   β”‚   β”œβ”€β”€ streaming.py         # WebRTC WHIP/WHEP live streaming
β”‚   β”‚   β”‚   β”œβ”€β”€ reports.py           # PDF crime report generation
β”‚   β”‚   β”‚   β”œβ”€β”€ audit.py             # Search + alert audit trail
β”‚   β”‚   β”‚   β”œβ”€β”€ multicam.py          # Multi-camera trajectory + Pursuit Wave
β”‚   β”‚   β”‚   β”œβ”€β”€ assistant.py         # AI Copilot (Ollama / Cloud LLM + MCP)
β”‚   β”‚   β”‚   β”œβ”€β”€ models.py            # YOLO model registry
β”‚   β”‚   β”‚   β”œβ”€β”€ detections.py        # Tracklet inspection endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ assault_detection.py # Assault statistics + alerts
β”‚   β”‚   β”‚   β”œβ”€β”€ metrics.py           # Dashboard metrics aggregation
β”‚   β”‚   β”‚   └── system_jobs.py       # Pipeline job queue
β”‚   β”‚   β”œβ”€β”€ alerts/
β”‚   β”‚   β”‚   β”œβ”€β”€ loitering.py         # Dwell-time polygon zone analyser
β”‚   β”‚   β”‚   └── chain_snatching.py   # Violent theft / snatching state machine
β”‚   β”‚   β”œβ”€β”€ analytics/
β”‚   β”‚   β”‚   β”œβ”€β”€ camera_graph.py      # Spatial adjacency graph
β”‚   β”‚   β”‚   β”œβ”€β”€ trajectory_engine.py # DAG-based cross-camera trajectory
β”‚   β”‚   β”‚   β”œβ”€β”€ pursuit_wave.py     # Predictive pursuit manager
β”‚   β”‚   β”‚   └── hot_target.py        # Hot target manager
β”‚   β”‚   β”œβ”€β”€ embeddings/
β”‚   β”‚   β”‚   β”œβ”€β”€ clip_encoder.py      # CLIP visual embedding extractor
β”‚   β”‚   β”‚   β”œβ”€β”€ captioner.py         # BLIP auto-captioning
β”‚   β”‚   β”‚   └── tracklet_embeddings.py
β”‚   β”‚   β”œβ”€β”€ detection/
β”‚   β”‚   β”‚   β”œβ”€β”€ detector.py          # YOLOv8/v11 detection wrapper
β”‚   β”‚   β”‚   β”œβ”€β”€ tracker.py           # ByteTrack wrapper
β”‚   β”‚   β”‚   └── weights/best.pt      # Model weights
β”‚   β”‚   β”œβ”€β”€ search/
β”‚   β”‚   β”‚   β”œβ”€β”€ vector_index.py      # Qdrant index service
β”‚   β”‚   β”‚   β”œβ”€β”€ query_engine.py      # Hybrid NL search logic
β”‚   β”‚   β”‚   └── image_search.py      # CLIP image-to-image search
β”‚   β”‚   β”œβ”€β”€ streaming/               # MediaMTX integration + chunker + inference worker
β”‚   β”‚   β”œβ”€β”€ reporting/               # PDF report generator (ReportLab)
β”‚   β”‚   β”œβ”€β”€ preprocess/              # FFmpeg + OpenCV pipeline
β”‚   β”‚   β”œβ”€β”€ db/
β”‚   β”‚   β”‚   β”œβ”€β”€ models.py            # SQLAlchemy ORM models
β”‚   β”‚   β”‚   β”œβ”€β”€ crud.py
β”‚   β”‚   β”‚   └── session.py
β”‚   β”‚   β”œβ”€β”€ assistant/               # Ollama / Cloud LLM + MCP tool calling
β”‚   β”‚   └── config.py                # Centralised data path resolver (get_data_path)
β”‚   β”œβ”€β”€ data/                        # ALL runtime data (auto-created on first launch)
β”‚   β”‚   β”œβ”€β”€ drishti.db               # SQLite database
β”‚   β”‚   β”œβ”€β”€ minio_mock/              # Raw uploaded video files
β”‚   β”‚   β”œβ”€β”€ processed/               # Transcoded MP4s, tracklet crops, frames
β”‚   β”‚   β”œβ”€β”€ vector_db/               # Qdrant persistent collection
β”‚   β”‚   └── audit_logs/              # Daily JSONL audit files
β”‚   └── requirements.txt
β”‚
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ App.tsx                  # Central routing, state, sidebar, modals
β”‚   β”‚   β”œβ”€β”€ pages/                   # 18 page components
β”‚   β”‚   β”œβ”€β”€ components/              # Shared UI components
β”‚   β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”‚   β”œβ”€β”€ api.ts               # Centralised API_BASE constant
β”‚   β”‚   β”‚   └── operator.ts          # DEMO_OPERATOR identity constant
β”‚   β”‚   └── utils/
β”‚   β”‚       β”œβ”€β”€ colors.ts            # classColor() for detection class colouring
β”‚   β”‚       └── dateFormatter.ts     # formatDisplayDate() standardisation
β”‚   └── package.json
β”‚
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ scalability.md               # Production city-scale architecture
β”‚   β”œβ”€β”€ preprocess-api.md
β”‚   β”œβ”€β”€ detection-tracking-api.md
β”‚   β”œβ”€β”€ loitering-detection.md
β”‚   β”œβ”€β”€ chain-snatching-api.md
β”‚   └── embeddings-api.md
β”‚
β”œβ”€β”€ flow arch of project.jpeg
β”œβ”€β”€ proposed technical architecture at scale.jpeg
└── AGENTS.md

πŸš€ Getting Started

Prerequisites

  • Python 3.10+
  • Node.js 18+
  • FFmpeg installed and on PATH (verify: ffmpeg -version)
  • (Optional) CUDA-capable GPU for faster YOLO + CLIP inference

Backend Setup

cd backend

# Create and activate virtual environment
python -m venv .venv

# Windows
.venv\Scripts\activate

# Linux / macOS
source .venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Start the API server
# Development (hot reload, HTTP :8000) - always uses the project venv, even if a global uvicorn is on PATH
.\dev.ps1          # or: dev.bat

# Demo / phones (HTTP :8000 + HTTPS :8443 with a self-signed LAN certificate, no reload)
.\serve.ps1        # or: ..\.venv\Scripts\python.exe serve.py

# NOTE: a bare `uvicorn app.main:app` may resolve to a global Python without the project packages
# (symptom: ModuleNotFoundError: No module named 'supervision'). Use the launchers above.

WebRTC Server Setup (For real-time stream)

cd backend

# Go to mediaMTX dir
cd \data\mediamtx

# Execute the file with the config file
.\mediamtx.exe .\mediamtx.yml

URLs:

Endpoint URL
REST API http://localhost:8000
Swagger UI http://localhost:8000/docs
ReDoc http://localhost:8000/redoc
Health check http://localhost:8000/health

Note: All data (SQLite DB, video files, vector index, audit logs) is stored under backend/data/. The directory structure is created automatically on first launch. The server also runs startup auto-migrations on every boot β€” existing data is preserved.

Frontend Setup

cd frontend

npm install

npm run dev

Frontend URL: http://localhost:5173


🎬 Demo Walkthrough

1. Register a Camera Node

/cameras β†’ Register Camera β†’ enter Camera ID (e.g. CAM_001), name, lat/lon coordinates, and optionally assign a YOLO detector model.

2. Upload a CCTV Video

Camera Detail page β†’ Ingest Video β†’ select a video file β†’ optionally enable Loitering Zone Detection with a polygon zone and dwell threshold β†’ upload.

The pipeline runs automatically in the background:

Upload β†’ FFmpeg transcode (720p/10FPS) β†’ OpenCV frame sampling (4FPS)
β†’ YOLOv8 detection β†’ ByteTrack tracking β†’ CLIP embedding β†’ BLIP captioning
β†’ Qdrant vector upsert β†’ Status: complete

3. Search for a Person or Vehicle

/search β†’ type a natural-language description (e.g. "person in blue hoodie near the entrance") β†’ filter by camera nodes and time range β†’ run search.

Results show: thumbnail crop, CLIP similarity score, camera + timestamp, BLIP caption, and a "Why this matched" explainability panel.

4. Tag a Suspect for Pursuit

On any search result β†’ Tag as Hot Target β†’ assign label and priority β†’ the suspect is registered in the Pursuit registry and monitored via Pursuit Wave across adjacent camera nodes.

5. Review Alerts

/alerts β†’ review loitering, theft, and assault alerts β†’ click any alert to view evidence frames, tracklet timeline β†’ acknowledge with operator stamp.

6. Live Monitoring

  • Watch Live β€” /cameras/:id/live β€” real-time WebRTC stream with bounding-box overlays and performance telemetry.
  • Broadcast from a phone β€” https://<LAN-IP>:8443/camera-app β€” pair with the code from Cameras β†’ Pair device; start the backend with python serve.py for the HTTPS listener (docs/live-streaming.md).

πŸŽ₯ Sample Detection Videos

See TraceNet in action: sample CCTV footage showcasing Abandoned Object Detection , Assault Detection and Chain Snatching / Theft Detection.

🎬 Watch Sample Detection Videos

πŸ€– Trained Detection Models

πŸ“¦ Download Abandoned Object, Assault & Theft Detection Models


πŸ“‘ Key API Endpoints

Method Endpoint Description
GET /health Health check
GET /api/v1/cameras List all camera nodes
POST /api/v1/cameras/create-new-camera Register a camera
POST /api/v1/ingest Upload and process a CCTV video
POST /api/v1/search Natural language search
POST /api/v1/search/image Reverse photo search
GET /api/v1/alerts List all alerts (filterable by type, camera, status)
PUT /api/v1/alerts/{id}/acknowledge Acknowledge an alert
POST /api/v1/multicam/trajectory/reconstruct Reconstruct cross-camera trajectory
POST /api/v1/multicam/targets/tag Tag a suspect as hot target
POST /api/v1/stream/start Start a live stream session
POST /api/v1/stream/pair/generate Generate a mobile device pair code
POST /api/v1/reports/generate Generate a PDF crime report
GET /api/v1/audit/compliance-report Get system compliance report
GET /api/v1/metrics/dashboard Get dashboard metrics
GET /api/v1/jobs Get system job queue status

Full interactive documentation: http://localhost:8000/docs


πŸ—οΈ Architecture at Scale

For the proposed city-scale production architecture (edge node processing, GPU worker pools, Qdrant cluster, PostgreSQL + pgvector, MediaMTX cluster, AWS S3 tiered storage), see:

πŸ“„ docs/scalability.md

Proposed Production Architecture at Scale


βš–οΈ Ethical Guardrails

TraceNet is designed with strict ethical boundaries for law-enforcement use:

  1. Human-in-the-loop always β€” the system ranks and surfaces candidates. It never auto-declares an identity match.
  2. Explainability over black-box scores β€” every result shows why it matched, not just a number.
  3. Privacy-conscious β€” no predictive-policing or "suspicious intent" classifiers. Attribute search only (appearance, location, time).
  4. Audit everything β€” every search query, alert acknowledgement, and export is logged with operator identity and timestamp.
  5. Scope discipline β€” person + vehicle attribute search only. No open-vocabulary action/activity recognition.

πŸ”¬ Problem Statement

ERH26_PS_07 β€” Digital Forensics / AI Video Analytics

Smart city surveillance networks generate terabytes of footage that are effectively unsearchable with legacy tools. A detective investigating a crime must manually review camera by camera, hour by hour. TraceNet turns this on its head β€” the investigator describes what they are looking for in plain language, and the system surfaces the most relevant evidence across the entire camera network, ranked by semantic similarity, with full chain-of-custody audit trails suitable for use in an evidentiary context.


πŸ“„ License

Built for demonstration and hackathon evaluation purposes. Not licensed for production law-enforcement deployment without appropriate legal and ethical review.

About

TraceNet is an AI-driven descriptive search system for smart city CCTV footage

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages