14 KiB
APC Ngoro — System Architecture, Business Logic & Single-Machine Migration Guide
1. Project Overview & Context
APC Ngoro (Automated Poultry Counter - Site Ngoro) is an edge AI computer-vision system designed for automated real-time poultry counting, batch consolidation, video recording, recounting validation, and operational reporting in slaughterhouse facilities.
Evolution & Physical Topology
- Legacy Split Topology:
- NanoPi 1 (Edge RK3588, ARM64): Real-time video ingestion, RKNN NPU YOLO detection (
ngoro-all-2.rknn), ByteTrack tracking, batch lifecycle management (batch_store.py), and Web Dashboard (counter_dashboard.pyon port5000). - NanoPi 2 (Edge RK3588, ARM64): Recount Engine (
recount_engine/app.pyon port8765) running offline video playback, ByteTrack tracking, and count verification. - MotionEye Ingest Server (
192.168.192.251:8090): HTTP ingest storage archiving completed batch.mp4videos in/data/media/Camera1.
- NanoPi 1 (Edge RK3588, ARM64): Real-time video ingestion, RKNN NPU YOLO detection (
- Unified Single-Machine Topology (
192.168.192.158):- Single Intel host running all three components (
Counter Live,Recount Engine,Dashboard) under a single systemd supervisor unit (apc-ngoro-service.service→scripts/apc_supervisor.py) with isolated hardware resource allocation and local NVMe video storage (batch_videos/+recount_output/). - Hardware Specs: Intel(R) Core(TM) Ultra 5 125H (Meteor Lake, 18 vCPUs), 16 GB RAM, 468 GB NVMe SSD, Intel Arc Graphics GPU, and Intel Meteor Lake NPU.
- Single Intel host running all three components (
2. Core Business Logic & Invariants
2.1 Daily Cutoff & Counting Dates
- Default Cutoff Time:
20:00(8:00 PM). Initialized fromDAILY_CUTOFF_TIME/CUTOFF_TIMEin.envand persisted in SQLite (site_settings). - Adjustable Cut-Off via Dashboard (
/api/cutoff-settings&cutoff_utils.py):- Operators can adjust the cut-off time (
HH:MM, evening>= 06:00or post-midnight< 06:00) directly from the Waktu Cut-off card in the Operational Dashboard without restarting services (BatchStorerefreshes every 2 seconds):- Temporary Per-Day Override (
cutoff_overrides): Extends or changes a single counting day (e.g., Today or Yesterday) and automatically reverts to the default cut-off (20:00) on subsequent days. - Permanent Default Change (
site_settings+.env): Updates the global default for all future operational days. - Retroactive Batch Reassignment & Active Batch Extension: Optionally moves batches crossing the adjusted cut-off boundary between
target_dateandtarget_date + 1 day, renumbering both days cleanly while preserving all video/recount metadata anddaily_summaries. Extending the cut-off after rollover also updates an in-flight active batch in-place without dropping it.
- Temporary Per-Day Override (
- Operators can adjust the cut-off time (
- An operational day runs from
Deadline(D - 1)toDeadline(D)(e.g.20:00on dayD-1to20:00on dayD). AtDeadline(D), counters reset whenRESET_COUNTERS_AT_CUTOFF=true.
2.2 Batch & Sub-Batch Lifecycle Rules
- Minimum Main Batch Threshold:
MAIN_BATCH_MIN_COUNT = 700chickens. - Noise Filtering Threshold:
MIN_OBJECT_PER_BATCH=10,MIN_DURATION_PER_BATCH=10(statusVALIDwhen meeting minimums,PARTIALwhencount >= 1below minimums). - Inactivity Gap: If no chicken crosses the counting line for
BATCH_TIMEOUT_SECONDS(25 seconds),_end_batch_locked()closes the batch. - Batch Numbering & Merging Rules:
- Batch 1 Sub-Batch Exception (Future Counting Days >
2026-11-18):- If the very first batch(es) of a counting day close with
count < MAIN_BATCH_MIN_COUNT(< 700), they do not become Main Batch1. Instead, they are assigned sub-batch labels (1a,1b, ...) and merge forward into the upcoming Main Batch1(the first batch of the day withcount >= 700). - Historical batches (
counting_date <= 2026-11-18) retain their existing recorded Batch1designations in dashboards and exports.
- If the very first batch(es) of a counting day close with
- Subsequent Batches (
>= 700vs< 700):- If
count >= 700: Assigned the next sequential integer Main Batch number (1,2,3, ...). - If
count < 700: Assigned as a Sub-Batch (Child Batch) (1b,2a,2b, ...) merging backward into the preceding Main Batch (get_last_main_batch_number).
- If
- Batch 1 Sub-Batch Exception (Future Counting Days >
- Query & State Safety (No Stuck Batches):
get_last_main_batch_number()andget_next_main_batch_number()inbatch_store.pyfilterCAST(batch_number AS TEXT) NOT GLOB '*[a-zA-Z]*'so pure-integer main batch numbering ignores sub-batch suffixes (1a,1b) without falling back to wrong integer casts (e.g.,CAST('1a' AS INTEGER) == 1).- Both queries execute without filtering
WHERE count >= 700to prevent duplicate Batch 1 UNIQUE constraint collisions. _end_batch_locked()always clearsself.current_state = Noneand cancelsself.batch_timerinside error/cleanup paths so SQLite exceptions never poison memory state.
flowchart LR
subgraph DayStart ["Start of Counting Day (After 20:00 Cutoff)"]
B1a["1st Batch: Count = 15 (< 700)\nAssigned: '1a' (Sub-Batch)"]
B1["2nd Batch: Count = 1,350 (>= 700)\nAssigned: '1' (Main Batch 1)"]
B1b["3rd Batch: Count = 80 (< 700)\nAssigned: '1b' (Sub-Batch)"]
B2["4th Batch: Count = 1,400 (>= 700)\nAssigned: '2' (Main Batch 2)"]
end
B1a -- "Batch 1 Exception: Merges FORWARD\ninto Main Batch #1" --> B1
B1b -- "Standard Rule: Merges BACKWARD\ninto Main Batch #1" --> B1
2.3 Video Recording, Sub-Batch Saving, Retention & Recount UI Persistence
- Race-Free Batch Video Recording (
batch_video_recorder.py&counter_live_rknn_bytetrack.py):- While a batch is open,
BatchVideoRecorder.start()writes raw H.264 frames (libx264 ultrafaston SHM/dev/shm/apc-ngoro) to a unique monotonic.partial.mp4filename (batch_<tentative_id>_<ms>_<seq>.partial.mp4) so consecutive batches never unlink or overwrite each other. - When
_end_batch_locked()triggers_on_batch_closed(meta):- If discarded,
batch_recorder.stop_discard()executes synchronously. - If persisted (
meta["ok"]),batch_recorder.detach()claims the active writer state synchronously before spawning the backgroundbatch-finalizethread, andfinalize(final_batch_id=meta["batch_id"], detached=detached)names the outputbatch_<final_batch_id>.mp4(e.g.,batch_2026-11-18-22a.mp4) using PID/thread-unique.restamp.mp4temp files.
- If discarded,
- Storage Routing:
- On the unified Intel host (
192.168.192.158),_save_batch_video_local()moves the finalized file directly into local NVMeBATCH_VIDEO_DIR(/home/admin123/ngoro_project/batch_videos/batch_<id>.mp4) and setsvideo_url=/api/v1/recount/source/<id>. - On NanoPi (
motioneye_client.py),_upload_batch_video_async()uploads to MotionEye Ingest (192.168.192.251:8090). If an ingest server validates with digits-onlybatch_id(HTTP 400: invalid batch_id),upload_batch_video()automatically retries usingencode_ingest_batch_id()(YYYY-MM-DD-22a→YYYY-MM-DD-2201) and records the exact returned filename and URL in SQLite.
- On the unified Intel host (
- Across
retention_utils.py,recount_engine/app.py,motioneye_ingest/app.py, andcounter_dashboard.py,BATCH_ID_REaccepts single- and multi-letter sub-batch suffixes (^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]*$).
- While a batch is open,
- Video Retention Policies:
- Recounted Overlay Videos (
batch_<id>_recount.mp4) & Source Caches (_src_<id>.mp4) inrecount_output/:- Retained for 6 hours (
RECOUNT_OVERLAY_TTL_HOURS=6), enforced hourly by/etc/cron.d/apc-recount-cleanup→scripts/recount_overlay_cleanup.py. - Quantitative recount metadata (
recount_count,recount_delta,recount_video_url) remains permanently in SQLite (apc_ngoro.db).
- Retained for 6 hours (
- Original Batch Videos (
batch_<id>.mp4):- Retained for the latest 7 active counting days on the Intel host (
ACTIVE_RETENTION_DAYS=7, or3on NanoPi), enforced daily at01:00by/etc/cron.d/apc-retention→scripts/retention_active_days.py.
- Retained for the latest 7 active counting days on the Intel host (
- Recounted Overlay Videos (
- Recount Execution & UI Persistence (
templates/dashboard_recounting.html&recount_engine/app.py):- Recounts process video frames with ByteTrack, generate an annotated replay (
batch_<id>_recount.mp4), compute\Delta = \text{Recount Count} - \text{Original Count}, and useRECOUNT_START_COUNT=1compensation. - On page load,
loadBatches().finally(() => refreshStatusOnce())ensuresbatchIndexis populated before status synchronization. - Selecting or returning to any batch card with a completed recount (
recount_count != null) invokesopenReplay(replayUrl, false)instead of hiding the video element withcloseLiveStream(true), so<video id="recount-replay">persists across card switches.applyStatus()updates bothselectedBatchandbatchIndex[data.batch_id]whenCOMPLETED.
- Recounts process video frames with ByteTrack, generate an annotated replay (
2.4 Excel Reporting Structure
Excel exports (/api/export-day-xlsx/<date> and /api/export-daily-xlsx) exclude the legacy Status column and render two stacked standalone tables on the same worksheet:
- Table 1 (
1. HITUNG AYAM POTONG (RINCIAN SELURUH BATCH)):- Columns:
Batch #,Tipe Batch,Hitung Ayam Potong,Catatan,Mulai,Selesai,Durasi (menit)(plusTanggalfor daily exports). - Lists every physical batch run chronologically (
order by start_time ASC, id ASC), showing leading sub-batches (1a) with noteDigabung ke Batch 1before Main Batch1. - Includes summary TOTAL and RATA-RATA rows.
- Columns:
- Table 2 (
2. BATCH DISESUAIKAN (SETELAH PENYESUAIAN) - HANYA BATCH TETAP):- Columns:
Batch #,Tipe Batch,Batch Disesuaikan,Catatan,Mulai,Selesai,Durasi (menit)(plusTanggalfor daily exports). - Consolidates leading sub-batches (
1a) and trailing sub-batches (1b, ...) into their Main Batch (1), computing earlieststart_time, latestend_time, summed durations, and matching total counts. - Batches with 0 chickens are strictly excluded.
- Columns:
3. Directory & File Manifest
| Path | Purpose |
|---|---|
batch_store.py |
SQLite batch persistence (WAL enabled on Intel host), numbering, dynamic cut-off state machine |
cutoff_utils.py |
Adjustable cut-off settings, per-day overrides, deadline computation, batch reconciliation |
counter_dashboard.py |
Flask web dashboard (port 5000), REST APIs, SSE stream, Excel export generator |
counter_live_rknn_bytetrack.py |
Real-time RTSP ingest, OpenVINO/RKNN inference (OpenVINOYOLO), ByteTrack, local NVMe saver |
batch_video_recorder.py |
Async SHM H.264 segment recorder with detach(), unique .partial.mp4, FPS restamping |
recount_engine/app.py |
Flask recount engine (port 8765) with local NVMe resolution and OpenVINO inference |
scripts/apc_supervisor.py |
Unified single-machine process supervisor for Counter, Recount, and Dashboard |
systemd/apc-ngoro-service.service |
Systemd unit running apc_supervisor.py on 192.168.192.158 |
retention_utils.py |
Shared active counting date helpers and canonical BATCH_ID_RE |
scripts/recount_overlay_cleanup.py |
Hourly TTL cleanup for recount_output/ (RECOUNT_OVERLAY_TTL_HOURS=6) |
scripts/retention_active_days.py |
Daily retention cleanup for batch_videos/ (ACTIVE_RETENTION_DAYS=7) |
templates/ |
dashboard_operational.html, dashboard_recounting.html |
static/ |
CSS, JavaScript, icons, and branding assets |
models/ |
Models including best_openvino_model/, ngoro-all-2.onnx, ngoro-all-2.pt |
batch_videos/ |
NVMe source video archive on 192.168.192.158 (batch_<id>.mp4 / <id>.mp4) |
recount_output/ |
Recounted overlay MP4 outputs (batch_<id>_recount.mp4) |
apc_ngoro.db |
Primary SQLite database storing batch records and recount metadata |
4. Single Intel Machine Architecture & Resource Allocation
On admin123@192.168.192.158, systemd/apc-ngoro-service.service launches scripts/apc_supervisor.py, which isolates CPU affinity, OS nice priority, and OpenVINO accelerator devices across the 18-vCPU Meteor Lake hardware:
graph TD
subgraph Hardware ["Intel Core Ultra 5 125H (18 vCPUs, 16GB RAM, NVMe SSD)"]
ArcGPU["Intel Arc Graphics GPU\nOpenVINO device='GPU'"]
IntelNPU["Intel Meteor Lake NPU\nOpenVINO device='NPU'"]
PCores["CPU Cores 0-7 (P-Cores)"]
ECores["CPU Cores 8-15 (E-Cores)"]
DashCores["CPU Cores 14-17"]
end
subgraph Supervisor ["apc_supervisor.py (apc-ngoro-service.service)"]
COUNTER["[COUNTER] counter_live_rknn_bytetrack.py\nNice=-10 | LIVE_CPU_CORES=0-7 | LIVE_OPENVINO_DEVICE=GPU"]
RECOUNT["[RECOUNT] recount_engine/app.py\nNice=10 | RECOUNT_CPU_CORES=8-15 | RECOUNT_OPENVINO_DEVICE=NPU"]
DASHBOARD["[DASHBOARD] counter_dashboard.py\nNice=0 | DASHBOARD_CPU_CORES=14-17 | Port 5000"]
end
ArcGPU --> COUNTER
PCores --> COUNTER
IntelNPU --> RECOUNT
ECores --> RECOUNT
DashCores --> DASHBOARD
Runtime Key Parameters (.env on 192.168.192.158)
- Inference & Affinity:
MODEL_PATH=/home/admin123/ngoro_project/models/best_openvino_modelLIVE_OPENVINO_DEVICE=GPU,LIVE_CPU_CORES=0-7,LIVE_INFERENCE_THREADS=4RECOUNT_OPENVINO_DEVICE=NPU,RECOUNT_CPU_CORES=8-15,RECOUNT_INFERENCE_THREADS=4,RECOUNT_FFMPEG_THREADS=4BATCH_RECORD_THREADS=2
- Local NVMe & Loopback Storage:
BATCH_VIDEO_DIR=/home/admin123/ngoro_project/batch_videosRECOUNT_OUTPUT_DIR=/home/admin123/ngoro_project/recount_outputRECOUNT_ENGINE_URL=http://127.0.0.1:8765,RECOUNT_PUBLIC_BASE=http://127.0.0.1:8765RECOUNT_LIVE_FRAME_PATH=/dev/shm/apc-ngoro/recount_live_frame.jpg
- SQLite Concurrency:
- WAL journaling enabled (
PRAGMA journal_mode=WAL,PRAGMA synchronous=NORMAL,PRAGMA busy_timeout=5000) for safe concurrent reads/writes between Counter Live, Dashboard, and Recount Engine.
- WAL journaling enabled (
5. Operations & Verification Commands on 192.168.192.158
# Check unified service status & component logs
sudo systemctl status apc-ngoro-service.service
journalctl -u apc-ngoro-service.service -f
# Check local service endpoints
curl -s http://127.0.0.1:5000/api/health
curl -s http://127.0.0.1:8765/health
# Check retention timers/crons (dry-run)
/home/admin123/ngoro_project/venv/bin/python /home/admin123/ngoro_project/scripts/recount_overlay_cleanup.py --dry-run
/home/admin123/ngoro_project/venv/bin/python /home/admin123/ngoro_project/scripts/retention_active_days.py --dry-run
Updated on 2026-11-18 with sub-batch video recording, recount UI persistence, Batch 1 sub-batch forward-merging, and unified supervisor architecture.