Files

25 KiB
Raw Permalink Blame History

Changelog

All notable changes to this project are documented here. Format follows Keep a Changelog (dated entries; no version tags are cut in this repo — main is the release line).

[Unreleased]

Added

  • Annotated output filename carries the source clip name (e963ba0): merged_annotated.mp4 -> merged_annotated_<source>.mp4 (single model: <model>_annotated_<source>.mp4). Client upload name wins; stored file name is the fallback (/upload/reuse). Unsafe chars replaced, stem capped at 80 chars. Download name follows the file (app.py download_name=).
  • Upload models and convert to .engine from the web UI (1b032ed): upload .pt/.onnx/.engine weights through /api/models/upload (aliases /api/model/upload, /api/upload/model, /models/upload, /upload/model); new weights appear in the model groups immediately. A .pt/.onnx source can be converted to a TensorRT .engine from the UI or via /api/models/<stem>/convert (aliases accept the stem in the URL or body); conversion runs in a background thread in two stages (.pt -> .onnx via Ultralytics export(format="onnx", imgsz=640), then .pt -> .engine via export(format="engine", device=0, half=True, imgsz=640); Ultralytics cannot export an engine from an ONNX file, so a sibling .pt is required for the engine stage), with status polling on /api/models/conversions/<id> (list /api/models/conversions, cancel /.../cancel). Known classes are derived from model metadata when the stem is not in KNOWN_MODEL_CLASSES and cached by path/mtime/size. Conversion and analysis are mutually exclusive: an in-flight conversion blocks /upload and /api/analyze (409), and an active analysis job blocks conversion (409); only one conversion runs at a time. New src/model_conversion.py (ConversionManager, ConversionJob); updated src/model_registry.py (derive_known_classes, _resolve_known_classes, find_truck_detector via groups).
  • POST /api/analyze machine endpoint (540e1b5): multipart video + fcp_mode letter (A–D) or explicit model_stems; returns 202 {"job_id","status_url"}; 409 busy guard when any job is pending/running (one GPU, atomic check+enqueue under submit lock); optional X-API-Key auth iff env RECOUNTER_API_KEY set; all errors JSON. For FCP → recounter clip repush (phase 1 of cross-service recount; FCP sender still TODO, see docs/ai-handoff-fcp-recount.md).
  • config.yaml → fcp.mode_models: FCP model-mode letter → {stem: engine_classes}, mirroring platform models.modes engines[].classes exactly (B/D use v4-best truck-only role, not truck-detector weights).
  • Network reality (verified 2026-10-20): direct http://192.168.192.93:9050/api/analyze from the FCP host (.96) works (live 202 → COMPLETED). Only ICMP ping .96↔.93 is blocked — never use ping as a health check, use HTTP. A reverse-SSH-tunnel approach was built then fully reverted (e3a905e → cb483c0); direct URL is the 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 pipeline ran a same-class IoU-0.5 dedup over all detections, including the primary model's own tracked ones. FCP keeps every tracked detection — the detector's own NMS already removed duplicates inside a model (predict.py:891). Two sacks stacked on the truck overlap by more than IoU 0.5, so the recounter dropped one of them and lost its crossing (54 detections dropped in 400 frames of the test clip). Consequence: published counts increase — on the 20-minute test clip the recounter now reports the same 161 in / 1 out as FCP (it reported 158 in / 1 out before). The dedup now compares only detections from different models.
  • Upload 500 on new video + start analysis: /upload referenced video_path in probe_video(video_path) before the variable was defined (NameError → Flask 500). Removed the duplicate premature height-check block; post-save resize_video_to_max_height() (720p) already covers it (app.py:120-125, b1dd06e).
  • Single-model class filters silently dropped (src/job.py): worker 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, atomic), so there is no second _compressed.mp4 next to it, the client never sees the suffix, and the API's output_path stays valid. Only files over the 250 MB cap are compressed; a failed encode or a result that still overshoots the cap leaves the original untouched, so no video is ever lost. A 724 MB annotated video becomes 218 MB. The job videos are deleted 5 days after the job (scripts/purge_expired_outputs.py, cron daily 03:17); the job directory, the thumbnail and the sample frames stay, so the jobs list still renders.
  • Output lifecycle hardening (review of 5e2a317): the download route no longer overrides Content-Length (it broke ranged requests — a 206 with a full-length body length), so Range downloads work again; the encode temp is now unique per attempt and is validated (playable video, fsynced) before it replaces the original, and a failing os.replace keeps the original and cleans up instead of 500-ing the download; the route serves video extensions only (never the temp of an encode in flight); a stale temp of a killed encode is swept after 2 h instead of 5 days; cancelled and failed jobs are not re-encoded; the job shows "Compressing…" while it runs.
  • Batch lifecycle now matches FCP's (1c313d9, 59d8c55): the line counter is fed on every frame (FCP predict.py:1066-1067 — it used to run only while a batch was open, so crossings before the batch opened were never counted), the batch FSM is built with FCP's arguments (predict.py:739-745: stabilize 0 s, threshold disabled, idle timeout 20 s, min duration 5 s, truck-gone tolerance 30 s), and the truck model now runs in fixed-zone mode too (predict.py:882) so the batch's truck signal is a real detection inside the counting area (predict.py:893-902) instead of the static zone's constant confidence. Consequence: published counts can change for every clip — crossings before the first batch opens now count, and batch_count reflects the real truck sessions instead of always being 0 in fixed-zone mode.
  • A broken zone calibration degrades instead of publishing a wrong count (2ca4cb6): a truck_area with a malformed point, a missing or short truck_area, or a degenerate (zero-area) counting polygon now drops the job back to dynamic mode instead of raising a 500, inventing a heuristic ROI, or filtering every detection away (which reported zero sacks).
  • Review-wave hardening (76b902d): a count_line without x_start/x_end/y no longer scales the fallback twice (the counting window moved to 266...624 instead of 400...936); a broken config.yaml answers JSON 400 on POST /api/analyze instead of a 500 HTML page; a job created with zone_mode=fixed but no calibrated ROI is labelled dynamic, because that is what it counts against.
  • FCP detection thresholds and cadence (3c354c6, 70acfbb, acc74dc): detection.sack_conf 0.40 → 0.30, min_bbox_area.box 1500 → 1000 (FCP config.yaml:83-93), stabilizer.max_hold 25 → 10 (FCP predict.py:668), pipeline.truck_det_interval 15 → 5 (FCP predict.py:882). The truck ROI now refreshes 3× faster, so a batch opens and closes sooner. Consequence: published counts can change for every clip — the sac confidence gate is looser, the box area threshold is lower, and the occlusion hold is shorter (a sack hidden for more than 10 frames can be lost).
  • Counting happens inside FCP's calibrated count-line x-window (8a82b8b): the counter now uses the calibrated count_line x-range from zones.json (384...934 in the 1280x720 analysis frame, FCP predict.py:701-703) instead of the truck-ROI bounds (400...936). The ROI x-filter (400...936, FCP predict.py:541-548) still applies, so the effective window is 400...934 on both sides. Consequence: in fixed-zone mode a crossing whose bbox centre falls in (934, 936] no longer counts.
  • Batch lifecycle driven by real crossings (fc94189): the batch FSM now receives the real crossing events and the real sack-in-truck-area count (FCP predict.py:1064-1085) instead of a hardcoded "no crossing" flag, so the idle timeout and the per-batch counts follow the sacks. Per-track counting state is cleared at every batch start while the clip totals are kept (5e4add2) — FCP clears its counter after finalising a batch row (predict.py:1139-1150); the recounter clears at batch start because it reports one cumulative count per clip. Consequence: the per-batch counts in the job result can change.
  • Invalid configuration now fails fast (fcafc98): a broken config.yaml raises instead of silently falling back to the built-in defaults (a missing file still falls back). Detection confidences must be in (0, 1], IoU thresholds in (0, 1], minimum bbox areas >= 0; the offending key and value are named in the error. A job whose config is broken fails with that message instead of counting with the wrong thresholds.
  • Truncated clips are flagged (3d9cce2): a clip whose decoded frame count is more than 2 % below the container's frame count is reported as truncated: true (with frames_expected) in the job result and in GET /api/jobs / GET /api/jobs/<id>. The counts are still reported — they cover the frames that were decoded. A cancelled job also reports truncated: true (the decoder stopped early).
  • Counts limited to the calibrated counting polygon (d74ca41): a detection is counted only when its bbox centre lies inside the calibrated counting_area (FCP's detection_polygon filter, predict.py:939-942). The polygon is FCP's detection_poly_pts scaled to the 1280x720 analysis frame (predict.py:688-698). Consequence: published counts can change for every clip — detections outside the calibrated detection area no longer count.
  • Default counting zone is now the calibrated static zone (f4e7b5d): zone_mode defaults to "fixed" (the zones.json calibration, built in the 1280x720 analysis frame) instead of "dynamic", where the count line was derived from the detected truck bbox — a moving line. FCP always counts against its calibrated line (predict.py:715-724, :1037, :1066). Consequence: published counts change for every clip analysed without an explicit zone_mode (e.g. POST /api/analyze) — the count line no longer follows the truck; the web form already sent zone_mode=fixed. "dynamic" stays available as an explicit opt-in, and a deployment with no usable calibration on disk (missing or corrupt zones.json) falls back to "dynamic" automatically.
  • Analysis frame pinned to 1280x720, model input pinned to 640x640 (fcdfed1): every decoded frame is resized to 1280x720 before detection (FCP predict.py:826) and both models run with an explicit imgsz=640 (FCP predict.py:467). The annotated output is written at 1280x720 (an explicit output_height below 720 still downscales it). The static zone ROI is built in the 1280x720 frame (build_static_roi(zone, *ANALYSIS_SIZE)), so the count line (y=220) and the ROI x-window (400...936) match FCP's for every clip. Consequence: clips whose native resolution is not 1280x720 now publish FCP's geometry; 1280x720 clips are unaffected. output_height above 720 is now inert — the frame is fixed at 720p.
  • Counting/tracking params mirrored from platform (karung_counter_semarang): stabilizer.max_hold_frames 10 → 25 (~1 s occlusion hold), cfg/tracker.yaml track_buffer 60 → 90 (~3.6 s lost-track hold), ByteTrackTracker gained iou=0.7 passed to model.track(). src/stabilizer.py, src/tracking.py, cfg/tracker.yaml now byte-identical to the platform (37e2d3e).
  • 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).

