Files

1592 lines
73 KiB
Python

import os
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;tcp|buffer_size;20480000|max_delay;500000|reorder_queue_size;500"
import argparse
import cv2
import numpy as np
import json
import threading
import time
from ultralytics import YOLO
from shapely.geometry import Point, Polygon, box
import torch
from datetime import datetime
import logging
# Import repo modules
from src.detection import TruckDetector
from src.tracking import ByteTrackTracker
from src.stabilizer import BboxStabilizer
from src.counting import MultiClassLineCounter, drop_sacks_overlapping_boxes
from src.batch import BatchLifecycleManager, BatchRecord
from src.logger import CSVLogger
from src.dashboard import DashboardOverlay
from src.pipeline import RTSPStreamReader
from src.ui import LiveFrameWriter, update_live_status
from src.config_loader import (
Config,
check_legacy_batch_mode,
load_config,
resolve_active_mode,
)
from src.persistence import (
DatabaseManager,
StateManager,
get_counting_date as _persistence_get_counting_date,
)
# --- SQLite Database & State Configuration ---
if os.name == 'nt':
OUTPUT_DIR = 'd:/Belajar/menghitung karung'
DB_PATH = f'{OUTPUT_DIR}/jetson_counter.db'
STATE_FILE = f'{OUTPUT_DIR}/current_batch.json'
BATCH_MODE_FILE = f'{OUTPUT_DIR}/batch_mode.json'
LIVE_STREAM_FRAME_PATH = f'{OUTPUT_DIR}/live_frame.jpg'
else:
OUTPUT_DIR = os.getenv('OUTPUT_DIR', '/opt/jetson-counter')
DB_PATH = os.getenv('DB_PATH', f'{OUTPUT_DIR}/jetson_counter.db')
STATE_FILE = os.getenv('STATE_FILE', f'{OUTPUT_DIR}/current_batch.json')
BATCH_MODE_FILE = os.getenv('BATCH_MODE_FILE', f'{OUTPUT_DIR}/batch_mode.json')
LIVE_STREAM_FRAME_PATH = os.getenv('LIVE_STREAM_FRAME_PATH', '/dev/shm/jetson-counter/live_frame.jpg')
CAMERA_NAME = os.getenv('CAMERA_NAME', 'CC1')
OBJECT_LABEL = os.getenv('OBJECT_LABEL', 'karung-pakan')
DAILY_CUTOFF_TIME = os.getenv('DAILY_CUTOFF_TIME', '20:00')
BATCH_MERGE_THRESHOLD_SECONDS = int(os.getenv('BATCH_MERGE_THRESHOLD_SECONDS', '300'))
active_batch_info = None
batch_logger = None # CSVLogger for batch_summary.csv / sack_events.csv (set in run_prediction)
# --- CLI runtime flags (set from parse_args in __main__; defaults = production) ---
NO_DASHBOARD = False # --no-dashboard: skip live frame + live_status.json writes
NO_DB = False # --no-db: skip SQLite/state-file persistence
def parse_args():
"""CLI controls — zero flags reproduces systemd production behaviour."""
p = argparse.ArgumentParser(
description="Feedmill Counting Platform — production pipeline (systemd service + dev CLI)"
)
p.add_argument("--source", type=str, default=None,
help="Video file path (overrides RTSP_URL)")
p.add_argument("--env", type=str, default=".env",
help="Path to .env file")
p.add_argument("--model", type=str, default=None,
help="Override MODEL_PATH (.pt/.engine)")
p.add_argument("--output-dir", type=str, default=None,
help="Override output dir for DB/state/live-frame (default: .env values)")
p.add_argument("--output-json", type=str, default=None,
help="Override batch report JSON path")
p.add_argument("--sack-conf", type=float, default=None,
help="Override sack detection confidence (default 0.35)")
p.add_argument("--truck-conf", type=float, default=None,
help="Override truck detection confidence (default 0.35)")
p.add_argument("--box-conf", type=float, default=None,
help="Override box detection confidence (default 0.35)")
p.add_argument("--box-model", type=str, default=None,
help="Override yolo11n sack+box model path (.pt/.engine)")
p.add_argument("--model-mode", type=str, default=None,
help="Model pipeline mode (default: config.yaml models.active_mode). "
"A=combined only; B=v4 truck + yolo11n sack+box; "
"C=A + yolo11n box-only; D=v4 truck + best sack + yolo11n box; "
"E=single unified yolo11n sack+box+truck; "
"F=single unified yolo8n sack+box+truck (imgsz 320); "
"G=single unified yolo26n sack+box+truck. "
"New modes from config.yaml need no code change.")
p.add_argument("--config", type=str, default=None,
help="Path to config.yaml (default: config.yaml next to predict.py)")
p.add_argument("--batch-timeout", type=float, default=None,
help="Override sack-idle + truck-gone timeouts (seconds)")
p.add_argument("--max-frames", type=int, default=None,
help="Stop after N frames (dev)")
p.add_argument("--no-dashboard", action="store_true",
help="Disable live frame publish + live_status.json")
p.add_argument("--no-db", action="store_true",
help="Disable SQLite/state-file persistence")
return p.parse_args()
def get_counting_date(dt=None):
"""Get the counting date based on current time and daily cutoff."""
return _persistence_get_counting_date(dt=dt, cutoff_str=DAILY_CUTOFF_TIME)
# --- Persistence Module Delegation ---
_db_manager = None
_state_manager = None
def _get_db_manager():
global _db_manager
if _db_manager is None or _db_manager.db_path != DB_PATH:
_db_manager = DatabaseManager(DB_PATH)
return _db_manager
def _get_state_manager():
global _state_manager
if (
_state_manager is None
or _state_manager.state_file != STATE_FILE
or _state_manager.batch_mode_file != BATCH_MODE_FILE
):
_state_manager = StateManager(STATE_FILE, BATCH_MODE_FILE)
return _state_manager
def init_db():
"""Initialize the database (backward compatibility)."""
_get_db_manager().init_db()
def get_next_batch_number(counting_date):
"""Get next batch number (backward compatibility)."""
return _get_db_manager().get_next_batch_number(counting_date, CAMERA_NAME, OBJECT_LABEL)
def get_last_batch_info(counting_date):
"""Get last batch info (backward compatibility)."""
return _get_db_manager().get_last_batch_info(counting_date, CAMERA_NAME, OBJECT_LABEL)
def save_active_batch_state():
"""Save active batch state (backward compatibility)."""
global active_batch_info
if NO_DB:
return
_get_state_manager().save_active_batch_state(active_batch_info)
def log_crossing_event(ev, counter, batch_id, timestamp):
"""Print one crossing event (direction-aware wording) + append CSV event row.
Shared by the manual and auto event loops. CSV failure only warns —
the counting pipeline must never crash because of logging.
"""
label = "KARUNG" if ev.get("class_name", "sack") == "sack" else "BOX"
is_unloading = ev.get("direction") == "unloading"
if is_unloading:
total = counter.unloading_count if label == "KARUNG" else counter.box_unloading_count
print(f"[{label}] {label.capitalize()} #{ev['track_id']} keluar.")
print(f"[TOTAL] Total {label.lower()} keluar: {total}.")
else:
total = counter.loading_count if label == "KARUNG" else counter.box_loading_count
print(f"[{label}] {label.capitalize()} #{ev['track_id']} masuk.")
print(f"[TOTAL] Total {label.lower()} saat ini: {total}.")
if batch_logger:
try:
batch_logger.log_event(
int(batch_id or 0), ev["track_id"],
ev.get("direction", "loading"), timestamp,
ev.get("class_name", "sack"))
except Exception as e:
print(f"[WARN] CSV log_event gagal: {e}")
def log_manual_batch_stop():
"""CSV row for a manual batch stopped via dashboard button.
predict.py does not write manual batches to SQLite (counter_dashboard.py
owns that insert), so this is the only place the CSV row is produced.
"""
info = active_batch_info
if info is None or batch_logger is None:
return
final_count = int(info.get("count", 0) or 0)
box_final = int(info.get("box_count", 0) or 0)
# Manual batches are always kept (incl. 0/0) — covered/container trucks.
try:
batch_logger.log_batch(BatchRecord(
batch_id=int(info.get("batch_number", 0) or 0),
start_time=datetime.fromisoformat(
info.get("start_time") or datetime.now().isoformat()).timestamp(),
end_time=time.time(),
loading_count=final_count,
unloading_count=int(info.get("unloading", 0) or 0),
box_loading_count=box_final,
box_unloading_count=int(info.get("box_unloading", 0) or 0),
))
print(f"[CSV Info] Manual batch #{info.get('batch_number')} disimpan ke batch_summary.csv.")
except Exception as e:
print(f"[WARN] CSV log_batch manual gagal: {e}")
def finalize_batch(final_count, start_time_iso, end_time_iso,
box_final_count=0, box_unloading_count=0, model_mode="?",
unloading_count=0):
global active_batch_info
if active_batch_info is None:
return
net_sack = int(final_count) - int(unloading_count or 0)
net_box = int(box_final_count) - int(box_unloading_count or 0)
if NO_DB:
print(f"[DB Info] --no-db: batch #{active_batch_info.get('batch_number', 0)} "
f"({final_count} karung, {box_final_count} box) tidak disimpan.")
active_batch_info = None
save_active_batch_state()
return
if int(final_count) == 0 and int(box_final_count) == 0:
print(f"[BATCH] Batch #{active_batch_info.get('batch_number', 0)} bernilai 0 diabaikan (tidak disimpan ke database).")
active_batch_info = None
save_active_batch_state()
return
# Delegate database operations to persistence module
_get_db_manager().insert_finalized_batch(
active_batch_info,
final_count,
start_time_iso,
end_time_iso,
box_final_count,
box_unloading_count,
model_mode,
unloading_count,
net_sack,
net_box,
camera_name=CAMERA_NAME,
object_label=OBJECT_LABEL,
)
# CSV row for every kept batch (discard/NO_DB early-returns above), even if
# the SQLite write failed — CSV is the fallback record.
if batch_logger:
try:
batch_logger.log_batch(BatchRecord(
batch_id=active_batch_info.get("batch_number"),
start_time=datetime.fromisoformat(start_time_iso).timestamp(),
end_time=datetime.fromisoformat(end_time_iso).timestamp(),
loading_count=int(final_count),
unloading_count=int(unloading_count or 0),
box_loading_count=int(box_final_count or 0),
box_unloading_count=int(box_unloading_count or 0),
))
print(f"[CSV Info] Batch #{active_batch_info.get('batch_number')} disimpan ke batch_summary.csv.")
except Exception as e:
print(f"[WARN] CSV log_batch gagal: {e}")
active_batch_info = None
save_active_batch_state()
class PipelineState:
"""Encapsulates active runtime state for the counting pipeline."""
def __init__(self):
self.metrics = {
"total_masuk": 0,
"total_keluar": 0,
"box_masuk": 0,
"box_keluar": 0,
}
self.counted_sack_positions = []
pipeline_state = PipelineState()
# --- Active Runtime Parameters & State Machine Constants ---
DUPLICATE_CIRCLE_RADIUS = 35
CROSS_CLASS_IOU = 0.4 # drop sack dets overlapping a box det (cross-model)
SHOW_ALL_BBOXES = False
counted_sack_positions = pipeline_state.counted_sack_positions
INFERENCE_STRIDE = 2
STATE_WAITING_FOR_TRUCK = "WAITING_FOR_TRUCK"
STATE_COUNTING_SACKS = "COUNTING_SACKS"
STATE_TRUCK_FULL = "TRUCK_FULL"
STATE_TRUCK_LEAVING = "TRUCK_LEAVING"
system_state = STATE_WAITING_FOR_TRUCK
metrics = pipeline_state.metrics
# --- Model paths & config ---
# All weights live in models/ (see models/modelREADME.md for mode/filter matrix
# and config.yaml models.* for the canonical paths + per-mode presets).
_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
_MODELS_DIR = os.path.join(_BASE_DIR, "models")
_DEFAULT_CONFIG_PATH = os.path.join(_BASE_DIR, "config.yaml")
# Active Config object (set in __main__/run_prediction before the pipeline starts).
_CFG: Config | None = None
def _legacy_combined_fallback() -> str:
"""Pre-YAML combined-model auto-pick (kept for --model/MODEL_PATH handling)."""
_env_model = os.getenv("MODEL_PATH")
if _env_model and os.path.exists(_env_model):
return _env_model
_candidates = [
os.path.join(_MODELS_DIR, "v4-best.engine"),
os.path.join(_MODELS_DIR, "v4-best.pt"),
os.path.join(_MODELS_DIR, "v4-best (1).pt"),
os.path.join(_MODELS_DIR, "model_karung_truk.engine"),
os.path.join(_MODELS_DIR, "model_karung_truk.pt"),
]
return next((p for p in _candidates if os.path.exists(p)),
os.path.join(_MODELS_DIR, "v4-best.pt"))
def apply_cli_overrides_to_config(cfg: Config, args) -> Config:
"""Fold legacy CLI/env model overrides into the Config object (in place).
--model/--box-model/MODEL_PATH keep their pre-YAML meaning:
a single v4 file used wherever a v4 engine is needed.
--sack-conf/--truck-conf/--box-conf override detection_params conf.
"""
v4_override = args.model or os.getenv("MODEL_PATH")
if v4_override:
if not os.path.exists(v4_override):
print(f"[WARN] --model/MODEL_PATH {v4_override} tidak ditemukan, "
f"dipakai langsung (YOLO bisa resolve).")
for key in ("combined", "truck_only"):
if key in cfg.models.paths:
cfg.models.paths[key] = v4_override
if getattr(args, "box_model", None):
cfg.models.paths["box"] = args.box_model
for cls_name, val in (("sack", args.sack_conf), ("truck", args.truck_conf),
("box", args.box_conf)):
if val is not None and cls_name in cfg.models.detection_params:
cfg.models.detection_params[cls_name].conf = float(val)
if getattr(args, "batch_timeout", None) is not None:
cfg.batch.timeout_seconds = float(args.batch_timeout)
return cfg
# --- Model pipeline modes -------------------------------------------------
# Modes are DATA in config.yaml models.modes (engines + class filters only).
# A=combined only; B=v4 truck + yolo11n sack+box; C=A + yolo11n box-only (default);
# D=v4 truck + best sack-only + yolo11n box-only; E=single unified yolo11n sack+box+truck;
# F=single unified yolo8n sack+box+truck (imgsz 320); G=single unified yolo26n sack+box+truck. New modes need no code change.
# All engines verified to coexist (~16-24 MB peak of 7.6 GB).
def resolve_model_mode(explicit: str | None) -> str:
"""Precedence: --model-mode > MODEL_MODE env (deprecated) > config.yaml.
Dashboard switches persist to config.yaml models.active_mode and take effect
on next service restart (models are loaded once at startup).
batch_mode.json is legacy and no longer consulted.
"""
cfg = _CFG or load_config(_DEFAULT_CONFIG_PATH)
return resolve_active_mode(explicit, cfg)
class _RtspHealth:
"""Frame-drop / freeze monitor for the RTSP loop (journal only).
Miscount risk: a stall crossing the count line misses sacks; on resume
batch timers may have aged out. Logs are rate-limited: first fail of a
burst + every 100th, one freeze line per episode, recovery closes it.
"""
def __init__(self, gap_warn=5.0, now=None, on_log=print):
self.gap_warn = float(gap_warn)
self._now = now or time.time
self._log = on_log
self.fail_total = 0
self.fail_burst = 0
self.freeze_total = 0
self.freeze_logged = False
self.gap_max = 0.0
self.last_ok_t = self._now()
def on_frame_fail(self, batch_active=False, count=0):
t = self._now()
if self.fail_burst == 0:
self._burst_start = t
self.fail_burst += 1
self.fail_total += 1
if self.fail_burst in (1, 100) or self.fail_burst % 10000 == 0:
self._log(
f"[RTSP] grab fail x{self.fail_burst} (total={self.fail_total}) "
f"last_ok={t - self.last_ok_t:.1f}s ago"
)
if (not self.freeze_logged) and (t - self.last_ok_t) > self.gap_warn:
self.freeze_logged = True
self.freeze_total += 1
self._log(f"[RTSP] freeze {(t - self.last_ok_t):.1f}s (no frames)")
if batch_active:
self._log(
f"[RTSP][RISK] freeze during active batch "
f"(count={count}) — verify manual count"
)
def on_frame(self, batch_active=False, count=0):
t = self._now()
gap = t - self.last_ok_t
if gap > self.gap_max:
self.gap_max = gap
if self.fail_burst > 0 or self.freeze_logged:
if self.freeze_logged or gap > 1.0:
self._log(
f"[RTSP] recovered after {gap:.1f}s gap / {self.fail_burst} fails"
)
self.fail_burst = 0
self.freeze_logged = False
elif gap > self.gap_warn:
# read() blocked instead of failing — frame gap catches it
self.freeze_total += 1
self._log(f"[RTSP] freeze {gap:.1f}s (frame gap)")
if batch_active:
self._log(
f"[RTSP][RISK] freeze during active batch "
f"(count={count}) — verify manual count"
)
self.last_ok_t = t
def _bbox_area_ok(d, min_area: float) -> bool:
"""Permissive per-class guardrail from config.yaml detection_params."""
x1, y1, x2, y2 = d.bbox
return (x2 - x1) * (y2 - y1) >= min_area
def build_model_pipeline(mode, cfg, device, base_dir=None):
"""Instantiate YOLO handles + detectors/trackers for a mode preset.
Roles derive structurally from the preset's per-engine `classes`
(config.yaml models.modes) — no per-mode-letter branching, so new
modes (E, F, ...) work without code changes:
- tracker (primary): first engine covering `sack`
- truck_detector: first engine covering `truck`
(separate_truck_model = truck engine is not the primary)
- box_tracker: dedicated iff a non-primary engine covers `box`
(shared with the primary tracker otherwise, e.g. mode B)
Returns dict with keys: mode, truck_detector, tracker, box_tracker
(None when sack tracker covers boxes or no box engine), separate_truck_model,
class_filters, min_areas.
"""
base_dir = base_dir or _BASE_DIR
preset = cfg.models.modes[mode]
filters = {k: tuple(v) for k, v in preset.class_filters.items()}
dp_truck = cfg.detection_params_for("truck")
dp_sack = cfg.detection_params_for("sack")
dp_box = cfg.detection_params_for("box")
print(f"[INFO] Model mode: {mode} ({preset.description})")
dummy = np.zeros((720, 1280, 3), dtype=np.uint8)
handles: dict[str, object] = {}
def _load(path_key: str):
if path_key not in handles:
path = cfg.engine_path(path_key, base_dir)
print(f"[INFO] Memuat {path_key}: {path}")
m = YOLO(path)
_ = m(dummy, imgsz=640, device=device, verbose=False) # warm-up CUDA/TRT ctx
handles[path_key] = m
return handles[path_key]
primary_key = next((e.path for e in preset.engines if "sack" in e.classes), None)
truck_key = next((e.path for e in preset.engines if "truck" in e.classes), None)
box_keys = [e.path for e in preset.engines if "box" in e.classes]
if primary_key is None:
raise ValueError(
f"Mode {mode!r} has no engine covering class 'sack' — "
f"at least one engines[].classes must include sack."
)
# Pre-load all unique engines for this mode, ensuring PyTorch .pt models
# load before TensorRT .engine models (Jetson CUDA/TRT requirement).
required_keys: list[str] = []
for k in [primary_key, truck_key, *([k for k in box_keys if k != primary_key] if (box_keys and filters.get("box")) else [])]:
if k is not None and k not in required_keys:
required_keys.append(k)
required_keys.sort(key=lambda k: 0 if str(cfg.engine_path(k, base_dir)).lower().endswith(".pt") else 1)
for k in required_keys:
_load(k)
# Tracker conf = lowest per-class threshold so low-conf sacks/boxes survive
# to the per-class filter (which applies the real thresholds).
_tracker_conf = min(dp_truck.conf, dp_sack.conf, dp_box.conf)
tracker = ByteTrackTracker(_load(primary_key), _tracker_conf, dp_sack.iou)
truck_detector = (
TruckDetector(_load(truck_key), dp_truck.conf,
class_filter=filters.get("truck") or ("truck",),
iou=dp_truck.iou)
if truck_key is not None else None
)
separate_truck_model = truck_key is not None and truck_key != primary_key
box_tracker = None
if box_keys and filters.get("box"):
dedicated = next((k for k in box_keys if k != primary_key), None)
if dedicated is not None:
box_tracker = ByteTrackTracker(_load(dedicated), dp_box.conf, dp_box.iou)
# else: boxes share the primary tracker (single ID space, e.g. mode B)
return {
"mode": mode,
"truck_detector": truck_detector,
"tracker": tracker,
"box_tracker": box_tracker,
"separate_truck_model": separate_truck_model,
"class_filters": filters,
"min_areas": {
"truck": dp_truck.min_bbox_area,
"sack": dp_sack.min_bbox_area,
"box": dp_box.min_bbox_area,
},
"confs": {
"truck": dp_truck.conf,
"sack": dp_sack.conf,
"box": dp_box.conf,
},
}
# =====================================================================
# =====================================================================
# 1. KONFIGURASI KOORDINAT ZONA & STREAMING STATE
# =====================================================================
width = 1280
height = 720
scale_x = 1.0
scale_y = 1.0
current_fps = 0.0
LOADED_ZONES = {}
_DEBUG_ZONES_TYPES = ("palet", "truck", "counting", "line")
_DEBUG_ZONES_CACHE = {"mtime": None, "state": {k: False for k in _DEBUG_ZONES_TYPES}}
def _load_debug_zone_toggles():
"""Read /dev/shm/jetson-counter/debug_zones.json (cached by mtime)."""
global _DEBUG_ZONES_CACHE
path = os.path.join(os.path.dirname(LIVE_STREAM_FRAME_PATH), "debug_zones.json")
try:
st = os.stat(path)
except OSError:
default_on = os.getenv("DEBUG_ZONES") == "1"
return {k: default_on for k in _DEBUG_ZONES_TYPES}
if _DEBUG_ZONES_CACHE.get("mtime") == st.st_mtime_ns:
return _DEBUG_ZONES_CACHE["state"]
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f) or {}
except Exception:
data = {}
state = {k: bool(data.get(k, False)) for k in _DEBUG_ZONES_TYPES}
_DEBUG_ZONES_CACHE = {"mtime": st.st_mtime_ns, "state": state}
return state
# =====================================================================
# 5. PROSES PREDIKSI & VISUALISASI VIDEO
# =====================================================================
def _filter_sacks_in_roi(detections, roi):
"""Keep only sacks whose centroid X falls within the truck ROI."""
if roi is None:
return []
return [
d for d in detections
if roi.contains_x((d.bbox[0] + d.bbox[2]) / 2.0)
]
def run_prediction(model_path, source_path,
output_json_path="hasil_perhitungan.json", max_frames=None,
inference_stride=None, sack_conf=None, truck_conf=None,
box_conf=None, box_model_path=None, model_mode=None,
output_dir=None, batch_timeout=None,
config_path=None, cfg=None):
global metrics, current_fps, INFERENCE_STRIDE, width, height
global active_batch_info, system_state, DUPLICATE_CIRCLE_RADIUS, CROSS_CLASS_IOU
global DB_PATH, STATE_FILE, BATCH_MODE_FILE, LIVE_STREAM_FRAME_PATH
global batch_logger, CAMERA_NAME, OBJECT_LABEL, DAILY_CUTOFF_TIME, BATCH_MERGE_THRESHOLD_SECONDS
global scale_x, scale_y, _CFG
# --- Unified config (config.yaml canonical, .env for secrets/deployment) ---
_CFG = cfg or load_config(config_path or _DEFAULT_CONFIG_PATH)
cfg = _CFG
# Legacy path overrides keep their pre-YAML meaning (folded into cfg).
if model_path and model_path != _legacy_combined_fallback():
for _k in ("combined", "truck_only"):
if _k in cfg.models.paths:
cfg.models.paths[_k] = model_path
if box_model_path:
cfg.models.paths["box"] = box_model_path
for _cls, _v in (("sack", sack_conf), ("truck", truck_conf), ("box", box_conf)):
if _v is not None and _cls in cfg.models.detection_params:
cfg.models.detection_params[_cls].conf = float(_v)
# --- Path / identity / timing globals from config (output_dir wins) ---
if output_dir:
# Cross-platform: plain join, keep config layout when output_dir is None
DB_PATH = os.path.join(output_dir, "jetson_counter.db")
STATE_FILE = os.path.join(output_dir, "current_batch.json")
BATCH_MODE_FILE = os.path.join(output_dir, "batch_mode.json")
LIVE_STREAM_FRAME_PATH = os.path.join(output_dir, "live_frame.jpg")
print(f"[INFO] Output dir override: {output_dir}")
else:
DB_PATH = os.path.join(cfg.output.dir, cfg.output.db_name)
STATE_FILE = os.path.join(cfg.output.dir, cfg.output.state_file)
BATCH_MODE_FILE = os.path.join(cfg.output.dir, cfg.output.batch_mode_file)
LIVE_STREAM_FRAME_PATH = cfg.output.live_frame_path
CAMERA_NAME = cfg.camera.name
OBJECT_LABEL = cfg.camera.object_label
DAILY_CUTOFF_TIME = cfg.batch.daily_cutoff_time
BATCH_MERGE_THRESHOLD_SECONDS = cfg.batch.merge_threshold_seconds
# --- CSV logger (batch_summary.csv + sack_events.csv) next to the DB ---
# --no-db means "persist nothing"; construction/call failures only warn.
if NO_DB:
batch_logger = None
else:
_csv_dir = os.path.dirname(DB_PATH) or "."
try:
batch_logger = CSVLogger(_csv_dir)
print(f"[INFO] CSV logger aktif: {os.path.join(_csv_dir, 'batch_summary.csv')}, "
f"{os.path.join(_csv_dir, 'sack_events.csv')}")
except Exception as e:
batch_logger = None
print(f"[WARN] CSV logger gagal diinisialisasi: {e}")
# --- Counting-knob state from config ---
DUPLICATE_CIRCLE_RADIUS = cfg.counting.duplicate_circle_radius
CROSS_CLASS_IOU = cfg.counting.cross_class_iou
# Legacy batch_mode.json no longer drives the mode — nudge once if stale.
_legacy_warn = check_legacy_batch_mode(cfg, BATCH_MODE_FILE)
if _legacy_warn:
print(f"[WARN] {_legacy_warn}")
mode = resolve_model_mode(model_mode)
# 1. Silencing YOLO logs
from ultralytics.utils import LOGGER
LOGGER.setLevel(logging.WARNING)
INFERENCE_STRIDE = inference_stride if inference_stride is not None else cfg.stream.inference_stride
# Reset lists and dicts
for k in metrics:
metrics[k] = 0
# Device
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"[INFO] Device inferensi diset ke: {device}")
# Reader
is_stream = any(str(source_path).startswith(p) for p in ["rtsp://", "rtmp://", "http://", "https://"])
if is_stream:
print("[INFO] Membuka RTSP stream menggunakan Threaded GStreamer NVDEC Reader...")
cap = RTSPStreamReader(source_path)
if not cap.wait_until_ready():
print(f"Error: Gagal membuka video source (RTSP stream/file) di {source_path}")
cap.release()
return
else:
print("[INFO] Membuka file video lokal...")
cap = cv2.VideoCapture(source_path)
if not cap.isOpened():
print(f"Error: Gagal membuka video source (RTSP stream/file) di {source_path}")
return
width = 1280
height = 720
fps = cap.get(cv2.CAP_PROP_FPS)
if fps <= 0 or np.isnan(fps):
fps = 25.0
print(f"[INFO] Resolusi Asli: {int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))}x{int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))} @ {fps:.1f} FPS (Diresize ke 1280x720 untuk koordinat tetap)")
# Initialize components per mode preset (engines verified to coexist)
pipe = build_model_pipeline(mode, cfg, device, _BASE_DIR)
print("[INFO] Warm-up model selesai.")
truck_detector = pipe["truck_detector"]
tracker = pipe["tracker"]
box_tracker = pipe["box_tracker"]
separate_truck_model = pipe["separate_truck_model"]
min_areas = pipe["min_areas"]
confs = pipe["confs"]
stabilizer = BboxStabilizer(
ema_alpha=0.35,
max_hold_frames=10,
max_height_ratio=1.5,
min_height_ratio=0.70,
)
# Separate stabilizer for the box tracker's own ID space (modes C/D).
# Mode B shares the yolo11n tracker (single ID space) so this stays unused.
box_stabilizer = BboxStabilizer(
ema_alpha=0.35,
max_hold_frames=10,
max_height_ratio=1.5,
min_height_ratio=0.70,
)
# ================================================================
# HARDCODED COORDINATES FOR LOCAL (1280x720)
# Truck detector hanya untuk batch lifecycle (deteksi truk datang/pergi)
# Area di bawah ini FIXED, tidak tergantung deteksi truk.
# ================================================================
# ----------------------------------------------------------------
# Zones: load from zones.json (source of truth), fallback to defaults.
# zones.json is authored in 1920x1080 native space unless coord_space says
# "1280x720". Keep the 1280x720 canvas coordinate space downstream, while
# preserving raw authored coordinates in LOADED_ZONES for 1:1 debug labels.
# ----------------------------------------------------------------
global LOADED_ZONES
import json as _json
from src.config_loader import read_zone_polygons
from src.truck_roi import TruckROI
_zones_path = getattr(cfg, "zones", None)
_zones_path = getattr(_zones_path, "config_file", "zones.json") if _zones_path else "zones.json"
if not os.path.isabs(_zones_path):
_base = os.path.dirname(os.path.abspath(config_path)) if config_path else os.getcwd()
_zones_path = os.path.join(_base, _zones_path)
_DEFAULT_NATIVE = {
"palet": [[612, 628], [1454, 630], [1458, 1074], [608, 1071]],
"truck": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"line_y_native": 330,
"line_x_start_native": 577,
"line_x_end_native": 1401,
"roi": [600, 343, 1404, 1078],
}
def _parse_zones_from_disk():
try:
with open(_zones_path, "r", encoding="utf-8") as _zf:
_raw = _json.load(_zf)
try:
read_zone_polygons(_zones_path)
except Exception:
pass
_coord = str(_raw.get("coord_space", "1920x1080")).lower()
if _coord == "1280x720":
_sx, _sy = 1.0, 1.0
else:
_sx, _sy = 1280.0 / 1920.0, 720.0 / 1080.0
def _sc(pts):
return [[int(round(p[0] * _sx)), int(round(p[1] * _sy))] for p in (pts or [])]
_raw_palet = _raw.get("palet") or _DEFAULT_NATIVE["palet"]
_raw_truck = _raw.get("truck") or _DEFAULT_NATIVE["truck"]
_raw_counting = _raw.get("counting") or _DEFAULT_NATIVE["counting"]
_palet_pts = _sc(_raw_palet)
_truck_pts = _sc(_raw_truck)
_counting_pts = _sc(_raw_counting)
_cl = _raw.get("counting_line")
if isinstance(_cl, list) and len(_cl) == 2:
_raw_line_xs = int(min(_cl[0][0], _cl[1][0]))
_raw_line_xe = int(max(_cl[0][0], _cl[1][0]))
_raw_line_y = int(round((_cl[0][1] + _cl[1][1]) / 2.0))
else:
_raw_line_y = int(_raw.get("line_y", _DEFAULT_NATIVE["line_y_native"]))
_raw_line_xs = int(_raw.get("line_x_start", _DEFAULT_NATIVE["line_x_start_native"]))
_raw_line_xe = int(_raw.get("line_x_end", _DEFAULT_NATIVE["line_x_end_native"]))
_line_y = int(round(_raw_line_y * _sy))
_line_xs = int(round(_raw_line_xs * _sx))
_line_xe = int(round(_raw_line_xe * _sx))
_roi_raw = _raw.get("roi")
if _roi_raw and len(_roi_raw) == 4:
_roi = [
int(round(_roi_raw[0] * _sx)),
int(round(_roi_raw[1] * _sy)),
int(round(_roi_raw[2] * _sx)),
int(round(_roi_raw[3] * _sy)),
]
elif _truck_pts:
_xs = [p[0] for p in _truck_pts]
_ys = [p[1] for p in _truck_pts]
_roi = [min(_xs), min(_ys), max(_xs), max(_ys)]
else:
_roi = [
int(round(v * (_sx if i % 2 == 0 else _sy)))
for i, v in enumerate(_DEFAULT_NATIVE["roi"])
]
return {
"palet": _palet_pts,
"truck": _truck_pts,
"counting": _counting_pts,
"raw_palet": _raw_palet,
"raw_truck": _raw_truck,
"raw_counting": _raw_counting,
"line_y": _line_y,
"line_x_start": _line_xs,
"line_x_end": _line_xe,
"raw_line_y": _raw_line_y,
"raw_line_x_start": _raw_line_xs,
"raw_line_x_end": _raw_line_xe,
"roi": _roi,
"coord_space": _coord,
}
except Exception as e:
print(f"[WARNING] Gagal memuat zones.json ({e}), menggunakan default.")
_sx, _sy = 1280.0 / 1920.0, 720.0 / 1080.0
return {
"palet": [[int(round(p[0] * _sx)), int(round(p[1] * _sy))] for p in _DEFAULT_NATIVE["palet"]],
"truck": [[int(round(p[0] * _sx)), int(round(p[1] * _sy))] for p in _DEFAULT_NATIVE["truck"]],
"counting": [[int(round(p[0] * _sx)), int(round(p[1] * _sy))] for p in _DEFAULT_NATIVE["counting"]],
"raw_palet": _DEFAULT_NATIVE["palet"],
"raw_truck": _DEFAULT_NATIVE["truck"],
"raw_counting": _DEFAULT_NATIVE["counting"],
"line_y": int(round(_DEFAULT_NATIVE["line_y_native"] * _sy)),
"line_x_start": int(round(_DEFAULT_NATIVE["line_x_start_native"] * _sx)),
"line_x_end": int(round(_DEFAULT_NATIVE["line_x_end_native"] * _sx)),
"raw_line_y": _DEFAULT_NATIVE["line_y_native"],
"raw_line_x_start": _DEFAULT_NATIVE["line_x_start_native"],
"raw_line_x_end": _DEFAULT_NATIVE["line_x_end_native"],
"roi": [
int(round(_DEFAULT_NATIVE["roi"][0] * _sx)),
int(round(_DEFAULT_NATIVE["roi"][1] * _sy)),
int(round(_DEFAULT_NATIVE["roi"][2] * _sx)),
int(round(_DEFAULT_NATIVE["roi"][3] * _sy)),
],
"coord_space": "1920x1080",
}
LOADED_ZONES = _parse_zones_from_disk()
print(f"[INFO] Zones loaded from {_zones_path} (coord_space={LOADED_ZONES['coord_space']})")
try:
_zones_mtime = os.stat(_zones_path).st_mtime_ns
except OSError:
_zones_mtime = None
scale_x = 1.0
scale_y = 1.0
detection_poly_pts = LOADED_ZONES["counting"]
detection_polygon = Polygon(detection_poly_pts)
static_line_y = LOADED_ZONES["line_y"]
static_line_x_start = LOADED_ZONES["line_x_start"]
static_line_x_end = LOADED_ZONES["line_x_end"]
truck_poly_pts = LOADED_ZONES["truck"]
truck_polygon = Polygon(truck_poly_pts)
_roi = LOADED_ZONES["roi"]
static_roi = TruckROI(
x1=_roi[0],
y1=_roi[1],
x2=_roi[2],
y2=_roi[3],
line_y=static_line_y,
confidence=1.0
)
def _reload_zones_if_changed():
nonlocal _zones_mtime, detection_poly_pts, detection_polygon
nonlocal truck_poly_pts, truck_polygon, static_line_y, static_line_x_start, static_line_x_end, static_roi
global LOADED_ZONES
try:
st = os.stat(_zones_path)
except OSError:
return
if _zones_mtime == st.st_mtime_ns:
return
_zones_mtime = st.st_mtime_ns
LOADED_ZONES = _parse_zones_from_disk()
detection_poly_pts = LOADED_ZONES["counting"]
detection_polygon = Polygon(detection_poly_pts)
truck_poly_pts = LOADED_ZONES["truck"]
truck_polygon = Polygon(truck_poly_pts)
static_line_y = LOADED_ZONES["line_y"]
static_line_x_start = LOADED_ZONES["line_x_start"]
static_line_x_end = LOADED_ZONES["line_x_end"]
_r = LOADED_ZONES["roi"]
static_roi = TruckROI(
x1=_r[0],
y1=_r[1],
x2=_r[2],
y2=_r[3],
line_y=static_line_y,
confidence=1.0,
)
counter.update_line(static_line_y, static_line_x_start, static_line_x_end)
print(f"[INFO] Zones hot-reloaded from {_zones_path} (coord_space={LOADED_ZONES['coord_space']})", flush=True)
# NOTE: counting-knob globals (DUPLICATE_CIRCLE_RADIUS, MIN_VALID_AREA,
# JARAK_TOLERANSI_DUPLIKAT, MAX_REID_TRANSIT_DISTANCE, ...) were set from
# config.yaml at the top of run_prediction — intentionally NOT reset to
# zones.json REFs here (config.yaml is canonical now).
counter = MultiClassLineCounter(
line_y=static_line_y,
line_x_start=static_line_x_start,
line_x_end=static_line_x_end,
margin=20,
dedup_radius=float(DUPLICATE_CIRCLE_RADIUS),
capture_below=float(cfg.counting.capture_below_px),
max_step_dy=float(cfg.counting.max_step_dy_px),
max_gap_frames=int(cfg.counting.max_gap_frames),
unload_confirm_frames=int(cfg.counting.unload_confirm_frames),
)
_idle_timeout = batch_timeout if batch_timeout is not None else cfg.batch.timeout_seconds
_truck_gone = (batch_timeout if batch_timeout is not None
else cfg.batch.truck_gone_tolerance_seconds)
batch_mgr = BatchLifecycleManager(
stabilize_seconds=0.0, # Start batch instantly when triggered by crossing
stabilize_threshold_px=9999.0, # Disable displacement threshold check
sack_idle_timeout=_idle_timeout, # tanpa karung masuk & tanpa karung di truk -> WAITING
min_batch_duration=5.0, # Short min duration
truck_gone_tolerance=_truck_gone, # WAITING: tanpa karung & tanpa sinyal truk -> END BATCH (config.yaml batch.truck_gone_tolerance_seconds)
)
dashboard = DashboardOverlay()
live_writer = LiveFrameWriter(output_path=LIVE_STREAM_FRAME_PATH)
global active_batch_info
if NO_DB:
active_batch_info = None
else:
active_batch_info = _get_state_manager().load_active_batch_state()
# -- restart resume --------------------------------------------------
# B1.1: seed totals from the state file so a mid-batch restart does not
# zero the live count (previously first crossing overwrote it with ~0).
# B1.2: an orphan AUTO batch can't resume (batch_mgr starts fresh), so
# finalize it now instead of losing the row.
_startup_mode = _get_state_manager().load_batch_mode(default_mode=cfg.batch.default_mode)
if active_batch_info:
try:
counter.set_counts(
loading=active_batch_info.get("count", 0),
unloading=active_batch_info.get("unloading", 0),
box_loading=active_batch_info.get("box_count", 0),
box_unloading=active_batch_info.get("box_unloading", 0),
)
print(f"[BATCH] Resume batch #{active_batch_info.get('batch_number')} "
f"dari state file: {counter.loading_count} karung "
f"({counter.unloading_count} unload), {counter.box_loading_count} box.")
except Exception as e:
print(f"[BATCH] Gagal restore counter dari state file: {e}")
if _startup_mode == "auto":
_orphan = active_batch_info.get("batch_number")
finalize_batch(
counter.loading_count,
active_batch_info.get("start_time") or datetime.now().isoformat(),
datetime.now().isoformat(),
box_final_count=counter.box_loading_count,
box_unloading_count=counter.box_unloading_count,
model_mode=active_batch_info.get("model_mode", "?"),
unloading_count=counter.unloading_count,
)
counter.reset()
stabilizer.reset()
box_stabilizer.reset()
print(f"[BATCH] Mode auto: batch terbuka #{_orphan} di-finalisasi pasca-restart.")
frame_idx = 0
last_time = time.time()
current_fps = 0.0
prev_manual_active = (active_batch_info is not None and active_batch_info.get("batch_number") is not None)
prev_auto_active = False
_prev_truck_in_area = False
TRUCK_DET_INTERVAL_IDLE = 5 # Check truck every 5 frames when IDLE
TRUCK_DET_INTERVAL_STABILIZING = 1 # Check truck every frame when STABILIZING
# --- RTSP health monitoring (journal only) -------------------------------
# Frame drops + stalls that can cause miscounts: a freeze crossing the
# count line means missed sacks; on resume the batch timer may have aged
# out (sack_idle_timeout) → premature finalize. Logs flag RISK for the
# operator to verify the manual count for that batch.
_health = _RtspHealth(
gap_warn=float(getattr(cfg.stream, "health_warn_gap_seconds", 5.0) or 5.0),
on_log=lambda m: print(m, flush=True),
)
try:
while cap.isOpened():
_pg = time.perf_counter()
ret, frame = cap.read()
if not ret:
if is_stream:
_health.on_frame_fail(
batch_active=batch_mgr.is_active,
count=counter.loading_count,
)
time.sleep(0.01)
continue
else:
break
if frame is not None:
frame = cv2.resize(frame, (1280, 720))
_reload_zones_if_changed()
# Good frame: catches stalls where read() blocked (no ret=False)
# and closes fail/freeze episodes on recovery.
_health.on_frame(
batch_active=batch_mgr.is_active,
count=counter.loading_count,
)
timestamp = time.time()
perf_t0 = time.perf_counter()
_st_grab = perf_t0 - _pg # RTSP read + upscale (P1)
_st_det = _st_truck = _st_box = 0.0
frame_idx += 1
if max_frames is not None and frame_idx > max_frames:
break
# Track previous state for transition detection
prev_auto_active = batch_mgr.is_active
prev_state = batch_mgr.state
# ================================================================
# STATE-DRIVEN MODEL SWITCHING
# ================================================================
tracked_sacks = []
events = []
# Run tracker and stabilizer for sacks on every frame
if INFERENCE_STRIDE <= 1 or frame_idx % INFERENCE_STRIDE == 0 or 'last_raw_tracked_all' not in locals():
_pd = time.perf_counter()
raw_tracked_all = tracker.update(frame, [])
_st_det += time.perf_counter() - _pd
last_raw_tracked_all = raw_tracked_all
else:
raw_tracked_all = last_raw_tracked_all
# Filter sack (+box, modes B-D) detections. Per-class conf floor
# comes from config.yaml detection_params (authoritative).
# Counter splits by class_name downstream; MultiClassLineCounter
# ignores anything that is not sack/box.
# min_bbox_area guardrails come from config.yaml detection_params.
raw_tracked_sacks = [
d for d in raw_tracked_all
if d.class_name in ("sack", "box") and d.confidence >= confs.get(d.class_name, 0.50)
and _bbox_area_ok(d, min_areas.get(d.class_name, 0))
]
# Truck candidates: from shared tracker (modes A/C) and/or the
# separate v4 truck model (modes B/D, every 5th frame, cached).
truck_candidates = [
d for d in raw_tracked_all
if d.class_name == "truck" and _bbox_area_ok(d, min_areas.get("truck", 0))
]
if separate_truck_model:
if frame_idx % 5 == 0 or 'last_detected_trucks' not in locals():
_pd = time.perf_counter()
last_detected_trucks = truck_detector.detect(frame)
_st_truck += time.perf_counter() - _pd
truck_candidates += last_detected_trucks
# Filter truck detections: Wajib 100% berada di dalam detection_polygon & ambil maksimal 1 bbox terbaik
valid_trucks = []
for d in truck_candidates:
if d.class_name == "truck" and d.confidence >= confs.get("truck", 0.45):
x1, y1, x2, y2 = d.bbox
# Overlap >= 50%, NOT 100% containment: a docked truck's bbox
# rests on the frame bottom (y2 exceeds the polygon's bottom
# edge by 1-2 px), which made truck_in_area flicker False while
# the truck never left (batch 15 split, 2026-09-29 14:07).
# ponytail: area-fraction gate; centroid-inside is the
# stricter upgrade path if background trucks leak into the band.
truck_bbox_poly = box(x1, y1, x2, y2)
area = (x2 - x1) * (y2 - y1)
if (area > 0 and
detection_polygon.intersection(truck_bbox_poly).area / area >= 0.5):
valid_trucks.append((area, d.confidence, d))
# Hanya ambil 1 truk (bbox dengan luas area / confidence terbesar) yang valid di area deteksi
if valid_trucks:
valid_trucks.sort(key=lambda x: (x[0], x[1]), reverse=True)
raw_tracked_trucks = [valid_trucks[0][2]]
else:
raw_tracked_trucks = []
stable = stabilizer.update(raw_tracked_sacks)
# Box stream: modes C/D run a dedicated box tracker (own ID space +
# own stabilizer); mode B shares the yolo11n tracker (single ID space).
stable_boxes = []
if box_tracker is not None:
if INFERENCE_STRIDE <= 1 or frame_idx % INFERENCE_STRIDE == 0 or 'last_raw_tracked_boxes' not in locals():
_pd = time.perf_counter()
raw_tracked_boxes = box_tracker.update(frame, [])
_st_box += time.perf_counter() - _pd
last_raw_tracked_boxes = raw_tracked_boxes
else:
raw_tracked_boxes = last_raw_tracked_boxes
raw_boxes = [d for d in raw_tracked_boxes
if d.class_name == "box"
and _bbox_area_ok(d, min_areas.get("box", 0))]
stable_boxes = box_stabilizer.update(raw_boxes)
stable_boxes = [
d for d in stable_boxes
if detection_polygon.contains(Point((d.bbox[0] + d.bbox[2]) / 2.0, (d.bbox[1] + d.bbox[3]) / 2.0))
]
else:
# Mode B/E: boxes already stabilized alongside sacks; mode A: none.
stable_boxes = [d for d in stable if d.class_name == "box"]
stable = [d for d in stable if d.class_name != "box"]
# Parity with dedicated-tracker branch: drop boxes outside detection area.
stable_boxes = [
d for d in stable_boxes
if detection_polygon.contains(Point((d.bbox[0] + d.bbox[2]) / 2.0, (d.bbox[1] + d.bbox[3]) / 2.0))
]
# Filter using Detection Area (4-point Polygon)
stable = [
d for d in stable
if detection_polygon.contains(Point((d.bbox[0] + d.bbox[2]) / 2.0, (d.bbox[1] + d.bbox[3]) / 2.0))
]
# Combined list for ROI filter / counting / viz (counter splits by class).
# Cross-model suppression: v4 has no box class (white boxes labeled
# "sack"); box model always wins. cross_class_iou <= 0 disables.
if stable_boxes and CROSS_CLASS_IOU > 0:
stable = drop_sacks_overlapping_boxes(stable, stable_boxes, CROSS_CLASS_IOU)
stable_all = stable + stable_boxes
# Count sacks currently visible in the bottom 85% of truck area (for batch start/end condition)
min_ty, max_ty = truck_polygon.bounds[1], truck_polygon.bounds[3]
truck_height = max_ty - min_ty
truck_cutoff_y = min_ty + 0.15 * truck_height
sacks_in_truck_area = 0
for d in stable:
cx = (d.bbox[0] + d.bbox[2]) / 2.0
cy = (d.bbox[1] + d.bbox[3]) / 2.0
if truck_polygon.contains(Point(cx, cy)) and cy >= truck_cutoff_y:
sacks_in_truck_area += 1
# Cek apakah ada truk valid di area deteksi (1 truk, overlap >= 50% polygon)
truck_in_area = len(raw_tracked_trucks) > 0
if truck_in_area != _prev_truck_in_area:
info = ""
if raw_tracked_trucks:
_tb = raw_tracked_trucks[0]
info = " bbox={} conf={:.2f}".format(
tuple(int(v) for v in _tb.bbox), _tb.confidence)
print("[TRUCK] truck_in_area {} -> {} (state={}, valid={}{})".format(
int(_prev_truck_in_area), int(truck_in_area),
batch_mgr.state, len(raw_tracked_trucks), info))
_prev_truck_in_area = truck_in_area
# Cek Mode Batch: auto | do_manual | manual (default from config.yaml)
current_batch_mode = _get_state_manager().load_batch_mode(default_mode=cfg.batch.default_mode)
roi = static_roi
# ================================================================
# MODE OPERATOR (manual / do_manual: controlled by dashboard API)
# ================================================================
if current_batch_mode != "auto":
manual_batch_exists = False
s_data = _get_state_manager().load_active_batch_state()
if s_data and s_data.get("batch_number"):
manual_batch_exists = True
active_batch_info = s_data
else:
# Stop transition below needs the last batch id/counts/times
# (the dashboard already deleted STATE_FILE) — keep them one
# frame; the stop branch clears them.
if not prev_manual_active:
active_batch_info = None
is_batch_active = manual_batch_exists
# Transition handling for Manual Mode
if is_batch_active and not prev_manual_active:
# Mid-batch mode flip (force): keep the open batch's counts
# (B1.1-style) instead of zeroing them. Fresh dashboard
# start carries count>0 only when left over from a flip.
try:
_keep = int(active_batch_info.get("count", 0) or 0)
_keep_box = int(active_batch_info.get("box_count", 0) or 0)
except Exception:
_keep = _keep_box = 0
if _keep or _keep_box:
counter.set_counts(
loading=_keep,
unloading=int(active_batch_info.get("unloading", 0) or 0),
box_loading=_keep_box,
box_unloading=int(active_batch_info.get("box_unloading", 0) or 0),
)
print(f"[BATCH] Mode diganti saat batch aktif — "
f"lanjutkan #{active_batch_info.get('batch_number')} "
f"dengan {counter.loading_count} karung.")
else:
counter.reset()
stabilizer.reset()
box_stabilizer.reset()
print(f"[BATCH] Manual Batch #{active_batch_info.get('batch_number')} dimulai via Tombol.")
system_state = STATE_COUNTING_SACKS
elif not is_batch_active and prev_manual_active:
print(f"[BATCH] Manual Batch dihentikan via Tombol.")
log_manual_batch_stop()
active_batch_info = None
system_state = STATE_WAITING_FOR_TRUCK
counter.reset()
stabilizer.reset()
box_stabilizer.reset()
prev_manual_active = is_batch_active
if is_batch_active:
tracked_sacks = _filter_sacks_in_roi(stable_all, static_roi)
events = counter.update(tracked_sacks)
for ev in events:
log_crossing_event(ev, counter,
active_batch_info["batch_number"], timestamp)
if 'cx' in ev and 'cy' in ev:
counted_sack_positions.append((ev['cx'], ev['cy'], time.time(), ev['track_id']))
if active_batch_info is not None:
active_batch_info["count"] = counter.loading_count
active_batch_info["box_count"] = counter.box_loading_count
active_batch_info["box_unloading"] = counter.box_unloading_count
active_batch_info["unloading"] = counter.unloading_count
active_batch_info["last_detection_time"] = datetime.now().isoformat()
save_active_batch_state()
else:
tracked_sacks = []
events = []
batch_num_disp = active_batch_info.get("batch_number", "--") if active_batch_info else "--"
viz_state = STATE_COUNTING_SACKS if is_batch_active else "IDLE"
viz_progress = 1.0 if is_batch_active else 0.0
# ================================================================
# MODE OTOMATIS (100% Original Algorithm: Truk + Sack Crossing)
# ================================================================
else:
# Run line crossing counter on every frame
tracked_sacks = _filter_sacks_in_roi(stable_all, static_roi)
events = counter.update(tracked_sacks)
has_crossing = len(events) > 0
# --- Sack-driven Batch Lifecycle Transitions ---
if batch_mgr.state in ("IDLE", "TRUCK_STABILIZING"):
batch_mgr.update_truck(has_crossing, (0.0, 0.0), timestamp)
if batch_mgr.state in ("COUNTING_SACKS", "WAITING_FOR_ACTIVITY"):
batch_mgr.update_sacks(
has_crossing_event=has_crossing,
sacks_in_area_count=sacks_in_truck_area,
timestamp=timestamp,
loading_count=counter.loading_count,
unloading_count=counter.unloading_count,
)
if batch_mgr.state == "WAITING_FOR_ACTIVITY":
activity_detected = has_crossing or (sacks_in_truck_area > 0) or truck_in_area
batch_mgr.update_truck(activity_detected, None, timestamp)
for ev in events:
log_crossing_event(ev, counter,
active_batch_info["batch_number"] if active_batch_info else 0,
timestamp)
if 'cx' in ev and 'cy' in ev:
counted_sack_positions.append((ev['cx'], ev['cy'], time.time(), ev['track_id']))
if active_batch_info is not None:
active_batch_info["count"] = counter.loading_count
active_batch_info["box_count"] = counter.box_loading_count
active_batch_info["box_unloading"] = counter.box_unloading_count
active_batch_info["unloading"] = counter.unloading_count
active_batch_info["last_detection_time"] = datetime.now().isoformat()
save_active_batch_state()
# Batch just started (STABILIZING -> COUNTING)
if batch_mgr.is_active and not prev_auto_active:
if active_batch_info and active_batch_info.get("batch_number"):
# Force-flip manual->auto with an open batch: keep the
# existing number/counts instead of minting a duplicate.
counter.set_counts(
loading=int(active_batch_info.get("count", 0) or 0),
unloading=int(active_batch_info.get("unloading", 0) or 0),
box_loading=int(active_batch_info.get("box_count", 0) or 0),
box_unloading=int(active_batch_info.get("box_unloading", 0) or 0),
)
print(f"[BATCH] Mode auto dengan batch aktif — "
f"lanjut #{active_batch_info['batch_number']}.")
else:
counting_date = get_counting_date()
batch_num = get_next_batch_number(counting_date)
now_iso = datetime.now().isoformat()
active_batch_info = {
"counting_date": counting_date,
"batch_number": batch_num,
"count": 0,
"box_count": 0,
"model_mode": mode,
"start_time": now_iso,
"last_detection_time": now_iso
}
save_active_batch_state()
print(f"[BATCH] Sesi batch #{active_batch_info.get('batch_number')} dimulai secara otomatis.")
system_state = STATE_COUNTING_SACKS
# Batch just ended (WAITING -> IDLE, truck left)
elif not batch_mgr.is_active and prev_auto_active:
final_count = counter.loading_count
start_iso = active_batch_info["start_time"] if active_batch_info else datetime.now().isoformat()
end_iso = datetime.now().isoformat()
batch_num = active_batch_info["batch_number"] if active_batch_info else 0
finalize_batch(final_count, start_iso, end_iso,
box_final_count=counter.box_loading_count,
box_unloading_count=counter.box_unloading_count,
model_mode=mode,
unloading_count=counter.unloading_count)
print(f"[BATCH] Truk pergi. Sesi batch #{batch_num} selesai secara otomatis. "
f"Total karung: {final_count}, box: {counter.box_loading_count}.")
system_state = STATE_WAITING_FOR_TRUCK
counter.reset()
stabilizer.reset()
box_stabilizer.reset()
if batch_mgr.state == "TRUCK_STABILIZING" and prev_state != "TRUCK_STABILIZING":
system_state = "TRUCK_STABILIZING"
elif batch_mgr.state == "WAITING_FOR_ACTIVITY" and prev_state != "WAITING_FOR_ACTIVITY":
system_state = "WAITING_FOR_ACTIVITY"
elif batch_mgr.state == "COUNTING_SACKS" and prev_state == "WAITING_FOR_ACTIVITY":
system_state = STATE_COUNTING_SACKS
prev_auto_active = batch_mgr.is_active
is_batch_active = batch_mgr.is_active
batch_num_disp = batch_mgr.current_batch_id
viz_state = batch_mgr.state
viz_progress = batch_mgr.stabilize_progress
# Sync counts to metrics so APIs get correct results
metrics['total_masuk'] = counter.loading_count
metrics['total_keluar'] = counter.unloading_count
metrics['box_masuk'] = counter.box_loading_count
metrics['box_keluar'] = counter.box_unloading_count
# 4. Draw Dashboard visualization overlay
perf_draw = time.perf_counter()
try:
with open(os.path.join(os.path.dirname(LIVE_STREAM_FRAME_PATH), "viewers.json")) as _vf:
_vw = json.load(_vf)
except Exception:
_vw = {"total": 0, "full": 0}
if _vw.get("total", 0) > 0: # S2: nobody watching -> no draw/enc
viz = dashboard.draw(
frame=frame,
detections=stable if ((is_batch_active and SHOW_ALL_BBOXES) or (not is_batch_active)) and 'stable' in dir() else tracked_sacks,
roi=roi,
loading_count=counter.loading_count,
unloading_count=counter.unloading_count,
batch_id=batch_num_disp,
history=batch_mgr.history if current_batch_mode == "auto" else [],
system_state=viz_state,
batch_duration=batch_mgr.batch_duration if current_batch_mode == "auto" else 0,
idle_timer=batch_mgr.time_since_last_sack_activity if current_batch_mode == "auto" else 0,
stabilize_progress=viz_progress,
waiting_duration=batch_mgr.waiting_duration if current_batch_mode == "auto" else 0,
)
# Debug: draw zone polygons + vertex coords per office toggles (or DEBUG_ZONES=1)
_lz = LOADED_ZONES or {}
if _lz:
_toggles = _load_debug_zone_toggles()
_colors = {"palet": (255, 0, 255), "truck": (0, 165, 255), "counting": (0, 255, 255)}
for _name in ("palet", "truck", "counting"):
if not _toggles.get(_name):
continue
_pts = _lz.get(_name, [])
_raw_pts = _lz.get("raw_" + _name, _pts)
if not _pts:
continue
_arr = np.array(_pts, dtype=np.int32).reshape((-1, 1, 2))
cv2.polylines(viz, [_arr], True, _colors[_name], 2)
for _i, (_x, _y) in enumerate(_pts):
_rx, _ry = _raw_pts[_i] if _i < len(_raw_pts) else (_x, _y)
cv2.circle(viz, (int(_x), int(_y)), 5, _colors[_name], -1)
_lbl = f"{_name}[{_i}] [{int(_rx)},{int(_ry)}]"
_lx = max(4, min(1090, int(_x) + 6))
_ly = max(16, min(712, int(_y) - 6))
cv2.putText(viz, _lbl, (_lx, _ly),
cv2.FONT_HERSHEY_SIMPLEX, 0.42, (0, 0, 0), 3, cv2.LINE_AA)
cv2.putText(viz, _lbl, (_lx, _ly),
cv2.FONT_HERSHEY_SIMPLEX, 0.42, _colors[_name], 1, cv2.LINE_AA)
if _toggles.get("line"):
_lx0 = int(_lz.get("line_x_start", 0))
_lx1 = int(_lz.get("line_x_end", 0))
_ly0 = int(_lz.get("line_y", 0))
_rlx0 = int(_lz.get("raw_line_x_start", _lx0))
_rlx1 = int(_lz.get("raw_line_x_end", _lx1))
_rly0 = int(_lz.get("raw_line_y", _ly0))
cv2.rectangle(viz, (_lx0, max(0, _ly0 - 20)), (_lx1, min(720, _ly0 + 20)), (0, 255, 0), 1)
cv2.line(viz, (_lx0, _ly0), (_lx1, _ly0), (255, 0, 255), 2)
cv2.circle(viz, (_lx0, _ly0), 5, (255, 0, 255), -1)
cv2.circle(viz, (_lx1, _ly0), 5, (255, 0, 255), -1)
_line_lbl = f"line y={_rly0} x=[{_rlx0}..{_rlx1}]"
cv2.putText(viz, _line_lbl, (max(4, _lx0 + 6), max(16, _ly0 - 24)),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 0), 3, cv2.LINE_AA)
cv2.putText(viz, _line_lbl, (max(4, _lx0 + 6), max(16, _ly0 - 24)),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 0, 255), 1, cv2.LINE_AA)
# Draw Truck Bounding Boxes on viz frame
if 'raw_tracked_trucks' in locals() and raw_tracked_trucks:
for trk in raw_tracked_trucks:
tx1, ty1, tx2, ty2 = [int(v) for v in trk.bbox]
t_label = f"TRUCK {trk.confidence:.0%}"
if trk.track_id is not None:
t_label = f"TRUCK #{trk.track_id} {trk.confidence:.0%}"
cv2.rectangle(viz, (tx1, ty1), (tx2, ty2), (0, 165, 255), 2) # Orange color
# Label tag background
lbl_size, _ = cv2.getTextSize(t_label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
cv2.rectangle(viz, (tx1, max(0, ty1 - 20)), (tx1 + lbl_size[0] + 6, ty1), (0, 165, 255), -1)
cv2.putText(viz, t_label, (tx1 + 3, max(14, ty1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
# Draw active Duplicate Radius Circles on viz frame (terkini 3.0 detik)
if 'counted_sack_positions' in globals() and counted_sack_positions:
rad_vis = DUPLICATE_CIRCLE_RADIUS if ('DUPLICATE_CIRCLE_RADIUS' in globals() and DUPLICATE_CIRCLE_RADIUS > 0) else 60
now_t = time.time()
# Clean up expired entries in-place to avoid memory accumulation
counted_sack_positions[:] = [p for p in counted_sack_positions if len(p) >= 3 and (now_t - p[2]) <= 3.0]
for pos_item in counted_sack_positions:
px, py = pos_item[0], pos_item[1]
tid = pos_item[3] if len(pos_item) > 3 else 0
cv2.circle(viz, (int(px), int(py)), int(rad_vis), (0, 255, 255), 2, lineType=cv2.LINE_AA)
cv2.circle(viz, (int(px), int(py)), 4, (0, 255, 0), -1)
cv2.putText(viz, f"DEDUP #{tid}", (int(px) - 25, max(15, int(py) - int(rad_vis) - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 255), 1)
cv2.putText(viz, f"RADIUS DEDUP: {rad_vis}px", (viz.shape[1] - 270, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 255, 255), 2)
# Write live frame to RAM disk for Flask port 5000
perf_enc = time.perf_counter()
if not NO_DASHBOARD:
live_writer.write_frame(
viz,
preview=(_vw.get("total", 0) - _vw.get("full", 0)) > 0,
quality=60,
full=_vw.get("full", 0) > 0,
)
perf_end = time.perf_counter()
elif not NO_DASHBOARD and not os.path.isfile(LIVE_STREAM_FRAME_PATH):
# P0: /dev/shm is wiped on boot -> if we never write, the dashboard
# 503s before counting the viewer and viewers.json stays 0 forever
# (deadlock). One unconditional write breaks the cycle.
live_writer.write_frame(frame, preview=True, quality=60, full=True)
perf_enc = perf_end = time.perf_counter()
else:
perf_end = perf_enc = time.perf_counter()
# S3 instrumentation: where does a frame actually go?
# pre-draw = inference + tracker + counting + state
# draw = dashboard.draw + truck/dedup overlays
# enc = JPEG write(s)
if frame_idx % 100 == 0:
_state_ms = (perf_draw - perf_t0) * 1000 - (_st_det + _st_truck + _st_box) * 1000
print(
f"[PERF] loop={(perf_end - perf_t0) * 1000:.0f}ms "
f"grab={_st_grab * 1000:.0f}ms "
f"det={_st_det * 1000:.0f}ms "
f"truck={_st_truck * 1000:.0f}ms "
f"box={_st_box * 1000:.0f}ms "
f"state={_state_ms:.0f}ms "
f"pre-draw={(perf_draw - perf_t0) * 1000:.0f}ms "
f"draw={(perf_enc - perf_draw) * 1000:.0f}ms "
f"enc={(perf_end - perf_enc) * 1000:.0f}ms "
f"fps={current_fps:.1f} "
f"viewers={_vw.get('total', 0)}/{_vw.get('full', 0)} "
f"grbfail={_health.fail_total} freeze={_health.freeze_total} "
f"gapmax={_health.gap_max:.1f}",
flush=True,
)
# Compute FPS every 25 frames
if frame_idx % 25 == 0:
elapsed = time.time() - last_time
current_fps = 25.0 / elapsed if elapsed > 0 else 0
last_time = time.time()
if NO_DASHBOARD:
continue
status_file = os.getenv('LIVE_STATUS_FILE', '/dev/shm/jetson-counter/live_status.json' if os.name != 'nt' else 'd:/Belajar/menghitung karung/live_status.json')
update_live_status(current_fps, status_file)
finally:
# Membersihkan dan menutup semua resource
cap.release()
cv2.destroyAllWindows()
net_count = metrics['total_masuk'] - metrics['total_keluar']
box_net = metrics['box_masuk'] - metrics['box_keluar']
final_results = {
"total_masuk_truck": metrics['total_masuk'],
"total_keluar_truck": metrics['total_keluar'],
"net_karung_di_truck": net_count,
"box_masuk_truck": metrics['box_masuk'],
"box_keluar_truck": metrics['box_keluar'],
"net_box_di_truck": box_net,
}
with open(output_json_path, 'w') as f:
json.dump(final_results, f, indent=4)
print("\n" + "=" * 50)
print("PROSES SELESAI!")
print(final_results)
if __name__ == "__main__":
args = parse_args()
# Load .env (override=True so repo .env / --env takes precedence over stale systemd EnvironmentFile vars)
try:
from dotenv import load_dotenv
load_dotenv(args.env, override=True)
except ImportError:
print("[WARN] python-dotenv tidak tersedia, memakai environment apa adanya.")
NO_DASHBOARD = args.no_dashboard
NO_DB = args.no_db
# Unified config first (config.yaml canonical; .env supplies secrets/RTSP).
_CFG = load_config(args.config or _DEFAULT_CONFIG_PATH)
_CFG = apply_cli_overrides_to_config(_CFG, args)
if args.source:
SOURCE_INPUT = args.source
else:
_env_url = _CFG.stream.rtsp_url
SOURCE_INPUT = _env_url if _env_url else ("anomali.mp4" if (os.path.exists("anomali.mp4") and os.name == 'nt') else "rtsp://192.168.192.96:8554/cam")
OUTPUT_JSON = args.output_json or "hasil_perhitungan.json"
print(f"[INFO] config={args.config or _DEFAULT_CONFIG_PATH} source={SOURCE_INPUT} "
f"model_mode={resolve_model_mode(args.model_mode)} "
f"no_dashboard={NO_DASHBOARD} no_db={NO_DB}")
try:
run_prediction(
model_path=args.model,
source_path=SOURCE_INPUT,
output_json_path=OUTPUT_JSON,
max_frames=args.max_frames,
sack_conf=args.sack_conf,
truck_conf=args.truck_conf,
box_conf=args.box_conf,
box_model_path=args.box_model,
model_mode=args.model_mode,
output_dir=args.output_dir,
batch_timeout=args.batch_timeout,
config_path=args.config or _DEFAULT_CONFIG_PATH,
cfg=_CFG,
)
except KeyboardInterrupt:
print("\n" + "=" * 50)
print("[INFO] Program dihentikan secara manual (Ctrl+C).")
print("Membersihkan resource dan menyimpan hasil perhitungan terakhir...")
# Simpan hasil perhitungan parsial sebelum keluar
final_results = {
"total_masuk_truck": metrics['total_masuk'],
"total_keluar_truck": metrics['total_keluar'],
"net_karung_di_truck": metrics['total_masuk'] - metrics['total_keluar'],
"box_masuk_truck": metrics['box_masuk'],
"box_keluar_truck": metrics['box_keluar'],
"net_box_di_truck": metrics['box_masuk'] - metrics['box_keluar'],
}
with open(OUTPUT_JSON, 'w') as f:
json.dump(final_results, f, indent=4)
print("Hasil akhir yang disimpan:")
print(final_results)
print("=" * 50)