Author SHA1 Message Date
jetson 1c26f9f95b feat(zones): use native 1080p zones, sync FCP main, and auto-sync default preset 2026-11-17 12:26:30 +07:00
jetson b9d4bd11b3 feat(counting): align max_step_dy (160) and unload_confirm (1) with FCP main 2026-11-17 11:15:35 +07:00
jetson 3cc0919fb1 feat(pipeline,config): sync detection thresholds, filter order, and multi-model tracking with FCP main 2026-11-17 10:19:54 +07:00
jetson ff55a733d6 feat(counting,zones): align corridor filter and default palet zone with FCP main 2026-11-17 09:39:47 +07:00
jetson f15caf8b7f docs: note Python >=3.10 requirement 2026-11-16 16:43:37 +07:00
jetson 08a0e54065 feat(ui): paste/import zone JSON in the calibrator + surface editor in nav 2026-11-12 16:19:16 +07:00
jetson 0fe59abb4a chore: tidy stale 1920x1080 docstrings and drop dead writer 2026-11-12 15:43:08 +07:00
jetson 6610a466ee fix(docs): scope the live-system claims and fix the RTSP instructions 2026-11-12 15:30:13 +07:00
jetson 0e76c096bb docs: zone calibration workflow, counting gates and the 1280x720 zone space 2026-11-12 14:39:17 +07:00
jetson 5c295c5849 feat(tools): record an RTSP stream for recounter/live parity runs 2026-11-12 14:32:05 +07:00
jetson 3ede31b554 fix(ui): harden the frame API and align the OpenCV calibrator 2026-11-12 14:21:12 +07:00
jetson c34ac85643 feat(ui): interactive zone editor over the analysis frame 2026-11-12 13:52:01 +07:00
jetson 8abc103401 fix(viz): draw the calibrated count band instead of the ROI bounds 2026-11-12 13:17:19 +07:00
jetson 6664cefd18 feat(viz): draw the calibrated counting and truck polygons 2026-11-12 13:06:09 +07:00
jetson 7662890cc5 feat(counting): port FCP's ID-switch, corridor and single-count gates 2026-11-12 11:49:40 +07:00
jetson cd596ca857 fix(zones): close the preset-space and file-handling residuals 2026-11-12 11:20:14 +07:00
jetson a0ea7d9f8e fix(zones): validate the preset space and make zone writes race-free 2026-11-12 11:04:44 +07:00
jetson b00701a936 feat(zones): validate, save and reset zone presets (localhost only) 2026-11-12 10:23:29 +07:00
jetson 7b3c5be2a9 feat(zones): ship FCP's calibrations in the 1280x720 analysis space 2026-11-12 09:40:57 +07:00
jetson 957ab0297d feat(zones): ship FCP's calibration in the 1280x720 analysis space 2026-11-12 09:29:33 +07:00
28 changed files with 4060 additions and 285 deletions

No files matched your search