2026-10-14 — Platform parity wave

Added

  • Re-attach orphaned output dirs after restart (d09800c): jobs are in-memory; JobQueue._register_orphans() now re-attaches output/job-* older than 300 s as synthetic COMPLETED jobs so they stay deletable from the UI. Younger dirs skipped (may belong to a live process).
  • config.yaml as single source of truth for tunables (7230e2b): detection, min_bbox_area, iou, roi, stabilizer, pipeline blocks; code reads config instead of scattered constants.
  • Start/stop/restart dashboard scripts (d89c985): start_dashboard.sh, stop_dashboard.sh, restart_dashboard.sh.

Fixed

  • min_bbox_area scaled from platform's 1280x720 reference to actual frame size (c2d720e) — hardcoded pixel area mis-scaled at other resolutions. No longer scaled: the analysis frame is pinned to 1280x720 (fcdfed1), so the values are literal px² in that frame.
  • "Waiting for first frame" placeholder hidden once MJPEG delivers the first frame (2efcdb2).

Changed

  • Platform detection parity + progress bars (ce604b0): detection behaviour matched to reference repo; download and processing progress bars on the UI.
  • Async writer thread + MJPEG mtime guard (92fd4cb): video encode off the pipeline thread; preview stream only re-sends when file mtime changes.

