This commit is contained in:
proitlab committed 2026-10-21 10:01:25 +07:00
commit 0f3d75fa1a
41 files changed
+10566

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
# =============================================================================
# Python & Virtual Environment
# =============================================================================
venv/
env/
ENV/
.venv/
__pycache__/
*.py[cod]
*$py.class
*.so
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# =============================================================================
# Environment & Secrets (Keep example files)
# =============================================================================
.env
.env.*
!.env.example
!config.env.example
# =============================================================================
# Database & State / Cache Files
# =============================================================================
*.db
*.db-*
*.db.bak*
*.sqlite
*.sqlite3
*.db-journal
*.db-wal
*.db-shm
# =============================================================================
# Logs, CSV & Large Data Exports
# =============================================================================
*.csv
*.log
*.tsv
# =============================================================================
# Media, Videos, Frames & Output Directories
# =============================================================================
recount_output/
motioneye_media/
bundled_models/
*.mp4
*.avi
*.mkv
*.mov
screenshot.jpg
*.jpg
*.jpeg
*.png
*.webp
!static/img/*
# =============================================================================
# AI / ML Model Weights
# =============================================================================
*.rknn
*.pt
*.pth
*.onnx
*.engine
*.tflite
# =============================================================================
# IDE, Editor & Operating System Files
# =============================================================================
.DS_Store
Thumbs.db
.idea/
.vscode/
*.swp
*.swo
*~
+113
View File
@@ -0,0 +1,113 @@
# System Flow: Video Recording & Recounting Architecture
**System Overview:** Poultry Counting via Object Detection
Dokumentasi alur kerja (*system flow*) pengolahan video dari proses deteksi *real-time* di **NanoPi 1**, penyimpanan sementara via RAM Disk (`/dev/shm`), pengiriman ke **MotionEye**, hingga proses *recounting* terpisah di **NanoPi 2**.
---
## 1. Arsitektur Perangkat & Pembagian Tugas
| Perangkat | Peran Utama | Deskripsi Tugas |
| :--- | :--- | :--- |
| **NanoPi 1** | Real-time Core & Dashboard | Merekam stream kamera, menjalankan model deteksi ayam *real-time*, mendeteksi penanda batch (talenan), mengelola RAM Disk (`/dev/shm`), serta menyajikan Web Dashboard. |
| **NanoPi 2** | Computing Core (Recount) | Menerima instruksi recount, menjalankan model deteksi ulang pada video rekaman, merender *Bounding Box*, dan menghitung progress persentase. |
| **MotionEye** | Central Storage | Menyimpan rekaman video per-batch secara permanen (retensi 3 hari) dan rekaman *continuous HD* per 30 menit. |
---
## 2. Diagram Alur Sistem (System Flowchart)
```
[ Kamera (Stream) ]
│
▼
┌────────────────────────────────────────────────────────────────────────┐
│ NANOPI 1 (Real-Time Core) │
│ │
│ [ Process 1: Main Detection Loop ] │
│ │ │
│ ├─► Jalankan Model AI (RAM) ──► Hitung Ayam & Talenan │
│ │ │
│ └─► Put Frame (Non-blocking) ──► [ Queue Memory ] │
│ │ │
│ [ Process 2: Multiprocessing Writer ] ◄─────┘ │
│ │ │
│ ├─► Encode Video & Tulis Frame ──► [/dev/shm/batch_X.mp4] (RAM) │
│ │ │
│ └─► (Saat Talenan Terdeteksi / Sinyal Batch End) │
│ │ │
└──────────────────┼─────────────────────────────────────────────────────┘
│
▼ (Background HTTP Upload)
┌────────────────────────────────────────────────────────────────────────┐
│ MOTIONEYE (Storage Server) │
│ │
│ 1. Terima File `batch_X.mp4` & Simpan ke Storage │
│ 2. Kirim Status `200 OK` ke NanoPi 1 │
│ 3. NanoPi 1 Menghapus File Sementara di `/dev/shm` │
└──────────────────┬─────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────────────┐
│ DASHBOARD OPERASIONAL (NanoPi 1 UI) │
│ │
│ Klien Memilih Batch ──► Klik "🔁 Mulai Recounting" │
└──────────────────┬─────────────────────────────────────────────────────┘
│
▼ (HTTP POST /api/v1/recount/start)
┌────────────────────────────────────────────────────────────────────────┐
│ NANOPI 2 (Recounting Engine) │
│ │
│ 1. Ambil Video Batch dari MotionEye │
│ 2. Jalankan Heavy Detection + Draw Bounding Box & Counter Line │
│ 3. Push Progress (%) & Live Count via WebSocket ──► [ Dashboard UI ] │
│ 4. Simpan Video Hasil Render (`batch_X_recount.mp4`) │
│ 5. Kirim Hasil Akhir (Total Count & Delta) ───────► [ Dashboard UI ] │
└────────────────────────────────────────────────────────────────────────┘
```
---
## 3. Tahapan Alur Kerja Detil (Step-by-Step)
### Tahap 1: Rekam Video Batch Tanpa Lag (NanoPi 1)
1. **Frame Capture:** *Main Loop* membaca frame dari kamera.
2. **Detection & Queueing:**
* Model AI mendeteksi ayam dan penanda batch (talenan berwarna mencolok).
* Frame mentah dipisahkan menggunakan `multiprocessing.Queue` ke proses *background writer*.
3. **Write to RAM Disk:**
* *Worker Process* menerima frame dan menulisnya menjadi file video di folder `/dev/shm/batch_TMP.mp4`.
* **Tujuan:** Menghindari *I/O Bottleneck* dan menjaga MicroSD NanoPi 1 tidak cepat rusak.
### Tahap 2: Pengalihan Batch & Pengiriman File (NanoPi 1 → MotionEye)
1. **Trigger Talenan:** Saat talenan terdeteksi, *Main Loop* mengirimkan sinyal `Batch End` ke *Worker Process*.
2. **File Freeze:** File `/dev/shm/batch_TMP.mp4` difinalisasi dan diubah namanya menjadi `/dev/shm/batch_[ID].mp4`.
3. **Async Upload:** *Background Task* mengirim file ke MotionEye via HTTP POST/NFS.
4. **RAM Cleanup:** Setelah MotionEye merespons dengan status `200 OK`, NanoPi 1 langsung menghapus file sementara dari `/dev/shm`.
### Tahap 3: Eksekusi Recounting (Dashboard → NanoPi 2)
1. **Inisiasi Klien:** Klien memilih daftar batch di Dashboard, lalu menekan tombol **"🔁 Mulai Recounting"**.
2. **Trigger Recount:** NanoPi 1 mengirimkan permintaan HTTP POST ke NanoPi 2 berisi `batch_id` dan *URL Video Stream/File* dari MotionEye.
3. **Processing & Progress Streaming (NanoPi 2):**
* NanoPi 2 mengunduh/membaca video dari MotionEye frame demi frame.
* Setiap *N-frame*, NanoPi 2 memperhitungkan kalkulasi persentase (`(frame_saat_ini / total_frame) * 100`) dan mengirimkannya ke NanoPi 1 via **WebSocket**.
* Dashboard menampilkan **Status Progress Persen** secara *real-time*.
4. **Render Bounding Box:** NanoPi 2 menggambar *Bounding Box* di sekeliling objek ayam dan garis penanda (*counting line*) langsung ke file video output baru (`batch_[ID]_recount.mp4`).
### Tahap 4: Penyajian Hasil Akhir di Dashboard
1. **Kalkulasi Selisih (Delta):**
* Selesai proses, NanoPi 2 mengirimkan `recount_count`.
* Dashboard menghitung selisih: Delta = Recount Count - Original Count.
2. **Update Visual UI:**
* **Card Hasil Recounting:** Menampilkan total hitung ulang + **Badge Indikator Selisih** (Warna Hijau jika bertambah, Merah jika berkurang, Abu-abu jika presisi).
* **Video Player:** Memuat file video baru dari NanoPi 2 yang telah dilengkapi visual *Bounding Box*.
---
## 4. Retensi Storage & Auto-Cleanup
* **MotionEye Storage:** Menyimpan video batch dan video continuous HD.
* **Retensi Batch = 3 Hari Aktif:** Cleanup batch sekarang diputuskan dari database `batches`, bukan umur file kalender. Artinya yang dipertahankan adalah **3 `counting_date` terakhir yang benar-benar punya batch**, sama seperti filter recount dashboard.
* **Lokasi Cleanup Batch:** Cron berjalan di **NanoPi 1** dan memanggil ingest MotionEye untuk menghapus `batch_*.mp4` yang `counting_date`-nya sudah di luar 3 hari aktif terakhir.
* **Retensi Overlay Recount = 6 Jam:** Di **NanoPi 2**, file hasil recount `batch_*_recount.mp4` dan cache sumber `_src_*.mp4` dibersihkan otomatis tiap jam jika umur file melewati 6 jam.
* **Data DB Tetap Ada:** Cleanup hanya menghapus file video. Riwayat batch, summary, dan angka recount/count di SQLite tetap dipertahankan untuk histori dashboard.
+500
View File
@@ -0,0 +1,500 @@
"""
Production batch persistence for edge Jetson counter.
Mirrors frigate-counter SQLite schema + current_batch.json contract.
"""
import json
import os
import sqlite3
import threading
import time
from datetime import datetime, timedelta
from pathlib import Path
_SHMD = os.getenv("SHM_DIR", "/dev/shm/apc-ngoro")
_RESET_FLAG = Path(f"{_SHMD}/.reset")
class BatchStore:
def __init__(
self,
db_path,
state_file,
camera_name,
object_label='ayam-potong',
cutoff_time='20:00',
batch_timeout=300.0,
ignore_batch_label_timeout=30.0,
min_object_per_batch=60,
min_duration_per_batch=60,
carry_ids=50,
logger=print,
on_batch_closed=None,
):
self.db_path = db_path
self.state_file = Path(state_file)
self.camera_name = camera_name
self.object_label = object_label
self.cutoff_time_str = cutoff_time
datetime.strptime(cutoff_time, '%H:%M')
self.batch_timeout = float(batch_timeout)
self.ignore_batch_label_timeout = float(ignore_batch_label_timeout)
self.min_object_per_batch = int(min_object_per_batch)
self.min_duration_per_batch = int(min_duration_per_batch)
self.carry_ids = int(carry_ids)
self.log = logger
self.on_batch_closed = on_batch_closed
self.state_lock = threading.Lock()
self.batch_timer = None
self.ignore_batch_label = False
self.ignore_batch_label_timer = None
self.previous_state = None
self.shutdown_event = threading.Event()
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
self.state_file.parent.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(db_path, check_same_thread=False)
self._init_db()
self.current_state = self._load_state()
self.previous_state = self.current_state
def _init_db(self):
cur = self.db.cursor()
cur.execute(
"""
CREATE TABLE IF NOT EXISTS batches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
counting_date TEXT NOT NULL,
batch_number INTEGER NOT NULL,
camera_name TEXT NOT NULL,
object_label TEXT NOT NULL,
count INTEGER NOT NULL,
start_time TEXT NOT NULL,
end_time TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(counting_date, batch_number, camera_name, object_label)
)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS daily_summaries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
counting_date TEXT NOT NULL,
camera_name TEXT NOT NULL,
object_label TEXT NOT NULL,
total_count INTEGER NOT NULL DEFAULT 0,
total_batches INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(counting_date, camera_name, object_label)
)
"""
)
# Recount / MotionEye media columns (idempotent)
for col, decl in (
("video_filename", "TEXT"),
("video_url", "TEXT"),
("recount_count", "INTEGER"),
("recount_delta", "INTEGER"),
("recount_video_url", "TEXT"),
):
try:
cur.execute(f"ALTER TABLE batches ADD COLUMN {col} {decl}")
except sqlite3.OperationalError:
pass
self.db.commit()
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()
def _load_state(self):
if not self.state_file.exists():
return None
try:
with open(self.state_file, 'r', encoding='utf-8') as f:
state = json.load(f)
current_date = self.get_counting_date()
if state.get('counting_date') != current_date:
self.log(
f"State file belongs to previous counting day ({state.get('counting_date')}). "
'Finalizing before fresh start.'
)
self._insert_batch(
state['counting_date'],
state['batch_number'],
state['count'],
state['start_time'],
datetime.now().isoformat(),
)
self.state_file.unlink(missing_ok=True)
return None
self.log(
f"Resumed batch #{state['batch_number']} from {state['start_time']} "
f"with count={state['count']}"
)
self._reset_batch_timer()
return state
except Exception as exc:
self.log(f'Failed to load state file: {exc}')
return None
def save_state(self):
if self.current_state is None:
self.state_file.unlink(missing_ok=True)
return
with open(self.state_file, 'w', encoding='utf-8') as f:
json.dump(self.current_state, f, indent=2, ensure_ascii=False)
def get_next_batch_number(self, counting_date):
cur = self.db.cursor()
cur.execute(
"""
SELECT COALESCE(MAX(batch_number), 0)
FROM batches
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
""",
(counting_date, self.camera_name, self.object_label),
)
return cur.fetchone()[0] + 1
def start_new_batch(self, counting_date):
batch_number = self.get_next_batch_number(counting_date)
now = datetime.now().isoformat()
counted_ids = []
if self.previous_state is not None:
try:
counted_ids = self.previous_state['counted_event_ids'][-self.carry_ids:]
except (KeyError, TypeError):
counted_ids = []
self.current_state = {
'counting_date': counting_date,
'batch_number': batch_number,
'count': 0,
'start_time': now,
'last_detection_time': now,
'counted_event_ids': counted_ids,
}
self.save_state()
self.log(f'Started batch #{batch_number} for {counting_date} ({self.object_label})')
def _reset_batch_timer(self):
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = threading.Timer(self.batch_timeout, self._on_batch_timeout)
self.batch_timer.daemon = True
self.batch_timer.start()
def _on_batch_timeout(self):
self.log(f'Batch inactivity timeout ({self.batch_timeout}s) reached')
self.end_batch(closed_by='timeout')
def _ignore_batch_label(self):
if not self.ignore_batch_label_timer:
self.ignore_batch_label = True
self.ignore_batch_label_timer = threading.Timer(
self.ignore_batch_label_timeout, self._on_ignore_batch_label_timeout
)
self.ignore_batch_label_timer.daemon = True
self.ignore_batch_label_timer.start()
self.log(
f'Ignore batch label for {self.ignore_batch_label_timeout}s'
)
def _on_ignore_batch_label_timeout(self):
self.ignore_batch_label_timer = None
self.ignore_batch_label = False
self.log('Ignore batch label cooldown finished')
def _check_reset_signal(self):
if _RESET_FLAG.exists():
_RESET_FLAG.unlink(missing_ok=True)
if self.current_state is not None:
self.log("External reset signal (SHM marker) — clearing in-memory state")
self.current_state = None
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
elif self.current_state is not None and not self.state_file.exists():
self.log("External reset signal (state file deleted) — clearing in-memory state")
self.current_state = None
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
def record_ayam_crossing(self, track_id):
"""Line-cross equivalent of production ayam-potong MQTT event."""
self._check_reset_signal()
with self.state_lock:
counting_date = self.get_counting_date()
started_new = False
if self.current_state is None:
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
event_key = str(track_id)
if event_key not in self.current_state['counted_event_ids']:
self.current_state['count'] += 1
self.current_state['counted_event_ids'].append(event_key)
self.log(
f'Counted ayam (track {track_id}) | batch #{self.current_state["batch_number"]} '
f'total: {self.current_state["count"]}'
)
self.current_state['last_detection_time'] = datetime.now().isoformat()
self.save_state()
self._reset_batch_timer()
return self.current_state['count'], started_new
def record_talenan_crossing(self, track_id):
"""Line-cross equivalent of production telenan MQTT batch close."""
self._check_reset_signal()
if self.ignore_batch_label:
return False
with self.state_lock:
self._ignore_batch_label()
result = self._end_batch_locked(closed_by='talenan')
self.log(f'Batch closed by talenan (track {track_id})')
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
return result
def end_batch(self, closed_by='manual'):
with self.state_lock:
return self._end_batch_locked(closed_by=closed_by)
def _end_batch_locked(self, closed_by='manual'):
if self.current_state is None:
return False
self.previous_state = self.current_state
state = self.current_state
start_time_obj = datetime.fromisoformat(state['start_time'])
end_time_obj = datetime.now()
duration_seconds = (end_time_obj - start_time_obj).total_seconds()
batch_id = f"{state['counting_date']}-{state['batch_number']}"
if (state['count'] < self.min_object_per_batch
or duration_seconds < self.min_duration_per_batch):
self.current_state = None
self.save_state()
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
self.log(
f'Batch #{state["batch_number"]} discarded '
f'(count={state["count"]}, duration={duration_seconds:.0f}s)'
)
# Signal recorder to abort without blocking the detect/timer thread.
if callable(self.on_batch_closed):
try:
self.on_batch_closed(
{
"ok": False,
"discarded": True,
"batch_id": batch_id,
"counting_date": state["counting_date"],
"batch_number": state["batch_number"],
"count": state["count"],
"closed_by": closed_by,
}
)
except Exception as exc:
self.log(f'on_batch_closed error: {exc}')
return False
end_time = end_time_obj.isoformat()
try:
self._insert_batch(
state['counting_date'],
state['batch_number'],
state['count'],
state['start_time'],
end_time,
)
cps = state['count'] / duration_seconds if duration_seconds > 0 else 0
self.log(
f'Batch #{state["batch_number"]} ended | count={state["count"]} | '
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by}'
)
except Exception as exc:
self.log(f'Failed to persist batch: {exc}')
return False
self.current_state = None
self.save_state()
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
# Truthy return with metadata for video finalize/upload hooks
meta = {
"ok": True,
"batch_id": batch_id,
"counting_date": state["counting_date"],
"batch_number": state["batch_number"],
"count": state["count"],
"closed_by": closed_by,
}
if callable(self.on_batch_closed):
try:
self.on_batch_closed(meta)
except Exception as exc:
self.log(f'on_batch_closed error: {exc}')
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
def set_batch_recount(
self,
counting_date,
batch_number,
recount_count=None,
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
def _insert_batch(self, counting_date, batch_number, count, start_time, end_time):
cur = self.db.cursor()
cur.execute(
"""
INSERT INTO batches
(counting_date, batch_number, camera_name, object_label, count, start_time, end_time)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(counting_date, batch_number, self.camera_name, self.object_label, count, start_time, end_time),
)
cur.execute(
"""
INSERT INTO daily_summaries
(counting_date, camera_name, object_label, total_count, total_batches)
VALUES (?, ?, ?, ?, 1)
ON CONFLICT(counting_date, camera_name, object_label)
DO UPDATE SET
total_count = total_count + excluded.total_count,
total_batches = total_batches + excluded.total_batches,
updated_at = CURRENT_TIMESTAMP
""",
(counting_date, self.camera_name, self.object_label, count),
)
self.db.commit()
cur.execute(
"""
SELECT total_count, total_batches
FROM daily_summaries
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
""",
(counting_date, self.camera_name, self.object_label),
)
row = cur.fetchone()
if row:
self.log(
f'Daily totals for {counting_date}: {row[0]} objects across {row[1]} batch(es)'
)
def cutoff_watcher_loop(self):
while not self.shutdown_event.is_set():
time.sleep(60)
with self.state_lock:
if self.current_state is None:
continue
if self.current_state['counting_date'] != self.get_counting_date():
self.log('Daily cutoff reached – finalizing batch')
self._end_batch_locked(closed_by='cutoff')
def start_cutoff_watcher(self):
t = threading.Thread(target=self.cutoff_watcher_loop, daemon=True)
t.start()
return t
@property
def current_batch_number(self):
if self.current_state is None:
return 0
return self.current_state['batch_number']
@property
def current_batch_count(self):
if self.current_state is None:
return 0
return self.current_state['count']
def get_closed_total_for_day(self, counting_date=None):
if counting_date is None:
counting_date = self.get_counting_date()
cur = self.db.cursor()
cur.execute(
"""
SELECT COALESCE(total_count, 0)
FROM daily_summaries
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
""",
(counting_date, self.camera_name, self.object_label),
)
row = cur.fetchone()
return row[0] if row else 0
def display_total(self):
return self.get_closed_total_for_day() + self.current_batch_count
def shutdown(self):
self.shutdown_event.set()
self.end_batch(closed_by='shutdown')
if self.batch_timer:
self.batch_timer.cancel()
self.db.close()
+478
View File
@@ -0,0 +1,478 @@
"""
RAM-disk batch video recorder for live counter.
Writes frames to /dev/shm while a batch is open; finalize renames for upload.
Designed so the detection loop never blocks on encode or writer join:
- put() is non-blocking (drop only when queue is full)
- max_fps <= 0 means record every frame (no throttle)
- encode runs in a separate process on CPU (ffmpeg libx264 ultrafast / OpenCV fallback)
- finalize() may join the writer; callers should run it off the detect thread
- after encode, restamp container FPS to written/wall so duration ≈ wall time
"""
from __future__ import annotations
import multiprocessing as mp
import os
import queue
import subprocess
import threading
import time
from pathlib import Path
from typing import Optional
import cv2
import numpy as np
SENTINEL = None
FFMPEG_BIN = os.getenv("FFMPEG_BIN", "ffmpeg")
# libx264 ultrafast keeps up at 640x480 without blocking NPU detect
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"
def _ffmpeg_writer_proc(
q: mp.Queue,
out_path: str,
fps: float,
width: int,
height: int,
encoder: str,
preset: str,
crf: str,
):
"""CPU encode via ffmpeg stdin — H.264 for browser + speed."""
path = Path(out_path)
path.parent.mkdir(parents=True, exist_ok=True)
fps = max(float(fps), 1.0)
cmd = [
FFMPEG_BIN,
"-hide_banner",
"-loglevel",
"error",
"-y",
"-f",
"rawvideo",
"-pix_fmt",
"bgr24",
"-s",
f"{width}x{height}",
"-r",
f"{fps:.6f}",
"-i",
"pipe:0",
"-an",
"-c:v",
encoder,
]
if encoder.startswith("libx264"):
cmd.extend(["-preset", preset, "-tune", "zerolatency", "-crf", crf])
# No +faststart here (needs second pass; breaks some pipe→file flows).
# Finalize restamp applies +faststart.
cmd.extend(["-pix_fmt", "yuv420p", str(path)])
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
)
assert proc.stdin is not None
frames = 0
err_tail = b""
try:
while True:
item = q.get()
if item is SENTINEL:
break
frame = item
if frame is None:
continue
fh, fw = frame.shape[:2]
if fw != width or fh != height:
if fw > width or fh > height:
frame = cv2.resize(
frame, (width, height), interpolation=cv2.INTER_AREA
)
else:
canvas = np.zeros((height, width, 3), dtype=frame.dtype)
canvas[:fh, :fw] = frame
frame = canvas
if not frame.flags["C_CONTIGUOUS"]:
frame = np.ascontiguousarray(frame)
try:
proc.stdin.write(frame.tobytes())
frames += 1
except BrokenPipeError:
break
except Exception as exc:
print(f"[BatchVideoRecorder] ffmpeg writer error: {exc}", flush=True)
finally:
try:
proc.stdin.close()
except Exception:
pass
try:
err_tail = proc.stderr.read() if proc.stderr else b""
except Exception:
err_tail = b""
try:
proc.wait(timeout=60)
except Exception:
proc.kill()
try:
proc.wait(timeout=5)
except Exception:
pass
ok = (
proc.returncode == 0
and Path(out_path).is_file()
and Path(out_path).stat().st_size > 1000
)
if not ok:
msg = (err_tail or b"").decode("utf-8", errors="replace")[-400:]
print(
f"[BatchVideoRecorder] ffmpeg failed rc={proc.returncode} "
f"frames={frames}: {msg}",
flush=True,
)
else:
print(
f"[BatchVideoRecorder] ffmpeg ok frames={frames} "
f"size={Path(out_path).stat().st_size}",
flush=True,
)
def _opencv_writer_proc(
q: mp.Queue,
out_path: str,
fps: float,
width: int,
height: int,
):
"""Fallback OpenCV writer (prefer avc1, then mp4v)."""
path = Path(out_path)
path.parent.mkdir(parents=True, exist_ok=True)
writer = None
try:
for fourcc in ("avc1", "H264", "mp4v"):
writer = cv2.VideoWriter(
str(path),
cv2.VideoWriter_fourcc(*fourcc),
max(fps, 1.0),
(width, height),
)
if writer.isOpened():
print(f"[BatchVideoRecorder] OpenCV fourcc={fourcc}", flush=True)
break
writer.release()
writer = None
if writer is None:
print("[BatchVideoRecorder] OpenCV VideoWriter failed to open", flush=True)
while True:
item = q.get()
if item is SENTINEL:
break
return
while True:
item = q.get()
if item is SENTINEL:
break
frame = item
if frame is None:
continue
fh, fw = frame.shape[:2]
if fw != width or fh != height:
if fw > width or fh > height:
frame = cv2.resize(
frame, (width, height), interpolation=cv2.INTER_AREA
)
else:
canvas = np.zeros((height, width, 3), dtype=frame.dtype)
canvas[:fh, :fw] = frame
frame = canvas
writer.write(frame)
except Exception as exc:
print(f"[BatchVideoRecorder] writer error: {exc}", flush=True)
finally:
if writer is not None:
writer.release()
def _writer_proc(
q: mp.Queue,
out_path: str,
fps: float,
width: int,
height: int,
use_ffmpeg: bool,
encoder: str,
preset: str,
crf: str,
):
if use_ffmpeg:
_ffmpeg_writer_proc(q, out_path, fps, width, height, encoder, preset, crf)
return
_opencv_writer_proc(q, out_path, fps, width, height)
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
try:
tmp = dst.with_suffix(".restamp.mp4")
cmd = [
FFMPEG_BIN,
"-y",
"-r",
f"{measured_fps:.6f}",
"-i",
str(src),
"-c",
"copy",
"-movflags",
"+faststart",
str(tmp),
]
subprocess.run(
cmd,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=600,
)
if not tmp.is_file() or tmp.stat().st_size < 1000:
tmp.unlink(missing_ok=True)
return False
tmp.replace(dst)
return True
except Exception as exc:
print(f"[BatchVideoRecorder] restamp failed: {exc}")
try:
dst.with_suffix(".restamp.mp4").unlink(missing_ok=True)
except Exception:
pass
return False
def _ffmpeg_available() -> bool:
try:
subprocess.run(
[FFMPEG_BIN, "-version"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
)
return True
except Exception:
return False
class BatchVideoRecorder:
"""Non-blocking frame sink that records the active batch to SHM."""
def __init__(
self,
shm_dir: str,
enabled: bool = True,
max_fps: float = 0.0,
queue_size: int = 480,
):
self.shm_dir = Path(shm_dir)
self.enabled = enabled
# <=0 means passthrough every frame (no FPS throttle)
self.max_fps = float(max_fps) if max_fps and max_fps > 0 else 0.0
self.queue_size = max(4, int(queue_size))
self.shm_dir.mkdir(parents=True, exist_ok=True)
self._q: Optional[mp.Queue] = None
self._proc: Optional[mp.Process] = None
self._w = self._h = 0
self._fps = 15.0
self._active = False
self._batch_id: Optional[str] = None
self._partial: Optional[Path] = None
self._last_put_mono = 0.0
self._dropped = 0
self._written = 0
self._t0 = 0.0
self._measured_fps = 0.0
self._lock = threading.Lock()
self._use_ffmpeg = _ffmpeg_available() and RECORD_ENCODER.lower() != "opencv"
@property
def active(self) -> bool:
return self._active
@property
def stats(self) -> dict:
return {
"active": self._active,
"batch_id": self._batch_id,
"written": self._written,
"dropped": self._dropped,
"size": f"{self._w}x{self._h}",
"fps": self._fps,
"max_fps": self.max_fps,
"measured_fps": self._measured_fps,
"encoder": RECORD_ENCODER if self._use_ffmpeg else "opencv",
}
def start(self, batch_id: str, width: int, height: int, fps: float):
if not self.enabled:
return
with self._lock:
self._stop_discard_locked()
self._batch_id = batch_id
self._w = max(1, int(width))
self._h = max(1, int(height))
src_fps = float(fps) if fps and fps > 1 else 15.0
# Writer stamp uses camera fps; finalize restamps to measured.
if self.max_fps > 0:
self._fps = min(src_fps, self.max_fps)
else:
self._fps = src_fps
self._partial = self.shm_dir / f"batch_{batch_id}.partial.mp4"
if self._partial.exists():
self._partial.unlink(missing_ok=True)
legacy = self.shm_dir / "batch_TMP.mp4"
legacy.unlink(missing_ok=True)
self._q = mp.Queue(maxsize=self.queue_size)
self._proc = mp.Process(
target=_writer_proc,
args=(
self._q,
str(self._partial),
self._fps,
self._w,
self._h,
self._use_ffmpeg,
RECORD_ENCODER,
RECORD_PRESET,
RECORD_CRF,
),
daemon=True,
)
self._proc.start()
self._active = True
self._last_put_mono = 0.0
self._dropped = 0
self._written = 0
self._measured_fps = 0.0
self._t0 = time.monotonic()
print(
f"[BatchVideoRecorder] start {batch_id} "
f"{self._w}x{self._h}@{self._fps:.1f} "
f"queue={self.queue_size} encoder="
f"{RECORD_ENCODER if self._use_ffmpeg else 'opencv'}",
flush=True,
)
def put(self, frame: np.ndarray):
if not self._active or self._q is None:
return
if self.max_fps > 0:
now = time.monotonic()
min_dt = 1.0 / self.max_fps
if self._last_put_mono and (now - self._last_put_mono) < min_dt:
self._dropped += 1
return
self._last_put_mono = now
try:
self._q.put_nowait(frame.copy())
self._written += 1
except queue.Full:
self._dropped += 1
try:
self._q.get_nowait()
except queue.Empty:
pass
try:
self._q.put_nowait(frame.copy())
self._written += 1
except queue.Full:
pass
def finalize(self) -> Optional[Path]:
"""Close writer, restamp FPS to match wall time, return final path."""
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
self._active = False
self._q = None
self._proc = None
self._batch_id = None
self._partial = None
if q is not None:
try:
q.put(SENTINEL, timeout=2)
except Exception:
pass
if proc is not None:
# Longer join — draining a full queue at end of batch can take a bit.
proc.join(timeout=120)
if proc.is_alive():
proc.terminate()
proc.join(timeout=2)
if not batch_id or partial is None:
return None
if not partial.is_file() or partial.stat().st_size < 1000:
partial.unlink(missing_ok=True)
return None
wall = max(0.001, time.monotonic() - t0) if t0 else 0.0
measured = (written / wall) if wall > 0 and written > 0 else 0.0
self._measured_fps = measured
total_attempted = written + dropped
drop_pct = (100.0 * dropped / total_attempted) if total_attempted else 0.0
print(
f"[BatchVideoRecorder] finalize {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"
if measured >= 1.0 and _restamp_fps(partial, out, measured):
partial.unlink(missing_ok=True)
else:
partial.replace(out)
return out
def stop_discard(self):
"""Abort recording and delete partial."""
with self._lock:
self._stop_discard_locked()
def _stop_discard_locked(self):
partial = self._partial
if self._active or self._proc is not None:
q, proc = self._q, self._proc
self._active = False
self._q = None
self._proc = None
self._batch_id = None
self._partial = None
if q is not None:
try:
q.put(SENTINEL, timeout=1)
except Exception:
pass
if proc is not None:
proc.join(timeout=5)
if proc.is_alive():
proc.terminate()
proc.join(timeout=2)
if partial is not None:
partial.unlink(missing_ok=True)
(self.shm_dir / "batch_TMP.mp4").unlink(missing_ok=True)
+155
View File
@@ -0,0 +1,155 @@
# =============================================================================
# ZenAI APC Ngoro — Edge RK3588 counter + dashboard
# Shared config for: counter_live_rknn_bytetrack.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
STATE_FILE=/tmp/apc_ngoro_current_batch.json
SHM_DIR=/dev/shm/apc-ngoro
# --- Input source ---
# RTSP / HTTP live stream, or a local video file path
SOURCE=rtsp://user:pass@192.168.0.100:554/stream1
# FFmpeg capture options passed to cv2.VideoCapture (RTSP low-latency flags)
OPENCV_FFMPEG_CAPTURE_OPTIONS=rtsp_transport;tcp|fflags;nobuffer|flags;low_delay
# --- RKNN model ---
# Path to exported .rknn model on NanoPi (edit after copying model file)
MODEL_PATH=/opt/models/yolo9t.rknn
IMGSZ=320
HALF=false
CORE_MASK=7
DEVICE=0
# --- 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
# --- ByteTrack tracking (ayam = index 0) ---
TRACK_HIGH_THRESH_0=0.25 # was 0.5 / 0.35 / 0.28 / 0.38 / 0.22
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_MATCH_THRESH_0=0.20
TRACK_BUFFER_0=30 # was 30 / 20 / 40 / 30 / 60
# was 3
TRACK_MIN_HITS_0=1
# --- ByteTrack tracking (talenan = index 1) ---
TRACK_HIGH_THRESH_1=0.4 # was 0.5
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=
OBJECT_LABEL=ayam-potong
CLASS_AYAM=ayam
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_ZONE_Y_END_FRAC=1.0
# --- Batch management ---
DAILY_CUTOFF_TIME=20:00
CUTOFF_TIME=20:00
RESET_COUNTERS_AT_CUTOFF=true
BATCH_TIMEOUT_SECONDS=300
IGNORE_BATCH_LABEL_TIMEOUT_SECONDS=30
MIN_OBJECT_PER_BATCH=60
MIN_DURATION_PER_BATCH=60
# --- CSV export ---
EXPORT_CSV=true
CROSS_CSV=/opt/apc-ngoro/batch_crossings.csv
# --- Rate / performance ---
MOTION_DETECTION_ENABLED=false
MOTION_THRESHOLD=5.0
RATE_WINDOW_SEC=60
WARMUP_FRAMES=30
RECONNECT_DELAY_SEC=3
MAX_RECONNECT_ATTEMPTS=0
FLUSH_EVERY_N_FRAMES=100
TRACKED_PRUNE_SEC=300
# --- Video recording ---
RECORD_VIDEO=false
VIDEO_SEGMENT_SEC=3600
OUTPUT_FPS=15
# --- Live stream snapshot (required for dashboard feed) ---
LIVE_STREAM_ENABLED=false
LIVE_STREAM_FRAME_PATH=/dev/shm/apc-ngoro/live_frame.jpg
LIVE_STREAM_QUALITY=75
LIVE_STREAM_EVERY_N=2
# --- Dashboard (counter_dashboard.py) ---
DASHBOARD_TEMPLATE=dashboard_operational.html
SECRET_KEY=change-me-in-production
DASHBOARD_HOST=0.0.0.0
DASHBOARD_PORT=5000
FLASK_DEBUG=false
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_RESOLUTION_DISPLAY=640x480
STREAM_ACCURACY_PCT=98
# --- 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
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
RECOUNT_STUB=false
# Optional: force delta for badge testing when RECOUNT_STUB=true (e.g. 5 or -3)
RECOUNT_STUB_DELTA=
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_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)
RECOUNT_START_COUNT=1
RECOUNT_LIVE_FRAME_MAX_WIDTH=960
RECOUNT_LIVE_JPEG_QUALITY=60
PREVIEW_WARM_WHEN_BUSY=false
View File
Whitespace-only changes.
+1793
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+502
View File
@@ -0,0 +1,502 @@
# ZenAI APC Ngoro — API Guide (for new developers)
This guide explains how to call the dashboard HTTP API on **NanoPi 1**.
You do **not** need to know Flask or the counter internals to get started.
---
## 1. Quick start
| Item | Value |
|------|--------|
| Local base URL | `http://127.0.0.1:5000` |
| Public base URL | `https://ngoro.apc.zenai.id` |
| Auth | **None** (LAN / tunnel trust — do not expose write endpoints blindly) |
| Default JSON | `Content-Type: application/json` |
| Service | `apc-ngoro-dashboard` (gunicorn on port 5000) |
Replace `BASE` in examples with either URL above.
```bash
export BASE=http://127.0.0.1:5000
# or: export BASE=https://ngoro.apc.zenai.id
```
---
## 2. First 5 minutes
```bash
# Is the API up?
curl -s "$BASE/api/health" | python3 -m json.tool
# Today / yesterday / all-time numbers
curl -s "$BASE/api/summary" | python3 -m json.tool
# Live batch (IDLE when nothing is counting)
curl -s "$BASE/api/current-batch" | python3 -m json.tool
```
Expected health response (shape may vary slightly):
```json
{
"success": true,
"service": "apc-ngoro-dashboard",
"site_name": "NGORO",
"db": "ok",
"state_file": "missing",
"time": "2026-09-29T14:46:37"
}
```
- `db: "ok"` → SQLite is readable.
- `state_file: "missing"` → no active live batch file (normal when idle).
- `state_file: "ok"` → counter has written `current_batch.json`.
---
## 3. Endpoint catalog
### 3.1 Dashboard reads
#### `GET /api/health`
Readiness probe for monitoring / load balancers.
| Status | Meaning |
|--------|---------|
| 200 | DB OK |
| 500 | DB unreachable (`db: "error"`, optional `db_error`) |
#### `GET /api/current-batch`
Live counter state from the edge state file.
```json
{
"success": false,
"error": "No active batch",
"count": 0,
"batch_number": null,
"counting_date": null,
"status": "IDLE"
}
```
When a batch is running you also get `start_time`, `last_detection_time`, and `status: "RUNNING"`.
> Note: “no active batch” still returns **HTTP 200** with `success: false`. Check `success` / `status`, not only the status code.
#### `GET /api/previous-batch`
Last finished batch in the DB.
```json
{
"success": true,
"date": "2026-09-29",
"batch_number": 22,
"count": 1667,
"start_time": "2026-09-29T03:27:30.136003",
"end_time": "2026-09-29T03:44:34.630252",
"duration_minutes": 17.1
}
```
#### `GET /api/summary`
Dashboard KPI tiles.
```json
{
"site_name": "NGORO",
"cutoff_time": "19:00",
"today": {
"date": "2026-09-29",
"total_count": 34227,
"total_batches": 22,
"trend_pct": 1.6,
"vs_avg_pct": 9.7
},
"yesterday": {
"date": "2026-09-28",
"total_count": 33683,
"total_batches": 21,
"is_last_active": true
},
"average_per_day": 31208.3,
"best_day": { "date": "2026-09-29", "count": 34227 },
"all_time": {
"grand_total": 499333,
"grand_batches": 345,
"total_days": 16,
"avg_per_batch": 1447.3
}
}
```
#### `GET /api/daily-data`
Daily summary rows for charts / tables.
| Query | Description | Default |
|-------|-------------|---------|
| `days` | Look back N calendar days from today | `30` |
| `date` | From-date `YYYY-MM-DD` (inclusive). If set, **overrides** `days` | — |
```bash
curl -s "$BASE/api/daily-data?days=7"
curl -s "$BASE/api/daily-data?date=2026-09-28"
```
```json
[
{
"date": "2026-09-28",
"total_count": 33683,
"total_batches": 21,
"avg_per_batch": 1604.0
}
]
```
#### `GET /api/day-detail/<date>`
One counting day + every batch that day.
```bash
curl -s "$BASE/api/day-detail/2026-09-29" | python3 -m json.tool
```
Each batch object includes:
| Field | Notes |
|-------|--------|
| `batch_number`, `count`, `start_time`, `end_time`, `duration_minutes` | Always present |
| `camera_name`, `object_label` | Camera / label used for counting |
| `recount_count`, `recount_delta` | `null` if never recounted |
| `video_url` | Source video URL when available |
#### `GET /api/recent-batches`
Newest finished batches.
| Query | Description | Default |
|-------|-------------|---------|
| `limit` | Max rows | `10` |
```bash
curl -s "$BASE/api/recent-batches?limit=1"
```
```json
[
{
"date": "2026-09-29",
"batch_number": 22,
"count": 1667,
"start_time": "2026-09-29T03:27:30.136003",
"end_time": "2026-09-29T03:44:34.630252",
"duration_minutes": 17.1,
"camera_name": "CC1",
"object_label": "ayam-potong",
"recount_count": null,
"recount_delta": null,
"video_url": "http://192.168.192.251:8090/files/2026-09-29-22"
}
]
```
#### `GET /api/available-dates`
Dates that have daily summaries (newest first).
```json
[
{ "date": "2026-09-29", "total_batches": 22, "total_count": 34227 },
{ "date": "2026-09-28", "total_batches": 21, "total_count": 33683 }
]
```
---
### 3.2 Recount API (`/api/v1/recount/...`)
Recount re-runs counting on a recorded batch video (proxied to NanoPi 2).
Batch IDs look like: `YYYY-MM-DD-N` e.g. `2026-09-29-22`.
#### `GET /api/v1/recount/batches`
Batches grouped by date (UI “Riwayat”).
```json
{
"days": 3,
"groups": [
{
"date": "2026-09-29",
"batches": [
{
"batch_id": "2026-09-29-22",
"batch_number": 22,
"original_count": 1667,
"start_time": "...",
"end_time": "...",
"recount_count": null,
"delta": null,
"video_url": "/api/v1/recount/source/2026-09-29-22",
"recount_video_url": null
}
]
}
]
}
```
#### `GET /api/v1/recount/status`
Current recount job (in-memory on this dashboard).
```json
{
"success": true,
"stub": false,
"status": "PROCESSING",
"progress": 32,
"current_count": 566,
"recount_count": null,
"delta": null,
"batch_id": "2026-09-29-1",
"original_count": 1783,
"video_url": null,
"error": null
}
```
`status` values: `IDLE` | `PROCESSING` | `COMPLETED` (+ possible `error` string).
#### `POST /api/v1/recount/start`
```bash
curl -s -X POST "$BASE/api/v1/recount/start" \
-H "Content-Type: application/json" \
-d '{"batch_id":"2026-09-29-22"}'
```
| HTTP | Meaning |
|------|---------|
| 200 | Started |
| 400 | Invalid `batch_id` |
| 404 | Batch not in DB |
| 409 | Another recount already `PROCESSING` |
Invalid body example:
```json
{ "success": false, "error": "batch_id tidak valid (format: YYYY-MM-DD-N)" }
```
#### `POST /api/v1/recount/stop`
```bash
curl -s -X POST "$BASE/api/v1/recount/stop"
```
Asks the job to cancel / stop. Returns JSON with current status.
#### Media helpers
| Endpoint | Type | Notes |
|----------|------|--------|
| `GET /api/v1/recount/live-frame` | `image/jpeg` | Single annotated frame from NanoPi 2 |
| `GET /api/v1/recount/live-video` | MJPEG stream | Prefer this in UI (`<img src="...">`) |
| `GET /api/v1/recount/source/<batch_id>` | video | Source MP4 for a batch |
| `GET /api/v1/recount/video/<filename>` | video | Recount output file on NanoPi 2 |
| `POST/GET /api/v1/recount/warm-source/<batch_id>` | JSON | Warm preview cache |
If NanoPi 2 is down, these may return **502** / **503**.
---
### 3.3 Live streams
#### `GET /api/stream` — Server-Sent Events (SSE)
Long-lived connection. Prefer this over polling `/api/current-batch`.
Events:
| Event name | Payload |
|------------|---------|
| `current-batch` | Same shape as `/api/current-batch` |
| `recount-status` | Same fields as `/api/v1/recount/status` (without wrapping extras) |
Heartbeat: comment line `: ping` about every **15 seconds** (keeps proxies happy).
```bash
# Watch the stream (Ctrl+C to stop)
curl -N "$BASE/api/stream"
```
Browser example:
```javascript
const es = new EventSource('/api/stream');
es.addEventListener('current-batch', (e) => {
const data = JSON.parse(e.data);
console.log('batch', data.status, data.count);
});
es.addEventListener('recount-status', (e) => {
const data = JSON.parse(e.data);
console.log('recount', data.status, data.progress);
});
es.onerror = () => {
// Browser auto-reconnects while CONNECTING.
// Only fall back to polling if readyState === EventSource.CLOSED.
if (es.readyState === EventSource.CLOSED) {
es.close();
// e.g. setInterval(() => fetch('/api/current-batch'), 2000);
}
};
```
#### `GET /api/live-video` — operational MJPEG
```html
<img src="/api/live-video" alt="Live feed" />
```
`Content-Type: multipart/x-mixed-replace; boundary=frame`
---
### 3.4 Exports (Excel)
Despite historical `-csv` names, these endpoints return **XLSX**.
| Preferred (alias) | Legacy (still works) |
|-------------------|----------------------|
| `GET /api/export-daily-xlsx?days=30` | `GET /api/export-daily-csv?days=30` |
| `GET /api/export-day-xlsx/<date>` | `GET /api/export-day-csv/<date>` |
```bash
curl -OJ "$BASE/api/export-daily-xlsx?days=7"
curl -OJ "$BASE/api/export-day-xlsx/2026-09-28"
```
`Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
---
### 3.5 Admin
#### `POST /api/reset`
Deletes live state files and signals the counter to reset.
```bash
curl -s -X POST "$BASE/api/reset"
```
**Warning:** Destructive and **unauthenticated**. Only use on trusted networks / during maintenance.
---
## 4. Errors
### Standard JSON error shape
```json
{ "success": false, "error": "Not found", "path": "/api/nonexistent" }
```
| HTTP | When |
|------|------|
| 400 | Bad request (e.g. invalid `batch_id`) |
| 404 | Unknown path **or** batch not found |
| 405 | Wrong HTTP method (e.g. `POST /api/summary`) |
| 409 | Conflict (recount already running) |
| 500 | Server / DB failure |
| 502 / 503 | Upstream (NanoPi 2 / MotionEye) or DB unavailable |
### Gotcha: HTTP 200 + `success: false`
Several read endpoints (notably `/api/current-batch` when idle) return **200** with `success: false`.
Always read the JSON body.
405 example:
```json
{
"success": false,
"error": "Method not allowed",
"path": "/api/summary",
"method": "POST"
}
```
---
## 5. Gotchas (read this)
1. **Export “csv” ≠ CSV** — files are `.xlsx`. Prefer `/api/export-*-xlsx`.
2. **`/api/daily-data?date=`** is a **from-date filter**, not “only this day”. Use `/api/day-detail/<date>` for a single day.
3. **Recount depends on NanoPi 2** — status may stay stuck / live-frame may fail if `NANOPI2_URL` is unreachable.
4. **No auth** — treat write endpoints (`start`, `stop`, `reset`) as internal.
5. **Counting date ≠ calendar midnight** — site uses a cutoff (`cutoff_time` in summary, often evening). A “day” can span late evening into the next morning.
6. **SSE vs polling** — do not poll `/api/current-batch` every 200ms; use `/api/stream`.
---
## 6. Data model (short glossary)
### Table `batches`
One finished counting run.
| Column | Meaning |
|--------|---------|
| `counting_date` | Business day (`YYYY-MM-DD`) |
| `batch_number` | Sequence within that day |
| `camera_name` / `object_label` | Source camera / class |
| `count` | Final live count |
| `start_time` / `end_time` | ISO timestamps |
| `video_url` / `video_filename` | Recorded video |
| `recount_count` / `recount_delta` | Optional recount result |
Batch id used by recount UI: `{counting_date}-{batch_number}` → `2026-09-29-22`.
### Table `daily_summaries`
Per-day rollup: `total_count`, `total_batches` for chart / KPI.
### Live state file
Path from env `STATE_FILE` / `CURRENT_BATCH_PATH` (default `/tmp/apc_ngoro_current_batch.json`).
Written by the live counter process; read by `/api/current-batch` and SSE.
---
## 7. Suggested client flow
```text
1. GET /api/health → abort if not 200
2. GET /api/summary → paint KPI tiles
3. EventSource /api/stream → live count + recount progress
4. GET /api/available-dates + /api/day-detail/<date> → history
5. (optional) POST /api/v1/recount/start with batch_id
```
---
## 8. Related docs
- [RECOUNTING_CONNECT.md](./RECOUNTING_CONNECT.md) — device topology (NanoPi 1 / 2 / MotionEye)
- [../RECOUNTING_SYSTEM_FLOW.md](../RECOUNTING_SYSTEM_FLOW.md) — recount system flow
Questions about routes live in `counter_dashboard.py` (`@app.route`).
+88
View File
@@ -0,0 +1,88 @@
# Recounting — Device Connection Checklist (Phase 0)
## Topology (ZeroTier `192.168.192.0/24`)
| Role | Host | Endpoints |
|------|------|-----------|
| NanoPi 1 (dashboard + live counter) | `192.168.192.208` | Dashboard `:5000` |
| MotionEye | `192.168.192.251` | UI `:8081`, ingest `:8090` |
| NanoPi 2 (recount engine) | `192.168.192.16` | Recount API `:8765` |
## Checklist
1. From NanoPi 1: `ping -c1 192.168.192.251` and `ping -c1 192.168.192.16`
2. Open MotionEye UI: `http://192.168.192.251:8081` — set `MOTIONEYE_USER` / `MOTIONEYE_PASSWORD` in `.env` if needed
3. **SSH to MotionEye as `support`** (not root): `ssh support@192.168.192.251`
4. Locate media dir (e.g. `/data/media/Camera1`). Set `MOTIONEYE_MEDIA_DIR`, `MOTIONEYE_CAMERA_ID=1`, `MOTIONEYE_SSH_USER=support`
5. Authorize NanoPi 1 key for `support` on ME (`/home/support/.ssh/authorized_keys`) and for NP2
6. Deploy ingest: `bash scripts/deploy-motioneye-ingest.sh`
7. Deploy recount: `bash scripts/deploy-recount-to-nanopi2.sh`
8. Manual test file name: `batch_YYYY-MM-DD-N.mp4` in media dir (or upload via ingest)
9. Set on NanoPi 1 `.env`: `RECOUNT_STUB=false`, corrected URLs below
## Required `.env` keys (NanoPi 1)
```
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=<shared-secret>
MOTIONEYE_MEDIA_DIR=/data/media/Camera1
MOTIONEYE_CAMERA_ID=1
MOTIONEYE_USER=support
MOTIONEYE_SSH_USER=support
BATCH_RECORD_ENABLED=true
BATCH_RECORD_FPS=0
BATCH_RECORD_QUEUE=120
RECOUNT_STUB=false
```
## Status notes (this host)
- MotionEye `:8081` HTTP responds (200).
- MotionEye SSH user is **`support`** (default in deploy script).
- SSH to ME/NP2 with `nanopi_agent` key was **not authorized** at implementation time.
- Local ingest smoke-tested on NanoPi 1 at `:8090` writing to `/opt/apc-ngoro/motioneye_media/` (temporary until ME deploy).
- Dashboard `RECOUNT_STUB=false` proxies to NanoPi 2; until recount is deployed, status shows connection refused (expected).
## Current status (post-deploy)
- MotionEye ingest: **OK** (`http://192.168.192.251:8090/health`)
- NanoPi 2 recount service: **running**, but first E2E failed with missing model file
- Fix model then retest:
```bash
# Option A — copy model only
bash /opt/apc-ngoro/scripts/copy-model-to-nanopi2.sh
# Option B — redeploy recount (now bundles the .rknn)
bash /opt/apc-ngoro/scripts/deploy-recount-to-nanopi2.sh
# Remove deprecated MotionEye-side calendar cleanup, then install new retention cron
bash /opt/apc-ngoro/scripts/deploy-motioneye-cleanup-cron.sh
bash /opt/apc-ngoro/scripts/deploy-retention-cron.sh
# Verify local active-day cron
cat /etc/cron.d/apc-retention
# Dry-run active-day cleanup from NP1
/opt/apc-ngoro/venv/bin/python /opt/apc-ngoro/scripts/retention_active_days.py --dry-run
# Dry-run overlay cleanup on NP2
ssh root@192.168.192.16 'cd /opt/apc-ngoro && /opt/apc-ngoro/venv/bin/python scripts/recount_overlay_cleanup.py --dry-run'
# Retest recount (batch 2026-09-09-19 already has video on ME)
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"}'
curl -sS http://127.0.0.1:5000/api/v1/recount/status
```
## Next actions for you
1. Append `~/.ssh/nanopi_agent.pub` to **`support`**’s `authorized_keys` on MotionEye (`/home/support/.ssh/authorized_keys`) and to NanoPi 2.
2. On MotionEye, set real `MOTIONEYE_MEDIA_DIR`, then run:
`bash /opt/apc-ngoro/scripts/deploy-motioneye-ingest.sh`
3. On NanoPi 2 (after copying RKNN model to `/opt/models/...`), run:
`bash /opt/apc-ngoro/scripts/deploy-recount-to-nanopi2.sh`
4. Remove deprecated MotionEye cron with `scripts/deploy-motioneye-cleanup-cron.sh`, then install the new retention automation with `scripts/deploy-retention-cron.sh`.
Batch files now keep only the last **3 active counting dates** (`ACTIVE_RETENTION_DAYS=3`), while NP2 overlay outputs are deleted after **6 hours** (`RECOUNT_OVERLAY_TTL_HOURS=6`).
5. Place today’s test file as `batch_YYYY-MM-DD-N.mp4` (or upload via ingest) and set that batch’s `video_url` in DB / via live recording.
6. Restart counter after `.env` changes: `systemctl restart apc-ngoro-counter`
+433
View File
@@ -0,0 +1,433 @@
# NanoPi 1 & NanoPi 2 Recount Communication Architecture & Adaptation Guide
Panduan komprehensif mengenai mekanisme komunikasi antara **NanoPi 1** (Primary Controller & Dashboard) dan **NanoPi 2** (Secondary Compute & Recount Worker), serta panduan implementasi untuk mengadaptasi pola arsitektur ini ke sistem edge computing lainnya.
---
## 1. Arsitektur Komunikasi & Topologi Jaringan
Sistem menggunakan pola **Decoupled Edge Worker Pattern**. Beban komputasi berat (*recounting*, inferensi ulang AI, dan re-encoding video) didelegasikan sepenuhnya ke NanoPi 2, sehingga NanoPi 1 tetap responsif melayani stream RTSP, inferensi live, dan UI Web.
```
[ Browser Klien ]
│
│ HTTP (Port 5000)
▼
┌────────────────────────────────────────────────────────┐
│ NANOPI 1 (Primary / Dashboard Node) │
│ IP: 192.168.192.x (Port 5000) │
│ • Database SQLite (apc_ngoro.db) │
│ • Web UI Dashboard & Reverse Proxy Controller │
└───────┬───────────────────────────────┬────────────────┘
│ │
│ HTTP REST (Port 8765) │ HTTP Upload (Port 8090)
▼ ▼
┌──────────────────────────────┐ ┌───────────────────────┐
│ NANOPI 2 (Worker Node) │ │ CENTRAL STORAGE │
│ IP: 192.168.192.16:8765 │ │ (MotionEye / Ingest) │
│ • Daemon Flask Engine │ │ IP: 192.168.192.251 │
│ • Worker Thread (RKNN+Byte) │ │ • File Server (:8090) │
└───────┬──────────────────────┘ └───────────▲───────────┘
│ │
└──────── Ambil Video Sumber ────────┘
HTTP GET /files/<batch_id>
```
### Prinsip Utama:
1. **100% HTTP REST over LAN**: Komunikasi saat *runtime* hanya menggunakan HTTP REST API murni, tanpa dependensi socket stateful yang rapuh.
2. **NanoPi 1 sebagai Single Gateway**: Browser klien tidak pernah mengakses NanoPi 2 secara langsung. Semua request (status, preview, video stream) di-proxy oleh NanoPi 1 untuk menghindari isu CORS, manajemen multi-port, dan keamanan jaringan.
3. **Storage Terpusat (Decoupled Storage)**: Video batch mentah tersimpan di server terpisah (MotionEye / HTTP Storage), sehingga NanoPi 2 dapat mengambil video secara langsung tanpa membebani I/O NanoPi 1.
---
## 2. Rincian API Endpoint Antar-Perangkat
### A. NanoPi 2 (Worker API — Port 8765)
Service berjalan sebagai daemon systemd `apc-ngoro-recount.service` menggunakan Flask multithreaded.
| Method | Endpoint | Fungsi | Payload / Respon |
| :--- | :--- | :--- | :--- |
| `GET` | `/health` | Pemeriksaan kesiapan worker & status model | `{"ok": true, "model_loaded": true, ...}` |
| `POST` | `/api/v1/recount/start` | Memicu job recounting baru | Body: `{"batch_id": "...", "video_url": "...", "original_count": 1347}` |
| `GET` | `/api/v1/recount/status` | Polling progres terkini & hasil akhir | `{"status": "PROCESSING", "progress": 45, "current_count": 612}` |
| `POST` | `/api/v1/recount/stop` | Membatalkan job yang sedang berjalan | `{"success": true}` |
| `GET` | `/api/v1/recount/live-frame`| Mengambil snapshot JPEG teranotasi terbaru | `image/jpeg` (dari buffer memori) |
| `GET` | `/media/<filename>` | Menyajikan file MP4 video hasil recount | `video/mp4` (mendukung `Accept-Ranges: bytes`) |
### B. NanoPi 1 (Reverse Proxy & Dashboard — Port 5000)
Meneruskan permintaan dari browser ke NanoPi 2 dan mengelola persistensi data ke SQLite.
| Method | Endpoint NanoPi 1 | Target di NanoPi 2 |
| :--- | :--- | :--- |
| `POST` | `/api/v1/recount/start` | Forward ke `http://192.168.192.16:8765/api/v1/recount/start` |
| `GET` | `/api/v1/recount/status` | Polling internal & sinkronisasi database |
| `POST` | `/api/v1/recount/stop` | Forward ke `http://192.168.192.16:8765/api/v1/recount/stop` |
| `GET` | `/api/v1/recount/live-frame`| Proxy stream frame tunggal dari NanoPi 2 |
| `GET` | `/api/v1/recount/live-video`| Multipart MJPEG generator dari snapshot NanoPi 2 |
| `GET` | `/api/v1/recount/video/<file>`| Chunked Range proxy untuk pemutaran video MP4 |
---
## 3. Alur Siklus Hidup Eksekusi (Lifecycle Sequence)
```mermaid
sequenceDiagram
autonumber
actor User as Browser Klien
participant N1 as NanoPi 1 (Dashboard)
participant N2 as NanoPi 2 (Recount Engine)
participant Storage as MotionEye Storage
User->>N1: POST /api/v1/recount/start (batch_id)
N1->>N1: Ambil video_url dari DB SQLite
N1->>N2: POST /api/v1/recount/start (batch_id, video_url)
N2-->>N1: 200 OK {"status": "PROCESSING"}
N1-->>User: 200 OK {"status": "PROCESSING"}
Note over N2,Storage: N2 membaca/download video dari Storage & mulai inferensi
N2->>Storage: GET /files/<batch_id>
loop Saat Proses Berjalan
User->>N1: GET /api/v1/recount/status
N1->>N2: GET /api/v1/recount/status
N2-->>N1: {"status": "PROCESSING", "progress": 45, "current_count": 612}
N1-->>User: Status JSON
User->>N1: GET /api/v1/recount/live-video (MJPEG)
N1->>N2: GET /api/v1/recount/live-frame (Snapshot)
N2-->>N1: image/jpeg
N1-->>User: multipart frame
end
Note over N2: Render MP4 selesai + Faststart Remux
N2->>N2: Set status = "COMPLETED"
User->>N1: GET /api/v1/recount/status
N1->>N2: GET /api/v1/recount/status
N2-->>N1: {"status": "COMPLETED", "recount_count": 1350, "delta": 3, "video_url": "..."}
N1->>N1: UPDATE batches SET recount_count=1350, recount_delta=3 WHERE ...
N1-->>User: {"status": "COMPLETED", ...}
User->>N1: GET /api/v1/recount/video/batch_X_recount.mp4 (Replay)
N1->>N2: GET /media/batch_X_recount.mp4 (Range forwarding)
N2-->>N1: 206 Partial Content
N1-->>User: Video Stream (Playback Halus)
```
---
## 4. Panduan Adaptasi untuk Sistem Lain (Adaptation Blueprint)
Gunakan blueprint berikut untuk mengimplementasikan sistem serupa pada 2 mesin edge (misal: Raspberry Pi, NanoPi, Jetson, atau Mini PC).
### Langkah 1: Implementasi Worker Node (Node 2)
Buat service API minimal (`worker_engine.py`):
```python
import threading
import time
from pathlib import Path
from flask import Flask, request, jsonify, send_from_directory, Response
app = Flask(__name__)
OUTPUT_DIR = Path("/opt/app/output")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
state = {
"status": "IDLE",
"progress": 0,
"current_count": 0,
"recount_count": None,
"delta": None,
"video_url": None,
"error": None
}
_cancel_event = threading.Event()
_latest_frame_jpeg = None
_lock = threading.Lock()
def _worker_thread(batch_id, video_url, original_count):
global _latest_frame_jpeg
try:
# 1. Buka stream video (cv2.VideoCapture)
# 2. Loop inferensi frame-by-frame
total_frames = 1000
count = 0
for f in range(total_frames):
if _cancel_event.is_set():
with _lock:
state["status"] = "IDLE"
state["error"] = "Dibatalkan"
return
# --- Proses AI & Anotasi Frame ---
count += 1
progress = int((f / total_frames) * 100)
# Update snapshot JPEG untuk live preview
# _, jpeg = cv2.imencode(".jpg", annotated_frame)
# with _lock: _latest_frame_jpeg = jpeg.tobytes()
with _lock:
state["progress"] = progress
state["current_count"] = count
time.sleep(0.01) # Simulasi komputasi
# 3. Finalisasi video MP4 dengan FFmpeg faststart
out_name = f"result_{batch_id}.mp4"
# subprocess.run(["ffmpeg", "-y", "-i", tmp, "-c", "copy", "-movflags", "+faststart", OUTPUT_DIR / out_name])
with _lock:
state["status"] = "COMPLETED"
state["progress"] = 100
state["recount_count"] = count
state["delta"] = count - original_count
state["video_url"] = f"http://192.168.1.50:8765/media/{out_name}"
except Exception as exc:
with _lock:
state["status"] = "IDLE"
state["error"] = str(exc)
@app.post("/api/v1/recount/start")
def start():
data = request.json or {}
if state["status"] == "PROCESSING":
return jsonify({"success": False, "error": "Sedang berjalan"}), 409
_cancel_event.clear()
state.update({"status": "PROCESSING", "progress": 0, "error": None})
t = threading.Thread(
target=_worker_thread,
args=(data["batch_id"], data["video_url"], data.get("original_count", 0)),
daemon=True
)
t.start()
return jsonify({"success": True})
@app.get("/api/v1/recount/status")
def get_status():
with _lock:
return jsonify(state)
@app.post("/api/v1/recount/stop")
def stop():
_cancel_event.set()
return jsonify({"success": True})
@app.get("/api/v1/recount/live-frame")
def live_frame():
with _lock:
if _latest_frame_jpeg is None:
return "No frame", 404
return Response(_latest_frame_jpeg, mimetype="image/jpeg")
@app.get("/media/<path:filename>")
def serve_media(filename):
# conditional=True WAJIB agar HTTP Range requests didukung
return send_from_directory(OUTPUT_DIR, filename, mimetype="video/mp4", conditional=True)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8765, threaded=True)
```
---
### Langkah 2: Implementasi Dispatcher / Proxy (Node 1)
Tambahkan reverse proxy dan sinkronisasi database pada controller utama (`dispatcher_app.py`):
```python
import urllib.request
import json
import threading
import time
from flask import Flask, jsonify, request, Response
app = Flask(__name__)
WORKER_URL = "http://192.168.1.50:8765"
def _http_json(method, url, payload=None):
req = urllib.request.Request(
url,
data=json.dumps(payload).encode() if payload else None,
headers={"Content-Type": "application/json"} if payload else {},
method=method
)
with urllib.request.urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode())
def _poll_worker_until_complete(batch_id):
while True:
data = _http_json("GET", f"{WORKER_URL}/api/v1/recount/status")
if data.get("status") == "COMPLETED":
# Simpan hasil akhir ke Database lokal
# db.execute("UPDATE batches SET recount=? WHERE id=?", (data["recount_count"], batch_id))
break
elif data.get("status") == "IDLE":
break
time.sleep(1.0)
@app.post("/api/v1/recount/start")
def recount_start():
batch_id = request.json.get("batch_id")
# Ambil URL video dari DB
video_url = f"http://192.168.1.200:8090/files/{batch_id}"
res = _http_json("POST", f"{WORKER_URL}/api/v1/recount/start", {
"batch_id": batch_id,
"video_url": video_url,
"original_count": 100
})
# Jalankan background watcher untuk sinkronisasi DB
threading.Thread(target=_poll_worker_until_complete, args=(batch_id,), daemon=True).start()
return jsonify(res)
@app.get("/api/v1/recount/status")
def recount_status():
return jsonify(_http_json("GET", f"{WORKER_URL}/api/v1/recount/status"))
@app.route("/api/v1/recount/video/<path:filename>")
def proxy_video(filename):
"""Chunked proxy forwarding Range header for fast HTML5 video seeking."""
remote_url = f"{WORKER_URL}/media/{filename}"
req = urllib.request.Request(remote_url)
if "Range" in request.headers:
req.add_header("Range", request.headers["Range"])
upstream = urllib.request.urlopen(req)
headers = {
"Accept-Ranges": "bytes",
"Content-Type": upstream.headers.get("Content-Type", "video/mp4"),
}
if "Content-Range" in upstream.headers:
headers["Content-Range"] = upstream.headers["Content-Range"]
if "Content-Length" in upstream.headers:
headers["Content-Length"] = upstream.headers["Content-Length"]
def stream():
while chunk := upstream.read(256 * 1024):
yield chunk
return Response(stream(), status=upstream.status, headers=headers)
```
---
## 5. Checklist Kunci Keberhasilan (Engineering Best Practices)
1. **Gunakan RAM Disk (`/dev/shm`) untuk Cache & Frame**:
- Tulis frame JPEG sementara dan video buffer di `/dev/shm` untuk mencegah keausan flash memory (MicroSD/eMMC) akibat penulisan I/O berkecepatan tinggi.
2. **Optimasi Pemutaran Video (`+faststart`)**:
- Selalu atur flag container MP4: `ffmpeg -movflags +faststart`.
- Ini memindahkan metadata indeks (*moov atom*) ke awal file, sehingga browser dapat langsung memutar video secara instan tanpa menunggu seluruh file selesai diunduh.
3. **Dukungan `Accept-Ranges: bytes`**:
- Endpoint media wajib melayani *HTTP Range Requests* (Status HTTP `206 Partial Content`).
- Tanpa ini, fitur seeking / slider video di browser akan macet atau gagal diputar.
4. **Otomatisasi Deployment Tunggal (Single-Command Deploy)**:
- Buat script bash berbasis SSH ControlMaster untuk mentransfer file tarball kode langsung ke Worker Node, menginstal dependensi, dan merestart service systemd dalam satu perintah.
- Contoh: [`scripts/deploy-recount-to-nanopi2.sh`](file:///opt/apc-ngoro/scripts/deploy-recount-to-nanopi2.sh).
5. **Auto-Cleanup / Retensi File Sementara**:
- Tetapkan cron job atau thread pembersih berkala untuk menghapus file video recount lama (misal berumur > 6 jam) di Worker Node agar kapasitas disk tidak penuh.
---
## 6. Komunikasi & Transfer Data Tanpa Password (Passwordless Setup)
Agar sistem dapat berjalan sepenuhnya otomatis tanpa intervensi manual (misalnya tidak ada prompt password yang memblokir cron job, background task, atau script deployment), terdapat dua lapisan konfigurasi tanpa password yang diterapkan:
---
### A. Lapisan Aplikasi / Runtime: HTTP REST & Token-Based Auth (Zero-Password by Design)
Saat sistem sedang beroperasi melayani penghitungan (*runtime*), **tidak ada penggunaan password SSH ataupun akun OS**.
Transfer data dilakukan murni menggunakan protokol HTTP berbasis port lokal:
1. **Transfer Video Otomatis**:
- Node 1 mengunggah video batch ke Storage/MotionEye via HTTP `multipart/form-data` (`POST /upload`).
- Node 2 mengunduh video sumber dari Storage via HTTP stream (`GET /files/<batch_id>`).
- Browser klien memutar video recount melalui reverse proxy Node 1 (`GET /api/v1/recount/video/<file>`).
2. **Keamanan Tanpa Password Interaktif**:
- **Shared API Token**: Header `X-Ingest-Token: <secret-token>` dilekatkan pada request HTTP untuk memastikan hanya Node resmi yang dapat mengunggah atau menghapus file.
- **Jaringan Terisolasi (Isolated Subnet / VPN)**: Service hanya di-bind pada IP LAN privat atau ZeroTier VPN (`192.168.192.0/24`), sehingga perangkat luar tidak dapat mengakses endpoint internal.
---
### B. Lapisan Sistem & Deployment: SSH Key-Based Authentication
Untuk kebutuhan deployment, sinkronisasi file sistem (*rsync/scp*), dan manajemen service (*systemctl*) antar-node tanpa prompt password:
#### 1. Generate SSH Keypair di Node 1 (Primary)
Jalankan perintah berikut di Node 1 untuk membuat public/private key tanpa passphrase:
```bash
# Buat key ed25519 modern dan cepat (tanpa passphrase: -N "")
ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519
```
#### 2. Pasang Public Key ke Node 2 (Worker) dan Storage Server
Salin public key dari Node 1 ke Node 2 (hanya perlu memasukkan password 1 kali saat inisialisasi):
```bash
# Cara otomatis (jika ssh-copy-id tersedia):
ssh-copy-id -i ~/.ssh/id_ed25519.pub root@192.168.192.16
# Atau cara manual (menempelkan public key ke authorized_keys):
cat ~/.ssh/id_ed25519.pub | ssh root@192.168.192.16 "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
```
#### 3. Uji Coba Passwordless SSH & Rsync
Setelah public key terpasang, perintah berikut dapat dieksekusi langsung tanpa prompt password:
```bash
# Uji eksekusi remote command:
ssh root@192.168.192.16 "hostname && uptime"
# Uji transfer file tanpa password via rsync:
rsync -avz /opt/apc-ngoro/recount_engine/ root@192.168.192.16:/opt/apc-ngoro/recount_engine/
```
#### 4. Konfigurasi Sudo Tanpa Password (Khusus User Non-Root)
Jika SSH login menggunakan user biasa (misalnya `support` atau `ubuntu`), service restart (`sudo systemctl restart ...`) akan meminta password sudo. Solusinya, tambahkan rule `NOPASSWD` di `/etc/sudoers.d/`:
```bash
# Di Node 2, jalankan sekali sebagai root:
echo "support ALL=(ALL) NOPASSWD: /bin/systemctl, /bin/mkdir, /bin/cp, /bin/rm" | sudo tee /etc/sudoers.d/apc-automation
sudo chmod 0440 /etc/sudoers.d/apc-automation
```
---
### C. Teknik Lanjutan: SSH ControlMaster (Koneksi Multiplexing)
Jika Anda belum sempat menyalin SSH key permanen atau kebijakan keamanan mewajibkan login dengan kredensial tertentu, gunakan teknik **SSH ControlMaster**. Teknik ini membuka satu *master session* (meminta password 1 kali), lalu semua perintah `scp`, `ssh`, dan `rsync` berikutnya memakai socket master tersebut tanpa meminta password lagi:
```bash
#!/usr/bin/env bash
HOST="192.168.192.16"
USER="root"
CONTROL_PATH="/tmp/cm-%r@%h:%p"
# 1. Buka Master Connection di background (Minta password 1 kali saja)
ssh -MNf -o ControlMaster=yes -o ControlPersist=120 -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}"
# 2. Semua transfer & command berikutnya otomatis memakai socket yang sama (TANPA PASSWORD)
scp -o ControlPath="$CONTROL_PATH" package.tgz "${USER}@${HOST}:/tmp/"
ssh -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}" "tar -xzf /tmp/package.tgz -C /opt/app && systemctl restart app"
# 3. Tutup master connection setelah selesai
ssh -O exit -o ControlPath="$CONTROL_PATH" "${USER}@${HOST}" 2>/dev/null || true
```
> Pola ini digunakan secara nyata pada script [`scripts/deploy-recount-to-nanopi2.sh`](file:///opt/apc-ngoro/scripts/deploy-recount-to-nanopi2.sh) dan [`scripts/deploy-motioneye-ingest.sh`](file:///opt/apc-ngoro/scripts/deploy-motioneye-ingest.sh).
---
### Ringkasan Pilihan Metode Transfer Data Tanpa Password
| Metode | Digunakan Untuk | Mekanisme Otentikasi | Keunggulan |
| :--- | :--- | :--- | :--- |
| **HTTP REST + Streaming** | Runtime Counting, Progress Polling, Live JPEG, MP4 Replay | Shared Header Token / Private Subnet | Sangat cepat, non-blocking, terisolasi dalam web stack |
| **SSH Key (Ed25519)** | Deployment Otomatis, Cron Job Sync, Remote Scripting | Asymmetric Cryptography (`authorized_keys`) | Standar industri Linux, zero-interaction, sangat aman |
| **SSH ControlMaster** | Script Deployment Satu Perintah (*One-click deploy*) | Socket Multiplexing (1 prompt $\rightarrow$ multi actions) | Tidak perlu konfigurasi awal SSH key di remote server |
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Install systemd services for ZenAI APC Ngoro
set -euo pipefail
INSTALL_DIR="${INSTALL_DIR:-/opt/apc-ngoro}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ ! -f "$INSTALL_DIR/.env" ]; then
echo "WARNING: $INSTALL_DIR/.env not found."
echo "Copy config.env.example to .env and configure before starting services:"
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
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"
+122
View File
@@ -0,0 +1,122 @@
"""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
+151
View File
@@ -0,0 +1,151 @@
#!/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+$")
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)
+731
View File
@@ -0,0 +1,731 @@
#!/usr/bin/env python3
"""
NanoPi 2 recount engine — process batch videos with RKNN + ByteTrack,
emit progress over HTTP, render annotated output video.
RKNN model is loaded once at process start and reused for every job.
"""
from __future__ import annotations
import atexit
import os
import re
import subprocess
import sys
import threading
import time
from pathlib import Path
from urllib.request import urlretrieve
from dotenv import load_dotenv
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))
load_dotenv(_ROOT / ".env")
from collections import deque
from counter_live_rknn_bytetrack import ( # noqa: E402
C_AYAM_BOX,
C_GREEN,
COUNT_PULSE_FRAMES,
CROSS_FLASH_FRAMES,
LINE_PULSE_FRAMES,
POPUP_LIFETIME,
ByteTracker,
RKNNYOLO,
crossed_line,
draw_batch_banner,
draw_elegant_counting_line,
draw_footer,
draw_hero_count,
draw_hud,
draw_pill,
draw_popups,
draw_skeleton_bold,
)
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)
PUBLIC_BASE = os.getenv("RECOUNT_PUBLIC_BASE", f"http://127.0.0.1:{PORT}").rstrip("/")
MODEL_PATH = os.getenv("MODEL_PATH", "/opt/models/zenai_apc_ngoro_20260908.rknn")
IMGSZ = int(os.getenv("IMGSZ", "320"))
CONF = float(os.getenv("CONF", "0.22"))
IOU = float(os.getenv("IOU", "0.40"))
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.535"))
LINE_ZONE_WIDTH = int(os.getenv("LINE_ZONE_WIDTH", "80"))
LINE_ZONE_Y_START_FRAC = float(os.getenv("LINE_ZONE_Y_START_FRAC", "0.5"))
LINE_ZONE_Y_END_FRAC = float(os.getenv("LINE_ZONE_Y_END_FRAC", "1.0"))
CROSS_DIRECTION = os.getenv("CROSS_DIRECTION", "ltr").lower()
AYAM_CLASS_ID = int(os.getenv("AYAM_CLASS_ID", "0"))
TRACK_HIGH = float(os.getenv("TRACK_HIGH_THRESH_0", "0.38"))
TRACK_LOW = float(os.getenv("TRACK_LOW_THRESH_0", "0.05"))
TRACK_MATCH = float(os.getenv("TRACK_MATCH_THRESH_0", "0.25"))
# Align tracker with live ayam defaults (TRACK_BUFFER_0 / TRACK_MIN_HITS_0)
TRACK_BUFFER = int(os.getenv("RECOUNT_TRACK_BUFFER", os.getenv("TRACK_BUFFER_0", "30")))
TRACK_MIN_HITS = int(os.getenv("RECOUNT_MIN_HITS", os.getenv("TRACK_MIN_HITS_0", "1")))
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"))
)
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+$")
_lock = threading.Lock()
_cancel = threading.Event()
_thread = None
_live_frame_lock = threading.Lock()
_live_jpeg = None # latest annotated JPEG bytes
_state = {
"status": "IDLE",
"progress": 0,
"current_count": 0,
"recount_count": None,
"delta": None,
"batch_id": None,
"original_count": 0,
"video_url": None,
"error": None,
}
# Single shared RKNN runtime — load once, reuse forever
_model = None
_model_lock = threading.Lock()
_model_error = None
def _set_state(**kwargs):
with _lock:
_state.update(kwargs)
def _get_state():
with _lock:
return dict(_state)
def _load_model_once():
"""Load RKNN 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):
raise RuntimeError(_model_error)
print(f"[recount] Loading RKNN once: {MODEL_PATH}", flush=True)
t0 = time.time()
try:
_model = RKNNYOLO(
model_path=MODEL_PATH,
core_mask=CORE_MASK,
imgsz=IMGSZ,
conf=CONF,
iou=IOU,
num_classes=NUM_CLASSES,
score_sigmoid=SCORE_SIGMOID,
)
_model_error = None
print(f"[recount] Model ready 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)
raise
return _model
def _release_model():
global _model
with _model_lock:
if _model is not None:
try:
_model.release()
except Exception:
pass
_model = None
atexit.register(_release_model)
def _publish_live_frame(frame_bgr):
"""Encode annotated frame for MJPEG clients (downscaled for bandwidth)."""
import cv2
global _live_jpeg
view = frame_bgr
h0, w0 = view.shape[:2]
if LIVE_FRAME_MAX_WIDTH > 0 and w0 > LIVE_FRAME_MAX_WIDTH:
scale = LIVE_FRAME_MAX_WIDTH / float(w0)
view = cv2.resize(
view,
(LIVE_FRAME_MAX_WIDTH, max(1, int(h0 * scale))),
interpolation=cv2.INTER_AREA,
)
ok, buf = cv2.imencode(
".jpg", view, [int(cv2.IMWRITE_JPEG_QUALITY), LIVE_JPEG_QUALITY]
)
if not ok:
return
data = buf.tobytes()
with _live_frame_lock:
_live_jpeg = data
try:
LIVE_FRAME_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp = LIVE_FRAME_PATH.with_suffix(".jpg.tmp")
tmp.write_bytes(data)
tmp.replace(LIVE_FRAME_PATH)
except Exception:
pass
def _get_live_jpeg():
with _live_frame_lock:
if _live_jpeg:
return _live_jpeg
if LIVE_FRAME_PATH.is_file():
try:
return LIVE_FRAME_PATH.read_bytes()
except Exception:
return None
return None
def _clear_live_frame():
"""Drop stale JPEG so UI does not flash the previous batch."""
global _live_jpeg
with _live_frame_lock:
_live_jpeg = None
try:
LIVE_FRAME_PATH.unlink(missing_ok=True)
except Exception:
pass
def _probe_duration_sec(path: Path) -> float:
"""Prefer ffprobe format duration (reflects restamped timestamps)."""
try:
out = subprocess.check_output(
[
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
str(path),
],
text=True,
timeout=30,
).strip()
val = float(out)
return val if val > 0 else 0.0
except Exception:
return 0.0
def _download(url: str, dest: Path):
dest.parent.mkdir(parents=True, exist_ok=True)
urlretrieve(url, str(dest))
def _probe_video_codec(path: Path) -> str:
try:
out = subprocess.check_output(
[
"ffprobe",
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=codec_name",
"-of",
"default=nw=1:nk=1",
str(path),
],
timeout=30,
)
return (out.decode("utf-8", errors="replace") or "").strip().lower()
except Exception:
return ""
def _ensure_browser_mp4(path: Path):
"""
Ensure recount output plays in Chrome/Edge: H.264 + yuv420p + faststart.
mp4v/mpeg4 from OpenCV is not reliably playable in browsers.
"""
if not path.is_file():
return
ffmpeg = os.getenv("FFMPEG_BIN", "ffmpeg")
codec = _probe_video_codec(path)
tmp = path.with_suffix(".h264.mp4")
need_transcode = codec not in ("h264", "avc1", "avc")
try:
if need_transcode:
print(f"[recount] transcoding {path.name} ({codec or '?'}) → h264", flush=True)
subprocess.run(
[
ffmpeg,
"-y",
"-i",
str(path),
"-an",
"-c:v",
"libx264",
"-preset",
"veryfast",
"-crf",
"23",
"-pix_fmt",
"yuv420p",
"-movflags",
"+faststart",
str(tmp),
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=1800,
)
else:
subprocess.run(
[
ffmpeg,
"-y",
"-i",
str(path),
"-c",
"copy",
"-movflags",
"+faststart",
str(tmp),
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=600,
)
if tmp.is_file() and tmp.stat().st_size > 1000:
tmp.replace(path)
print(f"[recount] browser mp4 ready: {path.name}", flush=True)
else:
tmp.unlink(missing_ok=True)
except Exception as exc:
print(f"[recount] browser mp4 skipped: {exc}", flush=True)
tmp.unlink(missing_ok=True)
def _run_job(batch_id: str, video_url: str, original_count: int):
import cv2
import numpy as np
_cancel.clear()
local_in = OUTPUT_DIR / f"_src_{batch_id}.mp4"
out_name = f"batch_{batch_id}_recount.mp4"
local_out = OUTPUT_DIR / out_name
try:
_clear_live_frame()
_set_state(
status="PROCESSING",
progress=0,
current_count=RECOUNT_START_COUNT,
recount_count=None,
delta=None,
batch_id=batch_id,
original_count=original_count,
video_url=None,
error=None,
)
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:
# Reuse cached source when present — avoid re-download every Mulai
if local_in.is_file() and local_in.stat().st_size > 0:
print(f"[recount] using cached source {local_in}", flush=True)
else:
print(f"[recount] downloading source {video_url}", flush=True)
_download(video_url, local_in)
cap = cv2.VideoCapture(str(local_in))
if not cap.isOpened():
raise RuntimeError(f"Cannot open video: {local_in}")
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
fps_meta = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) or 15.0
duration = _probe_duration_sec(local_in)
if duration <= 0 and total > 0 and fps_meta > 0:
duration = total / fps_meta
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 1280)
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 720)
line_x = int(w * LINE_X_FRAC)
fps = fps_meta
writer = cv2.VideoWriter(
str(local_out),
cv2.VideoWriter_fourcc(*"mp4v"),
max(fps, 1.0),
(w, h),
)
# Fresh tracker per job; model stays warm
tracker = ByteTracker(
track_high_thresh=TRACK_HIGH,
track_low_thresh=TRACK_LOW,
match_thresh=TRACK_MATCH,
track_buffer=TRACK_BUFFER,
min_hits=TRACK_MIN_HITS,
)
tracked = {}
crossed = set()
cross_flash = {}
popups = []
crossing_times = deque()
session_start = time.time()
inf_ms = 0.0
count = RECOUNT_START_COUNT
frame_idx = 0
line_pulse = 0
count_pulse = 0
last_frame = None
asap = PLAYBACK_SPEED <= 0
if asap:
frame_period = 0.0
mode = "asap"
else:
speed = PLAYBACK_SPEED
if total > 0 and duration > 0:
frame_period = (duration / float(total)) / speed
else:
frame_period = 1.0 / (max(fps_meta, 1.0) * speed)
mode = "paced"
print(
f"[recount] job {batch_id} mode={mode} fps_meta={fps_meta:.2f} "
f"frames≈{total} duration={duration:.1f}s "
f"min_hits={TRACK_MIN_HITS} track_buffer={TRACK_BUFFER} "
f"line_x={line_x} period={frame_period*1000:.1f}ms",
flush=True,
)
def _register_cross(tid, cx, bbox):
nonlocal count, line_pulse, count_pulse
if tid in crossed:
return False
crossed.add(tid)
count += 1
line_pulse = LINE_PULSE_FRAMES
count_pulse = COUNT_PULSE_FRAMES
cross_flash[tid] = CROSS_FLASH_FRAMES
crossing_times.append(time.monotonic())
popups.append(
{
"x": int(cx) - 12,
"y": int((bbox[1] + bbox[3]) / 2),
"born": frame_idx,
"text": "+1",
}
)
return True
while True:
if _cancel.is_set():
_set_state(status="IDLE", progress=0, error="Dibatalkan", video_url=None)
break
loop_t0 = time.monotonic()
ret, frame = cap.read()
if not ret:
break
frame_idx += 1
if line_pulse > 0:
line_pulse -= 1
if count_pulse > 0:
count_pulse -= 1
with _model_lock:
inf_start = time.time()
detections = model(frame)
inf_ms = inf_ms * 0.9 + (time.time() - inf_start) * 1000 * 0.1
boxes, scores, kpts_list = [], [], []
for det in detections:
if int(det["cls"]) != AYAM_CLASS_ID:
continue
boxes.append(det["bbox"])
scores.append(det["score"])
kpts_list.append(det.get("keypoints"))
if boxes:
boxes_arr = np.array(boxes, dtype=np.float32)
scores_arr = np.array(scores, dtype=np.float32)
tracked_map, det_to_track, lost_map = tracker.update(boxes_arr, scores_arr)
else:
tracked_map, det_to_track, lost_map = tracker.update(
np.zeros((0, 4), dtype=np.float32),
np.zeros((0,), dtype=np.float32),
)
for di, bbox in enumerate(boxes):
tid = det_to_track.get(di)
if tid is None:
continue
x1, y1, x2, y2 = map(int, bbox)
cx = (bbox[0] + bbox[2]) / 2.0
cy = (bbox[1] + bbox[3]) / 2.0
prev_cx = tracked.get(tid)
if crossed_line(
prev_cx,
cx,
line_x,
CROSS_DIRECTION,
LINE_ZONE_WIDTH,
cy=cy,
frame_height=h,
y_start_frac=LINE_ZONE_Y_START_FRAC,
y_end_frac=LINE_ZONE_Y_END_FRAC,
):
_register_cross(tid, cx, bbox)
tracked[tid] = cx
flash = cross_flash.get(tid, 0)
color = C_GREEN if flash > 0 else C_AYAM_BOX
thickness = 3 if flash > 0 else 2
cv2.rectangle(frame, (x1, y1), (x2, y2), color, thickness)
draw_pill(frame, f"ID {tid}", x1, y1 - 4, color)
kpts = kpts_list[di] if di < len(kpts_list) else None
if kpts is not None:
draw_skeleton_bold(frame, kpts)
# Match live: seed lost tracks only if unseen — never count on Kalman cross
for tid, lost_cx in lost_map.items():
if tid not in tracked:
tracked[tid] = lost_cx
# Calculate crossing rate over last 60 seconds
mono_now = time.monotonic()
while crossing_times and mono_now - crossing_times[0] > 60:
crossing_times.popleft()
rate = (len(crossing_times) / 60.0 * 60) if crossing_times else 0.0
elapsed = time.time() - session_start
draw_elegant_counting_line(
frame,
line_x,
h,
line_pulse,
CROSS_DIRECTION,
LINE_ZONE_WIDTH,
LINE_ZONE_Y_START_FRAC,
LINE_ZONE_Y_END_FRAC,
)
draw_hero_count(frame, line_x, h, count, count_pulse)
# Draw detailed top HUD, footer, and floating popups
batch_num = batch_id.split("-")[-1] if "-" in str(batch_id) else batch_id
draw_hud(frame, w, batch_num, count, count, elapsed, rate)
draw_footer(
frame,
w,
h,
frame_idx,
"RECOUNT",
inf_ms,
Path(MODEL_PATH).name,
)
popups = draw_popups(frame, popups, frame_idx)
for tid in list(cross_flash):
cross_flash[tid] -= 1
if cross_flash[tid] <= 0:
del cross_flash[tid]
writer.write(frame)
last_frame = frame
if frame_idx % LIVE_FRAME_EVERY_N == 0 or frame_idx == 1:
_publish_live_frame(frame)
if frame_idx % PROGRESS_EVERY_N == 0 or (total and frame_idx >= total):
if total > 0:
progress = min(99, int(round(frame_idx * 100 / total)))
else:
progress = min(99, frame_idx % 100)
_set_state(progress=progress, current_count=count)
if not asap and frame_period > 0:
elapsed = time.monotonic() - loop_t0
remain = frame_period - elapsed
if remain > 0.001:
if _cancel.wait(timeout=remain):
_set_state(status="IDLE", progress=0, error="Dibatalkan", video_url=None)
break
elif _cancel.is_set():
_set_state(status="IDLE", progress=0, error="Dibatalkan", video_url=None)
break
if last_frame is not None and not _cancel.is_set():
_publish_live_frame(last_frame)
cap.release()
writer.release()
if _cancel.is_set():
local_out.unlink(missing_ok=True)
return
# Stay PROCESSING until browser MP4 is ready (UI may show 99% finalize).
_set_state(progress=99, current_count=count)
print(f"[recount] finalizing browser MP4 {local_out}", flush=True)
_ensure_browser_mp4(local_out)
delta = count - original_count
video_public = f"{PUBLIC_BASE}/media/{out_name}"
print(
f"[recount] done {batch_id} count={count} delta={delta:+d}",
flush=True,
)
_set_state(
status="COMPLETED",
progress=100,
current_count=count,
recount_count=count,
delta=delta,
video_url=video_public,
error=None,
)
except Exception as exc:
_set_state(status="IDLE", progress=0, error=str(exc), video_url=None)
# Keep _src_{batch_id}.mp4 on disk for fast re-runs
@app.get("/health")
def health():
return jsonify(
{
"ok": True,
"model": MODEL_PATH,
"model_loaded": _model is not None,
"model_error": _model_error,
"output_dir": str(OUTPUT_DIR),
"overlay": "live",
"playback_speed": PLAYBACK_SPEED,
"mode": "asap" if PLAYBACK_SPEED <= 0 else "paced",
"start_count": RECOUNT_START_COUNT,
"min_hits": TRACK_MIN_HITS,
"track_buffer": TRACK_BUFFER,
"line_x_frac": LINE_X_FRAC,
}
)
@app.post("/api/v1/recount/start")
def start():
global _thread
data = request.get_json(silent=True) or {}
batch_id = (data.get("batch_id") or "").strip()
video_url = (data.get("video_url") or "").strip()
original_count = int(data.get("original_count") or 0)
if not BATCH_ID_RE.match(batch_id):
return jsonify({"success": False, "error": "invalid batch_id"}), 400
if not video_url:
return jsonify({"success": False, "error": "video_url required"}), 400
st = _get_state()
if st.get("status") == "PROCESSING":
return jsonify({"success": False, "error": "Recount sedang berjalan"}), 409
# Model must already be warm from service start; only load if somehow missing
if _model is None:
try:
_load_model_once()
except Exception as exc:
return jsonify({"success": False, "error": f"Model belum siap: {exc}"}), 503
_thread = threading.Thread(
target=_run_job, args=(batch_id, video_url, original_count), daemon=True
)
_thread.start()
return jsonify(
{
"success": True,
"batch_id": batch_id,
"original_count": original_count,
"status": "PROCESSING",
"model_loaded": _model is not None,
}
)
@app.get("/api/v1/recount/status")
def status():
payload = _get_state()
payload["success"] = True
payload["model_loaded"] = _model is not None
return jsonify(payload)
@app.post("/api/v1/recount/stop")
def stop():
st = _get_state()
if st.get("status") != "PROCESSING":
return jsonify({"success": True, "message": "Tidak ada job aktif", "status": st.get("status")})
_cancel.set()
return jsonify({"success": True, "message": "Pembatalan diminta"})
@app.get("/api/v1/recount/live-frame")
def live_frame():
"""Latest annotated JPEG for MJPEG clients (operational-style)."""
data = _get_live_jpeg()
if not data:
return jsonify({"success": False, "error": "live frame not available"}), 503
return Response(data, mimetype="image/jpeg")
@app.get("/media/<path:filename>")
def media(filename: str):
if ".." in filename or "/" in filename:
return jsonify({"error": "invalid"}), 400
path = OUTPUT_DIR / filename
if not path.is_file():
return jsonify({"error": "not found"}), 404
return send_from_directory(OUTPUT_DIR, filename, mimetype="video/mp4", conditional=True)
if __name__ == "__main__":
print(f"Recount engine http://{HOST}:{PORT}")
print(f"Model: {MODEL_PATH}")
print(f"Live frame: {LIVE_FRAME_PATH}")
try:
_load_model_once()
except Exception as exc:
print(f"WARNING: model preload failed ({exc}) — will retry on first job")
app.run(host=HOST, port=PORT, threaded=True)
+7
View File
@@ -0,0 +1,7 @@
numpy<2
rknn-toolkit-lite2
opencv-python
flask
python-dotenv
openpyxl
requests
+33
View File
@@ -0,0 +1,33 @@
"""Helpers for retention policies based on active counting dates."""
from __future__ import annotations
import re
import sqlite3
BATCH_ID_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})-\d+$")
def active_counting_dates(conn: sqlite3.Connection, limit: int = 3, table: str = "batches") -> list[str]:
"""Return latest distinct counting dates that actually have rows."""
if table not in ("batches", "daily_summaries"):
raise ValueError("invalid table")
cur = conn.cursor()
cur.execute(
f"""
SELECT DISTINCT counting_date
FROM {table}
ORDER BY counting_date DESC
LIMIT ?
""",
(int(limit),),
)
return [row[0] for row in cur.fetchall()]
def batch_id_to_counting_date(batch_id: str) -> str | None:
"""Extract YYYY-MM-DD from a canonical batch id."""
m = BATCH_ID_RE.match((batch_id or "").strip())
if not m:
return None
return m.group(1)
+35
View File
@@ -0,0 +1,35 @@
#!/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
@@ -0,0 +1,27 @@
#!/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
@@ -0,0 +1,57 @@
#!/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
@@ -0,0 +1,75 @@
#!/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"
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Install active-day retention cron on NanoPi 1 and overlay cleanup cron on NanoPi 2.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
NP2_HOST="${NANOPI2_HOST:-192.168.192.16}"
NP2_USER="${NANOPI2_SSH_USER:-root}"
echo "==> Installing local NP1 retention cron"
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
EOF
sudo chmod 644 /etc/cron.d/apc-retention
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"
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}"
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# Run on NanoPi as root: sudo bash /home/agent/apc-ngoro-staging/scripts/deploy-to-opt.sh
set -euo pipefail
STAGING="${STAGING:-/home/agent/apc-ngoro-staging}"
DEST="${DEST:-/opt/apc-ngoro}"
echo "==> Deploy $STAGING -> $DEST"
mkdir -p "$DEST"
rsync -a "$STAGING/" "$DEST/"
if [[ ! -f "$DEST/.env" && -f "$DEST/config.env.example" ]]; then
cp "$DEST/config.env.example" "$DEST/.env"
sed -i 's/\r$//' "$DEST/.env" 2>/dev/null || true
echo "==> Created $DEST/.env from config.env.example — edit before production use"
fi
chmod +x "$DEST"/*.sh 2>/dev/null || true
chown -R root:root "$DEST"
echo "==> Done. Next: cd $DEST && bash setup-venv.sh && bash install-services.sh"
@@ -0,0 +1,3 @@
# 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
@@ -0,0 +1,7 @@
#!/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
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Delete stale recount overlay videos from NanoPi 2 output storage."""
from __future__ import annotations
import argparse
import os
import time
from pathlib import Path
from dotenv import load_dotenv
ROOT = Path(__file__).resolve().parents[1]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Delete stale recount overlay files.")
parser.add_argument("--dry-run", action="store_true", help="show what would be deleted")
return parser.parse_args()
def iter_candidates(output_dir: Path):
for pattern in ("batch_*_recount.mp4", "_src_*.mp4"):
yield from output_dir.glob(pattern)
def main() -> int:
load_dotenv(ROOT / ".env")
args = parse_args()
output_dir = Path(os.getenv("RECOUNT_OUTPUT_DIR", str(ROOT / "recount_output")))
ttl_hours = float(os.getenv("RECOUNT_OVERLAY_TTL_HOURS", "6"))
cutoff_ts = time.time() - (ttl_hours * 3600.0)
if not output_dir.is_dir():
print(f"Output dir missing: {output_dir}")
return 0
deleted = 0
kept = 0
freed_bytes = 0
for path in sorted(iter_candidates(output_dir)):
try:
st = path.stat()
except FileNotFoundError:
continue
if st.st_mtime > cutoff_ts:
kept += 1
continue
freed_bytes += st.st_size
if args.dry_run:
print(f"DRY-RUN delete {path.name} size={st.st_size}")
deleted += 1
continue
try:
path.unlink()
print(f"Deleted {path.name} size={st.st_size}")
deleted += 1
except FileNotFoundError:
pass
print(
f"Done: deleted={deleted} kept={kept} freed_bytes={freed_bytes} "
f"ttl_hours={ttl_hours:g} dry_run={'yes' if args.dry_run else 'no'}"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,58 @@
#!/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
@@ -0,0 +1,119 @@
#!/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)"
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Keep MotionEye batch videos for the latest active counting dates only."""
from __future__ import annotations
import argparse
import os
import sqlite3
import sys
from pathlib import Path
from dotenv import load_dotenv
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."
)
parser.add_argument("--dry-run", action="store_true", help="show deletions without removing files")
return parser.parse_args()
def main() -> int:
load_dotenv(ROOT / ".env")
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")))
if not db_path.is_file():
print(f"DB not found: {db_path}", file=sys.stderr)
return 1
conn = sqlite3.connect(str(db_path))
keep_dates = set(active_counting_dates(conn, limit=keep_days, table="batches"))
conn.close()
if not keep_dates:
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
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()
counting_date = batch_id_to_counting_date(batch_id)
if not counting_date or counting_date in keep_dates:
skipped += 1
continue
if args.dry_run:
print(f"DRY-RUN delete {batch_id} ({item.get('filename')})")
deleted += 1
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}")
except Exception as exc:
errors += 1
print(f"ERROR deleting {batch_id}: {exc}", file=sys.stderr)
print(
f"Done: candidate_deleted={deleted} skipped={skipped} errors={errors} "
f"dry_run={'yes' if args.dry_run else 'no'}"
)
return 0 if errors == 0 else 2
if __name__ == "__main__":
raise SystemExit(main())
+99
View File
@@ -0,0 +1,99 @@
# 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
Executable
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# Setup Python venv for RK3588 NanoPi (ZenAI APC Ngoro)
set -euo pipefail
INSTALL_DIR="${INSTALL_DIR:-/opt/apc-ngoro}"
cd "$INSTALL_DIR"
if [ ! -f requirements.txt ]; then
echo "ERROR: requirements.txt not found in $INSTALL_DIR"
exit 1
fi
echo "Creating venv with system-site-packages (required for rknn-toolkit-lite2)..."
python3 -m venv --system-site-packages venv
echo "Installing Python dependencies..."
PYTHONNOUSERSITE=1 venv/bin/pip install --upgrade pip
PYTHONNOUSERSITE=1 venv/bin/pip install -r requirements.txt
echo "Done. Activate with: source $INSTALL_DIR/venv/bin/activate"
echo "Remember to copy config.env.example to .env and edit device-specific values."
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1,0,0,1,-15369.154492,-1214.474821)">
<g transform="matrix(2.475521,0,0,1,13975.506392,1186.474821)">
<g transform="matrix(0.906181,0,0,2.243269,-3748.32663,-602.148875)">
<path d="M4914.259,451.079L4899.937,418.342C4890.938,397.773 4896.821,373.725 4914.3,359.634C4931.78,345.543 4956.528,344.897 4974.719,358.056L5091.331,442.412C5110.585,456.34 5118.613,481.126 5111.182,503.698C5103.75,526.269 5082.567,541.437 5058.804,541.202L5050.939,541.125L5073.639,592.72C5084.006,616.282 5076.598,643.883 5055.826,659.087C5035.054,674.292 5006.505,673.01 4987.178,656.006L4879.266,561.062C4859.513,543.682 4852.636,515.859 4862.018,491.278C4870.545,468.936 4890.872,453.546 4914.259,451.079ZM5024.451,523.597L5058.975,523.939C5075.22,524.099 5089.702,513.73 5094.783,498.299C5099.864,482.868 5094.375,465.923 5081.212,456.401L4964.6,372.045C4952.718,363.449 4936.553,363.872 4925.136,373.075C4913.719,382.279 4909.876,397.987 4915.754,411.422L4940.573,468.149L4938.895,468.131L4921.244,467.996C4902.142,467.85 4884.959,479.587 4878.147,497.434C4871.336,515.281 4876.329,535.482 4890.671,548.1L4998.583,643.045C5011.827,654.698 5031.393,655.576 5045.628,645.156C5059.864,634.736 5064.941,615.82 5057.836,599.673L5026.223,527.819L5024.451,523.597ZM4968.825,486.959L4968.329,485.718L4934.424,409.522C4931.427,402.786 4933.334,394.877 4939.071,390.247C4944.809,385.617 4952.942,385.424 4958.893,389.777L5066.605,468.558C5073.63,473.696 5076.548,482.773 5073.834,491.042C5071.119,499.312 5063.389,504.893 5054.686,504.868L4935.094,504.524C4929.238,504.507 4923.97,508.081 4921.821,513.529C4919.672,518.976 4921.081,525.184 4925.371,529.17L4933.661,536.872L4933.813,536.71C4931.614,534.38 4930.948,530.969 4932.148,527.964C4933.414,524.793 4936.498,522.727 4939.912,522.76L4965.007,523.009L4966.208,526.487L4994.023,589.707C4995.219,592.424 4996.967,594.863 4999.156,596.868L5011.424,608.101C5013.105,608.525 5014.94,608.223 5016.431,607.162C5018.776,605.494 5019.627,602.408 5018.468,599.773L4986.687,527.539L4984.872,523.205L5004.848,523.403L5006.718,528.303L5038.39,600.465C5042.406,609.614 5039.521,620.325 5031.454,626.221C5023.387,632.117 5012.306,631.612 5004.809,625.008L4906.732,538.616C4897.389,530.386 4894.151,517.211 4898.615,505.588C4903.08,493.964 4914.304,486.344 4926.755,486.484L4968.825,486.959ZM5010.315,487.427L5009.613,485.749L4990.183,439.967C4988.127,435.122 4984.795,430.926 4980.542,427.825L4965.157,416.607C4963.539,415.428 4961.33,415.49 4959.782,416.759C4958.234,418.027 4957.738,420.181 4958.576,421.999L4986.474,482.492L4988.527,487.181L5010.315,487.427Z" style="fill:white;"/>
</g>
<g transform="matrix(0.739983,0,0,1.831843,-7379.262587,-607.649374)">
<rect x="10733" y="347" width="559" height="559" style="fill:none;"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.3 KiB

+16
View File
@@ -0,0 +1,16 @@
[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
+36
View File
@@ -0,0 +1,36 @@
[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
+33
View File
@@ -0,0 +1,33 @@
[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
+16
View File
@@ -0,0 +1,16 @@
[Unit]
Description=ZenAI APC Ngoro Recount Engine (NanoPi 2)
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
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# 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 rm -f /etc/systemd/system/apc-ngoro-counter.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."