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
25 changed files with 963 additions and 404 deletions

No files matched your search

+4 -2
View File
@@ -8,6 +8,7 @@ __pycache__/
*.pyc
*.pyo
venv/
venv-convert/
.venv/
# Data / state
@@ -17,16 +18,17 @@ current_batch.json
bytetrack_current_batch.json
batch_crossings.csv
# Models / binaries — track only .pt; converted artifacts stay local
# Models / binaries
*.rknn
*.pt
*.onnx
*.engine
# Runtime artifacts
/dev/shm/
*.log
*.jpg
*.png
calib_images/
# Superpowers / scratch
.superpowers/
+22 -16
View File
@@ -2,37 +2,36 @@
## Project Overview
Feedmill is a production edge counter for feed sacks and boxes. YOLO runs on edge hardware over an RTSP camera stream — NVIDIA Jetson (TensorRT, `.engine`) or Rockchip RK3588 NPU (RKNN, `.rknn`); backend is picked by `MODEL_PATH` suffix. 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
1. Camera: `connect_stream(SOURCE)` in `counter_live_rknn.py:run()` reads RTSP frames.
2. Optional motion gate skips inference when frame diff is below `MOTION_THRESHOLD`.
3. Inference: `create_model(MODEL_PATH)` picks `TRTYOLO` (`.engine`/`.trt`) or `RKNNYOLO` (`.rknn`); both subclass `YOLODetector` (shared letterbox preprocess + decode) and `_infer` returns raw output tensors.
3. Inference: `RKNNYOLO.__call__` (RKNN on NPU) returns detections.
4. Detections filtered by active batch class IDs (`0=sack`, `1=box`) and horizontal zone (`zone_x1..zone_x2`).
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
- `/` — runtime modules and config: `counter_live_rknn.py`, `batch_store.py`, `counter_control.py`, `counter_dashboard.py`, `convert_models.py` (pt→engine), `convert_to_rknn.py` (pt→rknn), `.env`, `config.env.example`.
- `/` — runtime modules and config: `counter_live_rknn.py`, `batch_store.py`, `counter_control.py`, `counter_dashboard.py`, `.env`, `config.env.example`.
- `tests/` — stdlib `unittest` suites.
- `docs/` — peer-sync and unified-batch specs/plans.
- `templates/` — `dashboard.html` (Jinja, Chart.js).
- `static/img/` — logos/icons.
- `model/` — `.pt` tracked; `.onnx`/`.engine`/`.rknn` gitignored (build via `convert_models.py` / `convert_to_rknn.py`). `/opt/models/` used in production (outside repo).
- `/opt/models/` — `.rknn` model files (outside repo).
## Development Commands
```bash
# venv
python3 -m venv /opt/feedmill/venv
/opt/feedmill/venv/bin/pip install -r requirements.txt -r requirements-jetson.txt # Jetson
/opt/feedmill/venv/bin/pip install -r requirements.txt -r requirements-rknn.txt # NanoPi
/opt/feedmill/venv/bin/pip install -r requirements.txt
# run counter
/opt/feedmill/venv/bin/python /opt/feedmill/counter_live_rknn.py
@@ -48,9 +47,12 @@ 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`.
No build step, lint config, or package manifest beyond `requirements.txt`.
## Code Conventions & Common Patterns
@@ -62,30 +64,34 @@ 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
- `counter_live_rknn.py` — main pipeline entry (`if __name__ == "__main__": run()`), backend wrappers (`YOLODetector`/`RKNNYOLO`/`TRTYOLO`, `create_model`), ByteTrack, crossing logic.
- `counter_live_rknn.py` — main pipeline entry (`if __name__ == "__main__": run()`), RKNN wrapper, ByteTrack, crossing logic.
- `batch_store.py` — SQLite schema migration, `BatchStore`, batch lifecycle, cutoff watcher.
- `counter_control.py` — internal HTTP control server (`/status`, `/start*`, `/stop`).
- `counter_dashboard.py` — Flask app, reporting, XLSX export, peer sync.
- `config.env.example` / `.env` — all runtime configuration.
- `requirements.txt` (common) + `requirements-jetson.txt` (pycuda; tensorrt from JetPack) + `requirements-rknn.txt` (rknn-toolkit-lite2) — Python dependencies.
- `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 venv at `/opt/feedmill/venv` with `--system-site-packages` (JetPack `tensorrt` visible).
- Dependencies: `numpy<2`, `opencv-python`, `flask`, `python-dotenv`, `openpyxl`, plus platform backend: RKNN runtime (`rknn-toolkit-lite2`, RK3588) or `tensorrt`+`pycuda` (Jetson).
- Models: `.rknn` (float, rk3588, via `convert_to_rknn.py` — needs `/dev/rknpu`, so run on NanoPi/x86) or `.engine` (`convert_models.py`, on Jetson). `NUM_CLASSES` must match model (3).
- 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 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.
+10 -15
View File
@@ -1,11 +1,11 @@
# Edge Deploy
# Edge RKNN Deploy
Production counter: **direct LAN RTSP** + **YOLO** (RKNN on RK3588 / TensorRT on Jetson) + **ByteTrack** + SQLite batch store + Flask dashboard + FCP peer sync.
Production counter: **direct LAN RTSP** + **YOLO RKNN** + **ByteTrack** + SQLite batch store + Flask dashboard + FCP peer sync.
## Quick install
```bash
# 1. Copy this folder to the target device (NanoPi RK3588 or Jetson)
# 1. Copy this folder to the RK3588 device
sudo mkdir -p /opt/feedmill
sudo cp -r feedmill/* /opt/feedmill/
sudo chown -R $(whoami):$(whoami) /opt/feedmill
@@ -28,19 +28,14 @@ Dashboard: `http://<ip-device>:7000` (internal control: `127.0.0.1:5000`).
## Model checklist
Backend follows the `MODEL_PATH` suffix: `.rknn` → RKNN (NanoPi), `.engine`/`.trt` → TensorRT (Jetson).
Set `.env` to the exported `.rknn` model path and make sure class order matches:
- **Jetson:** convert `.pt` → `.engine` with `convert_models.py` (uses ultralytics + TensorRT, run on the Jetson).
- **NanoPi:** convert `.pt` → `.onnx` → `.rknn` with `convert_to_rknn.py`. rknn-toolkit2 needs `/dev/rknpu` (Rockchip host) — run it on the NanoPi or an x86 PC, not on Jetson.
Set `.env` so class order matches:
1. `NUM_CLASSES=3` (sack, box, truck) — required; the `.engine` output layout is decoded with it (wrong value drops box/truck)
1. `NUM_CLASSES=3` (sack, box, truck)
2. `COUNTED_CLASS_IDS=0,1` (sack + box counted)
3. `TRUCK_CLASS_ID=2` (truck defines counting zone only)
4. `COUNT_AXIS=y`
5. `CROSS_DIRECTION=down`
6. `MODEL_PATH` → your model (e.g. `/opt/models/y11_11_20.rknn` or `.../zenai_fcp_20261120.engine`), `IMGSZ=320`
6. `MODEL_PATH=/opt/models/y11_11_20.rknn`, `IMGSZ=320`
---
@@ -65,17 +60,14 @@ nc -zv <camera-ip> 554
```bash
sudo systemctl is-active feedmill-counter feedmill-dashboard
# NanoPi (RKNN):
PYTHONNOUSERSITE=1 /opt/feedmill/venv/bin/python -c "from rknnlite.api import RKNNLite; print('rknn ok')"
# Jetson (TensorRT):
PYTHONNOUSERSITE=1 /opt/feedmill/venv/bin/python -c "import tensorrt, pycuda.driver; print('trt ok')"
sudo journalctl -u feedmill-counter -n 20 --no-pager
```
Good signs:
- `Stream ready!`
- `RKNN model loaded: ...` or `TensorRT engine loaded: ...`
- `RKNN model loaded: ...`
- `Frame 100 | Batch ...`
---
@@ -91,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).
+12 -10
View File
@@ -1,18 +1,18 @@
# Edge Sack Counter (Production)
# RKNN Sack Counter (Production)
RTSP + YOLO + ByteTrack line-crossing counter for **sacks**, **boxes**, and **trucks** (truck = zone only) on edge hardware: NVIDIA Jetson (TensorRT) and Rockchip RK3588 (RKNN). Unified batches report separate Sack and Box totals.
RTSP + YOLO RKNN + ByteTrack line-crossing counter for **sacks**, **boxes**, and **trucks** (truck = zone only) on Rockchip edge hardware. Unified batches report separate Sack and Box totals.
## Architecture
- **Input:** Direct LAN camera RTSP (low latency)
- **Inference:** YOLO with backend selected by `MODEL_PATH` suffix — `.engine`/`.trt` → TensorRT (Jetson), `.rknn` → RKNN (RK3588 NPU). 3 classes: sack=0, box=1, truck=2
- **Inference:** YOLO `.rknn` on RK3588 NPU (3 classes: sack=0, box=1, truck=2)
- **Logic:** Line crossing (`sack` + `box` counts) via `batch_store.py`; truck bbox defines horizontal counting zone
- **Output:** `feedmill.db` + `current_batch.json` (+ optional CSV/video/live frame)
- **Dashboard:** Flask on port **7000**; internal control server on `127.0.0.1:5000`
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
@@ -40,30 +40,32 @@ See **[DEPLOY.md](DEPLOY.md)**.
| Variable | Purpose |
|----------|---------|
| `SOURCE` | Direct camera RTSP URL |
| `MODEL_PATH` | Model file; suffix picks backend: `.rknn` (RK3588) or `.engine` (Jetson) |
| `MODEL_PATH` | `.rknn` file path (`/opt/models/y11_11_20.rknn`) |
| `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
| File | Purpose |
|------|---------|
| `counter_live_rknn.py` | RTSP + YOLO (RKNN/TensorRT backend) + ByteTrack line crossing |
| `counter_live_rknn.py` | RTSP + RKNN YOLO + ByteTrack line crossing |
| `batch_store.py` | SQLite persistence, unified batches, schema migration |
| `counter_control.py` | Internal HTTP control server (127.0.0.1:5000) |
| `counter_dashboard.py` | Flask UI, reporting, XLSX export, peer sync |
| `config.env.example` | Env template |
| `convert_models.py` | Jetson: `.pt` → `.onnx` → `.engine` (TensorRT, `imgsz=320`) |
| `convert_to_rknn.py` | `.pt` → `.onnx` → `.rknn` float export for `rk3588` (run on x86 or a Rockchip host with `/dev/rknpu`) |
| `requirements.txt` / `requirements-jetson.txt` / `requirements-rknn.txt` | Common deps + per-platform backend deps |
| `feedmill-counter.service` | Counter systemd unit |
| `feedmill-dashboard.service` | Dashboard systemd unit |
| `install-services.sh` / `setup-venv.sh` | Install / venv setup |
+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):
+12 -7
View File
@@ -19,21 +19,21 @@ SOURCE=rtsp://user:pass@192.168.0.100:554/stream1
# FFmpeg capture options passed to cv2.VideoCapture (RTSP low-latency flags)
OPENCV_FFMPEG_CAPTURE_OPTIONS=rtsp_transport;tcp|fflags;nobuffer|flags;low_delay
# --- Model (suffix selects backend: .rknn → RKNN / RK3588, .engine/.trt → TensorRT / Jetson) ---
# Model file: .rknn exported with convert_to_rknn.py (NanoPi), .engine exported with convert_models.py (Jetson)
# --- RKNN model ---
# Path to exported .rknn model (YOLO format, e.g. yolo11n.rknn)
MODEL_PATH=/opt/models/yolo9t.rknn
# Input image size for the model (square, e.g. 320 → 320×320)
IMGSZ=320
# Use FP16 inference on NPU (true/false); currently unused in ByteTrack variant
HALF=false
# NPU core mask for RKNN backend only (1=core0, 2=core1, 3=core0+core1, 7=all three); ignored by TensorRT
# NPU core mask: 1=core0, 2=core1, 3=core0+core1, 7=all three
CORE_MASK=7
# Compute device index (reserved; not used at runtime)
DEVICE=0
# --- YOLO decoder ---
# Number of object classes the model outputs (3 = sack, box, truck); must match the model — decoder misdetects output layout if wrong
NUM_CLASSES=3
# Number of object classes the model outputs (1 = sack only)
NUM_CLASSES=1
# Apply sigmoid to raw class scores (true/false); set true if model head uses BCE logits
SCORE_SIGMOID=false
@@ -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
-33
View File
@@ -1,33 +0,0 @@
#!/usr/bin/env python3
"""Convert model/*.pt checkpoints to ONNX and TensorRT .engine files.
Each export runs in its own subprocess: exporting ONNX (imports onnxruntime)
and then an engine in one process leaves torch.cuda unavailable on this Jetson.
"""
import subprocess
import sys
from pathlib import Path
MODEL_DIR = Path(__file__).parent / "model"
IMGSZ = 320 # matches train_args imgsz of the checkpoints
def export(pt: Path, fmt: str) -> None:
code = (
"from ultralytics import YOLO; "
f"YOLO({str(pt)!r}).export(format={fmt!r}, imgsz={IMGSZ})"
)
subprocess.run([sys.executable, "-c", code], check=True)
def main() -> None:
pts = sorted(MODEL_DIR.glob("*.pt"))
if not pts:
raise SystemExit(f"no .pt files in {MODEL_DIR}")
for pt in pts:
for fmt in ("onnx", "engine"):
print(f"=== {pt.name} -> {fmt}", flush=True)
export(pt, fmt)
if __name__ == "__main__":
main()
+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())
-71
View File
@@ -1,71 +0,0 @@
#!/usr/bin/env python3
"""Convert model/*.pt checkpoints to .rknn (RK3588) via ONNX.
Conversion-time only: needs rknn-toolkit2 (not rknn-toolkit-lite2, which is
the NanoPi serving runtime). ONNX export runs in its own subprocess like
convert_models.py; rknn-toolkit2 pins its own onnx version, so the two
scripts are kept separate.
Recipe matches counter_live_rknn.py feeding uint8 RGB (1,H,W,3):
mean 0 / std 255 normalizes 0-255 -> 0-1 inside the graph.
Float build (no quantization) for parity with the Jetson engine.
"""
import subprocess
import sys
from pathlib import Path
from rknn.api import RKNN
MODEL_DIR = Path(__file__).parent / "model"
IMGSZ = 320
TARGET_PLATFORM = "rk3588"
ONNX_OPSET = 13 # rknn-toolkit2 rejects newer opsets
def export_onnx(pt: Path) -> Path:
code = (
"from ultralytics import YOLO; "
f"YOLO({str(pt)!r}).export(format='onnx', imgsz={IMGSZ}, opset={ONNX_OPSET})"
)
subprocess.run([sys.executable, "-c", code], check=True)
onnx = pt.with_suffix(".onnx")
if not onnx.exists():
raise SystemExit(f"onnx export missing: {onnx}")
return onnx
def to_rknn(pt: Path) -> None:
onnx = export_onnx(pt)
rknn_path = pt.with_suffix(".rknn")
print(f"=== {pt.name} -> {rknn_path.name} (onnx {onnx.name})", flush=True)
rknn = RKNN(verbose=False)
try:
rknn.config(
mean_values=[[0, 0, 0]],
std_values=[[255, 255, 255]],
target_platform=TARGET_PLATFORM,
)
ret = rknn.load_onnx(model=str(onnx))
if ret != 0:
raise SystemExit(f"load_onnx failed: {onnx}")
ret = rknn.build(do_quantization=False)
if ret != 0:
raise SystemExit(f"rknn build failed: {pt}")
ret = rknn.export_rknn(str(rknn_path))
if ret != 0:
raise SystemExit(f"export_rknn failed: {rknn_path}")
finally:
rknn.release()
print(f"OK: {rknn_path} ({rknn_path.stat().st_size} bytes)", flush=True)
def main() -> None:
pts = sorted(MODEL_DIR.glob("*.pt"))
if not pts:
raise SystemExit(f"no .pt files in {MODEL_DIR}")
for pt in pts:
to_rknn(pt)
if __name__ == "__main__":
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
+53 -149
View File
@@ -8,11 +8,11 @@ import contextlib
import numpy as np
import cv2
import csv
import json
import os
import signal
import sys
import time
import json
from collections import deque
from datetime import datetime
from pathlib import Path
@@ -21,6 +21,7 @@ from dotenv import load_dotenv
load_dotenv()
from rknnlite.api import RKNNLite
from batch_store import BatchStore
from counter_control import start_control_server
@@ -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"))
@@ -530,11 +535,11 @@ def _xywhr_to_corners(cx, cy, w, h, angle):
return np.stack([p1, p2, p3, p4], axis=1)
class YOLODetector:
"""Shared letterbox preprocess + decode; backends implement _infer/release."""
class RKNNYOLO:
def __init__(
self,
model_path,
core_mask=1,
imgsz=320,
conf=0.3,
iou=0.45,
@@ -549,11 +554,21 @@ class YOLODetector:
self.num_keypoints = num_keypoints
self.score_sigmoid = score_sigmoid
def _infer(self, inp):
raise NotImplementedError
self.rknn = RKNNLite(verbose=False)
ret = self.rknn.load_rknn(model_path)
if ret != 0:
raise RuntimeError(f"Failed to load RKNN model: {model_path}")
ret = self.rknn.init_runtime(core_mask=core_mask)
if ret != 0:
raise RuntimeError(f"Failed to init RKNN runtime (core_mask={core_mask})")
def release(self):
raise NotImplementedError
try:
sdk_ver = self.rknn.get_sdk_version()
print(f"RKNN SDK version: {sdk_ver}")
except Exception:
pass
print(f"RKNN model loaded: {model_path} imgsz={imgsz} core_mask={core_mask}")
def _preprocess(self, frame):
h0, w0 = frame.shape[:2]
@@ -672,7 +687,7 @@ class YOLODetector:
inp = np.expand_dims(rgb, axis=0)
inp = np.ascontiguousarray(inp.astype(np.uint8))
outputs = self._infer(inp)
outputs = self.rknn.inference(inputs=[inp])
if len(outputs) == 0:
return []
@@ -777,147 +792,10 @@ class YOLODetector:
)
return detections
class RKNNYOLO(YOLODetector):
backend = "RKNN"
def __init__(
self,
model_path,
core_mask=1,
imgsz=320,
conf=0.3,
iou=0.45,
num_classes=1,
num_keypoints=0,
score_sigmoid=False,
):
super().__init__(
imgsz=imgsz,
conf=conf,
iou=iou,
num_classes=num_classes,
num_keypoints=num_keypoints,
score_sigmoid=score_sigmoid,
)
from rknnlite.api import RKNNLite # lazy: Jetson has no rknnlite
self.rknn = RKNNLite(verbose=False)
ret = self.rknn.load_rknn(model_path)
if ret != 0:
raise RuntimeError(f"Failed to load RKNN model: {model_path}")
ret = self.rknn.init_runtime(core_mask=core_mask)
if ret != 0:
raise RuntimeError(f"Failed to init RKNN runtime (core_mask={core_mask})")
try:
sdk_ver = self.rknn.get_sdk_version()
print(f"RKNN SDK version: {sdk_ver}")
except Exception:
pass
print(f"RKNN model loaded: {model_path} imgsz={imgsz} core_mask={core_mask}")
def _infer(self, inp):
return self.rknn.inference(inputs=[inp])
def release(self):
self.rknn.release()
class TRTYOLO(YOLODetector):
"""TensorRT engine backend (Jetson); same letterbox + decode as RKNN."""
backend = "TensorRT"
def __init__(
self,
model_path,
core_mask=None,
imgsz=320,
conf=0.3,
iou=0.45,
num_classes=1,
num_keypoints=0,
score_sigmoid=False,
):
super().__init__(
imgsz=imgsz,
conf=conf,
iou=iou,
num_classes=num_classes,
num_keypoints=num_keypoints,
score_sigmoid=score_sigmoid,
)
import pycuda.autoinit # noqa: F401 - one CUDA context per process
import pycuda.driver as cuda
import tensorrt as trt
self._cuda = cuda
runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING))
with open(model_path, "rb") as f:
raw = f.read()
# ultralytics .engine files prefix metadata: u32 LE length + JSON (same strip as ultralytics autobackend)
try:
meta_len = int.from_bytes(raw[:4], "little")
json.loads(raw[4 : 4 + meta_len].decode("utf-8"))
raw = raw[4 + meta_len :]
except (UnicodeDecodeError, ValueError):
pass # plain engine, no metadata prefix
self.engine = runtime.deserialize_cuda_engine(raw)
if self.engine is None:
raise RuntimeError(f"Failed to load TensorRT engine: {model_path}")
self.context = self.engine.create_execution_context()
self.stream = cuda.Stream()
in_name = out_name = None
for i in range(self.engine.num_io_tensors):
name = self.engine.get_tensor_name(i)
if self.engine.get_tensor_mode(name) == trt.TensorIOMode.INPUT:
in_name = name
else:
out_name = name
in_shape = tuple(self.engine.get_tensor_shape(in_name))
if len(in_shape) != 4 or in_shape[2] != imgsz or in_shape[3] != imgsz:
raise RuntimeError(
f"Engine input {in_shape} does not match imgsz={imgsz}; rebuild engine or set IMGSZ"
)
self._in_name = in_name
self._out_name = out_name
self.host_in = np.empty(in_shape, dtype=np.float32)
self.host_out = np.empty(
tuple(self.engine.get_tensor_shape(out_name)), dtype=np.float32
)
self.dev_in = cuda.mem_alloc(self.host_in.nbytes)
self.dev_out = cuda.mem_alloc(self.host_out.nbytes)
self.context.set_tensor_address(in_name, int(self.dev_in))
self.context.set_tensor_address(out_name, int(self.dev_out))
print(f"TensorRT engine loaded: {model_path} imgsz={imgsz}")
# warmup: first inference compiles CUDA kernels (~1s)
self._infer(np.zeros((1, imgsz, imgsz, 3), dtype=np.uint8))
def _infer(self, inp):
x = inp.astype(np.float32).transpose(0, 3, 1, 2) / 255.0
np.copyto(self.host_in, x)
self._cuda.memcpy_htod_async(self.dev_in, self.host_in, self.stream)
if not self.context.execute_async_v3(self.stream.handle):
raise RuntimeError("TensorRT execute_async_v3 failed")
self._cuda.memcpy_dtoh_async(self.host_out, self.dev_out, self.stream)
self.stream.synchronize()
return [self.host_out]
def release(self):
self.context = None
self.engine = None
def create_model(model_path, **kwargs):
"""Backend from model extension: .engine/.trt -> TensorRT, .rknn -> RKNN."""
if Path(model_path).suffix.lower() in {".engine", ".trt"}:
return TRTYOLO(model_path, **kwargs)
return RKNNYOLO(model_path, **kwargs)
# =============================================================================
# Drawing helpers
# =============================================================================
@@ -1454,13 +1332,14 @@ def run():
CROSS_CSV, ["batch", "frame", "timestamp", "object_id"]
)
model = create_model(
model = RKNNYOLO(
model_path=MODEL_PATH,
core_mask=CORE_MASK,
imgsz=IMGSZ,
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 = [
@@ -1507,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()
@@ -1525,7 +1406,7 @@ def run():
prev_batch_key = (store.current_batch_number or 0, store.current_batch_object_label)
print(
f"{model.backend}+ByteTrack counter | {w}x{h} @ {fps}fps | axis={count_axis} line={line_pos} | cross={CROSS_DIRECTION}"
f"RKNN+ByteTrack counter | {w}x{h} @ {fps}fps | axis={count_axis} line={line_pos} | cross={CROSS_DIRECTION}"
)
print(f"Model: {MODEL_PATH} | imgsz={IMGSZ} | core_mask={CORE_MASK}")
print(
@@ -1650,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:
@@ -1835,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
@@ -1910,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
+2 -7
View File
@@ -46,16 +46,11 @@ done
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
if [[ -f /etc/nv_tegra_release ]]; then
BACKEND_SMOKE="import tensorrt, pycuda.driver"
else
BACKEND_SMOKE="from rknnlite.api import RKNNLite"
fi
PYTHONNOUSERSITE=1 "${VENV_DIR}/bin/python" -c "
${BACKEND_SMOKE}
from rknnlite.api import RKNNLite
import cv2
from flask import Flask
print('import ok | backend + opencv + flask')
print('import ok | rknn + opencv + flask')
" || {
echo "Import check failed — fix venv before starting services."
exit 1
BIN
View File
Binary file not shown.
Binary file not shown.
-5
View File
@@ -1,5 +0,0 @@
# tensorrt ships with JetPack in /usr/lib/python3.10/dist-packages;
# venv runs with --system-site-packages, so no pip install needed.
# pycuda has no aarch64 wheel: built from source, needs nvcc (/usr/local/cuda)
# and boost headers (libboost-dev).
pycuda
-1
View File
@@ -1 +0,0 @@
rknn-toolkit-lite2
+1
View File
@@ -1,4 +1,5 @@
numpy<2
rknn-toolkit-lite2
opencv-python
flask
python-dotenv
+3 -17
View File
@@ -20,29 +20,15 @@ fi
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
sudo -u "${SERVICE_USER}" "${VENV_DIR}/bin/pip" install --upgrade pip
sudo -u "${SERVICE_USER}" "${VENV_DIR}/bin/pip" install -r "${INSTALL_DIR}/requirements.txt"
# Platform backend: Jetson (TensorRT) vs NanoPi (RKNN)
if [[ -f /etc/nv_tegra_release ]]; then
PLATFORM_REQS="${INSTALL_DIR}/requirements-jetson.txt"
else
PLATFORM_REQS="${INSTALL_DIR}/requirements-rknn.txt"
fi
sudo -u "${SERVICE_USER}" "${VENV_DIR}/bin/pip" install -r "${INSTALL_DIR}/requirements.txt" -r "${PLATFORM_REQS}"
if [[ -f /etc/nv_tegra_release ]]; then
PLATFORM_SMOKE="import tensorrt, pycuda.driver
print('tensorrt + pycuda ok')"
else
PLATFORM_SMOKE="from rknnlite.api import RKNNLite
print('rknnlite ok')"
fi
sudo -u "${SERVICE_USER}" PYTHONNOUSERSITE=1 "${VENV_DIR}/bin/python" -c "
from rknnlite.api import RKNNLite
import cv2
import flask
import dotenv
import openpyxl
${PLATFORM_SMOKE}
print('venv ok | opencv + flask + dotenv + openpyxl + backend')
print('venv ok | rknn + opencv + flask + dotenv + openpyxl')
"
echo ""
+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():