Files

280 lines
14 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Feedmill Recounter
AI video analysis tool for counting objects (sacks, boxes) in feedmill videos.
Built on top of [karung_counter_semarang](https://git.proit.id/andrew/karung-counting-feedmill-semarang).
## Features
- **CLI**: Process videos from the command line with any model + class filter
- **Web UI**: Upload videos, select models, download annotated output on port 9050
- **Live Preview**: MJPEG streaming — watch processing in real-time (15+ FPS at 640p)
- **Multiple Models**: Run multiple model configurations on the same video for comparison
- **Model Groups**: Models grouped by stem (e.g., `best.pt`, `best.engine`) with format dropdown
- **Model Upload & Conversion**: Upload `.pt`/`.onnx`/`.engine` weights from the web UI; convert `.pt`/`.onnx` sources to TensorRT `.engine` in the background with progress polling
- **Class Filtering**: Choose which classes to count (sack, box, truck)
- **Auto Truck Detection**: Automatically loads `truck-detector` when selected model lacks truck class
- **Counting Zone Modes**: Auto truck detection, fixed zone presets (zones.json), or auto-detect then freeze
- **Sack/Box Counts**: Separate in/out counts per object class in results
- **Video Reuse**: Re-analyze previously uploaded videos without re-uploading
- **Annotated Output**: Download MP4 videos with detection overlays for human review
- **720p Output Option**: Downscale annotated MP4 to 720p for smaller files / faster encode
- **Async Processing**: Background job queue — upload and poll status
- **Abort**: Cancel running jobs mid-processing
## Quick Start
```bash
pip install -e ".[dev]"
# List available models
recounter --list-models --models-dir ./models
# Process a single video via CLI
recounter --video input.mp4 --model v4-best.pt --filter sack --output-dir ./output
# Start web UI
recounter-web
# Open http://localhost:9050
```
### Comparing with the live system (RTSP)
The recounter analyses files. The live counter streams over RTSP, so compare
both on the **same** footage by recording the stream first:
```bash
tools/record_rtsp.sh rtsp://CAMERA/stream /tmp/opencode/compare.ts 300
```
Analyse the recording with the CLI — it takes any file OpenCV can open,
including `.ts`:
```bash
recounter --video /tmp/opencode/compare.ts --model v4-best.pt --filter sack --output-dir ./output
```
The web upload only accepts `.mp4`, `.avi`, `.mkv`, `.mov` and `.webm`, so
remux the recording first if you want to use the web UI:
```bash
ffmpeg -i /tmp/opencode/compare.ts -c copy /tmp/opencode/compare.mp4
```
Point the live system's source at the same file. A live RTSP run and a
recorded-file run can still differ in frame timing, so compare files, not a
live run against a file.
## CLI Reference
```
recounter --video PATH Input video file
--model NAME Model filename (repeatable for multiple)
--all-models Run all discovered models
--list-models List available models and exit
--filter NAME Class filter (repeatable): sack, box, truck
--sack-conf FLOAT Sack confidence threshold (default: 0.4)
--truck-conf FLOAT Truck confidence threshold (default: 0.5)
--output PATH Output path (single model only)
--output-dir DIR Output directory (default: ./output)
--output-height INT Downscale annotated output to this height (e.g. 720)
--models-dir DIR Models directory (default: ./models)
--zone-mode MODE fixed (default, uses zones.json), dynamic, or freeze
--zone-preset NAME Preset name in zones.json (default: active_preset)
--zones-path PATH Path to zones.json (default: ./zones.json)
```
## Web UI
- **Port**: 9050 (configurable via `WEB_PORT` env)
- **Upload**: Drag-and-drop or click to upload video, or select from previously uploaded videos
- **Model Selection**: Grouped cards with format dropdown (`.engine` / `.pt` / `.onnx`) and class filter
- **Live Preview**: Real-time MJPEG stream during processing
- **Job Status**: Auto-refreshing progress page with abort button
- **Download**: Annotated MP4 per model result
### Output lifecycle
- A finished job leaves **one** video: the annotated output is compressed in
place when the job ends (the compressed copy replaces the uncompressed
source under the same file name). Files over 250 MB are compressed; the
download name is the plain one — there is no `_compressed` file.
- Job videos are **deleted 5 days** after the job
(`scripts/purge_expired_outputs.py`, run daily by cron). The job
directory, the thumbnail and the sample frames stay. A temp file of an
encode in flight is swept after 2 h.
## API Endpoints
| Endpoint | Method | Description |
|---|---|---|
| `/` | GET | Upload form with model groups |
| `/upload` | POST | Start processing job |
| `/upload/reuse` | POST | Re-analyze an existing uploaded video |
| `/status/<job_id>` | GET | Job status with results |
| `/jobs` | GET | All jobs listing |
| `/download/<job_id>/<filename>` | GET | Download output video |
| `/preview/thumb/<job_id>` | GET | Thumbnail JPEG for a job's video |
| `/api/preview/<job_id>` | GET | MJPEG live stream during processing |
| `/api/models` | GET | List model groups (JSON) |
| `/api/models/upload` | POST | Upload a model file (`.pt`/`.onnx`/`.engine`); aliases `/api/model/upload`, `/api/upload/model`, `/models/upload`, `/upload/model` |
| `/api/models/<stem>/convert` | POST | Start `.pt`/`.onnx` -> `.engine` conversion; aliases accept the stem in the URL or request body |
| `/api/models/conversions` | GET | List conversion jobs |
| `/api/models/conversions/<id>` | GET | Conversion job status |
| `/api/models/conversions/<id>/cancel` | POST | Cancel a conversion |
| `/api/videos` | GET | List uploaded videos (JSON) |
| `/api/videos/<filename>` | DELETE | Delete an uploaded video |
| `/api/jobs` | GET | List all jobs (JSON) |
| `/api/jobs/<job_id>` | GET | Job detail (JSON) |
| `/api/jobs/<job_id>/cancel` | POST | Cancel a running job |
| `/api/jobs/<job_id>/samples` | GET | Sample frame paths (JSON) |
| `/calibrate` | GET | Interactive zone editor |
| `/api/zones` | GET | Zone preset list (JSON) |
| `/api/zones/<preset>` | GET | One zone preset (JSON) |
| `/api/zones/<preset>` | POST | Save a zone preset (localhost only) |
| `/api/zones/<preset>/reset` | POST | Restore a preset to its shipped default (localhost only) |
## Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `WEB_HOST` | `0.0.0.0` | Flask bind address |
| `WEB_PORT` | `9050` | Flask port |
| `FLASK_DEBUG` | `false` | Flask debug mode |
| `MODELS_DIR` | `./models` | Model weights directory |
| `UPLOAD_DIR` | `./uploads` | Uploaded videos directory |
| `OUTPUT_DIR` | `./output` | Annotated output directory |
| `ZONES_PATH` | `./zones.json` | Fixed zone preset file (`1920x1080`) |
| `FCP_ZONES_PATH` | host FCP `zones.json` | Optional override for auto-sync source (set empty `""` to disable) |
| `config.yaml` | root | Tunable pipeline params (conf, IoU, ROI, intervals) |
Edit `config.yaml` instead of the code for these values; restart the job / re-run the CLI to apply.
`config.yaml` carries the counting gates aligned with FCP `main`, under `counting:`:
- `capture_below_px` (100) — corridor below the line: a sack deep in the truck
bed never counts.
- `max_step_dy_px` (160) — a per-step vertical jump of this size is an ID
switch: the track's history resets.
- `max_gap_frames` (15) — frames a track may vanish before its history resets.
- `unload_confirm_frames` (1) — consecutive "above" frames needed to confirm
an unload.
A track counts at most once. The unload branch is unreachable by design
(parity with the deployed live counter, which runs the same gates — commit
`7beb820` contains the gates commit `8448dcb`): a track that already
counted as a loading can never count a second time. `unloading` is therefore
always 0 and `net` equals the gross count — unloadings are not counted.
## Project Structure
```
src/
├── interfaces.py # Detection dataclass + protocols
├── detection.py # YOLO detectors with class filtering
├── tracking.py # ByteTrack/FastTrack tracker
├── synthetic_track.py # Synthetic IDs for untracked detections
├── stabilizer.py # Bbox smoothing + occlusion hold
├── truck_roi.py # Truck ROI detection + EMA smoothing
├── zone_config.py # Fixed-zone presets (zones.json) + scaling
├── counting.py # Line-crossing counter
├── batch.py # Batch lifecycle state machine
├── dashboard.py # Frame annotation overlay
├── video_writer.py # Annotated video writer
├── model_registry.py # Model discovery, grouping, class metadata
├── model_conversion.py # Background .pt/.onnx -> .engine conversion (ConversionManager)
├── pipeline.py # Video processing pipeline
├── preview.py # Video probing, thumbnails, sample frames
└── job.py # Async job queue
```
## Model Formats
Models are grouped by stem name. Each group has available formats:
| Format | Extension | Speed | Notes |
|--------|-----------|-------|-------|
| TensorRT | `.engine` | Fastest | Preferred on Jetson (GPU-optimized) |
| PyTorch | `.pt` | Medium | Works everywhere |
| ONNX | `.onnx` | Medium | Requires `onnxruntime` (not available on Jetson) |
Format preference order: `.engine` > `.pt` > `.onnx`
Weights can be uploaded from the web UI (`/api/models/upload`) and a `.pt`/`.onnx`
source can be converted to `.engine` from the UI or API; conversion runs in the
background and blocks analysis while it runs.
## Truck Detection
The pipeline requires truck detection to start counting. If the selected model lacks a "truck" class (e.g., `best.engine` which only has "sack"), the system automatically loads the `truck-detector` model for truck detection.
Models with "truck" class: `v4-best`, `model_karung_truk`
Models without "truck" class: `best`, `karung-dimuat`, `yolo11n-bbox` (auto-loads truck-detector)
## Counting Zone
The web upload form offers three zone modes:
- **Auto-detect Truck**: truck detector finds the main truck every 5th frame (FCP parity, `predict.py:882`), ROI + counting line follow it (EMA-smoothed with 10px deadband, sticky truck pick)
- **Fixed Zone** (default): static zone from `zones.json` presets, built in the fixed 1280×720 analysis frame; never moves; presets editable via `tools/calibrate_zone.py`
- **Auto-detect + Freeze**: auto-detects the truck then locks the ROI permanently after 3 consecutive detections (geometry fixed, truck-presence still tracked for batch state machine)
In multi-model runs, the first model covering `sack` runs primary ByteTrack tracking every frame (`iou.sack_nms=0.45`); if a separate model covers `box`, a dedicated `box` ByteTrack tracker runs every frame (`iou.box_nms=0.7`); any remaining non-truck-only models run every 5th frame with synthetic track IDs. Per-class confidence (`sack_conf=0.35`, `box_conf=0.35`) and `min_bbox_area` filtering run before stabilization, matching FCP `main`.
### Calibrating counting zone
The counting line, the counting ROI and the truck ROI are stored in
**1920×1080** pixels (`reference_resolution: [1920, 1080]`) matching FCP
`main`'s `zones.json`, and scaled to the **1280×720** analysis frame at
runtime (`int(round(v * scale))`). When FCP's `zones.json`
(`/home/jetson/feedmill_semarang_project/karung_counter_semarang/zones.json`
or `FCP_ZONES_PATH`) has a newer modification timestamp, the `"default"` preset
automatically syncs from it for fixed-zone runs (web UI and CLI).
Open `http://<host>:9050/calibrate`:
1. Pick an uploaded video and scrub to a frame where the truck is in place.
2. Press **Unlock Edit**.
3. Drag the vertices of the counting ROI (blue), the truck ROI (orange) and the
two ends of the count line (green). The line stays horizontal; the shaded
band is the ±30 px trigger zone at 1080p (±20 px in the 1280×720 analysis frame).
4. **Save Zones**.
Two presets ship:
- `default` — synced to FCP `main` (`91d8b48`) in 1920×1080 (`count_line` y=215 -> y=143 in 720p). It is the active preset (`active_preset`).
- `fcp-2026-10-15` — the pre-recalibration geometry (`count_line` y=330 -> y=220 in 720p), matching the legacy `7beb820` deployment.
The write API (`POST /api/zones/<preset>`, `POST /api/zones/<preset>/reset`) is
**localhost-only**. From another machine, tunnel the port over SSH:
```bash
ssh -L 9050:127.0.0.1:9050 jetson@<host>
```
then open `http://127.0.0.1:9050/calibrate` locally.
Writes are atomic: the previous file is copied to `zones.json.bak`, the new
one is written to a temp file, and the temp file replaces `zones.json`.
Zone changes apply to the **next** analysis; a running job keeps the zone it
started with. `tools/calibrate_zone.py` supports the same 1920×1080 calibration
in an OpenCV window on the box itself (plus `--import-json PATH` for CLI import).
### Importing / exporting zone JSON
The calibrator accepts pasted recounter presets (`1920x1080` or `1280x720`) AND
FCP flat `zones.json` blobs (`palet`, `truck`, `counting`, `line_y`,
`line_x_start`, `line_x_end`, optional `counting_line` / `coord_space`),
converting inputs to `[1920, 1080]` automatically. Click **Import / Export JSON**,
paste a JSON object, and press **Import JSON**:
```json
{"truck_area":[[x,y],...],"counting_area":[[x,y],...],
"count_line":{"x_start":0,"x_end":0,"y":0},
"reference_resolution":[1920,1080]}
```
**Copy current zones** puts the active preset on the clipboard; **Download JSON**
saves it to a file. `POST /api/zones/<preset>` also accepts both FCP flat JSON
and recounter preset JSON.