Compare commits

..
4 Commits
Author SHA1 Message Date
Ryan Shpeherd 9f098d4b1f Update worker 2026-09-09 13:50:19 -04:00
Ryan Shpeherd d9c0998400 API json fixes 2026-09-09 12:35:18 -04:00
Ryan Shpeherd e4e5d75336 API working 2026-09-09 11:19:00 -04:00
Ryan ea46d418bd Move to new db setup 2026-09-08 20:31:06 -04:00
24 changed files with 1656 additions and 2047 deletions
+5 -4
View File
@@ -6,6 +6,11 @@
# -----------------------------------------------------
DB_ROOT_PASSWORD=changeme_root
DB_PASSWORD=changeme_videodetect
DB_USER=videodetect
DB_NAME=videodetect
DB_HOST=mariadb
API_HOST=https://api:3000
# -----------------------------------------------------
# Storage paths (host-side mounts)
@@ -14,7 +19,3 @@ NAS_OUTPUT_PATH=${PWD}/output
MODELS_PATH=${PWD}/models
TRAINING_PATH=${PWD}/training
# -----------------------------------------------------
# Grafana
# -----------------------------------------------------
GRAFANA_PASSWORD=changeme_grafana
+486
View File
@@ -0,0 +1,486 @@
# REFACTOR.md — Worker-to-API Refactor Plan
## Context
VideoDetect workers currently run as long-lived processes (`main.py``WorkerPool`) that query the database directly via `DBConnector`. The re-architecture moves to **independent, externally-invoked task processes** that communicate through a REST API provided by the Perl `api/app.pl` module. This enables finer-grained scaling, resilience to individual process crashes, and separation of concerns between scanning (discovery) and processing (AI inference).
---
## Target Architecture
```
┌───────────┐ /api/v1/nexttask/AISCAN ┌─────────────┐
│ Scanner │ ──────────────────────────────> │ Perl API │
│ (long- │ <────────────────────────────── │ (Dancer2) │
│ lived) │ task reservation + assign_key ├─────────────┤
└───────────┘ │ DB │
│ │
┌───────────────────────────────────────────┼──────────┐
│ ▼ │
│ ┌──────────────┐ │
│ POST /api/v1/task/:id/complete │ │
│ ◄─────────────────────────────────────────► │ │
│ │ │
│ ┌───────────────────────────────┘ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐ ┌──────────────┐
│worker-1│ │worker-2│ │worker-N│ │ MariaDB │
│(short- │ │(short- │ │(short- │ │ │
│ lived) │ │ lived) │ │ lived) │ └──────────────┘
└────────┘ └────────┘ └────────┘
```
Each worker process:
1. Starts → accepts `--tasks N` (default 1) via CLI argument
2. Loops up to N times: **claim task****fetch video data****process****submit results**
3. Exits cleanly after completing the requested count
---
## API Reference (from `api/app.pl`)
### GET `/api/v1/nexttask/:type`
Claims the next pending task of the given type and reserves it.
| Field | Type | Example |
|-----------|---------|----------------------------------------------|
| task | object | Task record from DB |
| assign_key| string | `"worker_338"` (server-generated) |
**On success:** HTTP 200 with JSON body:
```json
{
"task": {
"id": 1,
"video_id": 42,
"task_type": "AISCAN",
"status": "PENDING",
"created_at": "2026-09-09T13:05:56",
"updated_at": "2026-09-09T14:53:57",
"assign_key": null,
"results": null,
"assigned_at": "2026-09-09T14:43:31"
},
"assign_key": "worker_338"
}
```
**On no tasks available:** HTTP 404 with `{"message":"No task"}`.
> **NOTE:** The Perl API marks the task `IN_PROGRESS` and sets `assign_key` + `assigned_at` atomically (`UPDATE ... WHERE id=? AND status='PENDING'`). This is safe for multiple workers racing to claim the same task.
---
### GET `/api/v1/video/:id`
Returns full video metadata by ID.
| Field | Type | Example |
|---------------|---------|------------------------------------------------------|
| id | integer | `1` |
| file_path | string | `"/data/The Fappening/Sextape - Alyson Hannigan (American actress - American pie).wmv"` |
| file_size | integer | `19358016` |
| file_hash | string | `"1ffd178e9ee23039aebffd79ddcbc88e983633edcb75062e6bd4c269f4d7bf94"` |
| resolution_w | integer | `640` |
| resolution_h | integer | `480` |
| codec | string | `"wmv1"` |
| duration | float | `102.499` |
| last_scan_time| datetime| `"2026-09-09T13:05:56"` |
| created_at | datetime| `"2026-09-09T13:05:56"` |
| updated_at | datetime| `"2026-09-09T13:05:56"` |
**On not found:** HTTP 404 with `{"message":"No video"}`.
---
### POST `/api/v1/task/:task/complete`
Submits processing results for a claimed task. The API verifies the task is `IN_PROGRESS` and assigned to the given `assign_key`.
**Required parameters (form-encoded or JSON body):**
| Field | Type | Description |
|-------------|--------|------------------------------------------------|
| assign_key | string | Must match the key returned by `/nexttask` |
| results | object | JSON-serializable dict to store in DB `results` column |
**On success:** HTTP 200 with `{"message":"Task completed successfully"}`.
**On mismatch or task not IN_PROGRESS:** HTTP 403 with error message.
> **NOTE:** The Perl API currently uses `body_parameters->get("results")`, which reads form-encoded data. For JSON body submission, the Dancer2 config may need `serializer: JSON` (which is already set in `api/config.yml`). However, `body_parameters` only parses form-encoded fields — JSON body content goes to `$app->request->body`. **This needs verification before implementation.**
---
## Refactor Steps
### Phase 1 — Create the Task Worker Module
**Goal:** A single entry-point script that can run as a standalone process.
**File:** `src/task_worker.py` (new)
**Acceptance Criteria:**
- Starts with `python3 src/task_worker.py --tasks N` (default 1 task)
- Prints startup log message showing number of tasks requested and model version
- Exits cleanly after processing the requested count
```bash
# Default: process 1 task and exit
python3 -m src.task_worker
# Explicit: process 5 tasks and exit
python3 -m src.task_worker --tasks 5
# Also supported via direct script invocation
python3 src/task_worker.py --tasks 10
```
**CLI Implementation:**
```python
import argparse
parser = argparse.ArgumentParser(description="VideoDetect task worker")
parser.add_argument("--tasks", type=int, default=1,
help="Number of tasks to process before exiting (default: 1)")
args = parser.parse_args()
```
---
### Phase 2 — API Client Module
**Goal:** A thin HTTP client layer for communicating with the Perl API.
**File:** `src/api_client.py` (new)
**Acceptance Criteria:**
- Encapsulates all API calls in one class: `ApiClient(base_url)`
- Handles JSON serialization/deserialization automatically
- Raises a custom `ApiError` on HTTP errors (with status code and response body)
- Returns `None` for 404 responses (no task remaining) from `/nexttask`
**API Error handling:**
```python
class ApiError(Exception):
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message
super().__init__(f"API error {status_code}: {message}")
# Usage patterns:
try:
response = client.get_next_task("AISCAN")
except ApiError as e:
if e.status_code == 404:
logger.info("No more tasks available")
break # exit processing loop
raise
result = client.submit_results(task_id, assign_key, results_dict)
```
**Methods to implement:**
| Method | Endpoint | Returns | Special handling |
|--------|----------|---------|-----------------|
| `get_next_task(task_type)` | `GET /api/v1/nexttask/{type}` | `{"task": {...}, "assign_key": str} \| None` | Returns None on 404 |
| `get_video(video_id)` | `GET /api/v1/video/{id}` | dict with video metadata | Raises ApiError on 404/5xx |
| `submit_results(task_id, assign_key, results)` | `POST /api/v1/task/{task}/complete` | dict with response | Passes assign_key + serialized results |
**Notes for implementation:**
- Use Python's standard library only (`urllib.request`) if possible to avoid adding dependencies. If JSON body submission is needed for the Perl API, check whether `body_parameters->get('results')` in Dancer2 handles raw JSON (it typically does not — it expects form-encoded data).
- If form-encoding is required: `requests.post(url, data={'assign_key': key, 'results': json.dumps(results)})`
- If JSON body works: `requests.post(url, json={'assign_key': key, 'results': results})`
- **Recommendation:** Use the `requests` library (already in worker requirements.txt likely). Document both approaches and implement the one that matches your Dancer2 config.
---
### Phase 3 — Implement the AI Processing Pipeline
**Goal:** Extract the core AI processing logic from `orchestrator.py` into a reusable function callable by the task worker.
**File:** New or updated module in `src/` (tentatively `src/task_processor.py`)
**Acceptance Criteria:**
- Takes video metadata dict + file path as input
- Returns a results dict matching what will be stored in the DB `results` column
- Handles all error cases gracefully (returns errors instead of crashing)
- Logs all significant decisions at INFO level
**Input:**
```python
video = {
"id": 1,
"file_path": "/data/input/...",
"codec": "wmv1",
"duration": 102.499,
"resolution_w": 640,
"resolution_h": 480,
"file_size": 19358016,
"file_hash": "abc...",
}
```
**Output (results dict stored in DB):**
```python
{
"status": "COMPLETED", # or "FAILED" on error
"confidence": 0.87, # video-level confidence score
"routing_decision": "MATCH", # MATCH | REVIEW | SKIP
"face_count": 142, # total faces detected across all frames
"frame_count": 23, # frames extracted and processed
"model_version": "v0.0.0-placeholder",
"processing_time_seconds": 12.4,
"error": None, # error message if FAILED
}
```
**Processing flow (extracted from orchestrator.py):**
```python
def process_video(video: dict) -> dict:
"""Run the full AI scan pipeline on a single video.
Returns results dict for submission via API.
"""
start_time = time.time()
file_path = video["file_path"]
video_id = video["id"]
try:
# 1. Probe (if metadata is incomplete)
prober = VideoProber(timeout=10)
metadata = prober.probe(file_path)
# 2. Extract frames to scratch
scratch = ScratchManager(base_path="/scratch", video_id=str(video_id))
frame_dir = scratch.ensure_frame_dir()
sampler = FrameSampler(interval_seconds=30, quality=2)
frame_paths = sampler.extract_frames(
video_path=file_path, output_dir=str(frame_dir),
duration=metadata.duration, resolution=(metadata.resolution_w, metadata.resolution_h)
)
# 3. Detect faces
detector = FaceDetector(engine_path="/models/face_detector/face_detector.trt")
detections_per_frame = detector.detect_faces(frame_paths)
total_faces = sum(len(dets) for dets in detections_per_frame)
# 4. Crop and classify (aggregate confidences from face crops)
classifier = FaceClassifier(engine_path="/models/classifier/classifier.trt")
# ... crop paths → classify → get confidence list
# 5. Aggregate
confidence = aggregate(confidences, strategy="max")
# 6. Route
routing = router.route(confidence)
processing_time = time.time() - start_time
return {
"status": "COMPLETED",
"confidence": round(confidence, 4),
"routing_decision": routing,
"face_count": total_faces,
"frame_count": len(frame_paths),
"model_version": get_model_version(),
"processing_time_seconds": round(processing_time, 2),
"error": None,
}
except Exception as exc:
logger.error("Processing failed for video %d: %s", video_id, exc)
return {
"status": "FAILED",
"confidence": 0.0,
"routing_decision": "REVIEW",
"face_count": 0,
"frame_count": 0,
"model_version": get_model_version(),
"processing_time_seconds": round(time.time() - start_time, 2),
"error": str(exc),
}
```
**Notes for implementation:**
- Reuse existing classes from `orchestrator.py` (`FaceDetector`, `FaceClassifier`, `FrameSampler`, `ScratchManager`, `VideoProber`, `aggregate`, `router`) without refactoring them — just import and use them.
- GPU setup (torch CUDA, GPUMemoryManager) can be done once at module level or lazily inside `process_video()` to avoid overhead per task invocation.
- Model loading is expensive (~seconds). Consider lazy initialization or process-level caching via a singleton pattern.
---
### Phase 4 — Wire It Together in task_worker.py
**Goal:** Combine the API client, processing pipeline, and CLI entry point into a working script.
**Acceptance Criteria:**
- Full end-to-end: claim → fetch → process → submit → repeat N times
- Exits with code 0 on success, non-zero on unrecoverable errors
- Logs startup/shutdown counts (tasks attempted, tasks succeeded, tasks failed)
- Graceful shutdown on SIGTERM/SIGINT (finish current task, then exit)
**Expected lifecycle log output:**
```json
{"timestamp": "...", "level": "INFO", "message": "Task worker starting. Will process 3 task(s)."}
{"timestamp": "...", "level": "INFO", "message": "API client configured: base_url=http://localhost:8890"}
{"timestamp": "...", "level": "INFO", "message": "Claiming task 1 (video_id=42) for AISCAN"}
{"timestamp": "...", "level": "INFO", "message": "Processing video 42: /data/input/..."}
{"timestamp": "...", "level": "INFO", "message": "Video 42 complete: C=0.87 routing=MATCH faces=142 frames=23 time=12.4s"}
{"timestamp": "...", "level": "INFO", "message": "Submitting results for task 1 via API"}
{"timestamp": "...", "level": "INFO", "message": "Claiming task 2 (video_id=99) for AISCAN"}
{"timestamp": "...", "level": "INFO", "message": "Processing video 99: /data/input/..."}
{"timestamp": "...", "level": "INFO", "message": "Video 99 complete: C=0.31 routing=SKIP faces=0 frames=18 time=8.7s"}
{"timestamp": "...", "level": "INFO", "message": "Submitting results for task 2 via API"}
{"timestamp": "...", "level": "INFO", "message": "Claiming task 3 (video_id=157) for AISCAN"}
{"timestamp": "...", "level": "WARNING", "message": "Processing video 157 failed: ffprobe error: cannot decode stream"}
{"timestamp": "...", "level": "INFO", "message": "Submitting FAILED results for task 3 via API"}
{"timestamp": "...", "level": "INFO", "message": "No more tasks available (API returned 404)"}
{"timestamp": "...", "level": "INFO", "message": "Task worker finished: 3 attempted, 2 succeeded, 1 failed"}
```
**Core loop:**
```python
for i in range(1, args.tasks + 1):
logger.info("=== Processing task %d/%d ===", i, args.tasks)
# Claim a task
response = api.get_next_task("AISCAN")
if response is None:
logger.info("No more tasks available. Done.")
break
task = response["task"]
assign_key = response["assign_key"]
video_id = task["video_id"]
# Fetch video metadata
video = api.get_video(video_id)
# Process
results = process_video(video)
# Submit
api.submit_results(task["id"], assign_key, results)
logger.info("Finished: %d attempted, %d succeeded, %d failed", total_attempted, total_succeeded, total_failed)
```
---
### Phase 5 — Update docker-compose.yml
**Goal:** Change the worker service from a long-lived `WorkerPool` to a short-lived task process.
**Changes to `docker-compose.yml` worker section:**
1. **Update command** to invoke the task worker instead of `main.py`:
```yaml
command: python3 -m src.task_worker --tasks 50
```
2. **Add restart policy considerations** — since workers are now short-lived, you have two options:
- **Option A (simpler):** Run a single worker container with a large `--tasks` count (e.g., 100) so it processes many videos before exiting, then rely on Kubernetes/Cron/external scheduler to restart.
- **Option B (more flexible):** Make `--tasks` configurable via environment variable:
```yaml
environment:
- TASK_COUNT=${TASK_COUNT:-50}
command: >
python3 -m src.task_worker --tasks ${TASK_COUNT}
```
3. **Remove the WorkerPool initialization** from `main.py` — it becomes unused (or is removed entirely in a later cleanup).
---
### Phase 6 — Verify API Compatibility
**Goal:** Confirm the Dancer2 Perl API correctly handles JSON body submission from Python's `requests` library on `/api/v1/task/:task/complete`.
**Acceptance Criteria:**
- POST with `Content-Type: application/json` body containing `assign_key` + `results` (as a dict, not a string) returns 200
- POST with form-encoded data also works as fallback
- The Perl API correctly stores the results JSON in the database
**Test procedure:**
```bash
# Step 1: Create a test task manually (via MySQL or via scanner)
mysql videodetect -e "INSERT INTO tasks (task_type, video_id, status) VALUES ('AISCAN', 1, 'PENDING');"
# Step 2: Claim the task via API
curl -s http://localhost:8890/api/v1/nexttask/AISCAN | python3 -m json.tool
# Step 3: Submit results (adjust video_id to a real one)
curl -X POST http://localhost:8890/api/v1/task/1/complete \
-H "Content-Type: application/json" \
-d '{"assign_key":"worker_999","results":{"confidence":0.87,"routing_decision":"MATCH"}}' | python3 -m json.tool
# Step 4: Verify results stored in DB
mysql videodetect -e "SELECT id, status, results FROM tasks WHERE id=1;"
```
**If JSON body does NOT work**, update the Dancer2 API to handle JSON explicitly:
```perl
post '/api/v1/task/:task/complete' => sub {
my $task = route_parameters->get("task");
# Handle both JSON body and form-encoded data
my $body;
if (request_content_type eq 'application/json') {
use Dancer2::Core::Request::Entity;
$body = decode_json(request_body);
} else {
$body = body_parameters->to_hash;
}
my $assign_key = $body->{assign_key};
my $results = $body->{results};
# ... rest of the handler unchanged
};
```
---
## Files Modified / Created Summary
| File | Action | Description |
|------|--------|-------------|
| `src/task_worker.py` | **NEW** | CLI entry point: `--tasks N`, loop claim→process→submit |
| `src/api_client.py` | **NEW** | HTTP client for the Perl API (`ApiClient`) |
| `src/task_processor.py` | **NEW** | `process_video(video_dict)` — core AI pipeline callable standalone |
| `docker-compose.yml` | **MODIFY** | Change worker command to invoke task_worker; add TASK_COUNT env var |
| `api/app.pl` | **MAYBE MODIFY** | Update `/task/:task/complete` to handle JSON body if Dancer2 doesn't support it natively |
| `src/main.py` | **MODIFY (cleanup later)** | Remove or deprecate WorkerPool usage (long-lived process no longer needed) |
| `REFACTOR.md` | **CURRENT FILE** | This plan document |
---
## Risks & Considerations
1. **GPU model loading per invocation:** Each new Python process loads the ONNX/TensorRT engine into GPU memory. With `--tasks 1`, this is wasteful. Mitigation: use larger `--tasks` values (e.g., 20-100) so amortization is favorable, or implement a local cache server pattern later.
2. **Permanence of scratch space:** The `ScratchManager` creates per-video temp files under `/scratch`. Since workers are now short-lived, ensure `cleanup=True` is always set (it is by default in the existing code).
3. **API JSON body compatibility:** Dancer2's `body_parameters` may not parse JSON bodies — it expects form-encoded data. This is the highest-risk item. Test Phase 6 early.
4. **Task idempotency:** If a worker crashes between processing and submitting results, the task remains `IN_PROGRESS`. The Perl API prevents re-claiming (the WHERE clause checks `status='PENDING'`). A manual SQL update or a `/api/v1/task/:task/reset` endpoint may be needed for recovery. This is outside the scope of this refactor but worth noting.
---
## Suggested Order of Execution
1. **Phase 6 first** — verify API JSON compatibility (takes 5 minutes, unblocks everything)
2. **Phase 2** — create `api_client.py` with minimal methods
3. **Phase 3** — create `task_processor.py` by extracting from `orchestrator.py`
4. **Phase 1** — create `task_worker.py` with CLI + loop
5. **Phase 4** — wire together and test locally (`python3 -m src.task_worker --tasks 3`)
6. **Phase 5** — update docker-compose.yml and deploy
-170
View File
@@ -1,170 +0,0 @@
# 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
-182
View File
@@ -1,182 +0,0 @@
# 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 <file>
```
- **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
-152
View File
@@ -1,152 +0,0 @@
# 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
-168
View File
@@ -1,168 +0,0 @@
# 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
-187
View File
@@ -1,187 +0,0 @@
# 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
-181
View File
@@ -1,181 +0,0 @@
# 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<float>), 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
-216
View File
@@ -1,216 +0,0 @@
# 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 `<video>` element)
- Top-k contributing frames displayed as thumbnails (k=5 default)
- Confidence scores displayed per frame
- Label toggle button (True/False) with confirmation
- Optional notes field
- Submit button (saves to DB via API)
- Navigation: Previous/Next video in queue
### 7.3 Data Export
**File:** `src/review_export.py`
Features:
- **CSV Export:**
```csv
video_id,file_path,confidence_score,routing_decision,model_version,ground_truth,annotated_at,contributing_frames
12345,/data/input/video.mp4,0.62,REVIEW,v1.2.0,true,2026-08-03T10:30:00Z,"[{'timestamp': 30.0, 'crop_path': '/scratch/12345/crops/30000.jpg', 'confidence': 0.82}, ...]"
```
- **JSON Export:**
```json
[
{
"video_id": 12345,
"file_path": "/data/input/video.mp4",
"confidence_score": 0.62,
"routing_decision": "REVIEW",
"model_version": "v1.2.0",
"ground_truth": true,
"annotated_at": "2026-08-03T10:30:00Z",
"contributing_frames": [
{"timestamp": 30.0, "crop_path": "/scratch/12345/crops/30000.jpg", "confidence": 0.82}
]
}
]
```
- **Export Options:**
- Filter by annotation status (annotated/unannotated)
- Filter by date range
- Filter by model version
- Filter by ground truth label
- **Output Location:** `/data/output/reviews/`
### 7.4 UI Container
**File:** `ui/Dockerfile`
Base image: `python:3.10-slim`
Installed packages:
- Flask 3.0+ or FastAPI 0.100+ (lightweight web framework)
- Jinja2 3.1+ (template engine)
- PyMySQL (database connection for API)
- gunicorn (WSGI server)
### 7.5 Docker Compose Update
**File:** `docker-compose.yml` (update)
Add UI service:
```yaml
ui:
build:
context: ./ui
dockerfile: Dockerfile
ports:
- "5000:5000"
volumes:
- ./ui:/app/ui
environment:
- DB_HOST=mariadb
- DB_PORT=3306
- DB_NAME=videodetect
- DB_USER=videodetect
- DB_PASSWORD=${DB_PASSWORD}
depends_on:
- mariadb
networks:
- videodetect-network
```
### 7.6 Database Update
**File:** `db/schema.sql` (review_queue table — from STORY-01)
The `review_queue` table was defined in STORY-01. This story populates and queries it.
### 7.7 Configuration Updates
**File:** `config.yaml` (updates)
New fields:
```yaml
review_ui:
host: "0.0.0.0"
port: 5000
per_page: 20
top_k_frames: 5
export_path: /data/output/reviews
auth_enabled: false # per TC-06
ssl_enabled: false # per TC-06
```
## Acceptance Criteria
### Functional
- [ ] Review queue displays all videos with routing_decision = REVIEW and annotated = false
- [ ] Video player loads and plays the video correctly
- [ ] Top-k contributing frames are displayed as thumbnails with confidence scores
- [ ] Annotator can toggle label (True/False) and submit
- [ ] Submitted label is persisted to DB (review_queue table)
- [ ] Annotated videos are removed from the default queue view
- [ ] CSV export produces valid CSV with all required fields
- [ ] JSON export produces valid JSON with all required fields
- [ ] Export includes ground truth labels and contributing frame data
- [ ] UI is accessible via http://<server-ip>:5000 (no auth, no SSL)
- [ ] Pagination works correctly (20 items per page)
- [ ] Sort and filter operations work on the queue page
### Non-Functional
- [ ] Queue page loads in < 2 seconds (with 1000+ videos in queue)
- [ ] Video player loads in < 3 seconds
- [ ] Label submission completes in < 1 second
- [ ] Export of 1000 annotated videos completes in < 10 seconds
- [ ] UI uses < 100MB RAM at idle
- [ ] No authentication or SSL configured (per TC-06)
### Technical Constraints
- [ ] UI runs in Docker container (per TC-05)
- [ ] No reverse proxy configured
- [ ] No SSL certificates configured
- [ ] No authentication mechanism configured
- [ ] All API responses are JSON
- [ ] Database queries use parameterized statements
- [ ] Export files are UTF-8 encoded
## Dependencies
- **Prerequisites:** STORY-01 (Foundation — DB schema), STORY-05 (Classification — provides routing decisions)
- **Depends on:** None (can be built in parallel with STORY-04, STORY-05)
- **Enables:** STORY-08 (Active Learning — provides labeled training data)
## Risks & Mitigations
| Risk | Mitigation |
|------|--|
| Video playback in browser requires compatible format | Serve videos in web-compatible format (H.264 MP4); transcode if needed |
| Crop paths may not be accessible from UI container | Store crop paths in DB; serve via API endpoint |
| No auth means anyone on LAN can access | Acceptable per TC-06; document in security notes |
| Large review queue slows page loads | Implement server-side pagination; lazy load thumbnails |
## Estimated Effort
- **Sprint:** 7
- **Story Points:** 21
- **Dependencies:** STORY-01, STORY-05
-245
View File
@@ -1,245 +0,0 @@
# STORY-08: Active Learning Pipeline
## Epic
**E3: Active Learning** — As an ML engineer, I can fine-tune the classifier head with reviewed data.
## Related Requirements
| ID | Requirement |
|----|------|
| FR-06 | Active learning pipeline (label ingestion → fine-tuning → deployment): Batch retraining only. No online learning. Versioned model swaps. |
| NFR-04 | Determinism & Reproducibility: Config-seeded randomness, versioned models |
| NFR-05 | Fault Tolerance: Auto-retry on transient failures; skip & log on fatal errors |
| 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 the active learning pipeline that ingests annotated review data, fine-tunes the classifier head, validates the candidate model, and deploys it if it meets quality gates. This enables incremental model improvement using human-labeled data from the review queue.
## Scope
### In Scope
- Label ingestion from review queue (CSV/JSON export or direct DB query)
- Dataset versioning and preparation for training
- Head-only fine-tuning on face crops (freeze backbone, train classification head)
- Training with AdamW, configurable learning rate, early stopping
- Candidate model validation on held-out validation set
- F1 score and ECE (Expected Calibration Error) calculation
- Quality gate validation (ΔF1 > 0.02, ECE < 0.08)
- Model registry updates (ACTIVE, CANDIDATE, ARCHIVED states)
- Hot reload of new TensorRT engine
- Rollback on regression
### Out of Scope
- Frame sampling (covered in STORY-03)
- Face detection (covered in STORY-04)
- Classification inference (covered in STORY-05)
- Review UI (covered in STORY-07)
- Monitoring dashboards (covered in STORY-09)
## Deliverables
### 8.1 Label Ingestion
**File:** `src/active_learning/label_ingestor.py`
Features:
- **Data Source:** Query `review_queue` table for annotated labels
```sql
SELECT video_id, ground_truth, contributing_frames
FROM review_queue
WHERE annotated = true AND ground_truth IS NOT NULL
```
- **Crop Extraction:** Extract face crops from stored paths or re-extract from video
- **Dataset Versioning:** Create versioned dataset directory structure
```
/data/training/v2.0.0/
crops/
class_0/ (negative samples)
class_1/ (positive samples)
labels.csv
metadata.json
```
- **Train/Val Split:** 80/20 split (stratified by class)
- **Augmentation:** Apply standard augmentations at training time (not pre-computed)
- Random horizontal flip
- Random color jitter
- Random affine transform (±10 degrees rotation, ±10% scale)
### 8.2 Training Pipeline
**File:** `src/active_learning/trainer.py`
Features:
- **Model Loading:** Load pre-trained MobileNetV3 backbone (frozen)
```python
model = load_pretrained_mobilenetv3()
for param in model.features.parameters():
param.requires_grad = False
# Replace classification head
model.classifier = nn.Sequential(
nn.Linear(1280, 256),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(256, 2) # binary classification
)
```
- **Head-Only Fine-Tuning:** Only train the classification head
- Backbone weights are frozen (no gradient updates)
- Head weights are trainable
- This is faster and requires less data than full fine-tuning
- **Optimizer:** AdamW with configurable parameters
- Learning rate: 1e-3 (default), configurable
- Weight decay: 1e-2
- Betas: (0.9, 0.999)
- **Loss Function:** Binary Cross-Entropy with class weights (if imbalanced)
- **Training Configuration:**
- Epochs: 10-30 (configurable)
- Batch size: 32
- Early stopping: patience=5 epochs (no validation improvement)
- Learning rate scheduler: ReduceLROnPlateau (factor=0.5, patience=3)
- **Checkpointing:** Save checkpoint to `/models/candidate/` after each epoch
```
/models/candidate/
v2.0.0_epoch_01.pt
v2.0.0_epoch_02.pt
...
v2.0.0_best.pt (best validation F1)
```
### 8.3 Validation Pipeline
**File:** `src/active_learning/validator.py`
Features:
- **Validation Set:** Held-out 20% of annotated data (never seen during training)
- **Metrics Calculation:**
- **F1 Score:** Macro F1 on validation set
- **ECE (Expected Calibration Error):**
```python
def compute_ece(predictions, labels, n_bins=15):
bin_boundaries = np.linspace(0, 1, n_bins + 1)
ece = 0.0
for i in range(n_bins):
mask = (predictions >= bin_boundaries[i]) & (predictions < bin_boundaries[i+1])
if mask.sum() > 0:
bin_confidence = predictions[mask].mean()
bin_accuracy = labels[mask].mean()
ece += (mask.sum() / len(predictions)) * abs(bin_confidence - bin_accuracy)
return ece
```
- **Accuracy, Precision, Recall:** Standard classification metrics
- **Quality Gates:**
- ΔF1 > 0.02 (improvement over current model)
- ECE < 0.08 (calibration acceptable)
- Both gates must pass for deployment
### 8.4 Model Registry & Deployment
**File:** `src/active_learning/registry.py`
Features:
- **Model Registry:** Update DB `models` table
```sql
-- Promote candidate to active
UPDATE models SET status = 'ACTIVE' WHERE version = 'v2.0.0';
UPDATE models SET status = 'ARCHIVED' WHERE status = 'ACTIVE' AND version != 'v2.0.0';
```
- **TensorRT Engine Build:** Convert candidate model to TensorRT engine
```bash
trtexec --onnx=models/candidate/v2.0.0.onnx \
--saveEngine=models/candidate/v2.0.0.trt \
--fp32 --maxBatch=32 --workspace=2048
```
- **Hot Reload:** Signal worker process to reload new engine
- Option A: Restart worker container (`docker-compose restart worker`)
- Option B: In-process reload (graceful, no downtime)
- Default: In-process reload via signal handling
- **Rollback:** If new model causes issues, rollback to archived model
```sql
UPDATE models SET status = 'ACTIVE' WHERE version = 'v1.2.0';
UPDATE models SET status = 'ARCHIVED' WHERE version = 'v2.0.0';
```
### 8.5 Training Configuration
**File:** `config.yaml` (updates)
New fields:
```yaml
active_learning:
enabled: true
min_annotated_samples: 100 # minimum labeled data to trigger training
training:
epochs: 20
batch_size: 32
learning_rate: 1e-3
weight_decay: 1e-2
early_stopping_patience: 5
lr_scheduler: ReduceLROnPlateau
lr_factor: 0.5
lr_patience: 3
validation:
val_split: 0.2
min_f1_improvement: 0.02
max_ece: 0.08
deployment:
auto_deploy: true # deploy if quality gates pass
hot_reload: true
rollback_enabled: true
augmentation:
horizontal_flip: true
color_jitter: true
affine: true
affine_degrees: 10
affine_scale: 0.1
```
## Acceptance Criteria
### Functional
- [ ] Annotated labels are ingested from review_queue table correctly
- [ ] Dataset is versioned with proper directory structure
- [ ] Train/val split is stratified by class (80/20)
- [ ] Data augmentation is applied at training time (not pre-computed)
- [ ] Backbone weights are frozen during fine-tuning (verified by checking requires_grad)
- [ ] Classification head is trainable and receives gradient updates
- [ ] AdamW optimizer is used with correct parameters
- [ ] Early stopping works (training stops if no improvement for patience epochs)
- [ ] Candidate model is saved to /models/candidate/ with correct versioning
- [ ] F1 score is calculated correctly on validation set
- [ ] ECE is calculated correctly on validation set
- [ ] Quality gates are enforced (ΔF1 > 0.02 AND ECE < 0.08)
- [ ] Model registry is updated (ACTIVE, CANDIDATE, ARCHIVED states)
- [ ] TensorRT engine is built from candidate model
- [ ] Hot reload deploys new model without downtime
- [ ] Rollback restores previous model if deployment fails
### Non-Functional
- [ ] Training completes in < 4 hours on Tesla P40 (typical dataset: 1000 samples)
- [ ] Validation completes in < 30 minutes
- [ ] TensorRT engine build completes in < 10 minutes
- [ ] Hot reload completes in < 30 seconds
- [ ] Training uses < 18GB GPU memory
- [ ] Training is deterministic (same data + same config → same results)
### Technical Constraints
- [ ] CUDA 11.8 compatible (verified via torch.version.cuda)
- [ ] PyTorch ≤ 2.1.0 (verified via torch.__version__)
- [ ] FP32 training only (no mixed precision)
- [ ] No Tensor Cores used (CC 5.2 constraint)
- [ ] Model versioning follows semantic versioning (MAJOR.MINOR.PATCH)
- [ ] All training hyperparameters are configurable via config.yaml
## Dependencies
- **Prerequisites:** STORY-01 (Foundation), STORY-05 (Classification — provides base model), STORY-07 (Review UI — provides labeled data)
- **Depends on:** None (runs independently, triggered by labeled data threshold)
- **Enables:** STORY-05 (provides new model for inference)
## Risks & Mitigations
| Risk | Mitigation |
|------|--|
| Insufficient labeled data for meaningful fine-tuning | Set min_annotated_samples threshold (e.g., 100); wait until reached |
| Head-only fine-tuning may not be enough for domain shift | Offer full fine-tuning as option; document limitations |
| Model regression in production | Strict quality gates; keep previous model in ARCHIVED state for quick rollback |
| Long training times on Tesla P40 | Head-only training is faster; batch size tuning; early stopping |
| ECE calculation sensitivity | Use proper binning; report ECI with confidence intervals |
## Estimated Effort
- **Sprint:** 7-8
- **Story Points:** 34
- **Dependencies:** STORY-01, STORY-05, STORY-07
-360
View File
@@ -1,360 +0,0 @@
# STORY-09: Observability, Monitoring & Hardening
## Epic
**E4: Operations** — As a DevOps engineer, I can schedule, monitor, and resume batch jobs.
## Related Requirements
| ID | Requirement |
|----|------|
| NFR-05 | Fault Tolerance: Auto-retry on transient failures; skip & log on fatal errors |
| NFR-06 | Observability: Prometheus/Grafana metrics + structured logging; Tracks FPS, queue depth, confidence distribution, drift alerts |
| 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 |
| NFR-07 | Data Volume Handling: Efficient indexing for ~30TB dataset |
## Description
Implement comprehensive monitoring, metrics collection, fault tolerance, and system hardening. Expose Prometheus metrics for throughput, GPU utilization, queue depth, and confidence distribution. Build Grafana dashboards for real-time system health. Implement crash recovery, idempotency, retry logic, and drift detection.
## Scope
### In Scope
- Prometheus metrics exposure (videos processed, GPU utilization, queue depth, confidence distribution)
- Grafana dashboard configuration (throughput, error rates, confidence drift)
- Crash recovery with checkpointing
- Idempotent processing guarantees
- Retry logic for transient errors (up to 3 attempts)
- Weekly drift detection job
- Alerting on confidence distribution shifts and review queue growth
- Worker health checks and auto-restart
### Out of Scope
- Frame sampling (covered in STORY-04)
- Face detection (covered in STORY-05)
- Classification (covered in STORY-06)
- Review UI (covered in STORY-08)
- Active learning pipeline (covered in STORY-09)
## Deliverables
### 9.1 Prometheus Metrics
**File:** `src/metrics.py`
Metrics to expose:
- **Counter Metrics:**
- `videos_processed_total` (label: routing_decision=MATCH|REVIEW|SKIP|UNSCANNABLE|ERROR)
- `videos_processed_by_model_total` (label: model_version)
- `frames_extracted_total`
- `faces_detected_total`
- `inference_errors_total` (label: error_type)
- `retry_attempts_total` (label: step=probe|extract|detect|classify)
- **Gauge Metrics:**
- `gpu_utilization_percent` (label: gpu_id)
- `gpu_memory_used_bytes` (label: gpu_id)
- `gpu_memory_free_bytes` (label: gpu_id)
- `queue_depth_pending`
- `queue_depth_processing`
- `queue_depth_review`
- `scratch_usage_bytes`
- `scratch_usage_percent`
- **Histogram Metrics:**
- `video_processing_duration_seconds` (label: routing_decision)
- `confidence_score_distribution` (buckets: 0.0, 0.1, 0.2, ..., 0.9, 1.0)
- `frame_count_per_video`
- `face_count_per_video`
- **Summary Metrics:**
- `throughput_videos_per_hour` (calculated from counter)
- `average_confidence` (calculated from histogram)
Implementation:
```python
from prometheus_client import start_http_server, Counter, Gauge, Histogram
# Start metrics HTTP server
start_http_server(9090) # /metrics endpoint
# Define metrics
videos_processed = Counter(
'videos_processed_total',
'Total videos processed',
['routing_decision']
)
gpu_memory = Gauge(
'gpu_memory_used_bytes',
'GPU memory usage',
['gpu_id']
)
confidence_hist = Histogram(
'confidence_score_distribution',
'Video confidence scores',
buckets=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
)
```
### 9.2 Grafana Dashboards
**File:** `monitoring/grafana/dashboards/`
Dashboard 1: **System Overview**
- Panels:
- Throughput (videos/hour) — line chart, 1h window
- Queue depth (pending/processing/review) — stacked bar
- GPU utilization (both GPUs) — line chart
- GPU memory usage (both GPUs) — line chart
- Error rate (errors/100 videos) — bar chart
- Confidence distribution — histogram
Dashboard 2: **Processing Details**
- Panels:
- Processing duration per video — scatter plot
- Frame count per video — histogram
- Face count per video — histogram
- Confidence score by model version — box plot
- Routing decision distribution — pie chart
Dashboard 3: **Active Learning**
- Panels:
- Review queue size over time — line chart
- Annotation rate (labels/day) — bar chart
- Model version timeline — timeline panel
- F1 score by model version — line chart
- ECE by model version — line chart
**File:** `monitoring/grafana/dashboards/system_overview.json`
**File:** `monitoring/grafana/dashboards/processing_details.json`
**File:** `monitoring/grafana/dashboards/active_learning.json`
### 9.3 Crash Recovery
**File:** `src/crash_recovery.py`
Features:
- **Checkpointing:** Periodically save processing state
```python
def save_checkpoint(video_id, state, progress):
checkpoint = {
'video_id': video_id,
'state': state, # 'processing', 'extracting', 'detecting', 'classifying'
'progress': progress, # dict of step -> completed
'timestamp': datetime.utcnow().isoformat()
}
with open(f'/scratch/checkpoints/{video_id}.json', 'w') as f:
json.dump(checkpoint, f)
```
- **Recovery on Startup:** Scan for PROCESSING videos and re-queue them
```sql
UPDATE videos SET status = 'PENDING', updated_at = NOW()
WHERE status = 'PROCESSING' AND updated_at < NOW() - INTERVAL 5 MINUTE
```
- **Lock Timeout:** 5 minutes (videos stuck in PROCESSING beyond this are re-queued)
- **Re-queue Logic:** Only re-queue if worker is down (detected via health check)
- **Idempotency:** Re-processing a video produces same results (no duplicates)
### 9.4 Retry Logic
**File:** `src/retry.py`
Features:
- **Retry Decorator:**
```python
def retry(max_attempts=3, delay=1.0, backoff=2.0, exceptions=(Exception,)):
def decorator(func):
def wrapper(*args, **kwargs):
last_exception = None
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except exceptions as e:
last_exception = e
if attempt < max_attempts - 1:
wait = delay * (backoff ** attempt)
time.sleep(wait)
raise last_exception
return wrapper
return decorator
```
- **Applicable Steps:** ffprobe, frame extraction, face detection, classification, DB writes
- **Transient Errors:** Network timeout, GPU OOM, file lock contention
- **Non-Retryable Errors:** Codec unsupported, corrupt file, invalid path → skip and log
- **Retry Logging:** Log each retry attempt with error type and delay
### 9.5 Drift Detection
**File:** `src/drift_detector.py`
Features:
- **Weekly Job:** Compare current confidence distribution to baseline
```python
def detect_drift(current_confidences, baseline_confidences, threshold=0.10):
# Compare p(C > 0.5) shift
current_high = sum(1 for c in current_confidences if c > 0.5) / len(current_confidences)
baseline_high = sum(1 for c in baseline_confidences if c > 0.5) / len(baseline_confidences)
shift = abs(current_high - baseline_high)
if shift > threshold:
alert(f"Confidence drift detected: {shift:.2%} shift in p(C > 0.5)")
return True
return False
```
- **Baseline:** Stored in DB or config (computed from last training cycle)
- **Alert Conditions:**
- `p(C > 0.5)` shifts > 10% from baseline
- Review queue grows unbounded (> 1000 items for > 24 hours)
- Throughput drops below 20 videos/hour/GPU for > 1 hour
- Error rate exceeds 5% for any 1-hour window
- **Alert Channels:** Email, Slack webhook, or log entry (configurable)
### 9.6 Worker Health Checks
**File:** `src/health_check.py`
Features:
- **Health Endpoint:** `/health` returns worker status
```json
{
"status": "healthy",
"gpu_available": true,
"gpu_memory_used_gb": 12.5,
"queue_depth": 42,
"uptime_seconds": 86400,
"videos_processed_today": 156,
"last_error": null
}
```
- **Auto-Restart:** Docker restart policy for worker container
```yaml
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9090/health"]
interval: 30s
timeout: 10s
retries: 3
```
- **GPU Health:** Monitor GPU temperature and error counts
- **Disk Health:** Monitor scratch space usage and NAS connectivity
### 9.7 Docker Compose Update
**File:** `docker-compose.yml` (update)
Add monitoring services:
```yaml
prometheus:
image: prom/prometheus:v2.48.0
volumes:
- ./monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus_data:/prometheus
ports:
- "9090:9090"
networks:
- videodetect-network
grafana:
image: grafana/grafana:10.2.0
volumes:
- grafana_data:/var/lib/grafana
- ./monitoring/grafana/dashboards:/etc/grafana/provisioning/dashboards
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
ports:
- "3000:3000"
networks:
- videodetect-network
volumes:
prometheus_data:
grafana_data:
```
### 9.8 Configuration Updates
**File:** `config.yaml` (updates)
New fields:
```yaml
monitoring:
prometheus:
enabled: true
port: 9090
metrics_path: /metrics
grafana:
enabled: true
port: 3000
alerts:
confidence_drift_threshold: 0.10
review_queue_max_size: 1000
review_queue_max_age_hours: 24
throughput_min_videos_per_hour: 20
throughput_min_duration_hours: 1
error_rate_threshold: 0.05
error_rate_window_hours: 1
drift_detection:
enabled: true
schedule: weekly # cron: 0 2 * * 0 (Sundays at 2 AM)
baseline_source: db # db or config
crash_recovery:
lock_timeout_minutes: 5
auto_requeue: true
retry:
max_attempts: 3
initial_delay: 1.0
backoff_factor: 2.0
retryable_errors:
- timeout
- gpu_oom
- file_lock
non_retryable_errors:
- codec_unsupported
- file_corrupt
- invalid_path
```
## Acceptance Criteria
### Functional
- [ ] Prometheus metrics are exposed at `/metrics` endpoint and queryable
- [ ] All required metrics are present (counters, gauges, histograms, summaries)
- [ ] Grafana dashboards load and display correct data
- [ ] System Overview dashboard shows throughput, queue depth, GPU metrics
- [ ] Processing Details dashboard shows duration, frame count, confidence distribution
- [ ] Active Learning dashboard shows review queue, annotation rate, model versions
- [ ] Crash recovery re-queues stuck PROCESSING videos on worker restart
- [ ] Idempotent processing: re-processing produces same results (no duplicates)
- [ ] Retry logic retries transient errors up to 3 times with exponential backoff
- [ ] Non-retryable errors are skipped and logged (no infinite retry)
- [ ] Drift detection runs weekly and alerts on > 10% confidence shift
- [ ] Review queue growth alert triggers when queue > 1000 for > 24 hours
- [ ] Worker health check returns correct status
- [ ] Auto-restart triggers on health check failure
### Non-Functional
- [ ] Metrics collection overhead < 2% of CPU
- [ ] Grafana dashboard loads in < 3 seconds
- [ ] Crash recovery completes in < 30 seconds
- [ ] Drift detection completes in < 5 minutes
- [ ] Alert delivery completes in < 60 seconds
- [ ] Prometheus data retention: 30 days (configurable)
- [ ] Grafana data source refresh: 30 seconds
### Technical Constraints
- [ ] Prometheus metrics follow naming conventions (unit suffixes, proper labels)
- [ ] Grafana dashboards are JSON-exportable and version-controlled
- [ ] Crash recovery is idempotent (running twice produces same result)
- [ ] Retry logic does not retry non-transient errors
- [ ] Drift detection baseline is stored and versioned
- [ ] Health check endpoint responds in < 1 second
- [ ] All alerts are logged with timestamp and context
## Dependencies
- **Prerequisites:** STORY-01 (Foundation), STORY-05 (Classification — provides metrics data), STORY-08 (Active Learning — provides model metrics)
- **Depends on:** None (can be built in parallel with other stories)
- **Enables:** Production deployment and long-term operation
## Risks & Mitigations
| Risk | Mitigation |
|------|--|
| Prometheus metrics cardinality explosion | Limit label cardinality; use histograms instead of individual values |
| Grafana dashboard load time with large datasets | Use Prometheus aggregations; pre-compute panels |
| Crash recovery misses in-flight writes | Use DB transactions; lock timeout prevents permanent locks |
| Drift detection baseline becomes stale | Update baseline with each training cycle |
| Alert fatigue from too many alerts | Tune thresholds; implement alert grouping |
## Estimated Effort
- **Sprint:** 9+
- **Story Points:** 34
- **Dependencies:** STORY-01, STORY-05, STORY-08
+27
View File
@@ -0,0 +1,27 @@
FROM ubuntu:22.04
# Install Perl and system dependencies
RUN apt update && apt install -y \
dnsutils \
libdancer2-perl \
libdancer2-plugin-database-perl \
libdancer-plugin-database-core-perl \
libdbd-mysql-perl \
libhttp-lite-perl \
libjson-perl \
libspreadsheet-parsexlsx-perl \
libsql-splitstatement-perl \
libyaml-perl \
perl \
libdbi-perl \
build-essential \
ffmpeg
EXPOSE 3000
RUN mkdir -p /app
WORKDIR /app
COPY . /app
# Simple placeholder command
CMD ["perl", "app.pl"]
+186
View File
@@ -0,0 +1,186 @@
#!/usr/bin/perl
use strict;
use Dancer2;
use Dancer2::Plugin::Database;
use Data::Dumper;
use SQL::SplitStatement;
use HTTP::Lite;
$SIG{'INT'} = sub { exit; };
hook before => sub {
my $origin = request_header('Origin') || 'http://localhost:8890';
my $method = request_header('Access-Control-Request-Method') || '';
my $headers = request_header('Access-Control-Request-Headers') || '';
response_header 'Access-Control-Allow-Origin' => $origin;
response_header 'Access-Control-Allow-Methods' => $method;
response_header 'Access-Control-Allow-Headers' => $headers;
};
options qr{/api/v1/.+} => sub {
return {};
};
get '/api/v1/hello' => sub {
my $user = session('user') || 'world';
return {'hello' => $user };
};
get '/api/v1/videos' => sub {
my $sth = database->prepare("SELECT id, file_path FROM videos ORDER BY id");
$sth->execute();
my $ref = $sth->fetchall_hashref('id');
$sth->finish();
return $ref;
};
get '/api/v1/video' => sub {
my $path = query_parameters->get("path");
my $sth = database->prepare("SELECT * FROM videos WHERE file_path=?");
$sth->execute($path);
my $ref = $sth->fetchrow_hashref();
$sth->finish();
unless(ref $ref) {
send_error("No video", 404);
}
return $ref;
};
get '/api/v1/video/:video' => sub {
my $video = route_parameters->get("video");
my $sth = database->prepare("SELECT * FROM videos WHERE id=?");
$sth->execute($video);
my $ref = $sth->fetchrow_hashref();
$sth->finish();
unless(ref $ref) {
send_error("No video", 404);
}
return $ref;
};
post '/api/v1/video' => sub {
my $file_path = body_parameters->get("file_path");
my $file_hash = body_parameters->get("file_hash") || undef;
my $resolution_w = body_parameters->get("resolution_w");
my $resolution_h = body_parameters->get("resolution_h");
my $codec = body_parameters->get("codec");
my $sth = database->prepare("INSERT INTO videos (file_path, file_hash, resolution_w, resolution_h, codec) VALUES (?, ?, ?, ?, ?)");
$sth->execute($file_path, $file_hash, $resolution_w, $resolution_h, $codec);
my $video_id = database->last_insert_id(undef, undef, 'videos', undef);
$sth->finish();
return { id => $video_id };
};
get '/api/v1/tasks' => sub {
my $status = query_parameters->get("status") || 'PENDING';
my $sth = database->prepare("SELECT id, video_id, status FROM tasks WHERE status=? ORDER BY id");
$sth->execute($status);
my $ref = $sth->fetchall_hashref('id');
$sth->finish();
return $ref;
};
get '/api/v1/task/:task' => sub {
my $task = route_parameters->get("task");
my $sth = database->prepare("SELECT * FROM tasks WHERE id=?");
$sth->execute($task);
my $ref = $sth->fetchrow_hashref();
$sth->finish();
unless(ref $ref) {
send_error("No task", 404);
}
return $ref;
};
get '/api/v1/nexttask/:type' => sub {
my $type = route_parameters->get("type");
my $sth = database->prepare("SELECT * FROM tasks WHERE task_type=? AND status='PENDING' ORDER BY id LIMIT 1");
$sth->execute($type);
my $ref = $sth->fetchrow_hashref();
$sth->finish();
unless(ref $ref) {
send_error("No task", 404);
}
# Mark the task as in progress and assign it to a worker
my $assign_key = "worker_" . int(rand(1000)); # Example assign key, you can customize this
my $update_sth = database->prepare("UPDATE tasks SET status='IN_PROGRESS', assign_key=?, assigned_at=NOW() WHERE id=? AND status='PENDING'");
$update_sth->execute($assign_key, $ref->{id});
if($update_sth->rows == 0) {
send_error("Failed to claim task", 409);
}
$update_sth->finish();
return { task => $ref, assign_key => $assign_key };
};
post '/api/v1/task/:task/complete' => sub {
my $task = route_parameters->get("task");
# Accept both JSON body and form-encoded data for assign_key/results.
my ($assign_key, $results);
my $ct = request_header('Content-Type') || '';
if ($ct eq 'application/json') {
my $body = decode_json(request->body());
$assign_key = $body->{assign_key};
$results = $body->{results};
} else {
$assign_key = body_parameters->get("assign_key");
$results = body_parameters->get("results");
}
unless ($assign_key) {
send_error("Missing assign_key", 400);
}
# Verify the task is assigned to the worker
my $sth = database->prepare("SELECT * FROM tasks WHERE id=? AND assign_key=? AND status='IN_PROGRESS'");
$sth->execute($task, $assign_key);
my $ref = $sth->fetchrow_hashref();
$sth->finish();
unless(ref $ref) {
send_error("Task not assigned to this worker or not in progress", 403);
}
# Update the task as completed (store results as JSON text for MariaDB)
my $results_json = defined $results ? encode_json($results) : 'null';
my $update_sth = database->prepare("UPDATE tasks SET status='COMPLETED', results=?, updated_at=NOW() WHERE id=?");
$update_sth->execute($results_json, $task);
if($update_sth->rows == 0) {
send_error("Failed to complete task", 500);
}
$update_sth->finish();
return { message => "Task completed successfully" };
};
post '/api/v1/task' => sub {
my $video_id = body_parameters->get("video_id");
my $task_type = body_parameters->get("task_type");
database->do("DELETE FROM tasks WHERE video_id=? AND task_type=?", undef, $video_id, $task_type);
my $sth = database->prepare("INSERT INTO tasks (video_id, task_type, status) VALUES (?, ?, 'PENDING')");
$sth->execute($video_id, $task_type);
my $task_id = database->last_insert_id(undef, undef, 'tasks', undef);
$sth->finish();
return { id => $task_id };
};
start();
+39
View File
@@ -0,0 +1,39 @@
serializer: JSON
logger: console
engines:
serializer:
JSON:
allow_nonref: 1
allow_blessed: 1
pretty: 1
plugins:
Database:
driver: 'mysql'
database: 'videodetect'
host: 'mariadb'
port: 3306
username: 'videodetect'
password: 'changeme_videodetect'
connection_check_threshold: 10
dbi_params:
RaiseError: 1
AutoCommit: 1
on_connect_do: ["SET NAMES 'utf8'", "SET CHARACTER SET 'utf8'" ]
log_queries: 1
server:
port: 5000
workers: 4
bind: 0.0.0.0
logging:
level: info
logdir: /var/log/videodetect/api
logfile: videodetect-api.log
format: "[%d] %l [%P] %m"
paths:
scratch: /scratch
input: /data/input
output: /data/output
models: /models
+15 -99
View File
@@ -18,119 +18,35 @@ USE videodetect;
CREATE TABLE IF NOT EXISTS videos (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
file_path VARCHAR(2048) NOT NULL,
file_hash CHAR(64) NOT NULL COMMENT 'SHA-256 hash of file',
file_size BIGINT NOT NULL COMMENT 'Size of the file in bytes',
file_hash CHAR(64) COMMENT 'SHA-256 hash of file',
resolution_w INT DEFAULT NULL,
resolution_h INT DEFAULT NULL,
codec VARCHAR(50) DEFAULT NULL,
duration FLOAT DEFAULT NULL COMMENT 'Duration in seconds',
status ENUM('NEW', 'PENDING', 'PROCESSING', 'COMPLETED', 'UNSCANNABLE', 'ERROR')
NOT NULL DEFAULT 'NEW' COMMENT 'Processing status',
last_scan_time DATETIME DEFAULT NULL,
last_processed_time DATETIME DEFAULT NULL,
confidence_score FLOAT DEFAULT NULL COMMENT 'Video-level confidence score',
routing_decision ENUM('MATCH', 'REVIEW', 'SKIP') DEFAULT NULL COMMENT 'Routing decision',
model_version VARCHAR(50) DEFAULT NULL COMMENT 'Model version used for processing',
frame_count INT DEFAULT NULL COMMENT 'Number of frames sampled',
error_message TEXT DEFAULT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_file_hash (file_hash),
INDEX idx_videos_status (status),
UNIQUE KEY uk_path (file_path),
INDEX idx_videos_last_scan (last_scan_time),
INDEX idx_videos_status_last_scan (status, last_scan_time),
INDEX idx_videos_file_path (file_path(255))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- -----------------------------------------------------
-- Table: processing_logs
-- Audit trail for each video processing job
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS processing_logs (
CREATE TABLE IF NOT EXISTS tasks (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
task_type VARCHAR(16) NOT NULL,
video_id BIGINT NOT NULL,
model_version VARCHAR(50) NOT NULL,
frame_count INT NOT NULL DEFAULT 0,
confidence_score FLOAT DEFAULT NULL,
confidence_scores JSON DEFAULT NULL COMMENT 'Frame-level confidence scores',
routing_decision ENUM('MATCH', 'REVIEW', 'SKIP') NOT NULL,
processed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
error_message TEXT DEFAULT NULL,
FOREIGN KEY (video_id) REFERENCES videos(id) ON DELETE CASCADE,
INDEX idx_processing_logs_video (video_id),
INDEX idx_processing_logs_processed_at (processed_at),
INDEX idx_processing_logs_routing (routing_decision)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- -----------------------------------------------------
-- Table: models
-- Model registry tracking all deployed and archived models
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS models (
version VARCHAR(50) PRIMARY KEY,
status ENUM('ACTIVE', 'CANDIDATE', 'ARCHIVED') NOT NULL DEFAULT 'CANDIDATE',
path VARCHAR(2048) NOT NULL,
calibration_temp FLOAT DEFAULT NULL COMMENT 'Temperature scaling parameter',
f1_score FLOAT DEFAULT NULL COMMENT 'F1 score on validation set',
ece_score FLOAT DEFAULT NULL COMMENT 'Expected Calibration Error',
deployed_at DATETIME DEFAULT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_models_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- -----------------------------------------------------
-- Table: review_queue
-- Videos awaiting manual annotation
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS review_queue (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
video_id BIGINT NOT NULL,
confidence_score FLOAT NOT NULL,
routing_decision ENUM('REVIEW') NOT NULL DEFAULT 'REVIEW',
annotated BOOLEAN NOT NULL DEFAULT FALSE,
ground_truth BOOLEAN DEFAULT NULL COMMENT 'True label from annotator',
annotated_at DATETIME DEFAULT NULL,
notes TEXT DEFAULT NULL,
status ENUM('PENDING', 'IN_PROGRESS', 'COMPLETED', 'FAILED') NOT NULL DEFAULT 'PENDING',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
assign_key VARCHAR(64) DEFAULT NULL COMMENT 'Key to identify the worker assigned to this task',
assigned_at DATETIME DEFAULT NULL COMMENT 'Timestamp when the task was assigned to a worker',
results JSON DEFAULT NULL COMMENT 'Task-specific results or metadata',
FOREIGN KEY (video_id) REFERENCES videos(id) ON DELETE CASCADE,
INDEX idx_review_queue_annotated (annotated),
INDEX idx_review_queue_created (created_at)
INDEX idx_tasks_video (video_id),
INDEX idx_tasks_status (status),
INDEX idx_tasks_type_status (task_type, status),
UNIQUE KEY uk_tasks_video_type (video_id, task_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- -----------------------------------------------------
-- Table: scan_history
-- Tracks directory scan operations for incremental sync
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS scan_history (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
scan_start DATETIME NOT NULL,
scan_end DATETIME DEFAULT NULL,
files_discovered INT DEFAULT 0,
files_new INT DEFAULT 0,
files_modified INT DEFAULT 0,
files_removed INT DEFAULT 0,
files_unscannable INT DEFAULT 0,
duration_seconds FLOAT DEFAULT NULL,
status ENUM('RUNNING', 'COMPLETED', 'FAILED') NOT NULL DEFAULT 'RUNNING',
error_message TEXT DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- -----------------------------------------------------
-- Table: scanner_lock
-- Single-instance guard for the directory scanner. Ensures only one scan
-- runs at a time across all replicas. A lease (locked_at + lease_seconds)
-- lets a live scanner keep the lock via heartbeats, and lets a crashed
-- scanner's lock be taken over once it goes stale.
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS scanner_lock (
lock_name VARCHAR(64) PRIMARY KEY,
owner VARCHAR(128) NOT NULL COMMENT 'Instance id (host-pid-uuid) holding the lock',
locked_at DATETIME NOT NULL COMMENT 'Last time the lock was acquired or heartbeated',
lease_seconds INT NOT NULL DEFAULT 21600 COMMENT 'Lock is stale if older than this (6 hours)'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- -----------------------------------------------------
-- Insert default model entry
-- -----------------------------------------------------
INSERT IGNORE INTO models (version, status, path, calibration_temp, created_at)
VALUES ('v0.0.0-placeholder', 'ACTIVE', '/models/placeholder', 1.0, NOW());
+19 -81
View File
@@ -5,9 +5,9 @@ services:
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:-rootpass}
MYSQL_DATABASE: videodetect
MYSQL_USER: videodetect
MYSQL_PASSWORD: ${DB_PASSWORD:-videodetect123}
MYSQL_DATABASE: ${DB_NAME:-videodetect}
MYSQL_USER: ${DB_USER:-videodetect}
MYSQL_PASSWORD: ${DB_PASSWORD:-changeme_videodetect}
ports:
- "3306:3306"
volumes:
@@ -25,50 +25,6 @@ services:
limits:
memory: 2G
worker:
build:
context: .
dockerfile: worker/Dockerfile
container_name: videodetect-worker
restart: unless-stopped
environment:
- NVIDIA_VISIBLE_DEVICES=all
- NVIDIA_DRIVER_CAPABILITIES=compute,utility
- DB_HOST=mariadb
- DB_PORT=3306
- DB_NAME=videodetect
- DB_USER=videodetect
- DB_PASSWORD=${DB_PASSWORD:-videodetect123}
- CONFIG_PATH=/app/config.yaml
volumes:
- /dev/null:/dev/null # tmpfs mounted at /scratch in container
- nas_input:/data/input:ro
- ${NAS_OUTPUT_PATH:-./output}:/data/output
- ${MODELS_PATH:-./models}:/models
- ${TRAINING_PATH:-./training}:/data/training
tmpfs:
- /scratch:noexec,nosuid,size=100G
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: ["gpu"]
limits:
memory: 24G
networks:
- videodetect-network
depends_on:
mariadb:
condition: service_healthy
healthcheck:
test: ["CMD", "python3", "-c", "import torch; print(torch.cuda.is_available())"]
interval: 30s
timeout: 10s
retries: 3
start_period: 60s
ui:
build:
context: ./ui
@@ -82,7 +38,7 @@ services:
- DB_PORT=3306
- DB_NAME=videodetect
- DB_USER=videodetect
- DB_PASSWORD=${DB_PASSWORD:-videodetect123}
- DB_PASSWORD=${DB_PASSWORD:-changeme_videodetect}
- FLASK_ENV=production
volumes:
- ./ui:/app
@@ -98,50 +54,32 @@ services:
limits:
memory: 512M
prometheus:
image: prom/prometheus:v2.48.0
container_name: videodetect-prometheus
restart: unless-stopped
ports:
- "9090:9090"
volumes:
- ./monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- prometheus_data:/prometheus
networks:
- videodetect-network
deploy:
resources:
limits:
memory: 1G
grafana:
image: grafana/grafana:10.2.0
container_name: videodetect-grafana
restart: unless-stopped
api:
build:
context: ./api
dockerfile: Dockerfile
container_name: videodetect-api
restart: no
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:-admin}
- GF_USERS_ALLOW_SIGN_UP=false
- DB_HOST=mariadb
- DB_PORT=3306
- DB_NAME=videodetect
- DB_USER=videodetect
- DB_PASSWORD=${DB_PASSWORD:-changeme_videodetect}
- DANCER_ENVIRONMENT=production
volumes:
- grafana_data:/var/lib/grafana
- ./monitoring/grafana/provisioning:/etc/grafana/provisioning:ro
- ./api:/app
networks:
- videodetect-network
depends_on:
- prometheus
deploy:
resources:
limits:
memory: 512M
mariadb:
condition: service_healthy
volumes:
mariadb_data:
driver: local
prometheus_data:
driver: local
grafana_data:
driver: local
nas_input:
driver: local
driver_opts:
+23
View File
@@ -0,0 +1,23 @@
FROM ubuntu:22.04
# Install Perl, system deps, and ffmpeg (includes ffprobe)
RUN apt update && apt install -y \
libdbd-mysql-perl \
libhttp-lite-perl \
libjson-perl \
libyaml-perl \
perl \
libdbi-perl \
build-essential \
ffmpeg \
libstring-shellquote-perl
EXPOSE 3000
RUN mkdir -p /app
WORKDIR /app
COPY . /app
# Simple placeholder command
CMD ["perl", "scanner.pl"]
+34
View File
@@ -0,0 +1,34 @@
# VideoDetect — Scanner service (standalone compose file)
# Run: docker compose -f scanner-compose.yml up -d
services:
scanner:
build:
context: ./
dockerfile: Dockerfile
container_name: videodetect-scanner
restart: no
environment:
- DB_HOST=${DB_HOST}
- DB_PORT=3306
- DB_NAME=${DB_NAME}
- DB_USER=${DB_USER}
- DB_PASSWORD=${DB_PASSWORD}
- API_HOST=${API_HOST}
volumes:
- nas_input:/data:ro
- $PWD/scanner.pl:/app/scanner.pl:ro
networks:
- videodetect_videodetect-network
volumes:
nas_input:
driver: local
driver_opts:
type: nfs
o: addr=10.0.0.2,ro,nfsvers=4,hard,intr
device: ":/mnt/Bulk/Homes/ryan/Prawns"
networks:
videodetect_videodetect-network:
external: true
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use Digest::SHA qw(sha256_hex);
use JSON;
use String::ShellQuote qw/shell_quote/;
my $db_host = $ENV{'DB_HOST'} || 'mariadb';
my $db_name = $ENV{'DB_NAME'} || 'videodetect';
my $db_user = $ENV{'DB_USER'} || 'videodetect';
my $db_pass = $ENV{'DB_PASSWORD'} || 'videodetect123';
$SIG{INT} = sub { die "Interrupted\n"; };
my $dbh = DBI->connect("DBI:mysql:database=$db_name;host=$db_host", $db_user, $db_pass);
my @video_extensions = qw(mp4 mkv avi mov flv wmv mpg mpeg webm);
my @dir_queue = ('/data');
# Get NOW() from the database
my $sth = $dbh->prepare("SELECT NOW() AS now");
$sth->execute();
my $row = $sth->fetchrow_hashref();
my $now = $row->{now};
$sth->finish();
while(my $dir = shift @dir_queue) {
opendir(my $dh, $dir) or die "Cannot open directory $dir: $!";
print "$dir\n";
while (my $file = readdir($dh)) {
next if ($file eq '.' || $file eq '..');
my $full_path = "$dir/$file";
if (-d $full_path) {
unshift @dir_queue, $full_path;
} elsif (-f $full_path) {
process_file($full_path);
}
}
closedir($dh);
}
# Any entry where last_scan_time < $now is considered deleted or moved, so we can mark them as such
my $sth_delete = $dbh->prepare("DELETE FROM videos WHERE last_scan_time < ? OR last_scan_time IS NULL");
$sth_delete->execute($now);
sub process_file {
my ($file_path) = @_;
# Determine if the file is a video based on mime info or extension. For simplicity, let's check the extension.
if (my ($ext)=$file_path =~ /^.+\.(\S+?)$/) {
unless (grep { lc($ext) eq $_ } @video_extensions) {
return; # Not a video file
}
}
print "$file_path\n";
my $sth = $dbh->prepare("SELECT id,file_size FROM videos WHERE file_path=?");
$sth->execute($file_path);
if(my $row = $sth->fetchrow_hashref()) {
my $file_size = -s $file_path;
if ($file_size != $row->{file_size}) {
warn "File size mismatch for $file_path. Updating record.";
my $update_sth = $dbh->prepare("UPDATE videos SET file_size=?, last_scan_time=NOW() WHERE id=?");
$update_sth->execute($file_size, $row->{id});
$update_sth->finish();
create_aiscan_task($row->{id});
}
return; # Already exists and size matches
}
my $info = get_video_info($file_path);
unless ($info) {
warn "Failed to get video info for $file_path. Skipping.";
return;
}
$sth = $dbh->prepare("INSERT INTO videos (file_path, file_size, file_hash, resolution_w, resolution_h, codec, duration, last_scan_time) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
$sth->execute(
$file_path,
-s $file_path,
$info->{file_hash},
$info->{resolution_w},
$info->{resolution_h},
$info->{codec},
$info->{duration}
);
$sth->finish();
my $video_id = $dbh->last_insert_id(undef, undef, 'videos', undef);
create_aiscan_task($video_id);
}
sub create_aiscan_task {
my ($video_id) = @_;
$dbh->do("DELETE FROM tasks WHERE video_id=$video_id AND task_type='AISCAN'");
my $sth = $dbh->prepare("INSERT INTO tasks (video_id, task_type, status) VALUES (?, 'AISCAN', 'PENDING')");
$sth->execute($video_id);
$sth->finish();
}
sub get_video_info {
my ($file_path) = @_;
# --- Compute SHA-256 hash of the file ---
return undef unless -f $file_path && -r $file_path;
open(my $fh, '<:raw', $file_path) or do { warn "Cannot open $file_path: $!"; return undef; };
my $hash = sha256_hex($fh);
close($fh);
# --- Run ffprobe to extract metadata ---
my $probe_cmd = 'ffprobe -v quiet -print_format json -show_format -show_streams ' . shell_quote($file_path);
my $output = `$probe_cmd`;
return undef unless defined $output && length($output);
my $json = JSON->new->utf8->canonical(1);
my $data = $json->decode($output);
# --- Extract codec from video stream (prefer first video stream found) ---
my $codec = undef;
if (exists $data->{streams} && ref($data->{streams}) eq 'ARRAY') {
for my $stream (@{$data->{streams}}) {
if ($stream->{codec_type} eq 'video') {
$codec = $stream->{codec_name};
last;
}
}
}
# --- Extract resolution and duration from format/streams ---
my ($resolution_w, $resolution_h, $duration);
# Duration from format first, then stream
if (exists $data->{format} && exists $data->{format}{duration}) {
$duration = $data->{format}{duration} + 0; # force numeric
} elsif (exists $data->{streams}[0] && exists $data->{streams}[0]{duration}) {
$duration = $data->{streams}[0]{duration} + 0;
}
# Resolution from video stream first, then format side data
if (exists $data->{streams} && ref($data->{streams}) eq 'ARRAY') {
for my $stream (@{$data->{streams}}) {
next unless $stream->{codec_type} eq 'video';
if ($stream->{width} && $stream->{height}) {
$resolution_w = $stream->{width};
$resolution_h = $stream->{height};
last;
}
}
}
return {
file_hash => $hash,
resolution_w => $resolution_w // 0,
resolution_h => $resolution_h // 0,
codec => $codec // 'unknown',
duration => $duration,
};
}
+136
View File
@@ -0,0 +1,136 @@
"""HTTP client for VideoDetect's Perl REST API (api/app.pl).
Wraps the three worker-facing endpoints:
GET /api/v1/nexttask/:type — claim next pending task
GET /api/v1/video/:id — fetch video metadata
POST /api/v1/task/:task/complete — submit results
Uses the ``requests`` library; raises :class:`ApiError` on unexpected HTTP status codes.
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass, field
from typing import Any, Optional
import requests
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Exception
# ---------------------------------------------------------------------------
class ApiError(Exception):
"""Raised when the API returns an unexpected error status."""
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message
super().__init__(f"API error {status_code}: {message}")
# ---------------------------------------------------------------------------
# Client
# ---------------------------------------------------------------------------
class ApiClient:
"""Thin HTTP client for the Dancer2 REST API."""
def __init__(self, base_url: str = "http://localhost:3000"):
self.base_url = base_url.rstrip("/")
self.session = requests.Session()
logger.info("API client configured: base_url=%s", self.base_url)
# -- helpers -------------------------------------------------------------
def _get(self, path: str, **kwargs: Any) -> dict:
url = f"{self.base_url}{path}"
resp = self.session.get(url, **kwargs)
if resp.status_code == 404:
logger.debug("GET %s → 404", url)
return {} # caller distinguishes "not found" from real data
resp.raise_for_status()
return resp.json()
def _post(self, path: str, json_body: dict[str, Any]) -> dict:
"""POST a JSON body (Content-Type: application/json)."""
url = f"{self.base_url}{path}"
logger.debug("POST %s%s", url, json.dumps(json_body))
resp = self.session.post(url, json=json_body)
resp.raise_for_status()
return resp.json()
# -- public API ----------------------------------------------------------
def get_next_task(self, task_type: str) -> Optional[dict[str, Any]]:
"""Claim the next pending task.
Returns ``{"task": {...}, "assign_key": "worker_NNN"}`` on success,
or ``None`` when no PENDING tasks remain (HTTP 404).
"""
path = f"/api/v1/nexttask/{task_type}"
result = self._get(path)
if not result:
return None
assert "task" in result and "assign_key" in result, \
f"Unexpected response shape: {result}"
return result
def get_video(self, video_id: int) -> dict[str, Any]:
"""Fetch full video metadata by integer ID.
Raises :class:`ApiError` if the video is not found (404).
"""
path = f"/api/v1/video/{video_id}"
result = self._get(path)
if not result:
raise ApiError(404, f"Video {video_id} not found")
assert "id" in result, f"Unexpected video response shape: {result}"
return result
def submit_results(
self,
task_id: int,
assign_key: str,
results: dict[str, Any],
) -> dict[str, Any]:
"""Submit processing results for a claimed task.
Args:
task_id: The database ID returned by ``get_next_task``.
assign_key: The worker token returned by ``get_next_task``.
results: A JSON-serializable dict (status, confidence, routing_decision, etc.).
Returns the server response dict on success.
Raises :class:`ApiError` on 4xx/5xx.
"""
path = f"/api/v1/task/{task_id}/complete"
return self._post(path, {
"assign_key": assign_key,
"results": results,
})
def create_task(self, task_type: str, video_id: int) -> dict[str, Any]:
"""Create a new pending task.
Args:
task_type: Task type string (e.g. 'AISCAN', 'REVIEW').
video_id: The video to associate the task with.
Returns the server response dict on success.
Raises :class:`ApiError` on 4xx/5xx.
"""
path = "/api/v1/tasks"
return self._post(path, {
"task_type": task_type,
"video_id": video_id,
"status": "PENDING",
})
def close(self) -> None:
"""Close the underlying HTTP session."""
self.session.close()
+297
View File
@@ -0,0 +1,297 @@
"""Standalone AI-processing pipeline for the task-worker architecture.
``process_video(video_dict, config)`` runs the full scan pipeline on a single
video file and returns a results dict that can be submitted via the REST API.
It reuses existing classes from the codebase:
* ``VideoProber`` ffprobe metadata extraction
* ``ScratchManager`` per-video temp dirs under /scratch
* ``FrameSampler`` uniform frame extraction via ffmpeg
* ``FaceDetector`` TensorRT face detection on sampled frames
* ``FaceClassifier`` MobileNetV3 classification of face crops
* ``aggregator.aggregate`` per-crop → video-level confidence
* ``router.route`` routing thresholds (MATCH / REVIEW / SKIP)
GPU model loading is lazily initialised and cached at module level so that
sequential invocations within the same Python process reuse the same loaded
engines. This is important because each short-lived worker may be asked to
process several tasks in a row (``--tasks N``).
"""
from __future__ import annotations
import logging
import os
import time
from pathlib import Path
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Lazy imports — avoid heavy imports until actually needed
# ---------------------------------------------------------------------------
_face_detector_instance: Optional[Any] = None
_classifier_instance: Optional[Any] = None
def _get_face_detector(config: dict) -> Any:
"""Return a singleton ``FaceDetector`` (initialised once per process)."""
global _face_detector_instance
if _face_detector_instance is not None:
return _face_detector_instance
from face_detector import FaceDetector # noqa: local import, heavy
cfg = (config or {}).get("face_detection", {})
engine_path = cfg.get(
"model_path", "/models/face_detector/face_detector.trt"
)
_face_detector_instance = FaceDetector(
engine_path=engine_path,
input_size=int(cfg.get("input_size", 640)),
confidence_threshold=float(cfg.get("confidence_threshold", 0.25)),
iou_threshold=float(cfg.get("iou_threshold", 0.45)),
max_faces_per_frame=int(cfg.get("max_faces_per_frame", 10)),
max_faces_per_video=int(cfg.get("max_faces_per_video", 100)),
)
return _face_detector_instance
def _get_classifier(config: dict) -> Any:
"""Return a singleton ``FaceClassifier`` (initialised once per process)."""
global _classifier_instance
if _classifier_instance is not None:
return _classifier_instance
from classifier import FaceClassifier # noqa: local import, heavy
cfg = (config or {}).get("classifier", {})
engine_path = cfg.get(
"model_path", "/models/classifier/classifier.trt"
)
_classifier_instance = FaceClassifier(
engine_path=engine_path,
temperature=float(cfg.get("temperature", 1.0)),
input_size=int(cfg.get("input_size", 224)),
)
return _classifier_instance
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def get_model_version() -> str:
"""Return the currently active model version from the DB (best-effort)."""
try:
from db_connector import DatabaseConnector # noqa: local import, heavy
db = DatabaseConnector("default")
row = db.fetchone(
"SELECT version FROM models WHERE status = 'ACTIVE' LIMIT 1"
)
if row:
return row["version"]
except Exception as exc:
logger.debug("Could not fetch active model version: %s", exc)
return "v0.0.0-placeholder"
def process_video(video: Dict[str, Any], config: Optional[Dict] = None) -> Dict[str, Any]:
"""Run the full AI scan pipeline on a single video file.
Args:
video: Metadata dict (as returned by ``ApiClient.get_video``).
Must contain at minimum ``"id"`` and ``"file_path"``.
config: The loaded ``config.yaml`` dict (or None for defaults).
Returns:
A results dict suitable for submission via the REST API.
"""
config = config or {}
start_time = time.time()
video_id = video["id"]
file_path = video["file_path"]
logger.info("Processing video %d: %s", video_id, file_path)
sampling_cfg = (config or {}).get("sampling", {})
storage_cfg = (config or {}).get("storage", {})
gpu_cfg = (config or {}).get("gpu", {})
batching_cfg = (config or {}).get("batching", {})
agg_cfg = (config or {}).get("aggregation", {})
routing_cfg = (config or {}).get("routing", {})
try:
# 1. Probe metadata (use DB metadata if already populated, re-probe)
prober = VideoProber(timeout=10)
metadata = prober.probe(file_path)
if metadata.is_unscannable:
raise RuntimeError(metadata.error_message or "Video metadata could not be determined")
# Use video from API if available, fall back to probe results
resolution_w = video.get("resolution_w") or metadata.resolution_w or 640
resolution_h = video.get("resolution_h") or metadata.resolution_h or 480
duration = video.get("duration") or metadata.duration or 10.0
logger.info(
"Video %d: codec=%s resolution=%dx%d duration=%.1fs",
video_id, metadata.codec or "unknown",
resolution_w, resolution_h, duration,
)
# 2. Set up scratch space
scratch = ScratchManager(
base_path=storage_cfg.get("scratch_path", "/scratch"),
video_id=str(video_id),
auto_cleanup=True,
)
frame_dir = scratch.ensure_frame_dir()
# 3. Sample frames
interval = int(sampling_cfg.get("interval_seconds", 30))
quality = int(sampling_cfg.get("quality", 2))
sampler = FrameSampler(interval_seconds=interval, quality=quality)
resolution = (resolution_w, resolution_h)
extracted_frames = sampler.extract_frames(
video_path=file_path,
output_dir=str(frame_dir),
duration=duration,
interval_seconds=interval,
resolution=resolution,
timeout_seconds=30,
)
if not extracted_frames:
scratch.cleanup_all()
raise RuntimeError("No frames were extracted")
logger.info(
"Video %d: extracted %d frame(s)", video_id, len(extracted_frames)
)
# 4. Face detection
detector = _get_face_detector(config)
batch_size = _get_batch_size(gpu_cfg, batching_cfg)
detections_per_frame = detector.detect_faces(
extracted_frames, batch_size=batch_size
)
all_detections = sorted(
[d for dets in detections_per_frame for d in dets],
key=lambda d: d.confidence,
reverse=True,
)
total_faces = len(all_detections)
# 5. Classify (or SKIP if no faces)
if total_faces == 0:
logger.info(
"Video %d: no faces detected → routing to SKIP", video_id
)
scratch.cleanup_all()
return _failed_result(video_id, start_time, 0.0, "SKIP")
crop_dir = Path(scratch.frame_dir.parent) / "crops"
cropped_detections = detector.extract_crops(
all_detections, output_dir=str(crop_dir), crop_size=(224, 224)
)
crop_paths = [d.crop_path for d in cropped_detections if d.crop_path]
classifier = _get_classifier(config)
frame_confidences = classifier.classify(
crop_paths, batch_size=batch_size
)
# 6. Aggregate confidence
from aggregator import aggregate as agg_func # noqa: local import
video_confidence = agg_func(
frame_confidences,
strategy=agg_cfg.get("strategy", "max"),
alpha=float(agg_cfg.get("alpha", 1.0)),
beta=float(agg_cfg.get("beta", 0.1)),
top_k=int(agg_cfg.get("top_k", 3)),
)
# 7. Route
from router import route as route_fn # noqa: local import
routing = route_fn(
video_confidence,
t_high=float(routing_cfg.get("T_high", 0.75)),
t_low=float(routing_cfg.get("T_low", 0.45)),
)
processing_time = time.time() - start_time
logger.info(
"Video %d complete: C=%.4f routing=%s faces=%d frames=%d time=%.1fs",
video_id, video_confidence, routing, total_faces,
len(extracted_frames), processing_time,
)
scratch.cleanup_all()
return {
"status": "COMPLETED",
"confidence": round(video_confidence, 4),
"routing_decision": routing,
"face_count": total_faces,
"frame_count": len(extracted_frames),
"model_version": get_model_version(),
"processing_time_seconds": round(processing_time, 2),
"error": None,
}
except Exception as exc:
logger.error("Processing video %d failed: %s", video_id, exc, exc_info=True)
try:
scratch.cleanup_all() # noqa: undefined-name guard below
except NameError:
pass # scratch was never created (probe/probe error)
return {
"status": "FAILED",
"confidence": 0.0,
"routing_decision": "REVIEW",
"face_count": 0,
"frame_count": 0,
"model_version": get_model_version(),
"processing_time_seconds": round(time.time() - start_time, 2),
"error": str(exc),
}
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _get_batch_size(gpu_cfg: dict, batching_cfg: dict) -> int:
"""Compute an appropriate batch size based on GPU config."""
from gpu_manager import GPUMemoryManager # noqa: local import, heavy
mgr = GPUMemoryManager(
max_memory_gb=gpu_cfg.get("max_memory_gb", 18.0),
reduce_threshold_gb=batching_cfg.get("vram_reduce_threshold_gb", 16.0),
increase_threshold_gb=batching_cfg.get("vram_increase_threshold_gb", 10.0),
initial_batch_size=batching_cfg.get("max_batch_size", 16),
)
return mgr.current_batch_size
def _failed_result(
video_id: int, start_time: float, confidence: float, routing: str
) -> Dict[str, Any]:
"""Build a SKIP/early-exit result dict (no faces case)."""
return {
"status": "COMPLETED",
"confidence": round(confidence, 4),
"routing_decision": routing,
"face_count": 0,
"frame_count": 0,
"model_version": get_model_version(),
"processing_time_seconds": round(time.time() - start_time, 2),
"error": None,
}
+186
View File
@@ -0,0 +1,186 @@
"""VideoDetect task worker — short-lived process for AI scanning.
Usage::
python3 -m src.task_worker # process 1 task and exit
python3 -m src.task_worker --tasks 50 # process up to 50 tasks
python3 src/task_worker.py --tasks 10 # direct invocation
Environment variables:
API_BASE_URL (default http://localhost:3000)
Base URL of the Dancer2 REST API.
TASK_COUNT (default 1)
Maximum number of tasks to process before exiting.
On success exits with code 0; on unrecoverable errors exits non-zero.
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import signal
import sys
from pathlib import Path
# Ensure the src/ directory is on sys.path so our submodules import cleanly
_src = Path(__file__).resolve().parent
if str(_src) not in sys.path:
sys.path.insert(0, str(_src))
from api_client import ApiClient, ApiError
from task_processor import process_video, get_model_version
from config_loader import get_config
from logging_config import setup_logging
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Graceful shutdown
# ---------------------------------------------------------------------------
_shutdown_requested = False
def _signal_handler(signum: int, frame) -> None:
logger.info("Received signal %d — finishing current task then exiting", signum)
global _shutdown_requested
_shutdown_requested = True
signal.signal(signal.SIGTERM, _signal_handler)
signal.signal(signal.SIGINT, _signal_handler)
# ---------------------------------------------------------------------------
# CLI entry point
# ---------------------------------------------------------------------------
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="VideoDetect task worker — process AI scan tasks",
)
parser.add_argument(
"--tasks",
type=int,
default=int(os.environ.get("TASK_COUNT", "1")),
help="Number of tasks to process before exiting (default: 1 or $TASK_COUNT)",
)
parser.add_argument(
"--api-url",
default=os.environ.get("API_BASE_URL", "http://localhost:3000"),
help="Base URL of the Dancer2 REST API (default: http://localhost:3000)",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Run the task worker loop.
Returns exit code (0 = success).
"""
args = parse_args(argv)
# Load config for the processing pipeline
config = get_config()
# Setup JSON logging
log_cfg = (config or {}).get("logging", {})
setup_logging(
level=log_cfg.get("level", "INFO"),
log_format=log_cfg.get("format", "json"),
rotation_max_bytes=log_cfg.get("rotation_max_bytes", 104857600),
rotation_backup_count=log_cfg.get("rotation_backup_count", 10),
)
model_version = get_model_version()
logger.info(
"Task worker starting. Will process up to %d task(s). Model version: %s",
args.tasks,
model_version,
)
api = ApiClient(base_url=args.api_url)
total_attempted = 0
total_succeeded = 0
total_failed = 0
try:
for i in range(1, args.tasks + 1):
if _shutdown_requested:
logger.info("Shutdown requested after %d/%d tasks", i - 1, args.tasks)
break
logger.info("=== Processing task %d/%d ===", i, args.tasks)
# 1. Claim a task
response = api.get_next_task("AISCAN")
if response is None:
logger.info("No more tasks available (API returned no task)")
break
task_id = response["task"]["id"]
assign_key = response["assign_key"]
video_id = response["task"]["video_id"]
total_attempted += 1
logger.info(
"Claiming task %d (video_id=%d) for AISCAN", task_id, video_id
)
# 2. Fetch video metadata
try:
video = api.get_video(video_id)
except ApiError as exc:
logger.error("Failed to fetch video %d via API: %s", video_id, exc)
total_failed += 1
continue
# 3. Process the video (AI pipeline)
results = process_video(video, config=config)
if results["status"] == "COMPLETED":
logger.info(
"Video %d complete: C=%.4f routing=%s faces=%d frames=%d time=%.1fs",
video_id,
results.get("confidence", 0),
results.get("routing_decision", "?"),
results.get("face_count", 0),
results.get("frame_count", 0),
results.get("processing_time_seconds", 0),
)
total_succeeded += 1
else:
logger.warning(
"Video %d failed: %s",
video_id,
results.get("error", "unknown error"),
)
total_failed += 1
# 4. Submit results via API
try:
api.submit_results(task_id, assign_key, results)
logger.info("Submitted results for task %d via API", task_id)
except ApiError as exc:
logger.error(
"Failed to submit results for task %d: %s", task_id, exc
)
finally:
api.close()
logger.info(
"Task worker finished: %d attempted, %d succeeded, %d failed",
total_attempted,
total_succeeded,
total_failed,
)
return 0
if __name__ == "__main__":
sys.exit(main())
+2 -2
View File
@@ -64,5 +64,5 @@ HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
# Switch to non-root user
USER appuser
# Default command
CMD ["python3", "-m", "src.main"]
# Default command: process tasks from the API until drained
CMD ["python3", "-m", "src.task_worker"]
+40
View File
@@ -0,0 +1,40 @@
# VideoDetect — Worker service (standalone compose file)
# Run: docker compose -f worker/docker-compose.yml up -d
services:
worker:
build:
context: ./
dockerfile: Dockerfile
container_name: videodetect-worker
restart: "no"
environment:
- API_BASE_URL=${API_BASE_URL:-http://videodetect-api:3000}
- TASK_COUNT=${TASK_COUNT:-50}
- REVIEW_CONFIDENCE=${REVIEW_CONFIDENCE:-0.75}
- LOG_FILE=/logs/videodetect.log
volumes:
- nas_input:/data/input:ro
- scratch_data:/scratch
- $PWD/worker-logs:/logs
networks:
- videodetect_videodetect-network
deploy:
resources:
limits:
memory: 4G
nvidia-gpus: "1"
volumes:
nas_input:
driver: local
driver_opts:
type: nfs
o: addr=10.0.0.2,ro,nfsvers=4,hard,intr
device: ":/mnt/Bulk/Homes/ryan/Prawns"
scratch_data:
driver: local
networks:
videodetect_videodetect-network:
external: true