23 KiB
Fixed Zone Mode Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Add a "fixed zone" counting mode where the counting ROI/zone is pre-defined (from zones.json or web UI), eliminating per-frame truck detection for zone geometry and significantly improving FPS.
Architecture: Two pipeline modes — "dynamic" (existing: truck detection derives ROI each frame) and "fixed" (new: static TruckROI from zones.json or user input, truck detection only for batch lifecycle). The zone mode is selected per job via a radio button on the upload page. A CLI calibration tool lets users click on a video frame to generate zone coordinates.
Tech Stack: Python, Flask, OpenCV, JSON, existing TruckROI dataclass, existing BatchLifecycleManager
Spec: Reference implementation at /tmp/karung-counting-feedmill-semarang/predict.py lines 1361-1415 (static zone), archive/get_coordinates.py (calibration tool)
Global Constraints
- Python >= 3.10, NumPy < 2.0, Jetson Orin Nano (shared 7.6GB CPU/GPU memory)
- All 62 existing tests must pass after each task
- Follow existing Flat Design system (teal #0D9488, orange #EA580C, Plus Jakarta Sans)
- Git remote:
git.proit.id/andrew/feedmill-recounter.git
File Structure
| Action | File | Responsibility |
|---|---|---|
| Create | zones.json |
Default zone config (from reference repo) |
| Create | src/zone_config.py |
Load/save zone configs, validate, build TruckROI |
| Create | tools/calibrate_zone.py |
CLI/OpenCV interactive calibration tool |
| Modify | src/pipeline.py |
Accept fixed_zone param in both pipelines, skip truck detection when fixed |
| Modify | src/job.py |
Add zone_mode + fixed_zone to Job dataclass, pass to pipeline |
| Modify | app.py |
Parse zone form data, API endpoint for zone presets |
| Modify | templates/index.html |
Zone mode selector UI (Fixed/Auto), zone config inputs |
| Modify | static/app.js |
Toggle zone config visibility, form handling |
| Modify | src/dashboard.py |
Visual distinction for fixed vs dynamic zones |
| Create | tests/test_zone_config.py |
Tests for zone config loading/validation |
| Create | tests/test_fixed_zone_pipeline.py |
Tests for fixed zone pipeline path |
Task 1: zones.json + zone_config module
Files:
- Create:
zones.json - Create:
src/zone_config.py - Create:
tests/test_zone_config.py
Interfaces:
-
Consumes:
src.truck_roi.TruckROI -
Produces:
load_zone_config(path) -> dict,build_static_roi(zone_dict, video_w, video_h) -> TruckROI,list_zone_presets(zones_dir) -> list[dict] -
Step 1: Create zones.json with default values from reference repo
{
"presets": {
"default": {
"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},
"left_limit": 0.27578,
"right_limit": 0.72578,
"duplicate_circle_radius": 30,
"description": "Default zone for 1920x1080 camera"
}
},
"active_preset": "default"
}
- Step 2: Write test_zone_config.py
import json
import os
import pytest
from src.zone_config import load_zone_config, build_static_roi, list_zone_presets
def test_load_zone_config_reads_json(tmp_path):
cfg = {"presets": {"test": {"count_line": {"x_start": 100, "x_end": 200, "y": 150}}}, "active_preset": "test"}
p = tmp_path / "zones.json"
p.write_text(json.dumps(cfg))
result = load_zone_config(str(p))
assert result["active_preset"] == "test"
assert result["presets"]["test"]["count_line"]["y"] == 150
def test_build_static_roi_from_zone_config():
zone = {
"truck_area": [[100, 50], [110, 300], [400, 310], [390, 40]],
"count_line": {"x_start": 110, "x_end": 400, "y": 150},
}
roi = build_static_roi(zone, video_w=640, video_h=480)
assert roi.line_y == 150
assert roi.confidence == 1.0
assert roi.x1 < roi.x2
assert roi.y1 < roi.y2
def test_build_static_roi_scales_coords():
zone = {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
}
roi = build_static_roi(zone, video_w=1920, video_h=1080)
assert roi.line_y == 330
assert roi.x1 == 600
assert roi.x2 == 1404
def test_list_zone_presets(tmp_path):
cfg = {"presets": {"p1": {"description": "Zone 1"}, "p2": {"description": "Zone 2"}}}
p = tmp_path / "zones.json"
p.write_text(json.dumps(cfg))
presets = list_zone_presets(str(p))
assert len(presets) == 2
names = [p["name"] for p in presets]
assert "p1" in names
assert "p2" in names
- Step 3: Run tests to verify they fail
cd /home/jetson/feedmill_semarang_project/feedmill_recounter
python -m pytest tests/test_zone_config.py -v
# Expected: FAIL (module not found)
- Step 4: Implement zone_config.py
"""Zone configuration — load/save counting zone presets from zones.json."""
from __future__ import annotations
import json
import os
from typing import Any
from src.truck_roi import TruckROI
def load_zone_config(path: str) -> dict[str, Any]:
"""Load zones.json and return full config dict."""
with open(path) as f:
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.
The zone dict should have:
- truck_area: [[x1,y1], [x2,y2], [x3,y3], [x4,y4]] (4-point polygon)
- count_line: {"x_start": int, "x_end": int, "y": int}
Coordinates are in the video's native resolution (no scaling needed
if the zone was calibrated for this resolution).
"""
truck_pts = zone.get("truck_area", [])
count_line = zone.get("count_line", {})
# Compute bounding box of truck_area polygon
if truck_pts and len(truck_pts) >= 4:
xs = [p[0] for p in truck_pts]
ys = [p[1] for p in truck_pts]
x1 = max(0, min(xs))
y1 = max(0, min(ys))
x2 = min(video_w, max(xs))
y2 = min(video_h, max(ys))
else:
# Fallback: use 50% of frame
x1, y1 = int(video_w * 0.3), int(video_h * 0.1)
x2, y2 = int(video_w * 0.75), int(video_h * 0.95)
line_y = count_line.get("y", int((y1 + y2) / 2))
return TruckROI(
x1=x1, y1=y1, x2=x2, y2=y2,
line_y=line_y,
confidence=1.0,
)
def list_zone_presets(path: str) -> list[dict[str, Any]]:
"""Return list of preset summaries: [{"name": str, "description": str, ...}]."""
config = load_zone_config(path)
presets = config.get("presets", {})
return [
{"name": name, "description": vals.get("description", ""), **vals}
for name, vals in presets.items()
]
def get_active_zone(path: str, preset_name: str | None = None) -> dict[str, Any] | None:
"""Get the active preset dict. Falls back to active_preset field if name not given."""
config = load_zone_config(path)
presets = config.get("presets", {})
name = preset_name or config.get("active_preset")
return presets.get(name)
- Step 5: Run tests
python -m pytest tests/test_zone_config.py -v
# Expected: all PASS
- Step 6: Run full test suite
python -m pytest tests/ --tb=short
# Expected: all PASS (62+ existing tests still pass)
- Step 7: Commit
git add zones.json src/zone_config.py tests/test_zone_config.py
git commit -m "feat: zone config loader and static ROI builder"
Task 2: Pipeline — accept fixed_zone, skip truck detection
Files:
- Modify:
src/pipeline.py(bothrun_pipelineandrun_merged_pipeline) - Create:
tests/test_fixed_zone_pipeline.py
Interfaces:
-
Consumes:
TruckROIfrom zone_config.build_static_roi -
Produces: Both pipelines accept
fixed_zone: TruckROI | None = Noneparam -
Step 1: Write failing tests
# tests/test_fixed_zone_pipeline.py
import inspect
from src.pipeline import run_pipeline, run_merged_pipeline
def test_run_pipeline_accepts_fixed_zone():
sig = inspect.signature(run_pipeline)
assert "fixed_zone" in sig.parameters
def test_run_merged_pipeline_accepts_fixed_zone():
sig = inspect.signature(run_merged_pipeline)
assert "fixed_zone" in sig.parameters
def test_fixed_zone_defaults_to_none():
sig = inspect.signature(run_pipeline)
param = sig.parameters["fixed_zone"]
assert param.default is None
- Step 2: Run tests to verify they fail
python -m pytest tests/test_fixed_zone_pipeline.py -v
# Expected: FAIL (fixed_zone not in signature)
- Step 3: Add fixed_zone parameter to run_pipeline
In src/pipeline.py, add fixed_zone: TruckROI | None = None to run_pipeline signature (after truck_model_config):
def run_pipeline(
video_path: str,
model_config: ModelConfig,
output_path: str,
class_filter: list[str] | None = None,
truck_model_config: ModelConfig | None = None,
fixed_zone: TruckROI | None = None, # NEW
sack_conf: float = 0.4,
...
Then in the function body, skip truck detection when fixed_zone is provided:
# Truck detector — skip if fixed zone
truck_detector = None
if fixed_zone is None:
if truck_model_config is not None:
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 []):
truck_detector = BaseDetector(
shared_model, conf=truck_conf, class_filter=("truck",)
)
And in the frame loop, use fixed_zone as roi when provided:
# Truck detection
if fixed_zone is not None:
roi = fixed_zone # static ROI, never changes
else:
roi = roi_tracker.roi
if truck_detector is not None and frame_idx % truck_det_interval == 0:
trucks = truck_detector.detect(frame)
roi = roi_tracker.update(trucks)
- Step 4: Add fixed_zone parameter to run_merged_pipeline
Same pattern — add fixed_zone: TruckROI | None = None to signature, skip truck detection and use fixed ROI:
def run_merged_pipeline(
...
fixed_zone: TruckROI | None = None, # NEW
...
In body:
# Truck detector — skip if fixed zone
truck_det = None
if fixed_zone is 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",))
else:
for i, cfg in enumerate(model_configs):
if "truck" in (cfg.known_classes or []):
truck_det = detectors[i]
break
And in frame loop:
if fixed_zone is not None:
roi = fixed_zone
else:
roi = roi_tracker.roi
if truck_det is not None and frame_idx % truck_det_interval == 0:
trucks = truck_det.detect(frame)
roi = roi_tracker.update(trucks)
- Step 5: Run tests
python -m pytest tests/ --tb=short
# Expected: all PASS
- Step 6: Commit
git add src/pipeline.py tests/test_fixed_zone_pipeline.py
git commit -m "feat: add fixed_zone param to pipelines, skip truck detection when set"
Task 3: Job model — add zone_mode + fixed_zone
Files:
- Modify:
src/job.py
Interfaces:
-
Consumes:
TruckROI, zone_config -
Produces:
Job.zone_mode,Job.fixed_zone,Job.zone_preset -
Step 1: Add fields to Job dataclass and import TruckROI
from src.truck_roi import TruckROI
@dataclass
class Job:
...
zone_mode: str = "dynamic" # "dynamic" or "fixed"
fixed_zone: TruckROI | None = None
zone_preset: str = "" # name of zone preset used
- Step 2: Update add_job to accept zone params
def add_job(
self,
video_path: str,
model_configs: list[ModelConfig],
class_filters: dict[str, list[str] | None] | None = None,
zone_mode: str = "dynamic",
fixed_zone: TruckROI | None = None,
zone_preset: str = "",
) -> Job:
...
job = Job(
...
zone_mode=zone_mode,
fixed_zone=fixed_zone,
zone_preset=zone_preset,
)
- Step 3: Pass fixed_zone to pipeline calls in _run_job
In _run_job, when calling run_pipeline and run_merged_pipeline, pass fixed_zone=job.fixed_zone:
result = run_pipeline(
...
fixed_zone=job.fixed_zone,
...
)
And for merged:
result = run_merged_pipeline(
...
fixed_zone=job.fixed_zone,
...
)
- Step 4: Run tests
python -m pytest tests/ --tb=short
# Expected: all PASS
- Step 5: Commit
git add src/job.py
git commit -m "feat: add zone_mode and fixed_zone fields to Job"
Task 4: Web UI — zone mode selector on upload page
Files:
- Modify:
app.py - Modify:
templates/index.html - Modify:
static/app.js
Interfaces:
-
Consumes: zone_config.list_zone_presets, Job.zone_mode, Job.fixed_zone
-
Produces: Form data
zone_mode,zone_preset, zone coordinate inputs -
Step 1: Add API endpoint for zone presets in app.py
@app.route("/api/zones")
def api_zones():
zones_path = os.path.join(os.path.dirname(__file__), "zones.json")
if not os.path.isfile(zones_path):
return jsonify({"presets": [], "active": ""})
presets = list_zone_presets(zones_path)
config = load_zone_config(zones_path)
return jsonify({"presets": presets, "active": config.get("active_preset", "")})
Add import: from src.zone_config import load_zone_config, list_zone_presets, build_static_roi, get_active_zone
- Step 2: Update upload/reuse routes to parse zone form data
In both upload() and upload_reuse(), after parsing model configs:
zone_mode = request.form.get("zone_mode", "dynamic")
fixed_zone = None
zone_preset = ""
if zone_mode == "fixed":
preset_name = request.form.get("zone_preset", "")
zones_path = os.path.join(os.path.dirname(__file__), "zones.json")
if os.path.isfile(zones_path):
zone = get_active_zone(zones_path, preset_name)
if zone:
# Get video dimensions to build ROI
import cv2
cap = cv2.VideoCapture(video_path)
vw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
vh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap.release()
fixed_zone = build_static_roi(zone, vw, vh)
zone_preset = preset_name
job = job_queue.add_job(
...
zone_mode=zone_mode,
fixed_zone=fixed_zone,
zone_preset=zone_preset,
)
- Step 3: Add zone mode section to index.html (after existing videos, before model selection)
Insert between the existing-videos-section and model-section divs:
{# --- Zone Mode --- #}
<div class="zone-section" id="zone-section" style="display:none">
<h3 class="section-title">Counting Zone</h3>
<div class="zone-mode-toggle">
<label class="zone-mode-option">
<input type="radio" name="zone_mode" value="dynamic" checked>
<span class="zone-mode-label">Auto-detect Truck</span>
<span class="zone-mode-desc">ROI derived from truck detection each frame</span>
</label>
<label class="zone-mode-option">
<input type="radio" name="zone_mode" value="fixed">
<span class="zone-mode-label">Fixed Zone</span>
<span class="zone-mode-desc">Pre-defined counting zone, no truck detection needed (faster)</span>
</label>
</div>
<div class="zone-fixed-config" id="zone-fixed-config" style="display:none">
<div class="zone-preset-select">
<label for="zone-preset">Zone Preset:</label>
<select name="zone_preset" id="zone-preset">
<option value="">Select a preset...</option>
</select>
</div>
<div class="zone-coords-preview" id="zone-coords-preview" style="margin-top:var(--space-3);font-size:var(--text-sm);color:var(--color-neutral-600)"></div>
</div>
</div>
Add CSS for .zone-section, .zone-mode-toggle, .zone-mode-option, .zone-mode-label, .zone-mode-desc matching existing Flat Design patterns.
- Step 4: Add JS to toggle zone section visibility, load presets, and handle selection
In static/app.js, add:
// Show zone section when video is selected (alongside file-info)
// On page load, fetch /api/zones and populate #zone-preset dropdown
// Toggle #zone-fixed-config visibility when zone_mode radio changes
// When preset selected, show coords preview (count_line y, x_start, x_end)
- Step 5: Run full test suite
python -m pytest tests/ --tb=short
# Expected: all PASS
- Step 6: Commit
git add app.py templates/index.html static/app.js
git commit -m "feat: web UI zone mode selector with preset dropdown"
Task 5: Calibration tool (CLI/OpenCV)
Files:
- Create:
tools/calibrate_zone.py
Interfaces:
-
Consumes: video file path
-
Produces: updates
zones.jsonwith new preset -
Step 1: Create the calibration tool
Based on reference archive/get_coordinates.py, adapted for this project:
#!/usr/bin/env python3
"""Interactive zone calibration tool.
Usage: python tools/calibrate_zone.py <video_path> [preset_name]
Click 4 points for truck area, 4 points for detection area,
2 points for count line. Press 's' to save to zones.json.
Press 'c' to clear and restart. Press 'q' to quit.
"""
import cv2, json, os, sys, numpy as np
ZONES_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "zones.json")
STATE_TRUCK, STATE_DETECTION, STATE_LINE, STATE_DONE = 0, 1, 2, 3
state = STATE_TRUCK
pts = {"truck": [], "detection": [], "line": []}
def click(event, x, y, flags, param):
global state
if event != cv2.EVENT_LBUTTONDOWN:
return
if state == STATE_TRUCK:
pts["truck"].append([x, y])
if len(pts["truck"]) == 4: state = STATE_DETECTION
elif state == STATE_DETECTION:
pts["detection"].append([x, y])
if len(pts["detection"]) == 4: state = STATE_LINE
elif state == STATE_LINE:
pts["line"].append([x, y])
if len(pts["line"]) == 2: state = STATE_DONE
draw()
def draw():
vis = img.copy()
# Draw polygons and line...
labels = {
STATE_TRUCK: f"1. TRUCK AREA ({len(pts['truck'])}/4)",
STATE_DETECTION: f"2. DETECTION AREA ({len(pts['detection'])}/4)",
STATE_LINE: f"3. COUNT LINE ({len(pts['line'])}/2)",
STATE_DONE: "DONE! 's'=save 'c'=redo",
}
cv2.rectangle(vis, (10,10), (vis.shape[1]-10, 50), (0,0,0), -1)
cv2.putText(vis, labels[state], (20, 35), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2)
cv2.imshow("Calibrator", vis)
if __name__ == "__main__":
video = sys.argv[1]
preset = sys.argv[2] if len(sys.argv) > 2 else "custom"
cap = cv2.VideoCapture(video)
cap.set(cv2.CAP_PROP_POS_FRAMES, int(cap.get(cv2.CAP_PROP_FRAME_COUNT) * 0.1))
ret, img = cap.read()
cap.release()
cv2.namedWindow("Calibrator")
cv2.setMouseCallback("Calibrator", click)
draw()
while True:
k = cv2.waitKey(1) & 0xFF
if k == ord("c"):
for v in pts.values(): v.clear()
state = STATE_TRUCK; draw()
elif k == ord("s") and state == STATE_DONE:
y = (pts["line"][0][1] + pts["line"][1][1]) // 2
cfg = json.load(open(ZONES_PATH)) if os.path.isfile(ZONES_PATH) else {"presets": {}}
cfg["presets"][preset] = {
"truck_area": pts["truck"], "counting_area": pts["detection"],
"count_line": {"x_start": pts["line"][0][0], "x_end": pts["line"][1][0], "y": y},
"description": f"Calibrated from {os.path.basename(video)}",
}
cfg["active_preset"] = preset
json.dump(cfg, open(ZONES_PATH, "w"), indent=2)
print(f"Saved '{preset}' -> y={y}, x=[{pts['line'][0][0]},{pts['line'][1][0]}]")
break
elif k in (ord("q"), 27): break
cv2.destroyAllWindows()
- Step 2: Test manually
python tools/calibrate_zone.py uploads/some_video.mp4 test_zone
- Step 3: Commit
git add tools/calibrate_zone.py
git commit -m "feat: interactive zone calibration tool"
Task 6: Dashboard — visual distinction for fixed zone
Files:
-
Modify:
src/dashboard.py -
Step 1: In _draw_roi, detect fixed zone (confidence == 1.0) and draw dashed border + "FIXED ZONE" label
Replace _draw_roi method:
def _draw_roi(self, frame: np.ndarray, roi: TruckROI) -> None:
if roi.confidence >= 1.0:
# Fixed zone: dashed cyan border
for x in range(roi.x1, roi.x2, 12):
cv2.line(frame, (x, roi.y1), (min(x + 6, roi.x2), roi.y1), (0, 200, 200), 1)
cv2.line(frame, (x, roi.y2), (min(x + 6, roi.x2), roi.y2), (0, 200, 200), 1)
for y in range(roi.y1, roi.y2, 12):
cv2.line(frame, (roi.x1, y), (roi.x1, min(y + 6, roi.y2)), (0, 200, 200), 1)
cv2.line(frame, (roi.x2, y), (roi.x2, min(y + 6, roi.y2)), (0, 200, 200), 1)
cv2.putText(frame, "FIXED ZONE", (roi.x1, roi.y1 - 8),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 200, 200), 1)
else:
# Dynamic: existing solid orange
cv2.rectangle(frame, (roi.x1, roi.y1), (roi.x2, roi.y2), ORANGE, 2)
cv2.putText(frame, f"TRUCK ROI ({roi.confidence:.0%})",
(roi.x1, roi.y1 - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.5, ORANGE, 1)
for x in range(roi.x1, roi.x2, 20):
cv2.line(frame, (x, roi.y1), (min(x + 10, roi.x2), roi.y1), GRAY, 1)
- Step 2: Run tests
python -m pytest tests/ --tb=short
- Step 3: Commit
git add src/dashboard.py
git commit -m "feat: visual distinction for fixed zone vs dynamic ROI"
Task 7: Final integration + push
- Step 1: Run full test suite
python -m pytest tests/ -v --tb=short
- Step 2: Manual end-to-end test
python app.py
# Test 1: Upload with dynamic mode (existing behavior unchanged)
# Test 2: Upload with fixed zone mode, select "default" preset
# Test 3: Run calibrate tool, create new preset, upload with it
- Step 3: Push
git push origin main