Initial commit: RKNN sack counter + dashboard + peer sync
This commit is contained in:
commit
94660b8387
25 files changed
+8115
No files matched your search
+36
@@ -0,0 +1,36 @@
|
||||
# Secrets / env
|
||||
.env
|
||||
peer_sync_token.txt
|
||||
docs/peer_sync_token.txt
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
venv/
|
||||
.venv/
|
||||
|
||||
# Data / state
|
||||
*.db
|
||||
*.db-*
|
||||
current_batch.json
|
||||
bytetrack_current_batch.json
|
||||
batch_crossings.csv
|
||||
|
||||
# Models / binaries
|
||||
*.rknn
|
||||
*.pt
|
||||
*.onnx
|
||||
|
||||
# Runtime artifacts
|
||||
/dev/shm/
|
||||
*.log
|
||||
*.jpg
|
||||
*.png
|
||||
|
||||
# Superpowers / scratch
|
||||
.superpowers/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,90 @@
|
||||
# Repository Guidelines
|
||||
|
||||
## 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.
|
||||
|
||||
## 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: `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).
|
||||
|
||||
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`.
|
||||
|
||||
## Key Directories
|
||||
|
||||
- `/` — 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.
|
||||
- `/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
|
||||
|
||||
# run counter
|
||||
/opt/feedmill/venv/bin/python /opt/feedmill/counter_live_rknn.py
|
||||
|
||||
# run dashboard
|
||||
/opt/feedmill/venv/bin/python /opt/feedmill/counter_dashboard.py
|
||||
|
||||
# tests
|
||||
cd /opt/feedmill && /opt/feedmill/venv/bin/python -m unittest discover -s tests -v
|
||||
|
||||
# services
|
||||
sudo systemctl status feedmill-counter feedmill-dashboard
|
||||
sudo journalctl -u feedmill-counter -f
|
||||
sudo ./install-services.sh
|
||||
sudo ./uninstall-services.sh
|
||||
```
|
||||
|
||||
No build step, lint config, or package manifest beyond `requirements.txt`.
|
||||
|
||||
## Code Conventions & Common Patterns
|
||||
|
||||
- Config constants: `UPPER_SNAKE_CASE` loaded from env via `os.getenv` (counter ~lines 27-121; dashboard ~32-52). `.env` loaded with `python-dotenv`.
|
||||
- Classes: `PascalCase`; functions/variables: `snake_case`.
|
||||
- Class IDs fixed: sack=0, box=1, truck=2; labels normalized to `sack`/`box`/`mixed`.
|
||||
- State guarded by `BatchStore.state_lock`; SQLite opened with `check_same_thread=False`.
|
||||
- Error handling: stream reconnect loop, model release on failure, try/except around DB ops, JSON error responses in dashboard.
|
||||
- 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.
|
||||
|
||||
## Important Files
|
||||
|
||||
- `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` — Python dependencies.
|
||||
- `feedmill-counter.service`, `feedmill-dashboard.service` — systemd units.
|
||||
- `API.md`, `DEPLOY.md`, `README.md` — API, deployment, overview docs.
|
||||
|
||||
## 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`.
|
||||
- Install scripts require root; services run as root with `PYTHONNOUSERSITE=1`.
|
||||
- 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).
|
||||
- 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.
|
||||
@@ -0,0 +1,360 @@
|
||||
# counter_dashboard.py — API Documentation
|
||||
|
||||
## Page
|
||||
|
||||
### `GET /`
|
||||
Renders the main dashboard HTML page (`dashboard.html`).
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### `GET /api/live-video`
|
||||
MJPEG streaming endpoint. Serves live frames from the path configured in `LIVE_STREAM_FRAME_PATH` (default `/dev/shm/feedmill/live_frame.jpg`) as `multipart/x-mixed-replace`.
|
||||
|
||||
**Response:** JPEG stream with `--frame` boundary delimiters.
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/current-batch`
|
||||
Returns the currently active batch's data or idle state with next batch number.
|
||||
|
||||
**Success response (running):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"active": true,
|
||||
"status": "running",
|
||||
"batch_mode": "manual",
|
||||
"counting_date": "2024-01-01",
|
||||
"batch_number": 12,
|
||||
"object_label": "mixed",
|
||||
"count": 342,
|
||||
"sack_count": 210,
|
||||
"box_count": 132,
|
||||
"object_labels": ["sack", "box"],
|
||||
"counts": {"sack": 210, "box": 132},
|
||||
"plate": null,
|
||||
"source": null,
|
||||
"fcp_batch_number": null,
|
||||
"start_time": "2024-01-01T14:30:00",
|
||||
"last_detection_time": "2024-01-01T14:35:00"
|
||||
}
|
||||
```
|
||||
|
||||
`count` is the combined total. `sack_count` and `box_count` are the separate class totals.
|
||||
|
||||
**Stopped response (no active batch, 200):**
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"active": false,
|
||||
"status": "stopped",
|
||||
"batch_mode": "manual",
|
||||
"error": "No active batch",
|
||||
"count": 0,
|
||||
"sack_count": 0,
|
||||
"box_count": 0,
|
||||
"object_labels": [],
|
||||
"counts": {"sack": 0, "box": 0},
|
||||
"plate": null,
|
||||
"source": null,
|
||||
"fcp_batch_number": null,
|
||||
"batch_number": null,
|
||||
"next_batch_number": 13,
|
||||
"counting_date": "2024-01-01"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/batch/start`
|
||||
Manually starts a new unified batch on the counter engine. One batch counts sacks and boxes together and reports separate class totals.
|
||||
|
||||
**Success response (200):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Started Batch #13",
|
||||
"batch_number": 13,
|
||||
"object_label": "mixed",
|
||||
"object_labels": ["sack", "box"],
|
||||
"count": 0,
|
||||
"sack_count": 0,
|
||||
"box_count": 0,
|
||||
"counts": {"sack": 0, "box": 0},
|
||||
"plate": null,
|
||||
"status": "running"
|
||||
}
|
||||
```
|
||||
|
||||
**Legacy aliases:** `POST /api/batch/start/sack` and `POST /api/batch/start/box` still work and start the same unified batch. The class argument is ignored.
|
||||
|
||||
**Error response (503 if engine offline):**
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"error": "Engine counter tidak aktif. Pastikan service feedmill-counter berjalan."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/batch/stop`
|
||||
Manually stops the currently active batch, saves records to SQLite (`batches` and `daily_summaries`), and returns state to idle.
|
||||
|
||||
**Success response (200):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Batch #13 stopped (342 items)",
|
||||
"batch_number": 13,
|
||||
"object_label": "mixed",
|
||||
"count": 342,
|
||||
"sack_count": 210,
|
||||
"box_count": 132,
|
||||
"object_labels": ["sack", "box"],
|
||||
"counts": {"sack": 210, "box": 132},
|
||||
"plate": null,
|
||||
"persisted": true,
|
||||
"status": "stopped"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/batch/status`
|
||||
Returns real-time status of the counter engine and batch state.
|
||||
|
||||
**Success response (200):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"active": true,
|
||||
"status": "running",
|
||||
"batch_mode": "manual",
|
||||
"batch_number": 13,
|
||||
"object_label": "mixed",
|
||||
"count": 342,
|
||||
"sack_count": 210,
|
||||
"box_count": 132,
|
||||
"object_labels": ["sack", "box"],
|
||||
"counts": {"sack": 210, "box": 132},
|
||||
"plate": null,
|
||||
"counting_date": "2024-01-01",
|
||||
"engine_alive": true
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/previous-batch`
|
||||
Returns the most recently completed batch from the `batches` database table, with computed `duration_minutes`.
|
||||
|
||||
**Success response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"date": "2024-01-01",
|
||||
"batch_number": 11,
|
||||
"object_label": "mixed",
|
||||
"count": 287,
|
||||
"sack_count": 190,
|
||||
"box_count": 97,
|
||||
"start_time": "2024-01-01T14:00:00",
|
||||
"end_time": "2024-01-01T14:27:00",
|
||||
"duration_minutes": 27.0
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/summary`
|
||||
Returns today, yesterday, and all-time aggregate statistics plus average per day and best day.
|
||||
|
||||
**Success response:**
|
||||
```json
|
||||
{
|
||||
"today": {
|
||||
"date": "2024-01-01",
|
||||
"total_count": 1500,
|
||||
"total_batches": 8,
|
||||
"count": 1500,
|
||||
"sack_count": 980,
|
||||
"box_count": 520
|
||||
},
|
||||
"yesterday": {
|
||||
"date": "2023-12-31",
|
||||
"total_count": 1342,
|
||||
"total_batches": 7,
|
||||
"count": 1342,
|
||||
"sack_count": 860,
|
||||
"box_count": 482
|
||||
},
|
||||
"all_time": {
|
||||
"grand_total": 50000,
|
||||
"grand_batches": 260,
|
||||
"total_days": 45,
|
||||
"count": 50000,
|
||||
"sack_count": 32000,
|
||||
"box_count": 18000
|
||||
},
|
||||
"average_per_day": 1111.1,
|
||||
"best_day": {
|
||||
"date": "2023-12-15",
|
||||
"count": 2100
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/daily-data`
|
||||
Returns daily summary rows for charting.
|
||||
|
||||
**Query params:**
|
||||
| Param | Type | Default | Description |
|
||||
|--------|------|---------|---------------------------------|
|
||||
| `days` | int | 30 | Number of days to look back |
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"total_count": 1500,
|
||||
"total_batches": 8,
|
||||
"avg_per_batch": 187.5
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/day-detail/<date>`
|
||||
Returns all batch records for a specific `counting_date` along with summary totals.
|
||||
|
||||
**Path params:**
|
||||
| Param | Type | Description |
|
||||
|--------|--------|------------------------|
|
||||
| `date` | string | Date in `YYYY-MM-DD` |
|
||||
|
||||
**Success response:**
|
||||
```json
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"total_count": 1500,
|
||||
"total_batches": 8,
|
||||
"sack_count": 980,
|
||||
"box_count": 520,
|
||||
"total_duration_minutes": 216.0,
|
||||
"avg_duration_minutes": 27.0,
|
||||
"batches": [
|
||||
{
|
||||
"batch_number": 1,
|
||||
"object_label": "mixed",
|
||||
"count": 187,
|
||||
"sack_count": 120,
|
||||
"box_count": 67,
|
||||
"start_time": "2024-01-01T08:00:00",
|
||||
"end_time": "2024-01-01T08:27:00",
|
||||
"duration_minutes": 27.0
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/recent-batches`
|
||||
Returns the most recent batches with computed durations.
|
||||
|
||||
**Query params:**
|
||||
| Param | Type | Default | Description |
|
||||
|---------|------|---------|---------------------------------|
|
||||
| `limit` | int | 10 | Max number of batches to return |
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"batch_number": 8,
|
||||
"object_label": "mixed",
|
||||
"count": 213,
|
||||
"sack_count": 140,
|
||||
"box_count": 73,
|
||||
"start_time": "2024-01-01T16:30:00",
|
||||
"end_time": "2024-01-01T16:58:00",
|
||||
"duration_minutes": 28.0
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/available-dates`
|
||||
Returns all dates with data from the `daily_summaries` table, ordered by date descending.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"total_count": 1500,
|
||||
"total_batches": 8
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Export Endpoints (XLSX)
|
||||
|
||||
### `GET /api/export-daily-csv`
|
||||
Exports batch detail records for the last N days as an `.xlsx` file.
|
||||
|
||||
**Query params:**
|
||||
| Param | Type | Default | Description |
|
||||
|--------|------|---------|-----------------------------|
|
||||
| `days` | int | 30 | Number of days to look back |
|
||||
|
||||
**Response:** XLSX file download with columns: Date, Batch #, Type, Sack, Box, Total, Start Time, End Time, Duration (min).
|
||||
|
||||
Filename format: `{SITE_NAME}_daily_records_{timestamp}.xlsx`
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/export-day-csv/<date>`
|
||||
Exports all batch records for a single date as an `.xlsx` file.
|
||||
|
||||
**Path params:**
|
||||
| Param | Type | Description |
|
||||
|--------|--------|----------------------|
|
||||
| `date` | string | Date in `YYYY-MM-DD` |
|
||||
|
||||
**Response:** XLSX file download with columns: Batch Number, Type, Sack, Box, Total, Start Time, End Time, Duration (min).
|
||||
|
||||
Filename format: `{SITE_NAME}_day_detail_{date}.xlsx`
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
All endpoints return `{"success": false, "error": "<message>"}` with HTTP 500 on unexpected errors. Database-unavailable errors (`sqlite3.OperationalError`) return HTTP 200 with an empty/default data structure. The `/api/live-video` endpoint returns HTTP 503 if the frame file is not found.
|
||||
|
||||
---
|
||||
|
||||
## Peer Sync (FCP)
|
||||
|
||||
`POST /api/batch/start` and `POST /api/batch/stop` accept an optional `X-API-Key` header.
|
||||
|
||||
- If the header is **absent**, the request is processed normally (dashboard UI).
|
||||
- If the header is **present**, it must equal `PEER_API_TOKEN` (from `.env` or `docs/peer_sync_token.txt`); otherwise returns `401 {"success": false, "error": "unauthorized"}`.
|
||||
|
||||
Request body (JSON) is forwarded to the internal control server, supporting:
|
||||
`source`, `object_label`, `object_labels`, `fcp_batch_number`, `counting_date`,
|
||||
`plate`, `do_numbers`, `expected_sack`, `expected_box`, `started_at`,
|
||||
`net_sack`, `net_box`, `ended_at`.
|
||||
|
||||
Responses include `object_labels`, `counts`, and `plate` for peer compatibility.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Edge RKNN Deploy
|
||||
|
||||
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 RK3588 device
|
||||
sudo mkdir -p /opt/feedmill
|
||||
sudo cp -r feedmill/* /opt/feedmill/
|
||||
sudo chown -R $(whoami):$(whoami) /opt/feedmill
|
||||
|
||||
# 2. Configure
|
||||
cd /opt/feedmill
|
||||
cp config.env.example .env
|
||||
nano .env # SOURCE, MODEL_PATH, CAMERA_NAME, PEER_API_TOKEN, etc.
|
||||
sed -i 's/\r$//' .env
|
||||
|
||||
# 3. Venv + services
|
||||
chmod +x setup-venv.sh install-services.sh
|
||||
sudo ./setup-venv.sh
|
||||
sudo ./install-services.sh
|
||||
```
|
||||
|
||||
Dashboard: `http://<ip-device>:7000` (internal control: `127.0.0.1:5000`).
|
||||
|
||||
---
|
||||
|
||||
## Model checklist
|
||||
|
||||
Set `.env` to the exported `.rknn` model path and make sure class order matches:
|
||||
|
||||
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=/opt/models/y11_11_20.rknn`, `IMGSZ=320`
|
||||
|
||||
---
|
||||
|
||||
## Direct camera RTSP
|
||||
|
||||
Set in `.env`:
|
||||
|
||||
```env
|
||||
SOURCE=rtsp://user:pass@192.168.x.x:554/stream1
|
||||
```
|
||||
|
||||
Test before install:
|
||||
|
||||
```bash
|
||||
ffplay -rtsp_transport tcp -t 5 "$SOURCE"
|
||||
nc -zv <camera-ip> 554
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Validation checklist
|
||||
|
||||
```bash
|
||||
sudo systemctl is-active feedmill-counter feedmill-dashboard
|
||||
PYTHONNOUSERSITE=1 /opt/feedmill/venv/bin/python -c "from rknnlite.api import RKNNLite; print('rknn ok')"
|
||||
sudo journalctl -u feedmill-counter -n 20 --no-pager
|
||||
```
|
||||
|
||||
Good signs:
|
||||
|
||||
- `Stream ready!`
|
||||
- `RKNN model loaded: ...`
|
||||
- `Frame 100 | Batch ...`
|
||||
|
||||
---
|
||||
|
||||
## Logs & restart
|
||||
|
||||
```bash
|
||||
sudo journalctl -u feedmill-counter -f
|
||||
sudo systemctl restart feedmill-counter # after .env change
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Peer sync (FCP)
|
||||
|
||||
- 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).
|
||||
- See `docs/peer_sync_handoff.md`.
|
||||
@@ -0,0 +1,71 @@
|
||||
# RKNN Sack Counter (Production)
|
||||
|
||||
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 `.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`).
|
||||
|
||||
## Deploy
|
||||
|
||||
See **[DEPLOY.md](DEPLOY.md)**.
|
||||
|
||||
| Item | Default |
|
||||
|------|---------|
|
||||
| Install path | `/opt/feedmill` |
|
||||
| Venv | `/opt/feedmill/venv` |
|
||||
| DB | `/opt/feedmill/feedmill.db` |
|
||||
| Dashboard | `http://<device-ip>:7000` |
|
||||
| Cutoff | `06:00` |
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `sudo systemctl status feedmill-counter feedmill-dashboard` | Services running? |
|
||||
| `sudo journalctl -u feedmill-counter -f` | Live logs |
|
||||
| `sudo systemctl restart feedmill-counter` | After `.env` change |
|
||||
| `sudo ./uninstall-services.sh` | Remove services |
|
||||
|
||||
## Key env vars
|
||||
|
||||
| Variable | Purpose |
|
||||
|----------|---------|
|
||||
| `SOURCE` | Direct camera RTSP URL |
|
||||
| `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) |
|
||||
| `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` |
|
||||
| `DAILY_CUTOFF_TIME` / `CUTOFF_TIME` | Daily cutoff (`06:00`) |
|
||||
| `PEER_API_TOKEN` | Shared secret for FCP peer sync (`X-API-Key`) |
|
||||
|
||||
## Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `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 |
|
||||
| `feedmill-counter.service` | Counter systemd unit |
|
||||
| `feedmill-dashboard.service` | Dashboard systemd unit |
|
||||
| `install-services.sh` / `setup-venv.sh` | Install / venv setup |
|
||||
| `tests/` | stdlib unittest suites |
|
||||
| `docs/peer_sync_handoff.md` | FCP peer-sync spec |
|
||||
| `API.md` | Dashboard API reference |
|
||||
|
||||
The active production path is `counter_live_rknn.py`.
|
||||
+611
@@ -0,0 +1,611 @@
|
||||
"""
|
||||
Production batch persistence for the edge counter.
|
||||
Persists counted objects grouped into batches (closed by idle timeout or cutoff).
|
||||
"""
|
||||
import json
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def ensure_batch_schema(conn):
|
||||
"""Create batch tables and migrate legacy rows to separate class counters."""
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS batches (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
batch_number INTEGER NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
count INTEGER NOT NULL,
|
||||
sack_count INTEGER NOT NULL DEFAULT 0,
|
||||
box_count INTEGER NOT NULL DEFAULT 0,
|
||||
start_time TEXT NOT NULL,
|
||||
end_time TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, batch_number, camera_name, object_label)
|
||||
)
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS daily_summaries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
total_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_batches INTEGER NOT NULL DEFAULT 0,
|
||||
sack_count INTEGER NOT NULL DEFAULT 0,
|
||||
box_count INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, camera_name, object_label)
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
for table in ("batches", "daily_summaries"):
|
||||
columns = {row[1] for row in cur.execute(f"PRAGMA table_info({table})")}
|
||||
for column in ("sack_count", "box_count"):
|
||||
if column not in columns:
|
||||
cur.execute(
|
||||
f"ALTER TABLE {table} ADD COLUMN {column} INTEGER NOT NULL DEFAULT 0"
|
||||
)
|
||||
|
||||
batch_columns = {row[1] for row in cur.execute("PRAGMA table_info(batches)")}
|
||||
for col_name, col_type in (
|
||||
("source", "TEXT"),
|
||||
("fcp_batch_number", "INTEGER"),
|
||||
("plate", "TEXT"),
|
||||
("do_numbers", "TEXT"),
|
||||
("expected_sack", "INTEGER"),
|
||||
("expected_box", "INTEGER"),
|
||||
):
|
||||
if col_name not in batch_columns:
|
||||
cur.execute(f"ALTER TABLE batches ADD COLUMN {col_name} {col_type}")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE batches
|
||||
SET sack_count = count
|
||||
WHERE object_label = 'sack' AND sack_count = 0 AND count > 0
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE batches
|
||||
SET box_count = count
|
||||
WHERE object_label = 'box' AND box_count = 0 AND count > 0
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE batches
|
||||
SET object_label = 'sack'
|
||||
WHERE object_label = 'mixed' AND sack_count > 0 AND box_count = 0
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE batches
|
||||
SET object_label = 'box'
|
||||
WHERE object_label = 'mixed' AND box_count > 0 AND sack_count = 0
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE daily_summaries
|
||||
SET sack_count = total_count
|
||||
WHERE object_label = 'sack' AND sack_count = 0 AND total_count > 0
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE daily_summaries
|
||||
SET box_count = total_count
|
||||
WHERE object_label = 'box' AND box_count = 0 AND total_count > 0
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
class BatchStore:
|
||||
def __init__(
|
||||
self,
|
||||
db_path,
|
||||
state_file,
|
||||
camera_name,
|
||||
object_label='sack',
|
||||
cutoff_time='06:00',
|
||||
batch_timeout=600.0,
|
||||
min_object_per_batch=60,
|
||||
min_duration_per_batch=60,
|
||||
carry_ids=50,
|
||||
batch_mode='manual',
|
||||
logger=print,
|
||||
):
|
||||
self.db_path = db_path
|
||||
self.state_file = Path(state_file)
|
||||
self.camera_name = camera_name
|
||||
self.object_label = object_label
|
||||
self.cutoff_time_str = cutoff_time
|
||||
datetime.strptime(cutoff_time, '%H:%M')
|
||||
|
||||
self.batch_timeout = float(batch_timeout)
|
||||
self.min_object_per_batch = int(min_object_per_batch)
|
||||
self.min_duration_per_batch = int(min_duration_per_batch)
|
||||
self.carry_ids = int(carry_ids)
|
||||
self.batch_mode = str(batch_mode).strip().lower() if batch_mode else 'manual'
|
||||
self.log = logger
|
||||
|
||||
self.state_lock = threading.Lock()
|
||||
self.batch_timer = None
|
||||
self.previous_state = None
|
||||
self.shutdown_event = threading.Event()
|
||||
|
||||
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
self.state_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self.db = sqlite3.connect(db_path, check_same_thread=False)
|
||||
self._init_db()
|
||||
self.current_state = self._load_state()
|
||||
self.previous_state = self.current_state
|
||||
|
||||
def _init_db(self):
|
||||
ensure_batch_schema(self.db)
|
||||
|
||||
def get_counting_date(self, dt=None):
|
||||
if dt is None:
|
||||
dt = datetime.now()
|
||||
cutoff = datetime.strptime(self.cutoff_time_str, '%H:%M').time()
|
||||
if cutoff.hour < 12:
|
||||
if dt.time() < cutoff:
|
||||
return (dt.date() - timedelta(days=1)).isoformat()
|
||||
return dt.date().isoformat()
|
||||
if dt.time() < cutoff:
|
||||
return dt.date().isoformat()
|
||||
return (dt.date() + timedelta(days=1)).isoformat()
|
||||
|
||||
def _normalize_batch_label(self, label=None):
|
||||
raw = str(label or '').strip().lower()
|
||||
if raw in ('mixed', 'all', 'both'):
|
||||
return 'mixed'
|
||||
if raw in ('box', '1'):
|
||||
return 'box'
|
||||
if raw in ('sack', '0'):
|
||||
return 'sack'
|
||||
default_raw = str(self.object_label or 'sack').split(',')[0].strip().lower()
|
||||
return 'box' if default_raw == 'box' else 'sack'
|
||||
|
||||
def _normalize_item_label(self, label=None):
|
||||
raw = str(label or 'sack').strip().lower()
|
||||
return 'box' if raw == 'box' else 'sack'
|
||||
|
||||
def _load_state(self):
|
||||
if not self.state_file.exists():
|
||||
return None
|
||||
try:
|
||||
with open(self.state_file, 'r', encoding='utf-8') as f:
|
||||
state = json.load(f)
|
||||
legacy_label = self._normalize_batch_label(state.get('object_label'))
|
||||
if 'sack_count' not in state:
|
||||
state['sack_count'] = (
|
||||
int(state.get('count', 0))
|
||||
if legacy_label in ('sack', 'mixed')
|
||||
else 0
|
||||
)
|
||||
if 'box_count' not in state:
|
||||
state['box_count'] = (
|
||||
int(state.get('count', 0)) if legacy_label == 'box' else 0
|
||||
)
|
||||
state['sack_count'] = int(state.get('sack_count', 0))
|
||||
state['box_count'] = int(state.get('box_count', 0))
|
||||
state['count'] = state['sack_count'] + state['box_count']
|
||||
state['object_label'] = 'mixed'
|
||||
legacy_ids = state.get('counted_event_ids', [])
|
||||
state['counted_event_ids'] = [
|
||||
f"{legacy_label}:{event_id}" if ':' not in str(event_id) else event_id
|
||||
for event_id in legacy_ids
|
||||
]
|
||||
current_date = self.get_counting_date()
|
||||
if state.get('counting_date') != current_date:
|
||||
self.log(
|
||||
f"State file belongs to previous counting day ({state.get('counting_date')}). "
|
||||
'Finalizing before fresh start.'
|
||||
)
|
||||
self._insert_batch(
|
||||
state['counting_date'],
|
||||
state['batch_number'],
|
||||
state['count'],
|
||||
state['start_time'],
|
||||
datetime.now().isoformat(),
|
||||
object_label='mixed',
|
||||
sack_count=state['sack_count'],
|
||||
box_count=state['box_count'],
|
||||
metadata=state,
|
||||
)
|
||||
self.state_file.unlink(missing_ok=True)
|
||||
return None
|
||||
self.log(
|
||||
f"Resumed batch #{state['batch_number']} ({state['object_label']}) from {state['start_time']} "
|
||||
f"with count={state['count']}"
|
||||
)
|
||||
if self.batch_mode != 'manual':
|
||||
self._reset_batch_timer()
|
||||
return state
|
||||
except Exception as exc:
|
||||
self.log(f'Failed to load state file: {exc}')
|
||||
return None
|
||||
|
||||
def save_state(self):
|
||||
if self.current_state is None:
|
||||
self.state_file.unlink(missing_ok=True)
|
||||
return
|
||||
with open(self.state_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.current_state, f, indent=2, ensure_ascii=False)
|
||||
|
||||
def get_next_batch_number(self, counting_date):
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(MAX(batch_number), 0)
|
||||
FROM batches
|
||||
WHERE counting_date = ? AND camera_name = ?
|
||||
""",
|
||||
(counting_date, self.camera_name),
|
||||
)
|
||||
return cur.fetchone()[0] + 1
|
||||
|
||||
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
|
||||
|
||||
def update_batch_metadata(self, metadata):
|
||||
if not isinstance(metadata, dict):
|
||||
return
|
||||
with self.state_lock:
|
||||
if self.current_state is None:
|
||||
return
|
||||
for key in (
|
||||
'source',
|
||||
'fcp_batch_number',
|
||||
'plate',
|
||||
'do_numbers',
|
||||
'expected_sack',
|
||||
'expected_box',
|
||||
):
|
||||
if key in metadata and metadata[key] is not None:
|
||||
self.current_state[key] = metadata[key]
|
||||
self.save_state()
|
||||
|
||||
def _reset_batch_timer(self):
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
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')
|
||||
|
||||
def record_counted_object_crossing(self, track_id, object_label=None):
|
||||
"""Record one newly counted object crossing."""
|
||||
with self.state_lock:
|
||||
counting_date = self.get_counting_date()
|
||||
started_new = False
|
||||
if self.current_state is None:
|
||||
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)
|
||||
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)
|
||||
started_new = True
|
||||
|
||||
item_label = self._normalize_item_label(object_label)
|
||||
event_key = f'{item_label}:{track_id}'
|
||||
if event_key not in self.current_state['counted_event_ids']:
|
||||
self.current_state['count'] += 1
|
||||
self.current_state[f'{item_label}_count'] += 1
|
||||
self.current_state['counted_event_ids'].append(event_key)
|
||||
self.log(
|
||||
f'Counted {item_label} (track {track_id}) | '
|
||||
f'batch #{self.current_state["batch_number"]} '
|
||||
f'total: {self.current_state["count"]}'
|
||||
)
|
||||
|
||||
self.current_state['last_detection_time'] = datetime.now().isoformat()
|
||||
self.save_state()
|
||||
if self.batch_mode != 'manual':
|
||||
self._reset_batch_timer()
|
||||
return self.current_state['count'], started_new
|
||||
|
||||
def record_ayam_crossing(self, track_id):
|
||||
return self.record_counted_object_crossing(track_id)
|
||||
|
||||
def end_batch(self, closed_by='manual'):
|
||||
with self.state_lock:
|
||||
return self._end_batch_locked(closed_by=closed_by)
|
||||
|
||||
def _end_batch_locked(self, closed_by='manual'):
|
||||
if self.current_state is None:
|
||||
return False
|
||||
|
||||
self.previous_state = self.current_state
|
||||
state = self.current_state
|
||||
batch_label = self._normalize_batch_label(state.get('object_label'))
|
||||
|
||||
start_time_obj = datetime.fromisoformat(state['start_time'])
|
||||
end_time_obj = datetime.now()
|
||||
duration_seconds = (end_time_obj - start_time_obj).total_seconds()
|
||||
|
||||
is_manual = (closed_by == 'manual' or self.batch_mode == 'manual')
|
||||
should_discard = False
|
||||
if not is_manual:
|
||||
if (state['count'] < self.min_object_per_batch
|
||||
or duration_seconds < self.min_duration_per_batch):
|
||||
should_discard = True
|
||||
|
||||
if should_discard:
|
||||
self.current_state = None
|
||||
self.save_state()
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.batch_timer = None
|
||||
self.log(
|
||||
f'Batch #{state["batch_number"]} ({batch_label}) discarded '
|
||||
f'(count={state["count"]}, duration={duration_seconds:.0f}s, closed_by={closed_by})'
|
||||
)
|
||||
return False
|
||||
|
||||
end_time = end_time_obj.isoformat()
|
||||
try:
|
||||
self._insert_batch(
|
||||
state['counting_date'],
|
||||
state['batch_number'],
|
||||
state['count'],
|
||||
state['start_time'],
|
||||
end_time,
|
||||
object_label=batch_label,
|
||||
sack_count=state.get('sack_count', 0),
|
||||
box_count=state.get('box_count', 0),
|
||||
metadata=state,
|
||||
)
|
||||
cps = state['count'] / duration_seconds if duration_seconds > 0 else 0
|
||||
self.log(
|
||||
f'Batch #{state["batch_number"]} ({batch_label}) ended | count={state["count"]} | '
|
||||
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by}'
|
||||
)
|
||||
except Exception as exc:
|
||||
self.log(f'Failed to persist batch: {exc}')
|
||||
return False
|
||||
|
||||
self.current_state = None
|
||||
self.save_state()
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.batch_timer = None
|
||||
return True
|
||||
|
||||
def _insert_batch(
|
||||
self,
|
||||
counting_date,
|
||||
batch_number,
|
||||
count,
|
||||
start_time,
|
||||
end_time,
|
||||
object_label=None,
|
||||
sack_count=0,
|
||||
box_count=0,
|
||||
metadata=None,
|
||||
):
|
||||
batch_label = 'mixed'
|
||||
sack_count = int(sack_count or 0)
|
||||
box_count = int(box_count or 0)
|
||||
if not sack_count and not box_count and count:
|
||||
# Legacy caller without separate counters: trust the row label.
|
||||
legacy_label = self._normalize_batch_label(object_label)
|
||||
if legacy_label == 'box':
|
||||
box_count = int(count)
|
||||
else:
|
||||
sack_count = int(count)
|
||||
if sack_count > 0 and box_count > 0:
|
||||
row_label = 'mixed'
|
||||
elif box_count > 0 and sack_count == 0:
|
||||
row_label = 'box'
|
||||
elif sack_count > 0 and box_count == 0:
|
||||
row_label = 'sack'
|
||||
else:
|
||||
row_label = batch_label
|
||||
meta = metadata if isinstance(metadata, dict) else {}
|
||||
do_nums = meta.get('do_numbers')
|
||||
if isinstance(do_nums, (list, tuple)):
|
||||
do_nums = json.dumps(list(do_nums), ensure_ascii=False)
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO batches
|
||||
(counting_date, batch_number, camera_name, object_label, count,
|
||||
sack_count, box_count, start_time, end_time,
|
||||
source, fcp_batch_number, plate, do_numbers, expected_sack, expected_box)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
counting_date,
|
||||
batch_number,
|
||||
self.camera_name,
|
||||
row_label,
|
||||
count,
|
||||
sack_count,
|
||||
box_count,
|
||||
start_time,
|
||||
end_time,
|
||||
meta.get('source'),
|
||||
meta.get('fcp_batch_number'),
|
||||
meta.get('plate'),
|
||||
do_nums,
|
||||
meta.get('expected_sack'),
|
||||
meta.get('expected_box'),
|
||||
),
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO daily_summaries
|
||||
(counting_date, camera_name, object_label, total_count, total_batches,
|
||||
sack_count, box_count)
|
||||
VALUES (?, ?, ?, ?, 1, ?, ?)
|
||||
ON CONFLICT(counting_date, camera_name, object_label)
|
||||
DO UPDATE SET
|
||||
total_count = total_count + excluded.total_count,
|
||||
total_batches = total_batches + excluded.total_batches,
|
||||
sack_count = sack_count + excluded.sack_count,
|
||||
box_count = box_count + excluded.box_count,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""",
|
||||
(counting_date, self.camera_name, batch_label, count, sack_count, box_count),
|
||||
)
|
||||
self.db.commit()
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0), COALESCE(SUM(total_batches), 0)
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ? AND camera_name = ?
|
||||
""",
|
||||
(counting_date, self.camera_name),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
self.log(
|
||||
f'Daily totals for {counting_date}: {row[0]} objects across {row[1]} batch(es)'
|
||||
)
|
||||
|
||||
def cutoff_watcher_loop(self):
|
||||
while not self.shutdown_event.is_set():
|
||||
time.sleep(60)
|
||||
with self.state_lock:
|
||||
if self.current_state is None:
|
||||
continue
|
||||
if self.current_state['counting_date'] != self.get_counting_date():
|
||||
self.log('Daily cutoff reached – finalizing batch')
|
||||
self._end_batch_locked(closed_by='cutoff')
|
||||
|
||||
def start_cutoff_watcher(self):
|
||||
t = threading.Thread(target=self.cutoff_watcher_loop, daemon=True)
|
||||
t.start()
|
||||
return t
|
||||
|
||||
@property
|
||||
def current_batch_number(self):
|
||||
if self.current_state is None:
|
||||
return 0
|
||||
return self.current_state['batch_number']
|
||||
|
||||
@property
|
||||
def current_batch_count(self):
|
||||
if self.current_state is None:
|
||||
return 0
|
||||
return self.current_state['count']
|
||||
|
||||
@property
|
||||
def current_batch_object_label(self):
|
||||
if self.current_state is None:
|
||||
return None
|
||||
return self._normalize_batch_label(self.current_state.get('object_label'))
|
||||
|
||||
def get_closed_total_for_day(self, counting_date=None):
|
||||
if counting_date is None:
|
||||
counting_date = self.get_counting_date()
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0)
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ? AND camera_name = ?
|
||||
""",
|
||||
(counting_date, self.camera_name),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return row[0] if row else 0
|
||||
|
||||
def display_total(self):
|
||||
return self.get_closed_total_for_day() + self.current_batch_count
|
||||
|
||||
def get_status(self):
|
||||
with self.state_lock:
|
||||
active = self.current_state is not None
|
||||
cdate = self.get_counting_date()
|
||||
obj_label = (
|
||||
self._normalize_batch_label(self.current_state.get('object_label'))
|
||||
if active
|
||||
else None
|
||||
)
|
||||
sack_count = self.current_state.get('sack_count', 0) if active else 0
|
||||
box_count = self.current_state.get('box_count', 0) if active else 0
|
||||
return {
|
||||
"active": active,
|
||||
"status": "running" if active else "stopped",
|
||||
"batch_mode": self.batch_mode,
|
||||
"batch_number": self.current_state['batch_number'] if active else None,
|
||||
"object_label": obj_label,
|
||||
"object_labels": ["sack", "box"] if active else [],
|
||||
"next_batch_number": self.get_next_batch_number(cdate) if not active else None,
|
||||
"count": self.current_state['count'] if active else 0,
|
||||
"sack_count": sack_count,
|
||||
"box_count": box_count,
|
||||
"counts": {"sack": sack_count, "box": box_count},
|
||||
"counting_date": self.current_state['counting_date'] if active else cdate,
|
||||
"start_time": self.current_state['start_time'] if active else None,
|
||||
"last_detection_time": self.current_state['last_detection_time'] if active else None,
|
||||
"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,
|
||||
}
|
||||
|
||||
def shutdown(self):
|
||||
self.shutdown_event.set()
|
||||
self.end_batch(closed_by='shutdown')
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.db.close()
|
||||
@@ -0,0 +1,176 @@
|
||||
# =============================================================================
|
||||
# Edge RK3588 production sack counter + dashboard
|
||||
# Shared config for: counter_live_rknn.py + counter_dashboard.py
|
||||
# System Mode: MANUAL START & END BATCH
|
||||
# Copy to .env on device: cp config.env.example .env && nano .env
|
||||
# =============================================================================
|
||||
|
||||
# --- Core paths ---
|
||||
# Root output directory (logs, DB, video, CSV)
|
||||
OUTPUT_DIR=/opt/feedmill
|
||||
# SQLite database path for batch entries & crossing logs
|
||||
DB_PATH=/opt/feedmill/feedmill.db
|
||||
# JSON file persisting the current active batch state
|
||||
STATE_FILE=/opt/feedmill/bytetrack_current_batch.json
|
||||
|
||||
# --- Input source ---
|
||||
# RTSP / HTTP live stream, or a local video file path
|
||||
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
|
||||
|
||||
# --- 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: 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 (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
|
||||
|
||||
# --- Detection ---
|
||||
# Default confidence threshold – dipakai jika confidence per objek di bawah dikosongkan
|
||||
CONF=0.3
|
||||
# Confidence threshold khusus per objek (0.0 - 1.0). Kosongkan jika ingin mengikuti CONF di atas.
|
||||
SACK_CONF=0.3
|
||||
BOX_CONF=0.3
|
||||
TRUCK_CONF=0.3
|
||||
|
||||
# --- ByteTrack tracking ---
|
||||
# Counted sack class, index 0
|
||||
# Detections with score ≥ this get priority matching in the first association stage
|
||||
TRACK_HIGH_THRESH_0=0.25
|
||||
# Detections with score between this and TRACK_HIGH_THRESH are matched in the second stage
|
||||
TRACK_LOW_THRESH_0=0.1
|
||||
# IoU threshold for the first-stage association (0–1). Higher = stricter overlap required
|
||||
TRACK_MATCH_THRESH_0=0.3
|
||||
# Frames a track survives without a match before being permanently removed
|
||||
TRACK_BUFFER_0=30
|
||||
# Minimum consecutive (or total) hits needed before a track is considered confirmed
|
||||
TRACK_MIN_HITS_0=3
|
||||
|
||||
# --- ID-switch dedup guard ---
|
||||
# Prevents double counting when a track's ID changes right at the counting line:
|
||||
# after a crossing, a second crossing from a replacement (previously-inactive) track
|
||||
# within DEDUP_FRAMES frames and DEDUP_PX pixels along the line is ignored.
|
||||
# Simultaneous active tracks are never blocked. Set DEDUP_PX=-1 to disable.
|
||||
DEDUP_FRAMES=4
|
||||
DEDUP_PX=35
|
||||
|
||||
# --- Display ---
|
||||
# Site name shown on the dashboard header (top-right)
|
||||
SITE_NAME=ZenAi
|
||||
|
||||
# --- Object class names ---
|
||||
# Camera / location identifier shown in HUD and stored in DB
|
||||
CAMERA_NAME=ZenAi
|
||||
# Label used for batch grouping in the database
|
||||
OBJECT_LABEL=sack,box,truck
|
||||
# Class name for the counted object (must match NUM_CLASSES order, index 0)
|
||||
CLASS_COUNTED_OBJECT=sack,box,truck
|
||||
# Class IDs that are tracked and counted (0=sack, 1=box)
|
||||
COUNTED_CLASS_IDS=0,1
|
||||
# Class ID for truck detection used to determine the horizontal counting zone (2=truck)
|
||||
TRUCK_CLASS_ID=2
|
||||
|
||||
# --- Horizontal Counting Zone (Full Vertical Height) ---
|
||||
# Mode zona hitung horizontal:
|
||||
# auto = mengikuti posisi X dari deteksi truck (dengan fallback & hold jika deteksi hilang)
|
||||
# manual = selalu menggunakan batas X tetap dari ZONE_X_MIN/MAX atau ZONE_X_MIN_FRAC/MAX_FRAC
|
||||
ZONE_MODE=auto
|
||||
# Batas kiri & kanan zona dalam pixel (kosongkan jika ingin memakai FRAC di bawah)
|
||||
ZONE_X_MIN=
|
||||
ZONE_X_MAX=
|
||||
# Batas kiri & kanan zona dalam rasio lebar frame (0.0 - 1.0). Digunakan saat ZONE_X_MIN/MAX kosong.
|
||||
ZONE_X_MIN_FRAC=0.30
|
||||
ZONE_X_MAX_FRAC=0.80
|
||||
# Tambahan lebar (padding kiri & kanan dalam pixel) pada bounding box truck saat ZONE_MODE=auto
|
||||
TRUCK_ZONE_PAD_X=10
|
||||
# Berapa detik zona truck terakhir dipertahankan saat deteksi truck sempat hilang (ZONE_MODE=auto)
|
||||
TRUCK_ZONE_HOLD_SEC=300
|
||||
|
||||
# --- Line crossing ---
|
||||
# Counting axis: auto | x | y. Use y for sacks moving down across a horizontal line.
|
||||
COUNT_AXIS=y
|
||||
# Direction for counting: down (top-to-bottom) | up | ltr | rtl | both
|
||||
CROSS_DIRECTION=down
|
||||
# Fixed x-coordinate for the counting line (used when COUNT_AXIS=x)
|
||||
LINE_X=
|
||||
# Fraction of frame width where the counting line is drawn (default 0.5 = centre)
|
||||
LINE_X_FRAC=0.5
|
||||
# Fixed y-coordinate for the counting line (used when COUNT_AXIS=y)
|
||||
LINE_Y=
|
||||
# Fraction of frame height where the counting line is drawn (default 0.5 = centre)
|
||||
LINE_Y_FRAC=0.5
|
||||
|
||||
# --- Batch management (MANUAL TRIGGER) ---
|
||||
# Operating mode: manual | auto
|
||||
# manual: Operator clicks "START BATCH" to start counting and "STOP BATCH" to finish
|
||||
BATCH_MODE=manual
|
||||
|
||||
# Internal IPC control server (counter_live_rknn <-> counter_dashboard)
|
||||
COUNTER_CONTROL_HOST=127.0.0.1
|
||||
COUNTER_CONTROL_PORT=5001
|
||||
|
||||
# Daily cutoff time (HH:MM) – batch numbering resets after this time each day
|
||||
DAILY_CUTOFF_TIME=06:00
|
||||
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
|
||||
|
||||
# Minimum sacks per batch to persist to database (set to 1 for manual mode)
|
||||
MIN_OBJECT_PER_BATCH=1
|
||||
# Minimum duration in seconds a batch must be open (set to 0 for manual mode)
|
||||
MIN_DURATION_PER_BATCH=0
|
||||
|
||||
# --- CSV export ---
|
||||
# Write per-crossing events to a CSV file (true/false)
|
||||
EXPORT_CSV=true
|
||||
# Path where the crossing CSV is written
|
||||
CROSS_CSV=/opt/feedmill/batch_crossings.csv
|
||||
|
||||
# --- Rate / performance ---
|
||||
# Motion detection pre-filter (true/false)
|
||||
MOTION_DETECTION_ENABLED=false
|
||||
MOTION_THRESHOLD=5.0
|
||||
RATE_WINDOW_SEC=60
|
||||
WARMUP_FRAMES=30
|
||||
RECONNECT_DELAY_SEC=3
|
||||
MAX_RECONNECT_ATTEMPTS=0
|
||||
# Cap stream error messages per outage (0 = unlimited + keep FFmpeg stderr)
|
||||
STREAM_ERROR_LOG_MAX=3
|
||||
FLUSH_EVERY_N_FRAMES=100
|
||||
TRACKED_PRUNE_SEC=300
|
||||
|
||||
# --- Video recording ---
|
||||
RECORD_VIDEO=false
|
||||
VIDEO_SEGMENT_SEC=3600
|
||||
OUTPUT_FPS=15
|
||||
|
||||
# --- Live stream snapshot ---
|
||||
LIVE_STREAM_ENABLED=false
|
||||
LIVE_STREAM_FRAME_PATH=/dev/shm/feedmill/live_frame.jpg
|
||||
LIVE_STREAM_QUALITY=75
|
||||
LIVE_STREAM_EVERY_N=2
|
||||
|
||||
# --- Dashboard (counter_dashboard.py) ---
|
||||
SECRET_KEY=change-me-in-production
|
||||
DASHBOARD_HOST=0.0.0.0
|
||||
# Web access port for users/operators
|
||||
DASHBOARD_PORT=7000
|
||||
FLASK_DEBUG=false
|
||||
CURRENT_BATCH_PATH=/opt/feedmill/bytetrack_current_batch.json
|
||||
# Shared secret for FCP -> ZenAI peer sync (X-API-Key header)
|
||||
PEER_API_TOKEN=
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
Internal lightweight HTTP control server for counter_live_rknn.
|
||||
Exposes endpoints for starting, stopping, and checking manual batches.
|
||||
"""
|
||||
import json
|
||||
import threading
|
||||
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
|
||||
|
||||
class ControlHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, format, *args):
|
||||
# Mute standard noisy HTTP console logs
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path in ("/status", "/api/status"):
|
||||
status = self.server.store.get_status()
|
||||
self._send_json(200, {"success": True, **status})
|
||||
else:
|
||||
self._send_json(404, {"success": False, "error": f"Endpoint {self.path} not found"})
|
||||
|
||||
def _read_json_body(self):
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0") or "0")
|
||||
if length > 0:
|
||||
raw = self.rfile.read(length).decode("utf-8")
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
def do_POST(self):
|
||||
clean_path = self.path.split("?", 1)[0].rstrip("/")
|
||||
if clean_path in (
|
||||
"/start",
|
||||
"/start/sack",
|
||||
"/start/box",
|
||||
"/api/start",
|
||||
"/api/start/sack",
|
||||
"/api/start/box",
|
||||
"/api/batch/start",
|
||||
"/api/batch/start/sack",
|
||||
"/api/batch/start/box",
|
||||
):
|
||||
body = self._read_json_body()
|
||||
status = self.server.store.get_status()
|
||||
if status["active"]:
|
||||
if body and hasattr(self.server.store, "update_batch_metadata"):
|
||||
self.server.store.update_batch_metadata(body)
|
||||
sack_c = status.get("sack_count", 0)
|
||||
box_c = status.get("box_count", 0)
|
||||
self._send_json(200, {
|
||||
"success": True,
|
||||
"message": f"Batch #{status['batch_number']} is already running",
|
||||
"batch_number": status["batch_number"],
|
||||
"object_label": "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": body.get("plate") or status.get("plate"),
|
||||
"status": "running",
|
||||
})
|
||||
else:
|
||||
batch_num = self.server.store.start_new_batch()
|
||||
if body:
|
||||
if hasattr(self.server.store, "update_batch_metadata"):
|
||||
self.server.store.update_batch_metadata(body)
|
||||
elif hasattr(self.server.store, "current_state") and isinstance(self.server.store.current_state, dict):
|
||||
plate = body.get("plate")
|
||||
if plate:
|
||||
self.server.store.current_state["plate"] = plate
|
||||
if hasattr(self.server.store, "save_state"):
|
||||
self.server.store.save_state()
|
||||
self._send_json(200, {
|
||||
"success": True,
|
||||
"message": f"Started Batch #{batch_num}",
|
||||
"batch_number": batch_num,
|
||||
"object_label": "mixed",
|
||||
"object_labels": ["sack", "box"],
|
||||
"count": 0,
|
||||
"sack_count": 0,
|
||||
"box_count": 0,
|
||||
"counts": {"sack": 0, "box": 0},
|
||||
"plate": body.get("plate") or None,
|
||||
"status": "running",
|
||||
})
|
||||
elif clean_path in ("/stop", "/api/stop", "/api/batch/stop"):
|
||||
body = self._read_json_body()
|
||||
status = self.server.store.get_status()
|
||||
if not status["active"]:
|
||||
self._send_json(200, {
|
||||
"success": False,
|
||||
"error": "No active batch to stop",
|
||||
"status": "stopped",
|
||||
})
|
||||
else:
|
||||
if body and hasattr(self.server.store, "update_batch_metadata"):
|
||||
self.server.store.update_batch_metadata(body)
|
||||
cur_num = status["batch_number"]
|
||||
cur_count = status["count"]
|
||||
cur_sack = status.get("sack_count", 0)
|
||||
cur_box = status.get("box_count", 0)
|
||||
cur_plate = body.get("plate") or status.get("plate")
|
||||
ok = self.server.store.end_batch(closed_by="manual")
|
||||
self._send_json(200, {
|
||||
"success": True,
|
||||
"message": f"Batch #{cur_num} stopped ({cur_count} items)",
|
||||
"batch_number": cur_num,
|
||||
"object_label": "mixed",
|
||||
"object_labels": ["sack", "box"],
|
||||
"count": cur_count,
|
||||
"sack_count": cur_sack,
|
||||
"box_count": cur_box,
|
||||
"counts": {"sack": cur_sack, "box": cur_box},
|
||||
"plate": cur_plate,
|
||||
"persisted": ok,
|
||||
"status": "stopped",
|
||||
})
|
||||
else:
|
||||
self._send_json(404, {"success": False, "error": f"Endpoint {self.path} not found"})
|
||||
|
||||
def _send_json(self, code, payload):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
def start_control_server(store, host="127.0.0.1", port=5001, logger=print):
|
||||
try:
|
||||
server = HTTPServer((host, port), ControlHandler)
|
||||
server.store = store
|
||||
t = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
t.start()
|
||||
logger(f"Internal control server listening on http://{host}:{port}")
|
||||
return server
|
||||
except Exception as e:
|
||||
logger(f"Failed to start internal control server on {host}:{port}: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,867 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Edge RKNN production counter dashboard.
|
||||
Reads the counter database and active batch state for the sack counting flow.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from io import BytesIO
|
||||
from datetime import datetime, timedelta
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
|
||||
from flask import Flask, render_template, jsonify, request, Response
|
||||
from werkzeug.serving import WSGIRequestHandler
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from batch_store import ensure_batch_schema
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
app = Flask(__name__, template_folder="templates", static_folder="static")
|
||||
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "change-me-in-production")
|
||||
|
||||
_DEFAULT_DIR = "/opt/feedmill"
|
||||
DB_PATH = os.getenv("DB_PATH", f"{_DEFAULT_DIR}/feedmill.db")
|
||||
CURRENT_BATCH_PATH = os.getenv("STATE_FILE", os.getenv("CURRENT_BATCH_PATH", f"{_DEFAULT_DIR}/current_batch.json"))
|
||||
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")
|
||||
|
||||
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")
|
||||
|
||||
DASHBOARD_PORT = int(os.getenv("DASHBOARD_PORT", "5000"))
|
||||
DASHBOARD_HOST = os.getenv("DASHBOARD_HOST", "0.0.0.0")
|
||||
FLASK_DEBUG = os.getenv("FLASK_DEBUG", "false").lower() == "true"
|
||||
|
||||
COUNTER_CONTROL_HOST = os.getenv("COUNTER_CONTROL_HOST", "127.0.0.1")
|
||||
COUNTER_CONTROL_PORT = int(os.getenv("COUNTER_CONTROL_PORT", "5001"))
|
||||
COUNTER_CONTROL_URL = f"http://{COUNTER_CONTROL_HOST}:{COUNTER_CONTROL_PORT}"
|
||||
BATCH_MODE = os.getenv("BATCH_MODE", "manual").strip().lower()
|
||||
|
||||
@app.route("/api/live-video")
|
||||
def api_live_video():
|
||||
if not os.path.isfile(LIVE_STREAM_FRAME_PATH):
|
||||
return jsonify({"success": False, "error": "Live stream frame not available yet"}), 503
|
||||
|
||||
def generate():
|
||||
consecutive_fails = 0
|
||||
MAX_FAILS = 30
|
||||
while True:
|
||||
try:
|
||||
with open(LIVE_STREAM_FRAME_PATH, "rb") as f:
|
||||
jpeg = f.read()
|
||||
if not jpeg or len(jpeg) < 2 or jpeg[:2] != b"\xff\xd8":
|
||||
consecutive_fails += 1
|
||||
if consecutive_fails >= MAX_FAILS:
|
||||
return
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
consecutive_fails = 0
|
||||
yield (b"--frame\r\n"
|
||||
b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n")
|
||||
except FileNotFoundError:
|
||||
consecutive_fails += 1
|
||||
if consecutive_fails >= MAX_FAILS:
|
||||
return
|
||||
time.sleep(1.0)
|
||||
continue
|
||||
except Exception:
|
||||
consecutive_fails += 1
|
||||
if consecutive_fails >= MAX_FAILS:
|
||||
return
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
time.sleep(0.05)
|
||||
return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
|
||||
|
||||
|
||||
def _ensure_db():
|
||||
try:
|
||||
from pathlib import Path
|
||||
Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
ensure_batch_schema(conn)
|
||||
conn.close()
|
||||
except Exception as e:
|
||||
print(f"[Warning] Could not initialize database at {DB_PATH}: {e}")
|
||||
|
||||
_ensure_db()
|
||||
|
||||
|
||||
def get_db():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def get_counting_date(dt=None, cutoff_str=CUTOFF_TIME):
|
||||
if dt is None:
|
||||
dt = datetime.now()
|
||||
cutoff = datetime.strptime(cutoff_str, "%H:%M").time()
|
||||
if cutoff.hour < 12:
|
||||
if dt.time() < cutoff:
|
||||
return (dt.date() - timedelta(days=1)).isoformat()
|
||||
return dt.date().isoformat()
|
||||
if dt.time() < cutoff:
|
||||
return dt.date().isoformat()
|
||||
return (dt.date() + timedelta(days=1)).isoformat()
|
||||
|
||||
|
||||
def get_next_batch_number_db(counting_date=None):
|
||||
try:
|
||||
if counting_date is None:
|
||||
counting_date = get_counting_date()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT COALESCE(MAX(batch_number), 0) + 1 FROM batches WHERE counting_date = ?",
|
||||
(counting_date,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
return row[0] if row else 1
|
||||
except Exception:
|
||||
return 1
|
||||
|
||||
|
||||
def _send_counter_command(endpoint, data=b""):
|
||||
url = f"{COUNTER_CONTROL_URL}/{endpoint}"
|
||||
req = urllib.request.Request(url, data=data, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=4.0) as resp:
|
||||
return json.loads(resp.read().decode("utf-8")), resp.status
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
return json.loads(e.read().decode("utf-8")), e.code
|
||||
except Exception:
|
||||
return {"success": False, "error": f"HTTP {e.code}"}, e.code
|
||||
except urllib.error.URLError as e:
|
||||
return {
|
||||
"success": False,
|
||||
"error": "Engine counter tidak aktif. Pastikan service feedmill-counter berjalan.",
|
||||
"detail": str(e.reason),
|
||||
}, 503
|
||||
except Exception as e:
|
||||
return {"success": False, "error": str(e)}, 500
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template(
|
||||
"dashboard.html",
|
||||
site_name=SITE_NAME,
|
||||
camera_name=CAMERA_NAME,
|
||||
cutoff_time=CUTOFF_TIME,
|
||||
stream_fps=STREAM_FPS_DISPLAY,
|
||||
stream_resolution=STREAM_RESOLUTION_DISPLAY,
|
||||
stream_accuracy=STREAM_ACCURACY_PCT,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_obj_label(raw_label):
|
||||
val = str(raw_label or "").strip().lower()
|
||||
if val in ("mixed", "all", "both"):
|
||||
return "mixed"
|
||||
return "box" if val == "box" else "sack"
|
||||
|
||||
|
||||
def _separate_counts(raw_label, count, sack_count=None, box_count=None):
|
||||
"""Return separate class counts while remaining compatible with legacy rows."""
|
||||
total = int(count or 0)
|
||||
if sack_count is not None or box_count is not None:
|
||||
sacks = int(sack_count or 0)
|
||||
boxes = int(box_count or 0)
|
||||
elif _normalize_obj_label(raw_label) == "box":
|
||||
sacks, boxes = 0, total
|
||||
else:
|
||||
sacks, boxes = total, 0
|
||||
return sacks, boxes
|
||||
|
||||
|
||||
def _resolve_batch_label(raw_label, sack_count, box_count):
|
||||
"""Return 'sack', 'box', or 'mixed' based on actual counted contents."""
|
||||
sacks = int(sack_count or 0)
|
||||
boxes = int(box_count or 0)
|
||||
if sacks > 0 and boxes > 0:
|
||||
return "mixed"
|
||||
if boxes > 0 and sacks == 0:
|
||||
return "box"
|
||||
if sacks > 0 and boxes == 0:
|
||||
return "sack"
|
||||
return _normalize_obj_label(raw_label)
|
||||
|
||||
|
||||
@app.route("/api/current-batch")
|
||||
def api_current_batch():
|
||||
cdate = get_counting_date()
|
||||
try:
|
||||
with open(CURRENT_BATCH_PATH, "r") as f:
|
||||
data = json.load(f)
|
||||
sack_count, box_count = _separate_counts(
|
||||
data.get("object_label"),
|
||||
data.get("count", 0),
|
||||
data.get("sack_count"),
|
||||
data.get("box_count"),
|
||||
)
|
||||
return jsonify(
|
||||
{
|
||||
"success": True,
|
||||
"active": True,
|
||||
"status": "running",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"counting_date": data.get("counting_date", cdate),
|
||||
"batch_number": data.get("batch_number"),
|
||||
"object_label": _normalize_obj_label(data.get("object_label")),
|
||||
"count": data.get("count", 0),
|
||||
"sack_count": sack_count,
|
||||
"box_count": box_count,
|
||||
"plate": data.get("plate") or None,
|
||||
"start_time": data.get("start_time"),
|
||||
"last_detection_time": data.get("last_detection_time"),
|
||||
}
|
||||
)
|
||||
except FileNotFoundError:
|
||||
next_batch = get_next_batch_number_db(cdate)
|
||||
return jsonify(
|
||||
{
|
||||
"success": False,
|
||||
"active": False,
|
||||
"status": "stopped",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"error": "No active batch",
|
||||
"count": 0,
|
||||
"sack_count": 0,
|
||||
"box_count": 0,
|
||||
"batch_number": None,
|
||||
"object_label": None,
|
||||
"plate": None,
|
||||
"next_batch_number": next_batch,
|
||||
"counting_date": cdate,
|
||||
}
|
||||
), 200
|
||||
except Exception as e:
|
||||
next_batch = get_next_batch_number_db(cdate)
|
||||
return jsonify(
|
||||
{
|
||||
"success": False,
|
||||
"active": False,
|
||||
"status": "stopped",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"error": str(e),
|
||||
"count": 0,
|
||||
"sack_count": 0,
|
||||
"box_count": 0,
|
||||
"batch_number": None,
|
||||
"object_label": None,
|
||||
"plate": None,
|
||||
"next_batch_number": next_batch,
|
||||
"counting_date": cdate,
|
||||
}
|
||||
), 500
|
||||
|
||||
|
||||
def _get_peer_api_token():
|
||||
env_token = os.getenv("PEER_API_TOKEN", "").strip()
|
||||
if env_token:
|
||||
return env_token
|
||||
for candidate in (
|
||||
os.path.join(_DEFAULT_DIR, "peer_sync_token.txt"),
|
||||
os.path.join(_DEFAULT_DIR, "docs", "peer_sync_token.txt"),
|
||||
):
|
||||
if os.path.isfile(candidate):
|
||||
try:
|
||||
with open(candidate, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line.startswith("PEER_API_TOKEN="):
|
||||
return line.split("=", 1)[1].strip()
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def _check_peer_api_key():
|
||||
if "X-API-Key" not in request.headers:
|
||||
return None
|
||||
provided = request.headers.get("X-API-Key", "").strip()
|
||||
expected = _get_peer_api_token()
|
||||
if not expected or provided != expected:
|
||||
return jsonify({"success": False, "error": "unauthorized"}), 401
|
||||
return None
|
||||
|
||||
|
||||
@app.route("/api/batch/start", methods=["POST"])
|
||||
@app.route("/api/batch/start/<object_label>", methods=["POST"])
|
||||
def api_batch_start(object_label=None):
|
||||
auth_err = _check_peer_api_key()
|
||||
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")
|
||||
)
|
||||
return jsonify(data), code
|
||||
|
||||
|
||||
@app.route("/api/batch/stop", methods=["POST"])
|
||||
def api_batch_stop():
|
||||
auth_err = _check_peer_api_key()
|
||||
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")
|
||||
)
|
||||
return jsonify(data), code
|
||||
|
||||
|
||||
@app.route("/api/batch/status", methods=["GET"])
|
||||
def api_batch_status():
|
||||
url = f"{COUNTER_CONTROL_URL}/status"
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=2.0) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
return jsonify(data), 200
|
||||
except Exception:
|
||||
state_data = None
|
||||
if os.path.isfile(CURRENT_BATCH_PATH):
|
||||
try:
|
||||
with open(CURRENT_BATCH_PATH, "r") as f:
|
||||
state_data = json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cdate = get_counting_date()
|
||||
next_batch = get_next_batch_number_db(cdate)
|
||||
|
||||
if state_data:
|
||||
sack_count, box_count = _separate_counts(
|
||||
state_data.get("object_label"),
|
||||
state_data.get("count", 0),
|
||||
state_data.get("sack_count"),
|
||||
state_data.get("box_count"),
|
||||
)
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"active": True,
|
||||
"status": "running",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"batch_number": state_data.get("batch_number"),
|
||||
"object_label": _normalize_obj_label(state_data.get("object_label")),
|
||||
"count": state_data.get("count", 0),
|
||||
"sack_count": sack_count,
|
||||
"box_count": box_count,
|
||||
"plate": state_data.get("plate") or None,
|
||||
"counting_date": state_data.get("counting_date", cdate),
|
||||
"start_time": state_data.get("start_time"),
|
||||
"last_detection_time": state_data.get("last_detection_time"),
|
||||
"engine_alive": False,
|
||||
}), 200
|
||||
else:
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"active": False,
|
||||
"status": "stopped",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"batch_number": None,
|
||||
"object_label": None,
|
||||
"plate": None,
|
||||
"next_batch_number": next_batch,
|
||||
"count": 0,
|
||||
"sack_count": 0,
|
||||
"box_count": 0,
|
||||
"counting_date": cdate,
|
||||
"start_time": None,
|
||||
"last_detection_time": None,
|
||||
"engine_alive": False,
|
||||
}), 200
|
||||
|
||||
|
||||
@app.route("/api/previous-batch")
|
||||
def api_previous_batch():
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, object_label, count, sack_count, box_count,
|
||||
plate, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
ORDER BY end_time DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
if row:
|
||||
sack_count, box_count = _separate_counts(
|
||||
row["object_label"], row["count"], row["sack_count"], row["box_count"]
|
||||
)
|
||||
return jsonify(
|
||||
{
|
||||
"success": True,
|
||||
"date": row["counting_date"],
|
||||
"batch_number": row["batch_number"],
|
||||
"object_label": _resolve_batch_label(
|
||||
row["object_label"], sack_count, box_count
|
||||
),
|
||||
"count": row["count"],
|
||||
"sack_count": sack_count,
|
||||
"box_count": box_count,
|
||||
"plate": row["plate"] or None,
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": row["duration_minutes"],
|
||||
}
|
||||
)
|
||||
return jsonify({"success": False, "error": "No previous batch"}), 200
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/summary")
|
||||
def api_summary():
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
today = get_counting_date()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as total_count,
|
||||
COALESCE(SUM(total_batches), 0) as total_batches,
|
||||
COALESCE(SUM(sack_count), 0) as sack_count,
|
||||
COALESCE(SUM(box_count), 0) as box_count
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(today,),
|
||||
)
|
||||
today_row = cur.fetchone()
|
||||
yesterday = (datetime.strptime(today, "%Y-%m-%d").date() - timedelta(days=1)).isoformat()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as total_count,
|
||||
COALESCE(SUM(total_batches), 0) as total_batches,
|
||||
COALESCE(SUM(sack_count), 0) as sack_count,
|
||||
COALESCE(SUM(box_count), 0) as box_count
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(yesterday,),
|
||||
)
|
||||
yesterday_row = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as grand_total,
|
||||
COALESCE(SUM(total_batches), 0) as grand_batches,
|
||||
COALESCE(SUM(sack_count), 0) as sack_count,
|
||||
COALESCE(SUM(box_count), 0) as box_count,
|
||||
COUNT(DISTINCT counting_date) as total_days
|
||||
FROM daily_summaries
|
||||
"""
|
||||
)
|
||||
all_time = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT ROUND(AVG(day_total), 1) as avg_per_day
|
||||
FROM (
|
||||
SELECT SUM(total_count) as day_total
|
||||
FROM daily_summaries
|
||||
GROUP BY counting_date
|
||||
)
|
||||
"""
|
||||
)
|
||||
avg = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, SUM(total_count) as total_count
|
||||
FROM daily_summaries
|
||||
GROUP BY counting_date
|
||||
ORDER BY total_count DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
best = cur.fetchone()
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"today": {
|
||||
"date": today,
|
||||
"total_count": today_row["total_count"] if today_row else 0,
|
||||
"total_batches": today_row["total_batches"] if today_row else 0,
|
||||
"count": today_row["total_count"] if today_row else 0,
|
||||
"sack_count": today_row["sack_count"] if today_row else 0,
|
||||
"box_count": today_row["box_count"] if today_row else 0,
|
||||
},
|
||||
"yesterday": {
|
||||
"date": yesterday,
|
||||
"total_count": yesterday_row["total_count"] if yesterday_row else 0,
|
||||
"total_batches": yesterday_row["total_batches"] if yesterday_row else 0,
|
||||
"count": yesterday_row["total_count"] if yesterday_row else 0,
|
||||
"sack_count": yesterday_row["sack_count"] if yesterday_row else 0,
|
||||
"box_count": yesterday_row["box_count"] if yesterday_row else 0,
|
||||
},
|
||||
"all_time": {
|
||||
"grand_total": all_time["grand_total"],
|
||||
"grand_batches": all_time["grand_batches"],
|
||||
"total_days": all_time["total_days"],
|
||||
"count": all_time["grand_total"],
|
||||
"sack_count": all_time["sack_count"],
|
||||
"box_count": all_time["box_count"],
|
||||
},
|
||||
"average_per_day": avg["avg_per_day"] or 0,
|
||||
"best_day": {
|
||||
"date": best["counting_date"] if best else None,
|
||||
"count": best["total_count"] if best else 0,
|
||||
},
|
||||
}
|
||||
)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}", "today": {"date": datetime.now().date().isoformat(), "total_count": 0, "total_batches": 0}, "yesterday": {"date": "", "total_count": 0, "total_batches": 0}, "all_time": {"grand_total": 0, "grand_batches": 0, "total_days": 0}, "average_per_day": 0, "best_day": {"date": None, "count": 0}}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/daily-data")
|
||||
def api_daily_data():
|
||||
try:
|
||||
days = request.args.get("days", 30, type=int)
|
||||
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date,
|
||||
SUM(total_count) as total_count,
|
||||
SUM(total_batches) as total_batches,
|
||||
ROUND(CAST(SUM(total_count) AS FLOAT) / SUM(total_batches), 1) as avg_per_batch
|
||||
FROM daily_summaries
|
||||
WHERE counting_date >= ?
|
||||
GROUP BY counting_date
|
||||
ORDER BY counting_date ASC
|
||||
""",
|
||||
(date_from,),
|
||||
)
|
||||
daily_data = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"total_count": row["total_count"],
|
||||
"total_batches": row["total_batches"],
|
||||
"avg_per_batch": row["avg_per_batch"] or 0,
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(daily_data)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/day-detail/<date>")
|
||||
def api_day_detail(date):
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number, object_label, count, sack_count, box_count, plate, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY batch_number ASC
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
batches = []
|
||||
total_duration = 0
|
||||
for row in cur.fetchall():
|
||||
duration = row["duration_minutes"] or 0
|
||||
total_duration += duration
|
||||
sack_count, box_count = _separate_counts(
|
||||
row["object_label"], row["count"], row["sack_count"], row["box_count"]
|
||||
)
|
||||
batches.append(
|
||||
{
|
||||
"batch_number": row["batch_number"],
|
||||
"object_label": _resolve_batch_label(
|
||||
row["object_label"], sack_count, box_count
|
||||
),
|
||||
"count": row["count"],
|
||||
"sack_count": sack_count,
|
||||
"box_count": box_count,
|
||||
"plate": row["plate"] or None,
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": duration,
|
||||
}
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as total_count,
|
||||
COALESCE(SUM(total_batches), 0) as total_batches,
|
||||
COALESCE(SUM(sack_count), 0) as sack_count,
|
||||
COALESCE(SUM(box_count), 0) as box_count
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
summary = cur.fetchone()
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"date": date,
|
||||
"total_count": summary["total_count"] if summary else 0,
|
||||
"total_batches": summary["total_batches"] if summary else 0,
|
||||
"sack_count": summary["sack_count"] if summary else 0,
|
||||
"box_count": summary["box_count"] if summary else 0,
|
||||
"total_duration_minutes": round(total_duration, 1),
|
||||
"avg_duration_minutes": round(total_duration / len(batches), 1) if batches else 0,
|
||||
"batches": batches,
|
||||
}
|
||||
)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"date": date, "total_count": 0, "total_batches": 0, "sack_count": 0, "box_count": 0, "total_duration_minutes": 0, "avg_duration_minutes": 0, "batches": [], "error": f"Database unavailable: {e}"}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/recent-batches")
|
||||
def api_recent_batches():
|
||||
try:
|
||||
limit = request.args.get("limit", 10, type=int)
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, object_label, count, sack_count, box_count,
|
||||
plate, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
ORDER BY end_time DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
batches = []
|
||||
for row in cur.fetchall():
|
||||
sack_count, box_count = _separate_counts(
|
||||
row["object_label"], row["count"], row["sack_count"], row["box_count"]
|
||||
)
|
||||
batches.append(
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"batch_number": row["batch_number"],
|
||||
"object_label": _resolve_batch_label(
|
||||
row["object_label"], sack_count, box_count
|
||||
),
|
||||
"count": row["count"],
|
||||
"sack_count": sack_count,
|
||||
"box_count": box_count,
|
||||
"plate": row["plate"] or None,
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": row["duration_minutes"] or 0,
|
||||
}
|
||||
)
|
||||
conn.close()
|
||||
return jsonify(batches)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/available-dates")
|
||||
def api_available_dates():
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date,
|
||||
SUM(total_count) as total_count,
|
||||
SUM(total_batches) as total_batches
|
||||
FROM daily_summaries
|
||||
GROUP BY counting_date
|
||||
ORDER BY counting_date DESC
|
||||
"""
|
||||
)
|
||||
dates = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"total_count": row["total_count"],
|
||||
"total_batches": row["total_batches"],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(dates)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
def _excel_response(wb, filename):
|
||||
output = BytesIO()
|
||||
wb.save(output)
|
||||
output.seek(0)
|
||||
return Response(
|
||||
output.getvalue(),
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f"attachment; filename={filename}"},
|
||||
)
|
||||
|
||||
|
||||
def _style_header(ws, cols):
|
||||
header_font = Font(bold=True, color="FFFFFF", size=11)
|
||||
header_fill = PatternFill(start_color="2F5496", end_color="2F5496", fill_type="solid")
|
||||
thin_border = Border(
|
||||
left=Side(style="thin"), right=Side(style="thin"),
|
||||
top=Side(style="thin"), bottom=Side(style="thin"),
|
||||
)
|
||||
for col_idx, (col_letter, text) in enumerate(cols, 1):
|
||||
cell = ws.cell(row=1, column=col_idx, value=text)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(horizontal="center")
|
||||
cell.border = thin_border
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
|
||||
def _auto_width(ws):
|
||||
for col in ws.columns:
|
||||
max_len = 0
|
||||
col_letter = col[0].column_letter
|
||||
for cell in col:
|
||||
if cell.value is not None:
|
||||
max_len = max(max_len, len(str(cell.value)))
|
||||
ws.column_dimensions[col_letter].width = max_len + 4
|
||||
|
||||
|
||||
@app.route("/api/export-daily-csv")
|
||||
def export_daily_xlsx():
|
||||
try:
|
||||
days = request.args.get("days", 30, type=int)
|
||||
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, object_label, count, sack_count, box_count,
|
||||
plate, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date >= ?
|
||||
ORDER BY counting_date ASC, batch_number ASC
|
||||
""",
|
||||
(date_from,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 503
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Batch Details"
|
||||
_style_header(ws, [("A", "Date"), ("B", "Batch #"), ("C", "Plate"), ("D", "Type"), ("E", "Sack"), ("F", "Box"), ("G", "Total"), ("H", "Start Time"), ("I", "End Time"), ("J", "Duration (min)")])
|
||||
|
||||
for r_idx, row in enumerate(rows, 2):
|
||||
sack_count, box_count = _separate_counts(
|
||||
row["object_label"], row["count"], row["sack_count"], row["box_count"]
|
||||
)
|
||||
ws.cell(row=r_idx, column=1, value=row["counting_date"])
|
||||
ws.cell(row=r_idx, column=2, value=row["batch_number"])
|
||||
ws.cell(row=r_idx, column=3, value=row["plate"] or "-")
|
||||
ws.cell(row=r_idx, column=4, value=_resolve_batch_label(row["object_label"], sack_count, box_count).upper())
|
||||
ws.cell(row=r_idx, column=5, value=sack_count)
|
||||
ws.cell(row=r_idx, column=6, value=box_count)
|
||||
ws.cell(row=r_idx, column=7, value=row["count"])
|
||||
ws.cell(row=r_idx, column=8, value=row["start_time"])
|
||||
ws.cell(row=r_idx, column=9, value=row["end_time"])
|
||||
ws.cell(row=r_idx, column=10, value=row["duration_minutes"] or 0)
|
||||
|
||||
_auto_width(ws)
|
||||
filename = f"{SITE_NAME}_daily_records_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
||||
return _excel_response(wb, filename)
|
||||
|
||||
|
||||
@app.route("/api/export-day-csv/<date>")
|
||||
def export_day_xlsx(date):
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number, object_label, count, sack_count, box_count, plate, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY batch_number ASC
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 503
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = f"Day {date}"
|
||||
_style_header(ws, [("A", "Batch Number"), ("B", "Plate"), ("C", "Type"), ("D", "Sack"), ("E", "Box"), ("F", "Total"), ("G", "Start Time"), ("H", "End Time"), ("I", "Duration (min)")])
|
||||
|
||||
for r_idx, row in enumerate(rows, 2):
|
||||
sack_count, box_count = _separate_counts(
|
||||
row["object_label"], row["count"], row["sack_count"], row["box_count"]
|
||||
)
|
||||
ws.cell(row=r_idx, column=1, value=row["batch_number"])
|
||||
ws.cell(row=r_idx, column=2, value=row["plate"] or "-")
|
||||
ws.cell(row=r_idx, column=3, value=_resolve_batch_label(row["object_label"], sack_count, box_count).upper())
|
||||
ws.cell(row=r_idx, column=4, value=sack_count)
|
||||
ws.cell(row=r_idx, column=5, value=box_count)
|
||||
ws.cell(row=r_idx, column=6, value=row["count"])
|
||||
ws.cell(row=r_idx, column=7, value=row["start_time"])
|
||||
ws.cell(row=r_idx, column=8, value=row["end_time"])
|
||||
ws.cell(row=r_idx, column=9, value=row["duration_minutes"] or 0)
|
||||
|
||||
_auto_width(ws)
|
||||
filename = f"{SITE_NAME}_day_detail_{date}.xlsx"
|
||||
return _excel_response(wb, filename)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
WSGIRequestHandler.protocol_version = "HTTP/1.1"
|
||||
print(f"RKNN counter dashboard at http://{DASHBOARD_HOST}:{DASHBOARD_PORT}")
|
||||
print(f"DB: {DB_PATH}")
|
||||
print(f"State: {CURRENT_BATCH_PATH}")
|
||||
app.run(host=DASHBOARD_HOST, port=DASHBOARD_PORT, debug=FLASK_DEBUG)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,263 @@
|
||||
# Handoff: FCP → zenai_nano_fcp batch sync
|
||||
|
||||
Status: **FCP side is DONE and shipped. zenai side is NOT done yet.**
|
||||
|
||||
## 0. Test topology (read first)
|
||||
|
||||
| Role | Host | Ports | Notes |
|
||||
|---|---|---|---|
|
||||
| FCP **mirror** (test target) | `192.168.192.89` | operator `:5000`, office `:5721` | Repo checkout + systemd services (`karung-counter`, `karung-counter-dashboard`) run here. **Use this host for all manual start/stop tests.** |
|
||||
| zenai_nano_fcp (peer counter, NanoPi) | `192.168.192.209` | dashboard `:7000`, internal control `127.0.0.1:5000`, camera RTSP `:8554` | Peer API lives here. `PEER_API_URL=http://192.168.192.209:7000` |
|
||||
| LIVE FCP | other host (unknown yet) | — | **DO NOT touch.** No deploy, no restart, no batch start/stop there until the owner says so. |
|
||||
|
||||
Rules for the zenai-side developer:
|
||||
- Test only against `192.168.192.89` (FCP mirror) and `192.168.192.209` (peer).
|
||||
- The live FCP host is out of scope. Do not point `PEER_API_URL` at it.
|
||||
- `PEER_API_URL` lives in the FCP `.env` (gitignored) — never commit it.
|
||||
- The zenai dashboard currently has no active batch and sits in `manual` mode;
|
||||
a test start/stop pair is safe.
|
||||
- FCP mirror ports: operator UI `http://192.168.192.89:5000`, office UI
|
||||
`http://192.168.192.89:5721` (office only: mode / model_mode / require_plate /
|
||||
require_do writes, batch delete, OCR engine).
|
||||
- FCP mirror batch mode was switched `auto` → `manual` on 2026-11-13 for these
|
||||
tests (`/opt/jetson-counter/batch_mode.json`). Manual start/stop is rejected in
|
||||
`auto` mode (HTTP 409 `wrong_mode`).
|
||||
|
||||
FCP is the source of truth for counts. FCP pushes every **manual** batch
|
||||
start/stop to the zenai counter (RK3588/NanoPi device, `/opt/feedmill`,
|
||||
dashboard port 7000) so both sides count the same load.
|
||||
|
||||
Until the zenai work below is implemented, FCP already sends the requests and
|
||||
zenai answers with its **single-label** behaviour. FCP detects that and shows the
|
||||
operator a warning (`Peer hanya menerima satu label (sack) …`).
|
||||
|
||||
## 1. What FCP sends
|
||||
|
||||
Base URL from FCP `.env`:
|
||||
|
||||
```
|
||||
PEER_API_URL=http://192.168.192.209:7000 # zenai peer (empty => peer sync disabled)
|
||||
PEER_API_TOKEN=<shared secret> # -> X-API-Key header (value in docs/peer_sync_token.txt)
|
||||
PEER_API_TIMEOUT=5 # seconds, per request
|
||||
```
|
||||
|
||||
Requests are plain JSON POSTs. Headers: `Content-Type: application/json`,
|
||||
`X-API-Key: <PEER_API_TOKEN>`.
|
||||
|
||||
### 1.1 Start — `POST {PEER_API_URL}/api/batch/start`
|
||||
|
||||
```json
|
||||
{
|
||||
"source": "fcp-semarang",
|
||||
"object_label": "sack",
|
||||
"object_labels": ["sack", "box"],
|
||||
"fcp_batch_number": 12,
|
||||
"counting_date": "2026-11-13",
|
||||
"plate": "B 1234 XYZ",
|
||||
"do_numbers": ["DO-2026-0011"],
|
||||
"expected_sack": 40,
|
||||
"expected_box": 10,
|
||||
"started_at": "2026-11-13T09:12:03"
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2 Stop — `POST {PEER_API_URL}/api/batch/stop`
|
||||
|
||||
```json
|
||||
{
|
||||
"source": "fcp-semarang",
|
||||
"fcp_batch_number": 12,
|
||||
"counting_date": "2026-11-13",
|
||||
"plate": "B 1234 XYZ",
|
||||
"net_sack": 38,
|
||||
"net_box": 9,
|
||||
"ended_at": "2026-11-13T10:04:57"
|
||||
}
|
||||
```
|
||||
|
||||
`net_sack` / `net_box` are FCP's final numbers — **reference only**. zenai keeps
|
||||
its own counts; FCP stays authoritative for reporting.
|
||||
|
||||
## 2. What FCP expects back
|
||||
|
||||
FCP accepts the **existing** zenai reply shape, no change required:
|
||||
|
||||
```json
|
||||
{"success": true, "message": "Started Batch #7 (SACK)", "batch_number": 7,
|
||||
"object_label": "sack", "status": "running"}
|
||||
```
|
||||
|
||||
Rules FCP applies to the reply:
|
||||
|
||||
| Reply | FCP reaction |
|
||||
|---|---|
|
||||
| HTTP 200 + `success: true` | ok |
|
||||
| HTTP 200 + `success: false`, error contains `No active batch` (stop only) | ok — peer was already stopped |
|
||||
| HTTP 200 + `success: false`, other error | failed, warning shown |
|
||||
| HTTP 4xx | failed, no retry |
|
||||
| HTTP 5xx / timeout / refused | failed after 2 attempts (0.5 s apart), warning shown |
|
||||
|
||||
Peer failures never block the FCP batch (fail-soft):
|
||||
- **start failed** → zenai counts 0 for that batch; operator informed.
|
||||
- **stop failed** → zenai keeps counting; operator must stop zenai manually.
|
||||
|
||||
FCP also raises a warning when it asked for several labels (`object_labels`) but
|
||||
the reply only carries a single `object_label` — that means the peer still
|
||||
counts one class only.
|
||||
|
||||
## 3. Work on the zenai side (not yet done)
|
||||
|
||||
Repo: `/home/jetson/Feedmill_Semarang_Project/zenai_nano_fcp` (device path
|
||||
`/opt/feedmill`).
|
||||
|
||||
### 3.1 Multi-label batches (required)
|
||||
|
||||
Today `batch_store.py` is single-label:
|
||||
- `_normalize_batch_label()` accepts only `sack` / `box`.
|
||||
- `start_new_batch()` stores one `object_label` and one `count`.
|
||||
- `record_counted_object_crossing()` **ignores** any crossing whose label does
|
||||
not equal the active batch label.
|
||||
|
||||
Needed: one batch that counts `sack` and `box` separately.
|
||||
|
||||
- `_normalize_batch_label` → normalise a **list** of labels
|
||||
(`object_labels: ["sack", "box"]`), keep the old single `object_label` field
|
||||
working for the zenai UI (it may send `object_label: "sack"`).
|
||||
- Batch state: keep `counts: {"sack": N, "box": M}` (total = `sum(counts.values())`).
|
||||
Migrate the old `count` int for backward compatibility.
|
||||
- `record_counted_object_crossing(track_id, object_label)`: count the crossing
|
||||
when the label is in the active batch's label set; keep per-label counters.
|
||||
The counted-event dedup key must include the label
|
||||
(`f"{label}:{track_id}"`), otherwise sack and box IDs collide.
|
||||
- `end_batch()` must persist per-label counts (DB migration needed for the
|
||||
`batches` table: add `counts_json` or `box_count`/`sack_count` columns).
|
||||
- Batch discard rule ("discard when 0 counted") must consider the **total**.
|
||||
|
||||
### 3.2 Forward the request body (required)
|
||||
|
||||
`counter_dashboard.py::_send_counter_command()` posts an **empty body**, so the
|
||||
JSON FCP sends is dropped before it reaches `counter_control.py`.
|
||||
|
||||
- `api_batch_start` must forward the full JSON body to
|
||||
`http://127.0.0.1:5000/api/batch/start` (and `api_batch_stop` likewise).
|
||||
- `counter_control.py` must read the body: `object_labels` (list) or
|
||||
`object_label` (single), plus the metadata (`source`, `fcp_batch_number`,
|
||||
`counting_date`, `plate`, `do_numbers`, `expected_sack`, `expected_box`).
|
||||
- Store the metadata on the zenai batch row (new columns or a JSON blob) so
|
||||
zenai history can be joined with FCP history by `source` + `fcp_batch_number`.
|
||||
|
||||
### 3.3 API key (now sent by FCP)
|
||||
|
||||
- FCP sends `X-API-Key: <PEER_API_TOKEN>` on every start/stop request.
|
||||
- The shared secret lives in `docs/peer_sync_token.txt` (**gitignored**) — copy
|
||||
that file together with this handoff. Same value is in the FCP `.env`.
|
||||
- Accept `X-API-Key` on `/api/batch/start` and `/api/batch/stop`.
|
||||
- Validate **only when the header is present**, so the zenai dashboard UI keeps
|
||||
working unchanged.
|
||||
- Reject with HTTP 401 + `{"success": false, "error": "unauthorized"}` when the
|
||||
header is present but wrong. FCP treats 4xx as failed (no retry) and warns.
|
||||
|
||||
### 3.4 Idempotency (recommended)
|
||||
|
||||
- Start when a batch is already active → return the existing batch, HTTP 200
|
||||
(`status: "running"`). Already the case in `counter_control.py`; keep it.
|
||||
- Stop with no active batch → HTTP 200 `{"success": false, "error": "No active
|
||||
batch to stop"}`. Already the case; keep it (FCP treats it as success).
|
||||
- FCP re-sends a start when the operator presses "Mulai" twice; the peer must
|
||||
not create a second batch.
|
||||
|
||||
### 3.5 Reply shape (optional but recommended)
|
||||
|
||||
When the peer supports several labels it should answer with both:
|
||||
|
||||
```json
|
||||
{"success": true, "batch_number": 7, "object_labels": ["sack", "box"],
|
||||
"counts": {"sack": 12, "box": 3}, "status": "running"}
|
||||
```
|
||||
|
||||
FCP stops warning when `object_labels` is present in the reply.
|
||||
|
||||
## 4. Verification checklist (zenai side)
|
||||
|
||||
```bash
|
||||
# start (multi-label + metadata + api key)
|
||||
curl -s -X POST http://127.0.0.1:7000/api/batch/start \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H 'X-API-Key: <shared secret>' \
|
||||
-d '{"source":"fcp-semarang","object_label":"sack","object_labels":["sack","box"],
|
||||
"fcp_batch_number":12,"counting_date":"2026-11-13","plate":"B 1234 XYZ",
|
||||
"do_numbers":["DO-2026-0011"],"expected_sack":40,"expected_box":10,
|
||||
"started_at":"2026-11-13T09:12:03"}'
|
||||
|
||||
# stop
|
||||
curl -s -X POST http://127.0.0.1:7000/api/batch/stop \
|
||||
-H 'Content-Type: application/json' -H 'X-API-Key: <shared secret>' \
|
||||
-d '{"source":"fcp-semarang","fcp_batch_number":12,"counting_date":"2026-11-13",
|
||||
"plate":"B 1234 XYZ","net_sack":38,"net_box":9,"ended_at":"2026-11-13T10:04:57"}'
|
||||
```
|
||||
|
||||
Check:
|
||||
1. Reply has `success: true` and `object_labels: ["sack","box"]`.
|
||||
2. A sack crossing and a box crossing both raise the **total** count, and the
|
||||
per-label counters differ.
|
||||
3. The stored batch row keeps `source` / `fcp_batch_number` / plate / DO numbers.
|
||||
4. Stop replies with per-label counts and the row is persisted.
|
||||
|
||||
FCP side (from the Jetson, `PEER_API_URL` set):
|
||||
|
||||
```bash
|
||||
# manual batch start/stop in the operator UI -> watch the FCP log
|
||||
journalctl -u karung-counter-dashboard | grep PEER
|
||||
```
|
||||
|
||||
## 5. Verified test results (FCP mirror, 2026-11-13)
|
||||
|
||||
Full operator-button → zenai chain tested against the real peer
|
||||
(`192.168.192.209:7000`), FCP mirror `192.168.192.89` in `manual` batch mode:
|
||||
|
||||
| Step | FCP operator call | FCP result | zenai result |
|
||||
|---|---|---|---|
|
||||
| start | `POST http://192.168.192.89:5000/api/batch/start {"plate":"B 9999 TEST"}` | batch #12 started, `peer_sync.ok=true`, warning `Peer hanya menerima satu label (sack) …` | batch #4 running, `object_label: "sack"` |
|
||||
| stop | `POST http://192.168.192.89:5000/api/batch/stop` | batch #12 closed, `peer_sync.ok=true` | batch #4 stopped, `count: 0` |
|
||||
|
||||
Reproduce on the mirror:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://192.168.192.89:5000/api/batch/start \
|
||||
-H 'Content-Type: application/json' -d '{"plate":"B 9999 TEST"}'
|
||||
curl -s -X POST http://192.168.192.89:5000/api/batch/stop
|
||||
curl -s http://192.168.192.209:7000/api/batch/status
|
||||
journalctl -u karung-counter-dashboard | grep PEER
|
||||
```
|
||||
|
||||
FCP mirror side effects from that test (harmless, mirror only): batch #12 in the
|
||||
mirror DB with plate `B9999TEST`, and the mirror batch mode left on `manual`.
|
||||
|
||||
### 5.1 zenai defects found during that test
|
||||
|
||||
1. **Single label only.** Reply carries `object_label: "sack"`; FCP asked for
|
||||
`object_labels: ["sack","box"]`. → §3.1.
|
||||
2. **Request body dropped.** `counter_dashboard.py::_send_counter_command()`
|
||||
posts an empty body, so `plate` / `do_numbers` / `expected_*` /
|
||||
`fcp_batch_number` never reach `counter_control.py`. → §3.2.
|
||||
3. **Stopped batch not persisted.** The stop reply was
|
||||
`{"success": true, "count": 0, "persisted": false}`. `GET /api/recent-batches`
|
||||
on zenai still shows batches 1–3 for 2026-11-13 — test batch #4 is missing
|
||||
from zenai history. `end_batch()` reports the DB write as failed. Must be
|
||||
fixed on zenai, otherwise every synced batch vanishes from zenai history.
|
||||
4. **No `X-API-Key` check.** FCP now always sends the header (random secret,
|
||||
see `docs/peer_sync_token.txt`), but zenai ignores it — no 401 path exists
|
||||
yet. → §3.3.
|
||||
|
||||
## 6. Where the FCP code lives
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `src/peer_sync.py` | outbound client (stdlib urllib, retry, fail-soft) |
|
||||
| `counter_dashboard.py` | hooks in `api_batch_start` / `api_batch_stop` |
|
||||
| `templates/operator.html`, `templates/monitoring.html` | operator warning |
|
||||
| `tests/test_peer_sync.py` | mock-peer tests |
|
||||
| `docs/configuration.md` | env keys |
|
||||
|
||||
FCP sends only for **manual** and **do_manual** batch modes; `auto` mode is not
|
||||
synced (auto batches are started by the pipeline, not by the operator).
|
||||
@@ -0,0 +1,323 @@
|
||||
# Unified Batch Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Replace separate Sack and Box batch starts with one unified batch that records separate Sack and Box totals.
|
||||
|
||||
**Architecture:** Keep one row per batch. Add `sack_count` and `box_count` to batch state, `batches`, and `daily_summaries`, while retaining `count` as the total for API compatibility. New batches use `object_label = mixed` and accept crossings from both counted classes.
|
||||
|
||||
**Tech Stack:** Python 3.12, Flask, SQLite, Jinja template, vanilla JavaScript, stdlib `unittest`, openpyxl
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-13-unified-batch-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Do not add dependencies. Use stdlib `unittest` for tests.
|
||||
- Keep `count` equal to `sack_count + box_count` in every batch and API response.
|
||||
- Persist one database row per unified batch.
|
||||
- Preserve existing Sack and Box history, totals, batch numbers, and cutoff behavior.
|
||||
- Keep legacy start URLs working as aliases for unified start.
|
||||
- Preserve current dashboard visual system and responsive behavior.
|
||||
- This directory is not a Git repository, so use test checkpoints instead of commit steps.
|
||||
|
||||
## Review Focus
|
||||
|
||||
- Legacy active state: old Sack or Box count must survive resume and the batch must accept both classes afterward.
|
||||
- Same numeric track ID for different classes: one Sack and one Box must both count.
|
||||
- Legacy database rows: total counts must remain unchanged after separate-count backfill.
|
||||
- API compatibility: existing `count` field must remain the combined total.
|
||||
- Empty manual batch: it must create no batch row and must not increment daily batch totals.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Unified batch state and persistence
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/test_batch_store.py`
|
||||
- Modify: `batch_store.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `ensure_batch_schema(conn: sqlite3.Connection) -> None`
|
||||
- Produces: `BatchStore.start_new_batch(counting_date: str | None = None, object_label: str | None = None) -> int`
|
||||
- Produces: `BatchStore.get_status() -> dict` with `count`, `sack_count`, and `box_count`
|
||||
- Produces: batch rows using `object_label = "mixed"` and columns `sack_count`, `box_count`
|
||||
|
||||
- [ ] **Step 1: Write failing store tests**
|
||||
|
||||
Create `tests/test_batch_store.py` with `unittest`, `tempfile.TemporaryDirectory`, and isolated SQLite paths. Add tests named:
|
||||
|
||||
```python
|
||||
def test_mixed_batch_counts_sacks_and_boxes_separately(self):
|
||||
store = self.make_store()
|
||||
store.start_new_batch()
|
||||
store.record_counted_object_crossing(1, object_label="sack")
|
||||
store.record_counted_object_crossing(2, object_label="box")
|
||||
status = store.get_status()
|
||||
self.assertEqual(status["count"], 2)
|
||||
self.assertEqual(status["sack_count"], 1)
|
||||
self.assertEqual(status["box_count"], 1)
|
||||
```
|
||||
|
||||
Also cover:
|
||||
|
||||
- Same track ID once per class counts twice.
|
||||
- Legacy JSON state with `object_label = "sack"` and `count = 4` resumes as mixed with Sack 4, Box 0, total 4.
|
||||
- Legacy SQLite rows backfill `sack_count` or `box_count` without changing `total_count`.
|
||||
- One mixed batch row persists with total 2, Sack 1, Box 1.
|
||||
- Mixed daily summary persists total 2, Sack 1, Box 1, and `total_batches = 1`.
|
||||
- Empty manual batch persists no batch row and creates no daily summary.
|
||||
|
||||
- [ ] **Step 2: Run store tests and verify failure**
|
||||
|
||||
Run: `venv/bin/python -m unittest tests/test_batch_store.py -v`
|
||||
|
||||
Expected: FAIL because `sack_count`, `box_count`, and unified state do not exist.
|
||||
|
||||
- [ ] **Step 3: Add schema creation and migration**
|
||||
|
||||
In `batch_store.py`, add `ensure_batch_schema(conn)` that:
|
||||
|
||||
1. Creates `batches` and `daily_summaries` when absent.
|
||||
2. Adds `sack_count INTEGER NOT NULL DEFAULT 0` and `box_count INTEGER NOT NULL DEFAULT 0` to both tables when absent.
|
||||
3. Backfills legacy `daily_summaries.object_label = 'sack'` rows into `sack_count`, and legacy Box rows into `box_count`.
|
||||
4. Leaves `total_count`, `total_batches`, and existing rows unchanged.
|
||||
|
||||
Use `PRAGMA table_info(table_name)` to inspect columns before each `ALTER TABLE`. Call `ensure_batch_schema(self.db)` from `BatchStore._init_db()` and commit once.
|
||||
|
||||
- [ ] **Step 4: Upgrade batch state and counting**
|
||||
|
||||
In `batch_store.py`:
|
||||
|
||||
1. Add mixed-label normalization for `mixed`, `all`, and `both`.
|
||||
2. In `_load_state()`, convert legacy active state to `object_label = 'mixed'`, preserve legacy count in the matching class counter, and derive total from both counters.
|
||||
3. In `start_new_batch()`, always create a mixed batch with `count`, `sack_count`, and `box_count` initialized to zero.
|
||||
4. In `record_counted_object_crossing()`, remove the active-label type lock, normalize detected item to Sack or Box, increment that class counter and total, and use an event key containing both class and track ID.
|
||||
5. Keep manual mode behavior unchanged: crossings while no batch is active return `(0, False)`.
|
||||
|
||||
- [ ] **Step 5: Persist separate counters**
|
||||
|
||||
Change `_insert_batch()` to accept `sack_count` and `box_count`, insert both columns, and write one mixed `daily_summaries` row. Upsert `total_count`, `total_batches`, `sack_count`, and `box_count` independently.
|
||||
|
||||
Update `_end_batch_locked()` and cutoff finalization to pass the two counters.
|
||||
|
||||
- [ ] **Step 6: Run store tests**
|
||||
|
||||
Run: `venv/bin/python -m unittest tests/test_batch_store.py -v`
|
||||
|
||||
Expected: all store tests PASS.
|
||||
|
||||
- [ ] **Step 7: Checkpoint**
|
||||
|
||||
Run: `venv/bin/python -m py_compile batch_store.py tests/test_batch_store.py`
|
||||
|
||||
Expected: exit code 0.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Unified control and dashboard APIs
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/test_dashboard.py`
|
||||
- Modify: `counter_control.py`
|
||||
- Modify: `counter_dashboard.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `BatchStore.get_status()` fields `count`, `sack_count`, `box_count`
|
||||
- Produces: `POST /api/batch/start` calls counter command `start` without a class suffix
|
||||
- Produces: batch-related JSON responses include `sack_count` and `box_count`
|
||||
|
||||
- [ ] **Step 1: Write failing API tests**
|
||||
|
||||
Create `tests/test_dashboard.py` with Flask test client, temporary database, and `unittest.mock.patch`. Add tests named:
|
||||
|
||||
```python
|
||||
def test_start_endpoint_sends_unified_start_command(self):
|
||||
with patch("counter_dashboard._send_counter_command", return_value=({"success": True, "batch_number": 1}, 200)) as send:
|
||||
response = self.client.post("/api/batch/start")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
send.assert_called_once_with("start")
|
||||
```
|
||||
|
||||
Also cover:
|
||||
|
||||
- `/api/current-batch` returns saved mixed-state Sack and Box counts.
|
||||
- `/api/summary` returns separate today Sack and Box totals.
|
||||
- `/api/day-detail/<date>` returns separate counts for a mixed batch.
|
||||
- `/api/recent-batches` returns separate counts.
|
||||
- `/api/previous-batch` returns separate counts.
|
||||
- Legacy `POST /api/batch/start/sack` and `/api/batch/start/box` also send unified `start`.
|
||||
- Response `count` equals `sack_count + box_count`.
|
||||
|
||||
- [ ] **Step 2: Run API tests and verify failure**
|
||||
|
||||
Run: `venv/bin/python -m unittest tests/test_dashboard.py -v`
|
||||
|
||||
Expected: FAIL because start routes still use class suffixes and responses lack separate counters.
|
||||
|
||||
- [ ] **Step 3: Make control server start unified batches**
|
||||
|
||||
In `counter_control.py`, keep all existing start paths for compatibility, but call `start_new_batch()` without a class argument. Return `object_label = "mixed"` and include `sack_count`, `box_count`, and total `count` in start and stop responses.
|
||||
|
||||
- [ ] **Step 4: Update dashboard schema initialization**
|
||||
|
||||
Import and call `ensure_batch_schema(conn)` from `counter_dashboard._ensure_db()` instead of maintaining duplicate table definitions.
|
||||
|
||||
- [ ] **Step 5: Add separate counts to dashboard APIs**
|
||||
|
||||
In `counter_dashboard.py`:
|
||||
|
||||
1. Preserve `mixed` during object-label normalization.
|
||||
2. Make `/api/batch/start` and both legacy class routes call `_send_counter_command("start")`.
|
||||
3. Add `sack_count` and `box_count` to current-batch, batch-status fallback, previous-batch, day-detail, and recent-batch responses.
|
||||
4. Add `sack_count` and `box_count` to today, yesterday, and all-time summary objects.
|
||||
5. Select the new columns in every batch query.
|
||||
6. Keep `count` and existing aggregate total fields unchanged.
|
||||
|
||||
- [ ] **Step 6: Run API and store tests**
|
||||
|
||||
Run: `venv/bin/python -m unittest discover -s tests -v`
|
||||
|
||||
Expected: all current tests PASS.
|
||||
|
||||
- [ ] **Step 7: Checkpoint**
|
||||
|
||||
Run: `venv/bin/python -m py_compile counter_control.py counter_dashboard.py tests/test_dashboard.py`
|
||||
|
||||
Expected: exit code 0.
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Dashboard UI and exports
|
||||
|
||||
**Files:**
|
||||
- Modify: `templates/dashboard.html`
|
||||
- Modify: `counter_dashboard.py`
|
||||
- Test: `tests/test_dashboard.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: API fields `count`, `sack_count`, `box_count`, and `object_label = mixed`
|
||||
- Produces: DOM IDs `btnBatchStart`, `live-sack-count`, `live-box-count`, `today-sack-count`, `today-box-count`, `modalStopBatchSackCount`, and `modalStopBatchBoxCount`
|
||||
|
||||
- [ ] **Step 1: Write failing dashboard rendering tests**
|
||||
|
||||
Add Flask client tests that render `/` and assert:
|
||||
|
||||
```python
|
||||
html = self.client.get("/").get_data(as_text=True)
|
||||
self.assertIn('id="btnBatchStart"', html)
|
||||
self.assertNotIn('id="btnBatchStartSack"', html)
|
||||
self.assertNotIn('id="btnBatchStartBox"', html)
|
||||
self.assertIn('id="live-sack-count"', html)
|
||||
self.assertIn('id="live-box-count"', html)
|
||||
```
|
||||
|
||||
Also assert exports expose separate Sack and Box columns by reading returned XLSX with `openpyxl.load_workbook`.
|
||||
|
||||
- [ ] **Step 2: Run rendering tests and verify failure**
|
||||
|
||||
Run: `venv/bin/python -m unittest tests/test_dashboard.py -v`
|
||||
|
||||
Expected: FAIL because two start buttons and separate-count export columns do not exist.
|
||||
|
||||
- [ ] **Step 3: Replace both start controls**
|
||||
|
||||
In `templates/dashboard.html`, replace both buttons with one green button:
|
||||
|
||||
```html
|
||||
<button class="btn-batch btn-batch-start" id="btnBatchStart" type="button" onclick="handleStartBatch()">
|
||||
<i class="fas fa-play"></i> START BATCH <span id="lblNextBatch">#1</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
Remove `btn-batch-start-box` CSS. Keep the existing control-bar layout and touch target size.
|
||||
|
||||
- [ ] **Step 4: Show separate live and daily totals**
|
||||
|
||||
Add a secondary breakdown row under the active batch total with Sack and Box values. Keep combined total as primary metric. Add Sack and Box values under today's combined total.
|
||||
|
||||
Use existing CSS variables and muted-text treatment so hierarchy remains clear. Update JavaScript to populate new IDs from API fields and reset them to zero when idle.
|
||||
|
||||
- [ ] **Step 5: Update control-bar copy and behavior**
|
||||
|
||||
Change active and idle copy from class-specific wording to one batch counting both classes. Change `handleStartBatch()` to disable one button, call `POST /api/batch/start`, and show a combined-batch toast.
|
||||
|
||||
Update stop confirmation to display total, Sack, and Box counts separately.
|
||||
|
||||
- [ ] **Step 6: Update history and day-detail rendering**
|
||||
|
||||
Render new mixed batches with both counts. Keep legacy rows labeled Sack or Box readable. Replace type-based batch totals in the day-detail footer with counts of mixed, legacy Sack, and legacy Box rows without double counting.
|
||||
|
||||
- [ ] **Step 7: Update Excel exports**
|
||||
|
||||
In both export endpoints, select `sack_count` and `box_count`. Replace generic Type and Count columns with Sack, Box, and Total columns. Legacy rows use their stored class count for the matching column and zero for the other.
|
||||
|
||||
- [ ] **Step 8: Run dashboard and full tests**
|
||||
|
||||
Run: `venv/bin/python -m unittest discover -s tests -v`
|
||||
|
||||
Expected: all tests PASS.
|
||||
|
||||
- [ ] **Step 9: Run app smoke checks**
|
||||
|
||||
Run with temporary environment values:
|
||||
|
||||
```bash
|
||||
DB_PATH=/tmp/opencode/feedmill-test.db \
|
||||
CURRENT_BATCH_PATH=/tmp/opencode/feedmill-state.json \
|
||||
FLASK_APP=counter_dashboard.py \
|
||||
venv/bin/python -m flask --app counter_dashboard.py routes
|
||||
```
|
||||
|
||||
Expected: `/`, `/api/batch/start`, `/api/current-batch`, and `/api/summary` appear in route output.
|
||||
|
||||
Start the dashboard on an unused local port, request `/`, `/api/current-batch`, and `/api/summary`, then stop it. Expected: HTTP 200 responses and no template, JSON, or database errors.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Documentation and final verification
|
||||
|
||||
**Files:**
|
||||
- Modify: `API.md`
|
||||
- Modify: `README.md`
|
||||
- Modify: `docs/superpowers/specs/2026-11-13-unified-batch-design.md`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: final API response shapes and user-visible behavior
|
||||
- Produces: documentation matching unified start and separate totals
|
||||
|
||||
- [ ] **Step 1: Update API documentation**
|
||||
|
||||
Document unified `POST /api/batch/start`, legacy start aliases, `object_label = mixed`, `sack_count`, `box_count`, and `count` as total. Update current-batch and summary examples.
|
||||
|
||||
- [ ] **Step 2: Update operator documentation**
|
||||
|
||||
Replace references to choosing Start Sack or Start Box with one Start Batch action. Explain that each batch contains separate Sack and Box totals while the batch number and lifecycle are shared.
|
||||
|
||||
- [ ] **Step 3: Mark design implementation status**
|
||||
|
||||
Append a short implementation note to the design document naming completed files and verification commands. Do not change approved design decisions.
|
||||
|
||||
- [ ] **Step 4: Run complete verification**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
venv/bin/python -m unittest discover -s tests -v
|
||||
venv/bin/python -m py_compile batch_store.py counter_control.py counter_dashboard.py tests/test_batch_store.py tests/test_dashboard.py
|
||||
```
|
||||
|
||||
Expected: all tests PASS and compilation exits 0.
|
||||
|
||||
Start dashboard with temporary DB and state paths. Exercise:
|
||||
|
||||
1. `GET /` renders one START BATCH button.
|
||||
2. `POST /api/batch/start` reaches the unified start command.
|
||||
3. `GET /api/current-batch` returns total, Sack, and Box fields.
|
||||
4. `GET /api/summary` returns separate totals.
|
||||
5. Day-detail and both XLSX exports include Sack and Box values.
|
||||
|
||||
Expected: no server errors, template errors, or schema errors.
|
||||
|
||||
- [ ] **Step 5: Checkpoint**
|
||||
|
||||
List changed files and summarize test output. Do not claim completion unless the recorded commands pass.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Unified Batch Design
|
||||
|
||||
## Intent
|
||||
|
||||
Replace separate `START SACK` and `START BOX` actions with one `START BATCH` action. Each batch counts sacks and boxes together while preserving separate Sack and Box totals.
|
||||
|
||||
## Goals
|
||||
|
||||
- One visible Start Batch control.
|
||||
- One batch ID and one Start/Stop lifecycle for both object classes.
|
||||
- Separate live, daily, history, and export totals for Sack and Box.
|
||||
- Preserve existing batch history and totals.
|
||||
- Keep existing API consumers working where practical.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Redesign dashboard visual style.
|
||||
- Change object detection, confidence, tracking, or line-crossing logic.
|
||||
- Change batch numbering or daily cutoff behavior.
|
||||
|
||||
## Constraints
|
||||
|
||||
- Current `batches` table stores one count and one object label per row.
|
||||
- Current `daily_summaries` table stores totals by object label.
|
||||
- Existing records use `sack` or `box` labels and must remain readable.
|
||||
- Active batch state persists as JSON and must resume safely.
|
||||
|
||||
## Approaches considered
|
||||
|
||||
### 1. One batch row with separate counters, selected
|
||||
|
||||
Add `sack_count` and `box_count` to `batches` and `daily_summaries`. Keep `count` as total count for compatibility. New batches use `object_label = mixed`. API responses add `sack_count` and `box_count` while keeping `count` as total.
|
||||
|
||||
This gives one clean batch row, correct batch totals, and separate class totals.
|
||||
|
||||
### 2. Two rows per batch
|
||||
|
||||
Insert one Sack row and one Box row for each batch. This avoids schema changes but creates duplicate history entries and incorrect batch counts.
|
||||
|
||||
Rejected.
|
||||
|
||||
### 3. UI-only button merge
|
||||
|
||||
Keep the type-locked backend and expose one button. This cannot provide separate Sack and Box totals inside one batch.
|
||||
|
||||
Rejected.
|
||||
|
||||
## Design
|
||||
|
||||
### Batch state and counting
|
||||
|
||||
- `BatchStore.start_new_batch()` creates one mixed batch.
|
||||
- State stores `sack_count`, `box_count`, and total `count`.
|
||||
- `record_counted_object_crossing()` increments the matching class counter and total.
|
||||
- Both counted class IDs remain eligible while a batch is active.
|
||||
- Legacy active state converts safely: old Sack count becomes `sack_count`, old Box count becomes `box_count`.
|
||||
- Manual start aliases (`/start/sack`, `/start/box`) map to the same unified batch start behavior.
|
||||
|
||||
### Persistence
|
||||
|
||||
- Migrate `batches` with `sack_count INTEGER NOT NULL DEFAULT 0` and `box_count INTEGER NOT NULL DEFAULT 0`.
|
||||
- Migrate `daily_summaries` with the same fields.
|
||||
- Backfill legacy summary rows from `object_label` and `total_count`.
|
||||
- New mixed batch persists one row, increments overall total once, and updates both class totals.
|
||||
- Existing rows remain unchanged except backfilled compatibility fields.
|
||||
|
||||
### Dashboard
|
||||
|
||||
- Replace two Start buttons with one `START BATCH` button.
|
||||
- Active batch card shows total count plus separate Sack and Box counts.
|
||||
- Stop confirmation shows separate Sack and Box totals.
|
||||
- Today summary shows separate Sack and Box totals below combined total.
|
||||
- Recent batch and day-detail views show separate Sack and Box counts.
|
||||
- Existing visual system stays unchanged.
|
||||
|
||||
### APIs and exports
|
||||
|
||||
- Batch status, current batch, day detail, recent batches, previous batch, and summary responses add `sack_count` and `box_count`.
|
||||
- `count` remains total count for backward compatibility.
|
||||
- Excel exports add separate Sack and Box columns.
|
||||
- API documentation updates examples and endpoint behavior.
|
||||
|
||||
## Verification
|
||||
|
||||
- Unit tests cover mixed counting, persistence, migration, and API response fields.
|
||||
- Flask test client checks unified start behavior and dashboard rendering.
|
||||
- Python compilation and test suite run after changes.
|
||||
- Dashboard starts locally without template or API errors.
|
||||
|
||||
## Implementation status
|
||||
|
||||
Implemented 2026-11-13.
|
||||
|
||||
Changed files:
|
||||
- `batch_store.py`: `ensure_batch_schema()` migration, mixed active state, unified `start_new_batch()`, separate class counters, one mixed batch row and one mixed daily summary row.
|
||||
- `counter_control.py`: unified `start` aliases, stop response with total, Sack, Box counts.
|
||||
- `counter_dashboard.py`: unified start routes, `sack_count`/`box_count` in current-batch, batch-status fallback, previous-batch, day-detail, recent-batches, summary; XLSX exports now carry Sack, Box, Total columns.
|
||||
- `templates/dashboard.html`: one `START BATCH` button, live and today Sack/Box breakdown, stop modal totals, recent and day-detail rendering with both counts.
|
||||
- `API.md`, `README.md`: updated endpoint behavior and operator instructions.
|
||||
- `tests/test_batch_store.py`, `tests/test_dashboard.py`: store, API, control, rendering, and export coverage.
|
||||
|
||||
Verification: `venv/bin/python -m unittest discover -s tests -v` (19 tests) passes, `venv/bin/python -m py_compile batch_store.py counter_control.py counter_dashboard.py tests/test_batch_store.py tests/test_dashboard.py` exits 0, and the dashboard serves `/`, `/api/current-batch`, `/api/summary`, `/api/batch/status` with HTTP 200 against a temporary database.
|
||||
@@ -0,0 +1,33 @@
|
||||
[Unit]
|
||||
Description=RKNN Sack Counter (RTSP + ByteTrack)
|
||||
Documentation=file:///opt/feedmill/DEPLOY.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
|
||||
WorkingDirectory=/opt/feedmill
|
||||
|
||||
EnvironmentFile=/opt/feedmill/.env
|
||||
Environment=PYTHONNOUSERSITE=1
|
||||
Environment=PATH=/opt/feedmill/venv/bin:/usr/local/bin:/usr/bin:/bin
|
||||
|
||||
ExecStart=/opt/feedmill/venv/bin/python counter_live_rknn.py
|
||||
|
||||
TimeoutStopSec=30
|
||||
KillSignal=SIGTERM
|
||||
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
StartLimitInterval=120s
|
||||
StartLimitBurst=5
|
||||
|
||||
NoNewPrivileges=true
|
||||
ProtectHome=true
|
||||
PrivateTmp=false
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,33 @@
|
||||
[Unit]
|
||||
Description=RKNN Counter Dashboard (Flask, port 7000)
|
||||
Documentation=file:///opt/feedmill/DEPLOY.md
|
||||
After=network-online.target feedmill-counter.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
|
||||
WorkingDirectory=/opt/feedmill
|
||||
|
||||
EnvironmentFile=/opt/feedmill/.env
|
||||
Environment=PATH=/opt/feedmill/venv/bin:/usr/local/bin:/usr/bin:/bin
|
||||
Environment=FLASK_DEBUG=false
|
||||
|
||||
ExecStart=/opt/feedmill/venv/bin/python counter_dashboard.py
|
||||
|
||||
TimeoutStopSec=15
|
||||
KillSignal=SIGTERM
|
||||
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
StartLimitInterval=60s
|
||||
StartLimitBurst=3
|
||||
|
||||
NoNewPrivileges=true
|
||||
ProtectHome=true
|
||||
PrivateTmp=false
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install RKNN sack counter + dashboard services.
|
||||
# Run on the target device: sudo ./install-services.sh
|
||||
set -euo pipefail
|
||||
|
||||
INSTALL_DIR="${INSTALL_DIR:-/opt/feedmill}"
|
||||
VENV_DIR="${VENV_DIR:-/opt/feedmill/venv}"
|
||||
SERVICE_USER="${SERVICE_USER:-root}"
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "Run as root: sudo ./install-services.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -f "${INSTALL_DIR}/.env" ]]; then
|
||||
echo "Missing ${INSTALL_DIR}/.env"
|
||||
echo " cp ${INSTALL_DIR}/config.env.example ${INSTALL_DIR}/.env && nano ${INSTALL_DIR}/.env"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -x "${VENV_DIR}/bin/python" ]]; then
|
||||
echo "Missing venv: ${VENV_DIR}/bin/python"
|
||||
echo " sudo ./setup-venv.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sed -i 's/\r$//' "${INSTALL_DIR}/.env" 2>/dev/null || true
|
||||
|
||||
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
|
||||
|
||||
# Disable legacy service names
|
||||
for legacy in frigate-counter frigate-counter-dashboard feedmill feedmill-counter-dashboard; do
|
||||
if systemctl is-enabled "${legacy}" &>/dev/null; then
|
||||
systemctl disable --now "${legacy}" || true
|
||||
echo "Disabled legacy ${legacy}"
|
||||
fi
|
||||
done
|
||||
|
||||
for unit in feedmill-counter feedmill-dashboard; do
|
||||
sed -e "s|/opt/feedmill|${INSTALL_DIR}|g" \
|
||||
-e "s|User=root|User=${SERVICE_USER}|g" \
|
||||
-e "s|Group=root|Group=${SERVICE_USER}|g" \
|
||||
"${INSTALL_DIR}/${unit}.service" > "/etc/systemd/system/${unit}.service"
|
||||
echo "Installed /etc/systemd/system/${unit}.service"
|
||||
done
|
||||
|
||||
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
|
||||
|
||||
PYTHONNOUSERSITE=1 "${VENV_DIR}/bin/python" -c "
|
||||
from rknnlite.api import RKNNLite
|
||||
import cv2
|
||||
from flask import Flask
|
||||
print('import ok | rknn + opencv + flask')
|
||||
" || {
|
||||
echo "Import check failed — fix venv before starting services."
|
||||
exit 1
|
||||
}
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl reset-failed feedmill-counter feedmill-dashboard 2>/dev/null || true
|
||||
systemctl enable feedmill-counter feedmill-dashboard
|
||||
systemctl restart feedmill-counter feedmill-dashboard
|
||||
|
||||
echo ""
|
||||
systemctl --no-pager status feedmill-counter feedmill-dashboard || true
|
||||
echo ""
|
||||
echo "Logs: sudo journalctl -u feedmill-counter -f"
|
||||
echo "Dashboard: http://$(hostname -I | awk '{print $1}'):5000"
|
||||
@@ -0,0 +1,6 @@
|
||||
numpy<2
|
||||
rknn-toolkit-lite2
|
||||
opencv-python
|
||||
flask
|
||||
python-dotenv
|
||||
openpyxl
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-time venv for the RKNN sack counter.
|
||||
set -euo pipefail
|
||||
|
||||
INSTALL_DIR="${INSTALL_DIR:-/opt/feedmill}"
|
||||
VENV_DIR="${VENV_DIR:-/opt/feedmill/venv}"
|
||||
SERVICE_USER="${SERVICE_USER:-root}"
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "Run as root: sudo ./setup-venv.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
apt-get install -y python3-venv 2>/dev/null || true
|
||||
|
||||
mkdir -p "${INSTALL_DIR}"
|
||||
if [[ ! -x "${VENV_DIR}/bin/python" ]]; then
|
||||
python3 -m venv --system-site-packages "${VENV_DIR}"
|
||||
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"
|
||||
|
||||
sudo -u "${SERVICE_USER}" PYTHONNOUSERSITE=1 "${VENV_DIR}/bin/python" -c "
|
||||
from rknnlite.api import RKNNLite
|
||||
import cv2
|
||||
import flask
|
||||
import dotenv
|
||||
import openpyxl
|
||||
print('venv ok | rknn + opencv + flask + dotenv + openpyxl')
|
||||
"
|
||||
|
||||
echo ""
|
||||
echo "Next: cp config.env.example .env && nano .env && sudo ./install-services.sh"
|
||||
@@ -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 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
|
||||
<g transform="matrix(1,0,0,1,-15369.154492,-1214.474821)">
|
||||
<g transform="matrix(2.475521,0,0,1,13975.506392,1186.474821)">
|
||||
<g transform="matrix(0.906181,0,0,2.243269,-3748.32663,-602.148875)">
|
||||
<path d="M4914.259,451.079L4899.937,418.342C4890.938,397.773 4896.821,373.725 4914.3,359.634C4931.78,345.543 4956.528,344.897 4974.719,358.056L5091.331,442.412C5110.585,456.34 5118.613,481.126 5111.182,503.698C5103.75,526.269 5082.567,541.437 5058.804,541.202L5050.939,541.125L5073.639,592.72C5084.006,616.282 5076.598,643.883 5055.826,659.087C5035.054,674.292 5006.505,673.01 4987.178,656.006L4879.266,561.062C4859.513,543.682 4852.636,515.859 4862.018,491.278C4870.545,468.936 4890.872,453.546 4914.259,451.079ZM5024.451,523.597L5058.975,523.939C5075.22,524.099 5089.702,513.73 5094.783,498.299C5099.864,482.868 5094.375,465.923 5081.212,456.401L4964.6,372.045C4952.718,363.449 4936.553,363.872 4925.136,373.075C4913.719,382.279 4909.876,397.987 4915.754,411.422L4940.573,468.149L4938.895,468.131L4921.244,467.996C4902.142,467.85 4884.959,479.587 4878.147,497.434C4871.336,515.281 4876.329,535.482 4890.671,548.1L4998.583,643.045C5011.827,654.698 5031.393,655.576 5045.628,645.156C5059.864,634.736 5064.941,615.82 5057.836,599.673L5026.223,527.819L5024.451,523.597ZM4968.825,486.959L4968.329,485.718L4934.424,409.522C4931.427,402.786 4933.334,394.877 4939.071,390.247C4944.809,385.617 4952.942,385.424 4958.893,389.777L5066.605,468.558C5073.63,473.696 5076.548,482.773 5073.834,491.042C5071.119,499.312 5063.389,504.893 5054.686,504.868L4935.094,504.524C4929.238,504.507 4923.97,508.081 4921.821,513.529C4919.672,518.976 4921.081,525.184 4925.371,529.17L4933.661,536.872L4933.813,536.71C4931.614,534.38 4930.948,530.969 4932.148,527.964C4933.414,524.793 4936.498,522.727 4939.912,522.76L4965.007,523.009L4966.208,526.487L4994.023,589.707C4995.219,592.424 4996.967,594.863 4999.156,596.868L5011.424,608.101C5013.105,608.525 5014.94,608.223 5016.431,607.162C5018.776,605.494 5019.627,602.408 5018.468,599.773L4986.687,527.539L4984.872,523.205L5004.848,523.403L5006.718,528.303L5038.39,600.465C5042.406,609.614 5039.521,620.325 5031.454,626.221C5023.387,632.117 5012.306,631.612 5004.809,625.008L4906.732,538.616C4897.389,530.386 4894.151,517.211 4898.615,505.588C4903.08,493.964 4914.304,486.344 4926.755,486.484L4968.825,486.959ZM5010.315,487.427L5009.613,485.749L4990.183,439.967C4988.127,435.122 4984.795,430.926 4980.542,427.825L4965.157,416.607C4963.539,415.428 4961.33,415.49 4959.782,416.759C4958.234,418.027 4957.738,420.181 4958.576,421.999L4986.474,482.492L4988.527,487.181L5010.315,487.427Z" style="fill:white;"/>
|
||||
</g>
|
||||
<g transform="matrix(0.739983,0,0,1.831843,-7379.262587,-607.649374)">
|
||||
<rect x="10733" y="347" width="559" height="559" style="fill:none;"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.3 KiB |
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,223 @@
|
||||
import json
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import batch_store
|
||||
|
||||
|
||||
class BatchStoreUnifiedBatchTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.temp_dir.name)
|
||||
self.db_path = self.root / "feedmill.db"
|
||||
self.state_path = self.root / "current_batch.json"
|
||||
|
||||
def tearDown(self):
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
def make_store(self):
|
||||
return batch_store.BatchStore(
|
||||
db_path=self.db_path,
|
||||
state_file=self.state_path,
|
||||
camera_name="camera-a",
|
||||
cutoff_time="23:59",
|
||||
batch_mode="manual",
|
||||
logger=lambda _message: None,
|
||||
)
|
||||
|
||||
def test_mixed_batch_counts_sacks_and_boxes_separately(self):
|
||||
store = self.make_store()
|
||||
store.start_new_batch()
|
||||
|
||||
store.record_counted_object_crossing(1, object_label="sack")
|
||||
store.record_counted_object_crossing(2, object_label="box")
|
||||
|
||||
status = store.get_status()
|
||||
self.assertEqual(status["count"], 2)
|
||||
self.assertEqual(status["sack_count"], 1)
|
||||
self.assertEqual(status["box_count"], 1)
|
||||
self.assertEqual(status["object_label"], "mixed")
|
||||
store.db.close()
|
||||
|
||||
def test_same_track_id_counts_once_per_class(self):
|
||||
store = self.make_store()
|
||||
store.start_new_batch()
|
||||
|
||||
store.record_counted_object_crossing(7, object_label="sack")
|
||||
store.record_counted_object_crossing(7, object_label="box")
|
||||
|
||||
status = store.get_status()
|
||||
self.assertEqual(status["count"], 2)
|
||||
self.assertEqual(status["sack_count"], 1)
|
||||
self.assertEqual(status["box_count"], 1)
|
||||
store.db.close()
|
||||
|
||||
def test_legacy_active_state_resumes_as_mixed_and_accepts_both_classes(self):
|
||||
counting_date = "2026-11-13"
|
||||
self.state_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"counting_date": counting_date,
|
||||
"batch_number": 4,
|
||||
"object_label": "sack",
|
||||
"count": 4,
|
||||
"start_time": "2026-11-13T10:00:00",
|
||||
"last_detection_time": "2026-11-13T10:01:00",
|
||||
"counted_event_ids": ["1"],
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
with patch.object(
|
||||
batch_store.BatchStore, "get_counting_date", return_value=counting_date
|
||||
):
|
||||
store = batch_store.BatchStore(
|
||||
db_path=self.db_path,
|
||||
state_file=self.state_path,
|
||||
camera_name="camera-a",
|
||||
cutoff_time="23:59",
|
||||
batch_mode="manual",
|
||||
logger=lambda _message: None,
|
||||
)
|
||||
store.get_counting_date = lambda dt=None: counting_date
|
||||
|
||||
status = store.get_status()
|
||||
self.assertEqual(status["object_label"], "mixed")
|
||||
self.assertEqual(status["count"], 4)
|
||||
self.assertEqual(status["sack_count"], 4)
|
||||
self.assertEqual(status["box_count"], 0)
|
||||
|
||||
store.record_counted_object_crossing(2, object_label="box")
|
||||
status = store.get_status()
|
||||
self.assertEqual(status["count"], 5)
|
||||
self.assertEqual(status["sack_count"], 4)
|
||||
self.assertEqual(status["box_count"], 1)
|
||||
store.db.close()
|
||||
|
||||
def test_legacy_database_rows_are_backfilled_without_changing_totals(self):
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE batches (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
batch_number INTEGER NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
count INTEGER NOT NULL,
|
||||
start_time TEXT NOT NULL,
|
||||
end_time TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, batch_number, camera_name, object_label)
|
||||
);
|
||||
CREATE TABLE daily_summaries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
total_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_batches INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, camera_name, object_label)
|
||||
);
|
||||
INSERT INTO batches
|
||||
(counting_date, batch_number, camera_name, object_label, count, start_time, end_time)
|
||||
VALUES
|
||||
('2026-11-13', 1, 'camera-a', 'sack', 5, '2026-11-13T08:00:00', '2026-11-13T08:10:00');
|
||||
INSERT INTO daily_summaries
|
||||
(counting_date, camera_name, object_label, total_count, total_batches)
|
||||
VALUES
|
||||
('2026-11-13', 'camera-a', 'sack', 5, 1);
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
schema = getattr(batch_store, "ensure_batch_schema", None)
|
||||
self.assertIsNotNone(schema, "ensure_batch_schema must exist")
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
schema(conn)
|
||||
row = conn.execute(
|
||||
"SELECT total_count, sack_count, box_count FROM daily_summaries"
|
||||
).fetchone()
|
||||
conn.close()
|
||||
self.assertEqual(row, (5, 5, 0))
|
||||
|
||||
def test_mixed_batch_persists_one_row_with_separate_counts(self):
|
||||
store = self.make_store()
|
||||
store.start_new_batch()
|
||||
store.record_counted_object_crossing(1, object_label="sack")
|
||||
store.record_counted_object_crossing(2, object_label="box")
|
||||
|
||||
self.assertTrue(store.end_batch(closed_by="manual"))
|
||||
|
||||
row = store.db.execute(
|
||||
"""
|
||||
SELECT object_label, count, sack_count, box_count
|
||||
FROM batches
|
||||
"""
|
||||
).fetchone()
|
||||
self.assertEqual(row, ("mixed", 2, 1, 1))
|
||||
store.db.close()
|
||||
|
||||
def test_mixed_daily_summary_counts_batch_once(self):
|
||||
store = self.make_store()
|
||||
store.start_new_batch()
|
||||
store.record_counted_object_crossing(1, object_label="sack")
|
||||
store.record_counted_object_crossing(2, object_label="box")
|
||||
store.end_batch(closed_by="manual")
|
||||
|
||||
row = store.db.execute(
|
||||
"""
|
||||
SELECT object_label, total_count, total_batches, sack_count, box_count
|
||||
FROM daily_summaries
|
||||
"""
|
||||
).fetchone()
|
||||
self.assertEqual(row, ("mixed", 2, 1, 1, 1))
|
||||
store.db.close()
|
||||
|
||||
def test_empty_manual_batch_is_persisted(self):
|
||||
store = self.make_store()
|
||||
store.start_new_batch()
|
||||
|
||||
self.assertTrue(store.end_batch(closed_by="manual"))
|
||||
|
||||
batch_count = store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0]
|
||||
summary_row = store.db.execute(
|
||||
"SELECT total_count, total_batches, sack_count, box_count FROM daily_summaries"
|
||||
).fetchone()
|
||||
self.assertEqual(batch_count, 1)
|
||||
self.assertEqual(summary_row, (0, 1, 0, 0))
|
||||
store.db.close()
|
||||
|
||||
def test_morning_cutoff_0600_assigns_early_morning_to_previous_day(self):
|
||||
from datetime import datetime
|
||||
|
||||
store = batch_store.BatchStore(
|
||||
db_path=self.db_path,
|
||||
state_file=self.state_path,
|
||||
camera_name="camera-a",
|
||||
cutoff_time="06:00",
|
||||
batch_mode="manual",
|
||||
logger=lambda _message: None,
|
||||
)
|
||||
self.assertEqual(
|
||||
store.get_counting_date(datetime(2026, 11, 17, 5, 59, 59)),
|
||||
"2026-11-16",
|
||||
)
|
||||
self.assertEqual(
|
||||
store.get_counting_date(datetime(2026, 11, 17, 6, 0, 0)),
|
||||
"2026-11-17",
|
||||
)
|
||||
self.assertEqual(
|
||||
store.get_counting_date(datetime(2026, 11, 16, 21, 30, 0)),
|
||||
"2026-11-16",
|
||||
)
|
||||
store.db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,269 @@
|
||||
import sys
|
||||
import unittest
|
||||
from collections import deque
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import rknnlite.api # noqa: F401
|
||||
except ImportError:
|
||||
sys.modules.setdefault("rknnlite", MagicMock())
|
||||
sys.modules.setdefault("rknnlite.api", MagicMock())
|
||||
|
||||
import counter_live_rknn as clr
|
||||
|
||||
|
||||
def _run_crossing_step(
|
||||
detections,
|
||||
frame_idx,
|
||||
mono,
|
||||
line_pos,
|
||||
counted_tracked,
|
||||
counted_line_crossed,
|
||||
recent_crossings,
|
||||
axis="y",
|
||||
direction="down",
|
||||
):
|
||||
"""Run one frame of the crossing and dedup logic matching counter_live_rknn.run()."""
|
||||
active_tids = {tid for tid, _, _ in detections}
|
||||
crossings = []
|
||||
|
||||
for tid, cx, cy in detections:
|
||||
pos = cy if axis == "y" else cx
|
||||
along_pos = cx if axis == "y" else cy
|
||||
|
||||
if tid in counted_tracked:
|
||||
prev_cx, prev_cy, _ = counted_tracked[tid]
|
||||
prev_pos = prev_cy if axis == "y" else prev_cx
|
||||
if (
|
||||
clr.crossed_line(prev_pos, pos, line_pos, direction=direction)
|
||||
and tid not in counted_line_crossed
|
||||
):
|
||||
if clr.is_duplicate_cross(
|
||||
recent_crossings, along_pos, frame_idx, active_tids=active_tids
|
||||
):
|
||||
counted_line_crossed.add(tid)
|
||||
counted_tracked[tid] = (cx, cy, mono)
|
||||
continue
|
||||
recent_crossings.append((frame_idx, along_pos, tid))
|
||||
counted_line_crossed.add(tid)
|
||||
crossings.append(tid)
|
||||
|
||||
counted_tracked[tid] = (cx, cy, mono)
|
||||
|
||||
return crossings
|
||||
|
||||
|
||||
class CrossingGuardsTests(unittest.TestCase):
|
||||
def test_kalman_filter_q_shape_and_zero_cross_axis_coupling(self):
|
||||
trk = clr.KalmanBoxTracker([250.0, 40.0, 350.0, 160.0])
|
||||
self.assertEqual(trk.kf.P.shape, (8, 8))
|
||||
|
||||
# Strictly vertical motion: dx = 0, dy = +25 px/frame, constant size 100x120.
|
||||
for frame in (1, 2):
|
||||
trk.predict()
|
||||
self.assertEqual(trk.kf.P.shape, (8, 8))
|
||||
self.assertEqual(float(trk.kf.P[0, 1]), 0.0)
|
||||
actual = np.array(
|
||||
[250.0, 40.0 + frame * 25.0, 350.0, 160.0 + frame * 25.0],
|
||||
dtype=np.float32,
|
||||
)
|
||||
trk.update(actual)
|
||||
|
||||
vx = float(trk.kf.x[4, 0])
|
||||
vy = float(trk.kf.x[5, 0])
|
||||
self.assertAlmostEqual(vx, 0.0, places=5)
|
||||
self.assertGreater(vy, 20.0)
|
||||
|
||||
# Frame 3 missed detection (predict only), then frame 4 prediction check.
|
||||
trk.predict()
|
||||
trk.predict()
|
||||
pred_f4 = trk.get_state()
|
||||
actual_f4 = np.array(
|
||||
[250.0, 40.0 + 4 * 25.0, 350.0, 160.0 + 4 * 25.0],
|
||||
dtype=np.float32,
|
||||
)
|
||||
iou = float(clr._ious_xyxy(pred_f4[None], actual_f4[None])[0, 0])
|
||||
self.assertGreater(iou, 0.8)
|
||||
|
||||
def test_bytetrack_second_stage_continuation_and_class_high_threshold(self):
|
||||
tracker = clr.ByteTracker(
|
||||
track_high_thresh=0.25,
|
||||
track_low_thresh=0.1,
|
||||
match_thresh=0.3,
|
||||
track_buffer=30,
|
||||
min_hits=3,
|
||||
)
|
||||
|
||||
# High-score sack detection (>= 0.3) spawns a track.
|
||||
_, det_to_track, _ = tracker.update(
|
||||
np.array([[200.0, 100.0, 300.0, 220.0]], dtype=np.float32),
|
||||
np.array([0.45], dtype=np.float32),
|
||||
high_thresholds=np.array([0.3], dtype=np.float32),
|
||||
)
|
||||
self.assertIn(0, det_to_track)
|
||||
tid = det_to_track[0]
|
||||
|
||||
# Score drops to 0.15 (< 0.3, >= 0.1) for two consecutive frames: Stage 2 keeps ID.
|
||||
for offset in (15.0, 30.0):
|
||||
_, det_to_track, _ = tracker.update(
|
||||
np.array([[200.0, 100.0 + offset, 300.0, 220.0 + offset]], dtype=np.float32),
|
||||
np.array([0.15], dtype=np.float32),
|
||||
high_thresholds=np.array([0.3], dtype=np.float32),
|
||||
)
|
||||
self.assertEqual(det_to_track.get(0), tid)
|
||||
|
||||
# Unmatched detection with score 0.26 (>= 0.25 track_high_thresh, < 0.3 SACK_CONF)
|
||||
# must NOT spawn a new track.
|
||||
_, det_to_track, _ = tracker.update(
|
||||
np.array([[420.0, 100.0, 500.0, 200.0]], dtype=np.float32),
|
||||
np.array([0.26], dtype=np.float32),
|
||||
high_thresholds=np.array([0.3], dtype=np.float32),
|
||||
)
|
||||
self.assertEqual(det_to_track, {})
|
||||
|
||||
def test_simultaneous_sacks_crossing_within_dedup_px_are_both_counted(self):
|
||||
with patch.object(clr, "DEDUP_FRAMES", 4), patch.object(clr, "DEDUP_PX", 35.0):
|
||||
# Case A: two active tracks cross on the exact same frame within 15px.
|
||||
counted_tracked = {}
|
||||
counted_line_crossed = set()
|
||||
recent_crossings = deque()
|
||||
line_pos = 161.0
|
||||
|
||||
c1 = _run_crossing_step(
|
||||
[(1, 250.0, 150.0), (2, 265.0, 152.0)],
|
||||
frame_idx=1,
|
||||
mono=1.0,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
self.assertEqual(c1, [])
|
||||
|
||||
c2 = _run_crossing_step(
|
||||
[(1, 250.0, 168.0), (2, 265.0, 170.0)],
|
||||
frame_idx=2,
|
||||
mono=1.04,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
self.assertEqual(c2, [1, 2])
|
||||
|
||||
# Case B: two active tracks cross 2 frames apart within 15px while both stay active.
|
||||
counted_tracked = {}
|
||||
counted_line_crossed = set()
|
||||
recent_crossings = deque()
|
||||
|
||||
_run_crossing_step(
|
||||
[(1, 250.0, 150.0), (2, 265.0, 150.0)],
|
||||
frame_idx=1,
|
||||
mono=2.0,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
c2 = _run_crossing_step(
|
||||
[(1, 250.0, 168.0), (2, 265.0, 159.0)],
|
||||
frame_idx=2,
|
||||
mono=2.04,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
self.assertEqual(c2, [1])
|
||||
|
||||
c4 = _run_crossing_step(
|
||||
[(1, 250.0, 185.0), (2, 265.0, 168.0)],
|
||||
frame_idx=4,
|
||||
mono=2.12,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
self.assertEqual(c4, [2])
|
||||
|
||||
def test_id_switch_duplicate_blocked_when_old_track_inactive(self):
|
||||
with patch.object(clr, "DEDUP_FRAMES", 4), patch.object(clr, "DEDUP_PX", 35.0):
|
||||
recent_crossings = deque([(10, 250.0, 1)])
|
||||
|
||||
# Old track tid=1 has disappeared (not in active_tids): new track tid=2 is blocked.
|
||||
self.assertTrue(
|
||||
clr.is_duplicate_cross(
|
||||
recent_crossings, 260.0, frame_idx=12, active_tids={2}
|
||||
)
|
||||
)
|
||||
# When tid=1 is still active alongside tid=2, it is not blocked.
|
||||
self.assertFalse(
|
||||
clr.is_duplicate_cross(
|
||||
recent_crossings, 260.0, frame_idx=12, active_tids={1, 2}
|
||||
)
|
||||
)
|
||||
|
||||
def test_inheritance_guard_is_removed(self):
|
||||
self.assertFalse(hasattr(clr, "_inherit_prev"))
|
||||
self.assertFalse(hasattr(clr, "INHERIT_SEC"))
|
||||
self.assertFalse(hasattr(clr, "INHERIT_PX"))
|
||||
|
||||
with patch.object(clr, "DEDUP_FRAMES", 4), patch.object(clr, "DEDUP_PX", 35.0):
|
||||
counted_tracked = {}
|
||||
counted_line_crossed = set()
|
||||
recent_crossings = deque()
|
||||
line_pos = 161.0
|
||||
|
||||
# Track 1 crosses and then disappears.
|
||||
_run_crossing_step(
|
||||
[(1, 250.0, 150.0)],
|
||||
frame_idx=1,
|
||||
mono=1.0,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
c2 = _run_crossing_step(
|
||||
[(1, 250.0, 165.0)],
|
||||
frame_idx=2,
|
||||
mono=1.04,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
self.assertEqual(c2, [1])
|
||||
|
||||
# New track 2 appears upstream near track 1's crossed location on frame 8:
|
||||
# must NOT inherit track 1's crossed state.
|
||||
c8 = _run_crossing_step(
|
||||
[(2, 252.0, 155.0)],
|
||||
frame_idx=8,
|
||||
mono=1.28,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
self.assertEqual(c8, [])
|
||||
self.assertNotIn(2, counted_line_crossed)
|
||||
|
||||
# When track 2 actually crosses the line on frame 9, it counts once.
|
||||
c9 = _run_crossing_step(
|
||||
[(2, 252.0, 170.0)],
|
||||
frame_idx=9,
|
||||
mono=1.32,
|
||||
line_pos=line_pos,
|
||||
counted_tracked=counted_tracked,
|
||||
counted_line_crossed=counted_line_crossed,
|
||||
recent_crossings=recent_crossings,
|
||||
)
|
||||
self.assertEqual(c9, [2])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,332 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
import urllib.request
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
TEST_ROOT = Path(tempfile.mkdtemp(prefix="feedmill-dashboard-", dir="/tmp/opencode"))
|
||||
os.environ["DB_PATH"] = str(TEST_ROOT / "import.db")
|
||||
os.environ["STATE_FILE"] = str(TEST_ROOT / "import-state.json")
|
||||
|
||||
import counter_dashboard
|
||||
from counter_control import start_control_server
|
||||
|
||||
|
||||
class DashboardUnifiedBatchTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp_dir = tempfile.TemporaryDirectory(dir="/tmp/opencode")
|
||||
self.root = Path(self.temp_dir.name)
|
||||
self.db_path = self.root / "feedmill.db"
|
||||
self.state_path = self.root / "current_batch.json"
|
||||
counter_dashboard.DB_PATH = str(self.db_path)
|
||||
counter_dashboard.CURRENT_BATCH_PATH = str(self.state_path)
|
||||
counter_dashboard._ensure_db()
|
||||
self.client = counter_dashboard.app.test_client()
|
||||
|
||||
def tearDown(self):
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
def seed_batch(self, counting_date, batch_number=1, sack_count=3, box_count=2, plate="B 1234 XYZ"):
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO batches
|
||||
(counting_date, batch_number, camera_name, object_label, count,
|
||||
sack_count, box_count, plate, start_time, end_time)
|
||||
VALUES (?, ?, 'camera-a', 'mixed', ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
counting_date,
|
||||
batch_number,
|
||||
sack_count + box_count,
|
||||
sack_count,
|
||||
box_count,
|
||||
plate,
|
||||
f"{counting_date}T08:00:00",
|
||||
f"{counting_date}T08:10:00",
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO daily_summaries
|
||||
(counting_date, camera_name, object_label, total_count, total_batches,
|
||||
sack_count, box_count)
|
||||
VALUES (?, 'camera-a', 'mixed', ?, 1, ?, ?)
|
||||
""",
|
||||
(counting_date, sack_count + box_count, sack_count, box_count),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def test_dashboard_renders_single_start_button_and_separate_counters(self):
|
||||
html = self.client.get("/").get_data(as_text=True)
|
||||
|
||||
self.assertIn('id="btnBatchStart"', html)
|
||||
self.assertNotIn('id="btnBatchStartSack"', html)
|
||||
self.assertNotIn('id="btnBatchStartBox"', html)
|
||||
self.assertIn('id="live-sack-count"', html)
|
||||
self.assertIn('id="live-box-count"', html)
|
||||
self.assertIn('id="live-plate"', html)
|
||||
self.assertIn('id="today-sack-count"', html)
|
||||
self.assertIn('id="today-box-count"', html)
|
||||
self.assertIn('id="modalStopBatchSackCount"', html)
|
||||
self.assertIn('id="modalStopBatchBoxCount"', html)
|
||||
self.assertIn('id="modalStopBatchPlate"', html)
|
||||
|
||||
def test_daily_export_has_sack_and_box_columns(self):
|
||||
counting_date = counter_dashboard.get_counting_date()
|
||||
self.seed_batch(counting_date)
|
||||
|
||||
response = self.client.get("/api/export-daily-csv?days=30")
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
workbook = load_workbook(BytesIO(response.get_data()))
|
||||
sheet = workbook.active
|
||||
headers = [cell.value for cell in sheet[1]]
|
||||
self.assertIn("Plate", headers)
|
||||
self.assertIn("Sack", headers)
|
||||
self.assertIn("Box", headers)
|
||||
self.assertIn("Total", headers)
|
||||
row = [cell.value for cell in sheet[2]]
|
||||
self.assertEqual(row[headers.index("Plate")], "B 1234 XYZ")
|
||||
self.assertEqual(row[headers.index("Sack")], 3)
|
||||
self.assertEqual(row[headers.index("Box")], 2)
|
||||
self.assertEqual(row[headers.index("Total")], 5)
|
||||
|
||||
def test_day_export_has_sack_and_box_columns(self):
|
||||
counting_date = counter_dashboard.get_counting_date()
|
||||
self.seed_batch(counting_date)
|
||||
|
||||
response = self.client.get(f"/api/export-day-csv/{counting_date}")
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
workbook = load_workbook(BytesIO(response.get_data()))
|
||||
sheet = workbook.active
|
||||
headers = [cell.value for cell in sheet[1]]
|
||||
self.assertIn("Plate", headers)
|
||||
self.assertIn("Sack", headers)
|
||||
self.assertIn("Box", headers)
|
||||
self.assertIn("Total", headers)
|
||||
row = [cell.value for cell in sheet[2]]
|
||||
self.assertEqual(row[headers.index("Plate")], "B 1234 XYZ")
|
||||
self.assertEqual(row[headers.index("Sack")], 3)
|
||||
self.assertEqual(row[headers.index("Box")], 2)
|
||||
self.assertEqual(row[headers.index("Total")], 5)
|
||||
|
||||
def test_start_endpoint_sends_unified_start_command(self):
|
||||
with patch(
|
||||
"counter_dashboard._send_counter_command",
|
||||
return_value=({"success": True, "batch_number": 1}, 200),
|
||||
) as send:
|
||||
response = self.client.post("/api/batch/start")
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
send.assert_called_once_with("start")
|
||||
|
||||
def test_legacy_start_routes_send_unified_start_command(self):
|
||||
for path in ("/api/batch/start/sack", "/api/batch/start/box"):
|
||||
with self.subTest(path=path):
|
||||
with patch(
|
||||
"counter_dashboard._send_counter_command",
|
||||
return_value=({"success": True, "batch_number": 1}, 200),
|
||||
) as send:
|
||||
response = self.client.post(path)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
send.assert_called_once_with("start")
|
||||
|
||||
def test_current_batch_returns_separate_counts(self):
|
||||
self.state_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"counting_date": counter_dashboard.get_counting_date(),
|
||||
"batch_number": 4,
|
||||
"object_label": "mixed",
|
||||
"count": 5,
|
||||
"sack_count": 3,
|
||||
"box_count": 2,
|
||||
"start_time": "2026-11-13T08:00:00",
|
||||
"last_detection_time": "2026-11-13T08:01:00",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
response = self.client.get("/api/current-batch")
|
||||
data = response.get_json()
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(data["object_label"], "mixed")
|
||||
self.assertEqual(data["count"], 5)
|
||||
self.assertEqual(data["sack_count"], 3)
|
||||
self.assertEqual(data["box_count"], 2)
|
||||
|
||||
def test_summary_returns_separate_today_totals(self):
|
||||
counting_date = counter_dashboard.get_counting_date()
|
||||
self.seed_batch(counting_date)
|
||||
|
||||
response = self.client.get("/api/summary")
|
||||
data = response.get_json()
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(data["today"]["count"], 5)
|
||||
self.assertEqual(data["today"]["sack_count"], 3)
|
||||
self.assertEqual(data["today"]["box_count"], 2)
|
||||
self.assertEqual(data["all_time"]["count"], 5)
|
||||
self.assertEqual(data["all_time"]["sack_count"], 3)
|
||||
self.assertEqual(data["all_time"]["box_count"], 2)
|
||||
|
||||
def test_batch_status_fallback_returns_separate_counts(self):
|
||||
self.state_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"counting_date": counter_dashboard.get_counting_date(),
|
||||
"batch_number": 4,
|
||||
"object_label": "mixed",
|
||||
"count": 5,
|
||||
"sack_count": 3,
|
||||
"box_count": 2,
|
||||
"start_time": "2026-11-13T08:00:00",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with patch(
|
||||
"counter_dashboard.urllib.request.urlopen",
|
||||
side_effect=OSError("control server offline"),
|
||||
):
|
||||
response = self.client.get("/api/batch/status")
|
||||
|
||||
data = response.get_json()
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(data["count"], 5)
|
||||
self.assertEqual(data["sack_count"], 3)
|
||||
self.assertEqual(data["box_count"], 2)
|
||||
|
||||
def test_day_detail_returns_separate_counts(self):
|
||||
counting_date = counter_dashboard.get_counting_date()
|
||||
self.seed_batch(counting_date)
|
||||
|
||||
response = self.client.get(f"/api/day-detail/{counting_date}")
|
||||
data = response.get_json()
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(data["total_count"], 5)
|
||||
self.assertEqual(data["sack_count"], 3)
|
||||
self.assertEqual(data["box_count"], 2)
|
||||
self.assertEqual(data["batches"][0]["sack_count"], 3)
|
||||
self.assertEqual(data["batches"][0]["box_count"], 2)
|
||||
self.assertEqual(data["batches"][0]["plate"], "B 1234 XYZ")
|
||||
|
||||
def test_recent_and_previous_batches_return_separate_counts(self):
|
||||
counting_date = counter_dashboard.get_counting_date()
|
||||
self.seed_batch(counting_date)
|
||||
|
||||
recent = self.client.get("/api/recent-batches").get_json()
|
||||
previous = self.client.get("/api/previous-batch").get_json()
|
||||
|
||||
self.assertEqual(recent[0]["sack_count"], 3)
|
||||
self.assertEqual(recent[0]["box_count"], 2)
|
||||
self.assertEqual(recent[0]["plate"], "B 1234 XYZ")
|
||||
self.assertEqual(previous["sack_count"], 3)
|
||||
self.assertEqual(previous["box_count"], 2)
|
||||
self.assertEqual(previous["plate"], "B 1234 XYZ")
|
||||
|
||||
def test_control_server_stop_returns_separate_counts(self):
|
||||
class FakeStore:
|
||||
def get_status(self):
|
||||
return {
|
||||
"active": True,
|
||||
"batch_number": 7,
|
||||
"object_label": "mixed",
|
||||
"count": 5,
|
||||
"sack_count": 3,
|
||||
"box_count": 2,
|
||||
}
|
||||
|
||||
def end_batch(self, closed_by="manual"):
|
||||
return True
|
||||
|
||||
server = start_control_server(FakeStore(), port=0)
|
||||
self.addCleanup(server.shutdown)
|
||||
port = server.server_address[1]
|
||||
|
||||
request = urllib.request.Request(
|
||||
f"http://127.0.0.1:{port}/stop", data=b"", method="POST"
|
||||
)
|
||||
with urllib.request.urlopen(request) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
|
||||
self.assertEqual(data["count"], 5)
|
||||
self.assertEqual(data["sack_count"], 3)
|
||||
self.assertEqual(data["box_count"], 2)
|
||||
|
||||
def test_control_server_start_aliases_create_one_mixed_batch(self):
|
||||
class FakeStore:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def get_status(self):
|
||||
return {"active": False, "batch_number": None, "count": 0}
|
||||
|
||||
def start_new_batch(self, counting_date=None, object_label=None):
|
||||
self.calls.append((counting_date, object_label))
|
||||
return 7
|
||||
|
||||
store = FakeStore()
|
||||
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]
|
||||
|
||||
for path in ("/start/sack", "/start/box"):
|
||||
request = urllib.request.Request(
|
||||
f"http://127.0.0.1:{port}{path}",
|
||||
data=b"{}",
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=2) as response:
|
||||
self.assertEqual(response.status, 200)
|
||||
|
||||
self.assertEqual(store.calls, [(None, None), (None, None)])
|
||||
|
||||
def test_peer_sync_api_key_validation_and_body_forwarding(self):
|
||||
with patch("counter_dashboard._get_peer_api_token", return_value="secret-token"):
|
||||
bad = self.client.post(
|
||||
"/api/batch/start",
|
||||
headers={"X-API-Key": "wrong-token"},
|
||||
json={"plate": "B 1234 XYZ"},
|
||||
)
|
||||
self.assertEqual(bad.status_code, 401)
|
||||
self.assertFalse(bad.get_json()["success"])
|
||||
|
||||
with patch(
|
||||
"counter_dashboard._send_counter_command",
|
||||
return_value=({"success": True, "batch_number": 1}, 200),
|
||||
) as send:
|
||||
ok = self.client.post(
|
||||
"/api/batch/start",
|
||||
headers={"X-API-Key": "secret-token"},
|
||||
json={"plate": "B 1234 XYZ", "source": "fcp-semarang"},
|
||||
)
|
||||
self.assertEqual(ok.status_code, 200)
|
||||
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"])
|
||||
|
||||
|
||||
def tearDownModule():
|
||||
shutil.rmtree(TEST_ROOT, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# Remove RKNN counter systemd services.
|
||||
# Run on the target device: sudo ./uninstall-services.sh
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "Run as root: sudo ./uninstall-services.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for unit in feedmill-counter feedmill-dashboard feedmill feedmill-counter-dashboard; do
|
||||
systemctl stop "${unit}" 2>/dev/null || true
|
||||
systemctl disable "${unit}" 2>/dev/null || true
|
||||
rm -f "/etc/systemd/system/${unit}.service"
|
||||
done
|
||||
|
||||
systemctl daemon-reload
|
||||
echo "Removed feedmill-counter and feedmill-dashboard services."
|
||||
Binary file not shown.
Reference in new issue
Block a user