Compare commits

...
Author SHA1 Message Date
andrew 17e2244129 Update AGENTS.md
- Refresh repo guidelines
2026-12-01 11:14:11 +07:00
andrew ea1f376e1f Show real pipeline FPS and stream resolution from live metadata
- Counter writes stream_meta.json with processing FPS and frame dimensions
- Dashboard reads it instead of static defaults
2026-12-01 11:02:33 +07:00
andrew 1ca458f4e4 Replace placeholder 98% confidence with dash
- Akurasi Data Stream: Konfidensi placeholder '-' instead of 98%
2026-12-01 10:18:20 +07:00
andrew c78d89bc44 Draw white center dot with blue outline on counted objects 2026-12-01 09:12:04 +07:00
andrew c803c0760b Replace placeholder stream accuracy with dash 2026-12-01 09:01:30 +07:00
andrew 6af5968823 Display live batch mode (AUTO MODE / MANUAL TRIGGER) in dashboard UI 2026-11-30 08:10:20 +07:00
andrew a168322194 Update docs for auto-mode timeout and peer-sync ignore 2026-11-27 15:45:01 +07:00
andrew 581899e4a0 Ignore peer sync in auto mode and hold 30s batch timeout while truck is in zone 2026-11-27 15:01:54 +07:00
andrew 52612a4762 Fix dark-mode sun icon visibility and remove Porsi column from day detail modal 2026-11-27 15:01:54 +07:00
andrew 926f4c3876 Add PT-to-RKNN conversion script and moon dark mode icon 2026-11-27 13:09:44 +07:00
andrew 2abafd37e6 Switch theme toggle to SVG sun/moon icons
- Use sun_light mode.svg / moon_dark mode.svg in toggle button
- Swap icon src on theme change
- Invert sun icon in dark mode for contrast (brightness(0) invert(1))
2026-11-26 11:48:14 +07:00
andrew 31040d7661 Switch theme toggle to SVG sun/moon icons
- Use sun_light mode.svg / moon_dark mode.svg in toggle button
- Swap icon src on theme change
- Make sun icon white in dark mode via brightness(0) invert(1)
2026-11-26 11:38:24 +07:00
andrew 3659cbadd0 Make NMS IoU threshold configurable via IOU env var
- Add IOU env var (default 0.45) to counter_live_rknn.py, .env, config.env.example
- Pass iou=IOU to RKNNYOLO instead of hardcoded default
- Document IOU and per-class confidence vars in README env table
2026-11-24 16:29:53 +07:00
16 changed files with 908 additions and 82 deletions

No files matched your search