2026-09-30 — Accuracy defaults

Fixed

  • Restored accuracy defaults: detect_interval=1, sup_det_interval=5 (31bfe7c) — earlier throttling to every 2nd/10th frame had cost counts.

2026-09-29 — Fixed ROI + live box counts

Added

  • Fixed ROI zone mode as default selection (f2b5644).
  • Live box counts + separate sack/box nets on status page (81e6ae6).
  • Freeze ROI mode with deadband+sticky jitter fix and explicit fixed/frozen ROI flags (4bd9de5).
  • Stabilize secondary-model detections + box-wins suppression; web UI moved to port 9050 (ad41bf0).

Changed

  • Tracker throttled to every 2nd frame, supplementary detector interval 10, 720p output option (07289a4). (Later partially rolled back by 31bfe7c for accuracy.)

2026-09-28 — Counting correctness + downloads

Fixed

  • Exclude truck class from counting; switch to MultiClassLineCounter with real class labels (d383759) — trucks were inflating sack counts.
  • Consistent Sack In/Sack Out labels across live panel and result cards (1dbfeca).
  • Atomic compression writes, enforce 250 MB size limit, job status guard (f878110) — no more truncated _compressed.mp4 on kill.
  • Isolate tests from the real output/ dir via conftest autouse fixture (9a276b2).

