From 82590c392f14abac1ca76b46659a8d1bd6a35924 Mon Sep 17 00:00:00 2001 From: Ryan Shepherd Date: Mon, 3 Aug 2026 11:30:49 -0400 Subject: [PATCH] After story 1 --- .gitignore | 70 ++++ Plan.md | 196 ++++++++++ README.md | 168 ++++++++ Requirements.md | 182 +++++++++ STORY-01.md | 170 ++++++++ STORY-02.md | 182 +++++++++ STORY-03.md | 152 +++++++ STORY-04.md | 168 ++++++++ STORY-05.md | 187 +++++++++ STORY-06.md | 181 +++++++++ STORY-07.md | 216 ++++++++++ STORY-08.md | 245 ++++++++++++ STORY-09.md | 360 +++++++++++++++++ config.yaml | 248 ++++++++++++ db/schema.sql | 122 ++++++ docker-compose.yml | 146 +++++++ .../grafana/dashboards/active_learning.json | 97 +++++ .../dashboards/processing_details.json | 115 ++++++ .../grafana/dashboards/system_overview.json | 108 +++++ .../grafana/provisioning/dashboards.yml | 11 + .../grafana/provisioning/datasources.yml | 9 + monitoring/prometheus/prometheus.yml | 26 ++ run.pl | 68 ++++ src/config_loader.py | 126 ++++++ src/db_connector.py | 137 +++++++ src/logging_config.py | 89 +++++ src/main.py | 99 +++++ ui/Dockerfile | 16 + ui/app.py | 370 ++++++++++++++++++ ui/requirements.txt | 4 + worker/Dockerfile | 67 ++++ worker/requirements.txt | 40 ++ 32 files changed, 4375 insertions(+) create mode 100644 .gitignore create mode 100644 Plan.md create mode 100644 README.md create mode 100644 Requirements.md create mode 100644 STORY-01.md create mode 100644 STORY-02.md create mode 100644 STORY-03.md create mode 100644 STORY-04.md create mode 100644 STORY-05.md create mode 100644 STORY-06.md create mode 100644 STORY-07.md create mode 100644 STORY-08.md create mode 100644 STORY-09.md create mode 100644 config.yaml create mode 100644 db/schema.sql create mode 100644 docker-compose.yml create mode 100644 monitoring/grafana/dashboards/active_learning.json create mode 100644 monitoring/grafana/dashboards/processing_details.json create mode 100644 monitoring/grafana/dashboards/system_overview.json create mode 100644 monitoring/grafana/provisioning/dashboards.yml create mode 100644 monitoring/grafana/provisioning/datasources.yml create mode 100644 monitoring/prometheus/prometheus.yml create mode 100755 run.pl create mode 100644 src/config_loader.py create mode 100644 src/db_connector.py create mode 100644 src/logging_config.py create mode 100644 src/main.py create mode 100644 ui/Dockerfile create mode 100644 ui/app.py create mode 100644 ui/requirements.txt create mode 100644 worker/Dockerfile create mode 100644 worker/requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..868cded --- /dev/null +++ b/.gitignore @@ -0,0 +1,70 @@ +# VideoDetect .gitignore + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +*.egg +*.egg-info/ +dist/ +build/ +.eggs/ +*.whl + +# Virtual environments +venv/ +env/ +.venv/ + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# Docker +.docker/ + +# Environment +.env +.env.* + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log +logs/ + +# Data (large files) +data/ +*.mp4 +*.mov +*.avi +*.mkv + +# Models (large files) +models/*.pt +models/*.onnx +!models/.gitkeep + +# Scratch +scratch/ +*.tmp +*.temp + +# Testing +.pytest_cache/ +.coverage +htmlcov/ + +# Monitoring +prometheus/data/ +grafana/data/ + +# OS +.DS_Store +Thumbs.db diff --git a/Plan.md b/Plan.md new file mode 100644 index 0000000..b8b6e84 --- /dev/null +++ b/Plan.md @@ -0,0 +1,196 @@ +# Implementation Plan: Video Classification System + +## Overview +This document outlines the phased implementation plan for the Video Classification System. The plan breaks down the requirements into logical work packages (Sprints/Phases) that can be implemented, tested, and integrated sequentially. + +**Key Dependencies:** +1. **Infrastructure** must be available before any processing logic can run. +2. **Database Schema** must be finalized early to support metadata logging. +3. **Model Training Data** is a bottleneck; the initial model must be ready or a placeholder used for pipeline testing. + +--- + +## Phase 1: Foundation & Infrastructure (Sprint 1-2) +**Goal:** Establish the Docker environment, Database schema, and basic connectivity. No video processing yet, just the "skeleton." + +### 1.1 Environment Setup +- [ ] **Docker Compose Structure:** Create `docker-compose.yml` defining services for: + - `mariadb`: Persistent volume for metadata. + - `worker`: Build context for PyTorch/TensorRT environment. Include `nvidia-container-toolkit` config for GPU passthrough. + - `ui`: Placeholder container (e.g., nginx serving a static "Under Construction" page) to verify network connectivity. +- [ ] **Base Images:** + - Create a custom Dockerfile for the worker based on `nvidia/cuda:11.8.0-runtime-ubuntu20.04`. + - Install PyTorch (1.13+ with CUDA 11.8), OpenCV, FFmpeg-python, and TensorRT prerequisites. +- [ ] **Volume Mounts:** + - Map local NVMe path to `/scratch` in worker container (tmpfs preferred for speed). + - Map NAS/SMB path to `/data/input` and `/data/output` in worker container. + - Map `/models` and `/data/training` for persistence. + +### 1.2 Database Schema Design +- [ ] **MariaDB Schema:** Define tables in SQL migration script: + - `videos`: `id`, `file_path`, `file_hash`, `resolution_w`, `resolution_h`, `codec`, `status` (NEW, PENDING, PROCESSING, COMPLETED, UNSCANNABLE, ERROR), `last_scan_time`, `last_processed_time`. + - `processing_logs`: `id`, `video_id`, `model_version`, `frame_count`, `confidence_score`, `routing_decision`, `processed_at`. + - `models`: `version`, `status` (ACTIVE, CANDIDATE, ARCHIVED), `path`, `calibration_temp`. +- [ ] **Connection Layer:** Implement a Python module (`db_connector.py`) with connection pooling to MariaDB. + +### 1.3 Configuration Management +- [ ] **Config File:** Create `config.yaml` for thresholds (`T_high`, `T_low`), sampling intervals, and GPU settings. +- [ ] **Logging Setup:** Configure structured logging (JSON format) to stdout for Docker capture. + +**Exit Criteria:** +- `docker-compose up` starts DB and Worker containers successfully. +- Worker can connect to DB and create tables. +- GPU is visible inside the Worker container (`nvidia-smi`). + +--- + +## Phase 2: Core Ingestion & Codec Handling (Sprint 3-4) +**Goal:** Implement the directory scanner, video probing, and robust error handling for codecs/resolutions. + +### 2.1 Directory Scanner +- [ ] **Scanner Service:** Implement a background thread or separate script that walks `/data/input`. +- [ ] **File Detection:** Identify new files (not in DB) and update status to `PENDING`. +- [ ] **Deduplication:** Use `file_hash` (SHA-256 of first 1MB or full file if small) to prevent re-processing identical files. + +### 2.2 Video Probing & Metadata Extraction +- [ ] **FFmpeg Probe:** For each `PENDING` file, run `ffprobe` to extract: + - Codec name. + - Resolution (width/height). + - Duration. +- [ ] **Codec Validation:** Maintain a whitelist of supported codecs (H.264, H.265, VP8, VP9, etc.). + - If codec is unsupported or `ffprobe` fails: Set status to `UNSCANNABLE`. + - Log the specific error code/reason. +- [ ] **Resolution Handling:** Store resolution in DB. Implement logic to downscale high-res frames (4K) if necessary to fit VRAM constraints during inference. + +### 2.3 Batch Orchestration Skeleton +- [ ] **Job Queue:** Implement a simple priority queue or DB-based locking mechanism to assign files to Worker processes. +- [ ] **State Management:** Ensure atomic transitions from `PENDING` → `PROCESSING` to avoid duplicate processing. + +**Exit Criteria:** +- New files in `/data/input` appear in DB with correct metadata within 60 seconds. +- Unsupported codec files are marked `UNSCANNABLE` without crashing the scanner. +- DB accurately reflects the current state of the 30TB corpus. + +--- + +## Phase 3: Inference Pipeline & Model Integration (Sprint 5-6) +**Goal:** Implement frame sampling, face detection, classification, and confidence aggregation. + +### 3.1 Frame Sampling +- [ ] **FFmpeg Extraction:** Implement logic to extract 1 frame per 30 seconds uniformly. + - Handle variable FPS gracefully. + - Save frames to `/scratch/tmp/` with naming convention `{video_id}_{timestamp}.jpg`. +- [ ] **Memory Management:** Ensure frames are deleted from scratch space immediately after processing the video to prevent filling NVMe. + +### 3.2 Face Detection +- [ ] **Model Integration:** Load YOLOv8n (or chosen lightweight detector) via ONNX Runtime or TensorRT. +- [ ] **Batching:** Implement dynamic batching for face detection to maximize GPU utilization. +- [ ] **Crop Generation:** Extract face crops, resize to inference input size (e.g., 224x224). + +### 3.3 Classification & Aggregation +- [ ] **Model Integration:** Load MobileNetV3 (or chosen classifier) via TensorRT FP32. +- [ ] **Inference:** Run classification on face crops. +- [ ] **Aggregation Logic:** + - Calculate frame-level confidence `p_i`. + - Apply video-level aggregation (e.g., `max(p_i)` or weighted mean). + - Apply temperature scaling for calibration. +- [ ] **Routing Decision:** Compare final confidence `C` against `T_high` and `T_low`. Assign `MATCH`, `REVIEW`, or `SKIP`. + +### 3.4 Result Persistence +- [ ] **DB Update:** Update `videos` table with `processed_at`, `model_version`, and status `COMPLETED`. +- [ ] **Log Entry:** Insert record into `processing_logs`. +- [ ] **Export:** Write summary JSON/Parquet file to `/data/output` for analytics. + +**Exit Criteria:** +- A sample video is processed end-to-end: Frames extracted → Faces detected → Classified → Confidence calculated → DB updated. +- GPU memory usage stays under 18GB per GPU. +- Throughput meets baseline (>30 videos/hour/GPU on test set). + +--- + +## Phase 4: Active Learning & Review UI (Sprint 7-8) +**Goal:** Enable human-in-the-loop correction and model retraining. + +### 4.1 Review UI +- [ ] **UI Setup:** Deploy Label Studio or custom Flask UI. +- [ ] **Data Feed:** Query DB for videos with routing_decision = `REVIEW`. +- [ ] **Frontend:** Display video player + top-k contributing frames. Allow annotator to toggle label (True/False) or correct classification. +- [ ] **Export:** Generate CSV/JSON export of annotated data with ground truth. + +### 4.2 Fine-Tuning Pipeline +- [ ] **Data Loader:** Script to ingest exported annotations and prepare dataset for training. +- [ ] **Training Job:** + - Head-only fine-tuning on face crops. + - Use AdamW, LR=1e-3, Early Stopping. + - Save checkpoint to `/models/candidate/`. +- [ ] **Validation:** + - Run candidate model on held-out validation set. + - Calculate F1 score and ECE (Expected Calibration Error). + - If ΔF1 > 0.02 and ECE < 0.08, promote model to `ACTIVE`. + +### 4.3 Model Swapping +- [ ] **Registry Update:** Update DB `models` table to mark new version as `ACTIVE` and old as `ARCHIVED`. +- [ ] **Hot Reload:** Restart Worker containers or signal process to reload new TensorRT engine. + +**Exit Criteria:** +- Annotator can label a review video. +- Labeled data triggers a fine-tuning job. +- New model is validated and deployed automatically. + +--- + +## Phase 5: Observability, Monitoring & Hardening (Sprint 9+) +**Goal:** Ensure system reliability, debuggability, and long-term stability. + +### 5.1 Metrics & Logging +- [ ] **Prometheus Integration:** Expose metrics: + - `videos_processed_total` (by routing decision). + - `gpu_utilization`, `gpu_memory_used`. + - `queue_depth` (PENDING/PROCESSING counts). + - `confidence_distribution` histogram. +- [ ] **Grafana Dashboard:** Create dashboards for: + - Throughput (videos/hour). + - Error rates (UNSCANNABLE/ERROR counts). + - Confidence drift alerts. + +### 5.2 Fault Tolerance & Resumption +- [ ] **Crash Recovery:** Implement checkpointing. If Worker dies, mark `PROCESSING` jobs as `PENDING` again. +- [ ] **Idempotency:** Ensure re-processing a file does not duplicate DB entries or outputs. +- [ ] **Retry Logic:** Auto-retry transient errors (e.g., network blip during NAS access) up to 3 times. + +### 5.3 Drift Detection +- [ ] **Weekly Job:** Compare current confidence distribution to baseline. +- [ ] **Alerting:** Send alert if `p(C > 0.5)` shifts >10% or Review Queue grows unbounded. + +**Exit Criteria:** +- Dashboard shows real-time health of the system. +- System recovers gracefully from forced Worker termination. +- Alerts trigger correctly on simulated drift/errors. + +--- + +## Risk Mitigation + +| Risk | Mitigation Strategy | +|------|---------------------| +| **GPU OOM** | Implement strict batch size caps; downscale 4K frames to 1080p/720p before inference. | +| **Slow NAS I/O** | Cache frames in local NVMe `tmpfs`; minimize disk writes until final export. | +| **Codec Variance** | Extensive unit testing of `ffprobe` logic against known "bad" files. Graceful degradation to `UNSCANNABLE`. | +| **Model Regression** | Strict validation gate before model swap. Keep previous model in `ARCHIVED` state for quick rollback. | +| **30TB Scan Time** | Incremental scanning using `file_hash` and `last_modified` timestamps. Avoid full rescan. | + +--- + +## Deliverables Checklist +- [ ] `docker-compose.yml` +- [ ] Worker Dockerfile & Requirements.txt +- [ ] MariaDB SQL Schema +- [ ] Python Source Code (`src/`) + - `scanner.py` + - `processor.py` + - `model_runner.py` + - `db_handler.py` + - `train.py` +- [ ] Config Files (`config.yaml`) +- [ ] Grafana Dashboard JSON +- [ ] Documentation (`README.md`, `API_DOCS.md`) \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..ba71a14 --- /dev/null +++ b/README.md @@ -0,0 +1,168 @@ +# VideoDetect - Video Classification System + +A production-grade video classification system for processing large-scale video corpora (~30TB) to classify videos based on demographic presence using deep learning models. + +## Architecture + +``` +┌─────────────┐ ┌──────────────┐ ┌─────────────┐ +│ Scanner │────▶│ Processor │────▶│ Results │ +│ (STORY-02) │ │ (STORY-03/04)│ │ (STORY-05) │ +└─────────────┘ └──────────────┘ └─────────────┘ + │ │ │ + ▼ ▼ ▼ +┌─────────────┐ ┌──────────────┐ ┌─────────────┐ +│ MariaDB │◀───▶│ GPU (P40) │◀───▶│ Export │ +│ (Metadata) │ │ (Inference) │ │ (Parquet) │ +└─────────────┘ └──────────────┘ └─────────────┘ + │ + ▼ +┌─────────────┐ ┌──────────────┐ +│ Review UI │◀───▶│ Active Learn │ +│ (STORY-06) │ │ (STORY-07) │ +└─────────────┘ └──────────────┘ + │ + ▼ +┌─────────────┐ +│ Monitoring │ +│ (STORY-08) │ +└─────────────┘ +``` + +## Quick Start + +### Prerequisites +- Docker & Docker Compose v2+ +- NVIDIA Container Toolkit +- 2× Tesla P40 GPUs (or compatible) +- NAS/SMB mount at `/mnt/nas` (configurable via env vars) + +### Environment Variables + +```bash +# Database +export DB_ROOT_PASSWORD=your_root_password +export DB_PASSWORD=your_db_password + +# Paths (optional, defaults shown) +export NAS_INPUT_PATH=/mnt/nas/input +export NAS_OUTPUT_PATH=/mnt/nas/output +export MODELS_PATH=/mnt/nas/models +export TRAINING_PATH=/mnt/nas/training + +# Grafana admin password +export GRAFANA_PASSWORD=your_grafana_password +``` + +### Start the Stack + +```bash +docker-compose up -d +``` + +### Verify Services + +```bash +# Check all containers are running +docker-compose ps + +# Check GPU visibility in worker +docker exec videodetect-worker nvidia-smi + +# Check database connectivity +docker exec videodetect-mariadb mysql -u videodetect -p videodetect -e "SHOW TABLES;" + +# Access UI +open http://localhost:5000 + +# Access Grafana +open http://localhost:3000 (admin / your_grafana_password) + +# Access Prometheus +open http://localhost:9090 +``` + +## Project Structure + +``` +VideoDetect/ +├── docker-compose.yml # Multi-service orchestration +├── config.yaml # All configuration +├── db/ +│ └── schema.sql # MariaDB schema +├── worker/ +│ ├── Dockerfile # Worker container image +│ └── requirements.txt # Python dependencies +├── ui/ +│ ├── Dockerfile # UI container image +│ └── review/ # Review UI templates +├── src/ +│ ├── main.py # Worker entry point +│ ├── db_connector.py # Database connection layer +│ ├── config_loader.py # Configuration management +│ ├── logging_config.py # Logging setup +│ ├── scanner.py # Directory scanner (STORY-02) +│ ├── prober.py # Video probing (STORY-02) +│ ├── frame_sampler.py # Frame extraction (STORY-03) +│ ├── face_detector.py # Face detection (STORY-04) +│ ├── classifier.py # Classification (STORY-05) +│ ├── aggregator.py # Confidence aggregation (STORY-05) +│ ├── router.py # Threshold routing (STORY-05) +│ ├── result_updater.py # Result persistence (STORY-06) +│ ├── data_export.py # Parquet/JSONL export (STORY-06) +│ ├── review_api.py # Review API (STORY-07) +│ ├── active_learning/ # Active learning pipeline (STORY-08) +│ │ ├── label_ingestor.py +│ │ ├── trainer.py +│ │ ├── validator.py +│ │ └── registry.py +│ ├── metrics.py # Prometheus metrics (STORY-09) +│ ├── crash_recovery.py # Crash recovery (STORY-09) +│ └── drift_detector.py # Drift detection (STORY-09) +├── monitoring/ +│ ├── prometheus/ +│ │ └── prometheus.yml # Prometheus config +│ └── grafana/ +│ ├── dashboards/ # Grafana dashboard JSONs +│ └── provisioning/ # Grafana data source config +├── STORY-01.md through STORY-09.md # Implementation stories +├── Plan.md # Implementation plan +└── Requirements.md # Requirements document +``` + +## Implementation Stories + +| Story | Description | Sprint | Points | +|-------|-------------|--------|--------| +| STORY-01 | Foundation & Infrastructure | 1-2 | 13 | +| STORY-02 | Core Ingestion & Codec Handling | 3-4 | 21 | +| STORY-03 | Frame Sampling | 5 | 13 | +| STORY-04 | Face Detection | 5-6 | 21 | +| STORY-05 | Classification & Confidence | 5-6 | 21 | +| STORY-06 | Results Persistence & Export | 5-6 | 13 | +| STORY-07 | Review Interface | 7 | 21 | +| STORY-08 | Active Learning Pipeline | 7-8 | 34 | +| STORY-09 | Observability & Hardening | 9+ | 34 | + +## Hardware Requirements + +- **GPUs:** 2× Tesla P40 24GB (compute capability 5.2) +- **CUDA:** ≤ 11.8 +- **PyTorch:** ≤ 2.1.0 +- **Inference:** FP32 only (no Tensor Cores) +- **Storage:** NVMe/SSD for scratch, NAS/SMB for input/output +- **RAM:** ≥ 32GB system RAM + +## Key Design Decisions + +1. **TensorRT FP32 only** — Tesla P40 has no Tensor Cores; FP16 would not provide benefit +2. **YOLOv8n + MobileNetV3** — Lightweight models optimized for throughput over accuracy +3. **Max aggregation** — Most conservative confidence strategy; use highest frame confidence +4. **Temperature scaling** — Calibrates confidence scores without retraining +5. **Head-only fine-tuning** — Faster retraining with frozen backbone +6. **Parquet export** — Efficient columnar format for analytics +7. **No auth/SSL** — Per TC-06, internal LAN only + +## License + +Proprietary — VideoDetect Project diff --git a/Requirements.md b/Requirements.md new file mode 100644 index 0000000..6131195 --- /dev/null +++ b/Requirements.md @@ -0,0 +1,182 @@ +# Video Classification System: Requirements Document +**Version:** 1.2 +**Author:** AI Architecture Consultant +**Target Audience:** Engineering Leads, ML Engineers, DevOps, Product/Project Managers +**Purpose:** Define functional, technical, and operational requirements to drive implementation story creation and +sprint planning. + +--- + +## 1. System Overview & Objectives +The system processes a large corpus of video files (~30TB) as a local background batch job to classify each video into two +categories: +- `MATCH`: Video contains at least one Black male subject +- `NO_MATCH`: Video does not contain the target demographic + +The system prioritizes **throughput and speed** over maximum accuracy, outputs **calibrated confidence scores**, +routes low-confidence results to a **manual review queue**, and supports an **active learning loop** to +incrementally improve model performance using reviewed samples. + +--- + +## 2. Functional Requirements +| ID | Requirement | Priority | Notes | +|----|-------------|----------|-------| +| FR-01 | Configurable frame sampling interval (default: 1 frame per 30 seconds) | P0 | Must support override per +job/batch. Uniform temporal sampling preferred. | +| FR-02 | Face detection on all sampled frames | P0 | Lightweight detector only; no full-body or scene analysis. | +| FR-03 | Binary demographic classification of detected face crops | P0 | Outputs probability `p ∈ [0,1]` for +target class. | +| FR-04 | Video-level confidence aggregation & threshold routing | P0 | Aggregates frame-level scores → video +confidence `C`. Routes to `MATCH`, `REVIEW`, or `SKIP`. | +| FR-05 | Manual review interface for low-confidence videos | P1 | Displays video + contributing frames/crops + +model confidence. Supports binary labeling. | +| FR-06 | Active learning pipeline (label ingestion → fine-tuning → deployment) | P1 | Batch retraining only. No +online learning. Versioned model swaps. | +| FR-07 | Metadata logging & audit trail | P1 | Stores video ID, timestamps, frame counts, confidence scores, +routing decision, model version. | +| FR-08 | Batch job orchestration & crash recovery | P0 | Supports resume, parallel GPU scheduling, and +deterministic IDempotent processing. | +| FR-09 | Directory Scanning & Sync | P0 | Process to scan input directories, detect new/removed files, and sync state to MariaDB. | +| FR-10 | Codec & Resolution Detection & Handling | P0 | Detect video properties; handle unsupported codecs by flagging files as `UNSCANNABLE`. | + +--- + +## 3. Non-Functional Requirements +| ID | Requirement | Target | Notes | +|----|-------------|--------|-------| +| NFR-01 | Throughput | ≥ 30 videos/hour/GPU (≈ 60 videos/hour total) | Baseline; tunable via sampling interval & +batch size. | +| NFR-02 | Latency per video | ≤ 45 seconds end-to-end (15-min avg video) | Excludes I/O bottlenecks; measured at +compute stage. | +| NFR-03 | GPU Memory Safety | ≤ 18GB per GPU sustained | Leaves headroom for OS, queues, and peak allocation. | +| NFR-04 | Determinism & Reproducibility | Config-seeded randomness, versioned models | Enables auditability and +rollback. | +| NFR-05 | Fault Tolerance | Auto-retry on transient failures; skip & log on fatal errors | Prevents batch +poisoning. | +| NFR-06 | Observability | Prometheus/Grafana metrics + structured logging | Tracks FPS, queue depth, confidence +distribution, drift alerts. | +| NFR-07 | Data Volume Handling | Efficient indexing for ~30TB dataset | Metadata stored in MariaDB; file existence verified via hashing/checksums if needed. | +| NFR-08 | Codec Agnosticism | Handle H.264, H.265, VP8, VP9, AV1, MJPEG, etc. | Unsupported codecs flagged gracefully. | + +--- + +## 4. Technical & Environmental Constraints +| ID | Constraint | Details | +|----|------------|---------| +| TC-01 | Hardware | 2× Tesla P40 24GB (compute capability 5.2, PCIe 3.0, **no Tensor Cores**) | +| TC-02 | CUDA/Torch Compatibility | CUDA ≤ 11.8, PyTorch ≤ 2.1.0, FP32 inference only | +| TC-03 | Storage I/O | Fast local NVMe/SSD for temp frame cache; shared NAS/SMB for video input/output. 30TB Capacity. | +| TC-04 | Framework Stack | PyTorch → ONNX → TensorRT FP32; FFmpeg/OpenCV for sampling; **MariaDB** for metadata/state | +| TC-05 | Deployment Model | **Docker Compose** orchestrates all services (Workers, DB, UI). GPUs passed via `nvidia-container-toolkit`. | +| TC-06 | Network Security | Internal LAN only. No reverse proxy, SSL, or auth required for UI. | + +--- + +## 5. Data & Storage Architecture +| Layer | Specification | +|-------|---------------| +| **Input** | Raw video files (MP4, MOV, AVI, MKV) totaling ~30TB. Growth is slow (archival nature). Resolutions: 480p–4K. Codecs: Mixed. | +| **Scratch** | `tmpfs` or fast local SSD for extracted frames & face crops. Auto-cleaned post-job. | +| **Metadata Store** | **MariaDB** database storing: `file_path`, `file_hash`, `resolution`, `codec`, `last_scan_time`, `last_processed_time`, `model_version_used`, `confidence_score`, `routing_decision`, `status` (OK, UNSCANNABLE, ERROR). | +| **Results** | Parquet/JSON lines exported for analytics: `{video_id, model_version, sample_count, confidence_scores[], video_confidence, routing, processed_at}` | +| **Training Data** | Versioned directory structure: `/data/v1/crops/`, `/data/v1/labels/`. Augmentation pipeline +applied at training time. | +| **Model Registry** | `/models/` with semantic versioning. Active, candidate, and archived states tracked. | + +--- + +## 6. Confidence Scoring & Routing Logic +| Stage | Specification | +|-------|---------------| +| **Frame-Level** | Raw logits → temperature-scaled softmax → calibrated `p_i ∈ [0,1]` | +| **Video-Level** | `C = max(p_i)` OR `C = softmax(α·mean(p_i) + β·var(p_i))` (configurable) | +| **Routing Thresholds** | `C ≥ T_high` → `MATCH`
`T_low ≤ C < T_high` → `REVIEW`
`C < T_low` → `SKIP` +
*(Default: T_high=0.75, T_low=0.45)* | +| **Calibration** | Temperature scaling evaluated on held-out set every training cycle. Stores `T` with model +checkpoint. | +| **Error Handling** | If FFmpeg/OpenCV fails to decode frame or detect codec: Set status to `UNSCANNABLE`. Log error. Do not retry indefinitely. | + +--- + +## 7. Active Learning Pipeline +| Component | Specification | +|-----------|---------------| +| **Review Queue** | Lightweight web UI (Label Studio or custom Flask/FastAPI). Shows video player, top-k +contributing frames, model confidence, label toggle. Accessible via internal IP:Port. | +| **Label Export** | CSV/JSON export with `{video_id, frame_timestamps, crops_paths, ground_truth}` | +| **Fine-Tuning** | Head-only fine-tuning on face crops. 10–30 epochs, AdamW, LR=1e-3, early stopping. Runs on +idle GPU slot or off-peak schedule. | +| **Deployment** | Candidate model validated against held-out set → auto-swap if `ΔF1 > 0.02` & confidence +calibration passes. Rollback on regression. | +| **Drift Monitoring** | Weekly confidence histogram comparison. Alerts if `p(C > 0.5)` shifts >10% or review +queue grows unbounded. | + +--- + +## 8. Acceptance Criteria +| Area | Criteria | +|------|----------| +| **Sampling** | Configurable interval honored ±1 frame; handles variable FPS & codec edge cases. | +| **Inference** | Sustained ≥ 30 videos/hour/GPU at default sampling; GPU RAM ≤ 18GB. | +| **Confidence** | Calibration error (ECE) ≤ 0.08 on validation set; thresholds configurable via YAML/ENV. | +| **Routing** | 100% of videos assigned to exactly one bucket; metadata persisted before cleanup. | +| **Active Learning** | Labeled reviews → fine-tune → model swap → next batch uses new weights. Full loop < 48h. | +| **Reliability** | Batch resumes after crash without reprocessing; idempotent file handling. | +| **Syncing** | Scanning process accurately identifies new, modified, and deleted files in the 30TB corpus relative to DB state. | +| **Codec Handling** | Files with unsupported codecs are marked `UNSCANNABLE` in DB without crashing the batch. | +| **Deployment** | `docker-compose.yml` launches DB, Worker(s), and UI. UI accessible on LAN via standard port. | + +--- + +## 9. Implementation Story Mapping +| Epic | User Story | Acceptance Criteria | Priority | +|------|------------|---------------------|----------| +| **E1: Core Pipeline** | As an engineer, I can configure frame sampling interval and extract frames uniformly. | +FFmpeg/OpenCV extracts frames at interval; handles variable duration; logs frame count. | P0 | +| **E1** | As an engineer, I can run face detection on sampled frames in batch. | YOLOv8n/RetinaFace runs at +320²/416²; batch size auto-tuned to VRAM; outputs crop tensors. | P0 | +| **E1** | I can classify face crops and aggregate video confidence. | MobileNetV3 head outputs +calibrated `p`; aggregation logic configurable; results saved to Parquet. | P0 | +| **E1** | As a system, I can detect video resolution and codec. | FFmpeg probe extracts width, height, codec name. Stored in DB. | P0 | +| **E1** | As a system, I can handle unsupported codecs. | If decoding fails, file marked `UNSCANNABLE`. Error logged. | P0 | +| **E2: Routing & Review** | As an operator, I can route videos based on confidence thresholds. | High→MATCH, +Mid→REVIEW, Low→SKIP; thresholds in config; routing logged. | P0 | +| **E2** | As an annotator, I can view low-confidence videos and label them. | UI shows video + frames; label +saved; export triggers training pipeline. | P1 | +| **E3: Active Learning** | As an ML engineer, I can fine-tune the classifier head with reviewed data. | Dataset +versioned; head-only training; early stopping; ECE validated. | P1 | +| **E3** | As a system, I can swap models safely and roll back on regression. | Model registry with +candidate/active states; auto-validate; rollback script. | P1 | +| **E4: Operations** | As a DevOps, I can schedule, monitor, and resume batch jobs. | Multi-GPU process split; +crash recovery; Prometheus metrics; structured logs. | P0 | +| **E4** | As a lead, I can track confidence drift and review queue health. | Dashboard shows distribution, queue +size, throughput; alerts on thresholds. | P1 | +| **E5: Data Management** | As a system, I can scan directories and sync file state to MariaDB. | Detects new/removed files; updates `last_scan_time`; handles 30TB path space efficiently. | P0 | +| **E6: Infrastructure** | As a DevOps, I can deploy the entire stack via Docker Compose. | `docker-compose.yml` includes DB, Worker, UI. GPU passthrough configured. No SSL/Auth. | P0 | + +--- + +## 10. Assumptions & Open Questions +| Item | Status | +|------|--------| +| Dataset size & growth rate | ✅ ~30TB, slow growth (archival). | +| Video codec/resolution distribution | ✅ Varies 480p–4K. Virtually all codecs present. Unsupported ones flagged. | +| Review annotation bandwidth | ❓ Determines acceptable queue backlog & SLA | +| Retraining frequency preference | ❓ Nightly, weekly, or queue-depth triggered? | +| UI deployment environment | ✅ Internal LAN only. No security/SSL needed. Docker Compose managed. | +| Legal/ethics sign-off | ✅ Assumed handled per prompt; document retention policy still needed | + +--- + +## Next Steps +1. **Stakeholder Review**: Validate thresholds, throughput targets, and review workflow. +2. **Sprint 0 Setup**: Provision Docker env, install CUDA 11.8 + PyTorch 2.0.1, set up MariaDB schema & temp storage. Configure GPU passthrough in `docker-compose`. +3. **MVP Build**: Implement E1 stories → baseline throughput & confidence pipeline. +4. **Calibration & Routing**: Add ECE scaling, threshold routing, metadata persistence. +5. **Review & Active Learning**: Deploy UI, wiring label export → fine-tune → model swap. +6. **Data Syncing**: Implement directory scanner (E5) to maintain MariaDB state against 30TB filesystem. +7. **Hardening**: Multi-GPU scheduling, crash recovery, monitoring, drift alerts. + +Let me know if you want this exported as a Confluence/Markdown template, or if you'd like detailed technical specs +for any specific story (e.g., FFmpeg sampling logic, TensorRT export pipeline, or Label Studio integration schema). \ No newline at end of file diff --git a/STORY-01.md b/STORY-01.md new file mode 100644 index 0000000..c9f99aa --- /dev/null +++ b/STORY-01.md @@ -0,0 +1,170 @@ +# STORY-01: Foundation & Infrastructure + +## Epic +**E6: Infrastructure** — As a DevOps engineer, I can deploy the entire stack via Docker Compose. + +## Related Requirements +| ID | Requirement | +|----|-------------| +| TC-01 | Hardware: 2× Tesla P40 24GB (compute capability 5.2, PCIe 3.0, no Tensor Cores) | +| TC-02 | CUDA/Torch Compatibility: CUDA ≤ 11.8, PyTorch ≤ 2.1.0, FP32 inference only | +| TC-03 | Storage I/O: Fast local NVMe/SSD for temp frame cache; shared NAS/SMB for video input/output | +| TC-04 | Framework Stack: PyTorch → ONNX → TensorRT FP32; FFmpeg/OpenCV; MariaDB | +| TC-05 | Deployment Model: Docker Compose orchestrates all services; GPUs passed via nvidia-container-toolkit | +| TC-06 | Network Security: Internal LAN only; no reverse proxy, SSL, or auth | +| NFR-04 | Determinism & Reproducibility: Config-seeded randomness, versioned models | + +## Description +Establish the Docker environment, database schema, and basic connectivity. No video processing logic yet — just the operational skeleton that all subsequent stories depend on. + +## Scope + +### In Scope +- Docker Compose multi-service orchestration +- Custom Worker Dockerfile with CUDA 11.8 + PyTorch 2.1.0 + TensorRT FP32 +- MariaDB schema design and migration scripts +- Volume mounts for NVMe scratch, NAS input/output, and model persistence +- Configuration management (config.yaml + environment variables) +- Structured logging setup (JSON format to stdout) +- Database connection layer with connection pooling +- Network connectivity verification between all services + +### Out of Scope +- Video processing logic (covered in STORY-02 through STORY-05) +- Model loading or inference (covered in STORY-04) +- Review UI functionality (covered in STORY-06) +- Monitoring dashboards (covered in STORY-08) +- Active learning pipeline (covered in STORY-07) + +## Deliverables + +### 1.1 Docker Compose Structure +**File:** `docker-compose.yml` + +Services defined: +- `mariadb`: MariaDB 10.11+ with persistent volume +- `worker`: PyTorch/TensorRT inference worker with GPU passthrough +- `ui`: Placeholder service (nginx serving static page) for network verification + +Key configurations: +- `nvidia-container-toolkit` runtime configuration for GPU passthrough +- Volume mounts: + - NVMe → `/scratch` (tmpfs for speed) + - NAS/SMB → `/data/input` and `/data/output` + - Persistent → `/models` and `/data/training` +- Network bridge for inter-service communication +- Resource limits (GPU memory caps per NFR-03) + +### 1.2 Worker Dockerfile +**File:** `worker/Dockerfile` + +Base image: `nvidia/cuda:11.8.0-runtime-ubuntu22.04` + +Installed packages: +- PyTorch 2.1.0 (CUDA 11.8, FP32 only) +- TensorRT 8.6+ (FP32) +- OpenCV 4.8+ +- FFmpeg 5.x + ffprobe +- ONNX Runtime +- Python 3.10+ +- Required system libraries (libcudnn8, libglib2.0, etc.) + +### 1.3 Database Schema +**File:** `db/schema.sql` + +Tables: +- `videos`: `id` (BIGINT PK), `file_path` (VARCHAR), `file_hash` (CHAR(64)), `resolution_w` (INT), `resolution_h` (INT), `codec` (VARCHAR), `duration` (FLOAT), `status` (ENUM: NEW, PENDING, PROCESSING, COMPLETED, UNSCANNABLE, ERROR), `last_scan_time` (DATETIME), `last_processed_time` (DATETIME), `created_at` (DATETIME), `updated_at` (DATETIME) +- `processing_logs`: `id` (BIGINT PK), `video_id` (BIGINT FK), `model_version` (VARCHAR), `frame_count` (INT), `confidence_score` (FLOAT), `routing_decision` (ENUM: MATCH, REVIEW, SKIP), `processed_at` (DATETIME), `error_message` (TEXT) +- `models`: `version` (VARCHAR PK), `status` (ENUM: ACTIVE, CANDIDATE, ARCHIVED), `path` (VARCHAR), `calibration_temp` (FLOAT), `f1_score` (FLOAT), `ece_score` (FLOAT), `deployed_at` (DATETIME), `created_at` (DATETIME) +- `review_queue`: `id` (BIGINT PK), `video_id` (BIGINT FK), `confidence_score` (FLOAT), `routing_decision` (ENUM: REVIEW), `annotated` (BOOLEAN), `ground_truth` (BOOLEAN), `annotated_at` (DATETIME), `created_at` (DATETIME) + +Indexes: +- `idx_videos_status` on `videos(status)` +- `idx_videos_file_hash` on `videos(file_hash)` (UNIQUE) +- `idx_videos_last_scan` on `videos(last_scan_time)` +- `idx_processing_logs_video` on `processing_logs(video_id)` +- `idx_models_status` on `models(status)` +- `idx_review_queue_annotated` on `review_queue(annotated)` + +### 1.4 Database Connection Layer +**File:** `src/db_connector.py` + +Features: +- Connection pooling (DBUtils + PyMySQL) +- Configurable pool size (min=5, max=20) +- Automatic reconnection on disconnect +- Context manager support +- Prepared statements for all queries +- Transaction support for atomic state transitions + +### 1.5 Configuration Management +**File:** `config.yaml` + +Contents: +- `sampling`: `interval_seconds: 30`, `override_per_job: true` +- `thresholds`: `T_high: 0.75`, `T_low: 0.45` +- `gpu`: `max_memory_gb: 18`, `batch_size: auto`, `device: cuda` +- `storage`: `scratch_path: /scratch`, `input_path: /data/input`, `output_path: /data/output` +- `database`: `host: mariadb`, `port: 3306`, `pool_size: 20` +- `logging`: `format: json`, `level: INFO` +- `model`: `face_detector: yolo8n`, `classifier: mobilenetv3`, `input_size: 224` + +**File:** `src/config_loader.py` + +Features: +- Load config.yaml with environment variable overrides +- Validate all required fields +- Provide typed accessors (e.g., `config.thresholds.T_high`) +- Hot-reload support for config changes + +### 1.6 Logging Setup +**File:** `src/logging_config.py` + +- JSON structured logging via `python-json-logger` +- Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL +- Fields: timestamp, level, service, video_id, message, metadata (key-value pairs) +- Log rotation: 100MB per file, 10 files max +- All logs to stdout for Docker capture + +## Acceptance Criteria + +### Functional +- [ ] `docker-compose up` starts MariaDB, Worker, and UI containers successfully +- [ ] Worker container can connect to MariaDB and execute schema migrations +- [ ] GPU is visible inside Worker container (`nvidia-smi` shows Tesla P40) +- [ ] Volume mounts are accessible and writable in all containers +- [ ] Config.yaml loads correctly with all required fields validated +- [ ] Structured logging produces valid JSON output in all services +- [ ] Database connection pool handles concurrent connections (test with 20 simultaneous) + +### Non-Functional +- [ ] Worker container starts within 30 seconds +- [ ] MariaDB starts within 15 seconds +- [ ] GPU memory usage in Worker is < 2GB at idle (before model loading) +- [ ] All services communicate over Docker internal network (no host network exposure except UI port) +- [ ] Schema migration is idempotent (running twice produces same result) + +### Technical Constraints +- [ ] CUDA version in Worker is 11.8 (verified via `torch.version.cuda`) +- [ ] PyTorch version ≤ 2.1.0 (verified via `torch.__version__`) +- [ ] TensorRT runs in FP32 mode only +- [ ] No Tensor Cores used (compute capability 5.2 constraint respected) +- [ ] No SSL, auth, or reverse proxy configured (TC-06) + +## Dependencies +- **Prerequisites:** NVIDIA Container Toolkit installed on host, Docker Compose v2+, NAS/SMB mounts configured +- **Depends on:** None (this is the foundational story) +- **Enables:** STORY-02 (Ingestion), STORY-03 (Orchestration), STORY-04 (Inference), STORY-05 (Results), STORY-06 (Review UI), STORY-07 (Active Learning), STORY-08 (Monitoring) + +## Risks & Mitigations +| Risk | Mitigation | +|------|-----------| +| Tesla P40 (CC 5.2) incompatible with newer TensorRT | Use TensorRT 8.6 which supports CC 5.x; test early | +| CUDA 11.8 + PyTorch 2.1.0 dependency conflicts | Pin all versions in Dockerfile; use nvidia base image | +| NAS/SMB mount latency affects processing | Use local tmpfs for scratch; only read from NAS | +| MariaDB connection pool exhaustion | Monitor pool metrics; tune pool_size based on worker count | + +## Estimated Effort +- **Sprint:** 1-2 +- **Story Points:** 13 +- **Dependencies:** None diff --git a/STORY-02.md b/STORY-02.md new file mode 100644 index 0000000..c43547f --- /dev/null +++ b/STORY-02.md @@ -0,0 +1,182 @@ +# STORY-02: Core Ingestion & Codec Handling + +## Epic +**E5: Data Management** — As a system, I can scan directories and sync file state to MariaDB. +**E1: Core Pipeline** — As a system, I can detect video resolution and codec. + +## Related Requirements +| ID | Requirement | +|----|---------| +| FR-09 | Directory Scanning & Sync: Process to scan input directories, detect new/removed files, and sync state to MariaDB | +| FR-10 | Codec & Resolution Detection & Handling: Detect video properties; handle unsupported codecs by flagging files as UNSCANNABLE | +| NFR-07 | Data Volume Handling: Efficient indexing for ~30TB dataset | +| NFR-08 | Codec Agnosticism: Handle H.264, H.265, VP8, VP9, AV1, MJPEG, etc. | +| NFR-05 | Fault Tolerance: Auto-retry on transient failures; skip & log on fatal errors | + +## Description +Implement the directory scanner, video probing, and robust error handling for codecs and resolutions. This story enables the system to discover new files in the 30TB corpus, extract their metadata, validate codec support, and maintain accurate database state. + +## Scope + +### In Scope +- Background directory scanner service that walks `/data/input` +- File detection and deduplication via SHA-256 hashing +- Video probing via ffprobe (codec, resolution, duration) +- Codec whitelist/blacklist validation +- UNSCANNABLE status for unsupported or corrupt files +- Priority queue / DB-based locking for job assignment +- Atomic state transitions (PENDING → PROCESSING) +- Efficient handling of 30TB directory structure (incremental scanning) + +### Out of Scope +- Frame extraction (covered in STORY-04) +- Face detection and classification (covered in STORY-04) +- Confidence scoring and routing (covered in STORY-05) +- Review UI (covered in STORY-06) +- Active learning pipeline (covered in STORY-07) +- Monitoring dashboards (covered in STORY-08) + +## Deliverables + +### 2.1 Directory Scanner Service +**File:** `src/scanner.py` + +Core components: +- **Walker:** Recursive directory walker with configurable depth and path filters +- **Incremental Sync:** Compare current filesystem state against DB `last_scan_time` — only process new/modified files +- **File Detection:** Identify files not in DB or with status NEW/PENDING +- **Hash Computation:** SHA-256 of first 1MB (or full file if < 1MB) for deduplication +- **Scan Scheduler:** Configurable interval (default: every 60 seconds) via cron-like scheduler +- **Concurrency:** Multi-threaded walker with configurable worker count (default: 8 threads) +- **Error Handling:** Per-file error isolation — scanner continues on individual file failures + +Key behaviors: +- On scan start: query DB for files with `last_scan_time < now()` or `status IN ('NEW', 'PENDING')` +- For each file: compute hash → check DB for duplicate → if new, insert with status PENDING +- For removed files: mark as REMOVED in DB (optional, configurable) +- Update `last_scan_time` on `videos` table after successful scan + +### 2.2 Video Probing Module +**File:** `src/prober.py` + +Features: +- **ffprobe wrapper:** Execute ffprobe with optimized arguments for speed + ```bash + ffprobe -v error -select_streams v:0 -show_entries stream=codec_name,width,height,duration,r_frame_rate -show_entries format=duration -of json + ``` +- **Metadata extraction:** Parse JSON output for: + - `codec_name`: Video codec identifier + - `width`, `height`: Resolution + - `duration`: Video duration in seconds + - `r_frame_rate`: Frame rate (for sampling calculations) +- **Error handling:** Catch ffprobe failures (corrupt files, unsupported formats) +- **Timeout:** ffprobe execution limited to 10 seconds per file + +### 2.3 Codec Validation +**File:** `src/codec_validator.py` + +Codec whitelist (supported): +- H.264 (avc1) +- H.265 (hevc) +- VP8 (vp8) +- VP9 (vp9) +- AV1 (av01) +- MJPEG (mjpeg) +- MPEG-4 (mp4v) + +Codec blacklist (unsupported): +- Theora +- DivX/Xvid (legacy) +- ProRes (requires special handling) +- Any codec not in whitelist + +Behavior: +- If codec not in whitelist → set status UNSCANNABLE, log reason +- If ffprobe fails → set status UNSCANNABLE, log error code +- If file is not a valid video → set status UNSCANNABLE, log reason +- UNSCANNABLE files are excluded from processing pipeline + +### 2.4 Batch Orchestration Skeleton +**File:** `src/orchestrator.py` + +Components: +- **Job Queue:** Priority queue based on file modification time (newest first) +- **DB-based Locking:** Atomic state transition using UPDATE ... WHERE status = 'PENDING' +- **Worker Pool:** Configurable number of worker processes (default: 2, one per GPU) +- **State Machine:** + ``` + NEW → PENDING → PROCESSING → COMPLETED + → UNSCANNABLE + → ERROR + ``` +- **Concurrency Control:** Max concurrent processing per GPU (default: 1 video at a time per worker) +- **Idempotency:** Re-processing a file does not duplicate DB entries or outputs + +### 2.5 Configuration Updates +**File:** `config.yaml` (updates to STORY-01) + +New fields: +```yaml +scanner: + scan_interval_seconds: 60 + walker_threads: 8 + ffprobe_timeout_seconds: 10 + hash_algorithm: sha256 + hash_chunk_size_mb: 1 + +codec: + whitelist: [avc1, hevc, vp8, vp9, av01, mjpeg, mp4v] + default_status_on_error: UNSCANNABLE + +queue: + priority: modification_time # newest first + max_concurrent_per_gpu: 1 + lock_timeout_seconds: 300 +``` + +## Acceptance Criteria + +### Functional +- [ ] New files in `/data/input` appear in DB with correct metadata within 60 seconds of placement +- [ ] File hash deduplication prevents re-processing identical files +- [ ] ffprobe correctly extracts codec, resolution, and duration for all supported codecs +- [ ] Unsupported codec files are marked UNSCANNABLE without crashing the scanner +- [ ] Corrupt/unreadable files are marked UNSCANNABLE with appropriate error logged +- [ ] Atomic state transitions: PENDING → PROCESSING succeeds only once (no duplicate processing) +- [ ] Removed files are detected and marked REMOVED (if configured) +- [ ] Scanner handles 30TB directory structure without OOM (memory < 500MB during scan) +- [ ] Re-running scanner is idempotent — no duplicate entries or states + +### Non-Functional +- [ ] Scanner completes full 30TB directory walk in < 4 hours (incremental: < 10 minutes for typical day) +- [ ] ffprobe timeout (10s) is enforced — does not hang on corrupt files +- [ ] Scanner memory usage stays < 500MB regardless of directory depth +- [ ] Hash computation for 100MB file completes in < 5 seconds on NVMe +- [ ] Worker pool respects GPU count (2 workers for 2 GPUs) + +### Technical Constraints +- [ ] SHA-256 hash is deterministic and reproducible +- [ ] Codec detection matches ffprobe output exactly +- [ ] Resolution stored as integers (width, height) +- [ ] Duration stored as float (seconds) +- [ ] All scanner errors are logged with video_id, error_code, and file_path +- [ ] Scanner does not modify video files (read-only operation) + +## Dependencies +- **Prerequisites:** STORY-01 (Foundation & Infrastructure) — DB schema, connection layer, config +- **Depends on:** None (runs in parallel with STORY-03 if needed) +- **Enables:** STORY-04 (Inference Pipeline), STORY-05 (Results & Export) + +## Risks & Mitigations +| Risk | Mitigation | +|------|--| +| 30TB directory walk is extremely slow | Incremental scanning using last_scan_time; only walk new directories | +| ffprobe hangs on corrupt files | Enforce 10-second timeout via subprocess timeout | +| Hash computation on slow NAS is bottleneck | Hash only first 1MB; full hash optional for verification | +| Concurrent scanner + worker conflicts | DB-based locking; scanner only writes PENDING, workers read PENDING | +| Network mount latency | Cache directory listings; batch DB operations | + +## Estimated Effort +- **Sprint:** 3-4 +- **Story Points:** 21 +- **Dependencies:** STORY-01 diff --git a/STORY-03.md b/STORY-03.md new file mode 100644 index 0000000..ea9fcaa --- /dev/null +++ b/STORY-03.md @@ -0,0 +1,152 @@ +# STORY-03: Frame Sampling + +## Epic +**E1: Core Pipeline** — As an engineer, I can configure frame sampling interval and extract frames uniformly. + +## Related Requirements +| ID | Requirement | +|----|---------| +| FR-01 | Configurable frame sampling interval (default: 1 frame per 30 seconds); Must support override per job/batch; Uniform temporal sampling preferred | +| NFR-02 | Latency per video: ≤ 45 seconds end-to-end (15-min avg video) | +| NFR-03 | GPU Memory Safety: ≤ 18GB per GPU sustained | +| NFR-05 | Fault Tolerance: Auto-retry on transient failures; skip & log on fatal errors | +| TC-03 | Storage I/O: Fast local NVMe/SSD for temp frame cache | + +## Description +Implement frame extraction from processed videos using FFmpeg/OpenCV. Extract one frame per configurable interval (default: 30 seconds) uniformly across the video duration. Handle variable FPS, high-resolution frames, and manage scratch space efficiently. + +## Scope + +### In Scope +- Uniform temporal frame sampling via FFmpeg `-ss` timestamp extraction +- Configurable sampling interval (default: 30 seconds, override per job) +- Variable FPS handling (calculate correct timestamps) +- Frame extraction to JPEG format for storage efficiency +- Scratch space management (NVMe tmpfs with auto-cleanup) +- High-resolution frame handling (downscale 4K to fit VRAM constraints) +- Frame naming convention: `{video_id}_{timestamp}.jpg` +- Memory management (delete frames after processing) + +### Out of Scope +- Face detection (covered in STORY-04) +- Classification (covered in STORY-05) +- Confidence scoring (covered in STORY-05) +- Results export (covered in STORY-06) +- Review UI (covered in STORY-07) + +## Deliverables + +### 3.1 Frame Sampler Module +**File:** `src/frame_sampler.py` + +Core functionality: +- **Timestamp Calculator:** Compute uniform sampling timestamps + ```python + def calculate_timestamps(duration, interval): + """Return list of timestamps for frame extraction.""" + count = max(1, int(duration / interval)) + step = duration / count + return [i * step for i in range(count)] + ``` +- **FFmpeg Extraction:** Extract frames at computed timestamps + ```bash + ffmpeg -ss {timestamp} -i {video_path} -vframes 1 -q:v 2 -f jpeg {output_path} + ``` +- **Variable FPS Handling:** Adjust timestamps for videos with variable frame rates +- **Quality Control:** JPEG quality factor 2 (high quality, reasonable size) +- **Error Handling:** Per-frame error isolation — skip failed frames, log errors, continue + +### 3.2 Resolution Handling +**File:** `src/frame_sampler.py` (resolution handling section) + +Features: +- **Resolution Detection:** Use metadata from prober (STORY-02) +- **Downscale Logic:** Auto-downscale frames > 1080p to fit VRAM + - 4K (3840x2160) → 1080p (1920x1080) + - 2K (2560x1440) → 720p (1280x720) + - ≤ 1080p → no change +- **FFmpeg Scale Filter:** Apply during extraction + ```bash + ffmpeg -ss {ts} -i {video} -vf "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2" -vframes 1 -q:v 2 -f jpeg {output} + ``` +- **Aspect Ratio Preservation:** Letterbox/pillarbox to maintain original aspect ratio + +### 3.3 Scratch Space Management +**File:** `src/scratch_manager.py` + +Features: +- **Directory Structure:** `/scratch/{video_id}/frames/` for each video +- **Naming Convention:** `{video_id}_{timestamp_ms}.jpg` +- **Auto-Cleanup:** Delete all frames after video processing completes +- **Space Monitoring:** Alert if scratch usage exceeds 80% of tmpfs capacity +- **Cleanup on Error:** Ensure frames are cleaned up even if processing fails +- **Concurrent Access:** Per-video directory isolation (no conflicts between workers) + +### 3.4 Configuration Updates +**File:** `config.yaml` (updates to STORY-01/02) + +New fields: +```yaml +sampling: + interval_seconds: 30 + override_per_job: true + quality: 2 # JPEG quality (1-31, lower=better) + format: jpeg + +resolution: + max_height: 1080 + preserve_aspect_ratio: true + pad_to_square: false # Will be done in face detection if needed + +scratch: + path: /scratch + max_usage_percent: 80 + auto_cleanup: true + cleanup_on_error: true +``` + +## Acceptance Criteria + +### Functional +- [ ] Frames are extracted at uniform intervals (±1 frame tolerance) across video duration +- [ ] Default interval of 30 seconds produces correct number of frames for test videos +- [ ] Per-job interval override works (e.g., 10-second interval for specific videos) +- [ ] Variable FPS videos produce evenly spaced timestamps (not evenly spaced frames) +- [ ] 4K frames are downsampled to 1080p without crashing +- [ ] Aspect ratio is preserved during downscaling (no distortion) +- [ ] Frames are saved as high-quality JPEGs (quality factor 2) +- [ ] Frame naming follows convention: `{video_id}_{timestamp_ms}.jpg` +- [ ] Scratch space is cleaned up after video processing (no leftover frames) +- [ ] Failed frame extraction does not stop processing of other frames + +### Non-Functional +- [ ] Frame extraction for a 15-minute video completes in < 10 seconds on NVMe +- [ ] Scratch space usage per video < 50MB (typical case) +- [ ] Memory usage during extraction < 500MB per worker +- [ ] FFmpeg process timeout enforced (30 seconds per frame) +- [ ] No frames left in scratch after processing completes (verified by directory check) + +### Technical Constraints +- [ ] FFmpeg uses `-ss` for accurate timestamp seeking (not frame-by-frame) +- [ ] Downscaling uses FFmpeg scale filter (not post-processing resize) +- [ ] JPEG quality is consistent across all extracted frames +- [ ] Timestamps are in seconds with millisecond precision +- [ ] Scratch directory is created per-video and isolated from other workers + +## Dependencies +- **Prerequisites:** STORY-01 (Foundation), STORY-02 (Ingestion — provides metadata) +- **Depends on:** None (runs after ingestion, before STORY-04) +- **Enables:** STORY-04 (Face Detection — provides frames), STORY-05 (Classification) + +## Risks & Mitigations +| Risk | Mitigation | +|------|--| +| FFmpeg seeking is inaccurate for some codecs | Use `-accurate_seek` flag; fall back to frame-by-frame if needed | +| 4K downscaling increases processing time | Use FFmpeg scale filter (GPU-accelerated if available) | +| Scratch space fills up with many concurrent videos | Monitor usage; implement cleanup queue; alert at 80% | +| Variable FPS causes uneven frame distribution | Calculate timestamps based on duration, not frame count | + +## Estimated Effort +- **Sprint:** 5 (first half) +- **Story Points:** 13 +- **Dependencies:** STORY-01, STORY-02 diff --git a/STORY-04.md b/STORY-04.md new file mode 100644 index 0000000..a624228 --- /dev/null +++ b/STORY-04.md @@ -0,0 +1,168 @@ +# STORY-04: Face Detection + +## Epic +**E1: Core Pipeline** — As an engineer, I can run face detection on sampled frames in batch. + +## Related Requirements +| ID | Requirement | +|----|-------| +| FR-02 | Face detection on all sampled frames: Lightweight detector only; no full-body or scene analysis | +| NFR-03 | GPU Memory Safety: ≤ 18GB per GPU sustained | +| NFR-01 | Throughput: ≥ 30 videos/hour/GPU | +| TC-01 | Hardware: 2× Tesla P40 24GB (compute capability 5.2, PCIe 3.0, no Tensor Cores) | +| TC-02 | CUDA/Torch Compatibility: CUDA ≤ 11.8, PyTorch ≤ 2.1.0, FP32 inference only | +| TC-04 | Framework Stack: PyTorch → ONNX → TensorRT FP32 | + +## Description +Implement face detection on all sampled frames using a lightweight detector (YOLOv8n or equivalent). Convert the model to ONNX and TensorRT FP32 for inference. Implement dynamic batching to maximize GPU utilization while staying within VRAM constraints. Generate face crops for classification. + +## Scope + +### In Scope +- YOLOv8n face detection model (or equivalent lightweight detector) +- ONNX export and TensorRT FP32 engine conversion +- Dynamic batching for face detection inference +- Face crop extraction and resizing to inference input size (224×224) +- GPU memory management (stay within 18GB per GPU) +- Batch size auto-tuning based on available VRAM +- Face bounding box output with confidence scores +- Handling frames with no detected faces + +### Out of Scope +- Frame sampling (covered in STORY-03) +- Demographic classification (covered in STORY-05) +- Confidence aggregation (covered in STORY-05) +- Results export (covered in STORY-06) +- Review UI (covered in STORY-07) + +## Deliverables + +### 4.1 Face Detection Model +**File:** `models/face_detector/` + +Components: +- **Source Model:** YOLOv8n (Ultralytics) trained on face detection dataset (WIDER Face or equivalent) +- **ONNX Export:** `face_detector.onnx` with proper input/output shapes + - Input: `[1, 3, 640, 640]` (RGB, BGR depending on model) + - Output: `[1, num_anchors, 4+1]` (bbox coordinates + confidence) +- **TensorRT Engine:** `face_detector.trt` (FP32, built for Tesla P40 CC 5.2) + - Builder config: max_batch_size=32, max_workspace_size=4GB + - Serialization for runtime loading +- **Model Metadata:** `model.json` with input shape, normalization params, calibration data + +### 4.2 Face Detection Runner +**File:** `src/face_detector.py` + +Core components: +- **Model Loader:** Load TensorRT engine at startup + ```python + class FaceDetector: + def __init__(self, engine_path, device='cuda'): + self.engine = load_trt_engine(engine_path) + self.context = self.engine.create_execution_context() + self.input_shape = (1, 3, 640, 640) + self.device = device + ``` +- **Preprocessing:** Convert frame to model input format + - Resize to 640×640 + - Normalize (mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) + - Convert to NHWC/NCHW as required by TensorRT +- **Inference:** Run batched detection on multiple frames + - Dynamic batching: accumulate frames until batch_size reached or timeout + - Execute TensorRT engine + - Parse outputs (bounding boxes + confidence scores) +- **Post-processing:** NMS (Non-Maximum Suppression) to remove duplicate detections + - IoU threshold: 0.45 + - Confidence threshold: 0.25 (low to avoid missing faces) +- **Crop Generation:** Extract face crops from original frames + - Resize crops to 224×224 for classification input + - Save crops to `/scratch/{video_id}/crops/` + +### 4.3 Dynamic Batching +**File:** `src/batcher.py` + +Features: +- **Batch Accumulator:** Collect face detections across frames + - Max batch size: auto-tuned based on available VRAM (start at 16, adjust dynamically) + - Timeout: 100ms (process batch even if not full) +- **VRAM Monitoring:** Track GPU memory usage and adjust batch size + - If VRAM > 16GB: reduce batch size by 25% + - If VRAM < 10GB: increase batch size by 25% +- **Frame Ordering:** Maintain frame-to-batch mapping for correct crop assignment + +### 4.4 GPU Memory Management +**File:** `src/gpu_manager.py` + +Features: +- **Memory Tracking:** Monitor GPU memory usage continuously +- **Peak Allocation:** Ensure total GPU memory < 18GB (leaving 6GB headroom) +- **Cleanup:** Explicitly free TensorRT buffers after each batch +- **Per-Video Limits:** Max faces per video (e.g., 100) to prevent memory issues +- **Fallback:** If VRAM is critically low, reduce batch size and retry + +### 4.5 Configuration Updates +**File:** `config.yaml` (updates) + +New fields: +```yaml +face_detection: + model: yolo8n + model_path: /models/face_detector/face_detector.trt + input_size: 640 + confidence_threshold: 0.25 + iou_threshold: 0.45 + max_faces_per_frame: 10 + max_faces_per_video: 100 + +batching: + max_batch_size: 16 + batch_timeout_ms: 100 + vram_target_gb: 16 + vram_reduce_threshold_gb: 16 + vram_increase_threshold_gb: 10 +``` + +## Acceptance Criteria + +### Functional +- [ ] YOLOv8n model loads and runs inference via TensorRT FP32 +- [ ] Face detection correctly identifies faces in test frames (mAP > 0.50 on WIDER Face val) +- [ ] No faces detected in frames without faces (false positive rate < 5%) +- [ ] Face crops are correctly extracted and resized to 224×224 +- [ ] Dynamic batching works correctly (multiple frames processed in single batch) +- [ ] Batch size adjusts based on available VRAM +- [ ] Frames with no detected faces are handled gracefully (no crashes, no crops generated) +- [ ] NMS correctly removes duplicate detections (IoU > 0.45) +- [ ] Face bounding boxes are accurate (center coordinates within 10 pixels of ground truth) + +### Non-Functional +- [ ] GPU memory usage stays ≤ 18GB per GPU during face detection +- [ ] Face detection for 10 frames (batched) completes in < 2 seconds on Tesla P40 +- [ ] Batch processing throughput: ≥ 50 faces/second/GPU +- [ ] Model loading time < 5 seconds at startup +- [ ] No GPU OOM errors during extended processing + +### Technical Constraints +- [ ] TensorRT engine is FP32 only (no FP16, no INT8) +- [ ] No Tensor Cores used (CC 5.2 constraint) +- [ ] CUDA 11.8 compatible (verified via torch.version.cuda) +- [ ] ONNX model exports without errors (verified via onnx.checker) +- [ ] Face crops are saved in JPEG format at high quality + +## Dependencies +- **Prerequisites:** STORY-01 (Foundation), STORY-03 (Frame Sampling — provides frames) +- **Depends on:** None (runs after frame sampling) +- **Enables:** STORY-05 (Classification — provides face crops) + +## Risks & Mitigations +| Risk | Mitigation | +|------|--| +| Tesla P40 (CC 5.2) has no Tensor Cores — slower inference | Use TensorRT engine caching; maximize batch size to compensate | +| YOLOv8n may be too large for VRAM with classification | Use YOLOv8n (smallest variant); monitor VRAM closely | +| Many faces per frame could cause VRAM spike | Limit max faces per frame; reduce batch size if needed | +| TensorRT engine build time is long | Pre-build engines; cache on disk; skip rebuild if model unchanged | + +## Estimated Effort +- **Sprint:** 5-6 (second half) +- **Story Points:** 21 +- **Dependencies:** STORY-01, STORY-03 diff --git a/STORY-05.md b/STORY-05.md new file mode 100644 index 0000000..d0ffdb9 --- /dev/null +++ b/STORY-05.md @@ -0,0 +1,187 @@ +# STORY-05: Classification & Confidence Aggregation + +## Epic +**E1: Core Pipeline** — I can classify face crops and aggregate video confidence. + +## Related Requirements +| ID | Requirement | +|----|------| +| FR-03 | Binary demographic classification of detected face crops: Outputs probability p ∈ [0,1] for target class | +| FR-04 | Video-level confidence aggregation & threshold routing: Aggregates frame-level scores → video confidence C; Routes to MATCH, REVIEW, or SKIP | +| NFR-01 | Throughput: ≥ 30 videos/hour/GPU | +| NFR-03 | GPU Memory Safety: ≤ 18GB per GPU sustained | +| NFR-04 | Determinism & Reproducibility: Config-seeded randomness, versioned models | +| TC-01 | Hardware: 2× Tesla P40 24GB (compute capability 5.2, PCIe 3.0, no Tensor Cores) | +| TC-02 | CUDA/Torch Compatibility: CUDA ≤ 11.8, PyTorch ≤ 2.1.0, FP32 inference only | + +## Description +Implement demographic classification of detected face crops using a lightweight classifier (MobileNetV3 or equivalent). Apply temperature scaling for calibrated confidence scores. Aggregate frame-level confidence to video-level confidence using configurable aggregation logic. Route videos to MATCH, REVIEW, or SKIP based on threshold comparison. + +## Scope + +### In Scope +- MobileNetV3 (or equivalent) classification model via TensorRT FP32 +- Temperature scaling for confidence calibration +- Frame-level confidence computation (softmax with temperature) +- Video-level confidence aggregation (max or weighted mean, configurable) +- Threshold-based routing (T_high, T_low) +- Routing decision assignment (MATCH, REVIEW, SKIP) +- Confidence score persistence to DB and output files + +### Out of Scope +- Frame sampling (covered in STORY-03) +- Face detection (covered in STORY-04) +- Results export format (covered in STORY-06) +- Review UI (covered in STORY-07) +- Active learning / model retraining (covered in STORY-08) + +## Deliverables + +### 5.1 Classification Model +**File:** `models/classifier/` + +Components: +- **Source Model:** MobileNetV3-small (or equivalent lightweight classifier) + - Trained on demographic dataset (fairness considerations documented) + - Binary classification: Black male subject (class 1) vs. not (class 0) +- **ONNX Export:** `classifier.onnx` + - Input: `[1, 3, 224, 224]` (RGB, resized face crop) + - Output: `[1, 2]` (logits for class 0 and class 1) +- **TensorRT Engine:** `classifier.trt` (FP32) + - Builder config: max_batch_size=32, max_workspace_size=2GB +- **Calibration Data:** Temperature parameter T stored with model +- **Model Metadata:** `model.json` with architecture, training dataset, validation metrics + +### 5.2 Classification Runner +**File:** `src/classifier.py` + +Core components: +- **Model Loader:** Load TensorRT engine at startup + ```python + class FaceClassifier: + def __init__(self, engine_path, temperature=1.0, device='cuda'): + self.engine = load_trt_engine(engine_path) + self.context = self.engine.create_execution_context() + self.temperature = temperature + self.input_shape = (1, 3, 224, 224) + ``` +- **Preprocessing:** Convert face crop to model input + - Resize to 224×224 + - Normalize (ImageNet statistics) + - Convert to tensor (NCHW format) +- **Inference:** Run classification on face crops + - Dynamic batching (shared with face detection batcher) + - Execute TensorRT engine + - Get raw logits output +- **Temperature Scaling:** Apply temperature to logits before softmax + ```python + def calibrated_softmax(logits, temperature): + scaled_logits = logits / temperature + return softmax(scaled_logits, axis=-1) + ``` +- **Frame-level Confidence:** Extract probability for target class (class 1) + ```python + p_i = calibrated_probs[:, 1] # probability of target class + ``` + +### 5.3 Confidence Aggregation +**File:** `src/aggregator.py` + +Features: +- **Aggregation Strategies (configurable):** + 1. **Max:** `C = max(p_i)` — use highest confidence frame + 2. **Weighted Mean:** `C = softmax(α·mean(p_i) + β·var(p_i))` + 3. **Top-K Mean:** `C = mean(top_k(p_i))` — average of top K confidences +- **Default Strategy:** Max (most conservative, aligns with FR-04) +- **Parameter Configuration:** α, β, K configurable in config.yaml +- **Variance Calculation:** Compute variance of frame-level confidences (for uncertainty estimation) + +### 5.4 Threshold Routing +**File:** `src/router.py` + +Features: +- **Threshold Comparison:** + ```python + if C >= T_high: # default 0.75 + routing = 'MATCH' + elif C >= T_low: # default 0.45 + routing = 'REVIEW' + else: + routing = 'SKIP' + ``` +- **Configurable Thresholds:** T_high and T_low in config.yaml +- **Routing Decision Logging:** Log routing decision with confidence score +- **Edge Case Handling:** + - No faces detected → routing = SKIP (with confidence = 0.0) + - All frames have same confidence → routing based on threshold comparison + - Confidence exactly at threshold → use >= comparison (inclusive) + +### 5.5 Configuration Updates +**File:** `config.yaml` (updates) + +New fields: +```yaml +classifier: + model: mobilenetv3-small + model_path: /models/classifier/classifier.trt + input_size: 224 + temperature: 1.0 # calibration temperature + default_strategy: max # max, weighted_mean, top_k_mean + +aggregation: + strategy: max + alpha: 1.0 # for weighted_mean + beta: 0.1 # for weighted_mean + top_k: 3 # for top_k_mean + +routing: + T_high: 0.75 + T_low: 0.45 + no_faces_decision: SKIP +``` + +## Acceptance Criteria + +### Functional +- [ ] MobileNetV3 model loads and runs inference via TensorRT FP32 +- [ ] Classification outputs calibrated probability p ∈ [0,1] for target class +- [ ] Temperature scaling is applied correctly (verified on test set) +- [ ] Frame-level confidence scores are deterministic (same input → same output) +- [ ] Max aggregation produces C = max(p_i) correctly +- [ ] Weighted mean aggregation produces correct result with configurable α, β +- [ ] Threshold routing assigns exactly one of: MATCH, REVIEW, SKIP +- [ ] Videos with no detected faces are routed to SKIP with confidence 0.0 +- [ ] Confidence exactly at threshold uses >= comparison (inclusive) + +### Non-Functional +- [ ] Classification for 16 face crops (batched) completes in < 1 second on Tesla P40 +- [ ] GPU memory usage stays ≤ 18GB per GPU during classification +- [ ] Aggregation computation is negligible (< 10ms per video) +- [ ] Temperature parameter is stored with model checkpoint +- [ ] All routing decisions are logged with confidence score and threshold values + +### Technical Constraints +- [ ] TensorRT engine is FP32 only +- [ ] No Tensor Cores used (CC 5.2 constraint) +- [ ] CUDA 11.8 compatible +- [ ] ONNX model exports without errors +- [ ] Confidence scores are reproducible (deterministic inference) +- [ ] Aggregation strategy is configurable without code changes + +## Dependencies +- **Prerequisites:** STORY-01 (Foundation), STORY-03 (Frame Sampling), STORY-04 (Face Detection — provides crops) +- **Depends on:** None (runs after face detection) +- **Enables:** STORY-06 (Results Persistence), STORY-07 (Review UI — provides routing decisions) + +## Risks & Mitigations +| Risk | Mitigation | +|------|--| +| Temperature scaling parameters need tuning | Evaluate on held-out calibration set during training cycle | +| Max aggregation may be overly conservative | Offer weighted mean as alternative; allow per-job strategy selection | +| Model bias concerns with demographic classification | Document training dataset; audit fairness metrics; legal review required | +| TensorRT engine build time | Pre-build and cache engines; version control model files | + +## Estimated Effort +- **Sprint:** 5-6 (second half) +- **Story Points:** 21 +- **Dependencies:** STORY-01, STORY-03, STORY-04 diff --git a/STORY-06.md b/STORY-06.md new file mode 100644 index 0000000..a957787 --- /dev/null +++ b/STORY-06.md @@ -0,0 +1,181 @@ +# STORY-06: Results Persistence & Export + +## Epic +**E1: Core Pipeline** — As a system, I can persist processing results and export data for analytics. + +## Related Requirements +| ID | Requirement | +|----|------| +| FR-07 | Metadata logging & audit trail: Stores video ID, timestamps, frame counts, confidence scores, routing decision, model version | +| FR-04 | Video-level confidence aggregation & threshold routing: Results saved to Parquet | +| NFR-05 | Fault Tolerance: Metadata persisted before cleanup | +| NFR-07 | Data Volume Handling: Efficient indexing for ~30TB dataset | +| TC-03 | Storage I/O: Shared NAS/SMB for video input/output | + +## Description +Implement result persistence, metadata logging, and data export. Update the database with processing results, insert processing log entries, and export summary data in Parquet/JSONL format for analytics. Ensure all persistence happens before scratch space cleanup to prevent data loss. + +## Scope + +### In Scope +- Database update for processed videos (status, confidence, routing, timestamps) +- Processing log entry insertion (atomic transaction) +- Parquet/JSONL export to `/data/output` +- Confidence score persistence (frame-level and video-level) +- Model version tracking in DB and export +- Idempotent result persistence (re-processing doesn't duplicate entries) +- Transaction-safe updates (all-or-nothing) + +### Out of Scope +- Frame sampling (covered in STORY-03) +- Face detection (covered in STORY-04) +- Classification (covered in STORY-05) +- Review UI (covered in STORY-07) +- Active learning pipeline (covered in STORY-08) + +## Deliverables + +### 6.1 Result Updater +**File:** `src/result_updater.py` + +Features: +- **Video Record Update:** Update `videos` table with processing results + ```sql + UPDATE videos SET + status = 'COMPLETED', + last_processed_time = NOW(), + confidence_score = %s, + routing_decision = %s, + model_version = %s, + frame_count = %s, + updated_at = NOW() + WHERE id = %s AND status = 'PROCESSING' + ``` +- **Atomic Transaction:** Wrap video update + log insert in single transaction +- **State Guard:** Only update if status is PROCESSING (prevents duplicate processing) +- **Error Handling:** Rollback transaction on any error; re-queue video as PENDING + +### 6.2 Processing Logger +**File:** `src/processing_logger.py` + +Features: +- **Log Entry Insertion:** Insert record into `processing_logs` table + ```python + def insert_processing_log(video_id, model_version, frame_count, + confidence_score, routing_decision): + cursor.execute(""" + INSERT INTO processing_logs + (video_id, model_version, frame_count, confidence_score, + routing_decision, processed_at) + VALUES (%s, %s, %s, %s, %s, NOW()) + """, (video_id, model_version, frame_count, + confidence_score, routing_decision)) + ``` +- **Frame-Level Confidence Storage:** Store all frame-level confidence scores + - Option A: JSON array in processing_logs.confidence_scores (TEXT column) + - Option B: Separate `frame_confidences` table (for large datasets) + - Default: JSON array in processing_logs (simpler, sufficient for typical frame counts) +- **Audit Trail:** All log entries include timestamp, model version, and routing decision + +### 6.3 Data Export +**File:** `src/data_export.py` + +Features: +- **Parquet Export:** Write summary data to Parquet format + ```python + # Schema: + # video_id (int64), file_path (string), file_hash (string), + # model_version (string), sample_count (int32), + # confidence_scores (list), video_confidence (float), + # routing (string), processed_at (timestamp) + ``` +- **JSONL Export:** Alternative line-delimited JSON format for streaming analytics + ```json + {"video_id": 12345, "file_path": "/data/input/video.mp4", + "model_version": "v1.2.0", "sample_count": 8, + "confidence_scores": [0.82, 0.79, 0.85, 0.76, 0.81, 0.83, 0.78, 0.80], + "video_confidence": 0.85, "routing": "MATCH", "processed_at": "2026-08-03T10:30:00Z"} + ``` +- **Output Directory:** `/data/output/{model_version}/` organized by model version +- **File Naming:** `{model_version}_{batch_id}.parquet` and `{model_version}_{batch_id}.jsonl` +- **Batch ID:** Sequential counter or timestamp-based (e.g., `v1.2.0_20260803_103000`) +- **Compression:** Parquet with Snappy compression +- **Export Trigger:** Export after all videos in batch are processed (or periodically) + +### 6.4 Scratch Cleanup +**File:** `src/scratch_manager.py` (cleanup section) + +Features: +- **Post-Processing Cleanup:** Delete all frames and crops after results are persisted +- **Cleanup Order:** Results → Logs → Export → Cleanup (critical ordering) +- **Cleanup Verification:** Verify DB update before deleting scratch files +- **Cleanup on Error:** If persistence fails, do NOT delete scratch (allow retry) +- **Cleanup Logging:** Log cleanup completion with video_id and files removed + +### 6.5 Configuration Updates +**File:** `config.yaml` (updates) + +New fields: +```yaml +results: + persist_before_cleanup: true + transaction_safe: true + state_guard: true # only update PROCESSING → COMPLETED + +export: + format: parquet # parquet, jsonl, or both + output_path: /data/output + compression: snappy + batch_size: 100 # export after N videos + include_frame_confidences: true +``` + +## Acceptance Criteria + +### Functional +- [ ] Video status transitions from PROCESSING to COMPLETED after successful processing +- [ ] Processing log entry is inserted for every processed video +- [ ] Frame-level confidence scores are stored (all p_i values) +- [ ] Video-level confidence score is stored correctly +- [ ] Routing decision is persisted accurately +- [ ] Model version is recorded in both videos and processing_logs tables +- [ ] Parquet export produces valid, readable files with correct schema +- [ ] JSONL export produces valid JSON lines with correct fields +- [ ] Export files are organized by model version in /data/output/ +- [ ] Scratch space is cleaned up after persistence (verified by directory check) +- [ ] Re-processing a video updates existing records (no duplicates) +- [ ] Transaction rollback on error prevents partial state updates + +### Non-Functional +- [ ] Result persistence completes in < 5 seconds per video +- [ ] Parquet export for 100 videos completes in < 10 seconds +- [ ] JSONL export for 100 videos completes in < 10 seconds +- [ ] Export files are valid (verified by parquet.read_table and jsonl parsing) +- [ ] Scratch cleanup frees > 95% of allocated space per video +- [ ] No data loss if worker crashes between processing and persistence (PROCESSING state preserved) + +### Technical Constraints +- [ ] All DB updates use parameterized queries (no SQL injection) +- [ ] Transaction isolation level is READ COMMITTED or higher +- [ ] Parquet files use Snappy compression (not gzip, for speed) +- [ ] JSONL files are UTF-8 encoded +- [ ] Confidence scores are stored with float64 precision +- [ ] Timestamps are in UTC (ISO 8601 format) + +## Dependencies +- **Prerequisites:** STORY-01 (Foundation — DB schema), STORY-05 (Classification — provides results) +- **Depends on:** None (runs after classification) +- **Enables:** STORY-07 (Review UI — provides routing decisions), STORY-08 (Active Learning — provides training data) + +## Risks & Mitigations +| Risk | Mitigation | +|------|--| +| NAS write latency slows export | Batch writes; use local tmpfs for export staging | +| Parquet library compatibility with CUDA container | Test pyarrow in Worker container early; pin version | +| Transaction rollback leaves video in PROCESSING state | DB lock timeout (5 min) prevents permanent lock | +| Scratch cleanup before persistence causes data loss | Enforce ordering: persist → verify → cleanup | + +## Estimated Effort +- **Sprint:** 5-6 (second half) +- **Story Points:** 13 +- **Dependencies:** STORY-01, STORY-05 diff --git a/STORY-07.md b/STORY-07.md new file mode 100644 index 0000000..b26be4b --- /dev/null +++ b/STORY-07.md @@ -0,0 +1,216 @@ +# STORY-07: Review Interface + +## Epic +**E2: Routing & Review** — As an annotator, I can view low-confidence videos and label them. + +## Related Requirements +| ID | Requirement | +|----|------| +| FR-05 | Manual review interface for low-confidence videos: Displays video + contributing frames/crops + model confidence; Supports binary labeling | +| FR-07 | Metadata logging & audit trail: Stores annotated labels for active learning | +| NFR-06 | Observability: Tracks review queue depth | +| TC-06 | Network Security: Internal LAN only; no auth required | + +## Description +Implement a lightweight web-based review interface for annotating low-confidence videos. Display the video player, top-k contributing frames, model confidence scores, and allow annotators to toggle the ground truth label. Support CSV/JSON export of annotated data for active learning. + +## Scope + +### In Scope +- Lightweight web UI (Flask/FastAPI) serving on internal LAN +- Query DB for videos with routing_decision = REVIEW +- Video player with playback controls +- Display top-k contributing frames (highest confidence frames) +- Display model confidence scores per frame +- Binary label toggle (True/False — target class present or not) +- Label persistence to DB (review_queue table) +- CSV/JSON export of annotated data with ground truth +- Accessible via internal IP:Port (no auth, no SSL) + +### Out of Scope +- Frame sampling (covered in STORY-03) +- Face detection (covered in STORY-04) +- Classification (covered in STORY-05) +- Confidence aggregation (covered in STORY-05) +- Active learning pipeline / model retraining (covered in STORY-08) +- Monitoring dashboards (covered in STORY-09) + +## Deliverables + +### 7.1 Review Backend +**File:** `src/review_api.py` + +API Endpoints: +- `GET /api/review/queue` — List videos in review queue + - Query: `SELECT * FROM review_queue WHERE annotated = false ORDER BY created_at DESC` + - Pagination: 20 items per page + - Response: `{videos: [...], total: N, page: P, per_page: 20}` +- `GET /api/review/{video_id}` — Get video details for annotation + - Response: `{video_id, file_path, confidence_score, routing_decision, model_version, frame_count, contributing_frames: [{timestamp, crop_path, confidence}], video_duration}` +- `POST /api/review/{video_id}/label` — Submit annotation + - Body: `{ground_truth: true/false, notes: string (optional)}` + - Updates: `review_queue.annotated = true`, `review_queue.ground_truth = value`, `review_queue.annotated_at = NOW()` + - Response: `{status: 'annotated', video_id, ground_truth}` +- `GET /api/review/export` — Export annotated data + - Query params: `format=csv|json`, `annotated=true/false`, `date_from`, `date_to` + - Response: File download with annotated data +- `GET /api/review/stats` — Review queue statistics + - Response: `{total_in_queue: N, annotated_today: N, avg_confidence: F, confidence_distribution: {...}}` + +### 7.2 Review Frontend +**File:** `ui/review/` + +Pages: +- **Queue Page (`/`):** List of videos awaiting review + - Table columns: Video ID, File Path, Confidence Score, Model Version, Date Added, Actions (View) + - Sortable by confidence, date, file path + - Filter by confidence range, model version + - Pagination (20 items per page) +- **Annotation Page (`/review/{video_id}`):** Video annotation interface + - Video player with playback controls (HTML5 `