+2
View File
@@ -8,6 +8,7 @@ __pycache__/
*.pyc
*.pyo
venv/
venv-convert/
.venv/
# Data / state
@@ -27,6 +28,7 @@ batch_crossings.csv
*.log
*.jpg
*.png
calib_images/
# Superpowers / scratch
.superpowers/
+13 -6
View File
@@ -2,7 +2,7 @@
## Project Overview
Feedmill is a production edge counter for feed sacks and boxes. A Rockchip RK3588 NPU runs YOLO (RKNN) over an RTSP camera stream; ByteTrack tracks objects; a line-crossing rule increments counts. Counts persist to SQLite + JSON state; a Flask dashboard on port 7000 exposes batch control and reporting. Truck detections are used only to define the horizontal counting zone, not counted.
Feedmill is a production edge counter for feed sacks and boxes. A Rockchip RK3588 NPU runs YOLO (RKNN) over an RTSP camera stream; ByteTrack tracks objects; a line-crossing rule increments counts. Counts persist to SQLite + JSON state; a Flask dashboard exposes batch control/reporting on the configured port (default 7000 via `.env`). Truck detections define the horizontal counting zone only and are not counted. Batches are unified: one batch tracks combined `count` plus separate `sack_count`/`box_count`.
## Architecture & Data Flow
@@ -13,9 +13,9 @@ Feedmill is a production edge counter for feed sacks and boxes. A Rockchip RK358
5. Tracking: `ByteTracker.update` associates detections across frames.
6. Crossing: `crossed_line(prev_pos, pos, line_pos)` plus `is_duplicate_cross` dedup; on crossing, `BatchStore.record_counted_object_crossing(tid, object_label=...)`.
7. Persistence: `batch_store.py` writes `batches`/`daily_summaries` and `current_batch.json`.
8. Dashboard (`counter_dashboard.py`) reads DB/state and proxies start/stop to the counter control server (`counter_control.py`, 127.0.0.1:5000).
8. Dashboard (`counter_dashboard.py`) reads DB/state and proxies start/stop to the counter control server (`counter_control.py`, `127.0.0.1:5001`).
Batches: manual mode (operator start/stop; passing objects ignored while stopped) or auto mode (first crossing opens; idle timeout closes). Each batch tracks combined `count` plus separate `sack_count`/`box_count`.
Batches: manual mode (operator start/stop; passing objects ignored while stopped) or auto mode (first crossing opens; idle timeout closes; timeout held while truck in zone). Peer-sync requests are ignored in auto mode.
## Key Directories
@@ -47,6 +47,9 @@ sudo systemctl status feedmill-counter feedmill-dashboard
sudo journalctl -u feedmill-counter -f
sudo ./install-services.sh
sudo ./uninstall-services.sh
# optional model conversion (needs rknn, torch, onnx, ultralytics)
/opt/feedmill/venv/bin/python convert_pt_to_rknn.py model.pt -o /opt/models/model.rknn --imgsz 480 --target rk3588
```
No build step, lint config, or package manifest beyond `requirements.txt`.
@@ -61,6 +64,7 @@ No build step, lint config, or package manifest beyond `requirements.txt`.
- Atomic live-frame writes via temp file + `os.replace`.
- Dedup keys: `{label}:{track_id}` in `counted_event_ids`.
- Tests mock `rknnlite` import when unavailable; use temp SQLite/state files.
- Peer API validation: `X-API-Key` checked only when header present; wrong/missing expected token returns 401.
## Important Files
@@ -72,19 +76,22 @@ No build step, lint config, or package manifest beyond `requirements.txt`.
- `requirements.txt` — Python dependencies.
- `feedmill-counter.service`, `feedmill-dashboard.service` — systemd units.
- `API.md`, `DEPLOY.md`, `README.md` — API, deployment, overview docs.
- `docs/peer_sync_handoff.md` — FCP peer-sync contract.
## Runtime/Tooling Preferences
- Python 3.12.3 in `/opt/feedmill/venv` (system-site-packages false).
- Dependencies: `numpy<2`, `rknn-toolkit-lite2`, `opencv-python`, `flask`, `python-dotenv`, `openpyxl`.
- RKNN runtime 2.3.2 targeting RKNPU v2 (RK3588). Models live in `/opt/models/*.rknn`.
- RKNN runtime targeting RKNPU v2 (RK3588); models live in `/opt/models/*.rknn`.
- Install scripts require root; services run as root with `PYTHONNOUSERSITE=1`.
- Dashboard port comes from `.env` (`DASHBOARD_PORT`, typically 7000); code default is 5000.
- Internal control port defaults to 5001.
- No Node/Bun tooling; frontend is server-rendered Jinja + Chart.js.
## Testing & QA
- Framework: stdlib `unittest`; no pytest/conftest/CI config.
- Suites: `tests/test_batch_store.py` (8), `tests/test_crossing_guards.py` (5), `tests/test_dashboard.py` (13).
- Suites: `tests/test_batch_store.py` (12), `tests/test_crossing_guards.py` (5), `tests/test_dashboard.py` (15).
- Run from `/opt/feedmill` so top-level imports resolve.
- Coverage gaps: inference loop/RKNN loading, camera capture, control-server error paths, peer forwarding, frontend JS, concurrency/migration against production DB, service scripts.
- Dashboard tests mutate module globals (`DB_PATH`, `CURRENT_BATCH_PATH`) and create a persistent temp root at import.
- Dashboard tests mutate module globals (`DB_PATH`, `CURRENT_BATCH_PATH`) and create a persistent temp root at import.
+7
View File
@@ -358,3 +358,10 @@ Request body (JSON) is forwarded to the internal control server, supporting:
`net_sack`, `net_box`, `ended_at`.
Responses include `object_labels`, `counts`, and `plate` for peer compatibility.
---
## Auto-mode peer sync
When `BATCH_MODE=auto`, `POST /api/batch/start` and `POST /api/batch/stop` forwarded with `X-Peer-Sync: 1` (peer requests) return `200` with `ignored: true` and the current batch state; the local counter keeps running. Non-peer (local dashboard) calls still work.
+3
View File
@@ -83,6 +83,9 @@ sudo systemctl restart feedmill-counter # after .env change
## Peer sync (FCP)
- When the counter is in `BATCH_MODE=auto`, peer-sync start/stop requests (forwarded with `X-Peer-Sync: 1`) are ignored and the current batch state is returned unchanged.
- In auto mode the batch timer (default 30s) is held while a truck is detected in the counting zone and counts down 30s after the truck leaves.
- FCP POSTs start/stop to dashboard `/api/batch/start` and `/api/batch/stop` with `X-API-Key: <PEER_API_TOKEN>`.
- Body is forwarded to internal control server; metadata stored on batch row (`source`, `fcp_batch_number`, `plate`, `do_numbers`, `expected_sack`, `expected_box`).
- Validate API key only when header present (dashboard UI unaffected).
+7 -2
View File
@@ -12,7 +12,7 @@ RTSP + YOLO RKNN + ByteTrack line-crossing counter for **sacks**, **boxes**, and
Batch lifecycle:
- **Manual Mode (`BATCH_MODE=manual`, default):** Operator triggers **Start Batch** / **Stop Batch** via dashboard buttons or API. One unified batch counts sacks and boxes together while reporting separate Sack and Box totals. Objects passing while stopped are ignored.
- **Auto Mode (`BATCH_MODE=auto`):** Auto-creates batch on first crossing, closes batch after idle timeout (`BATCH_TIMEOUT_SECONDS=600`).
- **Auto Mode (`BATCH_MODE=auto`):** Auto-creates batch on first crossing, closes batch after idle timeout (`BATCH_TIMEOUT_SECONDS=30`); timer is held while a truck is present in the counting zone and counts down 30s after the truck leaves. Peer-sync start/stop requests are ignored when the counter is in auto mode.
## Deploy
@@ -44,13 +44,18 @@ See **[DEPLOY.md](DEPLOY.md)**.
| `NUM_CLASSES` | Model class count (3: sack, box, truck) |
| `COUNTED_CLASS_IDS` | Counted class IDs (0,1) |
| `TRUCK_CLASS_ID` | Truck class ID for zone (2) |
| `IOU` | NMS IoU threshold (default `0.45`) |
| `CONF` / `SACK_CONF` / `BOX_CONF` / `TRUCK_CONF` | Per-class confidence thresholds |
| `ZONE_MODE` | `auto` (follow truck) or `manual`/`fixed` |
| `COUNT_AXIS` | `y` for downward flow |
| `CROSS_DIRECTION` | `down` (default), `up`, `ltr`, `rtl`, or `both` |
| `LINE_Y` / `LINE_Y_FRAC` | Counting line position |
| `BATCH_MODE` | `manual` or `auto` |
| `BATCH_MODE` | `manual` or `auto` (auto ignores peer start/stop) |
| `BATCH_TIMEOUT_SECONDS` | Auto-mode idle timeout (default `30`; held while truck in zone) |
| `DAILY_CUTOFF_TIME` / `CUTOFF_TIME` | Daily cutoff (`06:00`) |
| `PEER_API_TOKEN` | Shared secret for FCP peer sync (`X-API-Key`) |
| `TRUCK_ZONE_HOLD_SEC` | Seconds to hold last truck zone (default `300`) |
| `TRUCK_ZONE_PAD_X` | Pixel pad around truck bbox for zone (default `10`) |
## Files
+68 -37
View File
@@ -121,7 +121,7 @@ class BatchStore:
camera_name,
object_label='sack',
cutoff_time='06:00',
batch_timeout=600.0,
batch_timeout=30.0,
min_object_per_batch=60,
min_duration_per_batch=60,
carry_ids=50,
@@ -144,6 +144,7 @@ class BatchStore:
self.state_lock = threading.Lock()
self.batch_timer = None
self.truck_present = False
self.previous_state = None
self.shutdown_event = threading.Event()
@@ -262,35 +263,40 @@ class BatchStore:
def start_new_batch(self, counting_date=None, object_label=None):
with self.state_lock:
if self.current_state is not None:
self.log(f'Batch #{self.current_state["batch_number"]} is already active')
return self.current_state['batch_number']
if counting_date is None:
counting_date = self.get_counting_date()
batch_number = self.get_next_batch_number(counting_date)
now = datetime.now().isoformat()
counted_ids = []
if self.previous_state is not None:
try:
counted_ids = list(self.previous_state['counted_event_ids'][-self.carry_ids:])
except (KeyError, TypeError):
counted_ids = []
self.current_state = {
'counting_date': counting_date,
'batch_number': batch_number,
'object_label': 'mixed',
'count': 0,
'sack_count': 0,
'box_count': 0,
'start_time': now,
'last_detection_time': now,
'counted_event_ids': counted_ids,
}
self.save_state()
if self.batch_mode != 'manual':
self._reset_batch_timer()
self.log(f'Started batch #{batch_number} for {counting_date} (mixed) [mode={self.batch_mode}]')
return batch_number
return self._start_new_batch_locked(
counting_date=counting_date, object_label=object_label
)
def _start_new_batch_locked(self, counting_date=None, object_label=None):
if self.current_state is not None:
self.log(f'Batch #{self.current_state["batch_number"]} is already active')
return self.current_state['batch_number']
if counting_date is None:
counting_date = self.get_counting_date()
batch_number = self.get_next_batch_number(counting_date)
now = datetime.now().isoformat()
counted_ids = []
if self.previous_state is not None:
try:
counted_ids = list(self.previous_state['counted_event_ids'][-self.carry_ids:])
except (KeyError, TypeError):
counted_ids = []
self.current_state = {
'counting_date': counting_date,
'batch_number': batch_number,
'object_label': 'mixed',
'count': 0,
'sack_count': 0,
'box_count': 0,
'start_time': now,
'last_detection_time': now,
'counted_event_ids': counted_ids,
}
self.save_state()
if self.batch_mode != 'manual':
self._reset_batch_timer()
self.log(f'Started batch #{batch_number} for {counting_date} (mixed) [mode={self.batch_mode}]')
return batch_number
def update_batch_metadata(self, metadata):
if not isinstance(metadata, dict):
@@ -310,19 +316,43 @@ class BatchStore:
self.current_state[key] = metadata[key]
self.save_state()
def set_truck_present(self, present):
"""Hold auto-mode batch timeout while a truck is present in the counting zone."""
present = bool(present)
with self.state_lock:
was_present = self.truck_present
self.truck_present = present
if self.batch_mode == 'manual' or self.current_state is None:
return
if present:
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
elif was_present or self.batch_timer is None:
self._reset_batch_timer()
def _reset_batch_timer(self):
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
if self.truck_present:
return
self.batch_timer = threading.Timer(self.batch_timeout, self._on_batch_timeout)
self.batch_timer.daemon = True
self.batch_timer.start()
def _on_batch_timeout(self):
self.log(
f'No {self.object_label} line crossing for {self.batch_timeout:.0f}s – '
'closing batch (next crossing starts a new batch)'
)
self.end_batch(closed_by='timeout')
with self.state_lock:
if self.current_state is None:
return
if self.truck_present:
self.batch_timer = None
return
self.log(
f'No {self.object_label} line crossing for {self.batch_timeout:.0f}s '
'and no truck in counting zone – closing batch (next crossing starts a new batch)'
)
self._end_batch_locked(closed_by='timeout')
def record_counted_object_crossing(self, track_id, object_label=None):
"""Record one newly counted object crossing."""
@@ -333,14 +363,14 @@ class BatchStore:
if self.batch_mode == 'manual':
# In manual mode, do not auto-start batch; wait for manual trigger
return 0, False
self.start_new_batch(counting_date, object_label=object_label)
self._start_new_batch_locked(counting_date, object_label=object_label)
started_new = True
elif self.current_state['counting_date'] != counting_date:
prev_label = self.current_state.get('object_label')
self._end_batch_locked(closed_by='cutoff')
if self.batch_mode == 'manual':
return 0, False
self.start_new_batch(counting_date, object_label=object_label or prev_label)
self._start_new_batch_locked(counting_date, object_label=object_label or prev_label)
started_new = True
item_label = self._normalize_item_label(object_label)
@@ -601,6 +631,7 @@ class BatchStore:
"plate": self.current_state.get('plate') if active else None,
"source": self.current_state.get('source') if active else None,
"fcp_batch_number": self.current_state.get('fcp_batch_number') if active else None,
"truck_present": self.truck_present,
}
def shutdown(self):
+7 -2
View File
@@ -45,6 +45,9 @@ SACK_CONF=0.3
BOX_CONF=0.3
TRUCK_CONF=0.3
# NMS IoU threshold (0.0 - 1.0): boxes with IoU above this are merged during non-max suppression
IOU=0.45
# --- ByteTrack tracking ---
# Counted sack class, index 0
# Detections with score ≥ this get priority matching in the first association stage
@@ -127,8 +130,10 @@ CUTOFF_TIME=06:00
# Reset frame counter and ByteTrack track-ID counter back to 0 at daily cutoff
RESET_COUNTERS_AT_CUTOFF=true
# Timeout in seconds without sack line crossings (disabled in manual mode so pauses won't close batch)
BATCH_TIMEOUT_SECONDS=600
# Timeout in seconds without line crossings before auto mode closes a batch.
# While a truck is detected in the counting zone ROI, the timer is held; once no
# truck is in the zone, the 30s countdown runs. (Disabled in manual mode.)
BATCH_TIMEOUT_SECONDS=30
# Minimum sacks per batch to persist to database (set to 1 for manual mode)
MIN_OBJECT_PER_BATCH=1
+409
View File
@@ -0,0 +1,409 @@
#!/usr/bin/env python3
"""Convert an Ultralytics YOLO .pt model to an INT8 RKNN model for RK3588.
Exports the raw multi-branch YOLO head (per-scale box DFL + class logits, plus
angle logits for OBB) without DFL decode or sigmoid so the output matches
``counter_live_rknn.RKNNYOLO._decode_multibranch``.
"""
import argparse
import inspect
import os
import sys
import time
import types
from pathlib import Path
import cv2
import numpy as np
import onnx
import torch
from dotenv import dotenv_values
from rknn.api import RKNN
from ultralytics import YOLO
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp"}
def letterbox_image(frame: np.ndarray, imgsz: int) -> np.ndarray:
"""Resize and pad frame to square (imgsz, imgsz, 3) BGR matching RKNNYOLO._preprocess."""
h0, w0 = frame.shape[:2]
scale = min(imgsz / h0, imgsz / w0)
nh, nw = int(h0 * scale), int(w0 * scale)
resized = cv2.resize(frame, (nw, nh), interpolation=cv2.INTER_LINEAR)
canvas = np.full((imgsz, imgsz, 3), 114, dtype=np.uint8)
dy = (imgsz - nh) // 2
dx = (imgsz - nw) // 2
canvas[dy : dy + nh, dx : dx + nw] = resized
return canvas
def load_env_defaults(env_file: Path) -> tuple[str | None, str]:
"""Read SOURCE and OPENCV_FFMPEG_CAPTURE_OPTIONS from an env file."""
if not env_file.is_file():
return None, "rtsp_transport;tcp|fflags;nobuffer|flags;low_delay"
cfg = dotenv_values(env_file)
source = (cfg.get("SOURCE") or "").strip() or None
ffmpeg_opts = (
cfg.get("OPENCV_FFMPEG_CAPTURE_OPTIONS")
or "rtsp_transport;tcp|fflags;nobuffer|flags;low_delay"
).strip()
return source, ffmpeg_opts
def _collect_existing_images(calib_dir: Path) -> list[Path]:
if not calib_dir.is_dir():
return []
return sorted(
p
for p in calib_dir.iterdir()
if p.is_file() and p.suffix.lower() in IMAGE_EXTS
)
def _capture_rtsp_frames(
source: str,
ffmpeg_opts: str,
calib_dir: Path,
imgsz: int,
target_count: int,
interval_sec: float,
) -> list[Path]:
"""Capture letterboxed calibration frames from an RTSP stream or video file."""
calib_dir.mkdir(parents=True, exist_ok=True)
if source.lower().startswith(("rtsp://", "http://")):
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = ffmpeg_opts
print(f"Capturing {target_count} calibration frames from: {source}")
cap = cv2.VideoCapture(source, cv2.CAP_FFMPEG)
if not cap.isOpened():
raise RuntimeError(f"Failed to open video/RTSP source: {source}")
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
saved: list[Path] = []
try:
for _ in range(10):
cap.read()
existing = _collect_existing_images(calib_dir)
start_idx = len(existing)
consecutive_failures = 0
while len(saved) + len(existing) < target_count:
ok, frame = cap.read()
if not ok or frame is None:
consecutive_failures += 1
if consecutive_failures >= 30:
break
time.sleep(0.05)
continue
consecutive_failures = 0
lb = letterbox_image(frame, imgsz)
out_path = calib_dir / f"calib_{start_idx + len(saved):04d}.jpg"
cv2.imwrite(str(out_path), lb, [cv2.IMWRITE_JPEG_QUALITY, 95])
saved.append(out_path)
# Drain buffered frames during the interval so each sample is fresh.
if interval_sec > 0 and len(saved) + len(existing) < target_count:
deadline = time.monotonic() + interval_sec
while time.monotonic() < deadline:
cap.grab()
time.sleep(0.01)
finally:
cap.release()
all_imgs = _collect_existing_images(calib_dir)
if len(all_imgs) < 10:
raise RuntimeError(
f"Captured only {len(all_imgs)} calibration frames (minimum 10 required) from {source}"
)
print(f"Prepared {len(all_imgs)} calibration images in {calib_dir}")
return all_imgs
def prepare_calibration_dataset(
calib_dir: Path,
imgsz: int,
target_count: int,
interval_sec: float,
rtsp_source: str | None,
env_file: Path,
) -> tuple[Path, int]:
"""Ensure calibration directory has letterboxed images and write dataset.txt."""
existing = _collect_existing_images(calib_dir)
if len(existing) < target_count:
env_source, ffmpeg_opts = load_env_defaults(env_file)
source = rtsp_source or env_source
if not source:
raise RuntimeError(
f"Calibration dir {calib_dir} has {len(existing)}/{target_count} images "
"and no --rtsp or SOURCE in .env was provided."
)
existing = _capture_rtsp_frames(
source=source,
ffmpeg_opts=ffmpeg_opts,
calib_dir=calib_dir,
imgsz=imgsz,
target_count=target_count,
interval_sec=interval_sec,
)
else:
print(f"Using {len(existing)} existing calibration images in {calib_dir}")
# Guarantee every image fed to RKNN matches (imgsz, imgsz) via letterboxing.
lb_dir = calib_dir / f"_lb_{imgsz}"
dataset_paths: list[Path] = []
for idx, img_path in enumerate(existing[:target_count]):
img = cv2.imread(str(img_path))
if img is None:
continue
if img.shape[0] == imgsz and img.shape[1] == imgsz:
dataset_paths.append(img_path.resolve())
else:
lb_dir.mkdir(parents=True, exist_ok=True)
lb_path = lb_dir / f"lb_{idx:04d}.jpg"
cv2.imwrite(
str(lb_path),
letterbox_image(img, imgsz),
[cv2.IMWRITE_JPEG_QUALITY, 95],
)
dataset_paths.append(lb_path.resolve())
if len(dataset_paths) < 10:
raise RuntimeError(
f"Only {len(dataset_paths)} readable calibration images in {calib_dir}"
)
dataset_txt = calib_dir / "dataset.txt"
dataset_txt.write_text("\n".join(str(p) for p in dataset_paths) + "\n", encoding="utf-8")
return dataset_txt, len(dataset_paths)
def _multibranch_forward(self, x):
"""Return raw per-scale Detect/OBB head tensors without DFL decode or sigmoid."""
outputs = []
has_obb = hasattr(self, "cv4")
for i in range(self.nl):
outputs.append(self.cv2[i](x[i]))
outputs.append(self.cv3[i](x[i]))
if has_obb:
outputs.append(self.cv4[i](x[i]))
return tuple(outputs)
def export_multibranch_onnx(
pt_path: Path, onnx_path: Path, imgsz: int, opset: int
) -> tuple[dict, list[tuple[str, tuple[int, ...]]]]:
"""Export YOLO .pt model to multi-branch ONNX matching RKNNYOLO._decode_multibranch."""
yolo = YOLO(str(pt_path))
class_names = dict(yolo.names)
pt_model = yolo.model.eval().cpu().float()
if hasattr(pt_model, "fuse"):
pt_model.fuse()
head = pt_model.model[-1]
if not (hasattr(head, "cv2") and hasattr(head, "cv3") and hasattr(head, "nl")):
raise RuntimeError(
f"Unsupported model head {type(head).__name__}: expected cv2, cv3, and nl attributes."
)
has_obb = hasattr(head, "cv4")
head.forward = types.MethodType(_multibranch_forward, head)
output_names: list[str] = []
for i in range(head.nl):
output_names.extend([f"box_{i}", f"cls_{i}"])
if has_obb:
output_names.append(f"angle_{i}")
dummy = torch.zeros(1, 3, imgsz, imgsz, dtype=torch.float32)
with torch.no_grad():
sample_outs = pt_model(dummy)
export_kwargs = {
"opset_version": opset,
"input_names": ["images"],
"output_names": output_names,
"do_constant_folding": True,
}
if "dynamo" in inspect.signature(torch.onnx.export).parameters:
export_kwargs["dynamo"] = False
torch.onnx.export(pt_model, dummy, str(onnx_path), **export_kwargs)
onnx_model = onnx.load(str(onnx_path))
onnx.checker.check_model(onnx_model)
out_shapes = [(name, tuple(tensor.shape)) for name, tensor in zip(output_names, sample_outs)]
print(f"Exported ONNX: {onnx_path} (opset={opset}, outputs={len(out_shapes)})")
for name, shape in out_shapes:
print(f" {name}: {shape}")
return class_names, out_shapes
def build_rknn(
onnx_path: Path,
rknn_path: Path,
target: str,
quant: bool,
quant_dtype: str,
dataset_txt: Path | None,
) -> None:
"""Compile ONNX model to RKNN (INT8 quantized when quant=True)."""
rknn = RKNN(verbose=False)
try:
ret = rknn.config(
mean_values=[[0, 0, 0]],
std_values=[[255, 255, 255]],
target_platform=target,
quantized_dtype=quant_dtype,
quantized_algorithm="normal",
quantized_method="channel",
optimization_level=3,
)
if ret != 0:
raise RuntimeError(f"rknn.config failed with code {ret}")
ret = rknn.load_onnx(model=str(onnx_path))
if ret != 0:
raise RuntimeError(f"rknn.load_onnx failed with code {ret}")
ret = rknn.build(
do_quantization=quant,
dataset=str(dataset_txt) if (quant and dataset_txt is not None) else None,
)
if ret != 0:
raise RuntimeError(f"rknn.build failed with code {ret}")
rknn_path.parent.mkdir(parents=True, exist_ok=True)
ret = rknn.export_rknn(str(rknn_path))
if ret != 0:
raise RuntimeError(f"rknn.export_rknn failed with code {ret}")
finally:
rknn.release()
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Convert Ultralytics YOLO .pt to INT8 .rknn for RK3588"
)
parser.add_argument("pt_path", type=Path, help="Input Ultralytics .pt model path")
parser.add_argument(
"-o",
"--output",
type=Path,
default=None,
help="Output .rknn path (default: <pt_path stem>.rknn)",
)
parser.add_argument("--imgsz", type=int, default=480, help="Square input size (default: 480)")
parser.add_argument("--target", default="rk3588", help="RKNN target platform (default: rk3588)")
parser.add_argument(
"--quant",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable INT8 quantization (default: True)",
)
parser.add_argument(
"--quant-dtype",
default="w8a8",
help="RKNN quantized_dtype (default: w8a8)",
)
parser.add_argument(
"--calib-dir",
type=Path,
default=None,
help="Calibration image directory (default: /opt/models/calib_images_<imgsz>)",
)
parser.add_argument(
"--rtsp",
default=None,
help="RTSP URL or video file to capture calibration frames from (default: SOURCE from .env)",
)
parser.add_argument(
"--env-file",
type=Path,
default=Path("/opt/feedmill/.env"),
help="Env file for default SOURCE and FFMPEG options (default: /opt/feedmill/.env)",
)
parser.add_argument(
"--calib-frames",
type=int,
default=50,
help="Number of calibration frames to collect (default: 50)",
)
parser.add_argument(
"--calib-interval",
type=float,
default=0.3,
help="Seconds between captured calibration frames (default: 0.3)",
)
parser.add_argument("--opset", type=int, default=12, help="ONNX opset version (default: 12)")
parser.add_argument(
"--keep-onnx",
action="store_true",
help="Keep intermediate .onnx file alongside output .rknn",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
pt_path = args.pt_path.resolve()
if not pt_path.is_file():
print(f"ERROR: Input .pt model not found: {pt_path}", file=sys.stderr)
return 1
rknn_path = (args.output or pt_path.with_suffix(".rknn")).resolve()
onnx_path = rknn_path.with_suffix(".onnx")
calib_dir = (args.calib_dir or Path(f"/opt/models/calib_images_{args.imgsz}")).resolve()
dataset_txt = None
calib_count = 0
if args.quant:
dataset_txt, calib_count = prepare_calibration_dataset(
calib_dir=calib_dir,
imgsz=args.imgsz,
target_count=args.calib_frames,
interval_sec=args.calib_interval,
rtsp_source=args.rtsp,
env_file=args.env_file,
)
class_names, _ = export_multibranch_onnx(
pt_path=pt_path,
onnx_path=onnx_path,
imgsz=args.imgsz,
opset=args.opset,
)
try:
build_rknn(
onnx_path=onnx_path,
rknn_path=rknn_path,
target=args.target,
quant=args.quant,
quant_dtype=args.quant_dtype,
dataset_txt=dataset_txt,
)
finally:
if not args.keep_onnx and onnx_path.exists():
onnx_path.unlink()
size_mb = rknn_path.stat().st_size / (1024 * 1024)
quant_desc = f"INT8 ({args.quant_dtype}, {calib_count} calib frames)" if args.quant else "FP16 (no quant)"
print("\nConversion complete:")
print(f" RKNN model : {rknn_path} ({size_mb:.2f} MB)")
print(f" Input size : {args.imgsz}x{args.imgsz}")
print(f" Target : {args.target}")
print(f" Precision : {quant_desc}")
print(f" Classes : {class_names}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+44
View File
@@ -29,6 +29,44 @@ class ControlHandler(BaseHTTPRequestHandler):
pass
return {}
def _is_peer_sync_request(self, body):
if self.headers.get("X-Peer-Sync", "").strip() == "1":
return True
if "X-API-Key" in self.headers:
return True
return isinstance(body, dict) and bool(body.get("source"))
def _get_batch_mode(self, status):
mode = (
getattr(self.server.store, "batch_mode", None)
or status.get("batch_mode")
or "manual"
)
return str(mode).strip().lower()
def _send_peer_ignored(self, action, status):
sack_c = status.get("sack_count", 0)
box_c = status.get("box_count", 0)
payload = {
"success": True,
"ignored": True,
"batch_mode": "auto",
"message": f"Ignored peer {action}: counter is in auto mode",
"batch_number": status.get("batch_number"),
"object_label": status.get("object_label") or "mixed",
"object_labels": ["sack", "box"],
"count": status.get("count", 0),
"sack_count": sack_c,
"box_count": box_c,
"counts": {"sack": sack_c, "box": box_c},
"plate": status.get("plate"),
"status": status.get("status")
or ("running" if status.get("active") else "stopped"),
}
if action == "stop":
payload["persisted"] = False
self._send_json(200, payload)
def do_POST(self):
clean_path = self.path.split("?", 1)[0].rstrip("/")
if clean_path in (
@@ -44,6 +82,9 @@ class ControlHandler(BaseHTTPRequestHandler):
):
body = self._read_json_body()
status = self.server.store.get_status()
if self._get_batch_mode(status) == "auto" and self._is_peer_sync_request(body):
self._send_peer_ignored("start", status)
return
if status["active"]:
if body and hasattr(self.server.store, "update_batch_metadata"):
self.server.store.update_batch_metadata(body)
@@ -89,6 +130,9 @@ class ControlHandler(BaseHTTPRequestHandler):
elif clean_path in ("/stop", "/api/stop", "/api/batch/stop"):
body = self._read_json_body()
status = self.server.store.get_status()
if self._get_batch_mode(status) == "auto" and self._is_peer_sync_request(body):
self._send_peer_ignored("stop", status)
return
if not status["active"]:
self._send_json(200, {
"success": False,
+35 -15
View File
@@ -35,12 +35,13 @@ CURRENT_BATCH_PATH = os.getenv("STATE_FILE", os.getenv("CURRENT_BATCH_PATH", f"{
CUTOFF_TIME = os.getenv("CUTOFF_TIME", os.getenv("DAILY_CUTOFF_TIME", "06:00"))
LIVE_STREAM_FRAME_PATH = os.getenv("LIVE_STREAM_FRAME_PATH", "/dev/shm/feedmill/live_frame.jpg")
LIVE_STREAM_META_PATH = os.getenv("LIVE_STREAM_META_PATH", "/dev/shm/feedmill/stream_meta.json")
SITE_NAME = os.getenv("SITE_NAME", "LIVE")
CAMERA_NAME = os.getenv("CAMERA_NAME", "")
STREAM_FPS_DISPLAY = os.getenv("STREAM_FPS_DISPLAY", "30.0")
STREAM_RESOLUTION_DISPLAY = os.getenv("STREAM_RESOLUTION_DISPLAY", "1280x720")
STREAM_ACCURACY_PCT = os.getenv("STREAM_ACCURACY_PCT", "98")
STREAM_ACCURACY_PCT = os.getenv("STREAM_ACCURACY_PCT", "-")
DASHBOARD_PORT = int(os.getenv("DASHBOARD_PORT", "5000"))
DASHBOARD_HOST = os.getenv("DASHBOARD_HOST", "0.0.0.0")
@@ -137,9 +138,10 @@ def get_next_batch_number_db(counting_date=None):
return 1
def _send_counter_command(endpoint, data=b""):
def _send_counter_command(endpoint, data=b"", headers=None):
url = f"{COUNTER_CONTROL_URL}/{endpoint}"
req = urllib.request.Request(url, data=data, method="POST")
req_headers = dict(headers) if headers else {}
req = urllib.request.Request(url, data=data, headers=req_headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=4.0) as resp:
return json.loads(resp.read().decode("utf-8")), resp.status
@@ -158,6 +160,21 @@ def _send_counter_command(endpoint, data=b""):
return {"success": False, "error": str(e)}, 500
def _read_stream_meta():
fps = STREAM_FPS_DISPLAY
res = STREAM_RESOLUTION_DISPLAY
try:
with open(LIVE_STREAM_META_PATH) as f:
meta = json.load(f)
if meta.get("fps"):
fps = str(meta["fps"])
if meta.get("width") and meta.get("height"):
res = f"{meta['width']}x{meta['height']}"
except (OSError, ValueError, KeyError, TypeError):
pass
return fps, res
@app.route("/")
def index():
return render_template(
@@ -165,9 +182,10 @@ def index():
site_name=SITE_NAME,
camera_name=CAMERA_NAME,
cutoff_time=CUTOFF_TIME,
stream_fps=STREAM_FPS_DISPLAY,
stream_resolution=STREAM_RESOLUTION_DISPLAY,
stream_fps=_read_stream_meta()[0],
stream_resolution=_read_stream_meta()[1],
stream_accuracy=STREAM_ACCURACY_PCT,
batch_mode=BATCH_MODE,
)
@@ -310,11 +328,12 @@ def api_batch_start(object_label=None):
if auth_err is not None:
return auth_err
raw = request.get_data()
data, code = (
_send_counter_command("start", data=raw)
if raw
else _send_counter_command("start")
)
kwargs = {}
if raw:
kwargs["data"] = raw
if "X-API-Key" in request.headers:
kwargs["headers"] = {"X-Peer-Sync": "1"}
data, code = _send_counter_command("start", **kwargs)
return jsonify(data), code
@@ -324,11 +343,12 @@ def api_batch_stop():
if auth_err is not None:
return auth_err
raw = request.get_data()
data, code = (
_send_counter_command("stop", data=raw)
if raw
else _send_counter_command("stop")
)
kwargs = {}
if raw:
kwargs["data"] = raw
if "X-API-Key" in request.headers:
kwargs["headers"] = {"X-Peer-Sync": "1"}
data, code = _send_counter_command("stop", **kwargs)
return jsonify(data), code
+32 -1
View File
@@ -12,6 +12,7 @@ import os
import signal
import sys
import time
import json
from collections import deque
from datetime import datetime
from pathlib import Path
@@ -57,6 +58,7 @@ CONF = float(os.getenv("CONF", "0.3"))
SACK_CONF = float(os.getenv("SACK_CONF")) if os.getenv("SACK_CONF") else CONF
BOX_CONF = float(os.getenv("BOX_CONF")) if os.getenv("BOX_CONF") else CONF
TRUCK_CONF = float(os.getenv("TRUCK_CONF")) if os.getenv("TRUCK_CONF") else CONF
IOU = float(os.getenv("IOU", "0.45"))
DEVICE = int(os.getenv("DEVICE", "0"))
# RKNN NPU core mask
@@ -80,7 +82,7 @@ DEDUP_FRAMES = int(os.getenv("DEDUP_FRAMES", "4"))
DEDUP_PX = float(os.getenv("DEDUP_PX", "35"))
DAILY_CUTOFF_TIME = os.getenv("DAILY_CUTOFF_TIME", "06:00")
BATCH_TIMEOUT_SECONDS = float(os.getenv("BATCH_TIMEOUT_SECONDS", "600"))
BATCH_TIMEOUT_SECONDS = float(os.getenv("BATCH_TIMEOUT_SECONDS", "30"))
MIN_OBJECT_PER_BATCH = int(os.getenv("MIN_OBJECT_PER_BATCH", "60"))
MIN_DURATION_PER_BATCH = int(os.getenv("MIN_DURATION_PER_BATCH", "60"))
BATCH_MODE = os.getenv("BATCH_MODE", "manual").strip().lower()
@@ -106,6 +108,9 @@ LIVE_STREAM_ENABLED = os.getenv("LIVE_STREAM_ENABLED", "false").lower() == "true
LIVE_STREAM_FRAME_PATH = os.getenv(
"LIVE_STREAM_FRAME_PATH", "/dev/shm/feedmill/live_frame.jpg"
)
LIVE_STREAM_META_PATH = os.getenv(
"LIVE_STREAM_META_PATH", "/dev/shm/feedmill/stream_meta.json"
)
LIVE_STREAM_QUALITY = int(os.getenv("LIVE_STREAM_QUALITY", "75"))
LIVE_STREAM_EVERY_N = int(os.getenv("LIVE_STREAM_EVERY_N", "2"))
@@ -1334,6 +1339,7 @@ def run():
conf=min(CONF, SACK_CONF, BOX_CONF, TRUCK_CONF, TRACK_LOW_THRESH_0),
num_classes=NUM_CLASSES,
score_sigmoid=SCORE_SIGMOID,
iou=IOU,
)
raw_cls_names = [
@@ -1380,6 +1386,8 @@ def run():
session_start = time.time()
frame_idx = 0
inf_ms = 0.0
prev_frame_time = time.monotonic()
proc_fps = 0.0
prev_gray = None
video_writer = None
crossing_times = deque()
@@ -1523,6 +1531,13 @@ def run():
zone_x1, zone_x2 = manual_x1, manual_x2
zone_source = "AUTO:MANUAL"
if not skip_inference:
truck_in_zone = any(
zone_x1 <= ((td["bbox"][0] + td["bbox"][2]) / 2.0) <= zone_x2
for td in truck_dets
)
store.set_truck_present(truck_in_zone)
draw_counting_zone_x(frame, zone_x1, zone_x2, w, h, zone_source)
for tdet in truck_dets:
@@ -1708,6 +1723,11 @@ def run():
cls_label = class_names_map.get(cls_id, "OBJ")
x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
flash = counted_cross_flash.get(tid, 0)
# mark counted center point: white dot with thin blue outline
cx_i = int((x1 + x2) / 2)
cy_i = int((y1 + y2) / 2)
cv2.circle(frame, (cx_i, cy_i), 4, (255, 255, 255), -1, cv2.LINE_AA)
cv2.circle(frame, (cx_i, cy_i), 4, (255, 140, 40) if cls_id == 1 else (0, 165, 255), 1, cv2.LINE_AA)
base_color = (255, 140, 40) if cls_id == 1 else C_COUNTED_BOX
color = C_GREEN if flash > 0 else base_color
obb = counted_obb_list[di] if di < len(counted_obb_list) else None
@@ -1783,6 +1803,17 @@ def run():
with open(tmp_path, "wb") as f:
f.write(jpeg.tobytes())
os.replace(tmp_path, LIVE_STREAM_FRAME_PATH)
now_mono = time.monotonic()
dt = now_mono - prev_frame_time
if dt > 0:
inst = 1.0 / dt
proc_fps = (proc_fps * 0.9 + inst * 0.1) if proc_fps else inst
prev_frame_time = now_mono
try:
with open(LIVE_STREAM_META_PATH, "w") as mf:
json.dump({"fps": round(proc_fps, 1), "width": w, "height": h}, mf)
except Exception:
pass
except Exception:
pass
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 512 512" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:affinity="https://www.affinity.studio/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1,0,0,1,-721.160506,-80.255975)">
<g transform="matrix(4.266667,0,0,4.266667,-4488.5584,-448.729773)">
<g transform="matrix(0.501566,0,0,0.501566,778.952023,-37.157747)">
<path d="M1068.036,447.958C1063.33,480.575 1035.237,505.675 1001.326,505.675C964.126,505.675 933.924,475.473 933.924,438.272C933.924,410.874 950.306,387.271 973.802,376.738C976.547,375.507 979.769,376.148 981.834,378.334C983.899,380.521 984.355,383.775 982.97,386.444C979.647,392.851 977.772,400.125 977.772,407.834C977.772,433.538 998.64,454.406 1024.344,454.406C1036.661,454.406 1047.868,449.613 1056.199,441.793C1058.39,439.738 1061.64,439.29 1064.304,440.678C1066.968,442.065 1068.465,444.985 1068.036,447.958ZM1048.13,463.703C1040.824,466.821 1032.784,468.547 1024.344,468.547C990.836,468.547 963.632,441.342 963.632,407.834C963.632,405.244 963.794,402.691 964.111,400.185C954.213,409.858 948.064,423.353 948.064,438.272C948.064,467.668 971.93,491.534 1001.326,491.534C1021.516,491.534 1039.098,480.278 1048.13,463.703Z"/>
</g>
<g transform="matrix(0.579146,0,0,0.579146,628.129321,52.177941)">
<rect x="1023.747" y="123.981" width="207.202" height="207.202" style="fill:none;"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

+40
View File
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 512 512" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:affinity="https://www.affinity.studio/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1,0,0,1,-237.606825,-80.255975)">
<g transform="matrix(4.266667,0,0,4.266667,-4130.378838,-448.729773)">
<g transform="matrix(0.413869,0,0,0.413869,667.424485,0.417027)" fill="#FFFFFF">
<g transform="matrix(1.060796,0,0,1.060796,-57.209043,-22.977402)">
<path d="M1001.326,370.87C1038.527,370.87 1068.729,401.072 1068.729,438.272C1068.729,475.473 1038.527,505.675 1001.326,505.675C964.126,505.675 933.924,475.473 933.924,438.272C933.924,401.072 964.126,370.87 1001.326,370.87ZM1001.326,385.011C971.93,385.011 948.064,408.876 948.064,438.272C948.064,467.668 971.93,491.534 1001.326,491.534C1030.722,491.534 1054.588,467.668 1054.588,438.272C1054.588,408.876 1030.722,385.011 1001.326,385.011Z"/>
</g>
<g transform="matrix(0,1,-0.602072,0,1314.697559,-563.053977)">
<path d="M1012.494,360.97C1012.494,367.845 1009.134,373.427 1004.994,373.427C1000.855,373.427 997.494,367.845 997.494,360.97L997.494,337.608C997.494,330.732 1000.855,325.151 1004.994,325.151C1009.134,325.151 1012.494,330.732 1012.494,337.608L1012.494,360.97Z"/>
</g>
<g transform="matrix(0.707107,0.707107,-0.425729,0.425729,512.031417,-486.373353)">
<path d="M1012.494,360.97C1012.494,367.845 1009.134,373.427 1004.994,373.427C1000.855,373.427 997.494,367.845 997.494,360.97L997.494,337.608C997.494,330.732 1000.855,325.151 1004.994,325.151C1009.134,325.151 1012.494,330.732 1012.494,337.608L1012.494,360.97Z"/>
</g>
<g transform="matrix(1,-0,0,0.602072,-1.317865,135.418709)">
<path d="M1012.494,360.97C1012.494,367.845 1009.134,373.427 1004.994,373.427C1000.855,373.427 997.494,367.845 997.494,360.97L997.494,337.608C997.494,330.732 1000.855,325.151 1004.994,325.151C1009.134,325.151 1012.494,330.732 1012.494,337.608L1012.494,360.97Z"/>
</g>
<g transform="matrix(0.707107,-0.707107,0.425729,0.425729,75.362759,938.084851)">
<path d="M1012.494,360.97C1012.494,367.845 1009.134,373.427 1004.994,373.427C1000.855,373.427 997.494,367.845 997.494,360.97L997.494,337.608C997.494,330.732 1000.855,325.151 1004.994,325.151C1009.134,325.151 1012.494,330.732 1012.494,337.608L1012.494,360.97Z"/>
</g>
<g transform="matrix(-0,-1,0.602072,-0,697.154821,1446.934659)">
<path d="M1012.494,360.97C1012.494,367.845 1009.134,373.427 1004.994,373.427C1000.855,373.427 997.494,367.845 997.494,360.97L997.494,337.608C997.494,330.732 1000.855,325.151 1004.994,325.151C1009.134,325.151 1012.494,330.732 1012.494,337.608L1012.494,360.97Z"/>
</g>
<g transform="matrix(-0.707107,-0.707107,0.425729,-0.425729,1499.820963,1374.753508)">
<path d="M1012.494,360.97C1012.494,367.845 1009.134,373.427 1004.994,373.427C1000.855,373.427 997.494,367.845 997.494,360.97L997.494,337.608C997.494,330.732 1000.855,325.151 1004.994,325.151C1009.134,325.151 1012.494,330.732 1012.494,337.608L1012.494,360.97Z"/>
</g>
<g transform="matrix(-0.707107,0.707107,-0.425729,-0.425729,1936.48962,-49.704695)">
<path d="M1012.494,360.97C1012.494,367.845 1009.134,373.427 1004.994,373.427C1000.855,373.427 997.494,367.845 997.494,360.97L997.494,337.608C997.494,330.732 1000.855,325.151 1004.994,325.151C1009.134,325.151 1012.494,330.732 1012.494,337.608L1012.494,360.97Z"/>
</g>
<g transform="matrix(-1,0,-0,-0.602072,2009.393044,751.643581)">
<path d="M1012.494,360.97C1012.494,367.845 1009.134,373.427 1004.994,373.427C1000.855,373.427 997.494,367.845 997.494,360.97L997.494,337.608C997.494,330.732 1000.855,325.151 1004.994,325.151C1009.134,325.151 1012.494,330.732 1012.494,337.608L1012.494,360.97Z"/>
</g>
</g>
<g transform="matrix(0.579146,0,0,0.579146,430.848092,52.177941)">
<rect x="1023.747" y="123.981" width="207.202" height="207.202" style="fill:none;"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.5 KiB

+30 -19
View File
@@ -178,6 +178,7 @@
color: var(--text-muted); cursor: pointer; font-size: 18px; line-height: 1;
display: inline-flex; align-items: center; justify-content: center;
}
.btn-theme img { width: 20px; height: 20px; display: block; }
/* ── Main ── */
.main {
@@ -792,15 +793,14 @@
background: rgba(0,0,0,0.18);
}
.modal-table th:nth-child(1), .modal-table td:nth-child(1) { width: 9%; }
.modal-table th:nth-child(2), .modal-table td:nth-child(2) { width: 14%; }
.modal-table th:nth-child(3), .modal-table td:nth-child(3) { width: 11%; }
.modal-table th:nth-child(2), .modal-table td:nth-child(2) { width: 15%; }
.modal-table th:nth-child(3), .modal-table td:nth-child(3) { width: 13%; }
.modal-table th:nth-child(4), .modal-table td:nth-child(4),
.modal-table th:nth-child(5), .modal-table td:nth-child(5) { width: 10%; }
.modal-table th:nth-child(6), .modal-table td:nth-child(6) { width: 10%; }
.modal-table th:nth-child(7), .modal-table td:nth-child(7) { width: 10%; }
.modal-table th:nth-child(8), .modal-table td:nth-child(8) { width: 10%; }
.modal-table th:nth-child(9), .modal-table td:nth-child(9) { width: 9%; }
.modal-table th:nth-child(10), .modal-table td:nth-child(10) { width: 7%; }
.modal-table th:nth-child(6), .modal-table td:nth-child(6) { width: 11%; }
.modal-table th:nth-child(7), .modal-table td:nth-child(7) { width: 11%; }
.modal-table th:nth-child(8), .modal-table td:nth-child(8) { width: 11%; }
.modal-table th:nth-child(9), .modal-table td:nth-child(9) { width: 10%; }
.modal-table .mono { font-family: var(--mono); font-weight: 600; }
.modal-empty {
color: var(--text-muted); font-size: 12px; padding: 16px; text-align: center;
@@ -884,7 +884,7 @@
<div class="site-name">{{ site_name }}</div>
<div class="site-line">Counting Day: <span id="current-date">--</span></div>
</div>
<button class="btn-theme" id="themeToggle" title="Mode terang" type="button" aria-label="Ganti tema">&#9788;</button>
<button class="btn-theme" id="themeToggle" title="Mode terang" type="button" aria-label="Ganti tema"><img id="themeIcon" src="{{ url_for('static', filename='img/sun_light mode.svg') }}?v=2" alt="sun" width="20" height="20"></button>
</div>
</header>
@@ -902,11 +902,11 @@
<span class="bc-dot"></span>
<span id="bcStatusText">STOPPED / IDLE</span>
</span>
<span class="bc-mode-tag"><i class="fas fa-hand-pointer"></i> MANUAL TRIGGER</span>
<span class="bc-mode-tag" id="bcModeTag">{% if batch_mode == 'auto' %}<i class="fas fa-robot"></i> AUTO MODE{% else %}<i class="fas fa-hand-pointer"></i> MANUAL TRIGGER{% endif %}</span>
</div>
<div class="bc-info-row">
<div class="bc-main-info" id="bcMainInfo">Sistem Siap Menghitung</div>
<div class="bc-sub-info" id="bcSubInfo">Sistem idle. Klik "Start Batch" untuk menghitung karung dan box sekaligus.</div>
<div class="bc-sub-info" id="bcSubInfo">{% if batch_mode == 'auto' %}Mode otomatis aktif. Batch dimulai otomatis saat karung/box melintas.{% else %}Sistem idle. Klik "Start Batch" untuk menghitung karung dan box sekaligus.{% endif %}</div>
</div>
</div>
<div class="bc-right">
@@ -1023,7 +1023,7 @@
<div class="side-card">
<div class="side-card-title">akurasi data stream</div>
<div class="acc-bar"><div class="acc-fill" id="accuracy-fill" data-accuracy="{{ stream_accuracy }}"></div></div>
<div class="acc-hint">Konfidensi {{ stream_accuracy }}% · Terakhir diupdate <span id="acc-updated">--</span></div>
<div class="acc-hint">Konfidensi - · Terakhir diupdate <span id="acc-updated">--</span></div>
</div>
<div class="side-card">
<div class="side-card-title">keterangan deteksi</div>
@@ -1193,7 +1193,6 @@
<th>Mulai</th>
<th>Selesai</th>
<th>Durasi</th>
<th>Porsi</th>
</tr>
</thead>
<tbody id="modal-table-body"></tbody>
@@ -1290,10 +1289,14 @@ function chartThemeColors() {
}
function syncThemeToggleUi() {
const icon = document.getElementById('themeIcon');
const sunUrl = "{{ url_for('static', filename='img/sun_light mode.svg') }}?v=2";
const moonUrl = "{{ url_for('static', filename='img/moon_dark mode.svg') }}";
const btn = document.getElementById('themeToggle');
if (!btn) return;
const light = getTheme() === 'light';
btn.innerHTML = light ? '&#9790;' : '&#9788;';
if (icon) icon.src = light ? moonUrl : sunUrl;
if (icon) icon.alt = light ? 'moon' : 'sun';
btn.title = light ? 'Mode gelap' : 'Mode terang';
btn.setAttribute('aria-label', light ? 'Ganti ke mode gelap' : 'Ganti ke mode terang');
}
@@ -1341,7 +1344,7 @@ document.addEventListener('DOMContentLoaded', () => {
}
const accFill = document.getElementById('accuracy-fill');
if (accFill) accFill.style.width = `${accFill.dataset.accuracy || 98}%`;
if (accFill) accFill.style.width = `${accFill.dataset.accuracy || '-'}%`;
loadSummary();
loadCurrentBatch();
loadChartData(7);
@@ -1391,8 +1394,11 @@ async function loadCurrentBatch() {
const svcCamDot = document.getElementById('svc-cam-dot');
// Control bar elements
const batchMode = (data.batch_mode || '{{ batch_mode|default("manual") }}').toLowerCase();
const isAuto = batchMode === 'auto';
const bcStatusBadge = document.getElementById('bcStatusBadge');
const bcStatusText = document.getElementById('bcStatusText');
const bcModeTag = document.getElementById('bcModeTag');
const bcMainInfo = document.getElementById('bcMainInfo');
const bcSubInfo = document.getElementById('bcSubInfo');
const btnStart = document.getElementById('btnBatchStart');
@@ -1400,6 +1406,12 @@ async function loadCurrentBatch() {
const lblNextBatch = document.getElementById('lblNextBatch');
const lblCurrBatch = document.getElementById('lblCurrBatch');
if (bcModeTag) {
bcModeTag.innerHTML = isAuto
? '<i class="fas fa-robot"></i> AUTO MODE'
: '<i class="fas fa-hand-pointer"></i> MANUAL TRIGGER';
}
if (svcCamEl) svcCamEl.textContent = videoActive ? 'Streaming' : 'Standby';
if (svcCamDot) svcCamDot.style.background = videoActive ? 'var(--green)' : 'var(--yellow-line)';
@@ -1473,7 +1485,9 @@ async function loadCurrentBatch() {
bcMainInfo.textContent = `Siap Menghitung (Batch #${currentBatchState.next_batch_number})`;
}
if (bcSubInfo) {
bcSubInfo.textContent = 'Sistem idle. Klik "Start Batch" untuk menghitung karung dan box sekaligus.';
bcSubInfo.textContent = isAuto
? 'Mode otomatis aktif. Batch dimulai otomatis saat karung/box melintas.'
: 'Sistem idle. Klik "Start Batch" untuk menghitung karung dan box sekaligus.';
}
if (btnStart) {
btnStart.style.display = 'inline-flex';
@@ -1969,7 +1983,6 @@ async function showDayDetail(date) {
const typePill = bType === 'mixed'
? '<span class="type-pill mixed">MIXED</span>'
: `<span class="type-pill ${bType}">${bType.toUpperCase()}</span>`;
const pct = total > 0 ? (b.count / total) * 100 : 0;
return `
<tr>
<td class="mono">#${b.batch_number}</td>
@@ -1981,7 +1994,6 @@ async function showDayDetail(date) {
<td>${formatTime(b.start_time)}</td>
<td>${formatTime(b.end_time)}</td>
<td>${b.duration_minutes} menit</td>
<td class="mono">${pct.toFixed(1)}%</td>
</tr>`;
}).join('');
@@ -1996,10 +2008,9 @@ async function showDayDetail(date) {
<td style="font-size:10px; color:var(--text-muted);">${batches[0] ? formatTime(batches[0].start_time) : '--'}</td>
<td style="font-size:10px; color:var(--text-muted);">${batches[batches.length - 1] ? formatTime(batches[batches.length - 1].end_time) : '--'}</td>
<td style="font-weight:700;">${Math.round(totalDuration * 10) / 10} menit</td>
<td class="mono" style="font-weight:700;">100%</td>
</tr>`;
} else {
tableHtml = `<tr><td colspan="10" class="modal-empty">Tidak ada batch pada tanggal ini</td></tr>`;
tableHtml = `<tr><td colspan="9" class="modal-empty">Tidak ada batch pada tanggal ini</td></tr>`;
}
document.getElementById('modal-table-body').innerHTML = tableHtml;
+88
View File
@@ -1,6 +1,7 @@
import json
import sqlite3
import tempfile
import time
import unittest
from pathlib import Path
from unittest.mock import patch
@@ -218,6 +219,93 @@ class BatchStoreUnifiedBatchTests(unittest.TestCase):
)
store.db.close()
def test_default_batch_timeout_is_30_seconds(self):
store = self.make_store()
self.addCleanup(store.db.close)
self.assertEqual(store.batch_timeout, 30.0)
def test_auto_mode_truck_present_prevents_timeout_until_truck_leaves(self):
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_timeout=0.15,
min_object_per_batch=1,
min_duration_per_batch=0,
batch_mode="auto",
logger=lambda _message: None,
)
self.addCleanup(store.shutdown)
store.set_truck_present(True)
store.record_counted_object_crossing(1, object_label="sack")
time.sleep(0.25)
self.assertTrue(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 0
)
store.set_truck_present(False)
time.sleep(0.25)
self.assertFalse(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
)
def test_auto_mode_truck_entering_cancels_running_timeout(self):
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_timeout=0.15,
min_object_per_batch=1,
min_duration_per_batch=0,
batch_mode="auto",
logger=lambda _message: None,
)
self.addCleanup(store.shutdown)
store.record_counted_object_crossing(1, object_label="sack")
time.sleep(0.05)
store.set_truck_present(True)
time.sleep(0.20)
self.assertTrue(store.get_status()["active"])
store.set_truck_present(False)
time.sleep(0.25)
self.assertFalse(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
)
def test_auto_mode_closes_after_timeout_when_no_truck(self):
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_timeout=0.15,
min_object_per_batch=1,
min_duration_per_batch=0,
batch_mode="auto",
logger=lambda _message: None,
)
self.addCleanup(store.shutdown)
store.record_counted_object_crossing(1, object_label="sack")
time.sleep(0.25)
self.assertFalse(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
)
if __name__ == "__main__":
unittest.main()
+109
View File
@@ -15,6 +15,7 @@ TEST_ROOT = Path(tempfile.mkdtemp(prefix="feedmill-dashboard-", dir="/tmp/openco
os.environ["DB_PATH"] = str(TEST_ROOT / "import.db")
os.environ["STATE_FILE"] = str(TEST_ROOT / "import-state.json")
import batch_store
import counter_dashboard
from counter_control import start_control_server
@@ -80,6 +81,21 @@ class DashboardUnifiedBatchTests(unittest.TestCase):
self.assertIn('id="modalStopBatchBoxCount"', html)
self.assertIn('id="modalStopBatchPlate"', html)
def test_dashboard_renders_mode_badge_for_auto_and_manual(self):
with patch.object(counter_dashboard, "BATCH_MODE", "auto"):
auto_html = self.client.get("/").get_data(as_text=True)
self.assertIn(
'id="bcModeTag"><i class="fas fa-robot"></i> AUTO MODE</span>',
auto_html,
)
with patch.object(counter_dashboard, "BATCH_MODE", "manual"):
manual_html = self.client.get("/").get_data(as_text=True)
self.assertIn(
'id="bcModeTag"><i class="fas fa-hand-pointer"></i> MANUAL TRIGGER</span>',
manual_html,
)
def test_daily_export_has_sack_and_box_columns(self):
counting_date = counter_dashboard.get_counting_date()
self.seed_batch(counting_date)
@@ -322,6 +338,99 @@ class DashboardUnifiedBatchTests(unittest.TestCase):
self.assertEqual(send.call_count, 1)
self.assertEqual(send.call_args[0][0], "start")
self.assertIn(b"B 1234 XYZ", send.call_args[1]["data"])
self.assertEqual(send.call_args[1]["headers"], {"X-Peer-Sync": "1"})
def test_peer_sync_forwards_peer_header_on_start_and_stop(self):
with patch("counter_dashboard._get_peer_api_token", return_value="secret-token"):
for endpoint, action in (("/api/batch/start", "start"), ("/api/batch/stop", "stop")):
with self.subTest(endpoint=endpoint, peer=True):
with patch(
"counter_dashboard._send_counter_command",
return_value=({"success": True}, 200),
) as send:
resp = self.client.post(
endpoint,
headers={"X-API-Key": "secret-token"},
json={"source": "fcp-semarang"},
)
self.assertEqual(resp.status_code, 200)
self.assertEqual(send.call_args[0][0], action)
self.assertEqual(send.call_args[1]["headers"], {"X-Peer-Sync": "1"})
with self.subTest(endpoint=endpoint, peer=False):
with patch(
"counter_dashboard._send_counter_command",
return_value=({"success": True}, 200),
) as send:
resp = self.client.post(endpoint)
self.assertEqual(resp.status_code, 200)
send.assert_called_once_with(action)
def test_peer_sync_ignored_in_auto_mode_while_local_stop_works(self):
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_timeout=60.0,
min_object_per_batch=1,
min_duration_per_batch=0,
batch_mode="auto",
logger=lambda _message: None,
)
self.addCleanup(store.shutdown)
server = start_control_server(store, host="127.0.0.1", port=0)
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
port = server.server_address[1]
def post(path, payload=None, peer=False):
raw = json.dumps(payload).encode("utf-8") if payload is not None else b""
headers = {"Content-Type": "application/json"} if payload is not None else {}
if peer:
headers["X-Peer-Sync"] = "1"
req = urllib.request.Request(
f"http://127.0.0.1:{port}{path}",
data=raw,
headers=headers,
method="POST",
)
with urllib.request.urlopen(req, timeout=2) as resp:
return resp.status, json.loads(resp.read().decode("utf-8"))
code, start_res = post(
"/api/batch/start",
payload={"source": "fcp-semarang", "plate": "B 1234 XYZ"},
peer=True,
)
self.assertEqual(code, 200)
self.assertTrue(start_res["success"])
self.assertTrue(start_res["ignored"])
self.assertEqual(start_res["object_labels"], ["sack", "box"])
self.assertFalse(store.get_status()["active"])
store.record_counted_object_crossing(1, object_label="sack")
self.assertTrue(store.get_status()["active"])
code, stop_res = post(
"/api/batch/stop",
payload={"source": "fcp-semarang"},
peer=True,
)
self.assertEqual(code, 200)
self.assertTrue(stop_res["success"])
self.assertTrue(stop_res["ignored"])
self.assertEqual(stop_res["object_labels"], ["sack", "box"])
self.assertTrue(store.get_status()["active"])
code, local_stop = post("/api/batch/stop", payload=None, peer=False)
self.assertEqual(code, 200)
self.assertTrue(local_stop["success"])
self.assertFalse(local_stop.get("ignored", False))
self.assertFalse(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
)
def tearDownModule():