+15 -3
View File
@@ -3,6 +3,7 @@
Feedmill Recounter: AI video analysis for counting sacks/boxes in feedmill videos. Flask web UI + CLI, file-backed (no DB).
## Commands
- Python >=3.10 required.
- Install: `pip install -e ".[dev]"`
- Tests: `pytest` (config in `pyproject.toml`: testpaths = `tests`)
- Single test: `pytest tests/test_app.py::test_name` or `pytest -k name`
@@ -12,11 +13,17 @@ Feedmill Recounter: AI video analysis for counting sacks/boxes in feedmill video
## Architecture
- `app.py`: Flask routes, job queue, model upload/conversion endpoints.
- `src/pipeline.py`: `run_pipeline` / `run_merged_pipeline`; analysis space is fixed 1280x720.
- `src/pipeline.py`: `run_pipeline` / `run_merged_pipeline`; analysis space is fixed 1280x720; pre-stabilizer conf/area filtering + post-polygon box-over-sack suppression; `run_merged_pipeline` selects the first `sack` engine as primary `ByteTrackTracker` (`iou.sack_nms=0.45`) and runs a dedicated per-frame `box_tracker` (`iou.box_nms=0.7`) when a separate engine covers `box`.
- `src/job.py`: in-memory `JobQueue`; jobs die on restart, output dirs survive.
- `src/model_registry.py`: scans `models/` by stem; formats `.engine` > `.pt` > `.onnx`.
- `src/model_conversion.py`: background conversion (`.pt` -> `.onnx`, then `.pt` -> `.engine`; Ultralytics cannot export an engine from ONNX); only one at a time and blocks analysis.
- Config: `config.yaml` (tunables), `zones.json` (fixed zones), `.env` (paths/secrets).
- `src/zone_config.py`: loads, validates and atomically saves the zone presets (`.bak` + temp file + `os.replace`).
- `src/counting.py`: `LineCrossCounter` — the FCP counting gates (single count, corridor, ID switch, unload confirm).
- Zone editor: `GET /calibrate` (`templates/calibrate.html`, `static/calibrate.js`); writes go through `POST /api/zones/<preset>` and `POST /api/zones/<preset>/reset` (localhost only).
- Zone writes go through `POST /api/zones/<preset>` (localhost-only, validated, atomic). Do not hand-edit `zones.json` while the web app runs — the editor merges over the stored preset.
- The counting gates live in `config.yaml` under `counting:` and match FCP `main` (`capture_below_px=100`, `max_step_dy_px=160`, `max_gap_frames=15`, `unload_confirm_frames=1`).
- `tools/calibrate_zone.py` and the `/calibrate` page produce the same geometry; keep their count-line derivation in sync (`x_start=min`, `x_end=max`, `y=round(mean(ys))`).
- Config: `config.yaml` (tunables), `zones.json` (fixed zones, native 1920x1080 scaled to 1280x720 at runtime), `.env` (paths/secrets).
## Quirks
- Model weights and `.engine` files are gitignored; local models required for real runs.
@@ -25,4 +32,9 @@ Feedmill Recounter: AI video analysis for counting sacks/boxes in feedmill video
- Web process currently `python app.py`; restart it after code changes.
- `README.md` says port 9000 in `.env.example`, but code defaults to 9050.
- Conversion to `.engine` must start from `.pt`; Ultralytics cannot export from ONNX.
- `.engine` conversion may take minutes on Jetson.
- `.engine` conversion may take minutes on Jetson.
- Zones live in `zones.json` natively in **1920x1080** (`reference_resolution` `[1920, 1080]`, matching FCP `main`), and `src/zone_config.py` scales them to the `1280x720` analysis space at runtime via `int(round(v * scale))`. `sync_fcp_zones` automatically updates `"default"` from FCP's `zones.json` (`FCP_ZONES_PATH` or `/home/jetson/feedmill_semarang_project/karung_counter_semarang/zones.json`) whenever FCP's file has a newer `mtime`.
- Two presets ship: `default` (synced to FCP `main` `91d8b48`: `palet` `[[612, 1], [1340, 1], [1340, 267], [608, 267]]`, `truck_area` `[[600, 290], [609, 1076], [1404, 1078], [1381, 290]]`, `counting_area` `[[574, 50], [586, 1077], [1418, 1076], [1397, 50]]`, `count_line` `y=215` -> runtime `143` at `720p`) and `fcp-2026-10-15` (pre-recalibration, `count_line` `y=330` -> runtime `220` at `720p` matching `7beb820`).
- Zone writes are localhost-only; remote operators use an SSH tunnel (`ssh -L 9050:127.0.0.1:9050 jetson@<host>`). Both `POST /api/zones/<preset>` and `/calibrate` (Import JSON) accept FCP 1920x1080 flat JSON as well as recounter preset JSON (and scale legacy `1280x720` inputs up to `1920x1080`).
- `tools/record_rtsp.sh` records an RTSP stream to a file for live-vs-recounter parity runs; the recounter stays file-based (no RTSP input path).
- The `/calibrate` editor and `tools/calibrate_zone.py` both accept a pasted JSON preset (Import / Export JSON panel), so zones can be shared over chat or email and applied by paste.
+58
View File
@@ -47,6 +47,15 @@ version tags are cut in this repo — `main` is the release line).
sanctioned path.
- `docs/ai-handoff-fcp-recount.md`: AI handoff for the FCP-side phase 2.
- `ERD.md` (Mermaid ERD) + this changelog (`97507f8`).
- **Interactive zone editor** at `/calibrate`: drag the counting ROI, the truck
ROI and the count line over a frame of an uploaded video, then save. Zone
writes are localhost-only and atomic (`zones.json.bak` + temp file +
`os.replace`). The editor also accepts a pasted JSON preset (Import / Export
JSON panel) and can copy or download the active preset as JSON.
- **Zone write API**: `POST /api/zones/<preset>` and
`POST /api/zones/<preset>/reset` validate, save and restore a zone preset.
- `tools/record_rtsp.sh` records an RTSP stream to a file, so the live counter
and the recounter can be compared on the same footage.
### Fixed
- **Overlapping sacks of one model were dropped** (`ac2a235`): the merged
@@ -69,8 +78,42 @@ version tags are cut in this repo — `main` is the release line).
looked filters up by `ModelConfig.filename` while UI/API store them by
`stem` — `filter_<stem>` now honored on single-model jobs (stem-first,
filename fallback for legacy callers).
- `tools/calibrate_zone.py` now writes coordinates in the 1280×720 analysis
space (the frame is resized before the clicks are taken, so the native video
resolution does not matter) and derives the count line the way the live
counter does (horizontal at the mean y of its two endpoints).
### Changed
- **Store `zones.json` natively in 1080p (`1920×1080`), sync with FCP `main` (`91d8b48`), and auto-sync from FCP `zones.json`**:
- `zones.json`, `DEFAULT_ZONES`, `/calibrate`, and `tools/calibrate_zone.py` now author and store presets natively in `1920×1080` (`reference_resolution: [1920, 1080]`), and runtime scaling in `src/zone_config.py` uses `int(round(v * scale))` to match FCP `main` `predict.py:762, 781-783` at `1280×720`.
- Added `normalize_zone_preset()` in `src/zone_config.py` (and matching client-side support in `static/calibrate.js`) so FCP flat `zones.json` payloads (`palet`, `truck`, `counting`, `line_y`/`line_x_start`/`line_x_end`, `counting_line`, `coord_space`) and legacy `1280×720` presets normalize cleanly to `[1920, 1080]`.
- Added `sync_fcp_zones()` + shared `resolve_zone()` so both `app.py` and `cli.py` (`--zone-mode`, `--zone-preset`, `--zones-path`, defaulting to `fixed` from `zones.json`) automatically update `presets["default"]` whenever FCP's `zones.json` is newer.
- Updated `presets["default"]` to FCP `main` (`91d8b48`: `count_line` `y=215` -> `143` at 720p) and `fcp-2026-10-15` to native `1920×1080` (`count_line` `y=330` -> `220` at 720p).
- **Sync detection thresholds, filter ordering, and multi-model tracking with FCP `main` (`91d8b48`)**:
- `detection.sack_conf` 0.30 → **0.35**, plus per-class ByteTrack NMS thresholds `iou.sack_nms` (**0.45**) and `iou.box_nms` (**0.7**) matching FCP `config.yaml:103-116`.
- Pre-stabilizer `conf` and `min_bbox_area` filtering (`_filter_raw_detections`) now runs before `BboxStabilizer` so held occlusions do not drop due to `0.85x` confidence decay and sub-threshold boxes cannot suppress valid sacks; cross-class suppression (`_suppress_sacks_under_boxes`) now uses `iou < threshold` (`>=` drop parity) and runs after polygon/ROI filtering.
- `truck_detection_centroid` selects the largest-area valid truck instead of first match.
- `run_merged_pipeline` now selects the first engine covering `sack` for primary `ByteTrackTracker` (fixing FCP Modes B/D where `v4-best` is truck-only) and runs a dedicated per-frame `box` `ByteTrackTracker` + `BboxStabilizer` when a separate engine covers `box` (fixing FCP Modes C/D).
- **Align corridor filter and default palet zone with FCP main (`91d8b48`)**:
the corridor filter in `src/counting.py` now keeps `_initial_zone` when a
detection sits deep in the truck bed (matching FCP `main`), while
`counting.max_step_dy_px` (120→160) and `counting.unload_confirm_frames` (3→1)
now match FCP `main`'s `CountingConfig` (`src/config_loader.py:104-107`).
Recalibrated `presets.default.palet` in
`zones.json` and `DEFAULT_ZONES` to `[[408, 1], [893, 1], [893, 178], [405, 178]]`
(scaled from FCP's 1920×1080 `[[612, 1], [1340, 1], [1340, 267], [608, 267]]`).
`fcp-2026-10-15` stays unchanged.
- **`zones.json` now carries the calibration in the 1280×720 analysis space**
(`reference_resolution: [1280, 720]`, scale factor 1.0), matching the live
counter's geometry. Two presets ship: `default` (the
`feat/interactive-roi-line` branch's `95c031b` recalibration, count line
y=182 — the active preset) and `fcp-2026-10-15` (the pre-recalibration
geometry, count line y=220), which is what the deployed live counter (commit
`7beb820`) counts with today, because its `predict.py` hardcodes the line at
y=220 in 1280×720 and does not read `zones.json`. The
`feat/interactive-roi-line` branch (HEAD `95c031b`) does read `zones.json`,
so once it is deployed `default` is the matching preset. **Published counts
change**: the previous preset was a 1920×1080 approximation.
- **A finished job leaves ONE compressed video** (`5e2a317`): the annotated
output is compressed in place when the job finishes — the compressed copy
replaces the uncompressed source under the same file name (`os.replace`,
@@ -191,6 +234,21 @@ version tags are cut in this repo — `main` is the release line).
- **Auto-resize uploads to 720p, 720p default output** — only transcoded when
source is taller than 720p; default output height option set to 720p
(`89a265c`).
- **Counting gates ported from the live counter's `feat/interactive-roi-line`
branch**: a track counts at most once, a sack deep in the truck bed never
counts, an ID switch drops the track's history, an unload needs three
consecutive frames above the line. New `counting:` keys in `config.yaml`
(`capture_below_px`, `max_step_dy_px`, `max_gap_frames`,
`unload_confirm_frames`).
- **`unloading` is 0 on every batch and `net` equals the gross count.** The
unload branch is unreachable by design (parity with the deployed live counter,
which runs the same gates — `7beb820` contains the gates commit `8448dcb`):
the gates were ported literally, including the live counter's own unreachable
unload branch — a track that already counted as a loading can never count a
second time — and the deployed live counter publishes `unloading = 0` on
every batch. Unloadings are not counted.
- The annotated output draws the calibrated counting and truck polygons
instead of a plain bounding box.
### Added
- Plan doc for fixed-zone mode (`.opencode/plans/fixed-zone-mode.md`).
+112 -1
View File
@@ -37,6 +37,33 @@ 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
```
@@ -51,6 +78,9 @@ recounter --video PATH Input video file
--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
@@ -97,6 +127,11 @@ recounter --video PATH Input video file
| `/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
@@ -108,10 +143,28 @@ recounter --video PATH Input video file
| `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
```
@@ -165,4 +218,62 @@ The web upload form offers three zone modes:
- **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, model #1 (primary, alphabetical order) is tracked every frame; supplementary models run every 5th frame; detections from supplementary models get synthetic track IDs so counts and overlays stay stable.
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.
+152 -68
View File
@@ -3,6 +3,8 @@
from __future__ import annotations
import json
import math
import os
import subprocess
import threading
@@ -18,7 +20,6 @@ from werkzeug.utils import secure_filename
from pathlib import Path
from shapely.errors import GEOSException
from shapely.geometry import Polygon
from src.compress import compress_in_place
@@ -29,13 +30,17 @@ from src.model_conversion import (
MODEL_UPLOAD_EXTENSIONS,
conversion_status_dict,
)
from src.preview import extract_thumbnail, extract_sample_frames, probe_video, resize_video_to_max_height
from src.preview import (
extract_thumbnail, extract_sample_frames, probe_video,
resize_video_to_max_height, extract_frame_jpeg,
)
from src.pipeline import ANALYSIS_SIZE
from src.truck_roi import TruckROI
from src.validation import ValidationError
from src.zone_config import (
load_zone_config, list_zone_presets, build_static_roi, build_counting_polygon,
build_truck_polygon, get_active_zone,
load_zone_config, list_zone_presets, build_static_roi, get_active_zone,
DEFAULT_ZONES, ZONE_BOUNDS_H, ZONE_BOUNDS_W,
resolve_zone, save_zone_preset, sync_fcp_zones,
)
load_dotenv()
@@ -151,77 +156,23 @@ def upload():
def _static_roi(zone: dict) -> TruckROI:
"""Build the fixed zone ROI in FCP's 1280x720 analysis frame.
The zone preset is authored for 1920x1080 (zones.json reference_resolution)
and scaled down to the analysis frame exactly like FCP does
(predict.py:687-689) — it must not be scaled to the uploaded clip's
native size.
Zone presets are stored in 1920x1080 (zones.json reference_resolution is
[1920, 1080]) and scaled to 1280x720 at runtime.
"""
return build_static_roi(zone, *ANALYSIS_SIZE)
def _static_polygon(zone: dict) -> Polygon | None:
"""Build the counting polygon in FCP's 1280x720 analysis frame.
Same arithmetic as FCP's hardcoded detection_polygon (predict.py:688-698):
the zone's counting_area scaled by 1280/1920 x 720/1080, truncated.
"""
return build_counting_polygon(zone, *ANALYSIS_SIZE)
def _static_truck_polygon(zone: dict) -> Polygon | None:
"""Build the truck-area polygon in FCP's 1280x720 analysis frame.
Same arithmetic as FCP's hardcoded truck_polygon (predict.py:706-712):
the zone's truck_area scaled by 1280/1920 x 720/1080, truncated.
"""
return build_truck_polygon(zone, *ANALYSIS_SIZE)
def _resolve_zone(
zone_mode: str, zone_preset: str
) -> tuple[str, TruckROI | None, str, Polygon | None, Polygon | None]:
"""Resolve the counting zone of a job.
Returns (zone_mode, fixed_zone, zone_preset, counting_polygon,
truck_polygon). "fixed" needs a calibrated preset on disk; without one the
job falls back to "dynamic" so an uncalibrated deployment still runs (FCP
always counts on its calibrated line, so "fixed" is the default).
"""
if zone_mode != "fixed":
return zone_mode, None, zone_preset, None, None
zone = None
reason = "no zone file"
roi: TruckROI | None = None
polygon: Polygon | None = None
truck_polygon: Polygon | None = None
built = False
if os.path.isfile(ZONES_PATH):
try:
zone = get_active_zone(ZONES_PATH, zone_preset or None)
if zone is None:
reason = "no active preset"
else:
# ROI + counting polygon + truck polygon come from the same zone
# dict. A structurally invalid calibration must degrade to
# dynamic, not 500 — so the builds stay inside this guard.
roi = _static_roi(zone)
polygon = _static_polygon(zone)
truck_polygon = _static_truck_polygon(zone)
if zone.get("counting_area") and polygon is None:
# A counting area that is present but could not be built
# means the calibration is broken. Counting without it
# would widen the counting area, so degrade the zone.
reason = "malformed counting_area"
else:
built = True
except (OSError, ValueError, TypeError, AttributeError, IndexError,
KeyError, OverflowError, GEOSException) as exc:
# A corrupt/unreadable calibration must degrade to dynamic, not 500.
reason = f"unreadable calibration — could not be read/applied ({exc})"
if not built:
print(f"[ZONE] {reason} at {ZONES_PATH} — falling back to dynamic")
return "dynamic", None, zone_preset, None, None
return "fixed", roi, zone_preset or "default", polygon, truck_polygon
"""Resolve the counting zone of a job (auto-syncing FCP zones when newer)."""
return resolve_zone(
zone_mode,
zone_preset,
ZONES_PATH,
ANALYSIS_SIZE,
zone_reader=get_active_zone,
)
def _save_and_queue(video, model_configs, class_filters,
@@ -434,6 +385,36 @@ def download(job_id, filename):
return send_file(send_path, as_attachment=True, download_name=os.path.basename(send_path))
@app.route("/calibrate")
def calibrate_page():
"""Interactive zone calibration page."""
return render_template("calibrate.html")
@app.route("/api/frame")
def api_frame():
"""One JPEG frame of an uploaded video, resized to the analysis size."""
safe = secure_filename(request.args.get("video", ""))
if not safe or not safe.lower().endswith(VIDEO_EXTENSIONS):
return jsonify({"error": "invalid filename"}), 400
try:
t = float(request.args.get("t", "0"))
except ValueError:
return jsonify({"error": "invalid t"}), 400
if not math.isfinite(t) or t < 0:
return jsonify({"error": "invalid t"}), 400
path = os.path.join(UPLOAD_DIR, safe)
if not os.path.isfile(path):
return jsonify({"error": "not found"}), 404
try:
jpeg = extract_frame_jpeg(path, t, ANALYSIS_SIZE)
except ValueError:
return jsonify({"error": "invalid t"}), 400
except (FileNotFoundError, RuntimeError, OSError) as exc:
return jsonify({"error": str(exc)}), 500
return Response(jpeg, mimetype="image/jpeg")
@app.route("/api/videos")
def api_videos():
"""List previously uploaded videos."""
@@ -664,6 +645,7 @@ def api_zones():
"""Return zone presets from zones.json."""
if not os.path.isfile(ZONES_PATH):
return jsonify([])
sync_fcp_zones(ZONES_PATH)
try:
presets = list_zone_presets(ZONES_PATH)
return jsonify(presets)
@@ -671,6 +653,108 @@ def api_zones():
return jsonify([])
def _is_local_request() -> bool:
"""True when the request came from this machine.
The recounter serves one port, so FCP's office/operator port split
(counter_dashboard.py:2275) does not exist here. Remote operators use
an SSH tunnel, which makes the request arrive from loopback.
"""
# ::ffff:127.0.0.1 is the IPv4-mapped form of the loopback address; it
# shows up when the server listens on :: (IPv6) and the client is IPv4.
return request.remote_addr in ("127.0.0.1", "::1", "::ffff:127.0.0.1")
def _read_zones_config():
"""Return (config, error_response) for the zones file.
error_response is a Flask response tuple when the file is missing or
unusable, else None. Never raises: a corrupt zones.json must answer
with a status code, never a traceback.
"""
if not os.path.isfile(ZONES_PATH):
return None, (jsonify({"error": "zones.json not found"}), 404)
sync_fcp_zones(ZONES_PATH)
try:
config = load_zone_config(ZONES_PATH)
except OSError as exc:
return None, (jsonify({"error": f"cannot read zones.json: {exc}"}), 500)
except ValueError as exc: # malformed JSON
return None, (jsonify({"error": f"zones.json is not valid JSON: {exc}"}), 500)
if not isinstance(config, dict):
return None, (jsonify({"error": "zones.json must contain a JSON object"}), 500)
return config, None
@app.route("/api/zones/<preset_name>", methods=["GET"])
def api_zone_detail(preset_name: str):
"""Return one zone preset plus the coordinate space it is authored in."""
config, error = _read_zones_config()
if error is not None:
return error
presets = config.get("presets")
preset = presets.get(preset_name) if isinstance(presets, dict) else None
if preset is None:
return jsonify({"error": "unknown preset"}), 404
return jsonify({
"preset": preset,
"source_width": ZONE_BOUNDS_W,
"source_height": ZONE_BOUNDS_H,
})
@app.route("/api/zones/<preset_name>", methods=["POST"])
def api_zone_save(preset_name: str):
"""Save one zone preset. Localhost only."""
if not _is_local_request():
return jsonify({"error": "local access only"}), 403
_, error = _read_zones_config()
if error is not None:
return error
raw = request.get_data(cache=True)
if raw:
try:
payload = json.loads(raw)
except (ValueError, UnicodeDecodeError):
return jsonify({"error": "request body is not valid JSON"}), 400
else:
payload = {}
preset = payload.get("preset", payload) if isinstance(payload, dict) else payload
if not isinstance(preset, dict):
return jsonify({"error": "preset must be an object"}), 400
try:
save_zone_preset(ZONES_PATH, preset_name, preset)
except FileNotFoundError:
return jsonify({"error": "zones.json not found"}), 404
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
except OSError as exc:
return jsonify({"error": str(exc)}), 500
return jsonify({"status": "saved"})
@app.route("/api/zones/<preset_name>/reset", methods=["POST"])
def api_zone_reset(preset_name: str):
"""Restore a preset to the shipped default. Localhost only."""
if not _is_local_request():
return jsonify({"error": "local access only"}), 403
_, error = _read_zones_config()
if error is not None:
return error
default = DEFAULT_ZONES.get(preset_name)
if default is None:
return jsonify({"error": "unknown preset"}), 404
try:
save_zone_preset(ZONES_PATH, preset_name, default, replace=True)
except FileNotFoundError:
return jsonify({"error": "zones.json not found"}), 404
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
except OSError as exc:
return jsonify({"error": str(exc)}), 500
return jsonify({"status": "reset", "preset": default})
@app.route("/api/jobs")
def api_jobs():
return jsonify([{
+20 -1
View File
@@ -6,9 +6,12 @@ import argparse
import os
import sys
from dotenv import load_dotenv
from src.model_registry import ModelConfig, scan_models
from src.naming import annotated_output_name
from src.pipeline import run_pipeline
from src.pipeline import ANALYSIS_SIZE, run_pipeline
from src.zone_config import resolve_zone
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
@@ -37,10 +40,19 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
help="Output directory for annotated videos")
parser.add_argument("--output-height", type=int, default=None,
help="Downscale annotated output to this height (e.g. 720)")
parser.add_argument("--zone-mode", choices=["fixed", "dynamic", "freeze"],
default="fixed",
help="Counting zone mode (default: fixed from zones.json)")
parser.add_argument("--zone-preset", type=str, default="",
help="Preset name in zones.json (default: active_preset)")
parser.add_argument("--zones-path", type=str,
default=os.getenv("ZONES_PATH", "./zones.json"),
help="Path to zones.json (default: ./zones.json)")
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> None:
load_dotenv()
args = parse_args(argv)
discovered = scan_models(args.models_dir)
@@ -92,6 +104,9 @@ def main(argv: list[str] | None = None) -> None:
sys.exit(1)
class_filter = args.filter if args.filter else None
resolved_mode, fixed_zone, _preset, counting_polygon, truck_polygon = resolve_zone(
args.zone_mode, args.zone_preset, args.zones_path, ANALYSIS_SIZE
)
for model_cfg in selected:
if args.output and len(selected) == 1:
@@ -119,8 +134,12 @@ def main(argv: list[str] | None = None) -> None:
model_config=model_cfg,
output_path=out_path,
class_filter=class_filter,
fixed_zone=fixed_zone,
counting_polygon=counting_polygon,
truck_polygon=truck_polygon,
sack_conf=args.sack_conf,
truck_conf=args.truck_conf,
freeze_roi=(resolved_mode == "freeze"),
output_max_height=args.output_height,
progress_callback=progress_callback,
)
+10 -1
View File
@@ -4,7 +4,7 @@
# Missing keys fall back to built-in defaults — partial files are fine.
detection:
sack_conf: 0.3 # detector confidence for sack (FCP config.yaml:87 — reduce undercounting)
sack_conf: 0.35 # detector confidence for sack (FCP config.yaml:109)
box_conf: 0.35 # detector confidence for box
truck_conf: 0.45 # truck detector confidence
@@ -20,6 +20,8 @@ iou:
suppress_sack_box: 0.4 # drop sack overlapping a box (box label wins)
synthetic: 0.3 # synthetic track ID matching
sticky_truck: 0.3 # keep previous main truck pick
sack_nms: 0.45 # primary sack ByteTrack NMS IoU (FCP config.yaml:111)
box_nms: 0.7 # box ByteTrack NMS IoU (FCP config.yaml:115)
roi:
ema_alpha: 0.15 # truck ROI smoothing
@@ -38,6 +40,13 @@ batch:
truck_gone_tolerance_seconds: 30.0 # truck-gone: in WAITING, N s with no sack and
# no truck signal -> batch ends
# Counting gates (FCP main, src/config_loader.py:104-107).
counting:
capture_below_px: 100 # corridor below the line: deep truck bed, never counts
max_step_dy_px: 160 # per-step vertical jump = ID switch -> reset track history
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
pipeline:
detect_interval: 1 # detection+tracking every N frames (1 = every frame, most accurate)
sup_det_interval: 5 # supplementary models every N frames
+10 -1
View File
@@ -20,7 +20,7 @@ CONFIG_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.y
DEFAULTS: dict = {
"detection": {
"sack_conf": 0.3,
"sack_conf": 0.35,
"box_conf": 0.35,
"truck_conf": 0.45,
},
@@ -34,6 +34,8 @@ DEFAULTS: dict = {
"suppress_sack_box": 0.4,
"synthetic": 0.3,
"sticky_truck": 0.3,
"sack_nms": 0.45,
"box_nms": 0.7,
},
"roi": {
"ema_alpha": 0.15,
@@ -50,6 +52,13 @@ DEFAULTS: dict = {
"timeout_seconds": 20.0,
"truck_gone_tolerance_seconds": 30.0,
},
"counting": {
# FCP main, src/config_loader.py:104-107.
"capture_below_px": 100,
"max_step_dy_px": 160,
"max_gap_frames": 15,
"unload_confirm_frames": 1,
},
"pipeline": {
"detect_interval": 1,
"sup_det_interval": 5,
+149 -19
View File
@@ -18,6 +18,15 @@ Counting logic (Low-FPS robust):
This approach is immune to low FPS because it doesn't require
detecting the exact frame of crossing. It only needs the track
to have been seen ABOVE the line at ANY point in its lifetime.
FCP counting gates (karung_counter_semarang, main, src/counting.py):
- corridor: detections deeper than capture_below px below the line sit
in the truck bed; they never arm a crossing
- teleport / stale gap: a track that jumped too far vertically or
vanished too long is an ID switch — its history is dropped
- single-direction lock: a track_id counts at most once overall
- unload confirm: an unload needs N consecutive "above" frames
- same-direction dx dedup: two crossings at nearly the same x count once
"""
from __future__ import annotations
@@ -37,6 +46,10 @@ class LineCrossCounter:
Loading = track was ever "above", now "below" (entered truck)
Unloading = track was ever "below", now "above" (left truck)
FCP parity: a track_id counts at most once overall, so a track that
loaded is never counted again — the unloading branch stays unreachable
(same as karung_counter_semarang, main).
"""
def __init__(
@@ -46,16 +59,34 @@ class LineCrossCounter:
line_x_end: int,
margin: int = 20,
dedup_radius: float = 30.0,
capture_below: float = 100.0,
max_step_dy: float = 160.0,
max_gap_frames: int = 15,
unload_confirm_frames: int = 1,
) -> None:
self._line_y = line_y
self._line_x_start = line_x_start
self._line_x_end = line_x_end
self._margin = margin
self._dedup_radius = dedup_radius
self._capture_below = float(capture_below)
self._max_step_dy = float(max_step_dy)
self._max_gap_frames = int(max_gap_frames)
self._unload_confirm_frames = int(unload_confirm_frames)
self._loading_count = 0
self._unloading_count = 0
# Step index for tracking gaps across updates
self._step_idx = 0
# track_id -> last seen y1 and step index
self._last_y1: dict[int, float] = {}
self._last_step: dict[int, int] = {}
# track_id -> initial valid zone ("above" | "below")
self._initial_zone: dict[int, str] = {}
# track_id -> consecutive frames seen in "above"
self._above_streak: dict[int, int] = {}
# track_id -> zone state for y1: "above" | "below" | None
self._state: dict[int, str | None] = {}
# track_id -> whether this track has EVER been in each zone
@@ -103,6 +134,17 @@ class LineCrossCounter:
def line_x_end(self, value: int) -> None:
self._line_x_end = value
def update_line(self, line_y: int, line_x_start: int, line_x_end: int) -> None:
"""Update line geometry for future crossings only.
Per-track history is kept: a track that was already above the old
line is still "above" the new one. Mirrors FCP's update_line
(FCP main, src/counting.py:315-319).
"""
self.line_y = int(line_y)
self.line_x_start = int(line_x_start)
self.line_x_end = int(line_x_end)
def update(self, detections: list[Detection]) -> list[dict]:
"""Process detections, return list of crossing events.
@@ -111,14 +153,16 @@ class LineCrossCounter:
- BUT uses accumulated history (has_been_above) for counting decision
- A track counts as "loading" when:
1. It has been seen ABOVE the line at any previous point
2. Its current y1 is now BELOW the line
3. It hasn't been counted for loading yet
2. Its current y1 is now BELOW the line (within the active corridor)
3. It hasn't been counted yet (single-direction lock)
4. It passes spatial dedup check
"""
now_t = time.time()
self._step_idx += 1
events: list[dict] = []
upper = self._line_y - self._margin
lower = self._line_y + self._margin
max_below = self._line_y + self._capture_below
# Clean up expired dedup circles (older than 3.0 seconds)
self._dedup_circles = [c for c in self._dedup_circles if (now_t - c["time"]) <= 3.0]
@@ -138,6 +182,38 @@ class LineCrossCounter:
if cx < self._line_x_start or cx > self._line_x_end:
continue
# --- CORRIDOR FILTER: DEEP TRUCK BED (STACKED SACKS) ---
# Detections below max_below are deep in the truck bed; they must
# never arm _has_been_below or trigger a loading count when an ID
# switches onto them.
if y1 > max_below:
self._last_y1[tid] = y1
self._last_step[tid] = self._step_idx
self._has_been_above.pop(tid, None)
self._has_been_below.pop(tid, None)
self._state.pop(tid, None)
self._above_streak.pop(tid, None)
continue
# --- TELEPORTATION & STALE GAP GATE ---
# A track that jumped too far vertically in one step, or that
# reappeared after many frames, is an ID switch: drop its history
# so it cannot falsely trigger.
if tid in self._last_step:
gap = self._step_idx - self._last_step[tid]
dy = abs(y1 - self._last_y1[tid])
if (self._max_gap_frames > 0 and gap > self._max_gap_frames) or (
self._max_step_dy > 0 and dy > self._max_step_dy
):
self._has_been_above[tid] = False
self._has_been_below[tid] = False
self._state[tid] = None
self._initial_zone.pop(tid, None)
self._above_streak[tid] = 0
self._last_y1[tid] = y1
self._last_step[tid] = self._step_idx
counted_dirs = self._counted.setdefault(tid, set())
# Determine y1 zone state (top edge of sack bbox)
@@ -148,41 +224,59 @@ class LineCrossCounter:
else:
new_state = self._state.get(tid) # in band: hold
prev_state = self._state.get(tid)
self._state[tid] = new_state
# Record initial valid zone if not yet known
if tid not in self._initial_zone and new_state in ("above", "below"):
self._initial_zone[tid] = new_state
# Track zone history — CRITICAL for low-FPS robustness
# Once a track has been seen above/below, it stays recorded forever
if new_state == "above":
self._has_been_above[tid] = True
elif new_state == "below":
self._has_been_below[tid] = True
self._above_streak[tid] = self._above_streak.get(tid, 0) + 1
else:
self._above_streak[tid] = 0
if new_state == "below":
self._has_been_below[tid] = True
# --- HYBRID COUNTING LOGIC ---
# Loading: track was EVER above, NOW below (entered truck from top)
# This works even if the track jumped over the line between frames
# Single-direction lock: a track_id is counted at most once.
# Loading: track was EVER above, NOW below within the corridor.
is_loading = (
new_state == "below"
and self._has_been_above.get(tid, False)
and "loading" not in counted_dirs
and len(counted_dirs) == 0
)
# Unloading: track was EVER below, NOW above (left truck)
# Gated on a prior loading: a track that was never loaded
# (e.g. first seen below the line) must not count as unloading
# Unloading: track originated "below", was EVER below, NOW
# confirmed above for N consecutive frames.
# FCP parity note: a counted track already owns a direction, so the
# single-direction lock keeps unloading unreachable — a track that
# loaded is never counted a second time.
is_unloading = (
new_state == "above"
and tid in self._loaded_tracks
and self._has_been_below.get(tid, False)
and "unloading" not in counted_dirs
and self._initial_zone.get(tid) == "below"
and self._above_streak.get(tid, 0) >= self._unload_confirm_frames
and len(counted_dirs) == 0
)
if is_loading or is_unloading:
# Check spatial distance against all active dedup circles
direction = "loading" if is_loading else "unloading"
# Duplicate: position too close (2D) OR two crossings on the
# same side of the line at nearly the same x (horizontal
# proximity, same direction only).
is_duplicate = False
for circle in self._dedup_circles:
dist = ((cx - circle["x"]) ** 2 + (y1 - circle["y"]) ** 2) ** 0.5
if dist <= self._dedup_radius:
dist_2d = ((cx - circle["x"]) ** 2 + (y1 - circle["y"]) ** 2) ** 0.5
same_dir_dx = (
abs(cx - circle["x"])
if circle.get("direction") == direction
else float("inf")
)
if dist_2d <= self._dedup_radius or same_dir_dx <= self._dedup_radius:
is_duplicate = True
break
@@ -194,7 +288,8 @@ class LineCrossCounter:
"x": cx,
"y": y1,
"time": now_t,
"track_id": tid
"track_id": tid,
"direction": direction,
})
if is_loading:
@@ -236,6 +331,11 @@ class LineCrossCounter:
"""Reset all counters (new batch)."""
self._loading_count = 0
self._unloading_count = 0
self._step_idx = 0
self._last_y1.clear()
self._last_step.clear()
self._initial_zone.clear()
self._above_streak.clear()
self._state.clear()
self._has_been_above.clear()
self._has_been_below.clear()
@@ -261,6 +361,11 @@ class LineCrossCounter:
twice in the clip total. Upgrade path: per-batch result rows, then
a full reset() per batch.
"""
self._step_idx = 0
self._last_y1.clear()
self._last_step.clear()
self._initial_zone.clear()
self._above_streak.clear()
self._state.clear()
self._has_been_above.clear()
self._has_been_below.clear()
@@ -286,15 +391,40 @@ class MultiClassLineCounter:
line_x_end: int,
margin: int = 20,
dedup_radius: float = 30.0,
capture_below: float = 100.0,
max_step_dy: float = 160.0,
max_gap_frames: int = 15,
unload_confirm_frames: int = 1,
) -> None:
self._sack = LineCrossCounter(
line_y, line_x_start, line_x_end, margin, dedup_radius
line_y=line_y,
line_x_start=line_x_start,
line_x_end=line_x_end,
margin=margin,
dedup_radius=dedup_radius,
capture_below=capture_below,
max_step_dy=max_step_dy,
max_gap_frames=max_gap_frames,
unload_confirm_frames=unload_confirm_frames,
)
self._box = LineCrossCounter(
line_y, line_x_start, line_x_end, margin, dedup_radius
line_y=line_y,
line_x_start=line_x_start,
line_x_end=line_x_end,
margin=margin,
dedup_radius=dedup_radius,
capture_below=capture_below,
max_step_dy=max_step_dy,
max_gap_frames=max_gap_frames,
unload_confirm_frames=unload_confirm_frames,
)
# -- line geometry proxies (kept in sync on both counters) --
def update_line(self, line_y: int, line_x_start: int, line_x_end: int) -> None:
"""Update shared line geometry for future crossings only."""
self._sack.update_line(line_y, line_x_start, line_x_end)
self._box.update_line(line_y, line_x_start, line_x_end)
@property
def line_y(self) -> int:
return self._sack.line_y
+40 -11
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
import cv2
import numpy as np
from shapely.geometry import Polygon
from src.batch import BatchRecord
from src.interfaces import Detection
@@ -26,6 +27,8 @@ ORANGE = (0, 165, 255)
GRAY = (140, 140, 140)
DARK_GREEN = (0, 130, 0)
LIGHT_BLUE = (255, 200, 100)
# Counting-area polygon — FCP's detection area, drawn behind the boxes.
COUNT_ZONE = (235, 99, 37)
# State display labels and colors
@@ -54,17 +57,32 @@ class DashboardOverlay:
idle_timer: float = 0.0,
stabilize_progress: float = 0.0,
waiting_duration: float = 0.0,
counting_polygon: Polygon | None = None,
truck_polygon: Polygon | None = None,
) -> np.ndarray:
out = frame.copy()
# The calibrated zones go down first so the detection boxes stay
# readable on top of them (FCP draw() draws the polygons first too).
if counting_polygon is not None and counting_polygon.area > 0:
pts = np.array(
counting_polygon.exterior.coords, dtype=np.int32,
).reshape((-1, 1, 2))
cv2.polylines(out, [pts], True, COUNT_ZONE, 2)
if truck_polygon is not None and truck_polygon.area > 0:
pts = np.array(
truck_polygon.exterior.coords, dtype=np.int32,
).reshape((-1, 1, 2))
cv2.polylines(out, [pts], True, ORANGE, 2)
if roi is not None:
self._draw_roi(frame, roi)
self._draw_counting_zone(frame, roi)
self._draw_detections(frame, detections)
self._draw_stats(frame, loading_count, unloading_count, batch_id, history)
self._draw_roi(out, roi)
self._draw_counting_zone(out, roi)
self._draw_detections(out, detections)
self._draw_stats(out, loading_count, unloading_count, batch_id, history)
self._draw_system_state(
frame, system_state, batch_duration, idle_timer, stabilize_progress,
out, system_state, batch_duration, idle_timer, stabilize_progress,
waiting_duration,
)
return frame
return out
def _draw_roi(self, frame: np.ndarray, roi: TruckROI) -> None:
if roi.fixed:
@@ -132,20 +150,31 @@ class DashboardOverlay:
) -> None:
y = roi.line_y
h, w = frame.shape[:2]
# Blend only the narrow strip region, not the full frame
# The count window is the calibrated one when the zone has it — the
# counter counts inside that window, not inside the ROI bounds
# (same fallback as src/pipeline.py:536-541).
x1 = roi.line_x_start if roi.line_x_start is not None else roi.x1
x2 = roi.line_x_end if roi.line_x_end is not None else roi.x2
sy = max(0, y - margin)
ey = min(h, y + margin)
sx = max(0, roi.x1)
ex = min(w, roi.x2)
# Clamp the calibrated window into the frame. A corrupt zone (window
# inverted or outside the frame) counts nothing, so no band is drawn
# at all — drawing one over the ROI bounds would lie about the
# window the counter actually uses.
sx = max(0, min(w, x1))
ex = max(0, min(w, x2))
if ex <= sx or ey <= sy:
return
# Blend only the narrow strip region, not the full frame
strip = frame[sy:ey, sx:ex].copy()
cv2.rectangle(strip, (0, 0), (ex - sx, ey - sy), MAGENTA, -1)
cv2.addWeighted(strip, 0.15, frame[sy:ey, sx:ex], 0.85, 0, frame[sy:ey, sx:ex])
# Draw center line
cv2.line(frame, (roi.x1, y), (roi.x2, y), MAGENTA, 2)
cv2.line(frame, (sx, y), (ex, y), MAGENTA, 2)
cv2.putText(
frame,
f"COUNT LINE Y={y} (y1 trigger)",
(roi.x1, y - margin - 8),
(sx, y - margin - 8),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, MAGENTA, 1,
)
+237 -111
View File
@@ -235,20 +235,30 @@ def build_batch_manager(cfg: dict) -> BatchLifecycleManager:
)
def _extract_valid_trucks(
detections: list[Detection], truck_conf: float, min_truck_area: float
) -> list[Detection]:
"""Extract truck detections meeting conf and min_bbox_area from tracker output."""
return [
d for d in detections
if d.class_name == "truck"
and d.confidence >= truck_conf
and (d.bbox[2] - d.bbox[0]) * (d.bbox[3] - d.bbox[1]) >= min_truck_area
]
def truck_detection_centroid(
truck_detections: list[Detection],
counting_polygon: Polygon | None = None,
min_overlap: float = 0.5,
) -> tuple[float, float] | None:
"""Centroid of the truck FCP would call "in the area", or None when there is none.
"""Centroid of the largest valid truck FCP calls "in the area", or None.
FCP keeps a truck only when at least 50% of its bbox lies inside the
detection polygon (predict.py:893-902) and uses that as the batch's truck
signal (predict.py:964). Without a polygon any truck counts.
The FSM only leaves IDLE when a truck is detected AND a centroid is known
(src/batch.py:133-134), so the centroid must follow the detection.
FCP keeps trucks with at least 50% of their bbox inside the detection
polygon and picks the largest-area (then highest-confidence) candidate
(predict.py:1074-1095). Without a polygon any truck counts.
"""
best: tuple[float, float, tuple[float, float]] | None = None
for det in truck_detections:
if det.class_name != "truck":
continue
@@ -260,8 +270,10 @@ def truck_detection_centroid(
overlap = counting_polygon.intersection(box(x1, y1, x2, y2)).area
if overlap / area < min_overlap:
continue
return ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
return None
candidate = (area, det.confidence, ((x1 + x2) / 2.0, (y1 + y2) / 2.0))
if best is None or candidate[:2] > best[:2]:
best = candidate
return best[2] if best is not None else None
def update_batch_state(
@@ -396,11 +408,18 @@ def run_pipeline(
model_config.known_classes if model_config.known_classes else None
)
# Run inference at the lowest per-class conf so box TPs in
# [box_conf, sack_conf) survive; per-class gating happens later.
# Run inference at the lowest per-class conf so box/truck TPs survive
# to the per-class gating stages downstream (FCP predict.py:496).
truck_from_tracker = (
truck_model_config is None
and "truck" in (model_config.known_classes or [])
and (effective_filter is None or "truck" in effective_filter)
)
effective_detector_conf = (
min(sack_conf, box_conf) if not effective_filter or "box" in effective_filter else sack_conf
)
if truck_from_tracker:
effective_detector_conf = min(effective_detector_conf, truck_conf)
# Check onnxruntime for .onnx models
if model_config.path.endswith(".onnx"):
@@ -413,28 +432,27 @@ def run_pipeline(
)
shared_model = YOLO(model_config.path)
detector = BaseDetector(
shared_model, conf=effective_detector_conf, class_filter=effective_filter
)
# Truck detector — the FSM's truck signal is the real detection in BOTH
# zone modes (FCP predict.py:882-886), so it always runs.
# Truck detector — only construct BaseDetector when using a separate model
# so we never share one Ultralytics YOLO instance between .track() and .predict().
truck_detector = None
if truck_model_config is not None:
# Load a separate truck detection model
truck_shared = YOLO(truck_model_config.path)
truck_detector = BaseDetector(truck_shared, conf=truck_conf, class_filter=("truck",))
elif "truck" in (model_config.known_classes or []):
# Use the same model for truck detection
truck_detector = BaseDetector(
shared_model, conf=truck_conf, class_filter=("truck",)
)
tracker = ByteTrackTracker(shared_model, conf=effective_detector_conf)
primary_nms = (
cfg["iou"]["box_nms"]
if (effective_filter is not None and "sack" not in effective_filter and "box" in effective_filter)
else cfg["iou"]["sack_nms"]
)
tracker = ByteTrackTracker(
shared_model, conf=effective_detector_conf, iou=primary_nms
)
stabilizer = BboxStabilizer(
ema_alpha=cfg["stabilizer"]["ema_alpha"],
max_hold_frames=cfg["stabilizer"]["max_hold"],
)
min_areas = _scaled_min_areas(cfg, w, h)
roi_tracker = TruckROITracker(
frame_width=w,
frame_height=h,
@@ -448,6 +466,10 @@ def run_pipeline(
line_x_start=int(w * 0.38),
line_x_end=int(w * 0.72),
margin=20,
capture_below=float(cfg["counting"]["capture_below_px"]),
max_step_dy=float(cfg["counting"]["max_step_dy_px"]),
max_gap_frames=int(cfg["counting"]["max_gap_frames"]),
unload_confirm_frames=int(cfg["counting"]["unload_confirm_frames"]),
)
batch_mgr = build_batch_manager(cfg)
dashboard = DashboardOverlay()
@@ -503,12 +525,19 @@ def run_pipeline(
if cancel_check and frame_idx % 30 == 0 and cancel_check():
break
# Truck detection — every truck_det_interval frames, the result
# is cached in between (FCP predict.py:882-886 caches
# last_detected_trucks).
# Track every frame (FCP predict.py:1066-1067).
raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
# Truck detection — separate model runs every truck_det_interval;
# shared tracker extracts truck candidates directly without sharing YOLO.predict().
if truck_detector is not None and frame_idx % truck_det_interval == 0:
last_trucks = truck_detector.detect(frame)
elif truck_from_tracker and frame_idx % detect_interval == 0:
last_trucks = _extract_valid_trucks(
raw_tracked, truck_conf, min_areas.get("truck", 0)
)
has_truck_source = truck_detector is not None or truck_from_tracker
if fixed_zone is not None:
roi = fixed_zone
# The calibrated zone is a fixed AREA: it says where to count,
@@ -518,7 +547,7 @@ def run_pipeline(
truck_present = truck_centroid is not None
else:
roi = roi_tracker.roi
if truck_detector is not None and frame_idx % truck_det_interval == 0:
if has_truck_source and frame_idx % truck_det_interval == 0:
roi = roi_tracker.update(last_trucks)
truck_present = roi is not None and roi.confidence > 0
truck_centroid = None
@@ -536,17 +565,15 @@ def run_pipeline(
roi.line_x_end if roi.line_x_end is not None else roi.x2
)
# Track → Stabilize → Count — on EVERY frame (FCP predict.py:1066-1067:
# "Run line crossing counter on every frame"). Gating it on an open
# batch would drop every crossing that happens before the batch
# opens.
tracked_sacks: list[Detection] = []
counter_input: list[Detection] = []
events: list[dict] = []
raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
# Filter → Stabilize → Polygon → Cross-class suppress → ROI X-window → Count
raw_tracked = _filter_raw_detections(
raw_tracked, effective_filter, sack_conf, box_conf, min_areas
)
stable = stabilizer.update(raw_tracked)
stable = apply_class_filter(stable, effective_filter)
stable = filter_by_counting_polygon(stable, counting_polygon)
stable = _suppress_sacks_under_boxes(
stable, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
if roi is not None:
tracked_sacks = [
@@ -556,11 +583,6 @@ def run_pipeline(
else:
tracked_sacks = stable
tracked_sacks = _suppress_sacks_under_boxes(
tracked_sacks, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
tracked_sacks = _apply_class_confs(tracked_sacks, sack_conf, box_conf)
tracked_sacks = _apply_min_area(tracked_sacks, _scaled_min_areas(cfg, w, h))
counter_input = countable_detections(tracked_sacks)
events = counter.update(counter_input)
@@ -593,6 +615,8 @@ def run_pipeline(
batch_duration=batch_mgr.batch_duration,
stabilize_progress=batch_mgr.stabilize_progress,
waiting_duration=batch_mgr.waiting_duration,
counting_polygon=counting_polygon,
truck_polygon=truck_polygon,
)
# Draw model info overlay
@@ -690,7 +714,10 @@ def _compute_iou(box1: tuple, box2: tuple) -> float:
def _deduplicate_detections(
primary: list[Detection], extras: list[Detection], iou_threshold: float = 0.5
primary: list[Detection],
extras: list[Detection],
iou_threshold: float = 0.5,
extra_against: list[Detection] | tuple[Detection, ...] = (),
) -> list[Detection]:
"""Drop a detection that duplicates the same object seen by ANOTHER model.
@@ -701,13 +728,15 @@ def _deduplicate_detections(
The tracked primary always wins: an extra detection carries a synthetic
track id, and swapping the id would lose the track's crossing history.
`extra_against` suppresses extras overlapping a separate box_tracker without
merging those box_tracker detections into the primary/synthetic stream.
"""
kept = list(primary)
for det in sorted(extras, key=lambda d: d.confidence, reverse=True):
if any(
other.class_name == det.class_name
and _compute_iou(other.bbox, det.bbox) > iou_threshold
for other in kept
for other in (*kept, *extra_against)
):
continue
kept.append(det)
@@ -717,14 +746,32 @@ def _deduplicate_detections(
def _suppress_sacks_under_boxes(dets, iou_threshold=0.5):
"""Drop sack dets overlapping a box det — same object, box label wins.
ponytail: box-wins heuristic; models without a box class label boxes as
sack. Upgrade path: per-model provenance field on Detection.
Matches FCP's drop_sacks_overlapping_boxes (src/counting.py:487):
keeps a sack iff all box IoUs < iou_threshold; iou_threshold <= 0 disables.
"""
if iou_threshold <= 0:
return dets
boxes = [d for d in dets if d.class_name == "box"]
if not boxes:
return dets
return [d for d in dets if d.class_name != "sack"
or not any(_compute_iou(d.bbox, b.bbox) > iou_threshold for b in boxes)]
return [
d for d in dets
if d.class_name != "sack"
or all(_compute_iou(d.bbox, b.bbox) < iou_threshold for b in boxes)
]
def _filter_raw_detections(
dets: list[Detection],
class_filter: list[str] | None,
sack_conf: float,
box_conf: float,
min_areas: dict,
) -> list[Detection]:
"""Apply class filter, per-class conf floor, and min bbox area before stabilization."""
filtered = apply_class_filter(dets, class_filter)
filtered = _apply_class_confs(filtered, sack_conf, box_conf)
return _apply_min_area(filtered, min_areas)
def _apply_class_confs(dets, sack_conf, box_conf):
@@ -827,54 +874,117 @@ def run_merged_pipeline(
w, h = analysis_size(src_w, src_h)
print(f"[PIPELINE] source {src_w}x{src_h} -> analysis {w}x{h}")
# Load all detectors
detectors = []
# Load all models once, resolve each model's effective class filter
models = []
eff_filters: list[list[str] | None] = []
for mcfg in model_configs:
if mcfg.path.endswith(".onnx"):
try:
import onnxruntime
import onnxruntime # noqa: F401
except ImportError:
raise RuntimeError(
f"onnxruntime not installed. Cannot load '{mcfg.filename}'. "
f"Use the .engine version instead."
)
model = YOLO(mcfg.path)
eff_filter = (class_filters or {}).get(mcfg.stem) or mcfg.known_classes or None
# Inference at lowest per-class conf so box TPs in [box_conf, sack_conf)
# survive; per-class gating happens later.
det_conf = (
min(sack_conf, box_conf) if not eff_filter or "box" in eff_filter else sack_conf
models.append(YOLO(mcfg.path))
eff_filters.append(
(class_filters or {}).get(mcfg.stem)
or (class_filters or {}).get(mcfg.filename)
or mcfg.known_classes
or None
)
detectors.append(BaseDetector(model, conf=det_conf, class_filter=eff_filter))
# Truck detector — the FSM's truck signal is the real detection in BOTH
# zone modes (FCP predict.py:882-886), so it always runs.
def _is_truck_only(ef: list[str] | tuple[str, ...] | None) -> bool:
return ef is not None and set(ef) == {"truck"}
# Primary tracker: first engine covering "sack" (FCP predict.py:474);
# otherwise first non-truck-only engine, fallback 0.
primary_idx = next(
(i for i, ef in enumerate(eff_filters) if ef is None or "sack" in ef),
next((i for i, ef in enumerate(eff_filters) if not _is_truck_only(ef)), 0),
)
primary_filter = eff_filters[primary_idx]
# Dedicated box tracker when a separate engine covers "box" (FCP predict.py:506-511).
box_idx = (
next(
(
i for i, ef in enumerate(eff_filters)
if i != primary_idx and (ef is None or "box" in ef)
),
None,
)
if primary_filter is not None and "box" not in primary_filter
else None
)
# Resolve truck source BEFORE building trackers so we include truck_conf in
# tracker conf when truck shares a model, and never share a YOLO instance
# between ByteTrackTracker (.track) and BaseDetector (.predict).
truck_det = None
truck_source: str | None = None
if truck_model_config is not None:
truck_shared = YOLO(truck_model_config.path)
truck_det = BaseDetector(truck_shared, conf=truck_conf, class_filter=("truck",))
# ponytail: first-match truck detector; could prefer dedicated truck model over sack model w/ truck class
truck_source = "detector"
else:
for i, mcfg in enumerate(model_configs):
if "truck" in (mcfg.known_classes or []):
truck_det = detectors[i]
break
truck_idx = next(
(
i for i, (mcfg, ef) in enumerate(zip(model_configs, eff_filters))
if (ef is None or "truck" in ef)
and ("truck" in (mcfg.known_classes or []) or (ef is not None and "truck" in ef))
),
None,
)
if truck_idx == primary_idx:
truck_source = "primary"
elif box_idx is not None and truck_idx == box_idx:
truck_source = "box"
elif truck_idx is not None:
truck_det = BaseDetector(models[truck_idx], conf=truck_conf, class_filter=("truck",))
truck_source = "detector"
# Single tracker using first model's weights
tracker_model = YOLO(model_configs[0].path)
primary_eff = (
(class_filters or {}).get(model_configs[0].stem)
or model_configs[0].known_classes
or None
)
effective_detector_conf = (
min(sack_conf, box_conf) if not primary_eff or "box" in primary_eff else sack_conf
min(sack_conf, box_conf) if not primary_filter or "box" in primary_filter else sack_conf
)
tracker = ByteTrackTracker(tracker_model, conf=effective_detector_conf)
if truck_source == "primary":
effective_detector_conf = min(effective_detector_conf, truck_conf)
primary_nms = (
cfg["iou"]["box_nms"]
if (primary_filter is not None and "sack" not in primary_filter and "box" in primary_filter)
else cfg["iou"]["sack_nms"]
)
tracker = ByteTrackTracker(
models[primary_idx], conf=effective_detector_conf, iou=primary_nms
)
box_tracker = None
box_stabilizer = None
box_filter: list[str] | None = None
if box_idx is not None:
box_filter = eff_filters[box_idx]
box_det_conf = min(box_conf, truck_conf) if truck_source == "box" else box_conf
box_tracker = ByteTrackTracker(
models[box_idx], conf=box_det_conf, iou=cfg["iou"]["box_nms"]
)
box_stabilizer = BboxStabilizer(
ema_alpha=cfg["stabilizer"]["ema_alpha"],
max_hold_frames=cfg["stabilizer"]["max_hold"],
)
# Supplementary detectors: any remaining non-truck-only engines.
extra_detectors = []
for i, ef in enumerate(eff_filters):
if i in (primary_idx, box_idx) or _is_truck_only(ef):
continue
det_conf = min(sack_conf, box_conf) if not ef or "box" in ef else sack_conf
extra_detectors.append(BaseDetector(models[i], conf=det_conf, class_filter=ef))
stabilizer = BboxStabilizer(
ema_alpha=cfg["stabilizer"]["ema_alpha"],
max_hold_frames=cfg["stabilizer"]["max_hold"],
)
min_areas = _scaled_min_areas(cfg, w, h)
synthetic = SyntheticIdAssigner(
iou_threshold=cfg["iou"]["synthetic"],
max_age=cfg["stabilizer"]["max_hold"],
@@ -892,6 +1002,10 @@ def run_merged_pipeline(
line_x_start=int(w * 0.38),
line_x_end=int(w * 0.72),
margin=20,
capture_below=float(cfg["counting"]["capture_below_px"]),
max_step_dy=float(cfg["counting"]["max_step_dy_px"]),
max_gap_frames=int(cfg["counting"]["max_gap_frames"]),
unload_confirm_frames=int(cfg["counting"]["unload_confirm_frames"]),
)
batch_mgr = build_batch_manager(cfg)
dashboard = DashboardOverlay()
@@ -906,13 +1020,6 @@ def run_merged_pipeline(
# Last truck detections — kept between detection frames (FCP caches
# last_detected_trucks, predict.py:882-886).
last_trucks: list[Detection] = []
# Primary model's class filter (mirrors eff_filter above) — applied to
# ByteTrack output so UI class checkboxes apply to the primary model too.
primary_filter = (
(class_filters or {}).get(model_configs[0].stem)
or model_configs[0].known_classes
or None
)
def on_batch_end(record):
nonlocal completed_batches
@@ -928,6 +1035,8 @@ def run_merged_pipeline(
# (predict.py:1021-1022).
counter.reset_state()
stabilizer.reset()
if box_stabilizer is not None:
box_stabilizer.reset()
batch_mgr.on_batch_start(on_batch_start)
batch_mgr.on_batch_end(on_batch_end)
@@ -949,12 +1058,28 @@ def run_merged_pipeline(
if cancel_check and frame_idx % 30 == 0 and cancel_check():
break
# Truck detection — every truck_det_interval frames, the result
# is cached in between (FCP predict.py:882-886 caches
# last_detected_trucks).
if truck_det is not None and frame_idx % truck_det_interval == 0:
last_trucks = truck_det.detect(frame)
# Primary & dedicated box trackers run every frame (FCP predict.py:1041, 1103).
raw_primary = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
raw_boxes_all = (
box_tracker.update(frame, [])
if (box_tracker is not None and frame_idx % detect_interval == 0)
else []
)
# Truck detection — separate model runs every truck_det_interval;
# shared tracker extracts truck candidates directly (FCP predict.py:1062-1071).
if truck_source == "detector" and truck_det is not None and frame_idx % truck_det_interval == 0:
last_trucks = truck_det.detect(frame)
elif truck_source == "primary" and frame_idx % detect_interval == 0:
last_trucks = _extract_valid_trucks(
raw_primary, truck_conf, min_areas.get("truck", 0)
)
elif truck_source == "box" and frame_idx % detect_interval == 0:
last_trucks = _extract_valid_trucks(
raw_boxes_all, truck_conf, min_areas.get("truck", 0)
)
has_truck_source = truck_source is not None
if fixed_zone is not None:
roi = fixed_zone
# The calibrated zone is a fixed AREA: it says where to count,
@@ -964,7 +1089,7 @@ def run_merged_pipeline(
truck_present = truck_centroid is not None
else:
roi = roi_tracker.roi
if truck_det is not None and frame_idx % truck_det_interval == 0:
if has_truck_source and frame_idx % truck_det_interval == 0:
roi = roi_tracker.update(last_trucks)
truck_present = roi is not None and roi.confidence > 0
truck_centroid = None
@@ -982,54 +1107,53 @@ def run_merged_pipeline(
roi.line_x_end if roi.line_x_end is not None else roi.x2
)
# Detection + tracking — on EVERY frame (FCP predict.py:1066-1067:
# "Run line crossing counter on every frame"). Gating it on an open
# batch would drop every crossing that happens before the batch
# opens.
tracked: list[Detection] = []
counter_input: list[Detection] = []
events: list[dict] = []
# Primary: tracker gives detections WITH track_id for counting
primary = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
primary = apply_class_filter(primary, primary_filter)
# Pre-stabilizer per-class filtering for primary & dedicated box streams
primary = _filter_raw_detections(
raw_primary, primary_filter, sack_conf, box_conf, min_areas
)
raw_boxes: list[Detection] = []
if box_tracker is not None and box_stabilizer is not None:
raw_boxes = _filter_raw_detections(
raw_boxes_all, box_filter, sack_conf, box_conf, min_areas
)
raw_boxes = [d for d in raw_boxes if d.class_name == "box"]
# Supplementary: run extra models every N frames for richer annotations
extras: list[Detection] = []
if len(detectors) > 1 and frame_idx % sup_det_interval == 0:
with ThreadPoolExecutor(max_workers=len(detectors) - 1) as pool:
extra_detectors = [d for i, d in enumerate(detectors) if i != 0]
if extra_detectors and frame_idx % sup_det_interval == 0:
with ThreadPoolExecutor(max_workers=len(extra_detectors)) as pool:
futures = {pool.submit(d.detect, frame): d for d in extra_detectors}
for future in as_completed(futures):
try:
extras.extend(future.result())
except Exception:
pass
extras = _apply_class_confs(extras, sack_conf, box_conf)
extras = _apply_min_area(extras, min_areas)
# Deduplicate ACROSS models only — the same object seen by two
# models is one object. Inside one model the detector's own NMS
# already did that (FCP predict.py:891); deduping there drops real,
# overlapping sacks (a stack on the truck) and loses crossings.
# Deduplicate ACROSS models only — also compare extras against
# dedicated box_tracker so extra boxes do not double-count.
merged = _deduplicate_detections(
primary, extras, iou_threshold=cfg["iou"]["dedup"]
primary, extras, iou_threshold=cfg["iou"]["dedup"], extra_against=raw_boxes
)
# Give supplementary (track_id=None) dets stable negative ids
assigned = synthetic.assign(merged)
# Stabilize and filter to ROI
# Stabilize primary (+ supplementary), then dedicated box stream if configured
stable = stabilizer.update(assigned)
if box_stabilizer is not None:
stable = stable + box_stabilizer.update(raw_boxes)
stable = filter_by_counting_polygon(stable, counting_polygon)
stable = _suppress_sacks_under_boxes(
stable, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
if roi is not None:
tracked = [d for d in stable if roi.contains_x((d.bbox[0] + d.bbox[2]) / 2.0)]
else:
tracked = stable
tracked = _suppress_sacks_under_boxes(
tracked, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
tracked = _apply_class_confs(tracked, sack_conf, box_conf)
tracked = _apply_min_area(tracked, _scaled_min_areas(cfg, w, h))
# Count using only detections with track_id (tracker results)
counter_input = countable_detections(
[d for d in tracked if d.track_id is not None]
@@ -1065,6 +1189,8 @@ def run_merged_pipeline(
batch_duration=batch_mgr.batch_duration,
stabilize_progress=batch_mgr.stabilize_progress,
waiting_duration=batch_mgr.waiting_duration,
counting_polygon=counting_polygon,
truck_polygon=truck_polygon,
)
# Model info overlay
+42 -3
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import math
import os
import subprocess
@@ -13,7 +14,7 @@ def probe_video(video_path: str) -> dict:
"""Return video metadata: {width, height, fps, duration, frame_count}."""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise FileNotFoundError(f"Cannot open video: {video_path}")
raise FileNotFoundError(f"Cannot open video: {os.path.basename(video_path)}")
try:
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
@@ -108,7 +109,7 @@ def extract_thumbnail(
"""Extract a single frame as JPEG. Returns the output_path."""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise FileNotFoundError(f"Cannot open video: {video_path}")
raise FileNotFoundError(f"Cannot open video: {os.path.basename(video_path)}")
try:
fps = cap.get(cv2.CAP_PROP_FPS)
if fps > 0:
@@ -126,13 +127,51 @@ def extract_thumbnail(
cap.release()
def extract_frame_jpeg(
video_path: str, time_sec: float = 0.0, size: tuple[int, int] = (1280, 720)
) -> bytes:
"""Return one frame of the video as JPEG bytes, resized to `size`.
`size` is the analysis frame size (1280x720) so the calibration overlay
maps 1:1 onto the pixels the pipeline counts on.
Raises ValueError when `time_sec` is not a usable seek position (not
finite, negative, or so large that the frame index overflows) and
FileNotFoundError when the video cannot be opened.
"""
if not math.isfinite(time_sec) or time_sec < 0:
raise ValueError("time_sec must be a finite, non-negative number")
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise FileNotFoundError(f"Cannot open video: {os.path.basename(video_path)}")
try:
fps = cap.get(cv2.CAP_PROP_FPS)
frame_idx = 0
if fps and fps > 0:
target = time_sec * fps
if not math.isfinite(target):
raise ValueError(f"time_sec {time_sec} is out of range for this video")
frame_idx = int(target)
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
ret, frame = cap.read()
if not ret:
raise RuntimeError(f"Could not read frame at {time_sec}s")
frame = cv2.resize(frame, size)
ok, buf = cv2.imencode(".jpg", frame)
if not ok:
raise RuntimeError("Could not encode frame as JPEG")
return buf.tobytes()
finally:
cap.release()
def extract_sample_frames(
video_path: str, output_dir: str, count: int = 6
) -> list[str]:
"""Extract evenly-spaced frames as JPEGs. Returns list of paths."""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise FileNotFoundError(f"Cannot open video: {video_path}")
raise FileNotFoundError(f"Cannot open video: {os.path.basename(video_path)}")
try:
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if frame_count <= 0:
+5
View File
@@ -110,3 +110,8 @@ def validate_config(cfg: dict) -> None:
number = _number(f"min_bbox_area.{key}", value)
if number < 0:
raise ValidationError(f"min_bbox_area.{key}={number} must be >= 0")
for key, value in _section(cfg, "counting").items():
number = _number(f"counting.{key}", value)
if number < 0:
raise ValidationError(f"counting.{key}={number} must be >= 0")
+494 -20
View File
@@ -4,6 +4,9 @@ from __future__ import annotations
import json
import os
import shutil
import tempfile
import threading
from math import isfinite
from numbers import Real
from typing import Any
@@ -20,12 +23,6 @@ def load_zone_config(path: str) -> dict[str, Any]:
return json.load(f)
def save_zone_config(config: dict[str, Any], path: str) -> None:
"""Save zone config dict to zones.json."""
with open(path, "w") as f:
json.dump(config, f, indent=2)
def build_static_roi(zone: dict[str, Any], video_w: int, video_h: int) -> TruckROI:
"""Build a TruckROI from a zone config dict, scaling from reference resolution.
@@ -64,13 +61,13 @@ def build_static_roi(zone: dict[str, Any], video_w: int, video_h: int) -> TruckR
x2 = min(video_w, max(xs))
y2 = min(video_h, max(ys))
# Calibrated count-line (FCP predict.py:702-703). The counter counts inside
# Calibrated count-line (FCP predict.py:781-783). The counter counts inside
# the x-window, not inside the truck-ROI bounds. The fallbacks are already
# in frame space (x1/x2/y1/y2 are scaled) — never scale them twice.
line_y = int(count_line["y"] * sy) if "y" in count_line else (y1 + y2) // 2
line_y = int(round(count_line["y"] * sy)) if "y" in count_line else (y1 + y2) // 2
if count_line:
line_x_start = int(count_line["x_start"] * sx) if "x_start" in count_line else x1
line_x_end = int(count_line["x_end"] * sx) if "x_end" in count_line else x2
line_x_start = int(round(count_line["x_start"] * sx)) if "x_start" in count_line else x1
line_x_end = int(round(count_line["x_end"] * sx)) if "x_end" in count_line else x2
else:
# No calibrated line — the counter falls back to the ROI bounds.
line_x_start = None
@@ -122,9 +119,9 @@ def _scaled_points(
x, y = p
if not isinstance(x, Real) or not isinstance(y, Real):
return None
if not (isfinite(x) and isfinite(y)):
if not _is_finite_real(x) or not _is_finite_real(y):
return None
scaled.append((int(x * sx), int(y * sy)))
scaled.append((int(round(x * sx)), int(round(y * sy))))
return scaled
except (TypeError, ValueError, IndexError, KeyError, OverflowError):
return None
@@ -153,11 +150,10 @@ def build_counting_polygon(
) -> Polygon | None:
"""Build the counting polygon of a zone, scaled to the video frame.
zone["counting_area"] holds FCP's detection_poly_pts (predict.py:692-697)
at zone["reference_resolution"]. FCP hardcodes the 1280/1920 x 720/1080
scale and truncates every coordinate with int() — the arithmetic here is
identical to build_static_roi's, so the polygon matches FCP's
detection_polygon exactly.
zone["counting_area"] holds FCP's counting polygon (predict.py:761-769)
at zone["reference_resolution"]. FCP scales from 1920x1080 to 1280x720
using int(round(v * scale)) — the arithmetic here is identical, so the
polygon matches FCP's detection_polygon pixel-for-pixel.
Returns None when the zone has no usable counting_area (no polygon filter).
A malformed calibration degrades to None, it never raises.
@@ -170,9 +166,9 @@ def build_truck_polygon(
) -> Polygon | None:
"""Build the truck-area polygon of a zone, scaled to the video frame.
zone["truck_area"] holds FCP's truck_poly_pts (predict.py:706-712) at
zone["reference_resolution"]. The arithmetic is identical to
build_static_roi's, so the polygon matches FCP's truck_polygon exactly.
zone["truck_area"] holds FCP's truck polygon (predict.py:761-769) at
zone["reference_resolution"]. The arithmetic uses int(round(v * scale))
so the polygon matches FCP's truck_polygon pixel-for-pixel.
Returns None when the zone has no usable truck_area — a malformed
calibration must degrade to "no truck area", never raise.
@@ -186,3 +182,481 @@ def get_active_zone(path: str, preset_name: str | None = None) -> dict[str, Any]
presets = config.get("presets", {})
name = preset_name or config.get("active_preset")
return presets.get(name)
# The canonical zone presets, stored natively in 1920x1080 space and scaled
# to 1280x720 at runtime (mirroring FCP main karung_counter_semarang/zones.json).
DEFAULT_ZONES: dict[str, Any] = {
"default": {
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 215},
"reference_resolution": [1920, 1080],
"left_limit": 0.27578,
"right_limit": 0.72578,
"duplicate_circle_radius": 30,
"min_valid_area": 15000,
"jarak_toleransi_duplikat": 30,
"max_reid_transit_distance": 400,
"circle_stay_timeout_sec": 10.0,
"inference_stride": 2,
"confirm_delay_sec": 0.5,
"exit_confirm_delay_sec": 6.0,
"description": "FCP main (91d8b48) calibration, native 1920x1080 (scaled to 1280x720 at runtime)",
},
"fcp-2026-10-15": {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"palet": [[612, 628], [1454, 630], [1458, 1074], [608, 1071]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
"reference_resolution": [1920, 1080],
"left_limit": 0.27578,
"right_limit": 0.72578,
"duplicate_circle_radius": 30,
"min_valid_area": 15000,
"jarak_toleransi_duplikat": 30,
"max_reid_transit_distance": 400,
"circle_stay_timeout_sec": 10.0,
"inference_stride": 2,
"confirm_delay_sec": 0.5,
"exit_confirm_delay_sec": 6.0,
"description": "FCP 7beb820 calibration (pre-2026-11-11 recalibration), native 1920x1080",
},
}
ZONE_BOUNDS_W = 1920
ZONE_BOUNDS_H = 1080
_DEFAULT_FCP_ZONES_PATH = "/home/jetson/feedmill_semarang_project/karung_counter_semarang/zones.json"
_REPO_ZONES_PATH = os.path.abspath(
os.path.join(os.path.dirname(os.path.dirname(__file__)), "zones.json")
)
_POLYGON_KEYS = ("truck_area", "counting_area", "palet")
_FCP_FLAT_KEYS = (
"truck",
"counting",
"line_y",
"line_x_start",
"line_x_end",
"counting_line",
"coord_space",
)
_FCP_TRANSIENT_KEYS = _FCP_FLAT_KEYS + ("roi",)
def _is_finite_real(v: Any) -> bool:
if not isinstance(v, Real) or isinstance(v, bool):
return False
try:
return isfinite(float(v))
except (OverflowError, TypeError, ValueError):
return False
def _resolve_source_resolution(raw: dict[str, Any]) -> tuple[float, float]:
"""Return (src_w, src_h) encoded by raw's coord_space or reference_resolution."""
if "coord_space" in raw and raw["coord_space"] is not None:
raw_cs = str(raw["coord_space"]).strip().lower()
parts = raw_cs.split("x")
if len(parts) == 2:
try:
w, h = float(parts[0]), float(parts[1])
if isfinite(w) and isfinite(h) and w > 0 and h > 0:
return w, h
except ValueError:
pass
raise ValueError(f"invalid coord_space: {raw['coord_space']!r}")
if "reference_resolution" in raw and raw["reference_resolution"] is not None:
ref = raw["reference_resolution"]
if (
isinstance(ref, (list, tuple))
and len(ref) == 2
and _is_finite_real(ref[0])
and _is_finite_real(ref[1])
and float(ref[0]) > 0
and float(ref[1]) > 0
):
return float(ref[0]), float(ref[1])
raise ValueError("reference_resolution must be [width, height] of positive numbers")
return float(ZONE_BOUNDS_W), float(ZONE_BOUNDS_H)
def _scale_coord(v: Any, scale: float) -> int | float:
fv = float(v)
if scale != 1.0:
return int(round(fv * scale))
return int(fv) if fv.is_integer() else fv
def _scale_polygon(pts: Any, key: str, sx: float, sy: float) -> list[list[int | float]]:
if not isinstance(pts, list):
raise ValueError(f"{key} must be a polygon list")
scaled = []
for pt in pts:
if not (isinstance(pt, (list, tuple)) and len(pt) == 2
and _is_finite_real(pt[0]) and _is_finite_real(pt[1])):
raise ValueError(f"{key} contains an invalid point")
scaled.append([_scale_coord(pt[0], sx), _scale_coord(pt[1], sy)])
return scaled
def normalize_zone_preset(raw: dict[str, Any]) -> dict[str, Any]:
"""Normalize an FCP flat zones.json or recounter preset to [1920, 1080].
Accepts:
- FCP flat schema: truck, counting, palet, line_y/line_x_start/line_x_end
or 2-point counting_line, with optional coord_space (default 1920x1080).
- Recounter preset schema: truck_area, counting_area, palet, count_line,
with optional reference_resolution (scales 1280x720 -> 1920x1080).
Strips transient FCP flat keys and sets reference_resolution=[1920, 1080].
"""
if not isinstance(raw, dict):
raise ValueError("preset must be an object")
src_w, src_h = _resolve_source_resolution(raw)
sx = ZONE_BOUNDS_W / src_w
sy = ZONE_BOUNDS_H / src_h
out: dict[str, Any] = {
k: v for k, v in raw.items() if k not in _FCP_TRANSIENT_KEYS
}
for target_key, flat_key in (
("truck_area", "truck"),
("counting_area", "counting"),
("palet", "palet"),
):
pts = raw.get(target_key) if target_key in raw else raw.get(flat_key)
if pts is not None:
out[target_key] = _scale_polygon(pts, target_key, sx, sy)
if raw.get("count_line") is not None:
line = raw["count_line"]
if not isinstance(line, dict):
raise ValueError("count_line must be an object")
scaled_line = dict(line)
for coord_key, sc in (("x_start", sx), ("x_end", sx), ("y", sy)):
v = line.get(coord_key)
if not _is_finite_real(v):
raise ValueError("count_line needs integer x_start, x_end and y")
scaled_line[coord_key] = _scale_coord(v, sc)
out["count_line"] = scaled_line
elif raw.get("counting_line") is not None:
cl = raw["counting_line"]
if not (
isinstance(cl, list)
and len(cl) == 2
and all(
isinstance(p, (list, tuple)) and len(p) == 2
and _is_finite_real(p[0]) and _is_finite_real(p[1])
for p in cl
)
):
raise ValueError("counting_line must be 2 [x, y] points")
xs = sorted([float(cl[0][0]), float(cl[1][0])])
mean_y = (float(cl[0][1]) + float(cl[1][1])) / 2.0
out["count_line"] = {
"x_start": int(round(xs[0] * sx)),
"x_end": int(round(xs[1] * sx)),
"y": int(round(mean_y * sy)),
}
elif any(k in raw for k in ("line_y", "line_x_start", "line_x_end")):
xs_raw, xe_raw, y_raw = (
raw.get("line_x_start"),
raw.get("line_x_end"),
raw.get("line_y"),
)
if not (_is_finite_real(xs_raw) and _is_finite_real(xe_raw) and _is_finite_real(y_raw)):
raise ValueError("count_line needs integer x_start, x_end and y")
out["count_line"] = {
"x_start": _scale_coord(xs_raw, sx),
"x_end": _scale_coord(xe_raw, sx),
"y": _scale_coord(y_raw, sy),
}
out["reference_resolution"] = [ZONE_BOUNDS_W, ZONE_BOUNDS_H]
return out
def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
"""Validate one zone preset, raise ValueError naming the offending key.
Checks: truck_area present with exactly 4 points (the runtime needs 4);
every polygon key that is present holds >=3 points of 2 finite numbers
inside 0..1920 x 0..1080 and forms a valid polygon with area > 0;
count_line has finite integer x_start < x_end and a y inside the frame;
reference_resolution, when present, is [1920, 1080].
Unknown keys (the tuning knobs) pass through untouched.
Returns a validated copy: count_line numbers and reference_resolution
become ints, so the caller persists exactly what was checked.
"""
if not isinstance(preset, dict):
raise ValueError("preset must be an object")
normalized = dict(preset)
if "reference_resolution" in preset:
ref = preset["reference_resolution"]
if not (
isinstance(ref, (list, tuple))
and len(ref) == 2
and all(isinstance(v, Real) and not isinstance(v, bool) for v in ref)
and [float(v) for v in ref] == [float(ZONE_BOUNDS_W), float(ZONE_BOUNDS_H)]
):
raise ValueError(
f"reference_resolution must be [{ZONE_BOUNDS_W}, {ZONE_BOUNDS_H}]"
)
# Always pin the native 1920x1080 space (scaled to 1280x720 at runtime).
normalized["reference_resolution"] = [ZONE_BOUNDS_W, ZONE_BOUNDS_H]
for key in _POLYGON_KEYS:
if key not in preset:
if key == "truck_area":
raise ValueError("truck_area is required")
continue
pts = preset[key]
if key == "truck_area":
# build_static_roi needs 4 points; a 3-point truck_area would
# pass here and then degrade the job to dynamic mode.
if not isinstance(pts, list) or len(pts) != 4:
raise ValueError("truck_area must be a polygon with exactly 4 points")
elif not isinstance(pts, list) or len(pts) < 3:
raise ValueError(f"{key} must be a polygon with at least 3 points")
clean: list[tuple[float, float]] = []
for pt in pts:
if (not isinstance(pt, (list, tuple)) or len(pt) != 2
or not all(isinstance(v, Real) and not isinstance(v, bool) for v in pt)):
raise ValueError(f"{key} contains an invalid point")
try:
x, y = float(pt[0]), float(pt[1])
except (OverflowError, TypeError, ValueError) as exc:
raise ValueError(f"{key} contains an invalid point") from exc
if not (isfinite(x) and isfinite(y)):
raise ValueError(f"{key} contains an invalid point")
if not (0 <= x <= ZONE_BOUNDS_W and 0 <= y <= ZONE_BOUNDS_H):
raise ValueError(
f"{key} point {[x, y]} is outside {ZONE_BOUNDS_W}x{ZONE_BOUNDS_H} bounds"
)
clean.append((x, y))
try:
poly = Polygon(clean)
except GEOSException as exc:
raise ValueError(f"{key} is not a valid polygon: {exc}") from exc
if not poly.is_valid or poly.area <= 0:
raise ValueError(f"{key} is degenerate (invalid or zero area)")
line = preset.get("count_line")
if line is not None:
if not isinstance(line, dict):
raise ValueError("count_line must be an object")
nums: dict[str, int] = {}
for name in ("x_start", "x_end", "y"):
v = line.get(name)
if not isinstance(v, Real) or isinstance(v, bool):
raise ValueError("count_line needs integer x_start, x_end and y")
try:
fv = float(v)
except (OverflowError, TypeError, ValueError) as exc:
raise ValueError("count_line needs integer x_start, x_end and y") from exc
if not isfinite(fv) or not fv.is_integer():
raise ValueError("count_line needs integer x_start, x_end and y")
nums[name] = int(fv)
x_start, x_end, y = nums["x_start"], nums["x_end"], nums["y"]
if not (0 <= x_start < x_end <= ZONE_BOUNDS_W):
raise ValueError(
f"count_line x_start/x_end must satisfy 0 <= x_start < x_end <= {ZONE_BOUNDS_W}"
)
if not (0 <= y <= ZONE_BOUNDS_H):
raise ValueError(f"count_line y={y} is outside 0..{ZONE_BOUNDS_H}")
normalized["count_line"] = {**line, **nums}
return normalized
# Serializes the read-modify-write in save_zone_preset; without it two
# concurrent writes can lose one of the updates.
_SAVE_LOCK = threading.Lock()
def _write_zone_config_atomic(path: str, config: dict[str, Any]) -> None:
"""Atomically overwrite zones.json with a .bak backup, preserving file mode."""
shutil.copy2(path, path + ".bak")
directory = os.path.dirname(os.path.abspath(path))
fd, tmp = tempfile.mkstemp(
dir=directory, prefix=os.path.basename(path) + ".", suffix=".tmp"
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)
f.write("\n")
# mkstemp creates 0600; keep the mode the file had before.
os.chmod(tmp, os.stat(path).st_mode & 0o777)
os.replace(tmp, path)
except BaseException:
if os.path.exists(tmp):
os.unlink(tmp)
raise
def save_zone_preset(path: str, name: str, preset: dict[str, Any],
replace: bool = False) -> None:
"""Merge a preset into zones.json under `name`, atomically, with a backup.
Accepts either a standard recounter preset or FCP's flat zones.json shape
(auto-normalized to [1920, 1080] before merging). The preset is merged
OVER the stored one unless replace=True.
Raises FileNotFoundError if the file does not exist and ValueError if the
file or preset is unusable.
"""
if not os.path.isfile(path):
raise FileNotFoundError(f"zones.json not found: {path}")
if not isinstance(preset, dict):
raise ValueError("preset must be an object")
ref = preset.get("reference_resolution")
is_legacy_720p = (
isinstance(ref, (list, tuple))
and len(ref) == 2
and _is_finite_real(ref[0])
and _is_finite_real(ref[1])
and [float(ref[0]), float(ref[1])] == [1280.0, 720.0]
)
if any(k in preset for k in _FCP_FLAT_KEYS) or is_legacy_720p:
preset = normalize_zone_preset(preset)
with _SAVE_LOCK:
config = load_zone_config(path)
if not isinstance(config, dict):
raise ValueError("zones.json must contain a JSON object")
presets = config.get("presets")
if presets is None:
presets = {}
config["presets"] = presets
elif not isinstance(presets, dict):
raise ValueError("zones.json 'presets' must be a JSON object")
merged = preset if replace else {**presets.get(name, {}), **preset}
presets[name] = validate_zone_preset(merged)
_write_zone_config_atomic(path, config)
def _resolve_fcp_zones_source(zones_path: str, fcp_zones_path: str | None) -> str | None:
"""Return FCP zones.json path to sync from, or None when auto-sync is disabled."""
if fcp_zones_path is not None:
return fcp_zones_path.strip() or None
if "FCP_ZONES_PATH" in os.environ:
return os.environ["FCP_ZONES_PATH"].strip() or None
if os.path.abspath(zones_path) == _REPO_ZONES_PATH:
return _DEFAULT_FCP_ZONES_PATH
return None
def sync_fcp_zones(
zones_path: str,
fcp_zones_path: str | None = None,
*,
force: bool = False,
) -> bool:
"""Sync presets['default'] from FCP's zones.json when FCP's file is newer.
Returns True when zones_path was updated, False otherwise. Never raises on
an unreadable/malformed external FCP file or write failure so fixed-zone
inference and read routes degrade cleanly.
"""
src = _resolve_fcp_zones_source(zones_path, fcp_zones_path)
if not src or not os.path.isfile(src) or not os.path.isfile(zones_path):
return False
if os.path.abspath(src) == os.path.abspath(zones_path):
return False
try:
src_st = os.stat(src)
dst_st = os.stat(zones_path)
except OSError:
return False
if not force and src_st.st_mtime_ns <= dst_st.st_mtime_ns:
return False
try:
raw_fcp = load_zone_config(src)
normalized = normalize_zone_preset(raw_fcp)
candidate = validate_zone_preset(normalized)
except (OSError, ValueError, TypeError, OverflowError) as exc:
print(f"[ZONE] ignoring unreadable FCP zones at {src}: {exc}")
return False
with _SAVE_LOCK:
try:
src_st = os.stat(src)
dst_st = os.stat(zones_path)
if not force and src_st.st_mtime_ns <= dst_st.st_mtime_ns:
return False
config = load_zone_config(zones_path)
if not isinstance(config, dict):
return False
presets = config.get("presets")
if presets is None:
presets = {}
config["presets"] = presets
elif not isinstance(presets, dict):
return False
current = presets.get("default", {})
if not isinstance(current, dict):
current = {}
merged = validate_zone_preset({**current, **candidate})
if merged == current and not force:
return False
presets["default"] = merged
_write_zone_config_atomic(zones_path, config)
except (OSError, ValueError, TypeError, OverflowError) as exc:
print(f"[ZONE] failed to sync FCP zones into {zones_path}: {exc}")
return False
print(f"[ZONE] synced 'default' preset from FCP zones: {src}")
return True
def resolve_zone(
zone_mode: str,
zone_preset: str,
zones_path: str,
analysis_size: tuple[int, int] = (1280, 720),
*,
zone_reader=None,
) -> tuple[str, TruckROI | None, str, Polygon | None, Polygon | None]:
"""Resolve the counting zone of a job or CLI run in analysis_size (1280x720).
Auto-syncs 'default' from FCP's zones.json when newer, then builds the
fixed TruckROI + counting/truck polygons. Falls back to 'dynamic' if
zones_path is missing or malformed.
"""
if zone_mode != "fixed":
return zone_mode, None, zone_preset, None, None
sync_fcp_zones(zones_path)
reader = zone_reader or get_active_zone
w, h = analysis_size
reason = "no zone file"
roi: TruckROI | None = None
polygon: Polygon | None = None
truck_polygon: Polygon | None = None
built = False
if os.path.isfile(zones_path):
try:
zone = reader(zones_path, zone_preset or None)
if zone is None:
reason = "no active preset"
else:
roi = build_static_roi(zone, w, h)
polygon = build_counting_polygon(zone, w, h)
truck_polygon = build_truck_polygon(zone, w, h)
if zone.get("counting_area") and polygon is None:
reason = "malformed counting_area"
else:
built = True
except (
OSError, ValueError, TypeError, AttributeError,
IndexError, KeyError, OverflowError, GEOSException,
) as exc:
reason = f"unreadable calibration — could not be read/applied ({exc})"
if not built:
print(f"[ZONE] {reason} at {zones_path} — falling back to dynamic")
return "dynamic", None, zone_preset, None, None
return "fixed", roi, zone_preset or "default", polygon, truck_polygon
+622
View File
@@ -0,0 +1,622 @@
/* Interactive zone editor.
*
* The backdrop is a 16:9 frame (1280x720) and the SVG overlay uses a
* 1920x1080 viewBox, so coordinates are edited directly in FCP's 1920x1080
* zone space with uniform scaling and letterbox offset ("xMidYMid meet").
*/
(function () {
'use strict';
const ZONE_SOURCE_W = 1920;
const ZONE_SOURCE_H = 1080;
const ZONE_LINE_MARGIN = 30; // 20px trigger band in 720p == 30px in 1080p
const SVG_NS = 'http://www.w3.org/2000/svg';
// Area key -> visibility toggle key and colour.
const AREAS = [
{ key: 'counting_area', vis: 'counting', color: '#2563eb' },
{ key: 'truck_area', vis: 'truck', color: '#d97706' }
];
let zonesData = null;
let zoneEditMode = false;
let zoneDrag = null;
const zoneVisibility = { counting: false, truck: false, counting_line: false };
let currentPreset = '';
let frameTimer = null;
const $ = function (id) { return document.getElementById(id); };
function setStatus(text) {
$('zone-status').textContent = text;
}
function sourcePoint(ev) {
const svg = document.getElementById('zoneOverlay');
const r = svg.getBoundingClientRect();
const scale = Math.min(r.width / ZONE_SOURCE_W, r.height / ZONE_SOURCE_H);
const offsetX = (r.width - ZONE_SOURCE_W * scale) / 2;
const offsetY = (r.height - ZONE_SOURCE_H * scale) / 2;
const x = Math.round((ev.clientX - r.left - offsetX) / scale);
const y = Math.round((ev.clientY - r.top - offsetY) / scale);
return {
x: Math.max(0, Math.min(ZONE_SOURCE_W, x)),
y: Math.max(0, Math.min(ZONE_SOURCE_H, y))
};
}
function svgEl(name, attrs) {
const node = document.createElementNS(SVG_NS, name);
Object.keys(attrs).forEach(function (key) {
node.setAttribute(key, attrs[key]);
});
return node;
}
function areaByKey(key) {
for (let i = 0; i < AREAS.length; i++) {
if (AREAS[i].key === key) return AREAS[i];
}
return null;
}
function makeHandle(id, color, cx, cy, radius, onDown) {
const node = svgEl('circle', {
id: id, cx: cx, cy: cy, r: radius,
fill: color, stroke: '#ffffff', 'stroke-width': '2',
'vector-effect': 'non-scaling-stroke'
});
node.classList.add('zone-handle');
node.style.display = zoneEditMode ? '' : 'none';
node.style.pointerEvents = zoneEditMode ? 'all' : 'none';
node.addEventListener('mousedown', onDown);
return node;
}
function renderZones() {
const layer = $('zoneLayer');
layer.innerHTML = '';
syncVisibilityUI();
if (!zonesData) return;
AREAS.forEach(function (area) {
const pts = zonesData[area.key];
if (!zoneVisibility[area.vis] || !Array.isArray(pts) || pts.length < 3) return;
layer.appendChild(svgEl('polygon', {
id: 'zp-' + area.vis,
points: pts.map(function (p) { return p[0] + ',' + p[1]; }).join(' '),
fill: area.color + '22',
stroke: area.color,
'stroke-width': '3',
'vector-effect': 'non-scaling-stroke'
}));
pts.forEach(function (pt, i) {
layer.appendChild(makeHandle(
'zh-' + area.vis + '-' + i, area.color, pt[0], pt[1], 12,
function (ev) { startZoneDrag(ev, area.key, 'poly', i); }
));
});
});
const line = zonesData.counting_line;
if (zoneVisibility.counting_line && Array.isArray(line) && line.length === 2) {
const lineY = Math.round((line[0][1] + line[1][1]) / 2);
line[0][1] = lineY;
line[1][1] = lineY;
const xMin = Math.min(line[0][0], line[1][0]);
const xMax = Math.max(line[0][0], line[1][0]);
const bandTop = Math.max(0, lineY - ZONE_LINE_MARGIN);
const bandBottom = Math.min(ZONE_SOURCE_H, lineY + ZONE_LINE_MARGIN);
const band = svgEl('rect', {
id: 'zb-counting', x: xMin, y: bandTop,
width: Math.max(1, xMax - xMin), height: Math.max(1, bandBottom - bandTop),
fill: 'rgba(22, 163, 74, 0.16)', stroke: '#16a34a',
'stroke-width': '1.5', 'stroke-dasharray': '6,4',
'vector-effect': 'non-scaling-stroke'
});
band.style.pointerEvents = 'none';
layer.appendChild(band);
const stroke = svgEl('line', {
id: 'zl-counting', x1: line[0][0], y1: lineY, x2: line[1][0], y2: lineY,
stroke: '#16a34a', 'stroke-width': '4', 'vector-effect': 'non-scaling-stroke'
});
stroke.style.pointerEvents = 'none';
layer.appendChild(stroke);
line.forEach(function (pt, i) {
layer.appendChild(makeHandle(
'zh-line-' + i, '#16a34a', pt[0], lineY, 13,
function (ev) { startZoneDrag(ev, 'counting_line', 'line', i); }
));
});
}
}
function startZoneDrag(ev, key, kind, index) {
if (!zoneEditMode) return;
ev.preventDefault();
ev.stopPropagation();
zoneDrag = { key: key, kind: kind, index: index };
document.addEventListener('mousemove', onZoneDrag);
document.addEventListener('mouseup', endZoneDrag);
}
function onZoneDrag(ev) {
if (!zoneDrag) return;
const pt = sourcePoint(ev);
const info = zoneDrag;
if (info.kind === 'poly') {
zonesData[info.key][info.index] = [pt.x, pt.y];
const area = areaByKey(info.key);
const poly = document.getElementById('zp-' + area.vis);
if (poly) {
poly.setAttribute('points', zonesData[info.key].map(function (p) {
return p[0] + ',' + p[1];
}).join(' '));
}
const handle = document.getElementById('zh-' + area.vis + '-' + info.index);
if (handle) {
handle.setAttribute('cx', pt.x);
handle.setAttribute('cy', pt.y);
}
return;
}
// The count line stays horizontal: the dragged endpoint sets x, and
// both endpoints take the dragged y.
const line = zonesData.counting_line;
line[info.index][0] = pt.x;
line[0][1] = pt.y;
line[1][1] = pt.y;
const x0 = line[0][0];
const x1 = line[1][0];
const bandTop = Math.max(0, pt.y - ZONE_LINE_MARGIN);
const bandBottom = Math.min(ZONE_SOURCE_H, pt.y + ZONE_LINE_MARGIN);
const band = document.getElementById('zb-counting');
if (band) {
band.setAttribute('x', Math.min(x0, x1));
band.setAttribute('y', bandTop);
band.setAttribute('width', Math.max(1, Math.abs(x1 - x0)));
band.setAttribute('height', Math.max(1, bandBottom - bandTop));
}
const stroke = document.getElementById('zl-counting');
if (stroke) {
stroke.setAttribute('x1', x0);
stroke.setAttribute('y1', pt.y);
stroke.setAttribute('x2', x1);
stroke.setAttribute('y2', pt.y);
}
['zh-line-0', 'zh-line-1'].forEach(function (id, i) {
const handle = document.getElementById(id);
if (!handle) return;
handle.setAttribute('cx', i === 0 ? x0 : x1);
handle.setAttribute('cy', pt.y);
});
}
function endZoneDrag() {
zoneDrag = null;
document.removeEventListener('mousemove', onZoneDrag);
document.removeEventListener('mouseup', endZoneDrag);
}
function syncVisibilityUI() {
const buttons = {
counting: 'zone-vis-counting',
truck: 'zone-vis-truck',
counting_line: 'zone-vis-line'
};
Object.keys(buttons).forEach(function (key) {
const btn = $(buttons[key]);
if (!btn) return;
const visible = Boolean(zoneVisibility[key]);
btn.setAttribute('aria-pressed', visible ? 'true' : 'false');
});
const all = Object.keys(buttons).every(function (key) { return zoneVisibility[key]; });
const global = $('zone-vis-all-btn');
if (global) {
global.setAttribute('aria-pressed', all ? 'true' : 'false');
global.textContent = all ? 'Hide All ROIs' : 'Show All ROIs';
}
}
function toggleZoneEdit() {
zoneEditMode = !zoneEditMode;
if (zoneEditMode && !zoneVisibility.counting && !zoneVisibility.truck
&& !zoneVisibility.counting_line) {
zoneVisibility.counting = true;
zoneVisibility.truck = true;
zoneVisibility.counting_line = true;
}
$('zone-edit-btn').textContent = zoneEditMode ? 'Lock Edit' : 'Unlock Edit';
setStatus(zoneEditMode ? 'Editing: drag handles, then Save' : 'Locked');
renderZones();
}
function toggleZoneItemVisibility(key) {
if (!(key in zoneVisibility)) return;
zoneVisibility[key] = !zoneVisibility[key];
renderZones();
}
function toggleAllZoneVisibility() {
const all = Object.keys(zoneVisibility).every(function (key) { return zoneVisibility[key]; });
Object.keys(zoneVisibility).forEach(function (key) {
zoneVisibility[key] = !all;
});
renderZones();
}
function buildCurrentPresetPayload() {
const xs = zonesData.counting_line.map(function (p) { return p[0]; });
const ys = zonesData.counting_line.map(function (p) { return p[1]; });
const obj = {
truck_area: zonesData.truck_area,
counting_area: zonesData.counting_area,
count_line: {
x_start: Math.min.apply(null, xs),
x_end: Math.max.apply(null, xs),
y: Math.round(ys.reduce(function (a, b) { return a + b; }, 0) / ys.length)
},
reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H]
};
if (Array.isArray(zonesData.palet) && zonesData.palet.length >= 3) {
obj.palet = zonesData.palet;
}
return obj;
}
function isFiniteNumber(v) {
return typeof v === 'number' && Number.isFinite(v);
}
function resolveInputSpace(obj) {
if ('coord_space' in obj && obj.coord_space !== undefined && obj.coord_space !== null) {
if (typeof obj.coord_space !== 'string' || !obj.coord_space.trim()) {
throw new Error('coord_space must be formatted like "1920x1080"');
}
const parts = obj.coord_space.trim().toLowerCase().split('x');
if (parts.length === 2) {
const w = Number(parts[0]);
const h = Number(parts[1]);
if (parts[0].trim() && parts[1].trim() && Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {
return [w, h];
}
}
throw new Error('coord_space must be formatted like "1920x1080"');
}
if ('reference_resolution' in obj && obj.reference_resolution !== undefined && obj.reference_resolution !== null) {
if (!Array.isArray(obj.reference_resolution) || obj.reference_resolution.length !== 2) {
throw new Error('reference_resolution must be [width, height]');
}
const rw = obj.reference_resolution[0];
const rh = obj.reference_resolution[1];
if (!isFiniteNumber(rw) || !isFiniteNumber(rh) || rw <= 0 || rh <= 0) {
throw new Error('reference_resolution values must be positive numbers');
}
return [rw, rh];
}
return [ZONE_SOURCE_W, ZONE_SOURCE_H];
}
function scalePresetToSource(preset, srcW, srcH) {
const sx = srcW ? (ZONE_SOURCE_W / srcW) : 1;
const sy = srcH ? (ZONE_SOURCE_H / srcH) : 1;
const scalePt = function (p) {
return (sx === 1 && sy === 1)
? [p[0], p[1]]
: [Math.round(p[0] * sx), Math.round(p[1] * sy)];
};
const scaleVal = function (v, sc) {
return sc === 1 ? v : Math.round(v * sc);
};
const line = (preset && preset.count_line) || {};
const out = {
truck_area: Array.isArray(preset.truck_area) ? preset.truck_area.map(scalePt) : [],
counting_area: Array.isArray(preset.counting_area) ? preset.counting_area.map(scalePt) : [],
count_line: {
x_start: scaleVal(isFiniteNumber(line.x_start) ? line.x_start : 0, sx),
x_end: scaleVal(isFiniteNumber(line.x_end) ? line.x_end : 0, sx),
y: scaleVal(isFiniteNumber(line.y) ? line.y : 0, sy)
},
reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H]
};
if (Array.isArray(preset.palet)) {
out.palet = preset.palet.map(scalePt);
}
return out;
}
function applyPreset(preset) {
const raw = preset || {};
let res = [ZONE_SOURCE_W, ZONE_SOURCE_H];
try {
res = resolveInputSpace(raw);
} catch (e) {
res = [ZONE_SOURCE_W, ZONE_SOURCE_H];
}
const normalized = scalePresetToSource(raw, res[0], res[1]);
const line = normalized.count_line;
zonesData = {
truck_area: normalized.truck_area,
counting_area: normalized.counting_area,
palet: Array.isArray(normalized.palet) ? normalized.palet : null,
counting_line: [
[line.x_start, line.y],
[line.x_end, line.y]
]
};
renderZones();
}
async function loadPreset(name) {
currentPreset = name;
try {
const res = await fetch('/api/zones/' + encodeURIComponent(name));
const data = await res.json();
if (!res.ok) {
setStatus('Load failed: ' + (data.error || res.status));
return;
}
applyPreset(data.preset || {});
setStatus(zoneEditMode ? 'Editing: drag handles, then Save' : 'Locked');
} catch (err) {
setStatus('Load failed');
}
}
async function saveZones() {
if (!zonesData || !currentPreset) {
setStatus('Nothing to save');
return;
}
const payload = { preset: buildCurrentPresetPayload() };
try {
const res = await fetch('/api/zones/' + encodeURIComponent(currentPreset), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json().catch(function () { return {}; });
if (!res.ok) {
setStatus('Save failed: ' + (data.error || res.status));
return;
}
await loadPreset(currentPreset);
setStatus('Saved to zones.json');
} catch (err) {
setStatus('Save failed');
}
}
function parseZoneJson(text) {
let obj;
try { obj = JSON.parse(text); } catch (e) { throw new Error('Invalid JSON: ' + e.message); }
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) throw new Error('Expected a JSON object');
const res = resolveInputSpace(obj);
const truck = ('truck_area' in obj) ? obj.truck_area : obj.truck;
const counting = ('counting_area' in obj) ? obj.counting_area : obj.counting;
if (!Array.isArray(truck) || truck.length !== 4) throw new Error('truck_area/truck must be an array of 4 [x,y] points');
if (!Array.isArray(counting) || counting.length < 3) throw new Error('counting_area/counting must be an array of at least 3 [x,y] points');
let x0, x1, lineY;
if (obj.count_line && typeof obj.count_line === 'object' && !Array.isArray(obj.count_line)) {
x0 = obj.count_line.x_start;
x1 = obj.count_line.x_end;
lineY = obj.count_line.y;
} else if (Array.isArray(obj.counting_line) && obj.counting_line.length === 2
&& Array.isArray(obj.counting_line[0]) && obj.counting_line[0].length === 2
&& Array.isArray(obj.counting_line[1]) && obj.counting_line[1].length === 2) {
x0 = obj.counting_line[0][0];
x1 = obj.counting_line[1][0];
lineY = (obj.counting_line[0][1] + obj.counting_line[1][1]) / 2;
} else if ('line_y' in obj || 'line_x_start' in obj || 'line_x_end' in obj) {
x0 = obj.line_x_start;
x1 = obj.line_x_end;
lineY = obj.line_y;
} else {
throw new Error('count_line or line_y/line_x_start/line_x_end is required');
}
if (!isFiniteNumber(x0) || !isFiniteNumber(x1) || !isFiniteNumber(lineY)) {
throw new Error('count_line values must be finite numbers');
}
const checkPoly = function (pts, label) {
for (let i = 0; i < pts.length; i++) {
if (!Array.isArray(pts[i]) || pts[i].length !== 2) throw new Error(label + ' points must be [x,y]');
if (!pts[i].every(isFiniteNumber)) {
throw new Error(label + ' values must be finite numbers');
}
}
};
checkPoly(truck, 'truck_area');
checkPoly(counting, 'counting_area');
if (obj.palet !== undefined) {
if (!Array.isArray(obj.palet) || obj.palet.length < 3) throw new Error('palet must be at least 3 [x,y] points');
checkPoly(obj.palet, 'palet');
}
const unscaled = {
truck_area: truck,
counting_area: counting,
count_line: { x_start: Math.min(x0, x1), x_end: Math.max(x0, x1), y: Math.round(lineY) }
};
if (obj.palet !== undefined) unscaled.palet = obj.palet;
const parsed = scalePresetToSource(unscaled, res[0], res[1]);
parsed._source_resolution = res;
return parsed;
}
function importJson() {
const ta = $('zone-json');
if (!ta) return;
try {
const preset = parseZoneJson(ta.value);
const src = preset._source_resolution;
delete preset._source_resolution;
applyPreset(preset);
if (src && (src[0] !== ZONE_SOURCE_W || src[1] !== ZONE_SOURCE_H)) {
setStatus('Imported (scaled ' + src[0] + 'x' + src[1] + ' -> 1920x1080) — drag handles or Save');
} else {
setStatus('Imported — drag handles or Save');
}
} catch (err) {
setStatus('Import failed: ' + err.message);
}
}
function exportJson() {
if (!zonesData) { setStatus('Nothing to export'); return; }
const obj = buildCurrentPresetPayload();
const text = JSON.stringify(obj, null, 2);
const ta = $('zone-json');
if (ta) ta.value = text;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(function () { setStatus('Copied to clipboard'); }, function () { setStatus('Copied to textarea'); });
} else {
setStatus('Copied to textarea');
}
}
function downloadJson() {
if (!zonesData) { setStatus('Nothing to download'); return; }
const obj = buildCurrentPresetPayload();
const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = (currentPreset || 'zones') + '.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(a.href);
setStatus('Downloaded');
}
async function resetZones() {
if (!currentPreset) return;
try {
const res = await fetch('/api/zones/' + encodeURIComponent(currentPreset) + '/reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
});
const data = await res.json().catch(function () { return {}; });
if (!res.ok) {
setStatus('Reset failed: ' + (data.error || res.status));
return;
}
applyPreset(data.preset || {});
setStatus('Reset to the shipped default');
} catch (err) {
setStatus('Reset failed');
}
}
function loadFrame() {
const video = $('video-select').value;
if (!video) return;
const t = parseFloat($('time-slider').value) || 0;
$('zone-backdrop').src = '/api/frame?video=' + encodeURIComponent(video) + '&t=' + t;
}
async function loadVideos() {
const select = $('video-select');
try {
const res = await fetch('/api/videos');
const videos = await res.json();
select.innerHTML = '';
videos.forEach(function (video) {
const option = document.createElement('option');
option.value = video.filename;
option.textContent = video.filename;
select.appendChild(option);
});
if (!videos.length) {
setStatus('No videos uploaded yet');
return;
}
loadFrame();
} catch (err) {
setStatus('Could not load the video list');
}
}
async function loadPresets() {
const select = $('preset-select');
try {
const res = await fetch('/api/zones');
const presets = await res.json();
select.innerHTML = '';
presets.forEach(function (preset) {
const option = document.createElement('option');
option.value = preset.name;
option.textContent = preset.name;
select.appendChild(option);
});
if (!presets.length) {
setStatus('No zone presets found');
return;
}
await loadPreset(presets[0].name);
} catch (err) {
setStatus('Could not load the zone presets');
}
}
function init() {
$('zone-edit-btn').addEventListener('click', toggleZoneEdit);
$('zone-save-btn').addEventListener('click', saveZones);
$('zone-reload-btn').addEventListener('click', function () {
if (currentPreset) loadPreset(currentPreset);
});
$('zone-reset-btn').addEventListener('click', resetZones);
const importBtn = $('zone-import-btn');
if (importBtn) importBtn.addEventListener('click', importJson);
const copyBtn = $('zone-copy-btn');
if (copyBtn) copyBtn.addEventListener('click', exportJson);
const dlBtn = $('zone-download-btn');
if (dlBtn) dlBtn.addEventListener('click', downloadJson);
$('zone-vis-all-btn').addEventListener('click', toggleAllZoneVisibility);
$('zone-vis-counting').addEventListener('click', function () {
toggleZoneItemVisibility('counting');
});
$('zone-vis-truck').addEventListener('click', function () {
toggleZoneItemVisibility('truck');
});
$('zone-vis-line').addEventListener('click', function () {
toggleZoneItemVisibility('counting_line');
});
$('preset-select').addEventListener('change', function () {
loadPreset(this.value);
});
$('video-select').addEventListener('change', loadFrame);
$('zone-backdrop').addEventListener('error', function () {
setStatus('Frame failed to load (corrupt video, or the time is past the end)');
});
$('zone-backdrop').addEventListener('load', function () {
const el = $('zone-status');
const cur = (el && el.textContent) || '';
if (/fail|error/i.test(cur)) return; // don't clobber an error message
setStatus(zoneEditMode ? 'Editing: drag handles, then Save' : 'Locked');
});
$('time-slider').addEventListener('input', function () {
$('time-label').textContent = (parseFloat(this.value) || 0).toFixed(1) + ' s';
if (frameTimer) clearTimeout(frameTimer);
frameTimer = setTimeout(loadFrame, 150);
});
renderZones();
loadPresets();
loadVideos();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
+97
View File
@@ -1205,3 +1205,100 @@ main {
max-width: 1024px;
}
}
/* ---------- Zone calibration page ---------- */
.calibrate-heading {
margin-bottom: var(--space-4);
}
.calibrate-heading h2 {
margin-bottom: var(--space-1);
}
.calibrate-heading p {
color: var(--color-neutral-500);
font-size: var(--text-sm);
}
.calibrate-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
padding: var(--space-4);
margin-bottom: var(--space-3);
background: #fff;
border: 1px solid var(--color-neutral-200);
border-radius: var(--radius-lg);
}
.calibrate-toolbar label {
font-size: var(--text-sm);
font-weight: var(--font-semibold);
color: var(--color-neutral-600);
}
.calibrate-toolbar select {
max-width: 200px;
}
.calibrate-toolbar input[type="range"] {
width: 170px;
}
#time-label {
min-width: 3.5rem;
font-size: var(--text-sm);
font-variant-numeric: tabular-nums;
color: var(--color-neutral-600);
}
.calibrate-status {
margin-left: auto;
font-size: var(--text-sm);
color: var(--color-neutral-600);
}
#zone-legend {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin-bottom: var(--space-3);
}
#zone-legend .btn[aria-pressed="true"],
#zone-vis-all-btn[aria-pressed="true"] {
background: var(--color-primary);
color: #fff;
border-color: var(--color-primary);
}
.calibrate-stage {
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
overflow: hidden;
background: var(--color-neutral-900);
border: 1px solid var(--color-neutral-200);
border-radius: var(--radius-lg);
}
#zone-backdrop {
position: relative;
display: block;
width: 100%;
height: 100%;
object-fit: contain;
}
#zoneOverlay {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
#zoneOverlay .zone-handle {
cursor: grab;
}
+1
View File
@@ -19,6 +19,7 @@
<nav class="site-nav" aria-label="Main navigation">
<a href="/">Upload</a>
<a href="/jobs">Jobs</a>
<a href="/calibrate">Calibrate</a>
</nav>
</div>
</header>
+59
View File
@@ -0,0 +1,59 @@
{% extends "base.html" %}
{% block title %}Calibrate Zones - Feedmill Recounter{% endblock %}
{% block content %}
<div class="calibrate-heading">
<h2>Zone Calibration</h2>
<p>Drag the counting area, truck area and count line over a frame of an uploaded video, then save.
Coordinates are stored in 1920&times;1080 (scaled to 1280&times;720 at runtime to match FCP).
<a href="/" class="btn btn-ghost btn-sm" style="margin-left: var(--space-2);">&larr; Back to Upload</a>
</p>
</div>
<div class="calibrate-toolbar">
<label for="preset-select">Preset</label>
<select id="preset-select" class="form-select"></select>
<label for="video-select">Video</label>
<select id="video-select" class="form-select"></select>
<label for="time-slider">Time (s)</label>
<input type="range" id="time-slider" min="0" max="60" step="0.5" value="0">
<span id="time-label">0.0 s</span>
<button id="zone-edit-btn" type="button" class="btn btn-secondary btn-sm">Unlock Edit</button>
<button id="zone-save-btn" type="button" class="btn btn-primary btn-sm">Save Zones</button>
<button id="zone-reload-btn" type="button" class="btn btn-secondary btn-sm">Reload Zones</button>
<button id="zone-reset-btn" type="button" class="btn btn-secondary btn-sm">Reset Zones</button>
<button id="zone-vis-all-btn" type="button" class="btn btn-ghost btn-sm" aria-pressed="false">Show All ROIs</button>
<span id="zone-status" role="status" class="calibrate-status">Locked</span>
</div>
<div id="zone-legend" role="group" aria-label="ROI visibility">
<button type="button" id="zone-vis-counting" class="btn btn-secondary btn-sm" aria-pressed="false">Counting ROI</button>
<button type="button" id="zone-vis-truck" class="btn btn-secondary btn-sm" aria-pressed="false">Truck ROI</button>
<button type="button" id="zone-vis-line" class="btn btn-secondary btn-sm" aria-pressed="false">Count line</button>
</div>
<details class="calibrate-json-panel">
<summary>Import / Export JSON</summary>
<textarea id="zone-json" rows="6" placeholder='{"truck_area":[[x,y],...],"counting_area":[[x,y],...],"count_line":{"x_start":0,"x_end":0,"y":0},"reference_resolution":[1920,1080]}'></textarea>
<div class="calibrate-json-actions">
<button id="zone-import-btn" type="button" class="btn btn-secondary btn-sm">Import JSON</button>
<button id="zone-copy-btn" type="button" class="btn btn-ghost btn-sm">Copy current zones</button>
<button id="zone-download-btn" type="button" class="btn btn-ghost btn-sm">Download JSON</button>
</div>
</details>
<div class="calibrate-stage">
<img id="zone-backdrop" alt="Video frame under the zone overlay">
<svg id="zoneOverlay" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMid meet">
<g id="zoneLayer"></g>
</svg>
</div>
{% endblock %}
{% block scripts %}
<script src="{{ url_for('static', filename='calibrate.js') }}"></script>
{% endblock %}
+4
View File
@@ -429,6 +429,10 @@
<option value="">Loading presets...</option>
</select>
</div>
<p class="zone-hint" style="margin: var(--space-2) 0 0; font-size: var(--text-sm); color: var(--color-neutral-500);">
Annotated output draws the calibrated counting/truck polygons and the &plusmn;20 px band.
<a href="/calibrate">Open zone calibrator &rarr;</a>
</p>
</div>
</div>
+3
View File
@@ -13,6 +13,9 @@ def _isolate_job_queue(tmp_path, monkeypatch):
# .env RECOUNTER_API_KEY must not leak into tests (it enables 401 auth);
# auth tests set/override it via their own monkeypatch.setenv calls.
monkeypatch.delenv("RECOUNTER_API_KEY", raising=False)
# Prevent host FCP zones.json auto-sync during isolated unit tests unless
# a test sets FCP_ZONES_PATH or passes fcp_zones_path explicitly.
monkeypatch.setenv("FCP_ZONES_PATH", "")
import app as app_module
q = app_module.job_queue
+581
View File
@@ -622,3 +622,584 @@ def test_api_job_list_and_detail_report_truncation(client):
entry = next(j for j in listing if j["job_id"] == job.job_id)
assert entry["results"][0]["truncated"] is True
assert entry["results"][0]["frames_expected"] == 100
def _zones_file(tmp_path, preset):
zones = tmp_path / "zones.json"
zones.write_text(json.dumps({"presets": {"default": preset}, "active_preset": "default"}))
return str(zones)
def test_post_zones_saves_valid_preset(client, tmp_path, monkeypatch):
import app as app_module
preset = {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
"reference_resolution": [1920, 1080],
}
zones = _zones_file(tmp_path, preset)
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default", json={"preset": {**preset, "count_line": {"x_start": 600, "x_end": 1350, "y": 315}}})
assert resp.status_code == 200
saved = json.loads(open(zones).read())
assert saved["presets"]["default"]["count_line"]["y"] == 315
def test_post_zones_invalid_is_400_and_file_unchanged(client, tmp_path, monkeypatch):
import app as app_module
preset = {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
"reference_resolution": [1920, 1080],
}
zones = _zones_file(tmp_path, preset)
before = open(zones).read()
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default", json={"preset": {"truck_area": [[1, 1], [1, 1], [1, 1]]}})
assert resp.status_code == 400
assert open(zones).read() == before
def test_post_zones_from_non_localhost_is_403(client, tmp_path, monkeypatch):
import app as app_module
zones = _zones_file(tmp_path, {"truck_area": [[0, 0], [10, 0], [10, 10], [0, 10]]})
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default", json={"preset": {}},
environ_base={"REMOTE_ADDR": "10.1.2.3"})
assert resp.status_code == 403
def test_post_zones_reset_restores_the_default_preset(client, tmp_path, monkeypatch):
import app as app_module
zones = _zones_file(tmp_path, {"truck_area": [[0, 0], [10, 0], [10, 10], [0, 10]],
"count_line": {"x_start": 1, "x_end": 2, "y": 3}})
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default/reset")
assert resp.status_code == 200
saved = json.loads(open(zones).read())
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
# --- fix round 1: route-level coverage for F1-F9 ---
def _route_preset(**overrides):
"""A valid preset in the native 1920x1080 zone space, with overrides applied."""
preset = {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
"reference_resolution": [1920, 1080],
}
preset.update(overrides)
return preset
def test_post_zones_rejects_a_foreign_reference_resolution(client, tmp_path, monkeypatch):
"""F1: a foreign preset resolution is rejected when sent as a preset; the file must not change."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
before = open(zones).read()
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default",
json={"preset": _route_preset(reference_resolution=[640, 480])})
assert resp.status_code == 400
assert "reference_resolution" in resp.get_json()["error"]
assert open(zones).read() == before
def test_post_zones_rejects_a_non_finite_count_line(client, tmp_path, monkeypatch):
"""F2: Infinity used to reach int() and raise OverflowError (500)."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
body = ('{"preset": {"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],'
' "count_line": {"x_start": 577, "x_end": 1401, "y": Infinity}}}')
resp = client.post("/api/zones/default", data=body, content_type="application/json")
assert resp.status_code == 400
assert "count_line" in resp.get_json()["error"]
def test_post_zones_rejects_a_fractional_count_line(client, tmp_path, monkeypatch):
"""F3: bounds were checked on the truncated int, the raw float was stored."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default",
json={"preset": _route_preset(count_line={"x_start": 577, "x_end": 1920.9, "y": 330})})
assert resp.status_code == 400
assert "count_line" in resp.get_json()["error"]
def test_post_zones_stores_an_integral_float_count_line_as_an_int(client, tmp_path, monkeypatch):
"""F3: 1920.0 is an integer in disguise and must be persisted as 1920."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default",
json={"preset": _route_preset(count_line={"x_start": 577, "x_end": 1920.0, "y": 330})})
assert resp.status_code == 200
x_end = json.loads(open(zones).read())["presets"]["default"]["count_line"]["x_end"]
assert x_end == 1920
assert isinstance(x_end, int)
def test_post_zones_rejects_a_three_point_truck_area(client, tmp_path, monkeypatch):
"""F4: build_static_roi needs 4 points; 3 would degrade the job to dynamic."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default",
json={"preset": _route_preset(truck_area=[[600, 385], [609, 1076], [1404, 1078]])})
assert resp.status_code == 400
assert "truck_area" in resp.get_json()["error"]
def test_get_zone_detail_without_a_zones_file_is_404(client, tmp_path, monkeypatch):
"""F6: a missing file is a missing preset, not a server error."""
import app as app_module
monkeypatch.setattr(app_module, "ZONES_PATH", str(tmp_path / "missing.json"))
resp = client.get("/api/zones/default")
assert resp.status_code == 404
assert "not found" in resp.get_json()["error"]
def test_get_zone_detail_with_a_corrupt_zones_file_is_500(client, tmp_path, monkeypatch):
"""F6: invalid JSON must answer with a message, not a traceback."""
import app as app_module
zones = tmp_path / "zones.json"
zones.write_text("{not json")
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.get("/api/zones/default")
assert resp.status_code == 500
assert "not valid JSON" in resp.get_json()["error"]
assert "Traceback" not in resp.get_data(as_text=True)
def test_get_zone_detail_with_a_non_object_zones_file_is_500(client, tmp_path, monkeypatch):
"""F6: a JSON array is not a zone config."""
import app as app_module
zones = tmp_path / "zones.json"
zones.write_text("[1, 2, 3]")
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.get("/api/zones/default")
assert resp.status_code == 500
assert "JSON object" in resp.get_json()["error"]
assert "Traceback" not in resp.get_data(as_text=True)
@pytest.mark.parametrize("route", ["/api/zones/default", "/api/zones/default/reset"])
@pytest.mark.parametrize("content,expect", [
("{not json", "not valid JSON"),
("[1, 2, 3]", "JSON object"),
])
def test_zone_write_routes_reject_an_unusable_zones_file(client, tmp_path, monkeypatch, route, content, expect):
"""F6: the write routes use the same guard as GET."""
import app as app_module
zones = tmp_path / "zones.json"
zones.write_text(content)
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.post(route, json={"preset": _route_preset()})
assert resp.status_code == 500
assert expect in resp.get_json()["error"]
assert "Traceback" not in resp.get_data(as_text=True)
def test_post_zones_with_a_malformed_body_is_400(client, tmp_path, monkeypatch):
"""F7: the message names the body, not a preset key."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default", data="{not json", content_type="application/json")
assert resp.status_code == 400
error = resp.get_json()["error"]
assert "body" in error.lower()
assert "truck_area" not in error
def test_post_zones_reset_drops_keys_that_are_not_in_the_default(client, tmp_path, monkeypatch):
"""F8: reset replaces the stored preset wholesale, siblings untouched."""
import app as app_module
zones = tmp_path / "zones.json"
with open(zones, "w") as f:
json.dump({"presets": {"default": {**_route_preset(), "custom_tuning": 7},
"other": _route_preset()},
"active_preset": "default"}, f)
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.post("/api/zones/default/reset")
assert resp.status_code == 200
saved = json.loads(open(zones).read())
assert "custom_tuning" not in saved["presets"]["default"]
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
assert saved["presets"]["other"] == _route_preset()
assert saved["active_preset"] == "default"
def test_post_zones_from_ipv4_mapped_loopback_is_200(client, tmp_path, monkeypatch):
"""F9: ::ffff:127.0.0.1 is loopback when the server listens on IPv6."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default", json={"preset": _route_preset()},
environ_base={"REMOTE_ADDR": "::ffff:127.0.0.1"})
assert resp.status_code == 200
def test_post_zones_without_a_zones_file_is_404_and_creates_nothing(client, tmp_path, monkeypatch):
"""F6: the write routes refuse to create a missing zones.json."""
import app as app_module
missing = tmp_path / "missing.json"
monkeypatch.setattr(app_module, "ZONES_PATH", str(missing))
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
assert resp.status_code == 404
assert not missing.exists()
def test_post_zones_reset_without_a_zones_file_is_404_and_creates_nothing(client, tmp_path, monkeypatch):
"""F6: reset refuses to create a missing zones.json either."""
import app as app_module
missing = tmp_path / "missing.json"
monkeypatch.setattr(app_module, "ZONES_PATH", str(missing))
resp = client.post("/api/zones/default/reset")
assert resp.status_code == 404
assert not missing.exists()
# --- fix round 2: R1 reference_resolution, R2/R3 file handling, R4 mode ---
def test_post_zones_injects_the_analysis_space_when_the_key_is_absent(client, tmp_path, monkeypatch):
"""R1: a preset without reference_resolution defaults to native [1920, 1080] and scales cleanly."""
import app as app_module
from src.zone_config import build_static_roi
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
preset = {k: v for k, v in _route_preset().items() if k != "reference_resolution"}
# A new preset name: merging over a stored preset would keep the stored key.
resp = client.post("/api/zones/fresh", json={"preset": preset})
assert resp.status_code == 200
stored = json.loads(open(zones).read())["presets"]["fresh"]
assert stored["reference_resolution"] == [1920, 1080]
roi = build_static_roi(stored, 1280, 720)
assert (roi.x1, roi.x2) == (400, 936)
def test_post_zones_with_a_non_object_presets_is_400(client, tmp_path, monkeypatch):
"""R2: {"presets": []} used to raise TypeError inside the save."""
import app as app_module
zones = tmp_path / "zones.json"
zones.write_text(json.dumps({"presets": [], "active_preset": "default"}))
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
assert resp.status_code == 400
assert "presets" in resp.get_json()["error"]
assert "Traceback" not in resp.get_data(as_text=True)
assert json.loads(zones.read_text()) == {"presets": [], "active_preset": "default"}
def test_post_zones_reset_with_a_non_object_presets_is_400(client, tmp_path, monkeypatch):
"""R2: the reset route maps the same ValueError to 400."""
import app as app_module
zones = tmp_path / "zones.json"
zones.write_text(json.dumps({"presets": [], "active_preset": "default"}))
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.post("/api/zones/default/reset")
assert resp.status_code == 400
assert "presets" in resp.get_json()["error"]
assert "Traceback" not in resp.get_data(as_text=True)
assert json.loads(zones.read_text()) == {"presets": [], "active_preset": "default"}
def test_post_zones_does_not_recreate_a_vanished_zones_file(client, tmp_path, monkeypatch):
"""R3: a file that vanishes between the check and the save is not recreated."""
import os
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
real_load = app_module.load_zone_config
def load_then_remove(path):
config = real_load(path)
os.remove(path)
return config
monkeypatch.setattr(app_module, "load_zone_config", load_then_remove)
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
assert resp.status_code == 404
assert "not found" in resp.get_json()["error"]
assert not os.path.exists(zones)
def test_post_zones_keeps_the_zones_file_mode(client, tmp_path, monkeypatch):
"""R4: mkstemp creates 0600; the file must not become owner-only."""
import os
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
os.chmod(zones, 0o644)
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
assert resp.status_code == 200
assert os.stat(zones).st_mode & 0o777 == 0o644
# --- Interactive zone editor (Task 5) ---
def test_calibrate_page_renders(client):
resp = client.get("/calibrate")
assert resp.status_code == 200
assert b"zoneOverlay" in resp.data
assert b"zone-json" in resp.data
def test_index_page_links_to_calibrator(client):
resp = client.get("/")
assert resp.status_code == 200
assert b'/calibrate' in resp.data
def test_api_frame_rejects_a_bad_filename(client, tmp_path, monkeypatch):
import app as app_module
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
assert client.get("/api/frame?video=../etc/passwd").status_code == 400
assert client.get("/api/frame?video=missing.mp4").status_code == 404
def test_api_frame_returns_a_1280x720_jpeg(client, tmp_path, monkeypatch):
import cv2
import numpy as np
import app as app_module
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
path = tmp_path / "clip.mp4"
writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 10, (1920, 1080))
for _ in range(5):
writer.write(np.zeros((1080, 1920, 3), dtype=np.uint8))
writer.release()
resp = client.get("/api/frame?video=clip.mp4&t=0")
assert resp.status_code == 200
assert resp.mimetype == "image/jpeg"
img = cv2.imdecode(np.frombuffer(resp.data, dtype=np.uint8), cv2.IMREAD_COLOR)
assert img.shape[:2] == (720, 1280)
def _write_clip(path):
import cv2
import numpy as np
writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 10, (1920, 1080))
for _ in range(5):
writer.write(np.zeros((1080, 1920, 3), dtype=np.uint8))
writer.release()
def test_api_frame_rejects_an_unusable_time(client, tmp_path, monkeypatch):
import app as app_module
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
_write_clip(tmp_path / "clip.mp4")
for bad in ("inf", "-inf", "nan", "1e999", "-1", "abc"):
resp = client.get(f"/api/frame?video=clip.mp4&t={bad}")
assert resp.status_code == 400, bad
assert resp.mimetype == "application/json"
assert resp.get_json() == {"error": "invalid t"}
def test_api_frame_error_does_not_leak_the_server_path(client, tmp_path, monkeypatch):
import app as app_module
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
(tmp_path / "broken.mp4").write_bytes(b"not a video")
resp = client.get("/api/frame?video=broken.mp4&t=0")
assert resp.status_code == 500
assert resp.mimetype == "application/json"
message = resp.get_json()["error"]
assert str(tmp_path) not in message
assert "broken.mp4" in message
def test_extract_frame_jpeg_rejects_an_unusable_time(tmp_path):
from src.preview import extract_frame_jpeg
clip = tmp_path / "clip.mp4"
_write_clip(clip)
for bad in (float("inf"), float("-inf"), float("nan"), -1.0):
with pytest.raises(ValueError):
extract_frame_jpeg(str(clip), bad)
def test_open_cv_calibrator_merges_geometry_and_keeps_tuning_keys():
import importlib.util
from pathlib import Path
spec = importlib.util.spec_from_file_location(
"calibrate_zone",
Path(__file__).resolve().parents[1] / "tools" / "calibrate_zone.py",
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
stored = {
"truck_area": [[1, 2], [3, 4], [5, 6], [7, 8]],
"counting_area": [[1, 2], [3, 4], [5, 6], [7, 8]],
"palet": [[9, 9], [8, 8], [7, 7], [6, 6]],
"count_line": {"x_start": 1, "x_end": 2, "y": 3},
"reference_resolution": [1280, 720],
"left_limit": 0.27578,
"min_valid_area": 15000,
}
config = {"active_preset": "default", "presets": {"default": dict(stored)}}
measured = {
"truck_area": [[10, 20], [30, 40], [50, 60], [70, 80]],
"counting_area": [[11, 21], [31, 41], [51, 61], [71, 81]],
"count_line": {"x_start": 100, "x_end": 200, "y": 150},
"reference_resolution": [1280, 720],
}
module.merge_preset(config, "default", measured)
preset = config["presets"]["default"]
# the measured geometry wins ...
assert preset["truck_area"] == measured["truck_area"]
assert preset["counting_area"] == measured["counting_area"]
assert preset["count_line"] == measured["count_line"]
assert preset["reference_resolution"] == [1280, 720]
# ... the tuning knobs survive
assert preset["palet"] == stored["palet"]
assert preset["left_limit"] == stored["left_limit"]
assert preset["min_valid_area"] == stored["min_valid_area"]
def test_post_zones_accepts_fcp_flat_1080p_json(client, tmp_path, monkeypatch):
"""POST /api/zones/<preset> accepts FCP's flat 1920x1080 zones.json format."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
fcp_flat = {
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"line_y": 215,
"line_x_start": 577,
"line_x_end": 1401,
}
resp = client.post("/api/zones/default", json=fcp_flat)
assert resp.status_code == 200
saved = json.loads(open(zones).read())["presets"]["default"]
assert saved["reference_resolution"] == [1920, 1080]
assert saved["truck_area"] == fcp_flat["truck"]
assert saved["counting_area"] == fcp_flat["counting"]
assert saved["palet"] == fcp_flat["palet"]
assert saved["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
def test_resolve_zone_auto_syncs_when_fcp_zones_updated(tmp_path, monkeypatch):
"""When FCP's zones.json is newer, app._resolve_zone refreshes preset 'default' first."""
import os
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
fcp_zones = tmp_path / "fcp_zones.json"
fcp_zones.write_text(json.dumps({
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"line_y": 215,
"line_x_start": 577,
"line_x_end": 1401,
}))
st = os.stat(zones)
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
monkeypatch.setenv("FCP_ZONES_PATH", str(fcp_zones))
mode, roi, preset, cpoly, tpoly = app_module._resolve_zone("fixed", "")
assert mode == "fixed"
assert preset == "default"
assert roi.line_y == 143
assert roi.line_x_start == 385
assert roi.line_x_end == 934
assert cpoly is not None and tpoly is not None
def test_cli_uses_zones_json_fixed_mode_by_default(tmp_path, monkeypatch):
"""CLI loads zones.json fixed areas by default (and auto-syncs FCP zones)."""
import os
import cli as cli_mod
from src.model_registry import ModelConfig
clip = tmp_path / "clip.mp4"
_write_clip(clip)
zones = _zones_file(tmp_path, _route_preset())
fcp_zones = tmp_path / "fcp_zones.json"
fcp_zones.write_text(json.dumps({
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"line_y": 215,
"line_x_start": 577,
"line_x_end": 1401,
}))
st = os.stat(zones)
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
monkeypatch.setenv("FCP_ZONES_PATH", str(fcp_zones))
model_cfg = ModelConfig(
filename="best.pt", path=str(tmp_path / "best.pt"),
stem="best", known_classes=["sack"],
)
monkeypatch.setattr(cli_mod, "scan_models", lambda d: [model_cfg])
seen = {}
class _Res:
output_path = str(tmp_path / "out.mp4")
frame_count = 5
loading_count = 0
unloading_count = 0
net_count = 0
batch_count = 0
duration_seconds = 0.1
def fake_run_pipeline(**kwargs):
seen.update(kwargs)
return _Res()
monkeypatch.setattr(cli_mod, "run_pipeline", fake_run_pipeline)
cli_mod.main([
"--video", str(clip),
"--model", "best.pt",
"--zones-path", zones,
"--output", str(tmp_path / "out.mp4"),
])
assert seen["fixed_zone"] is not None
assert seen["fixed_zone"].line_y == 143
assert seen["fixed_zone"].line_x_start == 385
assert seen["counting_polygon"] is not None
assert seen["truck_polygon"] is not None
assert seen["freeze_roi"] is False
def test_post_zones_scales_legacy_720p_preset_to_1080p(client, tmp_path, monkeypatch):
"""POST /api/zones/<preset> accepts legacy [1280, 720] presets and stores [1920, 1080]."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
legacy_preset = {
"truck_area": [[400, 194], [406, 718], [936, 718], [920, 194]],
"counting_area": [[382, 34], [390, 718], [946, 718], [932, 34]],
"count_line": {"x_start": 384, "x_end": 934, "y": 144},
"reference_resolution": [1280, 720],
}
resp = client.post("/api/zones/default", json={"preset": legacy_preset})
assert resp.status_code == 200
saved = json.loads(open(zones).read())["presets"]["default"]
assert saved["reference_resolution"] == [1920, 1080]
assert saved["count_line"] == {"x_start": 576, "x_end": 1401, "y": 216}
+5 -3
View File
@@ -72,13 +72,13 @@ def test_load_config_raises_on_invalid_value(tmp_path):
def test_partial_yaml_only_box_conf_merges(tmp_path):
"""Only detection.box_conf overrides; sack_conf stays at default 0.3."""
"""Only detection.box_conf overrides; sack_conf stays at default 0.35."""
p = tmp_path / "config.yaml"
p.write_text("detection:\n box_conf: 0.25\n", encoding="utf-8")
cfg = load_config(str(p))
assert cfg["detection"]["box_conf"] == 0.25
assert cfg["detection"]["sack_conf"] == 0.3
assert cfg["detection"]["sack_conf"] == 0.35
assert cfg["min_bbox_area"] == DEFAULTS["min_bbox_area"]
assert _section_keys(cfg) == _section_keys(DEFAULTS)
@@ -170,9 +170,11 @@ def test_truck_roi_tracker_accepts_sticky_iou():
def test_detection_thresholds_match_fcp():
cfg = load_config()
assert cfg["detection"]["sack_conf"] == 0.30
assert cfg["detection"]["sack_conf"] == 0.35
assert cfg["detection"]["box_conf"] == 0.35
assert cfg["detection"]["truck_conf"] == 0.45
assert cfg["iou"]["sack_nms"] == 0.45
assert cfg["iou"]["box_nms"] == 0.7
assert cfg["min_bbox_area"]["sack"] == 1500
assert cfg["min_bbox_area"]["box"] == 1000
assert cfg["min_bbox_area"]["truck"] == 5000
+175 -18
View File
@@ -1,44 +1,58 @@
"""Counting core tests — FCP counting-logic parity."""
from src.counting import LineCrossCounter
import copy
import pytest
from src.config import DEFAULTS, load_config
from src.counting import LineCrossCounter, MultiClassLineCounter
from src.interfaces import Detection
from src.validation import ValidationError, validate_config
def _det(tid: int, y1: int, cls: str = "sack") -> Detection:
"""Detection with top edge at y1, spanning the whole counting X span."""
return Detection(bbox=(100.0, float(y1), 200.0, float(y1 + 50)),
def _det(tid: int, y1: int, cls: str = "sack", cx: float = 150.0) -> Detection:
"""Detection with top edge at y1, centred on cx."""
return Detection(bbox=(cx - 50.0, float(y1), cx + 50.0, float(y1 + 50)),
confidence=0.9, class_id=0, class_name=cls, track_id=tid)
def test_unloading_requires_prior_loading():
"""Track first seen below the line never counts as unloading."""
c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000)
assert c.update([_det(7, 200)]) == [] # first seen below -> no event
assert c.update([_det(7, 10)]) == [] # now above -> still no unloading
assert c.update([_det(7, 130)]) == [] # first seen below -> no event
assert c.update([_det(7, 10)]) == [] # now above -> still no unloading
assert c.unloading_count == 0
assert c.loading_count == 0
def test_loading_then_unloading_counts_both():
"""Above -> below counts loading; below -> above then counts unloading."""
c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000)
c.update([_det(3, 10)])
events = c.update([_det(3, 200)])
def test_track_counted_at_most_once():
"""FCP single-direction lock: one track counts once overall, as loading.
A track that loads and then leaves the truck again is not counted twice —
the loading stays, the unloading never happens.
"""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280)
c.update([_det(1, 250)]) # first seen below -> initial zone "below"
c.update([_det(1, 140)]) # above
events = c.update([_det(1, 250)]) # below again -> loading
assert [e["direction"] for e in events] == ["loading"]
c.update([_det(1, 140)]) # above again (streak 1)
c.update([_det(1, 140)]) # streak 2
events = c.update([_det(1, 140)]) # streak 3 -> would be an unloading
assert events == []
assert c.loading_count == 1
events = c.update([_det(3, 10)])
assert [e["direction"] for e in events] == ["unloading"]
assert c.unloading_count == 1
assert c.unloading_count == 0
def test_reset_clears_loaded_tracks():
"""reset() clears the loaded-track registry (FCP src/counting.py:235)."""
c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000)
c.update([_det(1, 10)])
c.update([_det(1, 200)])
c.update([_det(1, 130)])
assert c._loaded_tracks == {1}
c.reset()
assert c._loaded_tracks == set()
c.update([_det(1, 200)])
c.update([_det(1, 130)])
assert c.update([_det(1, 10)]) == []
assert c.unloading_count == 0
@@ -47,7 +61,7 @@ def test_reset_state_keeps_totals_but_clears_track_state():
"""reset_state() clears dedup state but keeps the clip totals."""
c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000)
c.update([_det(4, 10)])
c.update([_det(4, 200)])
c.update([_det(4, 130)])
assert c.loading_count == 1
c.reset_state()
assert c.loading_count == 1 # totals survive
@@ -55,4 +69,147 @@ def test_reset_state_keeps_totals_but_clears_track_state():
assert c._loaded_tracks == set() # per-track state cleared
# the same track may cross again in the next batch
assert [e["direction"] for e in c.update([_det(4, 10)])] == []
assert [e["direction"] for e in c.update([_det(4, 200)])] == ["loading"]
assert [e["direction"] for e in c.update([_det(4, 130)])] == ["loading"]
# ── FCP counting gates (karung_counter_semarang, main, src/counting.py) ───
def test_constructor_defaults_match_fcp_config():
"""Defaults mirror FCP's runtime config values (config_loader.py CountingConfig)."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280)
assert c._capture_below == 100.0
assert c._max_step_dy == 160.0
assert c._max_gap_frames == 15
assert c._unload_confirm_frames == 1
def test_corridor_below_capture_below_never_counts():
"""A sack deep in the truck bed never triggers a loading count."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
capture_below=100)
c.update([_det(1, 100)]) # above the line
events = c.update([_det(1, 400)]) # 180 px below -> beyond the corridor
assert events == []
assert c.loading_count == 0
def test_corridor_keeps_initial_zone():
"""FCP parity: the corridor filter preserves the initial zone."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
capture_below=100)
c.update([_det(1, 100)]) # above -> initial zone "above"
assert c._initial_zone[1] == "above"
c.update([_det(1, 400)]) # deep in the bed -> corridor filter
assert c._initial_zone[1] == "above"
events = c.update([_det(1, 250)]) # back in corridor -> still no loading (_has_been_above cleared)
assert events == []
assert c.loading_count == 0
def test_id_switch_large_dy_resets_history():
"""A vertical jump (ID switch) drops the track history, so no loading."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
max_step_dy=120)
c.update([_det(1, 100)]) # above
c.update([_det(1, 300)]) # 200 px jump -> history reset
events = c.update([_det(1, 300)])
assert events == []
assert c.loading_count == 0
def test_stale_gap_resets_history():
"""A track that vanished longer than max_gap_frames loses its history."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
max_step_dy=0, max_gap_frames=2)
c.update([_det(1, 100)]) # above
c.update([]) # missing
c.update([]) # missing
events = c.update([_det(1, 300)]) # reappears below after the gap
assert events == []
assert c.loading_count == 0
def test_unload_confirm_frames_requires_consecutive_above_frames():
"""The unload gate counts consecutive "above" frames only.
The streak is the gate's input: it grows while the track stays above the
line and resets on every other frame. FCP's unloading branch also needs
an empty direction set, which a counted track cannot have, so no
unloading is published either way.
"""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
unload_confirm_frames=3)
c.update([_det(1, 250)]) # below the line
c.update([_det(1, 140)]) # above: streak 1
c.update([_det(1, 140)]) # above: streak 2
assert c._above_streak[1] == 2
c.update([_det(1, 250)]) # back below: streak reset
assert c._above_streak[1] == 0
c.update([_det(1, 140)]) # streak 1
c.update([_det(1, 140)]) # streak 2
c.update([_det(1, 140)]) # streak 3 -> confirm threshold reached
assert c._above_streak[1] == 3
assert c.unloading_count == 0
def test_same_direction_dx_dedup():
"""Two tracks crossing at nearly the same x count once (same direction)."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280)
c.update([_det(1, 140, cx=600.0)])
events = c.update([_det(1, 250, cx=600.0)])
assert [e["direction"] for e in events] == ["loading"]
c.update([_det(2, 140, cx=610.0)])
c.update([_det(2, 200, cx=610.0)])
events = c.update([_det(2, 300, cx=610.0)]) # 10 px sideways, 50 px lower
assert events == []
assert c.loading_count == 1
def test_update_line_keeps_existing_track_history():
"""update_line changes the geometry only — per-track history survives."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280)
c.update([_det(1, 140)]) # above the old line
c.update_line(500, 0, 1280) # new line, far below
c.update([_det(1, 250)]) # still above the new line
c.update([_det(1, 370)])
c.update([_det(1, 490)]) # in the band of the new line
events = c.update([_det(1, 550)]) # below the new line
assert len(events) == 1
assert events[0]["direction"] == "loading"
def test_multiclass_forwards_gates_and_update_line():
"""Both class counters get the same gates and the same line geometry."""
c = MultiClassLineCounter(line_y=220, line_x_start=0, line_x_end=1280,
capture_below=100.0, max_step_dy=160.0,
max_gap_frames=15, unload_confirm_frames=1)
for counter in (c._sack, c._box):
assert counter._capture_below == 100.0
assert counter._max_step_dy == 160.0
assert counter._max_gap_frames == 15
assert counter._unload_confirm_frames == 1
c.update_line(500, 10, 1200)
assert c._sack.line_y == 500 and c._box.line_y == 500
assert c._sack.line_x_start == 10 and c._box.line_x_end == 1200
# ── counting config section ───────────────────────────────────────────
def test_counting_config_section_matches_fcp_values():
"""config.yaml + DEFAULTS carry the four counting gates (FCP runtime values)."""
cfg = load_config()
counting = cfg["counting"]
assert counting["capture_below_px"] == 100
assert counting["max_step_dy_px"] == 160
assert counting["max_gap_frames"] == 15
assert counting["unload_confirm_frames"] == 1
assert DEFAULTS["counting"] == counting
def test_validate_config_rejects_negative_counting_value():
cfg = copy.deepcopy(DEFAULTS)
cfg["counting"]["capture_below_px"] = -1
with pytest.raises(ValidationError):
validate_config(cfg)
+578 -3
View File
@@ -5,6 +5,7 @@ import os
import cv2
import numpy as np
import pytest
from shapely.geometry import Polygon
from src.counting import MultiClassLineCounter
from src.pipeline import apply_class_filter, run_pipeline, PipelineResult
from src.interfaces import Detection
@@ -243,7 +244,7 @@ def test_merged_pipeline_result_box_fields():
class _FakeCounter:
"""Stands in for MultiClassLineCounter with fixed counts."""
def __init__(self, line_y=0, line_x_start=0, line_x_end=0, margin=0):
def __init__(self, line_y=0, line_x_start=0, line_x_end=0, margin=0, **kwargs):
self.line_y = line_y
self.line_x_start = line_x_start
self.line_x_end = line_x_end
@@ -1396,12 +1397,14 @@ def _patch_real_counter(monkeypatch, pipe_mod):
return counters
# A sack that crosses the count line (y=360 in the 1280x720 analysis frame).
# The y1 jump stays inside the FCP gates: <= max_step_dy (160 px) per frame and
# below the corridor bound (line_y + capture_below = 460 px).
SACK_ABOVE = Detection(
bbox=(600.0, 200.0, 640.0, 240.0), confidence=0.9, class_id=0,
bbox=(600.0, 280.0, 640.0, 320.0), confidence=0.9, class_id=0,
class_name="sack", track_id=1,
)
SACK_BELOW = Detection(
bbox=(600.0, 500.0, 640.0, 540.0), confidence=0.9, class_id=0,
bbox=(600.0, 400.0, 640.0, 440.0), confidence=0.9, class_id=0,
class_name="sack", track_id=1,
)
@@ -1656,3 +1659,575 @@ def test_the_merged_runner_keeps_overlapping_sacks_of_one_model(tmp_path, monkey
)
assert {d.bbox for d in counter.seen} == {_OVERLAP_A.bbox, _OVERLAP_B.bbox}
# ── Zone polygons in the annotated output ───────────────────────────────
def test_dashboard_draws_zone_polygons():
"""The overlay draws the calibrated polygons, not just the ROI box."""
from src.dashboard import DashboardOverlay
counting = Polygon([(383, 33), (391, 718), (945, 717), (931, 33)])
truck = Polygon([(400, 257), (406, 717), (936, 719), (921, 229)])
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
out = DashboardOverlay().draw(
frame, [], None, 0, 0, None, None,
counting_polygon=counting, truck_polygon=truck,
)
assert out.shape == frame.shape
# A pixel on the truck polygon edge must be lit in the truck colour.
assert out[257, 400].tolist() == [0, 165, 255]
# Same for the counting polygon edge.
assert out[33, 383].tolist() == [235, 99, 37]
def test_dashboard_count_band_spans_calibrated_window():
"""The count band follows roi.line_x_start/line_x_end, not the ROI bounds."""
from src.dashboard import DashboardOverlay
from src.truck_roi import TruckROI
# ROI bounds are wide; the calibrated count window is a narrow slice
# inside them — the counter only counts in that slice.
roi = TruckROI(
x1=100, y1=100, x2=1000, y2=600, line_y=300, confidence=1.0,
fixed=False, line_x_start=400, line_x_end=800,
)
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
out = DashboardOverlay().draw(
frame, [], roi, 0, 0, None, None,
)
# Inside the calibrated window → magenta band.
assert out[310, 500].tolist() == [38, 0, 38]
# Inside the ROI bounds but outside the calibrated window → no band.
assert out[310, 200].tolist() == [0, 0, 0]
assert out[310, 900].tolist() == [0, 0, 0]
def test_dashboard_draws_no_band_for_inverted_calibrated_window():
"""An inverted calibrated window counts nothing, so no band is drawn."""
from src.dashboard import DashboardOverlay
from src.truck_roi import TruckROI
roi = TruckROI(
x1=100, y1=100, x2=1000, y2=600, line_y=300, confidence=1.0,
fixed=False, line_x_start=800, line_x_end=400,
)
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
out = DashboardOverlay().draw(
frame, [], roi, 0, 0, None, None,
)
# No band anywhere — not over the ROI bounds either.
assert out[310, 200].tolist() == [0, 0, 0]
assert out[310, 500].tolist() == [0, 0, 0]
def test_dashboard_draws_polygons_behind_detection_boxes():
"""Polygons go down first, so the detection boxes stay readable."""
from src.dashboard import DashboardOverlay
# A polygon edge that runs right along a detection box edge.
counting = Polygon([(383, 33), (383, 200), (500, 200), (500, 33)])
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
det = Detection(
bbox=(383, 33, 500, 200), confidence=0.9, class_id=0, class_name="sack",
)
out = DashboardOverlay().draw(
frame, [det], None, 0, 0, None, None, counting_polygon=counting,
)
# The box edge (green top line) sits on top of the polygon edge.
assert out[33, 400].tolist() == [0, 200, 0]
def test_pipeline_forwards_zone_polygons_to_dashboard(tmp_path, monkeypatch):
"""run_pipeline hands the zone polygons to the dashboard overlay."""
from src import pipeline as pipe_mod
_patch_pipeline_fakes(monkeypatch)
seen: list[dict] = []
class _RecordingDashboard:
def draw(self, frame, **kwargs):
seen.append(kwargs)
return frame
monkeypatch.setattr(pipe_mod, "DashboardOverlay", _RecordingDashboard)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path)
counting = Polygon([(383, 33), (391, 718), (945, 717), (931, 33)])
truck = Polygon([(400, 257), (406, 717), (936, 719), (921, 229)])
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
counting_polygon=counting,
truck_polygon=truck,
)
assert seen, "dashboard.draw() was never called"
assert all(call["counting_polygon"] is counting for call in seen)
assert all(call["truck_polygon"] is truck for call in seen)
# ── FCP full pipeline parity (pre-stabilizer filter, suppression, Mode D) ──
def test_truck_detection_centroid_picks_largest_valid_truck():
"""FCP picks the largest valid truck inside the counting polygon (predict.py:1088-1093)."""
from src.pipeline import truck_detection_centroid
poly = _fcp_polygon()
small = Detection(
bbox=(600.0, 100.0, 700.0, 200.0), confidence=0.95, class_id=2,
class_name="truck", track_id=1,
) # area 10_000, centroid (650, 150)
large = Detection(
bbox=(700.0, 200.0, 900.0, 400.0), confidence=0.70, class_id=2,
class_name="truck", track_id=2,
) # area 40_000, centroid (800, 300)
assert truck_detection_centroid([small, large], poly) == (800.0, 300.0)
# Equal-area tie-breaker picks higher confidence
eq_low = Detection(
bbox=(600.0, 100.0, 700.0, 200.0), confidence=0.60, class_id=2,
class_name="truck", track_id=3,
)
eq_high = Detection(
bbox=(700.0, 100.0, 800.0, 200.0), confidence=0.90, class_id=2,
class_name="truck", track_id=4,
)
assert truck_detection_centroid([eq_low, eq_high], poly) == (750.0, 150.0)
def test_subthreshold_box_does_not_suppress_valid_sack(tmp_path, monkeypatch):
"""Boxes below box_conf or min_bbox_area.box are dropped before suppression."""
from src import pipeline as pipe_mod
low_conf_box = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.31, class_id=1,
class_name="box", track_id=2,
)
valid_sack_a = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.90, class_id=0,
class_name="sack", track_id=1,
)
tiny_box = Detection(
bbox=(700.0, 290.0, 720.0, 330.0), confidence=0.90, class_id=1,
class_name="box", track_id=4,
) # area 800 < 1000
valid_sack_b = Detection(
bbox=(700.0, 290.0, 740.0, 330.0), confidence=0.90, class_id=0,
class_name="sack", track_id=3,
) # area 1600 >= 1500, IoU with tiny_box = 0.50
counter, _batch = _patch_counting_fakes(
monkeypatch, [valid_sack_a, low_conf_box, valid_sack_b, tiny_box]
)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert {d.track_id for d in counter.seen} == {1, 3}
def test_occluded_sack_held_by_stabilizer_survives_confidence_decay(tmp_path, monkeypatch):
"""Conf filtering runs before BboxStabilizer so 0.85x decay does not drop held sacks."""
from src import pipeline as pipe_mod
borderline_sack = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.36, class_id=0,
class_name="sack", track_id=1,
) # >= 0.35 on frame 1; held frame 2 decays to 0.306 < 0.35
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
_patch_pipeline_fakes(monkeypatch)
_patch_tracker(monkeypatch, pipe_mod, [[borderline_sack], []])
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack"],
),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert len(counter.calls_seen) == 2
assert [d.track_id for d in counter.calls_seen[0]] == [1]
assert [d.track_id for d in counter.calls_seen[1]] == [1]
def test_merged_pipeline_selects_first_sack_model_as_primary_and_runs_dedicated_box_tracker(
tmp_path, monkeypatch
):
"""Mode D (truck, sack, box) runs ByteTrack on sack (iou=0.45) and box (iou=0.7) every frame."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
created_trackers: list[dict] = []
class _ModeFakeTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
self.calls = 0
created_trackers.append({"path": self.path, "conf": conf, "kwargs": kwargs, "inst": self})
def update(self, frame, dets):
self.calls += 1
if "best.pt" in self.path:
return [
Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9,
class_id=0, class_name="sack", track_id=10,
)
]
if "yolo11n" in self.path:
return [
Detection(
bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9,
class_id=1, class_name="box", track_id=20,
)
]
return []
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeFakeTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
filters = {
"v4-best": ["truck"],
"best": ["sack"],
"yolo11n": ["box"],
}
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters=filters,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(created_trackers) == 2
assert created_trackers[0]["path"].endswith("best.pt")
assert created_trackers[0]["kwargs"].get("iou") == 0.45
assert created_trackers[0]["inst"].calls == 2
assert created_trackers[1]["path"].endswith("yolo11n.pt")
assert created_trackers[1]["kwargs"].get("iou") == 0.7
assert created_trackers[1]["inst"].calls == 2
# Frame 1 (despite sup_det_interval=5) receives both tracked sack and tracked box
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 10), ("box", 20)}
def test_merged_pipeline_mode_c_does_not_share_yolo_between_tracker_and_truck_det(
tmp_path, monkeypatch
):
"""Mode C extracts trucks from primary tracker rather than sharing YOLO with BaseDetector."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
from src.truck_roi import TruckROI
_patch_pipeline_fakes(monkeypatch)
base_detector_paths: list[str] = []
class _RecordingDetector:
def __init__(self, model, conf=0.0, class_filter=None):
base_detector_paths.append(getattr(model, "ckpt_path", ""))
def detect(self, frame):
return []
truck_det = Detection(
bbox=(600.0, 100.0, 800.0, 300.0), confidence=0.8,
class_id=2, class_name="truck", track_id=99,
)
sack_det = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9,
class_id=0, class_name="sack", track_id=10,
)
box_det = Detection(
bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9,
class_id=1, class_name="box", track_id=20,
)
class _ModeCTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
def update(self, frame, dets):
if "v4-best" in self.path:
return [truck_det, sack_det]
if "yolo11n" in self.path:
return [box_det]
return []
batch = _IdleBatch()
counter = _RecordingCounter()
monkeypatch.setattr(pipe_mod, "BaseDetector", _RecordingDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeCTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=5)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters={"v4-best": ["truck", "sack"], "yolo11n": ["box"]},
fixed_zone=TruckROI(x1=400, y1=150, x2=950, y2=720, line_y=182, confidence=1.0, fixed=True),
counting_polygon=_fcp_polygon(),
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert not any("v4-best" in p for p in base_detector_paths)
assert batch.truck_calls[0] == (True, (700.0, 200.0))
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 10), ("box", 20)}
def test_merged_pipeline_mode_b_uses_single_sack_box_tracker_and_separate_truck_det(
tmp_path, monkeypatch
):
"""Mode B runs one ByteTrackTracker on yolo11n (sack+box) and separate truck_det on v4-best."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
created_trackers: list[dict] = []
detector_filters: list[tuple] = []
class _ModeBDetector:
def __init__(self, model, conf=0.0, class_filter=None):
detector_filters.append((getattr(model, "ckpt_path", ""), class_filter))
def detect(self, frame):
return []
class _ModeBTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
created_trackers.append({"path": self.path, "conf": conf, "kwargs": kwargs})
def update(self, frame, dets):
return [
Detection(bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9, class_id=0, class_name="sack", track_id=1),
Detection(bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9, class_id=1, class_name="box", track_id=2),
]
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "BaseDetector", _ModeBDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeBTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters={"v4-best": ["truck"], "yolo11n": ["sack", "box"]},
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(created_trackers) == 1
assert created_trackers[0]["path"].endswith("yolo11n.pt")
assert created_trackers[0]["kwargs"].get("iou") == 0.45
assert any("v4-best" in p and cf == ("truck",) for p, cf in detector_filters)
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 1), ("box", 2)}
def test_merged_pipeline_deduplicates_extra_boxes_against_box_tracker(tmp_path, monkeypatch):
"""Extra supplementary model boxes overlapping box_tracker must not double-count."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
class _ExtraDetector:
def __init__(self, model, conf=0.0, class_filter=None):
self.path = getattr(model, "ckpt_path", "")
def detect(self, frame):
if "unified" in self.path:
return [
Detection(
bbox=(705.0, 292.0, 765.0, 352.0), confidence=0.85,
class_id=1, class_name="box", track_id=None,
)
]
return []
class _DualTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
def update(self, frame, dets):
if "best.pt" in self.path:
return [Detection(bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9, class_id=0, class_name="sack", track_id=10)]
if "yolo11n" in self.path:
return [Detection(bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9, class_id=1, class_name="box", track_id=20)]
return []
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "BaseDetector", _ExtraDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _DualTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=5)
cfgs = [
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["box"]),
ModelConfig(filename="unified.pt", path=str(tmp_path / "unified.pt"), stem="unified", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
frame5_boxes = [d for d in counter.calls_seen[4] if d.class_name == "box"]
assert [d.track_id for d in frame5_boxes] == [20]
def test_merged_pipeline_batch_start_resets_box_stabilizer(tmp_path, monkeypatch):
"""on_batch_start resets both primary stabilizer and dedicated box_stabilizer."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
stabilizers: list = []
class _TrackingStabilizer(_RecordingStabilizer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
stabilizers.append(self)
batch = _BatchStartFiringBatch()
counter = _RecordingCounter()
monkeypatch.setattr(pipe_mod, "BboxStabilizer", _TrackingStabilizer)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
cfgs = [
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(stabilizers) == 2
assert all(s.reset_calls == 1 for s in stabilizers)
def test_box_outside_roi_x_but_inside_counting_polygon_still_suppresses_sack(tmp_path, monkeypatch):
"""Cross-class suppression runs before roi.contains_x (FCP predict.py:1137->1227)."""
from src import pipeline as pipe_mod
from src.truck_roi import TruckROI
edge_box = Detection(
bbox=(355.0, 290.0, 425.0, 350.0), confidence=0.90, class_id=1,
class_name="box", track_id=2,
) # cx=390 (inside counting_poly, left of roi.x1=400)
mislabeled_sack = Detection(
bbox=(375.0, 290.0, 445.0, 350.0), confidence=0.90, class_id=0,
class_name="sack", track_id=1,
) # cx=410 (inside roi.x1=400), IoU = 50/90 = 0.556 >= 0.4
counter, _batch = _patch_counting_fakes(monkeypatch, [edge_box, mislabeled_sack])
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
poly = Polygon([(300, 100), (300, 700), (950, 700), (950, 100)])
fixed = TruckROI(x1=400, y1=200, x2=900, y2=700, line_y=220, confidence=1.0, fixed=True)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
fixed_zone=fixed,
counting_polygon=poly,
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert counter.seen == []
+8
View File
@@ -131,3 +131,11 @@ def test_two_sacks_unaffected():
def test_empty_input():
assert _suppress_sacks_under_boxes([]) == []
def test_overlapping_sack_at_exact_threshold_dropped():
"""IoU == threshold drops sack (>= parity with FCP); threshold <= 0 disables."""
box = det((0, 0, 100, 100), class_name="box")
sack = det((0, 0, 50, 100), class_name="sack") # IoU = 5000 / 10000 = 0.5 exact
assert [d.class_name for d in _suppress_sacks_under_boxes([box, sack], iou_threshold=0.5)] == ["box"]
assert _suppress_sacks_under_boxes([box, sack], iou_threshold=0.0) == [box, sack]
+467 -13
View File
@@ -3,11 +3,17 @@ import os
import pytest
from shapely.geometry import Point
from src.zone_config import (
DEFAULT_ZONES,
build_counting_polygon,
build_static_roi,
build_truck_polygon,
list_zone_presets,
load_zone_config,
normalize_zone_preset,
resolve_zone,
save_zone_preset,
sync_fcp_zones,
validate_zone_preset,
)
# FCP's detection_poly_pts at reference resolution (predict.py:692-697).
@@ -89,15 +95,15 @@ def _polygon_coords(poly):
def test_build_counting_polygon_matches_fcp_reference_polygon():
"""Scaled to 1280x720 the polygon equals FCP's hardcoded detection_polygon.
"""Scaled to 1280x720 the polygon equals FCP's detection_polygon.
FCP predict.py:688-698 scales 1920x1080 points by 1280/1920 and
720/1080 and truncates with int().
FCP main predict.py:761-769 scales 1920x1080 points by 1280/1920 and
720/1080 and rounds with int(round(...)).
"""
zone = {"counting_area": FCP_COUNTING_AREA, "reference_resolution": [1920, 1080]}
poly = build_counting_polygon(zone, 1280, 720)
assert _polygon_coords(poly) == [
(382, 33), (390, 718), (945, 717), (931, 33), (382, 33),
(383, 33), (391, 718), (945, 717), (931, 33), (383, 33),
]
@@ -105,7 +111,7 @@ def test_build_counting_polygon_defaults_to_1920x1080_reference():
"""A zone without reference_resolution uses FCP's 1920x1080 default."""
poly = build_counting_polygon({"counting_area": FCP_COUNTING_AREA}, 1280, 720)
assert _polygon_coords(poly) == [
(382, 33), (390, 718), (945, 717), (931, 33), (382, 33),
(383, 33), (391, 718), (945, 717), (931, 33), (383, 33),
]
@@ -151,14 +157,14 @@ FCP_TRUCK_AREA = [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
def test_build_truck_polygon_matches_fcp_reference_polygon():
"""The truck polygon is FCP's, scaled to the analysis frame."""
"""The truck polygon is FCP's, scaled to the analysis frame with int(round(...))."""
poly = build_truck_polygon(
{"truck_area": FCP_TRUCK_AREA, "reference_resolution": [1920, 1080]},
1280,
720,
)
assert list(poly.exterior.coords) == [
(400.0, 256.0), (406.0, 717.0), (936.0, 718.0), (920.0, 228.0), (400.0, 256.0)
(400.0, 257.0), (406.0, 717.0), (936.0, 719.0), (921.0, 229.0), (400.0, 257.0)
]
@@ -175,7 +181,7 @@ def test_build_truck_polygon_at_reference_resolution_is_unscaled():
def test_build_truck_polygon_defaults_to_1920x1080_reference():
poly = build_truck_polygon({"truck_area": FCP_TRUCK_AREA}, 1280, 720)
assert list(poly.exterior.coords)[0] == (400.0, 256.0)
assert list(poly.exterior.coords)[0] == (400.0, 257.0)
def test_build_counting_polygon_none_on_a_degenerate_polygon():
@@ -275,8 +281,8 @@ def test_build_counting_polygon_none_on_non_finite_coordinates():
def test_build_static_roi_carries_the_count_line_x_window():
"""The ROI carries FCP's calibrated count-line x-window.
FCP predict.py:701-703 scales the count line to the 1280x720 analysis
frame: x 384...934, y 220.
FCP main predict.py:781-783 scales the count line to the 1280x720 analysis
frame with int(round(...)): x 385...934, y 220.
"""
zone = {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
@@ -284,9 +290,9 @@ def test_build_static_roi_carries_the_count_line_x_window():
"reference_resolution": [1920, 1080],
}
roi = build_static_roi(zone, video_w=1280, video_h=720)
assert roi.line_x_start == 384 # int(577 * 1280 / 1920)
assert roi.line_x_end == 934 # int(1401 * 1280 / 1920)
assert roi.line_y == 220 # int(330 * 720 / 1080)
assert roi.line_x_start == 385 # int(round(577 * 1280 / 1920))
assert roi.line_x_end == 934 # int(round(1401 * 1280 / 1920))
assert roi.line_y == 220 # int(round(330 * 720 / 1080))
def test_build_static_roi_without_count_line_has_no_x_window():
@@ -298,3 +304,451 @@ def test_build_static_roi_without_count_line_has_no_x_window():
)
assert roi.line_x_start is None
assert roi.line_x_end is None
# ── Shipped preset (FCP main calibration in native 1920x1080 space) ──────
def test_shipped_default_preset_matches_fcp_live_calibration():
"""The default preset is FCP main (91d8b48) in 1920x1080, scaled to 1280x720 at runtime."""
zone = {
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 215},
"reference_resolution": [1920, 1080],
}
roi = build_static_roi(zone, video_w=1280, video_h=720)
assert (roi.x1, roi.y1, roi.x2, roi.y2) == (400, 193, 936, 719)
assert roi.line_y == 143
assert roi.line_x_start == 385
assert roi.line_x_end == 934
assert roi.confidence == 1.0
assert roi.fixed is True
def test_shipped_default_preset_polygons_are_usable():
"""Both shipped polygons are valid and scaled accurately to 1280x720."""
zone = {
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"reference_resolution": [1920, 1080],
}
counting = build_counting_polygon(zone, 1280, 720)
truck = build_truck_polygon(zone, 1280, 720)
assert counting is not None and counting.area > 0
assert truck is not None and truck.area > 0
assert _polygon_coords(counting) == [(383, 33), (391, 718), (945, 717), (931, 33), (383, 33)]
assert _polygon_coords(truck) == [(400, 193), (406, 717), (936, 719), (921, 193), (400, 193)]
assert counting.contains(Point(600, 300))
GOOD_PRESET = {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
"reference_resolution": [1920, 1080],
}
def test_validate_zone_preset_accepts_good_geometry():
assert validate_zone_preset(GOOD_PRESET) == GOOD_PRESET
def test_validate_zone_preset_rejects_degenerate_polygon():
bad = {**GOOD_PRESET, "truck_area": [[600, 385], [600, 385], [600, 385], [600, 385]]}
with pytest.raises(ValueError, match="truck_area"):
validate_zone_preset(bad)
def test_validate_zone_preset_rejects_out_of_bounds_point():
bad = {**GOOD_PRESET, "counting_area": [[574, 50], [586, 1077], [1418, 1076], [1950, 50]]}
with pytest.raises(ValueError, match="counting_area"):
validate_zone_preset(bad)
def test_validate_zone_preset_rejects_inverted_count_line():
bad = {**GOOD_PRESET, "count_line": {"x_start": 1401, "x_end": 577, "y": 330}}
with pytest.raises(ValueError, match="count_line"):
validate_zone_preset(bad)
def test_save_zone_preset_preserves_siblings_and_active_preset(tmp_path):
path = str(tmp_path / "zones.json")
cfg = {"presets": {"other": {"count_line": {"x_start": 1, "x_end": 2, "y": 3}}},
"active_preset": "other"}
with open(path, "w") as f:
json.dump(cfg, f)
save_zone_preset(path, "default", GOOD_PRESET)
saved = json.load(open(path))
assert saved["presets"]["other"]["count_line"] == {"x_start": 1, "x_end": 2, "y": 3}
assert saved["active_preset"] == "other"
assert saved["presets"]["default"]["truck_area"] == GOOD_PRESET["truck_area"]
assert os.path.isfile(path + ".bak")
def test_save_zone_preset_keeps_knob_keys_of_the_edited_preset(tmp_path):
path = str(tmp_path / "zones.json")
cfg = {"presets": {"default": {**GOOD_PRESET, "duplicate_circle_radius": 30}},
"active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
save_zone_preset(path, "default", {"truck_area": [[1, 1], [10, 1], [10, 10], [1, 10]]})
saved = json.load(open(path))
assert saved["presets"]["default"]["duplicate_circle_radius"] == 30
def test_repo_zones_json_ships_the_fcp_calibrations():
"""Guards the shipped file, not an inline fixture."""
repo_zones = os.path.join(os.path.dirname(os.path.dirname(__file__)), "zones.json")
cfg = load_zone_config(repo_zones)
assert cfg["active_preset"] == "default"
live = cfg["presets"]["default"]
assert live["reference_resolution"] == [1920, 1080]
assert live["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
assert live["truck_area"] == [[600, 290], [609, 1076], [1404, 1078], [1381, 290]]
assert live["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
assert live["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
assert DEFAULT_ZONES["default"]["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
roi = build_static_roi(live, 1280, 720)
assert (roi.x1, roi.y1, roi.x2, roi.y2) == (400, 193, 936, 719)
assert (roi.line_x_start, roi.line_x_end, roi.line_y) == (385, 934, 143)
legacy = cfg["presets"]["fcp-2026-10-15"]
assert legacy["reference_resolution"] == [1920, 1080]
assert legacy["count_line"] == {"x_start": 577, "x_end": 1401, "y": 330}
assert legacy["truck_area"] == [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
assert legacy["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
assert legacy["palet"] == [[612, 628], [1454, 630], [1458, 1074], [608, 1071]]
assert DEFAULT_ZONES["fcp-2026-10-15"]["palet"] == [[612, 628], [1454, 630], [1458, 1074], [608, 1071]]
# --- fix round 1: F1 reference_resolution, F2/F3 count_line, F4 truck_area ---
def test_validate_zone_preset_rejects_a_foreign_reference_resolution():
"""F1: raw validate_zone_preset rejects un-normalized non-1080p presets."""
bad = {**GOOD_PRESET, "reference_resolution": [1280, 720]}
with pytest.raises(ValueError, match="reference_resolution"):
validate_zone_preset(bad)
def test_validate_zone_preset_accepts_a_preset_without_reference_resolution():
"""F1: the key is optional; 1920x1080 is the native zone space."""
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
assert validate_zone_preset(preset) is not None
def test_validate_zone_preset_rejects_a_non_finite_count_line():
"""F2: int(float('inf')) raises OverflowError, which used to 500."""
bad = {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1401, "y": float("inf")}}
with pytest.raises(ValueError, match="count_line"):
validate_zone_preset(bad)
def test_validate_zone_preset_rejects_a_fractional_count_line():
"""F3: bounds were checked on the truncated int, the raw float was stored."""
bad = {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.9, "y": 330}}
with pytest.raises(ValueError, match="count_line"):
validate_zone_preset(bad)
def test_validate_zone_preset_normalizes_an_integral_float_count_line():
"""F3: 1920.0 is an integer in disguise and is stored as 1920."""
out = validate_zone_preset({**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.0, "y": 330.0}})
assert out["count_line"] == {"x_start": 577, "x_end": 1920, "y": 330}
assert all(isinstance(v, int) for v in out["count_line"].values())
def test_validate_zone_preset_requires_four_truck_area_points():
"""F4: build_static_roi needs 4 points; 3 would silently degrade the job."""
bad = {**GOOD_PRESET, "truck_area": [[600, 385], [609, 1076], [1404, 1078]]}
with pytest.raises(ValueError, match="truck_area"):
validate_zone_preset(bad)
def test_save_zone_preset_persists_the_normalized_preset(tmp_path):
"""F3: the normalized count_line must reach the file."""
path = str(tmp_path / "zones.json")
cfg = {"presets": {"default": GOOD_PRESET}, "active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
save_zone_preset(path, "default", {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.0, "y": 330.0}})
saved = json.load(open(path))
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1920, "y": 330}
# 1920.0 == 1920 in Python, so the type is the real assertion here
assert all(isinstance(v, int) for v in saved["presets"]["default"]["count_line"].values())
def test_save_zone_preset_with_replace_drops_stored_keys(tmp_path):
"""F8: replace=True swaps the stored preset wholesale."""
path = str(tmp_path / "zones.json")
cfg = {"presets": {"default": {**GOOD_PRESET, "duplicate_circle_radius": 30}},
"active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
save_zone_preset(path, "default", GOOD_PRESET, replace=True)
saved = json.load(open(path))
assert "duplicate_circle_radius" not in saved["presets"]["default"]
assert saved["active_preset"] == "default"
def test_save_zone_preset_uses_a_unique_temp_file(tmp_path):
"""F5: concurrent posts must not share one temp path."""
import src.zone_config as zc
path = str(tmp_path / "zones.json")
cfg = {"presets": {}, "active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
seen = []
real_mkstemp = zc.tempfile.mkstemp
def spy(*args, **kwargs):
fd, name = real_mkstemp(*args, **kwargs)
seen.append(name)
return fd, name
zc.tempfile.mkstemp = spy
try:
save_zone_preset(path, "default", GOOD_PRESET)
save_zone_preset(path, "other", GOOD_PRESET)
finally:
zc.tempfile.mkstemp = real_mkstemp
assert len(seen) == 2
assert seen[0] != seen[1]
assert all(os.path.dirname(p) == str(tmp_path) for p in seen)
# --- fix round 2: R1 reference_resolution injection, R2/R3 file handling, R4 mode, R5 lock ---
def test_validate_zone_preset_injects_the_analysis_space_when_the_key_is_absent():
"""R1: missing reference_resolution defaults to native [1920, 1080]."""
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
out = validate_zone_preset(preset)
assert out["reference_resolution"] == [1920, 1080]
def test_save_zone_preset_persists_the_injected_analysis_space(tmp_path):
"""R1: the injected key must reach the file so build_static_roi scales 1080p -> 720p."""
path = str(tmp_path / "zones.json")
cfg = {"presets": {}, "active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
save_zone_preset(path, "fresh", preset)
saved = json.load(open(path))
assert saved["presets"]["fresh"]["reference_resolution"] == [1920, 1080]
roi = build_static_roi(saved["presets"]["fresh"], 1280, 720)
assert (roi.x1, roi.x2) == (400, 936)
def test_save_zone_preset_rejects_a_non_object_presets(tmp_path):
"""R2: {"presets": []} used to raise TypeError inside the save."""
path = str(tmp_path / "zones.json")
with open(path, "w") as f:
json.dump({"presets": []}, f)
with pytest.raises(ValueError, match="presets"):
save_zone_preset(path, "default", GOOD_PRESET)
def test_save_zone_preset_rejects_a_non_object_config(tmp_path):
"""R2: a JSON array as the whole config is not a zone config."""
path = str(tmp_path / "zones.json")
with open(path, "w") as f:
json.dump([1, 2, 3], f)
with pytest.raises(ValueError, match="object"):
save_zone_preset(path, "default", GOOD_PRESET)
def test_save_zone_preset_refuses_to_create_a_missing_file(tmp_path):
"""R3: the write path must never bring a zones.json into existence."""
path = str(tmp_path / "zones.json")
with pytest.raises(FileNotFoundError):
save_zone_preset(path, "default", GOOD_PRESET)
assert not os.path.exists(path)
def test_save_zone_preset_keeps_the_file_mode(tmp_path):
"""R4: mkstemp creates 0600; the file must not silently become owner-only."""
path = str(tmp_path / "zones.json")
with open(path, "w") as f:
json.dump({"presets": {}, "active_preset": "default"}, f)
os.chmod(path, 0o644)
save_zone_preset(path, "default", GOOD_PRESET)
assert os.stat(path).st_mode & 0o777 == 0o644
def test_save_zone_preset_serializes_concurrent_writes(tmp_path, monkeypatch):
"""R5: two concurrent saves must not lose one of the presets."""
import threading
import time
import src.zone_config as zc
path = str(tmp_path / "zones.json")
with open(path, "w") as f:
json.dump({"presets": {}, "active_preset": "default"}, f)
# Widen the read-modify-write window so an unsynchronized save loses an update.
real_load = zc.load_zone_config
first_read = threading.Event()
def slow_load(p):
cfg = real_load(p)
first_read.set()
time.sleep(0.05)
return cfg
monkeypatch.setattr(zc, "load_zone_config", slow_load)
errors = []
def worker(name):
try:
zc.save_zone_preset(path, name, GOOD_PRESET)
except Exception as exc: # noqa: BLE001 - reported below
errors.append(exc)
t1 = threading.Thread(target=worker, args=("one",))
t2 = threading.Thread(target=worker, args=("two",))
t1.start()
assert first_read.wait(5)
t2.start()
t1.join(5)
t2.join(5)
assert not errors
saved = json.load(open(path))
assert set(saved["presets"]) == {"one", "two"}
# ── 1080p normalizer and FCP zones.json auto-sync ────────────────────────
def test_normalize_zone_preset_converts_fcp_flat_1080p_schema():
"""FCP main's flat zones.json maps cleanly to [1920, 1080] recounter format."""
fcp_flat = {
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"line_y": 215,
"line_x_start": 577,
"line_x_end": 1401,
"left_limit": 0.27578,
"external_stream_url": "http://192.168.192.96:8888/cam/",
}
out = normalize_zone_preset(fcp_flat)
assert out["reference_resolution"] == [1920, 1080]
assert out["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
assert out["truck_area"] == [[600, 290], [609, 1076], [1404, 1078], [1381, 290]]
assert out["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
assert out["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
assert out["left_limit"] == 0.27578
for transient in ("palet_area", "truck", "counting", "line_y", "line_x_start", "line_x_end"):
assert transient not in out
roi = build_static_roi(out, 1280, 720)
assert (roi.line_x_start, roi.line_x_end, roi.line_y) == (385, 934, 143)
def test_normalize_zone_preset_scales_720p_preset_to_1080p():
"""Legacy 1280x720 presets are scaled up by 1.5x into [1920, 1080]."""
legacy_720p = {
"truck_area": [[400, 194], [406, 718], [936, 718], [920, 194]],
"counting_area": [[382, 34], [390, 718], [946, 718], [932, 34]],
"count_line": {"x_start": 384, "x_end": 934, "y": 144},
"reference_resolution": [1280, 720],
}
out = normalize_zone_preset(legacy_720p)
assert out["reference_resolution"] == [1920, 1080]
assert out["truck_area"] == [[600, 291], [609, 1077], [1404, 1077], [1380, 291]]
assert out["counting_area"] == [[573, 51], [585, 1077], [1419, 1077], [1398, 51]]
assert out["count_line"] == {"x_start": 576, "x_end": 1401, "y": 216}
def test_normalize_zone_preset_supports_two_point_counting_line():
"""FCP's 2-point counting_line and coord_space='1280x720' normalize to [1920, 1080]."""
flat_720 = {
"coord_space": "1280x720",
"truck": [[400, 200], [400, 720], [936, 720], [920, 200]],
"counting": [[380, 40], [380, 720], [940, 720], [940, 40]],
"counting_line": [[934, 200], [384, 180]],
}
out = normalize_zone_preset(flat_720)
assert out["reference_resolution"] == [1920, 1080]
assert out["count_line"] == {"x_start": 576, "x_end": 1401, "y": 285}
assert "coord_space" not in out
assert "counting_line" not in out
def test_save_zone_preset_accepts_fcp_flat_payload(tmp_path):
path = str(tmp_path / "zones.json")
with open(path, "w") as f:
json.dump({"presets": {"default": GOOD_PRESET}, "active_preset": "default"}, f)
fcp_flat = {
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"line_y": 215,
"line_x_start": 577,
"line_x_end": 1401,
}
save_zone_preset(path, "default", fcp_flat)
saved = json.load(open(path))["presets"]["default"]
assert saved["reference_resolution"] == [1920, 1080]
assert saved["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
assert "truck" not in saved
assert "line_y" not in saved
def test_sync_fcp_zones_updates_default_when_fcp_file_is_newer(tmp_path):
recounter_zones = tmp_path / "recounter_zones.json"
fcp_zones = tmp_path / "fcp_zones.json"
recounter_zones.write_text(json.dumps({
"presets": {"default": GOOD_PRESET, "other": GOOD_PRESET},
"active_preset": "default",
}))
fcp_zones.write_text(json.dumps({
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"line_y": 250,
"line_x_start": 590,
"line_x_end": 1410,
}))
# Ensure FCP file mtime is strictly newer than recounter zones.json.
st = recounter_zones.stat()
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
updated = sync_fcp_zones(str(recounter_zones), str(fcp_zones))
assert updated is True
saved = json.loads(recounter_zones.read_text())
assert saved["presets"]["default"]["count_line"] == {"x_start": 590, "x_end": 1410, "y": 250}
assert saved["presets"]["other"] == GOOD_PRESET
def test_sync_fcp_zones_skips_when_local_zones_file_is_newer(tmp_path):
recounter_zones = tmp_path / "recounter_zones.json"
fcp_zones = tmp_path / "fcp_zones.json"
fcp_zones.write_text(json.dumps({
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"line_y": 250,
"line_x_start": 590,
"line_x_end": 1410,
}))
recounter_zones.write_text(json.dumps({
"presets": {"default": GOOD_PRESET},
"active_preset": "default",
}))
st = fcp_zones.stat()
os.utime(recounter_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
updated = sync_fcp_zones(str(recounter_zones), str(fcp_zones))
assert updated is False
saved = json.loads(recounter_zones.read_text())
assert saved["presets"]["default"] == GOOD_PRESET
def test_resolve_zone_loads_fixed_zone_and_polygons(tmp_path):
zones = tmp_path / "zones.json"
zones.write_text(json.dumps({
"presets": {"default": GOOD_PRESET},
"active_preset": "default",
}))
mode, roi, preset, cpoly, tpoly = resolve_zone("fixed", "", str(zones), (1280, 720))
assert mode == "fixed"
assert preset == "default"
assert roi is not None and roi.line_y == 220
assert cpoly is not None and tpoly is not None
+71 -8
View File
@@ -7,7 +7,10 @@ Keys: s=save, c=clear/restart, q/ESC=quit.
import argparse
import json
import os
import shutil
import sys
import tempfile
import cv2
import numpy as np
@@ -25,8 +28,37 @@ def load_zones(path: str) -> dict:
def save_zones(config: dict, path: str):
with open(path, "w") as f:
json.dump(config, f, indent=2)
if os.path.exists(path):
shutil.copy2(path, path + ".bak")
fd, tmp = tempfile.mkstemp(prefix=".zones.", suffix=".tmp",
dir=os.path.dirname(path) or ".")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)
f.write("\n")
if os.path.exists(path):
os.chmod(tmp, os.stat(path).st_mode & 0o777)
os.replace(tmp, path)
except BaseException:
try:
os.remove(tmp)
except OSError:
pass
raise
def merge_preset(config: dict, preset_name: str, preset: dict) -> None:
"""Merge the measured geometry into a preset, keeping its tuning keys.
Same contract as the web editor's server-side merge
(src/zone_config.py save_zone_preset): only the geometry this tool
measured is overwritten, so calibrating a shipped preset does not drop
its palet or tuning knobs.
"""
presets = config.setdefault("presets", {})
merged = dict(presets.get(preset_name, {}))
merged.update(preset)
presets[preset_name] = merged
def draw_state(frame, points, current_zone, zone_idx, zone_sizes, zone_names):
@@ -98,6 +130,11 @@ def run(video_path: str, preset_name: str, zones_path: str):
h, w = frame.shape[:2]
print(f"Video: {w}x{h}")
# Authored zone space is 1920x1080 (scaled to 1280x720 at runtime): resize
# the frame to 1920x1080 before taking clicks while sizing the display window
# to fit smaller monitors.
frame = cv2.resize(frame, (1920, 1080))
points = []
all_sizes = list(ZONE_SIZES) + [LINE_POINTS]
all_names = list(ZONE_KEYS) + ["count_line"]
@@ -147,13 +184,15 @@ def run(video_path: str, preset_name: str, zones_path: str):
preset[ZONE_KEYS[i]] = [list(p) for p in points[offset : offset + sz]]
offset += sz
x_start = points[offset][0]
x_end = points[offset + 1][0]
line_y = min(points[offset][1], points[offset + 1][1])
preset["count_line"] = {"x_start": x_start, "x_end": x_end, "y": line_y}
# FCP count-line semantics: the line stays horizontal at the
# mean y of its two endpoints, and the x endpoints are sorted.
xs = sorted([points[offset][0], points[offset + 1][0]])
line_y = round((points[offset][1] + points[offset + 1][1]) / 2)
preset["count_line"] = {"x_start": xs[0], "x_end": xs[1], "y": line_y}
preset["reference_resolution"] = [1920, 1080]
config = load_zones(zones_path)
config.setdefault("presets", {})[preset_name] = preset
merge_preset(config, preset_name, preset)
save_zones(config, zones_path)
print(f"Saved preset '{preset_name}' to {zones_path}")
cv2.destroyAllWindows()
@@ -162,12 +201,36 @@ def run(video_path: str, preset_name: str, zones_path: str):
cv2.destroyAllWindows()
def import_json_preset(json_path: str, preset_name: str, zones_path: str) -> None:
"""Import FCP flat or recounter JSON file into zones_path as [1920, 1080]."""
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.zone_config import normalize_zone_preset, validate_zone_preset
with open(json_path, encoding="utf-8") as f:
raw = json.load(f)
normalized = normalize_zone_preset(raw)
config = load_zones(zones_path)
merge_preset(config, preset_name, normalized)
config["presets"][preset_name] = validate_zone_preset(config["presets"][preset_name])
if config.get("active_preset") is None:
config["active_preset"] = preset_name
save_zones(config, zones_path)
print(f"Imported '{json_path}' as preset '{preset_name}' into {zones_path}")
def main():
parser = argparse.ArgumentParser(description="Interactive zone calibration tool")
parser.add_argument("video_path", help="Path to video file")
parser.add_argument("video_path", nargs="?", default=None, help="Path to video file")
parser.add_argument("--preset", default="calibrated", help="Preset name (default: calibrated)")
parser.add_argument("--zones", default="zones.json", help="Path to zones.json")
parser.add_argument("--import-json", dest="import_json", default=None,
help="Import FCP 1080p flat or recounter preset JSON into --zones")
args = parser.parse_args()
if args.import_json:
import_json_preset(args.import_json, args.preset, args.zones)
return
if not args.video_path:
parser.error("video_path is required unless --import-json is specified")
run(args.video_path, args.preset, args.zones)
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Record an RTSP stream to a file so FCP and the recounter can analyse the
# same footage. The recounter is file-based by design.
#
# Usage: tools/record_rtsp.sh <rtsp-url> <out-file> [seconds]
set -euo pipefail
URL="${1:?rtsp url required}"
OUT="${2:?output file required}"
SECONDS_TO_RECORD="${3:-300}"
if ! command -v ffmpeg >/dev/null 2>&1; then
echo "ffmpeg not found in PATH" >&2
exit 1
fi
mkdir -p "$(dirname "$OUT")"
ffmpeg -hide_banner -loglevel warning \
-rtsp_transport tcp \
-i "$URL" \
-t "$SECONDS_TO_RECORD" \
-c copy \
-y "$OUT"
echo "Recorded $SECONDS_TO_RECORD s -> $OUT"
+19 -1
View File
@@ -1,6 +1,24 @@
{
"presets": {
"default": {
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 215},
"reference_resolution": [1920, 1080],
"left_limit": 0.27578,
"right_limit": 0.72578,
"duplicate_circle_radius": 30,
"min_valid_area": 15000,
"jarak_toleransi_duplikat": 30,
"max_reid_transit_distance": 400,
"circle_stay_timeout_sec": 10.0,
"inference_stride": 2,
"confirm_delay_sec": 0.5,
"exit_confirm_delay_sec": 6.0,
"description": "FCP main (91d8b48) calibration, native 1920x1080 (scaled to 1280x720 at runtime)"
},
"fcp-2026-10-15": {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"palet": [[612, 628], [1454, 630], [1458, 1074], [608, 1071]],
@@ -16,7 +34,7 @@
"inference_stride": 2,
"confirm_delay_sec": 0.5,
"exit_confirm_delay_sec": 6.0,
"description": "Default zone from karung-counting-feedmill-semarang (1920x1080 native)"
"description": "FCP 7beb820 calibration (pre-2026-11-11 recalibration), native 1920x1080"
}
},
"active_preset": "default"