Added

  • Compress downloads to max 250 MB via ffmpeg with mtime-based cache (6f86bca).
  • Propagate sack vs box counts to results and UI (7932119).

2026-09-22 — Zones, merged pipeline, live preview

Added

  • Interactive zone calibration tool (859d6a0).
  • Zone config loader + static ROI builder (4ad4284), zone_mode / fixed_zone fields on Job (7c91081), preset dropdown in the web UI (f0ea95d), visual distinction for fixed zone vs dynamic ROI (2b46231).
  • Merged detection output + parallel model execution (fc20a52).
  • Live preview toggle, FPS indicator, live counting by object (09a8829).
  • Live preview switched from WebSocket to MJPEG streaming (a5566f3) and 15+ FPS push groundwork (f9e411f).

Fixed

  • Use tracker for counting + throttle supplementary detectors (5bf44d6) — detections without track IDs never reached the counter.
  • Absolute OUTPUT_DIR, resolution scaling for zones, full reference-repo values (35cccd0).
  • Toggle preview display bug, job deletion, pipeline optimizations (1632800).
  • Show live preview img by default (was display:none from SocketIO era) (b6379e1).

Changed

  • Docs: README updated with current features and API (39b582a).

2026-09-21 — Job UX + resource management

Added

  • Video reuse: re-analyze previous uploads without re-uploading (f779f05), delete button for uploaded videos (d353272).
  • Abort button for job cancellation (6783ff3).
  • Video upload required attr removed when an existing video is selected (42c80fd).

Fixed

  • Explicit GPU memory cleanup between models to prevent OOM (93daa68).
  • Pass truck centroid to batch manager for state transitions (1e28eb4).
  • Auto-use truck-detector when model lacks truck class (57afb62).
  • Pin numpy<2.0 to resolve Jetson torch incompatibility (a75db4c).

2026-09-18 — Grouped models + TensorRT

Added

  • ModelGroup + scan_model_groups() for grouped model display (22c7842), grouped selection in JS (d07b3ba), grouped Flask routes (dbd79ed).
  • TensorRT engine export script (d32045b).

Fixed

  • Graceful error when onnxruntime is missing for .onnx models (06b013a).
  • Removed duplicate v4-best (1).pt (1bc5e06).
  • Status page: flat progress bar, created_at formatting (47ffede); dynamic aria-valuenow, focus-visible styles (7b19b5b).

UI wave (2026-09-17 → 09-18)

  • Design system foundation, CSS tokens, base template (fbcff78, c17d480).
  • Upload page: drag-drop, video preview, model cards (f245e94); double-toggle bug + hardcoded colors (197c505).
  • Status page: progress bar, live preview, result cards, polling (1c54bb1); null safety + connection-lost handling (6323583, 1d35c28).
  • Jobs page: card grid with badges/thumbnails (b1170f4), semantic cards + flat progress bar (20d5234), accessibility/responsive polish (441a6a8).
  • Video preview endpoints: thumbnail, sample frames, live frame (dca6f6b).
  • Pipeline emits live annotated frames for preview (f487b5c); clears latest_frame on failure (87c8da3).

2026-09-16 — Initial working release

Added

  • Flask web UI on port 9000 with upload, job status, APIs (eb77e5b).
  • CLI entry point: --video, --model, --filter, --list-models (f38c970).
  • Async job queue — thread-safe add/get/cancel/list (e13926d).
  • Pipeline runner processing video through the counting pipeline (5a04cc5); annotated video writer wrapping OpenCV (61c9868).
  • Model registry scanning models/ with known-class map (f5982a4).
  • Core pipeline modules copied from karung_counter_semarang (71c1ae1).
  • Integration tests for Flask routes (05bdac5); complete README with usage, CLI, API reference (1377fbb).

Fixed

  • Secure upload/download paths, default filter, status enum compare, upload validation (40e2dbe).
  • Final review wave: CLI kwargs, class filter, job locks, upload order (2b54cc3).
  • Relax racy PENDING assertion in test_queue_add_job (f14f3b5).

2026-09-15 — Project init

  • Project structure and skeleton with pyproject.toml, config.yaml, cfg/tracker.yaml, README (43a959d, 927c84d, 7fb0174).