feat: migrate to all-in-one Intel OpenVINO architecture with local NVMe storage and adjustable cutoff

This commit is contained in:
proitlab committed 2026-12-03 12:04:29 +07:00
1 parent f051392739
commit 06eb562102
44 files changed
+35806 -3736

No files matched your search

+2
View File
@@ -51,6 +51,7 @@ wheels/
*.csv
*.log
*.tsv
kernel.errors.txt
# =============================================================================
# Media, Videos, Frames & Output Directories
@@ -58,6 +59,7 @@ wheels/
recount_output/
motioneye_media/
bundled_models/
*.zip
*.mp4
*.avi
*.mkv
+175
View File
@@ -0,0 +1,175 @@
# APC Ngoro — System Architecture, Business Logic & Single-Machine Migration Guide
## 1. Project Overview & Context
**APC Ngoro** (Automated Poultry Counter - Site Ngoro) is an edge AI computer-vision system designed for automated real-time poultry counting, batch consolidation, video recording, recounting validation, and operational reporting in slaughterhouse facilities.
### Evolution & Physical Topology
1. **Legacy Split Topology**:
- **NanoPi 1 (Edge RK3588, ARM64)**: Real-time video ingestion, RKNN NPU YOLO detection (`ngoro-all-2.rknn`), ByteTrack tracking, batch lifecycle management (`batch_store.py`), and Web Dashboard (`counter_dashboard.py` on port `5000`).
- **NanoPi 2 (Edge RK3588, ARM64)**: Recount Engine (`recount_engine/app.py` on port `8765`) running offline video playback, ByteTrack tracking, and count verification.
- **MotionEye Ingest Server (`192.168.192.251:8090`)**: HTTP ingest storage archiving completed batch `.mp4` videos in `/data/media/Camera1`.
2. **Unified Single-Machine Topology (`192.168.192.158`)**:
- Single Intel host running **all three components** (`Counter Live`, `Recount Engine`, `Dashboard`) under a single systemd supervisor unit (`apc-ngoro-service.service` → `scripts/apc_supervisor.py`) with isolated hardware resource allocation and local NVMe video storage (`batch_videos/` + `recount_output/`).
- **Hardware Specs**: Intel(R) Core(TM) Ultra 5 125H (Meteor Lake, 18 vCPUs), 16 GB RAM, 468 GB NVMe SSD, Intel Arc Graphics GPU, and Intel Meteor Lake NPU.
---
## 2. Core Business Logic & Invariants
### 2.1 Daily Cutoff & Counting Dates
- **Default Cutoff Time**: `20:00` (8:00 PM). Initialized from `DAILY_CUTOFF_TIME` / `CUTOFF_TIME` in `.env` and persisted in SQLite (`site_settings`).
- **Adjustable Cut-Off via Dashboard (`/api/cutoff-settings` & `cutoff_utils.py`)**:
- Operators can adjust the cut-off time (`HH:MM`, evening `>= 06:00` or post-midnight `< 06:00`) directly from the **Waktu Cut-off** card in the Operational Dashboard without restarting services (`BatchStore` refreshes every 2 seconds):
- **Temporary Per-Day Override (`cutoff_overrides`)**: Extends or changes a single counting day (e.g., Today or Yesterday) and automatically reverts to the default cut-off (`20:00`) on subsequent days.
- **Permanent Default Change (`site_settings` + `.env`)**: Updates the global default for all future operational days.
- **Retroactive Batch Reassignment & Active Batch Extension**: Optionally moves batches crossing the adjusted cut-off boundary between `target_date` and `target_date + 1 day`, renumbering both days cleanly while preserving all video/recount metadata and `daily_summaries`. Extending the cut-off after rollover also updates an in-flight active batch in-place without dropping it.
- An operational day runs from `Deadline(D - 1)` to `Deadline(D)` (e.g. `20:00` on day $D-1$ to `20:00` on day $D$). At `Deadline(D)`, counters reset when `RESET_COUNTERS_AT_CUTOFF=true`.
### 2.2 Batch & Sub-Batch Lifecycle Rules
- **Minimum Main Batch Threshold**: `MAIN_BATCH_MIN_COUNT = 700` chickens.
- **Noise Filtering Threshold**: `MIN_OBJECT_PER_BATCH=10`, `MIN_DURATION_PER_BATCH=10` (status `VALID` when meeting minimums, `PARTIAL` when `count >= 1` below minimums).
- **Inactivity Gap**: If no chicken crosses the counting line for `BATCH_TIMEOUT_SECONDS` (25 seconds), `_end_batch_locked()` closes the batch.
- **Batch Numbering & Merging Rules**:
- **Batch 1 Sub-Batch Exception (Future Counting Days > `2026-11-18`)**:
- If the very first batch(es) of a counting day close with `count < MAIN_BATCH_MIN_COUNT` (`< 700`), they do **not** become Main Batch `1`. Instead, they are assigned sub-batch labels (`1a`, `1b`, ...) and merge **forward** into the upcoming Main Batch `1` (the first batch of the day with `count >= 700`).
- Historical batches (`counting_date <= 2026-11-18`) retain their existing recorded Batch `1` designations in dashboards and exports.
- **Subsequent Batches (`>= 700` vs `< 700`)**:
- If `count >= 700`: Assigned the next sequential integer Main Batch number (`1`, `2`, `3`, ...).
- If `count < 700`: Assigned as a **Sub-Batch (Child Batch)** (`1b`, `2a`, `2b`, ...) merging **backward** into the preceding Main Batch (`get_last_main_batch_number`).
- **Query & State Safety (No Stuck Batches)**:
- `get_last_main_batch_number()` and `get_next_main_batch_number()` in `batch_store.py` filter `CAST(batch_number AS TEXT) NOT GLOB '*[a-zA-Z]*'` so pure-integer main batch numbering ignores sub-batch suffixes (`1a`, `1b`) without falling back to wrong integer casts (e.g., `CAST('1a' AS INTEGER) == 1`).
- Both queries execute without filtering `WHERE count >= 700` to prevent duplicate Batch 1 UNIQUE constraint collisions.
- `_end_batch_locked()` always clears `self.current_state = None` and cancels `self.batch_timer` inside error/cleanup paths so SQLite exceptions never poison memory state.
```mermaid
flowchart LR
subgraph DayStart ["Start of Counting Day (After 20:00 Cutoff)"]
B1a["1st Batch: Count = 15 (< 700)\nAssigned: '1a' (Sub-Batch)"]
B1["2nd Batch: Count = 1,350 (>= 700)\nAssigned: '1' (Main Batch 1)"]
B1b["3rd Batch: Count = 80 (< 700)\nAssigned: '1b' (Sub-Batch)"]
B2["4th Batch: Count = 1,400 (>= 700)\nAssigned: '2' (Main Batch 2)"]
end
B1a -- "Batch 1 Exception: Merges FORWARD\ninto Main Batch #1" --> B1
B1b -- "Standard Rule: Merges BACKWARD\ninto Main Batch #1" --> B1
```
### 2.3 Video Recording, Sub-Batch Saving, Retention & Recount UI Persistence
- **Race-Free Batch Video Recording (`batch_video_recorder.py` & `counter_live_rknn_bytetrack.py`)**:
- While a batch is open, `BatchVideoRecorder.start()` writes raw H.264 frames (`libx264 ultrafast` on SHM `/dev/shm/apc-ngoro`) to a unique monotonic `.partial.mp4` filename (`batch_<tentative_id>_<ms>_<seq>.partial.mp4`) so consecutive batches never unlink or overwrite each other.
- When `_end_batch_locked()` triggers `_on_batch_closed(meta)`:
- If discarded, `batch_recorder.stop_discard()` executes synchronously.
- If persisted (`meta["ok"]`), `batch_recorder.detach()` claims the active writer state synchronously before spawning the background `batch-finalize` thread, and `finalize(final_batch_id=meta["batch_id"], detached=detached)` names the output `batch_<final_batch_id>.mp4` (e.g., `batch_2026-11-18-22a.mp4`) using PID/thread-unique `.restamp.mp4` temp files.
- **Storage Routing**:
- On the unified Intel host (`192.168.192.158`), `_save_batch_video_local()` moves the finalized file directly into local NVMe `BATCH_VIDEO_DIR` (`/home/admin123/ngoro_project/batch_videos/batch_<id>.mp4`) and sets `video_url=/api/v1/recount/source/<id>`.
- On NanoPi (`motioneye_client.py`), `_upload_batch_video_async()` uploads to MotionEye Ingest (`192.168.192.251:8090`). If an ingest server validates with digits-only `batch_id` (`HTTP 400: invalid batch_id`), `upload_batch_video()` automatically retries using `encode_ingest_batch_id()` (`YYYY-MM-DD-22a` → `YYYY-MM-DD-2201`) and records the exact returned filename and URL in SQLite.
- Across `retention_utils.py`, `recount_engine/app.py`, `motioneye_ingest/app.py`, and `counter_dashboard.py`, `BATCH_ID_RE` accepts single- and multi-letter sub-batch suffixes (`^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]*$`).
- **Video Retention Policies**:
- **Recounted Overlay Videos (`batch_<id>_recount.mp4`) & Source Caches (`_src_<id>.mp4`)** in `recount_output/`:
- Retained for **6 hours** (`RECOUNT_OVERLAY_TTL_HOURS=6`), enforced hourly by `/etc/cron.d/apc-recount-cleanup` → `scripts/recount_overlay_cleanup.py`.
- Quantitative recount metadata (`recount_count`, `recount_delta`, `recount_video_url`) remains **permanently** in SQLite (`apc_ngoro.db`).
- **Original Batch Videos (`batch_<id>.mp4`)**:
- Retained for the latest **7 active counting days** on the Intel host (`ACTIVE_RETENTION_DAYS=7`, or `3` on NanoPi), enforced daily at `01:00` by `/etc/cron.d/apc-retention` → `scripts/retention_active_days.py`.
- **Recount Execution & UI Persistence (`templates/dashboard_recounting.html` & `recount_engine/app.py`)**:
- Recounts process video frames with ByteTrack, generate an annotated replay (`batch_<id>_recount.mp4`), compute $\Delta = \text{Recount Count} - \text{Original Count}$, and use `RECOUNT_START_COUNT=1` compensation.
- On page load, `loadBatches().finally(() => refreshStatusOnce())` ensures `batchIndex` is populated before status synchronization.
- Selecting or returning to any batch card with a completed recount (`recount_count != null`) invokes `openReplay(replayUrl, false)` instead of hiding the video element with `closeLiveStream(true)`, so `<video id="recount-replay">` persists across card switches. `applyStatus()` updates both `selectedBatch` and `batchIndex[data.batch_id]` when `COMPLETED`.
### 2.4 Excel Reporting Structure
Excel exports (`/api/export-day-xlsx/<date>` and `/api/export-daily-xlsx`) exclude the legacy `Status` column and render two stacked standalone tables on the same worksheet:
1. **Table 1 (`1. HITUNG AYAM POTONG (RINCIAN SELURUH BATCH)`)**:
- Columns: `Batch #`, `Tipe Batch`, `Hitung Ayam Potong`, `Catatan`, `Mulai`, `Selesai`, `Durasi (menit)` (plus `Tanggal` for daily exports).
- Lists every physical batch run chronologically (`order by start_time ASC, id ASC`), showing leading sub-batches (`1a`) with note `Digabung ke Batch 1` before Main Batch `1`.
- Includes summary **TOTAL** and **RATA-RATA** rows.
2. **Table 2 (`2. BATCH DISESUAIKAN (SETELAH PENYESUAIAN) - HANYA BATCH TETAP`)**:
- Columns: `Batch #`, `Tipe Batch`, `Batch Disesuaikan`, `Catatan`, `Mulai`, `Selesai`, `Durasi (menit)` (plus `Tanggal` for daily exports).
- Consolidates leading sub-batches (`1a`) and trailing sub-batches (`1b`, ...) into their Main Batch (`1`), computing earliest `start_time`, latest `end_time`, summed durations, and matching total counts.
- **Batches with 0 chickens are strictly excluded**.
---
## 3. Directory & File Manifest
| Path | Purpose |
| :--- | :--- |
| `batch_store.py` | SQLite batch persistence (WAL enabled on Intel host), numbering, dynamic cut-off state machine |
| `cutoff_utils.py` | Adjustable cut-off settings, per-day overrides, deadline computation, batch reconciliation |
| `counter_dashboard.py` | Flask web dashboard (port `5000`), REST APIs, SSE stream, Excel export generator |
| `counter_live_rknn_bytetrack.py` | Real-time RTSP ingest, OpenVINO/RKNN inference (`OpenVINOYOLO`), ByteTrack, local NVMe saver |
| `batch_video_recorder.py` | Async SHM H.264 segment recorder with `detach()`, unique `.partial.mp4`, FPS restamping |
| `recount_engine/app.py` | Flask recount engine (`port 8765`) with local NVMe resolution and OpenVINO inference |
| `scripts/apc_supervisor.py` | Unified single-machine process supervisor for Counter, Recount, and Dashboard |
| `systemd/apc-ngoro-service.service` | Systemd unit running `apc_supervisor.py` on `192.168.192.158` |
| `retention_utils.py` | Shared active counting date helpers and canonical `BATCH_ID_RE` |
| `scripts/recount_overlay_cleanup.py` | Hourly TTL cleanup for `recount_output/` (`RECOUNT_OVERLAY_TTL_HOURS=6`) |
| `scripts/retention_active_days.py` | Daily retention cleanup for `batch_videos/` (`ACTIVE_RETENTION_DAYS=7`) |
| `templates/` | `dashboard_operational.html`, `dashboard_recounting.html` |
| `static/` | CSS, JavaScript, icons, and branding assets |
| `models/` | Models including `best_openvino_model/`, `ngoro-all-2.onnx`, `ngoro-all-2.pt` |
| `batch_videos/` | NVMe source video archive on `192.168.192.158` (`batch_<id>.mp4` / `<id>.mp4`) |
| `recount_output/` | Recounted overlay MP4 outputs (`batch_<id>_recount.mp4`) |
| `apc_ngoro.db` | Primary SQLite database storing batch records and recount metadata |
---
## 4. Single Intel Machine Architecture & Resource Allocation
On `admin123@192.168.192.158`, `systemd/apc-ngoro-service.service` launches `scripts/apc_supervisor.py`, which isolates CPU affinity, OS nice priority, and OpenVINO accelerator devices across the 18-vCPU Meteor Lake hardware:
```mermaid
graph TD
subgraph Hardware ["Intel Core Ultra 5 125H (18 vCPUs, 16GB RAM, NVMe SSD)"]
ArcGPU["Intel Arc Graphics GPU\nOpenVINO device='GPU'"]
IntelNPU["Intel Meteor Lake NPU\nOpenVINO device='NPU'"]
PCores["CPU Cores 0-7 (P-Cores)"]
ECores["CPU Cores 8-15 (E-Cores)"]
DashCores["CPU Cores 14-17"]
end
subgraph Supervisor ["apc_supervisor.py (apc-ngoro-service.service)"]
COUNTER["[COUNTER] counter_live_rknn_bytetrack.py\nNice=-10 | LIVE_CPU_CORES=0-7 | LIVE_OPENVINO_DEVICE=GPU"]
RECOUNT["[RECOUNT] recount_engine/app.py\nNice=10 | RECOUNT_CPU_CORES=8-15 | RECOUNT_OPENVINO_DEVICE=NPU"]
DASHBOARD["[DASHBOARD] counter_dashboard.py\nNice=0 | DASHBOARD_CPU_CORES=14-17 | Port 5000"]
end
ArcGPU --> COUNTER
PCores --> COUNTER
IntelNPU --> RECOUNT
ECores --> RECOUNT
DashCores --> DASHBOARD
```
### Runtime Key Parameters (`.env` on `192.168.192.158`)
- **Inference & Affinity**:
- `MODEL_PATH=/home/admin123/ngoro_project/models/best_openvino_model`
- `LIVE_OPENVINO_DEVICE=GPU`, `LIVE_CPU_CORES=0-7`, `LIVE_INFERENCE_THREADS=4`
- `RECOUNT_OPENVINO_DEVICE=NPU`, `RECOUNT_CPU_CORES=8-15`, `RECOUNT_INFERENCE_THREADS=4`, `RECOUNT_FFMPEG_THREADS=4`
- `BATCH_RECORD_THREADS=2`
- **Local NVMe & Loopback Storage**:
- `BATCH_VIDEO_DIR=/home/admin123/ngoro_project/batch_videos`
- `RECOUNT_OUTPUT_DIR=/home/admin123/ngoro_project/recount_output`
- `RECOUNT_ENGINE_URL=http://127.0.0.1:8765`, `RECOUNT_PUBLIC_BASE=http://127.0.0.1:8765`
- `RECOUNT_LIVE_FRAME_PATH=/dev/shm/apc-ngoro/recount_live_frame.jpg`
- **SQLite Concurrency**:
- WAL journaling enabled (`PRAGMA journal_mode=WAL`, `PRAGMA synchronous=NORMAL`, `PRAGMA busy_timeout=5000`) for safe concurrent reads/writes between Counter Live, Dashboard, and Recount Engine.
---
## 5. Operations & Verification Commands on `192.168.192.158`
```bash
# Check unified service status & component logs
sudo systemctl status apc-ngoro-service.service
journalctl -u apc-ngoro-service.service -f
# Check local service endpoints
curl -s http://127.0.0.1:5000/api/health
curl -s http://127.0.0.1:8765/health
# Check retention timers/crons (dry-run)
/home/admin123/ngoro_project/venv/bin/python /home/admin123/ngoro_project/scripts/recount_overlay_cleanup.py --dry-run
/home/admin123/ngoro_project/venv/bin/python /home/admin123/ngoro_project/scripts/retention_active_days.py --dry-run
```
---
*Updated on 2026-11-18 with sub-batch video recording, recount UI persistence, Batch 1 sub-batch forward-merging, and unified supervisor architecture.*
+126 -85
View File
@@ -11,6 +11,8 @@ import time
from datetime import datetime, timedelta
from pathlib import Path
from cutoff_utils import compute_counting_date, ensure_cutoff_tables, load_cutoff_config
_SHMD = os.getenv("SHM_DIR", "/dev/shm/apc-ngoro")
_RESET_FLAG = Path(f"{_SHMD}/.reset")
@@ -37,6 +39,10 @@ class BatchStore:
self.object_label = object_label
self.cutoff_time_str = cutoff_time
datetime.strptime(cutoff_time, '%H:%M')
self._cutoff_lock = threading.Lock()
self._cutoff_cache_ts = 0.0
self._cutoff_default = self.cutoff_time_str
self._cutoff_overrides = {}
self.batch_timeout = float(batch_timeout)
self.ignore_batch_label_timeout = float(ignore_batch_label_timeout)
@@ -57,13 +63,16 @@ class BatchStore:
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.db = sqlite3.connect(db_path, timeout=10.0, check_same_thread=False)
self._init_db()
self.current_state = self._load_state()
self.previous_state = self.current_state
def _init_db(self):
cur = self.db.cursor()
cur.execute("PRAGMA journal_mode=WAL")
cur.execute("PRAGMA synchronous=NORMAL")
cur.execute("PRAGMA busy_timeout=5000")
cur.execute(
"""
CREATE TABLE IF NOT EXISTS batches (
@@ -108,14 +117,25 @@ class BatchStore:
except sqlite3.OperationalError:
pass
self.db.commit()
ensure_cutoff_tables(self.db, default_cutoff=self.cutoff_time_str)
def _get_cutoff_config(self):
with self._cutoff_lock:
now_mono = time.monotonic()
if (now_mono - self._cutoff_cache_ts) >= 2.0:
try:
default_co, overrides = load_cutoff_config(self.db, self.cutoff_time_str)
self._cutoff_default = default_co
self._cutoff_overrides = overrides
self.cutoff_time_str = default_co
except Exception:
pass
self._cutoff_cache_ts = now_mono
return self._cutoff_default, dict(self._cutoff_overrides)
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 dt.time() < cutoff:
return dt.date().isoformat()
return (dt.date() + timedelta(days=1)).isoformat()
default_cutoff, overrides = self._get_cutoff_config()
return compute_counting_date(dt, default_cutoff, overrides)
def _load_state(self):
if not self.state_file.exists():
@@ -162,45 +182,28 @@ class BatchStore:
json.dump(self.current_state, f, indent=2, ensure_ascii=False)
def assign_batch_number(self, counting_date, count):
cur = self.db.cursor()
cur.execute(
"""
SELECT COUNT(*)
FROM batches
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
""",
(counting_date, self.camera_name, self.object_label),
)
total_existing = cur.fetchone()[0]
# Rule: Sub-batch does not apply to the first batch of the day
if total_existing == 0:
return "1", True
if count >= self.main_batch_min_count:
return str(self.get_next_main_batch_number(counting_date)), True
else:
prev_main = self.get_last_main_batch_number(counting_date) or 1
letter = self.get_next_sub_batch_letter(counting_date, prev_main)
return f"{prev_main}{letter}", False
# Exception for Batch 1: if no main batch exists yet today,
# this leading sub-batch merges forward into upcoming Main Batch 1 (1a, 1b, ...).
target_main = self.get_last_main_batch_number(counting_date) or 1
letter = self.get_next_sub_batch_letter(counting_date, target_main)
return f"{target_main}{letter}", False
def get_last_main_batch_number(self, counting_date):
cur = self.db.cursor()
cur.execute(
"""
SELECT batch_number
SELECT MAX(CAST(batch_number AS INTEGER))
FROM batches
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
ORDER BY id DESC
LIMIT 1
AND CAST(batch_number AS TEXT) NOT GLOB '*[a-zA-Z]*'
""",
(counting_date, self.camera_name, self.object_label),
)
row = cur.fetchone()
if row:
m = re.match(r"^(\d+)", str(row[0]))
return int(m.group(1)) if m else None
return None
return int(row[0]) if row and row[0] is not None else None
def get_next_main_batch_number(self, counting_date):
cur = self.db.cursor()
@@ -209,12 +212,26 @@ class BatchStore:
SELECT COALESCE(MAX(CAST(batch_number AS INTEGER)), 0)
FROM batches
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
AND CAST(batch_number AS TEXT) NOT GLOB '*[a-zA-Z]*'
""",
(counting_date, self.camera_name, self.object_label),
)
val = cur.fetchone()[0]
return val + 1
@staticmethod
def _increment_sub_letter(last: str) -> str:
"""Increment alphabetical sub-batch suffix (a..z -> aa..az -> ba.. -> aaa)."""
if not last:
return 'a'
chars = list(last.lower())
for idx in range(len(chars) - 1, -1, -1):
if chars[idx] < 'z':
chars[idx] = chr(ord(chars[idx]) + 1)
return ''.join(chars)
chars[idx] = 'a'
return 'a' * (len(chars) + 1)
def get_next_sub_batch_letter(self, counting_date, main_batch_num):
cur = self.db.cursor()
cur.execute(
@@ -236,11 +253,8 @@ class BatchStore:
letters.append(suffix.lower())
if not letters:
return 'a'
letters.sort()
last = letters[-1]
if last == 'z':
return 'aa'
return chr(ord(last) + 1)
letters.sort(key=lambda s: (len(s), s))
return self._increment_sub_letter(letters[-1])
def get_next_batch_number(self, counting_date):
cur = self.db.cursor()
@@ -330,9 +344,18 @@ class BatchStore:
self.start_new_batch(counting_date)
started_new = True
elif self.current_state['counting_date'] != counting_date:
self._end_batch_locked(closed_by='cutoff')
self.start_new_batch(counting_date)
started_new = True
if counting_date < self.current_state['counting_date']:
self.current_state['counting_date'] = counting_date
self.current_state['batch_number'] = self.get_next_batch_number(counting_date)
self.save_state()
self.log(
f'Extended cut-off applied to active batch -> '
f'{counting_date} #{self.current_state["batch_number"]}'
)
else:
self._end_batch_locked(closed_by='cutoff')
self.start_new_batch(counting_date)
started_new = True
event_key = str(track_id)
if event_key not in self.current_state['counted_event_ids']:
@@ -497,26 +520,30 @@ class BatchStore:
return meta
def set_batch_video(self, counting_date, batch_number, video_filename=None, video_url=None):
cur = self.db.cursor()
cur.execute(
"""
UPDATE batches
SET video_filename = COALESCE(?, video_filename),
video_url = COALESCE(?, video_url)
WHERE counting_date = ? AND batch_number = ?
AND camera_name = ? AND object_label = ?
""",
(
video_filename,
video_url,
counting_date,
batch_number,
self.camera_name,
self.object_label,
),
)
self.db.commit()
return cur.rowcount > 0
bn_str = str(batch_number)
bn_int = int(bn_str) if bn_str.isdigit() else bn_str
with self.state_lock:
cur = self.db.cursor()
cur.execute(
"""
UPDATE batches
SET video_filename = COALESCE(?, video_filename),
video_url = COALESCE(?, video_url)
WHERE counting_date = ? AND (batch_number = ? OR batch_number = ?)
AND camera_name = ? AND object_label = ?
""",
(
video_filename,
video_url,
counting_date,
bn_str,
bn_int,
self.camera_name,
self.object_label,
),
)
self.db.commit()
return cur.rowcount > 0
def set_batch_recount(
self,
@@ -526,28 +553,32 @@ class BatchStore:
recount_delta=None,
recount_video_url=None,
):
cur = self.db.cursor()
cur.execute(
"""
UPDATE batches
SET recount_count = COALESCE(?, recount_count),
recount_delta = COALESCE(?, recount_delta),
recount_video_url = COALESCE(?, recount_video_url)
WHERE counting_date = ? AND batch_number = ?
AND camera_name = ? AND object_label = ?
""",
(
recount_count,
recount_delta,
recount_video_url,
counting_date,
batch_number,
self.camera_name,
self.object_label,
),
)
self.db.commit()
return cur.rowcount > 0
bn_str = str(batch_number)
bn_int = int(bn_str) if bn_str.isdigit() else bn_str
with self.state_lock:
cur = self.db.cursor()
cur.execute(
"""
UPDATE batches
SET recount_count = COALESCE(?, recount_count),
recount_delta = COALESCE(?, recount_delta),
recount_video_url = COALESCE(?, recount_video_url)
WHERE counting_date = ? AND (batch_number = ? OR batch_number = ?)
AND camera_name = ? AND object_label = ?
""",
(
recount_count,
recount_delta,
recount_video_url,
counting_date,
bn_str,
bn_int,
self.camera_name,
self.object_label,
),
)
self.db.commit()
return cur.rowcount > 0
def _insert_batch(self, counting_date, batch_number, count, start_time, end_time, status='VALID', is_main=True):
cur = self.db.cursor()
@@ -595,9 +626,19 @@ class BatchStore:
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')
new_counting_date = self.get_counting_date()
if self.current_state['counting_date'] != new_counting_date:
if new_counting_date < self.current_state['counting_date']:
self.current_state['counting_date'] = new_counting_date
self.current_state['batch_number'] = self.get_next_batch_number(new_counting_date)
self.save_state()
self.log(
f'Extended cut-off applied to active batch -> '
f'{new_counting_date} #{self.current_state["batch_number"]}'
)
else:
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)
+44 -15
View File
@@ -31,6 +31,7 @@ FFMPEG_BIN = os.getenv("FFMPEG_BIN", "ffmpeg")
RECORD_ENCODER = os.getenv("BATCH_RECORD_ENCODER", "libx264").strip() or "libx264"
RECORD_PRESET = os.getenv("BATCH_RECORD_PRESET", "ultrafast").strip() or "ultrafast"
RECORD_CRF = os.getenv("BATCH_RECORD_CRF", "28").strip() or "28"
RECORD_THREADS = os.getenv("BATCH_RECORD_THREADS", "2").strip() or "2"
def _ffmpeg_writer_proc(
@@ -42,6 +43,7 @@ def _ffmpeg_writer_proc(
encoder: str,
preset: str,
crf: str,
threads: str = "2",
):
"""CPU encode via ffmpeg stdin — H.264 for browser + speed."""
path = Path(out_path)
@@ -64,6 +66,8 @@ def _ffmpeg_writer_proc(
"-i",
"pipe:0",
"-an",
"-threads",
str(threads),
"-c:v",
encoder,
]
@@ -212,9 +216,10 @@ def _writer_proc(
encoder: str,
preset: str,
crf: str,
threads: str = "2",
):
if use_ffmpeg:
_ffmpeg_writer_proc(q, out_path, fps, width, height, encoder, preset, crf)
_ffmpeg_writer_proc(q, out_path, fps, width, height, encoder, preset, crf, threads)
return
_opencv_writer_proc(q, out_path, fps, width, height)
@@ -223,8 +228,8 @@ def _restamp_fps(src: Path, dst: Path, measured_fps: float) -> bool:
"""Rewrite container timestamps so duration = n_frames / measured_fps."""
if measured_fps <= 0.1:
return False
tmp = dst.with_suffix(f".{os.getpid()}.{threading.get_ident()}.restamp.mp4")
try:
tmp = dst.with_suffix(".restamp.mp4")
cmd = [
FFMPEG_BIN,
"-y",
@@ -253,7 +258,7 @@ def _restamp_fps(src: Path, dst: Path, measured_fps: float) -> bool:
except Exception as exc:
print(f"[BatchVideoRecorder] restamp failed: {exc}")
try:
dst.with_suffix(".restamp.mp4").unlink(missing_ok=True)
tmp.unlink(missing_ok=True)
except Exception:
pass
return False
@@ -301,6 +306,7 @@ class BatchVideoRecorder:
self._written = 0
self._t0 = 0.0
self._measured_fps = 0.0
self._session_seq = 0
self._lock = threading.Lock()
self._use_ffmpeg = _ffmpeg_available() and RECORD_ENCODER.lower() != "opencv"
@@ -327,6 +333,7 @@ class BatchVideoRecorder:
return
with self._lock:
self._stop_discard_locked()
self._session_seq += 1
self._batch_id = batch_id
self._w = max(1, int(width))
self._h = max(1, int(height))
@@ -336,7 +343,9 @@ class BatchVideoRecorder:
self._fps = min(src_fps, self.max_fps)
else:
self._fps = src_fps
self._partial = self.shm_dir / f"batch_{batch_id}.partial.mp4"
self._partial = self.shm_dir / (
f"batch_{batch_id}_{int(time.monotonic() * 1000)}_{self._session_seq}.partial.mp4"
)
if self._partial.exists():
self._partial.unlink(missing_ok=True)
legacy = self.shm_dir / "batch_TMP.mp4"
@@ -354,6 +363,7 @@ class BatchVideoRecorder:
RECORD_ENCODER,
RECORD_PRESET,
RECORD_CRF,
RECORD_THREADS,
),
daemon=True,
)
@@ -397,22 +407,39 @@ class BatchVideoRecorder:
except queue.Full:
pass
def finalize(self) -> Optional[Path]:
"""Close writer, restamp FPS to match wall time, return final path."""
def detach(self) -> Optional[tuple]:
"""Synchronously claim active writer state under lock so a new batch can start safely."""
with self._lock:
if not self._active and self._proc is None:
return None
batch_id = self._batch_id
q, proc = self._q, self._proc
partial = self._partial
written = self._written
dropped = self._dropped
t0 = self._t0
state = (
self._batch_id,
self._q,
self._proc,
self._partial,
self._written,
self._dropped,
self._t0,
)
self._active = False
self._q = None
self._proc = None
self._batch_id = None
self._partial = None
return state
def finalize(
self,
final_batch_id: Optional[str] = None,
detached: Optional[tuple] = None,
) -> Optional[Path]:
"""Close writer, restamp FPS to match wall time, return final path."""
if detached is None:
detached = self.detach()
if detached is None:
return None
batch_id, q, proc, partial, written, dropped, t0 = detached
target_batch_id = (final_batch_id or batch_id or "").strip()
if q is not None:
try:
q.put(SENTINEL, timeout=2)
@@ -424,7 +451,9 @@ class BatchVideoRecorder:
if proc.is_alive():
proc.terminate()
proc.join(timeout=2)
if not batch_id or partial is None:
if not target_batch_id or partial is None:
if partial is not None:
partial.unlink(missing_ok=True)
return None
if not partial.is_file() or partial.stat().st_size < 1000:
partial.unlink(missing_ok=True)
@@ -436,13 +465,13 @@ class BatchVideoRecorder:
total_attempted = written + dropped
drop_pct = (100.0 * dropped / total_attempted) if total_attempted else 0.0
print(
f"[BatchVideoRecorder] finalize {batch_id}: "
f"[BatchVideoRecorder] finalize {target_batch_id}: "
f"written={written} dropped={dropped} ({drop_pct:.1f}%) "
f"wall={wall:.1f}s measured_fps={measured:.2f}",
flush=True,
)
out = self.shm_dir / f"batch_{batch_id}.mp4"
out = self.shm_dir / f"batch_{target_batch_id}.mp4"
if measured >= 1.0 and _restamp_fps(partial, out, measured):
partial.unlink(missing_ok=True)
else:
+51 -55
View File
@@ -1,12 +1,12 @@
# =============================================================================
# ZenAI APC Ngoro — Edge RK3588 counter + dashboard
# Shared config for: counter_live_rknn_bytetrack.py + counter_dashboard.py
# ZenAI APC Ngoro — Single-Machine Intel OpenVINO Counter + Recount + Dashboard
# Shared config for: counter_live_rknn_bytetrack.py, recount_engine/app.py, counter_dashboard.py
# Copy to .env on device: cp config.env.example .env && nano .env
# =============================================================================
# --- Core paths ---
OUTPUT_DIR=/opt/apc-ngoro
DB_PATH=/opt/apc-ngoro/apc_ngoro.db
OUTPUT_DIR=/home/admin123/ngoro_project
DB_PATH=/home/admin123/ngoro_project/apc_ngoro.db
STATE_FILE=/tmp/apc_ngoro_current_batch.json
SHM_DIR=/dev/shm/apc-ngoro
@@ -16,42 +16,49 @@ 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 on NanoPi (edit after copying model file)
MODEL_PATH=/opt/models/yolo9t.rknn
# --- OpenVINO model & hardware resource isolation ---
MODEL_PATH=/home/admin123/ngoro_project/models/best_openvino_model
IMGSZ=320
HALF=false
CORE_MASK=7
DEVICE=0
# Real-time pipeline pinned to P-cores (0-7) + Intel Arc GPU (fallback CPU)
LIVE_OPENVINO_DEVICE=GPU
LIVE_CPU_CORES=0-7
LIVE_INFERENCE_THREADS=4
# Recount pipeline pinned to E-cores (8-15) + Intel NPU (fallback CPU)
RECOUNT_OPENVINO_DEVICE=NPU
RECOUNT_CPU_CORES=8-15
RECOUNT_INFERENCE_THREADS=4
RECOUNT_FFMPEG_THREADS=4
# Dashboard pinned to LP E-cores
DASHBOARD_CPU_CORES=14-17
# --- YOLO decoder ---
NUM_CLASSES=2
SCORE_SIGMOID=false
# --- Detection ---
CONF=0.15 # was 0.3 / 0.20 / 0.18 / 0.22 / 0.15
IOU=0.45 # was 0.65 / 0.40
CONF=0.4
IOU=0.45
# --- ByteTrack tracking (ayam = index 0) ---
# was TRACK_HIGH_THRESH_0=0.25 / 0.5 / 0.35 / 0.28 / 0.38 / 0.22
TRACK_HIGH_THRESH_0=0.18
TRACK_LOW_THRESH_0=0.05 # was 0.10 / 0.08
# was 0.8 / 0.70 / 0.45 / 0.30 / 0.38 / 0.25 / 0.50
TRACK_LOW_THRESH_0=0.05
TRACK_MATCH_THRESH_0=0.20
TRACK_BUFFER_0=30 # was 30 / 20 / 40 / 30 / 60
# was 3
TRACK_BUFFER_0=30
TRACK_MIN_HITS_0=1
# --- ByteTrack tracking (talenan = index 1) ---
TRACK_HIGH_THRESH_1=0.4 # was 0.5
TRACK_HIGH_THRESH_1=0.4
TRACK_LOW_THRESH_1=0.1
TRACK_MATCH_THRESH_1=0.6
TRACK_BUFFER_1=30
TRACK_MIN_HITS_1=3
# --- Display / site identity ---
SITE_NAME=SITE NGORO
#CAMERA_NAME=
SITE_NAME=NGORO
OBJECT_LABEL=ayam-potong
CLASS_AYAM=ayam
CLASS_TALENAN=talenan
@@ -59,34 +66,29 @@ CLASS_TALENAN=talenan
# --- Line crossing ---
CROSS_DIRECTION=rtl
LINE_X=
LINE_X_FRAC=0.475
LINE_ZONE_WIDTH=80
LINE_ZONE_Y_START_FRAC=0.5
LINE_X_FRAC=0.19
LINE_ZONE_WIDTH=0
LINE_ZONE_Y_START_FRAC=0
LINE_ZONE_Y_END_FRAC=1.0
# Opacity for line zone overlay when LINE_ZONE_WIDTH > 0 (was 0.12)
# was LINE_ZONE_ALPHA=0.12
LINE_ZONE_ALPHA=0.30
# --- Batch management ---
DAILY_CUTOFF_TIME=20:00
CUTOFF_TIME=20:00
RESET_COUNTERS_AT_CUTOFF=true
BATCH_TIMEOUT_SECONDS=300
BATCH_TIMEOUT_SECONDS=25
IGNORE_BATCH_LABEL_TIMEOUT_SECONDS=30
MIN_OBJECT_PER_BATCH=60
MIN_DURATION_PER_BATCH=60
MIN_OBJECT_PER_BATCH=10
MIN_DURATION_PER_BATCH=10
MAIN_BATCH_MIN_COUNT=700
# --- CSV export ---
EXPORT_CSV=true
CROSS_CSV=/opt/apc-ngoro/batch_crossings.csv
CROSS_CSV=/home/admin123/ngoro_project/batch_crossings.csv
# --- Rate / performance ---
# --- Asynchronous Stream Capture ---
# Decouple RTSP socket reading from NPU inference (prevents packet jitter drops)
# Fallback: set ASYNC_CAPTURE_ENABLED=false to revert to synchronous cap.read()
# was ASYNC_CAPTURE_ENABLED=false
ASYNC_CAPTURE_ENABLED=true
ASYNC_CAPTURE_QUEUE_SIZE=3
ASYNC_CAPTURE_QUEUE_SIZE=10
MOTION_DETECTION_ENABLED=false
MOTION_THRESHOLD=5.0
@@ -103,7 +105,7 @@ VIDEO_SEGMENT_SEC=3600
OUTPUT_FPS=15
# --- Live stream snapshot (required for dashboard feed) ---
LIVE_STREAM_ENABLED=false
LIVE_STREAM_ENABLED=true
LIVE_STREAM_FRAME_PATH=/dev/shm/apc-ngoro/live_frame.jpg
LIVE_STREAM_QUALITY=75
LIVE_STREAM_EVERY_N=2
@@ -118,45 +120,39 @@ CURRENT_BATCH_PATH=/tmp/apc_ngoro_current_batch.json
BATCH_RUNNING_THRESHOLD_SEC=30
# --- Dashboard display (HUD overlay on stream panel) ---
STREAM_FPS_DISPLAY=30.0
STREAM_FPS_DISPLAY=20
STREAM_RESOLUTION_DISPLAY=640x480
STREAM_ACCURACY_PCT=98
STREAM_ACCURACY_PCT=99.8
# --- Recounting / MotionEye / NanoPi 2 ---
NANOPI2_URL=http://192.168.192.16:8765
MOTIONEYE_URL=http://192.168.192.251:8081
MOTIONEYE_INGEST_URL=http://192.168.192.251:8090
MOTIONEYE_INGEST_TOKEN=change-me-ingest-token
MOTIONEYE_MEDIA_DIR=/data/media/Camera1
# Deprecated alias for old MotionEye calendar cleanup. Keep for compatibility.
RETENTION_DAYS=3
# Keep only the last N active counting dates that exist in DB batches.
ACTIVE_RETENTION_DAYS=3
MOTIONEYE_CAMERA_ID=1
MOTIONEYE_USER=support
MOTIONEYE_PASSWORD=
MOTIONEYE_SSH_USER=support
# --- Local NVMe Batch Video Storage & Retention ---
BATCH_VIDEO_DIR=/home/admin123/ngoro_project/batch_videos
BATCH_RECORD_ENABLED=true
# 0 = record every stream frame (no throttle). >0 caps record FPS.
BATCH_RECORD_FPS=0
BATCH_RECORD_QUEUE=480
# CPU encode in separate process (libx264 ultrafast) — does not block NPU detect
BATCH_RECORD_ENCODER=libx264
BATCH_RECORD_PRESET=ultrafast
BATCH_RECORD_CRF=28
BATCH_RECORD_THREADS=2
# Keep only the last N active counting dates that exist in DB batches.
ACTIVE_RETENTION_DAYS=7
# --- Local Recount Engine (127.0.0.1:8765) ---
RECOUNT_STUB=false
# Optional: force delta for badge testing when RECOUNT_STUB=true (e.g. 5 or -3)
RECOUNT_STUB_DELTA=
RECOUNT_HOST=0.0.0.0
RECOUNT_PORT=8765
RECOUNT_PUBLIC_BASE=http://192.168.192.16:8765
RECOUNT_OUTPUT_DIR=/opt/apc-ngoro/recount_output
# Delete batch_*_recount.mp4 and cached _src_*.mp4 after this many hours on NP2.
RECOUNT_ENGINE_URL=http://127.0.0.1:8765
RECOUNT_PUBLIC_BASE=http://127.0.0.1:8765
RECOUNT_OUTPUT_DIR=/home/admin123/ngoro_project/recount_output
RECOUNT_LIVE_FRAME_PATH=/dev/shm/apc-ngoro/recount_live_frame.jpg
# Delete batch_*_recount.mp4 after this many hours.
RECOUNT_OVERLAY_TTL_HOURS=6
# Process every frame (1 = same as real-time; do not raise for speed)
RECOUNT_FRAME_STRIDE=1
# 0 = ASAP process; final overlay video is H.264 for browser replay
RECOUNT_PLAYBACK_SPEED=0
# was 3
RECOUNT_MIN_HITS=1
RECOUNT_TRACK_BUFFER=30
# Initial recount count (1 compensates for truncated initialization seconds)
+491 -405
View File
File diff suppressed because it is too large. Load diff
+207 -87
View File
@@ -1,6 +1,6 @@
"""
Edge production live counter — RTSP + YOLO RKNN + ByteTrack + line crossing.
Runs on RK3588 hardware with RKNN model (320×320 input).
Edge production live counter — RTSP + YOLO OpenVINO + ByteTrack + line crossing.
Runs on Intel x86_64 hardware with OpenVINO model (320×320 input).
Uses ByteTrack (Kalman filter + two-stage IoU association) for tracking.
"""
@@ -8,6 +8,7 @@ import numpy as np
import cv2
import csv
import os
import shutil
import signal
import time
from collections import deque
@@ -18,19 +19,19 @@ from dotenv import load_dotenv
load_dotenv()
from rknnlite.api import RKNNLite
import openvino as ov
from batch_store import BatchStore
from batch_video_recorder import BatchVideoRecorder
from motioneye_client import upload_batch_video, resolve_video_url, batch_video_filename
import threading
import queue
# --- config (override via env / .env) ---
OUTPUT_DIR = os.getenv("OUTPUT_DIR", "/opt/apc-ngoro")
OUTPUT_DIR = os.getenv("OUTPUT_DIR", "/home/admin123/ngoro_project")
DB_PATH = os.getenv("DB_PATH", f"{OUTPUT_DIR}/apc_ngoro.db")
STATE_FILE = os.getenv("STATE_FILE", "/tmp/apc_ngoro_current_batch.json")
BATCH_VIDEO_DIR = Path(os.getenv("BATCH_VIDEO_DIR", f"{OUTPUT_DIR}/batch_videos"))
SOURCE = os.getenv("SOURCE", "rtsp://user:pass@192.168.0.100:554/stream1")
MODEL_PATH = os.getenv("MODEL_PATH", "/opt/models/yolo9t.rknn")
MODEL_PATH = os.getenv("MODEL_PATH", f"{OUTPUT_DIR}/models/best_openvino_model")
CAMERA_NAME = os.getenv("CAMERA_NAME", "CC1")
OBJECT_LABEL = os.getenv("OBJECT_LABEL", "ayam-potong")
CLASS_AYAM = os.getenv("CLASS_AYAM", "ayam")
@@ -48,10 +49,9 @@ IMGSZ = int(os.getenv("IMGSZ", "320"))
HALF = os.getenv("HALF", "false").lower() == "true"
CONF = float(os.getenv("CONF", "0.15"))
IOU = float(os.getenv("IOU", "0.45"))
DEVICE = int(os.getenv("DEVICE", "0"))
# RKNN NPU core mask
CORE_MASK = int(os.getenv("CORE_MASK", "1"))
LIVE_OPENVINO_DEVICE = os.getenv("LIVE_OPENVINO_DEVICE", "GPU").strip() or "GPU"
LIVE_CPU_CORES = os.getenv("LIVE_CPU_CORES", "0-7").strip()
LIVE_INFERENCE_THREADS = int(os.getenv("LIVE_INFERENCE_THREADS", "4"))
# YOLO decoder config
NUM_CLASSES = int(os.getenv("NUM_CLASSES", "2"))
@@ -141,10 +141,6 @@ def request_shutdown(signum, frame):
print("\nShutdown requested — finishing current frame...")
signal.signal(signal.SIGINT, request_shutdown)
signal.signal(signal.SIGTERM, request_shutdown)
# =============================================================================
# YOLO output decoder (NMS only — boxes are pre-decoded by the model)
# =============================================================================
@@ -486,14 +482,63 @@ class ByteTracker:
# =============================================================================
# RKNN YOLO wrapper (detect output format: (1, 4+num_classes, N))
# Resource isolation helpers (CPU affinity & OpenCV threads)
# =============================================================================
class RKNNYOLO:
def parse_cpu_cores(spec: str) -> set[int]:
"""Parse CPU list specs like '0-7' or '0,2,4-7' into a set of core IDs."""
cores: set[int] = set()
if not spec:
return cores
for part in spec.split(","):
item = part.strip()
if not item:
continue
if "-" in item:
start_s, end_s = item.split("-", 1)
start_i, end_i = int(start_s.strip()), int(end_s.strip())
lo, hi = min(start_i, end_i), max(start_i, end_i)
cores.update(range(lo, hi + 1))
else:
cores.add(int(item))
return cores
def apply_cpu_affinity(spec: str, label: str = "process", opencv_threads: int = 2) -> set[int]:
"""Pin current process to specified CPU cores and cap OpenCV thread pool."""
try:
cv2.setNumThreads(max(1, int(opencv_threads)))
except Exception:
pass
requested = parse_cpu_cores(spec)
if not requested:
return set()
try:
allowed = os.sched_getaffinity(0)
target = requested & allowed if allowed else requested
if not target:
target = requested
os.sched_setaffinity(0, target)
actual = os.sched_getaffinity(0)
print(f"[resource] {label} pinned to CPUs {sorted(actual)} (opencv_threads={opencv_threads})", flush=True)
return actual
except Exception as exc:
print(f"[resource] {label} CPU affinity warning ({spec}): {exc}", flush=True)
return set()
# =============================================================================
# OpenVINO YOLO wrapper (detect output format: (1, 4+num_classes, N))
# =============================================================================
class OpenVINOYOLO:
def __init__(
self,
model_path,
device="GPU",
num_threads=4,
core_mask=1,
imgsz=320,
conf=0.3,
@@ -502,6 +547,7 @@ class RKNNYOLO:
num_keypoints=0,
score_sigmoid=False,
):
del core_mask # Legacy RKNN parameter kept for signature compatibility
self.imgsz = imgsz
self.conf = conf
self.iou = iou
@@ -509,21 +555,77 @@ class RKNNYOLO:
self.num_keypoints = num_keypoints
self.score_sigmoid = score_sigmoid
self.rknn = RKNNLite(verbose=False)
ret = self.rknn.load_rknn(model_path)
if ret != 0:
raise RuntimeError(f"Failed to load RKNN model: {model_path}")
ret = self.rknn.init_runtime(core_mask=core_mask)
if ret != 0:
raise RuntimeError(f"Failed to init RKNN runtime (core_mask={core_mask})")
resolved = self._resolve_model_path(model_path)
self.model_path = str(resolved)
self.core = ov.Core()
model = self.core.read_model(self.model_path)
requested_device = (device or "CPU").strip().upper()
available = [d.upper() for d in self.core.available_devices]
target_device = self._pick_device(requested_device, available)
self.device, self.compiled_model = self._compile_with_fallback(
model, target_device, requested_device, num_threads
)
self.infer_request = self.compiled_model.create_infer_request()
print(
f"OpenVINO model loaded: {self.model_path} imgsz={imgsz} "
f"device={self.device} (requested={requested_device}, available={self.core.available_devices})",
flush=True,
)
@staticmethod
def _resolve_model_path(model_path) -> Path:
p = Path(model_path)
if p.is_dir():
xml = p / "best.xml"
if not xml.is_file():
xmls = sorted(p.glob("*.xml"))
if not xmls:
raise FileNotFoundError(f"No OpenVINO .xml model found in {p}")
xml = xmls[0]
return xml
if not p.is_file():
raise FileNotFoundError(f"OpenVINO model not found: {p}")
return p
@staticmethod
def _pick_device(requested: str, available_upper: list[str]) -> str:
if requested in ("AUTO", "CPU"):
return requested
for dev in available_upper:
if dev == requested or dev.startswith(f"{requested}."):
return requested
print(
f"[OpenVINOYOLO] Requested device '{requested}' not in available devices "
f"{available_upper}; falling back to CPU",
flush=True,
)
return "CPU"
def _compile_with_fallback(self, model, target_device: str, requested: str, num_threads: int):
def _cfg(dev: str) -> dict:
if dev == "CPU":
return {
"INFERENCE_NUM_THREADS": max(1, int(num_threads)),
"PERFORMANCE_HINT": "LATENCY",
}
return {"PERFORMANCE_HINT": "LATENCY"}
try:
sdk_ver = self.rknn.get_sdk_version()
print(f"RKNN SDK version: {sdk_ver}")
except Exception:
pass
print(f"RKNN model loaded: {model_path} imgsz={imgsz} core_mask={core_mask}")
compiled = self.core.compile_model(model, target_device, _cfg(target_device))
return target_device, compiled
except Exception as exc:
if target_device == "CPU":
raise
print(
f"[OpenVINOYOLO] Failed to compile on '{target_device}' (requested='{requested}'): "
f"{exc}; falling back to CPU",
flush=True,
)
compiled = self.core.compile_model(model, "CPU", _cfg("CPU"))
return "CPU", compiled
def _preprocess(self, frame):
h0, w0 = frame.shape[:2]
@@ -545,15 +647,15 @@ class RKNNYOLO:
rgb, gains = self._preprocess(frame)
scale, _, pad_y, pad_x = gains
inp = np.expand_dims(rgb, axis=0)
inp = np.ascontiguousarray(inp.astype(np.uint8))
inp = rgb.astype(np.float32) * (1.0 / 255.0)
inp = np.transpose(inp, (2, 0, 1))[None, ...]
inp = np.ascontiguousarray(inp)
outputs = self.rknn.inference(inputs=[inp])
if len(outputs) == 0:
res = self.infer_request.infer({0: inp})
if not res:
return []
out = outputs[0]
out = next(iter(res.values()))
out = np.squeeze(out, axis=0)
if out.shape[0] == self.num_classes + 4:
@@ -617,7 +719,12 @@ class RKNNYOLO:
return detections
def release(self):
self.rknn.release()
self.infer_request = None
self.compiled_model = None
self.core = None
RKNNYOLO = OpenVINOYOLO
# =============================================================================
@@ -1134,26 +1241,26 @@ def connect_stream(source, warmup=WARMUP_FRAMES):
return None, 0, 0, OUTPUT_FPS
def _upload_batch_video_async(store, local_path, batch_meta, logger):
"""Background: upload finalized SHM mp4 to MotionEye ingest, then delete local."""
def _job():
batch_id = batch_meta["batch_id"]
try:
result = upload_batch_video(local_path, batch_id)
video_url = result.get("video_url") or resolve_video_url(batch_id)
store.set_batch_video(
batch_meta["counting_date"],
batch_meta["batch_number"],
video_filename=batch_video_filename(batch_id),
video_url=video_url,
)
logger(f"Uploaded batch video {batch_id} → {video_url}")
Path(local_path).unlink(missing_ok=True)
except Exception as exc:
logger(f"Batch video upload failed for {batch_id}: {exc}")
threading.Thread(target=_job, daemon=True).start()
def _save_batch_video_local(store, local_path, batch_meta, logger):
"""Move finalized SHM mp4 into local NVMe BATCH_VIDEO_DIR and update SQLite."""
batch_id = batch_meta["batch_id"]
filename = f"batch_{batch_id}.mp4"
try:
BATCH_VIDEO_DIR.mkdir(parents=True, exist_ok=True)
dest = BATCH_VIDEO_DIR / filename
tmp = BATCH_VIDEO_DIR / f".{filename}.part"
shutil.move(str(local_path), str(tmp))
tmp.replace(dest)
video_url = f"/api/v1/recount/source/{batch_id}"
store.set_batch_video(
batch_meta["counting_date"],
batch_meta["batch_number"],
video_filename=filename,
video_url=video_url,
)
logger(f"Saved batch video {batch_id} → {dest}")
except Exception as exc:
logger(f"Batch video save failed for {batch_id}: {exc}")
# =============================================================================
@@ -1164,6 +1271,11 @@ def _upload_batch_video_async(store, local_path, batch_meta, logger):
def run():
global shutdown_requested
signal.signal(signal.SIGINT, request_shutdown)
signal.signal(signal.SIGTERM, request_shutdown)
apply_cpu_affinity(LIVE_CPU_CORES, label="live-counter")
BATCH_VIDEO_DIR.mkdir(parents=True, exist_ok=True)
store = BatchStore(
db_path=DB_PATH,
state_file=STATE_FILE,
@@ -1191,33 +1303,33 @@ def run():
if not BATCH_RECORD_ENABLED:
return
if not meta.get("ok"):
batch_recorder.stop_discard()
log_msg(
f"Batch video discarded for {meta.get('batch_id')} "
f"(closed_by={meta.get('closed_by')})"
)
return
detached = batch_recorder.detach()
def _job():
try:
if meta.get("ok"):
t0 = time.monotonic()
out_path = batch_recorder.finalize()
dt = time.monotonic() - t0
status_lbl = " [PARTIAL]" if meta.get("is_partial") else ""
log_msg(
f"Batch video finalize {meta.get('batch_id')}{status_lbl} "
f"in {dt:.2f}s stats={batch_recorder.stats}"
)
if out_path:
_upload_batch_video_async(store, out_path, meta, log_msg)
else:
batch_recorder.stop_discard()
else:
batch_recorder.stop_discard()
log_msg(
f"Batch video discarded for {meta.get('batch_id')} "
f"(closed_by={meta.get('closed_by')})"
)
t0 = time.monotonic()
out_path = batch_recorder.finalize(
final_batch_id=meta.get("batch_id"),
detached=detached,
)
dt = time.monotonic() - t0
status_lbl = " [PARTIAL]" if meta.get("is_partial") else ""
log_msg(
f"Batch video finalize {meta.get('batch_id')}{status_lbl} "
f"in {dt:.2f}s stats={batch_recorder.stats}"
)
if out_path:
_save_batch_video_local(store, out_path, meta, log_msg)
except Exception as exc:
log_msg(f"Batch video finalize error: {exc}")
try:
batch_recorder.stop_discard()
except Exception:
pass
threading.Thread(target=_job, daemon=True, name="batch-finalize").start()
@@ -1229,9 +1341,10 @@ def run():
CROSS_CSV, ["batch", "frame", "timestamp", "chicken_id"]
)
model = RKNNYOLO(
model = OpenVINOYOLO(
model_path=MODEL_PATH,
core_mask=CORE_MASK,
device=LIVE_OPENVINO_DEVICE,
num_threads=LIVE_INFERENCE_THREADS,
imgsz=IMGSZ,
conf=CONF,
iou=IOU,
@@ -1280,9 +1393,13 @@ def run():
line_x = resolve_line_x(w)
print(
f"RKNN+ByteTrack counter | {w}x{h} @ {fps}fps | line x={line_x} | cross={CROSS_DIRECTION}"
f"OpenVINO+ByteTrack counter | {w}x{h} @ {fps}fps | line x={line_x} | cross={CROSS_DIRECTION}"
)
print(f"Model: {MODEL_PATH} | imgsz={IMGSZ} | core_mask={CORE_MASK} | conf={CONF} | iou={IOU}")
print(
f"Model: {MODEL_PATH} | imgsz={IMGSZ} | device={model.device} | "
f"cores={LIVE_CPU_CORES} | conf={CONF} | iou={IOU}"
)
print(f"Batch videos dir: {BATCH_VIDEO_DIR}")
print(
f"ByteTrack Index 0: high_thresh={TRACK_HIGH_THRESH_0} low_thresh={TRACK_LOW_THRESH_0} "
f"match_thresh={TRACK_MATCH_THRESH_0} buffer={TRACK_BUFFER_0} min_hits={TRACK_MIN_HITS_0}"
@@ -1626,12 +1743,15 @@ def run():
if LIVE_STREAM_ENABLED and frame_idx % LIVE_STREAM_EVERY_N == 0:
try:
Path(LIVE_STREAM_FRAME_PATH).parent.mkdir(parents=True, exist_ok=True)
_, jpeg = cv2.imencode(
live_path = Path(LIVE_STREAM_FRAME_PATH)
live_path.parent.mkdir(parents=True, exist_ok=True)
ok, jpeg = cv2.imencode(
".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, LIVE_STREAM_QUALITY]
)
with open(LIVE_STREAM_FRAME_PATH, "wb") as f:
f.write(jpeg.tobytes())
if ok:
tmp_path = live_path.with_suffix(".jpg.tmp")
tmp_path.write_bytes(jpeg.tobytes())
tmp_path.replace(live_path)
except Exception:
pass
+335
View File
@@ -0,0 +1,335 @@
"""Shared helpers for adjustable daily cut-off times and batch reconciliation."""
from __future__ import annotations
import re
import sqlite3
from datetime import date, datetime, time as dt_time, timedelta
from pathlib import Path
DEFAULT_CUTOFF_TIME = "20:00"
CUTOFF_RE = re.compile(r"^([01]?\d|2[0-3]):([0-5]\d)$")
LEGACY_BATCH1_CUTOFF_DATE = "2026-11-18"
def validate_cutoff_time(cutoff_str: str) -> str:
"""Validate and normalize an HH:MM cut-off time string."""
raw = (cutoff_str or "").strip().replace(".", ":")
m = CUTOFF_RE.match(raw)
if not m:
raise ValueError(f"Format waktu cut-off tidak valid: '{cutoff_str}' (gunakan HH:MM)")
hour, minute = int(m.group(1)), int(m.group(2))
return f"{hour:02d}:{minute:02d}"
def ensure_cutoff_tables(conn: sqlite3.Connection, default_cutoff: str = DEFAULT_CUTOFF_TIME) -> None:
"""Create site_settings and cutoff_overrides tables idempotently."""
try:
norm_default = validate_cutoff_time(default_cutoff)
except ValueError:
norm_default = DEFAULT_CUTOFF_TIME
cur = conn.cursor()
cur.execute(
"""
CREATE TABLE IF NOT EXISTS site_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS cutoff_overrides (
counting_date TEXT PRIMARY KEY,
cutoff_time TEXT NOT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
)
cur.execute(
"INSERT OR IGNORE INTO site_settings (key, value) VALUES ('default_cutoff_time', ?)",
(norm_default,),
)
conn.commit()
def load_cutoff_config(
conn: sqlite3.Connection, fallback_default: str = DEFAULT_CUTOFF_TIME
) -> tuple[str, dict[str, str]]:
"""Return (default_cutoff_time, {counting_date: override_cutoff_time})."""
try:
norm_fallback = validate_cutoff_time(fallback_default)
except ValueError:
norm_fallback = DEFAULT_CUTOFF_TIME
cur = conn.cursor()
try:
cur.execute("SELECT value FROM site_settings WHERE key = 'default_cutoff_time'")
row = cur.fetchone()
except sqlite3.OperationalError:
ensure_cutoff_tables(conn, norm_fallback)
cur.execute("SELECT value FROM site_settings WHERE key = 'default_cutoff_time'")
row = cur.fetchone()
default_cutoff = norm_fallback
if row and row[0]:
try:
default_cutoff = validate_cutoff_time(str(row[0]))
except ValueError:
default_cutoff = norm_fallback
overrides: dict[str, str] = {}
cur.execute("SELECT counting_date, cutoff_time FROM cutoff_overrides")
for c_date, c_time in cur.fetchall():
if not c_date or not c_time:
continue
try:
overrides[str(c_date)] = validate_cutoff_time(str(c_time))
except ValueError:
continue
return default_cutoff, overrides
def deadline_for_counting_date(
counting_date_str: str,
default_cutoff: str = DEFAULT_CUTOFF_TIME,
overrides: dict[str, str] | None = None,
) -> datetime:
"""
Compute the exact datetime when operational counting date D closes.
Evening cut-off (>= 06:00) closes on calendar day D; post-midnight (< 06:00) closes on D + 1.
"""
cutoff_str = (overrides or {}).get(counting_date_str) or default_cutoff
norm = validate_cutoff_time(cutoff_str)
t: dt_time = datetime.strptime(norm, "%H:%M").time()
d = date.fromisoformat(counting_date_str)
if t.hour >= 6:
return datetime.combine(d, t)
return datetime.combine(d + timedelta(days=1), t)
def compute_counting_date(
dt: datetime | None = None,
default_cutoff: str = DEFAULT_CUTOFF_TIME,
overrides: dict[str, str] | None = None,
) -> str:
"""Determine which operational counting_date (YYYY-MM-DD) a timestamp belongs to."""
if dt is None:
dt = datetime.now()
# Strip tzinfo if aware so comparisons with naive deadline datetimes never fail
if dt.tzinfo is not None:
dt = dt.replace(tzinfo=None)
d_base = dt.date()
for delta in (-1, 0, 1, 2):
cand = d_base + timedelta(days=delta)
cand_str = cand.isoformat()
prev_str = (cand - timedelta(days=1)).isoformat()
prev_dl = deadline_for_counting_date(prev_str, default_cutoff, overrides)
curr_dl = deadline_for_counting_date(cand_str, default_cutoff, overrides)
if prev_dl <= dt < curr_dl:
return cand_str
norm = validate_cutoff_time(default_cutoff)
t = datetime.strptime(norm, "%H:%M").time()
if dt.time() < t:
return dt.date().isoformat()
return (dt.date() + timedelta(days=1)).isoformat()
def get_effective_cutoff(
conn: sqlite3.Connection,
counting_date_str: str,
fallback_default: str = DEFAULT_CUTOFF_TIME,
) -> tuple[str, bool, str]:
"""Return (effective_cutoff, is_override, default_cutoff) for a counting date."""
default_cutoff, overrides = load_cutoff_config(conn, fallback_default)
if counting_date_str in overrides:
return overrides[counting_date_str], True, default_cutoff
return default_cutoff, False, default_cutoff
def update_env_cutoff(env_path: str | Path, cutoff_time: str) -> bool:
"""Persist new default CUTOFF_TIME and DAILY_CUTOFF_TIME to .env if the file exists."""
norm = validate_cutoff_time(cutoff_time)
p = Path(env_path)
if not p.is_file():
return False
lines = p.read_text(encoding="utf-8").splitlines(keepends=True)
saw_cutoff = False
saw_daily = False
out: list[str] = []
for line in lines:
if line.startswith("CUTOFF_TIME="):
ending = "\n" if line.endswith("\n") else ""
out.append(f"CUTOFF_TIME={norm}{ending}")
saw_cutoff = True
elif line.startswith("DAILY_CUTOFF_TIME="):
ending = "\n" if line.endswith("\n") else ""
out.append(f"DAILY_CUTOFF_TIME={norm}{ending}")
saw_daily = True
else:
out.append(line)
if not saw_daily:
if out and not out[-1].endswith("\n"):
out.append("\n")
out.append(f"DAILY_CUTOFF_TIME={norm}\n")
if not saw_cutoff:
if out and not out[-1].endswith("\n"):
out.append("\n")
out.append(f"CUTOFF_TIME={norm}\n")
p.write_text("".join(out), encoding="utf-8")
return True
def _assign_numbers_for_group(
rows: list[tuple[int, int, str, str]],
counting_date: str,
main_batch_min_count: int,
) -> tuple[list[tuple[int, str]], int, int]:
"""
Assign sequential main/sub batch numbers for rows in one (counting_date, camera, label) group.
rows items: (id, count, start_time, old_batch_number) sorted chronologically.
Returns ([(id, new_batch_number), ...], main_count, total_count).
"""
planned: list[tuple[int, str]] = []
main_counter = 0
total_count = 0
sub_idx = 0
is_legacy = counting_date <= LEGACY_BATCH1_CUTOFF_DATE
for idx, (row_id, count, _st, _old_bn) in enumerate(rows):
cnt = int(count or 0)
total_count += cnt
if idx == 0 and is_legacy:
is_child = False
else:
is_child = cnt < int(main_batch_min_count)
if not is_child:
main_counter += 1
if main_counter > 1:
sub_idx = 0
planned.append((row_id, str(main_counter)))
else:
target_main = main_counter if main_counter >= 1 else 1
letter = chr(ord("a") + sub_idx) if sub_idx < 26 else f"a{sub_idx}"
sub_idx += 1
planned.append((row_id, f"{target_main}{letter}"))
return planned, main_counter, total_count
def reconcile_batches_for_cutoff_change(
conn: sqlite3.Connection,
target_date: str,
main_batch_min_count: int = 700,
fallback_default: str = DEFAULT_CUTOFF_TIME,
) -> dict:
"""
Re-evaluate counting_date for batches in (target_date, target_date + 1 day),
renumber batches cleanly without breaking SQLite UNIQUE constraints, preserve all video/recount columns,
and update daily_summaries for both dates.
"""
default_cutoff, overrides = load_cutoff_config(conn, fallback_default)
d0 = date.fromisoformat(target_date)
next_date = (d0 + timedelta(days=1)).isoformat()
prev_date = (d0 - timedelta(days=1)).isoformat()
prev_dl = deadline_for_counting_date(prev_date, default_cutoff, overrides)
cur = conn.cursor()
cur.execute(
"""
SELECT id, counting_date, batch_number, camera_name, object_label, count, start_time
FROM batches
WHERE counting_date IN (?, ?)
ORDER BY start_time ASC, id ASC
""",
(target_date, next_date),
)
rows = cur.fetchall()
grouped: dict[tuple[str, str, str], list[tuple[int, int, str, str]]] = {}
moved_count = 0
for r in rows:
row_id, old_date, old_bn, cam, lbl, count, start_time = r
try:
st_dt = datetime.fromisoformat(str(start_time))
if st_dt.tzinfo is not None:
st_dt = st_dt.replace(tzinfo=None)
except Exception:
st_dt = None
if st_dt is None:
new_date = old_date
elif st_dt < prev_dl:
# Never pull batches into prev_date outside the two-day window
new_date = old_date
else:
computed = compute_counting_date(st_dt, default_cutoff, overrides)
if computed < target_date:
new_date = target_date
elif computed > next_date:
new_date = next_date
else:
new_date = computed
if new_date != old_date:
moved_count += 1
key = (new_date, str(cam), str(lbl))
grouped.setdefault(key, []).append((int(row_id), int(count or 0), str(start_time), str(old_bn)))
# Phase 1: Temporary placeholders to prevent UNIQUE constraint collisions
for r in rows:
row_id = r[0]
cur.execute("UPDATE batches SET batch_number = ? WHERE id = ?", (f"__tmp_{row_id}", row_id))
# Phase 2: Assign final counting_date and renumbered batch_number
summary_stats: dict[str, dict[str, int]] = {
target_date: {"batches": 0, "total": 0},
next_date: {"batches": 0, "total": 0},
}
summary_rows: dict[tuple[str, str, str], tuple[int, int]] = {}
for (new_date, cam, lbl), grp_rows in grouped.items():
grp_rows.sort(key=lambda item: (item[2], item[0]))
planned, main_count, total_count = _assign_numbers_for_group(
grp_rows, new_date, main_batch_min_count
)
for row_id, new_bn in planned:
cur.execute(
"UPDATE batches SET counting_date = ?, batch_number = ? WHERE id = ?",
(new_date, new_bn, row_id),
)
summary_rows[(new_date, cam, lbl)] = (total_count, main_count)
if new_date in summary_stats:
summary_stats[new_date]["batches"] += main_count
summary_stats[new_date]["total"] += total_count
# Phase 3: Reconcile daily_summaries for target_date and next_date
cur.execute("DELETE FROM daily_summaries WHERE counting_date IN (?, ?)", (target_date, next_date))
for (s_date, cam, lbl), (tot_cnt, tot_b) in summary_rows.items():
cur.execute(
"""
INSERT INTO daily_summaries
(counting_date, camera_name, object_label, total_count, total_batches)
VALUES (?, ?, ?, ?, ?)
""",
(s_date, cam, lbl, tot_cnt, tot_b),
)
conn.commit()
return {
"moved_count": moved_count,
"affected_dates": [target_date, next_date],
"counts": summary_stats,
}
+26 -16
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env bash
# Install systemd services for ZenAI APC Ngoro
# Install unified single-machine systemd services for ZenAI APC Ngoro
set -euo pipefail
INSTALL_DIR="${INSTALL_DIR:-/opt/apc-ngoro}"
INSTALL_DIR="${INSTALL_DIR:-/home/admin123/ngoro_project}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ ! -f "$INSTALL_DIR/.env" ]; then
@@ -11,18 +11,28 @@ if [ ! -f "$INSTALL_DIR/.env" ]; then
echo " cp $INSTALL_DIR/config.env.example $INSTALL_DIR/.env"
fi
sudo cp "$SCRIPT_DIR/systemd/apc-ngoro-counter.service" /etc/systemd/system/
sudo cp "$SCRIPT_DIR/systemd/apc-ngoro-dashboard.service" /etc/systemd/system/
# Optional on NanoPi 2 only:
# sudo cp "$SCRIPT_DIR/systemd/apc-ngoro-recount.service" /etc/systemd/system/
# Optional on MotionEye host only:
# sudo cp "$SCRIPT_DIR/systemd/apc-motioneye-ingest.service" /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable apc-ngoro-counter apc-ngoro-dashboard
sudo systemctl restart apc-ngoro-counter apc-ngoro-dashboard
mkdir -p "$INSTALL_DIR/batch_videos" "$INSTALL_DIR/recount_output"
echo "Services installed and started."
echo " systemctl status apc-ngoro-counter"
echo " systemctl status apc-ngoro-dashboard"
echo "Dashboard: http://<nanopi-ip>:5000"
echo "Recount peers: see docs/RECOUNTING_CONNECT.md"
# Copy all unit files
sudo cp "$SCRIPT_DIR/systemd/apc-ngoro-service.service" /etc/systemd/system/
sudo cp "$SCRIPT_DIR/systemd/apc-ngoro-counter.service" /etc/systemd/system/
sudo cp "$SCRIPT_DIR/systemd/apc-ngoro-recount.service" /etc/systemd/system/
sudo cp "$SCRIPT_DIR/systemd/apc-ngoro-dashboard.service" /etc/systemd/system/
sudo systemctl daemon-reload
# Enable and start the unified master service
sudo systemctl enable apc-ngoro-service
sudo systemctl restart apc-ngoro-service
echo "================================================================="
echo "ZenAI APC Ngoro unified service installed and started!"
echo ""
echo "Management commands:"
echo " sudo systemctl restart apc-ngoro-service"
echo " sudo systemctl status apc-ngoro-service"
echo " sudo journalctl -u apc-ngoro-service -f"
echo ""
echo "Dashboard running at: http://127.0.0.1:5000"
echo "Recount API at: http://127.0.0.1:8765"
echo "================================================================="
Binary file not shown.
File diff suppressed because it is too large. Load diff
+25
View File
@@ -0,0 +1,25 @@
description: Ultralytics YOLOv9t model trained on /content/dataset_combined/data.yaml
author: Ultralytics
date: '2026-10-27T09:36:44.647382+00:00'
version: 8.4.190
license: AGPL-3.0 License (https://ultralytics.com/license)
docs: https://docs.ultralytics.com
stride: 32
task: detect
head: Detect
batch: 1
imgsz:
- 320
- 320
names:
0: ayam-potong
1: telenan
args:
data: null
batch: 1
fraction: 1.0
quantize: 16
nms: null
dynamic: false
channels: 3
end2end: false
+452
View File
@@ -0,0 +1,452 @@
#!/usr/bin/env python3
"""
python3 convert_to_rknn.py \
--input /opt/apc-ngoro/models/apc-ngoro.pt \
--no-half \
--no-nms \
--int8 \
--dataset calibration.txt \
--target-platform rk3588 \
--no-simplify \
--mean-values 0,0,0 \
--std-values 255,255,255 \
--dynamic-shapes "1,3,320,320"
"""
from __future__ import annotations
import argparse
import shutil
import sys
from pathlib import Path
VALID_TARGET_PLATFORMS = (
"rk3566",
"rk3568",
"rk3588",
"rv1103",
"rv1106",
"rk3562",
"rk3576",
"rv1103b",
"rv1106b",
"rk2118",
"rv1126b",
)
DEFAULT_TARGET_PLATFORM = "rk3588"
DEFAULT_HALF = False
DEFAULT_NMS = False
DEFAULT_MEAN_VALUES = "0,0,0"
DEFAULT_STD_VALUES = "255,255,255"
DEFAULT_QUANTIZED_DTYPE = "asymmetric_quantized-8"
DEFAULT_OPTIMIZATION_LEVEL = 3
def _parse_list(value: str, name: str) -> list[float]:
if value is None:
return []
try:
return [float(v.strip()) for v in value.split(",") if v.strip() != ""]
except ValueError as exc:
raise argparse.ArgumentTypeError(
f"Invalid {name} list: {value!r}. Use comma-separated numbers."
) from exc
def _add_bool_arg(parser: argparse.ArgumentParser, name: str, default: bool) -> None:
group = parser.add_mutually_exclusive_group()
group.add_argument(f"--{name}", dest=name, action="store_true")
group.add_argument(f"--no-{name}", dest=name, action="store_false")
parser.set_defaults(**{name: default})
def export_pt_to_onnx(
pt_path: Path,
onnx_output: Path | None,
imgsz: int,
opset: int,
simplify: bool,
dynamic: bool,
half: bool,
nms: bool,
verbose: bool,
) -> Path:
try:
from ultralytics import YOLO # type: ignore
except Exception as exc:
raise RuntimeError(
"Ultralytics is required to export .pt to ONNX. "
"Install with: pip install ultralytics"
) from exc
model = YOLO(str(pt_path))
export_result = model.export(
format="onnx",
imgsz=imgsz,
opset=opset,
simplify=simplify,
dynamic=dynamic,
half=half,
nms=nms,
verbose=verbose,
)
exported_path = None
if isinstance(export_result, (str, Path)):
exported_path = Path(export_result)
if exported_path is None:
candidate = pt_path.with_suffix(".onnx")
if candidate.exists():
exported_path = candidate
else:
onnx_files = sorted(
pt_path.parent.glob("*.onnx"),
key=lambda p: p.stat().st_mtime,
reverse=True,
)
if onnx_files:
exported_path = onnx_files[0]
if exported_path is None or not exported_path.exists():
raise RuntimeError("ONNX export did not produce a file.")
if onnx_output is not None:
onnx_output = onnx_output.resolve()
if exported_path.resolve() != onnx_output:
onnx_output.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(exported_path, onnx_output)
return onnx_output
return exported_path
def convert_onnx_to_rknn(
onnx_path: Path,
rknn_output: Path,
dataset: Path | None,
quantize: bool,
target_platform: str | None,
mean_values: list[float],
std_values: list[float],
quantized_dtype: str | None,
optimization_level: int,
verbose: bool,
dynamic_shapes: list[list[int]] | None,
) -> None:
try:
import onnx # type: ignore
except ImportError as exc:
raise RuntimeError(
"onnx is required by rknn-toolkit2. Install with: pip install 'onnx>=1.16.0'."
) from exc
if not hasattr(onnx, "mapping") and hasattr(onnx, "_mapping"):
onnx.mapping = onnx._mapping # type: ignore[attr-defined]
if not hasattr(onnx, "mapping"):
raise RuntimeError(
"Incompatible onnx version detected. rknn-toolkit2 expects onnx.mapping. "
"Install a compatible version (e.g. pip install 'onnx>=1.16.0')."
)
# rknn-toolkit2 expects onnx.mapping.TENSOR_TYPE_TO_NP_TYPE and NP_TYPE_TO_TENSOR_TYPE
if not hasattr(onnx.mapping, "TENSOR_TYPE_TO_NP_TYPE"):
try:
import numpy as np # type: ignore
mapping = {}
for value in onnx.TensorProto.DataType.values():
try:
np_type = onnx.helper.tensor_dtype_to_np_dtype(value)
if isinstance(np_type, type) or isinstance(np_type, np.dtype):
mapping[value] = np_type
except Exception:
continue
onnx.mapping.TENSOR_TYPE_TO_NP_TYPE = mapping # type: ignore[attr-defined]
if hasattr(onnx, "_mapping"):
onnx._mapping.TENSOR_TYPE_TO_NP_TYPE = mapping # type: ignore[attr-defined]
except Exception as exc:
raise RuntimeError(
"onnx mapping is missing TENSOR_TYPE_TO_NP_TYPE and could not be built. "
"Try onnx==1.17.* or install numpy."
) from exc
if not hasattr(onnx.mapping, "NP_TYPE_TO_TENSOR_TYPE"):
try:
import numpy as np # type: ignore
inverse = {}
for tensor_type, np_type in onnx.mapping.TENSOR_TYPE_TO_NP_TYPE.items():
try:
dtype = np.dtype(np_type)
inverse[dtype] = tensor_type
inverse[dtype.type] = tensor_type
except Exception:
continue
onnx.mapping.NP_TYPE_TO_TENSOR_TYPE = inverse # type: ignore[attr-defined]
if hasattr(onnx, "_mapping"):
onnx._mapping.NP_TYPE_TO_TENSOR_TYPE = inverse # type: ignore[attr-defined]
except Exception as exc:
raise RuntimeError(
"onnx mapping is missing NP_TYPE_TO_TENSOR_TYPE and could not be built. "
"Try onnx==1.17.* or install numpy."
) from exc
try:
from rknn.api import RKNN # type: ignore
except Exception as exc:
raise RuntimeError(
"RKNN Toolkit is required. Install rknn-toolkit or rknn-toolkit2."
) from exc
if not target_platform:
raise RuntimeError(
"RKNN target platform is required. "
"Pass --target-platform with your board type, e.g. --target-platform rk3588."
)
rknn = RKNN(verbose=verbose)
config_kwargs = {
"target_platform": target_platform,
"optimization_level": optimization_level,
"quant_img_RGB2BGR": True,
}
if mean_values:
config_kwargs["mean_values"] = [mean_values]
if std_values:
config_kwargs["std_values"] = [std_values]
if quantize:
config_kwargs["quantized_dtype"] = quantized_dtype or DEFAULT_QUANTIZED_DTYPE
if dynamic_shapes:
# rknn-toolkit2 expects: [[[shape]]] where shape is the full shape list
# Format: list(inputs) -> list(list(one_shape)) -> shape is list of dims
# For single input with shape [1, 3, 320, 320]: [[[1, 3, 320, 320]]]
first_shape = dynamic_shapes[0]
config_kwargs["dynamic_input"] = [[first_shape]]
try:
rknn.config(**config_kwargs)
except Exception as exc:
raise RuntimeError(
f"Failed to configure RKNN for target platform {target_platform!r}. "
"Pass the correct board type with --target-platform."
) from exc
ret = rknn.load_onnx(model=str(onnx_path))
if ret != 0:
raise RuntimeError("Failed to load ONNX model.")
if quantize and dataset is None:
raise RuntimeError("Quantization enabled but no dataset was provided.")
ret = rknn.build(
do_quantization=quantize,
dataset=str(dataset) if dataset else None,
)
if ret != 0:
raise RuntimeError("Failed to build RKNN model.")
rknn_output.parent.mkdir(parents=True, exist_ok=True)
ret = rknn.export_rknn(str(rknn_output))
if ret != 0:
raise RuntimeError("Failed to export RKNN model.")
rknn.release()
def main() -> int:
parser = argparse.ArgumentParser(description="Convert .pt to RKNN.")
parser.add_argument("--input", required=True, help="Path to .pt file.")
parser.add_argument(
"--output",
help="Path to output .rknn file. Defaults next to input.",
)
parser.add_argument(
"--keep-onnx",
action="store_true",
help="Keep the intermediate ONNX file.",
)
parser.add_argument("--imgsz", type=int, default=320, help="Export image size.")
parser.add_argument("--opset", type=int, default=12, help="ONNX opset version.")
_add_bool_arg(parser, "simplify", True)
_add_bool_arg(parser, "dynamic", False)
_add_bool_arg(parser, "half", DEFAULT_HALF)
_add_bool_arg(parser, "nms", DEFAULT_NMS)
parser.add_argument(
"--int8",
action="store_true",
help="Enable INT8 RKNN quantization for a smaller model (requires --dataset).",
)
parser.add_argument("--dataset", help="Calibration dataset for quantization.")
parser.add_argument(
"--quantize",
action="store_true",
help="Enable INT8 quantization (requires --dataset).",
)
parser.add_argument(
"--no-quantize",
dest="quantize",
action="store_false",
help="Disable quantization even if dataset is provided.",
)
parser.set_defaults(quantize=None)
parser.add_argument(
"--target-platform",
default=DEFAULT_TARGET_PLATFORM,
choices=VALID_TARGET_PLATFORMS,
help=f"Target platform. Defaults to {DEFAULT_TARGET_PLATFORM}.",
)
parser.add_argument(
"--mean-values",
default=DEFAULT_MEAN_VALUES,
help=f"Comma-separated mean values. Defaults to {DEFAULT_MEAN_VALUES}.",
)
parser.add_argument(
"--std-values",
default=DEFAULT_STD_VALUES,
help=f"Comma-separated std values. Defaults to {DEFAULT_STD_VALUES}.",
)
parser.add_argument(
"--quantized-dtype",
default=DEFAULT_QUANTIZED_DTYPE,
help=(
"Quantized dtype used when building INT8 RKNN. "
f"Defaults to {DEFAULT_QUANTIZED_DTYPE}."
),
)
parser.add_argument(
"--optimization-level",
type=int,
choices=(0, 1, 2, 3),
default=DEFAULT_OPTIMIZATION_LEVEL,
help=f"RKNN build optimization level. Defaults to {DEFAULT_OPTIMIZATION_LEVEL}.",
)
parser.add_argument("--verbose", action="store_true", help="Verbose logs.")
parser.add_argument(
"--dynamic-shapes",
help=(
"Enable RKNN dynamic input shapes. Format: "
"'1,3,320,320' (single shape per input). "
"If multiple shapes provided (semicolon-separated), only the first is used."
),
)
args = parser.parse_args()
input_path = Path(args.input).expanduser().resolve()
if not input_path.exists():
print(f"Input file not found: {input_path}", file=sys.stderr)
return 1
rknn_output = (
Path(args.output).expanduser().resolve()
if args.output
else input_path.with_suffix(".rknn")
)
if input_path.suffix.lower() != ".pt":
print("Input must be a .pt file.", file=sys.stderr)
return 1
onnx_path = input_path.with_suffix(".onnx")
if args.dynamic_shapes and not args.dynamic:
print("⚠️ --dynamic-shapes set; enabling dynamic ONNX export.")
args.dynamic = True
onnx_path = export_pt_to_onnx(
pt_path=input_path,
onnx_output=onnx_path,
imgsz=args.imgsz,
opset=args.opset,
simplify=args.simplify,
dynamic=args.dynamic,
half=args.half,
nms=args.nms,
verbose=args.verbose,
)
mean_values = _parse_list(args.mean_values, "mean-values") if args.mean_values else []
std_values = _parse_list(args.std_values, "std-values") if args.std_values else []
if mean_values and std_values and len(mean_values) != len(std_values):
print("mean-values and std-values must have the same length.", file=sys.stderr)
return 1
dataset = Path(args.dataset).expanduser().resolve() if args.dataset else None
if dataset and not dataset.exists():
print(f"Dataset file not found: {dataset}", file=sys.stderr)
return 1
quantize = args.quantize
if args.int8:
quantize = True
if quantize is None:
quantize = args.int8 or dataset is not None
if quantize and dataset is None:
print(
"INT8 quantization requires --dataset with calibration image paths "
"(one path per line).",
file=sys.stderr,
)
return 1
dynamic_shapes = None
if args.dynamic_shapes:
if quantize:
print(
"INT8 quantization is not compatible with --dynamic-shapes in "
"rknn-toolkit2 2.3.2. Re-run without --dynamic-shapes.",
file=sys.stderr,
)
return 1
if args.dynamic_shapes:
try:
parsed_shapes = [
[int(v) for v in shape.split(",") if v.strip()]
for shape in args.dynamic_shapes.split(";")
if shape.strip()
]
if not parsed_shapes:
print("Invalid --dynamic-shapes format.", file=sys.stderr)
return 1
if len(parsed_shapes) > 1:
print(
f"⚠️ Multiple shapes provided, but RKNN only supports one shape per input. "
f"Using first shape: {parsed_shapes[0]}",
file=sys.stderr,
)
dynamic_shapes = parsed_shapes
except ValueError:
print("Invalid --dynamic-shapes format.", file=sys.stderr)
return 1
try:
convert_onnx_to_rknn(
onnx_path=onnx_path,
rknn_output=rknn_output,
dataset=dataset,
quantize=quantize,
target_platform=args.target_platform,
mean_values=mean_values,
std_values=std_values,
quantized_dtype=args.quantized_dtype if quantize else None,
optimization_level=args.optimization_level,
verbose=args.verbose,
dynamic_shapes=dynamic_shapes,
)
except RuntimeError as exc:
print(str(exc), file=sys.stderr)
return 1
# finally:
# if onnx_path.exists() and not args.keep_onnx:
# try:
# onnx_path.unlink()
# except OSError:
# pass
print(f"RKNN saved to: {rknn_output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+3
View File
@@ -0,0 +1,3 @@
ultralytics
rknn-toolkit2
onnx>=1.16.0
-122
View File
@@ -1,122 +0,0 @@
"""HTTP client for MotionEye batch video ingest."""
from __future__ import annotations
import os
from pathlib import Path
from typing import Optional
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
try:
import requests
except ImportError: # pragma: no cover
requests = None
def _ingest_url() -> str:
return os.getenv("MOTIONEYE_INGEST_URL", "http://192.168.192.251:8090").rstrip("/")
def _token() -> str:
return os.getenv("MOTIONEYE_INGEST_TOKEN", "change-me-ingest-token")
def batch_video_filename(batch_id: str) -> str:
return f"batch_{batch_id}.mp4"
def resolve_video_url(batch_id: str) -> str:
"""Canonical download URL served by the ingest service."""
return f"{_ingest_url()}/files/{batch_id}"
def upload_batch_video(local_path: str | Path, batch_id: str, timeout: float = 120.0) -> dict:
"""
Upload a finalized batch mp4 to MotionEye ingest.
Returns JSON dict with video_url on success. Raises on failure.
"""
path = Path(local_path)
if not path.is_file():
raise FileNotFoundError(str(path))
url = f"{_ingest_url()}/upload"
headers = {"X-Ingest-Token": _token()}
if requests is not None:
with path.open("rb") as fh:
resp = requests.post(
url,
headers=headers,
data={"batch_id": batch_id},
files={"file": (batch_video_filename(batch_id), fh, "video/mp4")},
timeout=timeout,
)
if resp.status_code >= 400:
raise RuntimeError(f"ingest HTTP {resp.status_code}: {resp.text[:300]}")
data = resp.json()
if not data.get("success"):
raise RuntimeError(data.get("error") or "upload failed")
return data
# Minimal fallback without requests (multipart is awkward; require requests)
raise RuntimeError("requests package required for motioneye upload")
def health_check(timeout: float = 5.0) -> bool:
url = f"{_ingest_url()}/health"
try:
if requests is not None:
r = requests.get(url, timeout=timeout)
return r.status_code == 200 and r.json().get("ok") is True
with urlopen(Request(url), timeout=timeout) as resp:
return resp.status == 200
except (URLError, HTTPError, OSError, ValueError):
return False
def file_exists(batch_id: str, timeout: float = 5.0) -> Optional[dict]:
url = f"{_ingest_url()}/files/{batch_id}?meta=1"
try:
if requests is not None:
r = requests.get(url, timeout=timeout)
if r.status_code == 404:
return None
r.raise_for_status()
return r.json()
with urlopen(Request(url), timeout=timeout) as resp:
import json
return json.loads(resp.read().decode("utf-8"))
except Exception:
return None
def delete_batch_video(batch_id: str, timeout: float = 30.0) -> dict:
"""Delete a finalized batch mp4 from MotionEye ingest."""
url = f"{_ingest_url()}/files/{batch_id}"
headers = {"X-Ingest-Token": _token()}
if requests is not None:
resp = requests.delete(url, headers=headers, timeout=timeout)
if resp.status_code >= 400:
raise RuntimeError(f"ingest HTTP {resp.status_code}: {resp.text[:300]}")
data = resp.json()
if not data.get("success"):
raise RuntimeError(data.get("error") or "delete failed")
return data
req = Request(url, method="DELETE", headers=headers)
try:
with urlopen(req, timeout=timeout) as resp:
import json
data = json.loads(resp.read().decode("utf-8"))
if not data.get("success"):
raise RuntimeError(data.get("error") or "delete failed")
return data
except HTTPError as exc:
body = exc.read().decode("utf-8", errors="ignore")
raise RuntimeError(f"ingest HTTP {exc.code}: {body[:300]}") from exc
except URLError as exc:
raise RuntimeError(f"ingest URL error: {exc}") from exc
View File
Whitespace-only changes.
-151
View File
@@ -1,151 +0,0 @@
#!/usr/bin/env python3
"""
HTTP ingest for MotionEye media storage.
Receives batch_*.mp4 from NanoPi 1 and writes into MOTIONEYE_MEDIA_DIR.
"""
from __future__ import annotations
import os
import re
from pathlib import Path
from dotenv import load_dotenv
from flask import Flask, jsonify, request, send_from_directory
load_dotenv()
MEDIA_DIR = Path(os.getenv("MOTIONEYE_MEDIA_DIR", "/data/media/Camera1"))
INGEST_TOKEN = os.getenv("MOTIONEYE_INGEST_TOKEN", "change-me-ingest-token")
HOST = os.getenv("MOTIONEYE_INGEST_HOST", "0.0.0.0")
PORT = int(os.getenv("MOTIONEYE_INGEST_PORT", "8090"))
PUBLIC_BASE = os.getenv(
"MOTIONEYE_INGEST_PUBLIC_BASE",
os.getenv("MOTIONEYE_INGEST_URL", f"http://127.0.0.1:{PORT}"),
).rstrip("/")
BATCH_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]?$")
app = Flask(__name__)
MEDIA_DIR.mkdir(parents=True, exist_ok=True)
def _auth_ok() -> bool:
token = request.headers.get("X-Ingest-Token", "")
return bool(INGEST_TOKEN) and token == INGEST_TOKEN
def _filename(batch_id: str) -> str:
return f"batch_{batch_id}.mp4"
@app.get("/health")
def health():
return jsonify(
{
"ok": True,
"media_dir": str(MEDIA_DIR),
"writable": os.access(MEDIA_DIR, os.W_OK),
}
)
@app.post("/upload")
def upload():
if not _auth_ok():
return jsonify({"success": False, "error": "unauthorized"}), 401
batch_id = (request.form.get("batch_id") or "").strip()
if not BATCH_ID_RE.match(batch_id):
return jsonify({"success": False, "error": "invalid batch_id"}), 400
f = request.files.get("file")
if f is None or not f.filename:
return jsonify({"success": False, "error": "file required"}), 400
name = _filename(batch_id)
dest = MEDIA_DIR / name
tmp = MEDIA_DIR / f".{name}.partial"
try:
f.save(str(tmp))
tmp.replace(dest)
except Exception as exc:
if tmp.exists():
tmp.unlink(missing_ok=True)
return jsonify({"success": False, "error": str(exc)}), 500
video_url = f"{PUBLIC_BASE}/files/{batch_id}"
return jsonify(
{
"success": True,
"batch_id": batch_id,
"filename": name,
"path": str(dest),
"video_url": video_url,
"size": dest.stat().st_size,
}
)
@app.get("/files/<batch_id>")
def get_file(batch_id: str):
if not BATCH_ID_RE.match(batch_id):
return jsonify({"success": False, "error": "invalid batch_id"}), 400
name = _filename(batch_id)
path = MEDIA_DIR / name
if not path.is_file():
return jsonify({"success": False, "error": "not found"}), 404
if request.args.get("meta") == "1":
return jsonify(
{
"success": True,
"batch_id": batch_id,
"filename": name,
"video_url": f"{PUBLIC_BASE}/files/{batch_id}",
"size": path.stat().st_size,
}
)
return send_from_directory(MEDIA_DIR, name, mimetype="video/mp4", as_attachment=False)
@app.delete("/files/<batch_id>")
def delete_file(batch_id: str):
if not _auth_ok():
return jsonify({"success": False, "error": "unauthorized"}), 401
if not BATCH_ID_RE.match(batch_id):
return jsonify({"success": False, "error": "invalid batch_id"}), 400
path = MEDIA_DIR / _filename(batch_id)
deleted = False
if path.exists():
if not path.is_file():
return jsonify({"success": False, "error": "not a file"}), 400
try:
path.unlink()
deleted = True
except Exception as exc:
return jsonify({"success": False, "error": str(exc)}), 500
return jsonify({"success": True, "batch_id": batch_id, "deleted": deleted})
@app.get("/list")
def list_files():
if not _auth_ok():
return jsonify({"success": False, "error": "unauthorized"}), 401
files = sorted(MEDIA_DIR.glob("batch_*.mp4"))
items = [
{
"filename": p.name,
"batch_id": p.stem.replace("batch_", "", 1),
"size": p.stat().st_size,
"video_url": f"{PUBLIC_BASE}/files/{p.stem.replace('batch_', '', 1)}",
}
for p in files
]
return jsonify({"success": True, "files": items})
if __name__ == "__main__":
print(f"MotionEye ingest on http://{HOST}:{PORT}")
print(f"Media dir: {MEDIA_DIR}")
app.run(host=HOST, port=PORT, threaded=True)
+123 -52
View File
@@ -1,9 +1,10 @@
#!/usr/bin/env python3
"""
NanoPi 2 recount engine — process batch videos with RKNN + ByteTrack,
Local recount engine — process batch videos with OpenVINO + ByteTrack,
emit progress over HTTP, render annotated output video.
RKNN model is loaded once at process start and reused for every job.
OpenVINO model is loaded once at process start and reused for every job.
Pinned to E-cores (RECOUNT_CPU_CORES) so real-time counting is never starved.
"""
from __future__ import annotations
@@ -11,6 +12,7 @@ from __future__ import annotations
import atexit
import os
import re
import signal
import subprocess
import sys
import threading
@@ -23,8 +25,8 @@ from flask import Flask, Response, jsonify, request, send_from_directory
# Repo root on PATH for counter_live imports
_ROOT = Path(__file__).resolve().parent.parent
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
if str(ROOT := _ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
load_dotenv(_ROOT / ".env")
@@ -36,7 +38,8 @@ from counter_live_rknn_bytetrack import ( # noqa: E402
LINE_PULSE_FRAMES,
POPUP_LIFETIME,
ByteTracker,
RKNNYOLO,
OpenVINOYOLO,
apply_cpu_affinity,
crossed_line,
draw_batch_banner,
draw_elegant_counting_line,
@@ -47,19 +50,26 @@ from counter_live_rknn_bytetrack import ( # noqa: E402
draw_track_marker,
)
RECOUNT_CPU_CORES = os.getenv("RECOUNT_CPU_CORES", "8-15").strip()
apply_cpu_affinity(RECOUNT_CPU_CORES, label="recount-engine")
app = Flask(__name__)
HOST = os.getenv("RECOUNT_HOST", "0.0.0.0")
PORT = int(os.getenv("RECOUNT_PORT", "8765"))
OUTPUT_DIR = Path(os.getenv("RECOUNT_OUTPUT_DIR", str(_ROOT / "recount_output")))
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
BATCH_VIDEO_DIR = Path(os.getenv("BATCH_VIDEO_DIR", str(_ROOT / "batch_videos")))
BATCH_VIDEO_DIR.mkdir(parents=True, exist_ok=True)
PUBLIC_BASE = os.getenv("RECOUNT_PUBLIC_BASE", f"http://127.0.0.1:{PORT}").rstrip("/")
MODEL_PATH = os.getenv("MODEL_PATH", "/opt/models/ngoro-all.rknn")
MODEL_PATH = os.getenv("MODEL_PATH", str(_ROOT / "models" / "best_openvino_model"))
RECOUNT_DEVICE = os.getenv("RECOUNT_OPENVINO_DEVICE", "NPU").strip() or "NPU"
RECOUNT_THREADS = int(os.getenv("RECOUNT_INFERENCE_THREADS", "4"))
RECOUNT_FFMPEG_THREADS = os.getenv("RECOUNT_FFMPEG_THREADS", "4").strip() or "4"
IMGSZ = int(os.getenv("IMGSZ", "320"))
CONF = float(os.getenv("CONF", "0.15"))
IOU = float(os.getenv("IOU", "0.45"))
CORE_MASK = int(os.getenv("CORE_MASK", "7"))
NUM_CLASSES = int(os.getenv("NUM_CLASSES", "2"))
SCORE_SIGMOID = os.getenv("SCORE_SIGMOID", "false").lower() == "true"
LINE_X_FRAC = float(os.getenv("LINE_X_FRAC", "0.19"))
@@ -79,14 +89,14 @@ PROGRESS_EVERY_N = int(os.getenv("RECOUNT_PROGRESS_EVERY_N", "5"))
LIVE_FRAME_EVERY_N = int(os.getenv("RECOUNT_LIVE_FRAME_EVERY_N", "2"))
LIVE_FRAME_MAX_WIDTH = int(os.getenv("RECOUNT_LIVE_FRAME_MAX_WIDTH", "960"))
LIVE_FRAME_PATH = Path(
os.getenv("RECOUNT_LIVE_FRAME_PATH", str(OUTPUT_DIR / "live_frame.jpg"))
os.getenv("RECOUNT_LIVE_FRAME_PATH", "/dev/shm/apc-ngoro/recount_live_frame.jpg")
)
LIVE_JPEG_QUALITY = int(os.getenv("RECOUNT_LIVE_JPEG_QUALITY", "60"))
# 1 = realtime paced review; 0 = ASAP (no sleep); does not skip frames
PLAYBACK_SPEED = float(os.getenv("RECOUNT_PLAYBACK_SPEED", "0"))
RECOUNT_START_COUNT = int(os.getenv("RECOUNT_START_COUNT", "1"))
BATCH_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]?$")
BATCH_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]*$")
_lock = threading.Lock()
_cancel = threading.Event()
@@ -105,7 +115,7 @@ _state = {
"error": None,
}
# Single shared RKNN runtime — load once, reuse forever
# Single shared OpenVINO runtime — load once, reuse forever
_model = None
_model_lock = threading.Lock()
_model_error = None
@@ -122,19 +132,24 @@ def _get_state():
def _load_model_once():
"""Load RKNN into process memory. Safe to call repeatedly."""
"""Load OpenVINO model into process memory. Safe to call repeatedly."""
global _model, _model_error
with _model_lock:
if _model is not None:
return _model
if _model_error and not os.path.isfile(MODEL_PATH):
if _model_error and not os.path.exists(MODEL_PATH):
raise RuntimeError(_model_error)
print(f"[recount] Loading RKNN once: {MODEL_PATH}", flush=True)
print(
f"[recount] Loading OpenVINO once: {MODEL_PATH} "
f"(device={RECOUNT_DEVICE}, threads={RECOUNT_THREADS})",
flush=True,
)
t0 = time.time()
try:
_model = RKNNYOLO(
_model = OpenVINOYOLO(
model_path=MODEL_PATH,
core_mask=CORE_MASK,
device=RECOUNT_DEVICE,
num_threads=RECOUNT_THREADS,
imgsz=IMGSZ,
conf=CONF,
iou=IOU,
@@ -142,7 +157,10 @@ def _load_model_once():
score_sigmoid=SCORE_SIGMOID,
)
_model_error = None
print(f"[recount] Model ready in {time.time() - t0:.1f}s", flush=True)
print(
f"[recount] Model ready on {_model.device} in {time.time() - t0:.1f}s",
flush=True,
)
except Exception as exc:
_model_error = str(exc)
print(f"[recount] Model load failed: {exc}", flush=True)
@@ -339,6 +357,54 @@ def _probe_video_codec(path: Path) -> str:
return ""
def _resolve_local_source(batch_id: str, video_url: str) -> Path | None:
"""Resolve batch source video directly on local NVMe storage without HTTP download.
Supports both batch_<id>.mp4 and <id>.mp4 naming schemes.
"""
raw = (video_url or "").strip()
if raw.startswith("file://"):
p = Path(raw[7:])
if p.is_file() and p.stat().st_size > 0:
return p
elif raw.startswith("/"):
p = Path(raw)
if p.is_file() and p.stat().st_size > 0:
return p
candidates: list[str] = []
if batch_id:
clean_id = str(batch_id).strip()
stripped_id = clean_id.replace("batch_", "", 1)
candidates.extend([
f"batch_{stripped_id}.mp4",
f"{stripped_id}.mp4",
f"batch_{clean_id}.mp4",
clean_id if clean_id.endswith(".mp4") else f"{clean_id}.mp4",
])
for marker in ("/source/", "/files/"):
if marker in raw:
tail = raw.rsplit(marker, 1)[-1].split("?", 1)[0].strip("/")
if tail:
stripped_tail = tail.replace("batch_", "", 1).replace(".mp4", "")
candidates.extend([
f"batch_{stripped_tail}.mp4",
f"{stripped_tail}.mp4",
tail if tail.endswith(".mp4") else f"{tail}.mp4",
])
seen = set()
for name in candidates:
if not name or name in seen:
continue
seen.add(name)
cand = BATCH_VIDEO_DIR / name
if cand.is_file() and cand.stat().st_size > 0:
return cand
return None
def _ensure_browser_mp4(path: Path):
"""
Ensure recount output plays in Chrome/Edge: H.264 + yuv420p + faststart.
@@ -352,14 +418,18 @@ def _ensure_browser_mp4(path: Path):
need_transcode = codec not in ("h264", "avc1", "avc")
try:
if need_transcode:
print(f"[recount] transcoding {path.name} ({codec or '?'}) → h264", flush=True)
print(f"[recount] transcoding {path.name} ({codec or '?'}) → h264 (threads={RECOUNT_FFMPEG_THREADS})", flush=True)
subprocess.run(
[
ffmpeg,
"-y",
"-threads",
str(RECOUNT_FFMPEG_THREADS),
"-i",
str(path),
"-an",
"-threads",
str(RECOUNT_FFMPEG_THREADS),
"-c:v",
"libx264",
"-preset",
@@ -431,42 +501,22 @@ def _run_job(batch_id: str, video_url: str, original_count: int):
model = _load_model_once()
if video_url.startswith("file://"):
src = Path(video_url[7:])
if not src.is_file():
raise FileNotFoundError(video_url)
local_in = src
elif video_url.startswith("/") and Path(video_url).is_file():
local_in = Path(video_url)
else:
# Check if cached or currently being warmed up
resolved_local = _resolve_local_source(batch_id, video_url)
if resolved_local is not None:
local_in = resolved_local
print(f"[recount] using local NVMe source {local_in}", flush=True)
elif video_url.startswith(("http://", "https://")):
if local_in.is_file() and local_in.stat().st_size > 0:
print(f"[recount] using cached source {local_in}", flush=True)
else:
part_in = OUTPUT_DIR / f"_src_{batch_id}.mp4.part"
waited = 0
while part_in.is_file() and not local_in.is_file() and waited < 60:
if _cancel.is_set():
break
with _warmup_lock:
prog_info = _download_progress.get(batch_id)
if prog_info:
pct, msg = prog_info
_set_state(progress=pct, message=msg)
elif part_in.is_file():
try:
curr_bytes = part_in.stat().st_size
dl_mb = curr_bytes / (1024 * 1024)
_set_state(message=f"Mengunduh video sumber… ({dl_mb:.1f} MB)")
except Exception:
pass
time.sleep(0.3)
waited += 0.3
if not local_in.is_file():
print(f"[recount] downloading source {video_url}", flush=True)
ok = _download_with_progress(video_url, local_in, batch_id, is_active_job=True)
if not ok and not _cancel.is_set():
raise RuntimeError(f"Gagal mengunduh video sumber dari {video_url}")
print(f"[recount] downloading source {video_url}", flush=True)
ok = _download_with_progress(video_url, local_in, batch_id, is_active_job=True)
if not ok and not _cancel.is_set():
raise RuntimeError(f"Gagal mengunduh video sumber dari {video_url}")
else:
raise FileNotFoundError(
f"Video sumber lokal untuk batch {batch_id} tidak ditemukan di {BATCH_VIDEO_DIR}"
)
if _cancel.is_set():
_set_state(status="IDLE", progress=0, error="Dibatalkan", video_url=None)
@@ -749,6 +799,9 @@ def health():
"model": MODEL_PATH,
"model_loaded": _model is not None,
"model_error": _model_error,
"device": getattr(_model, "device", RECOUNT_DEVICE),
"cpu_cores": sorted(os.sched_getaffinity(0)),
"batch_video_dir": str(BATCH_VIDEO_DIR),
"output_dir": str(OUTPUT_DIR),
"overlay": "live",
"playback_speed": PLAYBACK_SPEED,
@@ -771,13 +824,23 @@ def warmup():
data = request.get_json(silent=True) or {}
batch_id = (data.get("batch_id") or "").strip()
video_url = (data.get("video_url") or "").strip()
if not batch_id or not video_url:
return jsonify({"success": False, "error": "missing batch_id or video_url"}), 400
if not batch_id:
return jsonify({"success": False, "error": "missing batch_id"}), 400
local_src = _resolve_local_source(batch_id, video_url)
if local_src is not None:
return jsonify({"success": True, "cached": True, "local_path": str(local_src)}), 200
if not video_url:
return jsonify({"success": False, "error": "local source not found and no video_url"}), 404
local_in = OUTPUT_DIR / f"_src_{batch_id}.mp4"
if local_in.is_file() and local_in.stat().st_size > 0:
return jsonify({"success": True, "cached": True}), 200
if not video_url.startswith(("http://", "https://")):
return jsonify({"success": False, "error": "local source not found"}), 404
with _warmup_lock:
if _warmup_batch_id == batch_id:
return jsonify({"success": True, "warming": True}), 200
@@ -894,6 +957,14 @@ def media(filename: str):
if __name__ == "__main__":
def _handle_recount_shutdown(signum, _frame):
_cancel.set()
print(f"\n[recount] Signal {signum} received — shutting down cleanly", flush=True)
raise SystemExit(0)
signal.signal(signal.SIGINT, _handle_recount_shutdown)
signal.signal(signal.SIGTERM, _handle_recount_shutdown)
print(f"Recount engine http://{HOST}:{PORT}")
print(f"Model: {MODEL_PATH}")
print(f"Live frame: {LIVE_FRAME_PATH}")
+3 -2
View File
@@ -1,7 +1,8 @@
numpy<2
rknn-toolkit-lite2
opencv-python
openvino
opencv-python-headless
flask
gunicorn
python-dotenv
openpyxl
requests
+1 -1
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import re
import sqlite3
BATCH_ID_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})-\d+[a-zA-Z]?$")
BATCH_ID_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})-\d+[a-zA-Z]*$")
def active_counting_dates(conn: sqlite3.Connection, limit: int = 3, table: str = "batches") -> list[str]:
+239
View File
@@ -0,0 +1,239 @@
#!/usr/bin/env python3
"""Unified supervisor for ZenAI APC Ngoro.
Manages all three sub-services (Real-time Counter, Recount Engine, Dashboard)
as child processes under a single systemd unit (apc-ngoro-service).
Aggregates stdout/stderr with component prefixes for unified journalctl viewing.
"""
from __future__ import annotations
import os
import signal
import subprocess
import sys
import threading
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VENV_PYTHON = ROOT / "venv" / "bin" / "python"
PYTHON_BIN = str(VENV_PYTHON) if VENV_PYTHON.is_file() else sys.executable
def parse_core_range(spec: str) -> set[int]:
cores: set[int] = set()
for part in spec.split(","):
part = part.strip()
if not part:
continue
if "-" in part:
lo, hi = map(int, part.split("-", 1))
cores.update(range(lo, hi + 1))
else:
cores.add(int(part))
return cores
def make_preexec(cores_spec: str | None, nice_val: int | None):
def preexec():
# Set CPU affinity if requested
if cores_spec and hasattr(os, "sched_setaffinity"):
try:
cores = parse_core_range(cores_spec)
os.sched_setaffinity(0, cores)
except Exception:
pass
# Set nice value if requested
if nice_val is not None:
try:
os.nice(nice_val)
except Exception:
pass
return preexec
class ServiceProcess:
def __init__(
self,
name: str,
cmd: list[str],
tag: str,
cores_spec: str | None = None,
nice_val: int | None = None,
env_extra: dict[str, str] | None = None,
):
self.name = name
self.cmd = cmd
self.tag = tag
self.cores_spec = cores_spec
self.nice_val = nice_val
self.env_extra = env_extra or {}
self.proc: subprocess.Popen | None = None
self.reader_thread: threading.Thread | None = None
self.should_run = True
def start(self):
env = os.environ.copy()
env["PYTHONUNBUFFERED"] = "1"
env["PYTHONNOUSERSITE"] = "1"
env.update(self.env_extra)
preexec = make_preexec(self.cores_spec, self.nice_val)
sys.stdout.write(f"[{self.tag}] Starting {self.name}...\n")
sys.stdout.flush()
self.proc = subprocess.Popen(
self.cmd,
cwd=str(ROOT),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
env=env,
preexec_fn=preexec,
start_new_session=True,
)
self.reader_thread = threading.Thread(
target=self._pipe_output, daemon=True, name=f"pipe-{self.name}"
)
self.reader_thread.start()
def _pipe_output(self):
if not self.proc or not self.proc.stdout:
return
try:
for line in iter(self.proc.stdout.readline, ""):
sys.stdout.write(f"[{self.tag}] {line}")
sys.stdout.flush()
except Exception:
pass
def stop(self, timeout: float = 5.0):
self.should_run = False
if not self.proc or self.proc.poll() is not None:
return
sys.stdout.write(f"[{self.tag}] Stopping {self.name} (SIGTERM)...\n")
sys.stdout.flush()
try:
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
except ProcessLookupError:
return
except Exception:
self.proc.terminate()
start_t = time.time()
while time.time() - start_t < timeout:
if self.proc.poll() is not None:
return
time.sleep(0.2)
sys.stdout.write(f"[{self.tag}] {self.name} did not stop, sending SIGKILL...\n")
sys.stdout.flush()
try:
os.killpg(os.getpgid(self.proc.pid), signal.SIGKILL)
except Exception:
self.proc.kill()
self.proc.wait()
class Supervisor:
def __init__(self):
self.services: list[ServiceProcess] = []
self.running = True
live_cores = os.getenv("LIVE_CPU_CORES", "0-7")
recount_cores = os.getenv("RECOUNT_CPU_CORES", "8-15")
dashboard_cores = os.getenv("DASHBOARD_CPU_CORES", "14-17")
self.services.append(
ServiceProcess(
name="Counter Live",
cmd=[PYTHON_BIN, "-u", "counter_live_rknn_bytetrack.py"],
tag="COUNTER",
cores_spec=live_cores,
nice_val=-10,
env_extra={
"YOLO_CONFIG_DIR": str(ROOT / ".ultralytics"),
"TORCH_HOME": str(ROOT / ".torch"),
},
)
)
self.services.append(
ServiceProcess(
name="Recount Engine",
cmd=[PYTHON_BIN, "-u", "recount_engine/app.py"],
tag="RECOUNT",
cores_spec=recount_cores,
nice_val=10,
)
)
self.services.append(
ServiceProcess(
name="Dashboard",
cmd=[PYTHON_BIN, "counter_dashboard.py"],
tag="DASHBOARD",
cores_spec=dashboard_cores,
nice_val=0,
env_extra={"FLASK_DEBUG": "false"},
)
)
def handle_signal(self, signum, frame):
sig_name = signal.Signals(signum).name
sys.stdout.write(f"[SUPERVISOR] Received signal {sig_name}, initiating graceful shutdown...\n")
sys.stdout.flush()
self.running = False
def run(self):
signal.signal(signal.SIGTERM, self.handle_signal)
signal.signal(signal.SIGINT, self.handle_signal)
sys.stdout.write("[SUPERVISOR] Starting APC Ngoro Unified Services...\n")
sys.stdout.flush()
for s in self.services:
s.start()
time.sleep(0.5)
# Monitor loop
while self.running:
for s in self.services:
if s.proc and s.proc.poll() is not None and s.should_run:
code = s.proc.poll()
sys.stdout.write(
f"[{s.tag}] Process exited with code {code}. Respawning in 5 seconds...\n"
)
sys.stdout.flush()
time.sleep(5.0)
if self.running and s.should_run:
s.start()
time.sleep(0.5)
# Shutdown sequence (parallel stop)
threads = []
for s in self.services:
t = threading.Thread(target=s.stop, args=(5.0,))
t.start()
threads.append(t)
for t in threads:
t.join()
sys.stdout.write("[SUPERVISOR] All services stopped cleanly.\n")
sys.stdout.flush()
def main():
env_file = ROOT / ".env"
if env_file.is_file():
from dotenv import load_dotenv
load_dotenv(env_file)
supervisor = Supervisor()
supervisor.run()
if __name__ == "__main__":
main()
-35
View File
@@ -1,35 +0,0 @@
#!/usr/bin/env bash
# Copy RKNN model from NanoPi 1 -> NanoPi 2 and restart recount.
# Run interactively (needs password once): bash scripts/copy-model-to-nanopi2.sh
set -euo pipefail
HOST="${NANOPI2_HOST:-192.168.192.16}"
USER="${NANOPI2_SSH_USER:-root}"
MODEL="${MODEL_PATH:-/opt/models/zenai_apc_ngoro_20260908.rknn}"
if [[ ! -f "$MODEL" ]]; then
echo "Model not found: $MODEL" >&2
exit 1
fi
SSH_BASE=(ssh -o StrictHostKeyChecking=accept-new)
SCP_BASE=(scp -o StrictHostKeyChecking=accept-new)
CONTROL_PATH="${HOME}/.ssh/cm-nanopi2-model-%r@%h:%p"
mkdir -p "${HOME}/.ssh"
cleanup() {
"${SSH_BASE[@]}" -O exit -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}" 2>/dev/null || true
}
trap cleanup EXIT
echo "==> SSH master to ${USER}@${HOST} (enter password once)"
"${SSH_BASE[@]}" -MNf -o ControlMaster=yes -o ControlPersist=120 -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}"
SSH=("${SSH_BASE[@]}" -o ControlPath="$CONTROL_PATH")
SCP=("${SCP_BASE[@]}" -o ControlPath="$CONTROL_PATH")
echo "==> Copy $(basename "$MODEL") → ${HOST}:/opt/models/"
"${SSH[@]}" "${USER}@${HOST}" "mkdir -p /opt/models"
"${SCP[@]}" "$MODEL" "${USER}@${HOST}:/opt/models/"
"${SSH[@]}" "${USER}@${HOST}" "ls -la /opt/models/$(basename "$MODEL"); systemctl restart apc-ngoro-recount.service; sleep 1; systemctl is-active apc-ngoro-recount.service; curl -sS http://127.0.0.1:8765/health; echo"
echo "==> Done. Re-test recount from dashboard or:"
echo " curl -X POST http://127.0.0.1:5000/api/v1/recount/start -H 'Content-Type: application/json' -d '{\"batch_id\":\"2026-09-09-19\"}'"
-27
View File
@@ -1,27 +0,0 @@
#!/usr/bin/env bash
# Remove deprecated MotionEye-side calendar cleanup cron.
# Active-day retention now runs from NanoPi 1 via scripts/deploy-retention-cron.sh.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOST="${MOTIONEYE_HOST:-192.168.192.251}"
USER="${MOTIONEYE_SSH_USER:-support}"
SSH_BASE=(ssh -o StrictHostKeyChecking=accept-new)
SCP_BASE=(scp -o StrictHostKeyChecking=accept-new)
CONTROL_PATH="${HOME}/.ssh/cm-motioneye-cron-%r@%h:%p"
mkdir -p "${HOME}/.ssh"
cleanup() {
"${SSH_BASE[@]}" -O exit -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}" 2>/dev/null || true
}
trap cleanup EXIT
echo "==> SSH master to ${USER}@${HOST} (password once)"
"${SSH_BASE[@]}" -MNf -o ControlMaster=yes -o ControlPersist=120 -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}"
SSH=("${SSH_BASE[@]}" -o ControlPath="$CONTROL_PATH" -t)
SCP=("${SCP_BASE[@]}" -o ControlPath="$CONTROL_PATH")
"${SCP[@]}" "$ROOT/scripts/motioneye-batch-cleanup.sh" "${USER}@${HOST}:/tmp/motioneye-batch-cleanup.sh"
"${SSH[@]}" "${USER}@${HOST}" "sudo mkdir -p /opt/apc-ngoro/scripts && sudo cp /tmp/motioneye-batch-cleanup.sh /opt/apc-ngoro/scripts/ && sudo chmod +x /opt/apc-ngoro/scripts/motioneye-batch-cleanup.sh && sudo rm -f /etc/cron.d/apc-batch-cleanup && echo removed && ls -l /etc/cron.d/apc-batch-cleanup 2>/dev/null || true"
echo "==> Deprecated MotionEye cleanup cron removed. Install the new NP1/NP2 retention cron with: bash /opt/apc-ngoro/scripts/deploy-retention-cron.sh"
-57
View File
@@ -1,57 +0,0 @@
#!/usr/bin/env bash
# Deploy MotionEye ingest with ONE password prompt (SSH ControlMaster + single tarball).
# Usage: bash scripts/deploy-motioneye-ingest.sh
# Default SSH user: support
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOST="${MOTIONEYE_HOST:-192.168.192.251}"
USER="${MOTIONEYE_SSH_USER:-support}"
REMOTE_DIR="${REMOTE_DIR:-/opt/apc-ngoro}"
# Do NOT force nanopi_agent key — that key is not authorized on ME and makes
# password auth flaky across many connections. Use SSH_KEY only if you set it.
SSH_BASE=(ssh -o StrictHostKeyChecking=accept-new)
SCP_BASE=(scp -o StrictHostKeyChecking=accept-new)
if [[ -n "${SSH_KEY:-}" && -f "${SSH_KEY}" ]]; then
SSH_BASE=(ssh -i "$SSH_KEY" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new)
SCP_BASE=(scp -i "$SSH_KEY" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new)
fi
CONTROL_PATH="${HOME}/.ssh/cm-motioneye-%r@%h:%p"
mkdir -p "${HOME}/.ssh"
chmod 700 "${HOME}/.ssh"
cleanup() {
"${SSH_BASE[@]}" -O exit -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}" 2>/dev/null || true
}
trap cleanup EXIT
echo "==> Packaging ingest files"
STAGE=$(mktemp -d)
PKG_TAR="/tmp/apc-me-ingest-$$.tgz"
mkdir -p "$STAGE/motioneye_ingest" "$STAGE/systemd" "$STAGE/scripts"
cp -a "$ROOT/motioneye_ingest/." "$STAGE/motioneye_ingest/"
cp -a "$ROOT/systemd/apc-motioneye-ingest.service" "$STAGE/systemd/"
cp -a "$ROOT/requirements.txt" "$ROOT/config.env.example" "$STAGE/"
cp -a "$ROOT/scripts/remote-install-motioneye-ingest.sh" "$STAGE/scripts/"
chmod +x "$STAGE/scripts/remote-install-motioneye-ingest.sh"
tar -czf "$PKG_TAR" -C "$STAGE" .
rm -rf "$STAGE"
echo "==> Opening SSH master session to ${USER}@${HOST}"
echo " Enter the support password ONCE when asked."
"${SSH_BASE[@]}" -MNf -o ControlMaster=yes -o ControlPersist=120 -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}"
SSH=("${SSH_BASE[@]}" -o ControlPath="$CONTROL_PATH")
SCP=("${SCP_BASE[@]}" -o ControlPath="$CONTROL_PATH")
echo "==> Uploading package (no second password if ControlMaster works)"
"${SCP[@]}" "$PKG_TAR" "${USER}@${HOST}:/tmp/apc-me-ingest.tgz"
echo "==> Remote install (sudo password may be asked once)"
"${SSH[@]}" -t "${USER}@${HOST}" "rm -rf /tmp/apc-me-ingest-pkg && mkdir -p /tmp/apc-me-ingest-pkg && tar -xzf /tmp/apc-me-ingest.tgz -C /tmp/apc-me-ingest-pkg && PKG_DIR=/tmp/apc-me-ingest-pkg REMOTE_DIR=${REMOTE_DIR} bash /tmp/apc-me-ingest-pkg/scripts/remote-install-motioneye-ingest.sh"
rm -f "$PKG_TAR"
echo "==> Done. Test from NanoPi 1:"
echo " curl -sS -H \"X-Ingest-Token: \${MOTIONEYE_INGEST_TOKEN:-change-me-ingest-token}\" http://${HOST}:8090/health"
-75
View File
@@ -1,75 +0,0 @@
#!/usr/bin/env bash
# Deploy recount engine to NanoPi 2 with ONE SSH password (ControlMaster + tarball).
# Usage: bash scripts/deploy-recount-to-nanopi2.sh
# Optional: NANOPI2_SSH_USER=support NANOPI2_HOST=192.168.192.16
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOST="${NANOPI2_HOST:-192.168.192.16}"
USER="${NANOPI2_SSH_USER:-root}"
REMOTE_DIR="${REMOTE_DIR:-/opt/apc-ngoro}"
SSH_BASE=(ssh -o StrictHostKeyChecking=accept-new)
SCP_BASE=(scp -o StrictHostKeyChecking=accept-new)
if [[ -n "${SSH_KEY:-}" && -f "${SSH_KEY}" ]]; then
SSH_BASE=(ssh -i "$SSH_KEY" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new)
SCP_BASE=(scp -i "$SSH_KEY" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new)
fi
CONTROL_PATH="${HOME}/.ssh/cm-nanopi2-%r@%h:%p"
mkdir -p "${HOME}/.ssh"
chmod 700 "${HOME}/.ssh"
cleanup() {
"${SSH_BASE[@]}" -O exit -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}" 2>/dev/null || true
}
trap cleanup EXIT
echo "==> Packaging recount files"
STAGE=$(mktemp -d)
PKG_TAR="/tmp/apc-np2-recount-$$.tgz"
mkdir -p "$STAGE"
# Copy only what NP2 needs (exclude local venv/db/media)
rsync -a \
--exclude 'venv/' \
--exclude '__pycache__/' \
--exclude '*.db' \
--exclude '.git/' \
--exclude 'motioneye_media/' \
--exclude 'recount_output/' \
--exclude '*.csv' \
"$ROOT/" "$STAGE/"
cp -a "$ROOT/scripts/remote-install-recount.sh" "$STAGE/scripts/"
chmod +x "$STAGE/scripts/remote-install-recount.sh"
# Bundle RKNN model so NP2 can load it (from env, .env, or latest default)
if [[ -z "${MODEL_PATH:-}" && -f "$ROOT/.env" ]]; then
MODEL_PATH="$(grep -E '^MODEL_PATH=' "$ROOT/.env" | tail -1 | cut -d= -f2- | tr -d \"\'\")"
fi
MODEL_SRC="${MODEL_PATH:-/opt/models/zenai_apc_ngoro_20260910.rknn}"
if [[ -f "$MODEL_SRC" ]]; then
mkdir -p "$STAGE/bundled_models"
cp -a "$MODEL_SRC" "$STAGE/bundled_models/"
echo " + bundled model $(basename "$MODEL_SRC")"
else
echo " WARN: model not found at ${MODEL_SRC} — NP2 must already have it"
fi
tar -czf "$PKG_TAR" -C "$STAGE" .
rm -rf "$STAGE"
echo "==> Opening SSH master session to ${USER}@${HOST}"
echo " Enter the ${USER} password ONCE when asked."
"${SSH_BASE[@]}" -MNf -o ControlMaster=yes -o ControlPersist=180 -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}"
SSH=("${SSH_BASE[@]}" -o ControlPath="$CONTROL_PATH")
SCP=("${SCP_BASE[@]}" -o ControlPath="$CONTROL_PATH")
echo "==> Uploading package"
"${SCP[@]}" "$PKG_TAR" "${USER}@${HOST}:/tmp/apc-np2-recount.tgz"
echo "==> Remote install"
"${SSH[@]}" -t "${USER}@${HOST}" "rm -rf /tmp/apc-np2-recount-pkg && mkdir -p /tmp/apc-np2-recount-pkg && tar -xzf /tmp/apc-np2-recount.tgz -C /tmp/apc-np2-recount-pkg && PKG_DIR=/tmp/apc-np2-recount-pkg REMOTE_DIR=${REMOTE_DIR} NANOPI2_PUBLIC_IP=${HOST} bash /tmp/apc-np2-recount-pkg/scripts/remote-install-recount.sh"
rm -f "$PKG_TAR"
echo "==> Done. Test: curl -sS http://${HOST}:8765/health"
+13 -13
View File
@@ -1,24 +1,24 @@
#!/usr/bin/env bash
# Install active-day retention cron on NanoPi 1 and overlay cleanup cron on NanoPi 2.
# Install local active-day batch video retention and recount overlay cleanup crons.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
NP2_HOST="${NANOPI2_HOST:-192.168.192.16}"
NP2_USER="${NANOPI2_SSH_USER:-root}"
PYTHON_BIN="${ROOT}/venv/bin/python"
echo "==> Installing local NP1 retention cron"
echo "==> Installing local retention and recount cleanup crons for ${ROOT}"
sudo mkdir -p /etc/cron.d
cat <<'EOF' | sudo tee /etc/cron.d/apc-retention >/dev/null
0 1 * * * root cd /opt/apc-ngoro && /opt/apc-ngoro/venv/bin/python scripts/retention_active_days.py >> /var/log/apc-retention.log 2>&1
cat <<EOF | sudo tee /etc/cron.d/apc-retention >/dev/null
0 1 * * * admin123 cd ${ROOT} && ${PYTHON_BIN} scripts/retention_active_days.py >> /tmp/apc-retention.log 2>&1
EOF
sudo chmod 644 /etc/cron.d/apc-retention
cat <<EOF | sudo tee /etc/cron.d/apc-recount-cleanup >/dev/null
0 * * * * admin123 cd ${ROOT} && ${PYTHON_BIN} scripts/recount_overlay_cleanup.py >> /tmp/apc-recount-cleanup.log 2>&1
EOF
sudo chmod 644 /etc/cron.d/apc-recount-cleanup
sudo rm -f /etc/cron.d/apc-batch-cleanup
echo "installed /etc/cron.d/apc-retention"
echo "==> Ensuring NP2 hourly overlay cleanup via remote installer"
bash "$ROOT/scripts/deploy-recount-to-nanopi2.sh"
echo "==> Verifying local cron"
echo "==> Verifying installed crons"
cat /etc/cron.d/apc-retention
echo
echo "==> Reminder: NP2 cron is installed by remote installer at /etc/cron.d/apc-recount-cleanup on ${NP2_USER}@${NP2_HOST}"
cat /etc/cron.d/apc-recount-cleanup
@@ -1,3 +0,0 @@
# Deprecated example. Active-day retention is now installed from NanoPi 1:
# bash /opt/apc-ngoro/scripts/deploy-motioneye-cleanup-cron.sh # remove old MotionEye cron
# bash /opt/apc-ngoro/scripts/deploy-retention-cron.sh # install NP1 + NP2 retention cron
-7
View File
@@ -1,7 +0,0 @@
#!/usr/bin/env bash
# Deprecated: use scripts/retention_active_days.py on NanoPi 1 instead.
# Active-day retention depends on SQLite batch history, not MotionEye file mtime.
set -euo pipefail
echo "[$(date -Iseconds)] DEPRECATED: use scripts/retention_active_days.py on NanoPi 1"
exit 0
+1 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Delete stale recount overlay videos from NanoPi 2 output storage."""
"""Delete stale recount overlay videos from local NVMe recount output storage."""
from __future__ import annotations
+32 -8
View File
@@ -10,10 +10,27 @@ import os
import re
import sqlite3
import sys
from pathlib import Path
DB_PATH = os.getenv("DB_PATH", "/opt/apc-ngoro/apc_ngoro.db")
from dotenv import load_dotenv
ROOT = Path(__file__).resolve().parents[1]
load_dotenv(ROOT / ".env")
DB_PATH = os.getenv("DB_PATH", str(ROOT / "apc_ngoro.db"))
THRESHOLD = int(os.getenv("MAIN_BATCH_MIN_COUNT", "700"))
def _increment_sub_letter(last: str) -> str:
chars = list(last.lower())
for idx in range(len(chars) - 1, -1, -1):
if chars[idx] < "z":
chars[idx] = chr(ord(chars[idx]) + 1)
return "".join(chars)
chars[idx] = "a"
return "a" * (len(chars) + 1)
def relabel_date(cur, target_date):
cur.execute(
"""
@@ -30,28 +47,35 @@ def relabel_date(cur, target_date):
main_counter = 0
prev_main = None
child_letter = 'a'
child_letter = "a"
had_leading_batch1_subs = False
planned = []
for idx, (row_id, b_num, count, status) in enumerate(rows):
b_str = str(b_num).strip()
has_letter = bool(re.search(r"[a-zA-Z]", b_str))
# Rule 1: Sub-batch does not apply to the first batch of the day
if idx == 0:
# Preserve historical first batches (<= 2026-11-18); from 2026-11-19 onward
# or if explicitly suffixed, leading sub-batches merge forward into Batch 1.
if idx == 0 and not has_letter and str(target_date or "") <= "2026-11-18":
is_child = False
else:
is_child = has_letter or (count < THRESHOLD)
is_child = has_letter or ((count or 0) < THRESHOLD)
if not is_child:
main_counter += 1
prev_main = main_counter
child_letter = 'a'
if main_counter > 1 or not had_leading_batch1_subs:
child_letter = "a"
planned.append((row_id, b_num, str(main_counter), count, status, "MAIN"))
else:
assigned_main = prev_main if prev_main is not None else 1
if prev_main is None:
assigned_main = 1
had_leading_batch1_subs = True
else:
assigned_main = prev_main
label = f"{assigned_main}{child_letter}"
child_letter = chr(ord(child_letter) + 1)
child_letter = _increment_sub_letter(child_letter)
planned.append((row_id, b_num, label, count, status, "SUB"))
# Phase 1: Temporary unique placeholder to prevent SQLite UNIQUE constraint collision
+34 -8
View File
@@ -7,10 +7,27 @@ import os
import re
import sqlite3
import sys
from pathlib import Path
DB_PATH = os.getenv("DB_PATH", "/opt/apc-ngoro/apc_ngoro.db")
from dotenv import load_dotenv
ROOT = Path(__file__).resolve().parents[1]
load_dotenv(ROOT / ".env")
DB_PATH = os.getenv("DB_PATH", str(ROOT / "apc_ngoro.db"))
THRESHOLD = int(os.getenv("MAIN_BATCH_MIN_COUNT", "700"))
def _increment_sub_letter(last: str) -> str:
chars = list(last.lower())
for idx in range(len(chars) - 1, -1, -1):
if chars[idx] < "z":
chars[idx] = chr(ord(chars[idx]) + 1)
return "".join(chars)
chars[idx] = "a"
return "a" * (len(chars) + 1)
def relabel_date(conn, target_date):
cur = conn.cursor()
cur.execute(
@@ -18,7 +35,7 @@ def relabel_date(conn, target_date):
SELECT id, batch_number, count, status
FROM batches
WHERE counting_date = ?
ORDER BY id ASC
ORDER BY start_time ASC, id ASC
""",
(target_date,),
)
@@ -29,23 +46,32 @@ def relabel_date(conn, target_date):
main_counter = 0
prev_main = None
child_letter = 'a'
child_letter = "a"
had_leading_batch1_subs = False
planned = []
for row_id, b_num, count, status in rows:
for idx, (row_id, b_num, count, status) in enumerate(rows):
b_str = str(b_num).strip()
has_letter = bool(re.search(r"[a-zA-Z]", b_str))
is_child = has_letter or (count < THRESHOLD)
if idx == 0 and not has_letter and str(target_date or "") <= "2026-11-18":
is_child = False
else:
is_child = has_letter or ((count or 0) < THRESHOLD)
if not is_child:
main_counter += 1
prev_main = main_counter
child_letter = 'a'
if main_counter > 1 or not had_leading_batch1_subs:
child_letter = "a"
planned.append((row_id, b_num, str(main_counter), count, status, "MAIN"))
else:
assigned_main = prev_main if prev_main is not None else 1
if prev_main is None:
assigned_main = 1
had_leading_batch1_subs = True
else:
assigned_main = prev_main
label = f"{assigned_main}{child_letter}"
child_letter = chr(ord(child_letter) + 1)
child_letter = _increment_sub_letter(child_letter)
planned.append((row_id, b_num, label, count, status, "CHILD"))
# To avoid unique constraint collisions during batch_number updates:
@@ -1,58 +0,0 @@
#!/usr/bin/env bash
# Install MotionEye ingest ONCE on the remote host (run via ssh -t from NanoPi 1).
# Expects REMOTE_DIR layout already extracted under /tmp/apc-me-ingest-pkg.
set -euo pipefail
REMOTE_DIR="${REMOTE_DIR:-/opt/apc-ngoro}"
PKG="${PKG_DIR:-/tmp/apc-me-ingest-pkg}"
echo "==> Installing ingest into ${REMOTE_DIR}"
sudo mkdir -p "${REMOTE_DIR}/motioneye_ingest" "${REMOTE_DIR}/systemd"
sudo cp -a "${PKG}/motioneye_ingest/." "${REMOTE_DIR}/motioneye_ingest/"
sudo cp -a "${PKG}/systemd/apc-motioneye-ingest.service" "${REMOTE_DIR}/systemd/"
sudo cp -a "${PKG}/requirements.txt" "${PKG}/config.env.example" "${REMOTE_DIR}/"
sudo chown -R "$(whoami):$(whoami)" "${REMOTE_DIR}"
cd "${REMOTE_DIR}"
# Important: do NOT pre-create an empty "venv" directory — that blocks python -m venv.
if [[ ! -x "${REMOTE_DIR}/venv/bin/python" ]]; then
echo "==> Creating Python venv + installing flask"
rm -rf "${REMOTE_DIR}/venv"
python3 -m venv "${REMOTE_DIR}/venv"
"${REMOTE_DIR}/venv/bin/pip" install -U pip
"${REMOTE_DIR}/venv/bin/pip" install flask python-dotenv
fi
if [[ ! -f .env ]]; then
cp config.env.example .env
fi
grep -q MOTIONEYE_MEDIA_DIR .env || echo 'MOTIONEYE_MEDIA_DIR=/data/media/Camera1' >> .env
grep -q MOTIONEYE_INGEST_TOKEN .env || echo 'MOTIONEYE_INGEST_TOKEN=change-me-ingest-token' >> .env
grep -q MOTIONEYE_INGEST_PORT .env || echo 'MOTIONEYE_INGEST_PORT=8090' >> .env
# Ensure public base URL for returned video links
if ! grep -q '^MOTIONEYE_INGEST_PUBLIC_BASE=' .env; then
echo 'MOTIONEYE_INGEST_PUBLIC_BASE=http://192.168.192.251:8090' >> .env
fi
if [[ ! -d "${MOTIONEYE_MEDIA_DIR:-/data/media/Camera1}" ]]; then
sudo mkdir -p /opt/apc-ngoro/motioneye_media
sudo chown -R "$(whoami):$(whoami)" /opt/apc-ngoro/motioneye_media
if ! grep -q '^MOTIONEYE_MEDIA_DIR=' .env; then
echo 'MOTIONEYE_MEDIA_DIR=/opt/apc-ngoro/motioneye_media' >> .env
fi
fi
# Prove interpreter exists before enabling the unit
test -x "${REMOTE_DIR}/venv/bin/python"
"${REMOTE_DIR}/venv/bin/python" -c "import flask, dotenv; print('deps ok')"
sudo cp systemd/apc-motioneye-ingest.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now apc-motioneye-ingest.service
sleep 1
sudo systemctl --no-pager -l status apc-motioneye-ingest.service | head -25
curl -sS http://127.0.0.1:8090/health || true
echo
echo "==> Install finished on $(hostname)"
-119
View File
@@ -1,119 +0,0 @@
#!/usr/bin/env bash
# Install recount engine on NanoPi 2 (run remotely after package extract).
set -euo pipefail
REMOTE_DIR="${REMOTE_DIR:-/opt/apc-ngoro}"
PKG="${PKG_DIR:-/tmp/apc-np2-recount-pkg}"
HOST_IP="${NANOPI2_PUBLIC_IP:-192.168.192.16}"
echo "==> Installing recount engine into ${REMOTE_DIR}"
SUDO=""
if [[ "$(id -u)" -ne 0 ]]; then
SUDO="sudo"
fi
$SUDO mkdir -p "${REMOTE_DIR}"
$SUDO cp -a "${PKG}/." "${REMOTE_DIR}/"
# Drop empty placeholder dirs that could block venv creation
if [[ -d "${REMOTE_DIR}/venv" && ! -x "${REMOTE_DIR}/venv/bin/python" ]]; then
$SUDO rm -rf "${REMOTE_DIR}/venv"
fi
$SUDO chown -R "$(whoami):$(whoami)" "${REMOTE_DIR}" 2>/dev/null || true
cd "${REMOTE_DIR}"
# Install bundled RKNN model if present in package
if [[ -d "${PKG}/bundled_models" ]]; then
$SUDO mkdir -p /opt/models
$SUDO cp -a "${PKG}/bundled_models/." /opt/models/
echo "==> Installed models to /opt/models: $(ls /opt/models)"
fi
if [[ ! -f .env ]]; then
cp config.env.example .env
fi
# Prefer MODEL_PATH already in packaged .env if the file exists on disk.
# Fall back to newest known ngoro weights — do NOT force an older model over .env.
MP="$(grep -E '^MODEL_PATH=' .env 2>/dev/null | tail -1 | cut -d= -f2- | tr -d \"\'\" || true)"
if [[ -n "${MP}" && -f "${MP}" ]]; then
echo "==> Keeping MODEL_PATH=${MP}"
elif [[ -f /opt/models/zenai_apc_ngoro_20260910.rknn ]]; then
if grep -q '^MODEL_PATH=' .env; then
sed -i 's|^MODEL_PATH=.*|MODEL_PATH=/opt/models/zenai_apc_ngoro_20260910.rknn|' .env
else
echo 'MODEL_PATH=/opt/models/zenai_apc_ngoro_20260910.rknn' >> .env
fi
elif [[ -f /opt/models/zenai_apc_ngoro_20260908.rknn ]]; then
if grep -q '^MODEL_PATH=' .env; then
sed -i 's|^MODEL_PATH=.*|MODEL_PATH=/opt/models/zenai_apc_ngoro_20260908.rknn|' .env
else
echo 'MODEL_PATH=/opt/models/zenai_apc_ngoro_20260908.rknn' >> .env
fi
fi
grep -q '^RECOUNT_PORT=' .env || echo 'RECOUNT_PORT=8765' >> .env
grep -q '^RECOUNT_PUBLIC_BASE=' .env || echo "RECOUNT_PUBLIC_BASE=http://${HOST_IP}:8765" >> .env
grep -q '^RECOUNT_OUTPUT_DIR=' .env || echo "RECOUNT_OUTPUT_DIR=${REMOTE_DIR}/recount_output" >> .env
grep -q '^RECOUNT_OVERLAY_TTL_HOURS=' .env || echo 'RECOUNT_OVERLAY_TTL_HOURS=6' >> .env
# Faster-than-realtime local processing + lighter live preview
if grep -q '^RECOUNT_FRAME_STRIDE=' .env; then
sed -i 's|^RECOUNT_FRAME_STRIDE=.*|RECOUNT_FRAME_STRIDE=1|' .env
else
echo 'RECOUNT_FRAME_STRIDE=1' >> .env
fi
if grep -q '^RECOUNT_LIVE_FRAME_MAX_WIDTH=' .env; then
sed -i 's|^RECOUNT_LIVE_FRAME_MAX_WIDTH=.*|RECOUNT_LIVE_FRAME_MAX_WIDTH=960|' .env
else
echo 'RECOUNT_LIVE_FRAME_MAX_WIDTH=960' >> .env
fi
if grep -q '^RECOUNT_LIVE_JPEG_QUALITY=' .env; then
sed -i 's|^RECOUNT_LIVE_JPEG_QUALITY=.*|RECOUNT_LIVE_JPEG_QUALITY=60|' .env
else
echo 'RECOUNT_LIVE_JPEG_QUALITY=60' >> .env
fi
if grep -q '^RECOUNT_PLAYBACK_SPEED=' .env; then
sed -i 's|^RECOUNT_PLAYBACK_SPEED=.*|RECOUNT_PLAYBACK_SPEED=0|' .env
else
echo 'RECOUNT_PLAYBACK_SPEED=0' >> .env
fi
# Keep RECOUNT_MIN_HITS from packaged NP1 .env (do not force an older value)
grep -q '^RECOUNT_MIN_HITS=' .env || echo 'RECOUNT_MIN_HITS=1' >> .env
if grep -q '^RECOUNT_TRACK_BUFFER=' .env; then
sed -i 's|^RECOUNT_TRACK_BUFFER=.*|RECOUNT_TRACK_BUFFER=30|' .env
else
echo 'RECOUNT_TRACK_BUFFER=30' >> .env
fi
grep -q '^RECOUNT_START_COUNT=' .env || echo 'RECOUNT_START_COUNT=1' >> .env
if [[ ! -x "${REMOTE_DIR}/venv/bin/python" ]]; then
echo "==> Creating Python venv"
rm -rf "${REMOTE_DIR}/venv"
python3 -m venv "${REMOTE_DIR}/venv"
"${REMOTE_DIR}/venv/bin/pip" install -U pip
# Core runtime first (always needed)
"${REMOTE_DIR}/venv/bin/pip" install flask python-dotenv opencv-python-headless "numpy<2" requests
# RKNN optional at pip time — may already be present system-wide / need wheel copy
"${REMOTE_DIR}/venv/bin/pip" install rknn-toolkit-lite2 || \
echo "WARN: rknn-toolkit-lite2 pip install failed — ensure RKNN is available on this device"
fi
mkdir -p recount_output
mkdir -p scripts
if [[ -f "${PKG}/scripts/recount_overlay_cleanup.py" ]]; then
cp -a "${PKG}/scripts/recount_overlay_cleanup.py" "${REMOTE_DIR}/scripts/"
chmod +x "${REMOTE_DIR}/scripts/recount_overlay_cleanup.py"
fi
test -x "${REMOTE_DIR}/venv/bin/python"
"${REMOTE_DIR}/venv/bin/python" -c "import flask, dotenv, cv2, numpy; print('deps ok')"
$SUDO cp systemd/apc-ngoro-recount.service /etc/systemd/system/
$SUDO systemctl daemon-reload
$SUDO systemctl enable apc-ngoro-recount.service
echo '0 * * * * root cd /opt/apc-ngoro && /opt/apc-ngoro/venv/bin/python scripts/recount_overlay_cleanup.py >> /var/log/apc-recount-cleanup.log 2>&1' | $SUDO tee /etc/cron.d/apc-recount-cleanup >/dev/null
$SUDO chmod 644 /etc/cron.d/apc-recount-cleanup
# Always restart so new code is loaded (enable --now does not restart an active unit)
$SUDO systemctl restart apc-ngoro-recount.service
sleep 2
$SUDO systemctl --no-pager -l status apc-ngoro-recount.service | head -30
curl -sS http://127.0.0.1:8765/health || true
echo
echo "==> Install finished on $(hostname)"
+32 -29
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Keep MotionEye batch videos for the latest active counting dates only."""
"""Keep local batch videos for the latest active counting dates only."""
from __future__ import annotations
@@ -15,13 +15,12 @@ ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from motioneye_client import _ingest_url, delete_batch_video
from retention_utils import active_counting_dates, batch_id_to_counting_date
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Delete MotionEye batch videos outside the latest active counting days."
description="Delete local batch videos outside the latest active counting days."
)
parser.add_argument("--dry-run", action="store_true", help="show deletions without removing files")
return parser.parse_args()
@@ -32,13 +31,18 @@ def main() -> int:
args = parse_args()
db_path = Path(os.getenv("DB_PATH", str(ROOT / "apc_ngoro.db")))
keep_days = max(1, int(os.getenv("ACTIVE_RETENTION_DAYS", "3")))
video_dir = Path(os.getenv("BATCH_VIDEO_DIR", str(ROOT / "batch_videos")))
keep_days = max(1, int(os.getenv("ACTIVE_RETENTION_DAYS", "7")))
if not db_path.is_file():
print(f"DB not found: {db_path}", file=sys.stderr)
return 1
conn = sqlite3.connect(str(db_path))
if not video_dir.is_dir():
print(f"Batch video dir missing: {video_dir}")
return 0
conn = sqlite3.connect(str(db_path), timeout=10.0)
keep_dates = set(active_counting_dates(conn, limit=keep_days, table="batches"))
conn.close()
@@ -46,44 +50,43 @@ def main() -> int:
print("No active counting dates found; nothing to delete.")
return 0
import requests
headers = {"X-Ingest-Token": os.getenv("MOTIONEYE_INGEST_TOKEN", "change-me-ingest-token")}
list_url = f"{_ingest_url()}/list"
resp = requests.get(list_url, headers=headers, timeout=30.0)
resp.raise_for_status()
payload = resp.json()
if not payload.get("success"):
raise RuntimeError(payload.get("error") or "list failed")
deleted = 0
skipped = 0
freed_bytes = 0
errors = 0
print(f"Keep active dates: {sorted(keep_dates, reverse=True)}")
for item in payload.get("files", []):
batch_id = (item.get("batch_id") or "").strip()
print(f"Keep active dates ({keep_days}): {sorted(keep_dates, reverse=True)}")
for path in sorted(video_dir.glob("*.mp4")):
if path.name.startswith("."):
continue
batch_id = path.stem.replace("batch_", "", 1).strip()
counting_date = batch_id_to_counting_date(batch_id)
if not counting_date or counting_date in keep_dates:
if not counting_date:
continue
if counting_date in keep_dates:
skipped += 1
continue
try:
size = path.lstat().st_size if path.is_symlink() else path.stat().st_size
except FileNotFoundError:
continue
if args.dry_run:
print(f"DRY-RUN delete {batch_id} ({item.get('filename')})")
print(f"DRY-RUN delete {path.name} ({size} bytes)")
deleted += 1
freed_bytes += size
continue
try:
result = delete_batch_video(batch_id)
if result.get("deleted"):
print(f"Deleted {batch_id}")
deleted += 1
else:
print(f"Already absent {batch_id}")
path.unlink()
print(f"Deleted {path.name} ({size} bytes)")
deleted += 1
freed_bytes += size
except Exception as exc:
errors += 1
print(f"ERROR deleting {batch_id}: {exc}", file=sys.stderr)
print(f"ERROR deleting {path.name}: {exc}", file=sys.stderr)
print(
f"Done: candidate_deleted={deleted} skipped={skipped} errors={errors} "
f"dry_run={'yes' if args.dry_run else 'no'}"
f"Done: deleted={deleted} skipped={skipped} freed_bytes={freed_bytes} "
f"errors={errors} dry_run={'yes' if args.dry_run else 'no'}"
)
return 0 if errors == 0 else 2
-99
View File
@@ -1,99 +0,0 @@
# Sync production files only to NanoPi APC Ngoro
# Usage: .\scripts\sync-to-nanopi.ps1 [-Restart]
param(
[string]$NanoPiHost = "192.168.192.208",
[string]$User = "agent",
[string]$RemotePath = "/home/agent/apc-ngoro-staging",
[string]$InstallPath = "/opt/apc-ngoro",
[string]$KeyPath = "$env:USERPROFILE\.ssh\nanopi_agent",
[switch]$Restart
)
$ErrorActionPreference = "Stop"
$RepoRoot = Split-Path $PSScriptRoot -Parent
if (-not (Test-Path "$RepoRoot\counter_dashboard.py")) {
throw "Repo root not found (expected counter_dashboard.py in $RepoRoot)"
}
$sshArgs = @("-o", "BatchMode=yes", "-o", "ConnectTimeout=15")
if (Test-Path $KeyPath) {
$sshArgs = @("-i", $KeyPath) + $sshArgs
}
$remote = "${User}@${NanoPiHost}:${RemotePath}"
$scpBase = @("scp") + $sshArgs
# Whitelist: only files needed on device
$files = @(
"counter_live_rknn_bytetrack.py",
"batch_store.py",
"batch_video_recorder.py",
"motioneye_client.py",
"counter_dashboard.py",
"config.env.example",
"requirements.txt",
"setup-venv.sh",
"install-services.sh",
"uninstall-services.sh"
)
$dirs = @(
"systemd",
"static",
"config",
"scripts",
"motioneye_ingest",
"recount_engine",
"docs"
)
Write-Host "==> Sync to $remote (whitelist only)" -ForegroundColor Cyan
ssh @sshArgs "${User}@${NanoPiHost}" "mkdir -p ${RemotePath}/templates ${RemotePath}/systemd ${RemotePath}/static ${RemotePath}/config ${RemotePath}/scripts ${RemotePath}/motioneye_ingest ${RemotePath}/recount_engine ${RemotePath}/docs"
if ($LASTEXITCODE -ne 0) { throw "failed to create remote staging dirs" }
foreach ($f in $files) {
$src = Join-Path $RepoRoot $f
if (-not (Test-Path $src)) { throw "Missing: $f" }
Write-Host " + $f"
& scp @sshArgs $src "${remote}/"
if ($LASTEXITCODE -ne 0) { throw "scp failed for $f" }
}
# templates: production dashboards only (skip Figma reference export)
$templates = @(
"dashboard_operational.html",
"dashboard_recounting.html"
)
ssh @sshArgs "${User}@${NanoPiHost}" "mkdir -p ${RemotePath}/templates"
foreach ($t in $templates) {
$tplSrc = Join-Path $RepoRoot "templates\$t"
if (-not (Test-Path $tplSrc)) { throw "Missing templates/$t" }
Write-Host " + templates/$t"
& scp @sshArgs $tplSrc "${remote}/templates/"
if ($LASTEXITCODE -ne 0) { throw "scp failed for $t" }
}
foreach ($d in $dirs) {
$src = Join-Path $RepoRoot $d
if (-not (Test-Path $src)) { throw "Missing: $d" }
Write-Host " + $d/"
ssh @sshArgs "${User}@${NanoPiHost}" "mkdir -p ${RemotePath}/$d"
& scp @sshArgs -r $src "${remote}/"
if ($LASTEXITCODE -ne 0) { throw "scp failed for $d" }
}
Write-Host "==> Sync complete (staging: $RemotePath)" -ForegroundColor Green
Write-Host ""
Write-Host "On NanoPi as root, deploy to ${InstallPath}:" -ForegroundColor Yellow
Write-Host " sudo bash $RemotePath/scripts/deploy-to-opt.sh" -ForegroundColor White
Write-Host " cd $InstallPath && sudo bash setup-venv.sh && sudo bash install-services.sh" -ForegroundColor White
Write-Host ""
if ($Restart) {
Write-Host "==> Restarting services (needs passwordless sudo)..." -ForegroundColor Cyan
ssh @sshArgs "${User}@${NanoPiHost}" "sudo systemctl restart apc-ngoro-counter apc-ngoro-dashboard 2>/dev/null && systemctl is-active apc-ngoro-counter apc-ngoro-dashboard || echo 'Run deploy + install-services on device first, or restart manually as root'"
}
Write-Host "Dashboard: http://${NanoPiHost}:5000" -ForegroundColor Green
+29 -8
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env bash
# Setup Python venv for RK3588 NanoPi (ZenAI APC Ngoro)
# Setup Python venv for single-machine x86_64 Intel OpenVINO deployment (ZenAI APC Ngoro)
set -euo pipefail
INSTALL_DIR="${INSTALL_DIR:-/opt/apc-ngoro}"
INSTALL_DIR="${INSTALL_DIR:-/home/admin123/ngoro_project}"
cd "$INSTALL_DIR"
if [ ! -f requirements.txt ]; then
@@ -10,12 +10,33 @@ if [ ! -f requirements.txt ]; then
exit 1
fi
echo "Creating venv with system-site-packages (required for rknn-toolkit-lite2)..."
python3 -m venv --system-site-packages venv
echo "Checking system prerequisites (ffmpeg, Intel OpenCL ICD)..."
for bin in ffmpeg ffprobe; do
if ! command -v "$bin" >/dev/null 2>&1; then
echo "WARNING: $bin not found. Install with: sudo apt-get update && sudo apt-get install -y ffmpeg intel-opencl-icd ocl-icd-libopencl1"
fi
done
echo "Installing Python dependencies..."
PYTHONNOUSERSITE=1 venv/bin/pip install --upgrade pip
PYTHONNOUSERSITE=1 venv/bin/pip install -r requirements.txt
UV_BIN="$(command -v uv || true)"
if [ -z "$UV_BIN" ] && [ -x "$HOME/.local/bin/uv" ]; then
UV_BIN="$HOME/.local/bin/uv"
fi
if [ -n "$UV_BIN" ]; then
echo "Creating clean Python virtual environment via uv in $INSTALL_DIR/venv..."
"$UV_BIN" venv --seed --clear "$INSTALL_DIR/venv"
echo "Installing Python dependencies via uv..."
"$UV_BIN" pip install --python "$INSTALL_DIR/venv/bin/python" -r requirements.txt
else
echo "Creating clean Python virtual environment in $INSTALL_DIR/venv..."
python3 -m venv venv
echo "Installing Python dependencies..."
PYTHONNOUSERSITE=1 venv/bin/pip install --upgrade pip
PYTHONNOUSERSITE=1 venv/bin/pip install -r requirements.txt
fi
echo "Creating local video directories..."
mkdir -p "$INSTALL_DIR/batch_videos" "$INSTALL_DIR/recount_output"
echo "Done. Activate with: source $INSTALL_DIR/venv/bin/activate"
echo "Remember to copy config.env.example to .env and edit device-specific values."
echo "Remember to ensure user is in render/video groups for GPU/NPU access: sudo usermod -aG render,video \$USER"
-16
View File
@@ -1,16 +0,0 @@
[Unit]
Description=ZenAI APC MotionEye batch video ingest (HTTP :8090)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/opt/apc-ngoro
EnvironmentFile=-/opt/apc-ngoro/.env
Environment=MOTIONEYE_INGEST_PUBLIC_BASE=http://192.168.192.251:8090
ExecStart=/opt/apc-ngoro/venv/bin/python /opt/apc-ngoro/motioneye_ingest/app.py
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target
+39 -36
View File
@@ -1,36 +1,39 @@
[Unit]
Description=ZenAI APC Ngoro Edge Counter (RTSP + RKNN + ByteTrack)
Documentation=file:///opt/apc-ngoro/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/opt/apc-ngoro
EnvironmentFile=/opt/apc-ngoro/.env
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONNOUSERSITE=1
Environment=YOLO_CONFIG_DIR=/opt/apc-ngoro/.ultralytics
Environment=TORCH_HOME=/opt/apc-ngoro/.torch
Environment=PATH=/opt/apc-ngoro/venv/bin:/usr/local/bin:/usr/bin:/bin
ExecStart=/opt/apc-ngoro/venv/bin/python -u counter_live_rknn_bytetrack.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
[Unit]
Description=ZenAI APC Ngoro Real-Time Counter (RTSP + OpenVINO + ByteTrack)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=admin123
Group=admin123
SupplementalGroups=render video
WorkingDirectory=/home/admin123/ngoro_project
EnvironmentFile=/home/admin123/ngoro_project/.env
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONNOUSERSITE=1
Environment=YOLO_CONFIG_DIR=/home/admin123/ngoro_project/.ultralytics
Environment=TORCH_HOME=/home/admin123/ngoro_project/.torch
Environment=PATH=/home/admin123/ngoro_project/venv/bin:/usr/local/bin:/usr/bin:/bin
# Resource isolation: dedicated P-cores (0-7) + high priority
AllowedCPUs=0-7
Nice=-10
ExecStart=/home/admin123/ngoro_project/venv/bin/python -u /home/admin123/ngoro_project/counter_live_rknn_bytetrack.py
TimeoutStopSec=30
KillSignal=SIGTERM
Restart=on-failure
RestartSec=10
StartLimitIntervalSec=120
StartLimitBurst=5
NoNewPrivileges=true
ProtectHome=false
PrivateTmp=false
[Install]
WantedBy=multi-user.target
+38 -33
View File
@@ -1,33 +1,38 @@
[Unit]
Description=ZenAI APC Ngoro Operational Dashboard (Flask, port 5000)
Documentation=file:///opt/apc-ngoro/README.md
After=network-online.target apc-ngoro-counter.service
Wants=network-online.target
[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/opt/apc-ngoro
EnvironmentFile=/opt/apc-ngoro/.env
Environment=PATH=/opt/apc-ngoro/venv/bin:/usr/local/bin:/usr/bin:/bin
Environment=FLASK_DEBUG=false
ExecStart=/opt/apc-ngoro/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
[Unit]
Description=ZenAI APC Ngoro Operational & Recount Dashboard (Flask, port 5000)
After=network-online.target apc-ngoro-counter.service apc-ngoro-recount.service
Wants=network-online.target apc-ngoro-recount.service
[Service]
Type=simple
User=admin123
Group=admin123
SupplementalGroups=render video
WorkingDirectory=/home/admin123/ngoro_project
EnvironmentFile=/home/admin123/ngoro_project/.env
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONNOUSERSITE=1
Environment=PATH=/home/admin123/ngoro_project/venv/bin:/usr/local/bin:/usr/bin:/bin
Environment=FLASK_DEBUG=false
# Resource isolation: E-cores / LP E-cores (14-17) + normal priority
AllowedCPUs=14-17
Nice=0
ExecStart=/home/admin123/ngoro_project/venv/bin/python /home/admin123/ngoro_project/counter_dashboard.py
TimeoutStopSec=15
KillSignal=SIGTERM
Restart=on-failure
RestartSec=5
StartLimitIntervalSec=60
StartLimitBurst=3
NoNewPrivileges=true
ProtectHome=false
PrivateTmp=false
[Install]
WantedBy=multi-user.target
+24 -5
View File
@@ -1,16 +1,35 @@
[Unit]
Description=ZenAI APC Ngoro Recount Engine (NanoPi 2)
Description=ZenAI APC Ngoro Local Recount Engine (OpenVINO + ByteTrack, port 8765)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/opt/apc-ngoro
EnvironmentFile=-/opt/apc-ngoro/.env
Environment=RECOUNT_PUBLIC_BASE=http://192.168.192.16:8765
ExecStart=/opt/apc-ngoro/venv/bin/python /opt/apc-ngoro/recount_engine/app.py
User=admin123
Group=admin123
SupplementalGroups=render video
WorkingDirectory=/home/admin123/ngoro_project
EnvironmentFile=/home/admin123/ngoro_project/.env
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONNOUSERSITE=1
Environment=PATH=/home/admin123/ngoro_project/venv/bin:/usr/local/bin:/usr/bin:/bin
# Resource isolation: dedicated E-cores (8-15) + low batch priority
AllowedCPUs=8-15
Nice=10
ExecStart=/home/admin123/ngoro_project/venv/bin/python -u /home/admin123/ngoro_project/recount_engine/app.py
TimeoutStopSec=30
KillSignal=SIGTERM
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
ProtectHome=false
PrivateTmp=false
[Install]
WantedBy=multi-user.target
+34
View File
@@ -0,0 +1,34 @@
[Unit]
Description=ZenAI APC Ngoro Unified Service (Counter + Recount + Dashboard)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=admin123
Group=admin123
SupplementalGroups=render video
WorkingDirectory=/home/admin123/ngoro_project
EnvironmentFile=/home/admin123/ngoro_project/.env
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONNOUSERSITE=1
Environment=PATH=/home/admin123/ngoro_project/venv/bin:/usr/local/bin:/usr/bin:/bin
ExecStart=/home/admin123/ngoro_project/venv/bin/python -u /home/admin123/ngoro_project/scripts/apc_supervisor.py
TimeoutStopSec=30
KillSignal=SIGTERM
KillMode=control-group
Restart=on-failure
RestartSec=10
StartLimitIntervalSec=120
StartLimitBurst=5
NoNewPrivileges=false
ProtectHome=false
PrivateTmp=false
[Install]
WantedBy=multi-user.target
+322 -5
View File
@@ -371,6 +371,72 @@
text-transform: uppercase;
}
.summary-item-val { font-family: var(--mono); font-size: var(--fs-kpi-md); font-weight: 700; }
.cutoff-head-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
.cutoff-val-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.cutoff-edit-btn {
padding: 4px 12px; border-radius: 6px;
border: 1px solid var(--border-accent);
background: var(--blue-bg); color: var(--blue-btn);
font-size: 12px; font-weight: 600; cursor: pointer;
font-family: inherit; transition: background 0.15s ease;
}
.cutoff-edit-btn:hover { background: rgba(22,130,178,0.25); }
.cutoff-override-badge {
display: inline-flex; align-items: center;
padding: 2px 8px; border-radius: 999px;
font-size: 10px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase;
background: var(--yellow-bg); color: var(--yellow-line); border: 1px solid var(--yellow);
}
html[data-theme="light"] .cutoff-override-badge { color: #854d0e; }
.cutoff-sub-note { font-size: 11px; color: var(--text-muted); }
.cutoff-modal-card { max-width: 520px; }
.cutoff-form { display: flex; flex-direction: column; gap: 16px; }
.cutoff-form-group { display: flex; flex-direction: column; gap: 8px; }
.cutoff-label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: var(--text-muted); }
.cutoff-time-input, .cutoff-date-input {
padding: 10px 12px; border-radius: 8px; border: 1px solid var(--border-divider);
background: var(--bg-panel); color: var(--text); font-family: var(--mono); font-size: 15px; font-weight: 600;
width: 100%;
}
.cutoff-preset-row { display: flex; flex-wrap: wrap; gap: 8px; }
.cutoff-preset-btn {
padding: 6px 12px; border-radius: 8px; border: 1px solid var(--border-divider);
background: var(--bg-panel); color: var(--text); font-family: var(--mono); font-size: 12px; font-weight: 600;
cursor: pointer;
}
.cutoff-preset-btn.active, .cutoff-preset-btn:hover {
background: var(--blue-bg); border-color: var(--blue); color: var(--blue-btn);
}
.cutoff-radio-group { display: flex; flex-direction: column; gap: 8px; }
.cutoff-radio-card {
display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px;
border-radius: 8px; border: 1px solid var(--border-divider); background: var(--bg-panel);
cursor: pointer; font-size: 13px;
}
.cutoff-radio-card input { margin-top: 3px; accent-color: var(--blue); }
.cutoff-radio-desc { font-size: 11px; color: var(--text-muted); margin-top: 2px; }
.cutoff-date-box {
display: flex; flex-direction: column; gap: 8px;
padding: 10px 12px; border-radius: 8px; background: var(--bg-panel); border: 1px solid var(--border-divider);
}
.cutoff-date-quick { display: flex; gap: 8px; flex-wrap: wrap; }
.cutoff-checkbox-row {
display: flex; align-items: flex-start; gap: 10px; font-size: 12px; color: var(--text); cursor: pointer;
}
.cutoff-checkbox-row input { margin-top: 2px; accent-color: var(--blue); }
.cutoff-modal-msg {
font-size: 12px; padding: 8px 12px; border-radius: 8px; display: none;
}
.cutoff-modal-msg.ok { display: block; background: var(--green-bg); color: var(--green); border: 1px solid rgba(16,185,129,0.35); }
.cutoff-modal-msg.err { display: block; background: rgba(239,68,68,0.14); color: #f87171; border: 1px solid rgba(239,68,68,0.35); }
.cutoff-modal-actions {
display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap; margin-top: 4px;
}
.cutoff-btn-danger {
background: var(--yellow-bg); border-color: var(--yellow); color: var(--yellow-line);
}
html[data-theme="light"] .cutoff-btn-danger { color: #854d0e; }
/* ── Recent activity ── */
.recent-wrap {
@@ -931,8 +997,17 @@
<div class="summary-item-val" id="grand-batches">--</div>
</div>
<div class="summary-item">
<div class="summary-item-label">waktu cut-off</div>
<div class="summary-item-val" id="cutoff-display">{{ cutoff_time | replace(':', '.') }}</div>
<div class="cutoff-head-row">
<div class="summary-item-label">waktu cut-off</div>
<button class="cutoff-edit-btn" type="button" onclick="openCutoffModal()">Ubah</button>
</div>
<div class="cutoff-val-row">
<div class="summary-item-val" id="cutoff-display">{{ cutoff_time | replace(':', '.') }}</div>
<span class="cutoff-override-badge" id="cutoff-override-badge"{% if not cutoff_is_override %} style="display:none;"{% endif %}>OVERRIDE</span>
</div>
<div class="cutoff-sub-note" id="cutoff-default-note"{% if not cutoff_is_override %} style="display:none;"{% endif %}>
Default: {{ (default_cutoff_time or cutoff_time) | replace(':', '.') }}
</div>
</div>
</div>
</div>
@@ -1040,6 +1115,75 @@
</div>
</div>
<!-- Cut-off Settings Modal -->
<div class="modal-overlay hidden" id="cutoff-modal">
<div class="modal-content cutoff-modal-card">
<div class="modal-header">
<div>
<h2>Pengaturan Waktu Cut-off</h2>
<div class="modal-subtitle">Sesuaikan batas akhir pergantian hari hitung (default 20:00).</div>
</div>
<button class="close-btn" type="button" onclick="closeCutoffModal()">&times;</button>
</div>
<div class="cutoff-form">
<div class="cutoff-form-group">
<label class="cutoff-label" for="cutoff-time-input">Waktu Cut-off (HH:MM)</label>
<input type="time" id="cutoff-time-input" class="cutoff-time-input" value="{{ cutoff_time }}" required>
<div class="cutoff-preset-row">
<button type="button" class="cutoff-preset-btn" onclick="setCutoffPreset('20:00')">20:00</button>
<button type="button" class="cutoff-preset-btn" onclick="setCutoffPreset('21:00')">21:00</button>
<button type="button" class="cutoff-preset-btn" onclick="setCutoffPreset('22:00')">22:00</button>
<button type="button" class="cutoff-preset-btn" onclick="setCutoffPreset('23:00')">23:00</button>
<button type="button" class="cutoff-preset-btn" onclick="setCutoffPreset('23:59')">23:59</button>
<button type="button" class="cutoff-preset-btn" onclick="setCutoffPreset('01:00')">01:00</button>
</div>
</div>
<div class="cutoff-form-group">
<span class="cutoff-label">Cakupan Perubahan</span>
<div class="cutoff-radio-group">
<label class="cutoff-radio-card">
<input type="radio" name="cutoff-scope" value="date" checked onchange="onCutoffScopeChange()">
<div>
<div><strong>Sementara (Hanya Tanggal Tertentu)</strong></div>
<div class="cutoff-radio-desc">Hari berikutnya otomatis kembali ke default (<span id="cutoff-scope-default-lbl">20:00</span>).</div>
</div>
</label>
<label class="cutoff-radio-card">
<input type="radio" name="cutoff-scope" value="default" onchange="onCutoffScopeChange()">
<div>
<div><strong>Default Permanen</strong></div>
<div class="cutoff-radio-desc">Mengubah jadwal cut-off standar untuk semua hari selanjutnya.</div>
</div>
</label>
</div>
</div>
<div class="cutoff-date-box" id="cutoff-date-box">
<label class="cutoff-label" for="cutoff-target-date">Tanggal Target</label>
<input type="date" id="cutoff-target-date" class="cutoff-date-input" onchange="syncCutoffDateSelection()">
<div class="cutoff-date-quick">
<button type="button" class="cutoff-preset-btn" onclick="selectCutoffQuickDate('today')">Hari Ini</button>
<button type="button" class="cutoff-preset-btn" onclick="selectCutoffQuickDate('yesterday')">Kemarin</button>
</div>
</div>
<label class="cutoff-checkbox-row">
<input type="checkbox" id="cutoff-recalculate" checked>
<span>Pindahkan &amp; urutkan ulang batch yang melewati cut-off pada tanggal ini</span>
</label>
<div class="cutoff-modal-msg" id="cutoff-modal-msg"></div>
<div class="cutoff-modal-actions">
<button type="button" class="tbtn" onclick="closeCutoffModal()">Batal</button>
<button type="button" class="tbtn cutoff-btn-danger" id="btn-cutoff-reset" onclick="saveCutoffSettings(true)" style="display:none;">Reset Override</button>
<button type="button" class="tbtn tbtn-primary" id="btn-cutoff-save" onclick="saveCutoffSettings(false)">Simpan Perubahan</button>
</div>
</div>
</div>
</div>
<script>
const SITE_NAME = {{ site_name | tojson }};
const LOGO_FALLBACK = {{ url_for('static', filename='img/logo-zenai-white.svg') | tojson }};
@@ -1154,13 +1298,21 @@ function startCurrentBatchStream() {
}
}
function formatBatchPadded(bn) {
if (!bn && bn !== 0) return '----';
const s = String(bn);
const m = s.match(/^(\d+)([a-zA-Z]*)$/);
return m ? (m[1].padStart(4, '0') + m[2]) : s.padStart(4, '0');
}
function renderCurrentBatch(data) {
const count = data.count || 0;
document.getElementById('live-count').textContent = count.toLocaleString('id-ID');
const batchNum = data.batch_number;
const batchPadded = formatBatchPadded(batchNum);
document.getElementById('live-batch-label').textContent =
batchNum ? `Batch #${String(batchNum).padStart(4, '0')}` : 'Batch #----';
batchNum ? `Batch #${batchPadded}` : 'Batch #----';
const status = data.status || 'IDLE';
const statusEl = document.getElementById('batch-status');
@@ -1169,7 +1321,7 @@ function renderCurrentBatch(data) {
const hint = document.getElementById('batch-status-hint');
hint.textContent = status === 'RUNNING'
? `Batch #${String(batchNum).padStart(4,'0')} sedang running`
? `Batch #${batchPadded} sedang running`
: 'Tidak ada batch aktif';
document.getElementById('svc-counter').textContent = status === 'RUNNING' ? 'Running' : 'Idle';
@@ -1239,6 +1391,19 @@ async function loadSummary() {
document.getElementById('cutoff-display').textContent =
data.cutoff_time.replace(':', '.');
}
const badge = document.getElementById('cutoff-override-badge');
const note = document.getElementById('cutoff-default-note');
if (badge) {
badge.style.display = data.cutoff_is_override ? 'inline-flex' : 'none';
}
if (note) {
if (data.cutoff_is_override && data.default_cutoff_time) {
note.textContent = `Default: ${data.default_cutoff_time.replace(':', '.')}`;
note.style.display = 'block';
} else {
note.style.display = 'none';
}
}
} catch (err) {
console.error('Gagal memuat ringkasan:', err);
}
@@ -1341,7 +1506,7 @@ async function loadRecentBatches() {
container.innerHTML = batches.map(b => `
<div class="recent-card">
<div class="recent-head">
<span class="recent-batch">B-${String(b.batch_number).padStart(4,'0')}${b.is_child ? ' <span class="status-badge warn" style="font-size:9px;padding:1px 5px;margin-left:4px;">SUB</span>' : ''}</span>
<span class="recent-batch">B-${formatBatchPadded(b.batch_number)}${b.is_child ? ' <span class="status-badge warn" style="font-size:9px;padding:1px 5px;margin-left:4px;">SUB</span>' : ''}</span>
<span class="recent-date">${formatDateID(b.date)}</span>
</div>
<div class="recent-count">${b.count.toLocaleString('id-ID')}</div>
@@ -1663,6 +1828,158 @@ function onVideoError() {
document.getElementById('detail-modal').addEventListener('click', e => {
if (e.target.id === 'detail-modal') closeModal();
});
let cutoffTodayDate = '';
let cutoffYesterdayDate = '';
let cutoffOverridesMap = {};
let cutoffDefaultTime = '20:00';
function setCutoffModalMsg(msg, kind = '') {
const el = document.getElementById('cutoff-modal-msg');
if (!el) return;
el.className = 'cutoff-modal-msg' + (kind ? ` ${kind}` : '');
el.textContent = msg || '';
}
function setCutoffPreset(hhmm) {
const inp = document.getElementById('cutoff-time-input');
if (inp) inp.value = hhmm;
document.querySelectorAll('.cutoff-preset-btn[onclick^="setCutoffPreset"]').forEach(btn => {
btn.classList.toggle('active', btn.textContent.trim() === hhmm);
});
}
function selectCutoffQuickDate(which) {
const dateInp = document.getElementById('cutoff-target-date');
if (!dateInp) return;
if (which === 'yesterday' && cutoffYesterdayDate) {
dateInp.value = cutoffYesterdayDate;
} else if (cutoffTodayDate) {
dateInp.value = cutoffTodayDate;
}
syncCutoffDateSelection();
}
function syncCutoffDateSelection() {
const dateInp = document.getElementById('cutoff-target-date');
const d = dateInp ? dateInp.value : '';
const hasOverride = !!(d && cutoffOverridesMap[d]);
const scopeEl = document.querySelector('input[name="cutoff-scope"]:checked');
const isDateScope = !scopeEl || scopeEl.value === 'date';
const resetBtn = document.getElementById('btn-cutoff-reset');
if (resetBtn) {
resetBtn.style.display = (isDateScope && hasOverride) ? 'inline-flex' : 'none';
}
if (isDateScope && d) {
const val = cutoffOverridesMap[d] || cutoffDefaultTime;
setCutoffPreset(val);
}
}
function onCutoffScopeChange() {
const scopeEl = document.querySelector('input[name="cutoff-scope"]:checked');
const scope = scopeEl ? scopeEl.value : 'date';
const dateBox = document.getElementById('cutoff-date-box');
if (dateBox) dateBox.style.display = scope === 'date' ? 'flex' : 'none';
if (scope === 'default') {
const resetBtn = document.getElementById('btn-cutoff-reset');
if (resetBtn) resetBtn.style.display = 'none';
setCutoffPreset(cutoffDefaultTime);
} else {
syncCutoffDateSelection();
}
}
async function openCutoffModal() {
setCutoffModalMsg('');
document.getElementById('cutoff-modal').classList.remove('hidden');
try {
const res = await fetch('/api/cutoff-settings');
const data = await res.json();
if (!res.ok || !data.success) {
setCutoffModalMsg(data.error || 'Gagal memuat pengaturan cut-off', 'err');
return;
}
cutoffTodayDate = data.today_date || '';
cutoffYesterdayDate = data.yesterday_date || '';
cutoffOverridesMap = data.overrides || {};
cutoffDefaultTime = data.default_cutoff_time || '20:00';
const defLbl = document.getElementById('cutoff-scope-default-lbl');
if (defLbl) defLbl.textContent = cutoffDefaultTime;
const dateRadio = document.querySelector('input[name="cutoff-scope"][value="date"]');
if (dateRadio) dateRadio.checked = true;
const dateInp = document.getElementById('cutoff-target-date');
if (dateInp) dateInp.value = cutoffTodayDate;
onCutoffScopeChange();
} catch (err) {
setCutoffModalMsg('Gagal memuat pengaturan cut-off: ' + err.message, 'err');
}
}
function closeCutoffModal() {
document.getElementById('cutoff-modal').classList.add('hidden');
}
async function saveCutoffSettings(isReset = false) {
const scopeEl = document.querySelector('input[name="cutoff-scope"]:checked');
const scope = isReset ? 'date' : (scopeEl ? scopeEl.value : 'date');
const cutoffTime = document.getElementById('cutoff-time-input').value;
const targetDate = document.getElementById('cutoff-target-date').value;
const recalculateBatches = document.getElementById('cutoff-recalculate').checked;
if (!isReset && !cutoffTime) {
setCutoffModalMsg('Masukkan waktu cut-off (HH:MM).', 'err');
return;
}
const saveBtn = document.getElementById('btn-cutoff-save');
const resetBtn = document.getElementById('btn-cutoff-reset');
if (saveBtn) saveBtn.disabled = true;
if (resetBtn) resetBtn.disabled = true;
setCutoffModalMsg('Menyimpan pengaturan cut-off...');
try {
const res = await fetch('/api/cutoff-settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
cutoff_time: cutoffTime,
scope,
target_date: targetDate,
recalculate_batches: recalculateBatches,
reset: isReset,
}),
});
const data = await res.json();
if (!res.ok || !data.success) {
setCutoffModalMsg(data.error || 'Gagal menyimpan pengaturan cut-off', 'err');
return;
}
const moved = data.reconcile ? (data.reconcile.moved_count || 0) : 0;
const msg = isReset
? `Override dihapus (${moved} batch disesuaikan ulang).`
: `Cut-off tersimpan: ${data.effective_cutoff_time}${moved > 0 ? ` · ${moved} batch dipindahkan & diurutkan ulang` : ''}.`;
setCutoffModalMsg(msg, 'ok');
await Promise.all([
loadSummary(),
loadChartData(chartDays),
loadDailyTable(),
loadRecentBatches(),
]);
setTimeout(closeCutoffModal, 700);
} catch (err) {
setCutoffModalMsg('Gagal menyimpan: ' + err.message, 'err');
} finally {
if (saveBtn) saveBtn.disabled = false;
if (resetBtn) resetBtn.disabled = false;
}
}
document.getElementById('cutoff-modal').addEventListener('click', e => {
if (e.target.id === 'cutoff-modal') closeCutoffModal();
});
</script>
</body>
</html>
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -2,10 +2,12 @@
# Uninstall systemd services for ZenAI APC Ngoro
set -euo pipefail
sudo systemctl stop apc-ngoro-counter apc-ngoro-dashboard 2>/dev/null || true
sudo systemctl disable apc-ngoro-counter apc-ngoro-dashboard 2>/dev/null || true
sudo systemctl stop apc-ngoro-service apc-ngoro-dashboard apc-ngoro-recount apc-ngoro-counter 2>/dev/null || true
sudo systemctl disable apc-ngoro-service apc-ngoro-dashboard apc-ngoro-recount apc-ngoro-counter 2>/dev/null || true
sudo rm -f /etc/systemd/system/apc-ngoro-service.service
sudo rm -f /etc/systemd/system/apc-ngoro-counter.service
sudo rm -f /etc/systemd/system/apc-ngoro-recount.service
sudo rm -f /etc/systemd/system/apc-ngoro-dashboard.service
sudo systemctl daemon-reload
echo "Services apc-ngoro-counter and apc-ngoro-dashboard removed."
echo "Services apc-ngoro-service and component units removed."