fix: resolve production-readiness issues across persistence, deploy, security, and pipeline

This commit is contained in:
openhands committed 2026-10-19 15:17:24 +07:00
1 parent 3b15f48338
commit fa1b07a381
11 files changed
+398 -248

No files matched your search

+7 -5
View File
@@ -322,12 +322,14 @@ OFFICE_PORT = CFG.dashboard.office_port
def is_office_request():
"""Check if request comes from office port."""
server_port = request.environ.get("SERVER_PORT", str(DASHBOARD_PORT))
# Also check Host header if port is in Host (e.g. 192.168.192.96:5721)
host_header = request.headers.get("Host", "")
if f":{OFFICE_PORT}" in host_header or str(server_port) == str(OFFICE_PORT):
server_port = str(request.environ.get("SERVER_PORT", ""))
if server_port == str(OFFICE_PORT):
return True
return False
if server_port == str(DASHBOARD_PORT):
return False
# Fallback when behind proxy or default WSGI port without explicit SERVER_PORT
host_header = request.headers.get("Host", "")
return f":{OFFICE_PORT}" in host_header
def _batch_active() -> bool:
+38 -8
View File
@@ -11,6 +11,29 @@ MODEL_ENGINES = [
"model_karung_truk.engine",
]
SRC_MODULES = [
"__init__.py",
"batch.py",
"clip.py",
"clip_jobs.py",
"config.py",
"config_loader.py",
"counting.py",
"dashboard.py",
"detection.py",
"do_batch.py",
"do_ocr.py",
"logger.py",
"main.py",
"persistence.py",
"pipeline.py",
"stabilizer.py",
"tracking.py",
"truck_roi.py",
"ui.py",
"validation.py",
]
files_to_sync = [
("templates/operator.html", "/home/jetson/karung/templates/operator.html"),
("templates/monitoring.html", "/home/jetson/karung/templates/monitoring.html"),
@@ -19,23 +42,30 @@ files_to_sync = [
("predict.py", "/home/jetson/karung/predict.py"),
("config.yaml", "/home/jetson/karung/config.yaml"),
(".env", "/home/jetson/karung/.env"),
] + [
(f"src/{f}", f"/home/jetson/karung/src/{f}") for f in SRC_MODULES
] + [
(f"models/{f}", f"/home/jetson/karung/models/{f}") for f in MODEL_ENGINES
]
def run():
host = os.getenv('JETSON_HOST', '192.168.192.96')
user = os.getenv('JETSON_USER', 'jetson')
password = os.getenv('JETSON_PASS', 'jetson')
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.192.96', username='jetson', password='jetson', timeout=10)
client.connect(host, username=user, password=password, timeout=10)
sftp = client.open_sftp()
# Ensure remote models/ dir exists (sftp.put fails otherwise)
try:
sftp.stat("/home/jetson/karung/models")
except FileNotFoundError:
print("Creating remote /home/jetson/karung/models/ ...")
sftp.mkdir("/home/jetson/karung/models")
# Ensure remote models/ and src/ dirs exist (sftp.put fails otherwise)
for remote_dir in ("/home/jetson/karung/models", "/home/jetson/karung/src"):
try:
sftp.stat(remote_dir)
except FileNotFoundError:
print(f"Creating remote {remote_dir}/ ...")
sftp.mkdir(remote_dir)
print("Uploading updated files to Jetson...")
for local_f, remote_f in files_to_sync:
@@ -49,7 +79,7 @@ def run():
print("All files uploaded successfully!")
print("Restarting services on Jetson...")
cmd = "echo jetson | sudo -S systemctl restart karung-counter karung-counter-dashboard"
cmd = f"echo {password} | sudo -S systemctl restart karung-counter karung-counter-dashboard"
stdin, stdout, stderr = client.exec_command(cmd)
print("STDOUT:", stdout.read().decode('utf-8', errors='ignore'))
print("STDERR:", stderr.read().decode('utf-8', errors='ignore'))
+31 -98
View File
@@ -6,42 +6,32 @@ import numpy as np
import json
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from ultralytics import YOLO
from shapely.geometry import Point, Polygon, LineString, box
from collections import defaultdict, deque
from shapely.geometry import Point, Polygon, box
import torch
import sqlite3
from datetime import datetime, timedelta
from datetime import datetime
import logging
# Import repo rafan modules
from src.detection import SackDetector, TruckDetector, BoxDetector
# Import repo modules
from src.detection import TruckDetector
from src.tracking import ByteTrackTracker
from src.stabilizer import BboxStabilizer
from src.truck_roi import TruckROITracker
from src.counting import LineCrossCounter, MultiClassLineCounter, drop_sacks_overlapping_boxes
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 CountingPipeline, RTSPStreamReader
from src.pipeline import RTSPStreamReader
from src.ui import LiveFrameWriter, update_live_status
from src.validation import InputValidator
from src.config_loader import (
Config,
check_legacy_batch_mode,
load_config,
read_zone_polygons,
resolve_active_mode,
)
from src.persistence import (
DatabaseManager,
StateManager,
get_counting_date as _persistence_get_counting_date,
init_db,
get_next_batch_number,
get_last_batch_info,
)
# --- SQLite Database & State Configuration ---
@@ -272,7 +262,7 @@ def finalize_batch(final_count, start_time_iso, end_time_iso,
class PipelineState:
"""Encapsulates runtime and calibration state for the counting pipeline."""
"""Encapsulates active runtime state for the counting pipeline."""
def __init__(self):
self.metrics = {
@@ -281,20 +271,7 @@ class PipelineState:
"box_masuk": 0,
"box_keluar": 0,
}
self.counted_sacks = {}
self.lost_counted_sacks = {}
self.counted_sack_positions = []
self.confirm_delay_sec = 0.5
self.exit_confirm_delay_sec = 6.0
self.min_valid_area = 15000
self.jarak_toleransi_duplikat = 80
self.max_reid_transit_distance = 400
self.circle_stay_timeout_sec = 10.0
self.entry_overlap_threshold = 0.20
self.exit_overlap_threshold = 0.05
self.tolerance_missing_frames = 1200
self.max_reid_frames = 200
self.debounce_frames = 8
pipeline_state = PipelineState()
@@ -437,6 +414,16 @@ def build_model_pipeline(mode, cfg, device, base_dir=None):
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 = ByteTrackTracker(_load(primary_key), dp_sack.conf, dp_sack.iou)
truck_detector = (
TruckDetector(_load(truck_key), dp_truck.conf,
@@ -477,14 +464,11 @@ def build_model_pipeline(mode, cfg, device, base_dir=None):
# =====================================================================
# 1. KONFIGURASI KOORDINAT ZONA & STREAMING STATE
# =====================================================================
import queue
width = 1280
height = 720
scale_x = 1.0
scale_y = 1.0
current_fps = 0.0
save_queue = queue.Queue(maxsize=100)
# =====================================================================
@@ -510,7 +494,7 @@ def run_prediction(model_path, source_path,
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 save_queue, scale_x, scale_y, _CFG
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)
@@ -559,19 +543,8 @@ def run_prediction(model_path, source_path,
batch_logger = None
print(f"[WARN] CSV logger gagal diinisialisasi: {e}")
# --- Counting-knob state from config (values match legacy zones.json) ---
pipeline_state.confirm_delay_sec = cfg.counting.confirm_delay_sec
pipeline_state.exit_confirm_delay_sec = cfg.counting.exit_confirm_delay_sec
# --- Counting-knob state from config ---
DUPLICATE_CIRCLE_RADIUS = cfg.counting.duplicate_circle_radius
pipeline_state.min_valid_area = cfg.counting.min_valid_area
pipeline_state.jarak_toleransi_duplikat = cfg.counting.jarak_toleransi_duplikat
pipeline_state.max_reid_transit_distance = cfg.counting.max_reid_transit_distance
pipeline_state.circle_stay_timeout_sec = cfg.counting.circle_stay_timeout_sec
pipeline_state.entry_overlap_threshold = cfg.counting.entry_overlap_threshold
pipeline_state.exit_overlap_threshold = cfg.counting.exit_overlap_threshold
pipeline_state.tolerance_missing_frames = cfg.counting.tolerance_missing_frames
pipeline_state.max_reid_frames = cfg.counting.max_reid_frames
pipeline_state.debounce_frames = cfg.counting.debounce_frames
CROSS_CLASS_IOU = cfg.counting.cross_class_iou
# Legacy batch_mode.json no longer drives the mode — nudge once if stale.
@@ -583,15 +556,10 @@ def run_prediction(model_path, source_path,
# 1. Silencing YOLO logs
from ultralytics.utils import LOGGER
import logging
LOGGER.setLevel(logging.WARNING)
INFERENCE_STRIDE = inference_stride if inference_stride is not None else cfg.stream.inference_stride
saver = None
saver_thread = None
save_queue = None
# Reset lists and dicts
for k in metrics:
metrics[k] = 0
@@ -712,33 +680,20 @@ def run_prediction(model_path, source_path,
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
elif os.path.exists(STATE_FILE):
try:
with open(STATE_FILE, "r") as sf:
active_batch_info = json.load(sf)
except Exception:
active_batch_info = None
else:
active_batch_info = None
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 = "auto"
try:
if os.path.exists(BATCH_MODE_FILE):
with open(BATCH_MODE_FILE, "r") as bmf:
_raw = json.load(bmf).get("mode")
if _raw in ("auto", "manual", "do_manual"):
_startup_mode = _raw
except Exception:
pass
_startup_mode = _get_state_manager().load_batch_mode(default_mode=cfg.batch.default_mode)
if active_batch_info:
try:
counter.set_counts(
@@ -807,8 +762,7 @@ def run_prediction(model_path, source_path,
print(f"[WARNING] Stream RTSP freeze terdeteksi. Batch timer dibekukan.")
# Tetap tulis frame terakhir ke dashboard agar tidak blank
if frame is not None and not NO_DASHBOARD:
writer = LiveFrameWriter(output_path=LIVE_STREAM_FRAME_PATH)
writer.write_frame(frame, preview=True, quality=60, full=True)
live_writer.write_frame(frame, preview=True, quality=60, full=True)
continue
# Track previous state for transition detection
@@ -943,17 +897,8 @@ def run_prediction(model_path, source_path,
batch_mgr.state, len(raw_tracked_trucks), info))
_prev_truck_in_area = truck_in_area
# Cek Mode Batch: auto | do_manual | manual (default: auto)
current_batch_mode = "auto"
if os.path.exists(BATCH_MODE_FILE):
try:
with open(BATCH_MODE_FILE, "r") as bmf:
bm_data = json.load(bmf)
raw_mode = bm_data.get("mode", "auto")
current_batch_mode = raw_mode if raw_mode in (
"auto", "do_manual", "manual") else "auto"
except Exception:
pass
# 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
@@ -962,15 +907,10 @@ def run_prediction(model_path, source_path,
# ================================================================
if current_batch_mode != "auto":
manual_batch_exists = False
if os.path.exists(STATE_FILE):
try:
with open(STATE_FILE, "r") as sf:
s_data = json.load(sf)
if s_data and s_data.get("batch_number"):
manual_batch_exists = True
active_batch_info = s_data
except Exception:
pass
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
@@ -1206,8 +1146,7 @@ def run_prediction(model_path, source_path,
# Write live frame to RAM disk for Flask port 5000
perf_enc = time.perf_counter()
if not NO_DASHBOARD:
writer = LiveFrameWriter(output_path=LIVE_STREAM_FRAME_PATH)
writer.write_frame(
live_writer.write_frame(
viz,
preview=(_vw.get("total", 0) - _vw.get("full", 0)) > 0,
quality=60,
@@ -1218,8 +1157,7 @@ def run_prediction(model_path, source_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.
writer = LiveFrameWriter(output_path=LIVE_STREAM_FRAME_PATH)
writer.write_frame(frame, preview=True, quality=60, full=True)
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()
@@ -1257,11 +1195,6 @@ def run_prediction(model_path, source_path,
finally:
# Membersihkan dan menutup semua resource
if saver_thread is not None:
save_queue.put(None)
saver_thread.join(timeout=2.0)
if saver is not None:
saver.release()
cap.release()
cv2.destroyAllWindows()
+163 -126
View File
@@ -1,5 +1,6 @@
"""Persistence module for database operations and state management."""
import contextlib
import json
import os
import sqlite3
@@ -22,52 +23,87 @@ class DatabaseManager:
if parent:
os.makedirs(parent, exist_ok=True)
conn = sqlite3.connect(self.db_path)
cur = conn.cursor()
with contextlib.closing(sqlite3.connect(self.db_path, timeout=10)) as conn:
cur = conn.cursor()
# Create batches table
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)
# Create batches table
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)
)
""")
# Create daily_summaries table
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)
)
""")
# Additive migration for box counting + model mode + DO/net columns (idempotent)
cur.execute("PRAGMA table_info(batches)")
_cols = {r[1] for r in cur.fetchall()}
for _col, _typ in (
("box_loading", "INTEGER NOT NULL DEFAULT 0"),
("box_unloading", "INTEGER NOT NULL DEFAULT 0"),
("model_mode", "TEXT NOT NULL DEFAULT 'A'"),
("plate", "TEXT NOT NULL DEFAULT ''"),
("do_numbers", "TEXT NOT NULL DEFAULT '[]'"),
("expected_sack", "INTEGER NOT NULL DEFAULT 0"),
("expected_box", "INTEGER NOT NULL DEFAULT 0"),
("net_sack", "INTEGER NOT NULL DEFAULT 0"),
("net_box", "INTEGER NOT NULL DEFAULT 0"),
):
if _col not in _cols:
cur.execute(f"ALTER TABLE batches ADD COLUMN {_col} {_typ}")
# Delivery orders (DO-gated manual batch)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS delivery_orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
counting_date TEXT NOT NULL,
photo_path TEXT NOT NULL,
no_do TEXT NOT NULL DEFAULT '',
plate TEXT NOT NULL DEFAULT '',
expected_sack INTEGER NOT NULL DEFAULT 0,
expected_box INTEGER NOT NULL DEFAULT 0,
ocr_raw TEXT,
status TEXT NOT NULL DEFAULT 'draft',
batch_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
)
""")
# Create daily_summaries table
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)
cur.execute(
"CREATE INDEX IF NOT EXISTS idx_do_date_status "
"ON delivery_orders(counting_date, status)"
)
""")
# Additive migration for box counting + model mode (idempotent)
cur.execute("PRAGMA table_info(batches)")
_cols = {r[1] for r in cur.fetchall()}
for _col, _typ in (
("box_loading", "INTEGER NOT NULL DEFAULT 0"),
("box_unloading", "INTEGER NOT NULL DEFAULT 0"),
("model_mode", "TEXT NOT NULL DEFAULT 'A'"),
):
if _col not in _cols:
cur.execute(f"ALTER TABLE batches ADD COLUMN {_col} {_typ}")
# One-time backfill (guarded by user_version)
if cur.execute("PRAGMA user_version").fetchone()[0] < 1:
cur.execute("UPDATE batches SET net_sack = count WHERE net_sack = 0 AND count != 0")
cur.execute("UPDATE batches SET net_box = box_loading WHERE net_box = 0 AND box_loading != 0")
cur.execute("PRAGMA user_version = 1")
conn.commit()
conn.close()
conn.commit()
print(f"[DB Info] Inisialisasi SQLite database berhasil: {self.db_path}")
except Exception as e:
@@ -81,25 +117,24 @@ class DatabaseManager:
) -> int:
"""Get the next batch number for a given date/camera/object combination."""
try:
conn = sqlite3.connect(self.db_path)
cur = conn.cursor()
with contextlib.closing(sqlite3.connect(self.db_path, timeout=10)) as conn:
cur = conn.cursor()
if camera_name is None:
camera_name = os.getenv("CAMERA_NAME", "CC1")
if object_label is None:
object_label = os.getenv("OBJECT_LABEL", "karung-pakan")
if camera_name is None:
camera_name = os.getenv("CAMERA_NAME", "CC1")
if object_label is None:
object_label = os.getenv("OBJECT_LABEL", "karung-pakan")
cur.execute(
"""
SELECT COALESCE(MAX(batch_number), 0)
FROM batches
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
""",
(counting_date, camera_name, object_label),
)
row = cur.fetchone()
conn.close()
return row[0] + 1
cur.execute(
"""
SELECT COALESCE(MAX(batch_number), 0)
FROM batches
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
""",
(counting_date, camera_name, object_label),
)
row = cur.fetchone()
return row[0] + 1
except Exception as e:
print(f"[DB Error] Gagal mendapatkan batch_number: {e}")
return 1
@@ -112,36 +147,35 @@ class DatabaseManager:
) -> Optional[Dict[str, Any]]:
"""Get the last batch information for a given date/camera/object combination."""
try:
conn = sqlite3.connect(self.db_path)
cur = conn.cursor()
with contextlib.closing(sqlite3.connect(self.db_path, timeout=10)) as conn:
cur = conn.cursor()
if camera_name is None:
camera_name = os.getenv("CAMERA_NAME", "CC1")
if object_label is None:
object_label = os.getenv("OBJECT_LABEL", "karung-pakan")
if camera_name is None:
camera_name = os.getenv("CAMERA_NAME", "CC1")
if object_label is None:
object_label = os.getenv("OBJECT_LABEL", "karung-pakan")
cur.execute(
"""
SELECT batch_number, count, start_time, end_time, box_loading, box_unloading, model_mode
FROM batches
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
ORDER BY batch_number DESC LIMIT 1
""",
(counting_date, camera_name, object_label),
)
row = cur.fetchone()
conn.close()
cur.execute(
"""
SELECT batch_number, count, start_time, end_time, box_loading, box_unloading, model_mode
FROM batches
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
ORDER BY batch_number DESC LIMIT 1
""",
(counting_date, camera_name, object_label),
)
row = cur.fetchone()
if row:
return {
"batch_number": row[0],
"count": row[1],
"start_time": row[2],
"end_time": row[3],
"box_loading": row[4],
"box_unloading": row[5],
"model_mode": row[6],
}
if row:
return {
"batch_number": row[0],
"count": row[1],
"start_time": row[2],
"end_time": row[3],
"box_loading": row[4],
"box_unloading": row[5],
"model_mode": row[6],
}
except Exception as e:
print(f"[DB Error] Gagal mendapatkan batch terakhir: {e}")
return None
@@ -149,43 +183,42 @@ class DatabaseManager:
def insert_batch(self, batch_data: Dict[str, Any]) -> bool:
"""Insert a new batch record into the database."""
try:
conn = sqlite3.connect(self.db_path)
cur = conn.cursor()
with contextlib.closing(sqlite3.connect(self.db_path, timeout=10)) as conn:
cur = conn.cursor()
counting_date = batch_data.get("counting_date")
batch_number = batch_data.get("batch_number")
camera_name = batch_data.get("camera_name") or os.getenv("CAMERA_NAME", "CC1")
object_label = batch_data.get("object_label") or os.getenv("OBJECT_LABEL", "karung-pakan")
count = batch_data.get("count", 0)
start_time = batch_data.get("start_time")
end_time = batch_data.get("end_time")
box_loading = batch_data.get("box_loading", 0)
box_unloading = batch_data.get("box_unloading", 0)
model_mode = batch_data.get("model_mode", "A")
counting_date = batch_data.get("counting_date")
batch_number = batch_data.get("batch_number")
camera_name = batch_data.get("camera_name") or os.getenv("CAMERA_NAME", "CC1")
object_label = batch_data.get("object_label") or os.getenv("OBJECT_LABEL", "karung-pakan")
count = batch_data.get("count", 0)
start_time = batch_data.get("start_time")
end_time = batch_data.get("end_time")
box_loading = batch_data.get("box_loading", 0)
box_unloading = batch_data.get("box_unloading", 0)
model_mode = batch_data.get("model_mode", "A")
cur.execute(
"""
INSERT INTO batches
(counting_date, batch_number, camera_name, object_label,
count, start_time, end_time, box_loading, box_unloading, model_mode)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
counting_date,
batch_number,
camera_name,
object_label,
count,
start_time,
end_time,
box_loading,
box_unloading,
model_mode,
),
)
conn.commit()
conn.close()
return True
cur.execute(
"""
INSERT INTO batches
(counting_date, batch_number, camera_name, object_label,
count, start_time, end_time, box_loading, box_unloading, model_mode)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
counting_date,
batch_number,
camera_name,
object_label,
count,
start_time,
end_time,
box_loading,
box_unloading,
model_mode,
),
)
conn.commit()
return True
except Exception as e:
print(f"[DB Error] Insert batch failed: {e}")
return False
@@ -389,27 +422,31 @@ class StateManager:
print(f"[DB Error] Gagal menulis {self.state_file}: {e}")
return False
def load_batch_mode(self) -> str:
def load_batch_mode(self, default_mode: str = "auto") -> str:
"""Load batch mode from batch mode file."""
fallback = default_mode if default_mode in ("auto", "do_manual", "manual") else "auto"
if not os.path.exists(self.batch_mode_file):
return "auto"
return fallback
try:
with open(self.batch_mode_file, "r", encoding="utf-8") as f:
data = json.load(f)
return data.get("mode", "auto")
mode = data.get("mode", fallback)
return mode if mode in ("auto", "do_manual", "manual") else fallback
except Exception as e:
print(f"[DB Error] Gagal memuat {self.batch_mode_file}: {e}")
return "auto"
return fallback
def save_batch_mode(self, mode: str) -> bool:
"""Save batch mode to batch mode file."""
"""Save batch mode to batch mode file atomically."""
try:
parent = os.path.dirname(self.batch_mode_file)
if parent:
os.makedirs(parent, exist_ok=True)
with open(self.batch_mode_file, "w", encoding="utf-8") as f:
tmp_path = f"{self.batch_mode_file}.tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump({"mode": mode}, f)
os.replace(tmp_path, self.batch_mode_file)
return True
except Exception as e:
print(f"[DB Error] Gagal menyimpan {self.batch_mode_file}: {e}")
+11 -8
View File
@@ -31,22 +31,23 @@ class LiveFrameWriter:
parent = os.path.dirname(self.output_path)
if parent:
os.makedirs(parent, exist_ok=True)
base, ext = os.path.splitext(self.output_path)
ext = ext or ".jpg"
if full:
tmp_path = self.output_path.replace(".jpg", ".tmp.jpg")
tmp_path = f"{base}.tmp{ext}"
cv2.imwrite(tmp_path, frame, [cv2.IMWRITE_JPEG_QUALITY, 80])
os.replace(tmp_path, self.output_path)
if preview:
preview_path = self.output_path.replace(".jpg", "_480.jpg")
tmp_prev = preview_path.replace(".jpg", ".tmp.jpg")
preview_path = f"{base}_480{ext}"
tmp_prev = f"{base}_480.tmp{ext}"
small = cv2.resize(frame, (854, 480), interpolation=cv2.INTER_AREA)
cv2.imwrite(tmp_prev, small, [cv2.IMWRITE_JPEG_QUALITY, quality])
os.replace(tmp_prev, preview_path)
except PermissionError:
# Transient file lock on Windows when Flask dashboard reads it, safe to ignore
pass
except Exception:
# Silently fail to avoid disrupting pipeline
pass
except Exception as e:
print(f"[ERROR] Gagal menulis live frame: {e}")
class DashboardOverlay:
@@ -111,7 +112,7 @@ def write_live_frame(frame: cv2.Mat, path: Optional[str]) -> None:
def update_live_status(fps: float, status_file: Optional[str] = None) -> None:
"""Update live status JSON file with current FPS."""
"""Update live status JSON file atomically with current FPS."""
if status_file is None:
return
@@ -119,8 +120,10 @@ def update_live_status(fps: float, status_file: Optional[str] = None) -> None:
parent = os.path.dirname(status_file)
if parent:
os.makedirs(parent, exist_ok=True)
with open(status_file, "w") as f:
tmp_path = f"{status_file}.tmp"
with open(tmp_path, "w") as f:
json.dump({"fps": round(fps, 1)}, f)
os.replace(tmp_path, status_file)
except Exception:
# Silently fail to avoid disrupting pipeline
pass
+4 -1
View File
@@ -14,7 +14,10 @@ class InputValidator:
VALID_MODEL_EXTENSIONS = (".pt", ".engine", ".onnx")
VALID_VIDEO_EXTENSIONS = (".mp4", ".avi", ".mkv", ".mov", ".m4v", ".flv", ".ts", ".webm")
URL_PATTERN = re.compile(r"^(rtsps?://|rtmp://|https?://)([^:/\s]+)(:\d+)?(/[^\s]*)?$", re.IGNORECASE)
URL_PATTERN = re.compile(
r"^(rtsps?://|rtmp://|https?://)([^@/\s]+@)?([^:/\s]+)(:\d+)?(/[^\s]*)?$",
re.IGNORECASE,
)
@staticmethod
def validate_model_path(path: str) -> bool:
+12
View File
@@ -231,6 +231,18 @@ def test_mode_post_operator_403(dash_client):
assert res.status_code == 403
def test_mode_post_operator_port_rejects_spoofed_host_header(dash_client):
client, _, _, _ = dash_client
res = client.post(
"/api/batch/mode",
json={"mode": "do_manual"},
headers={"Host": f"localhost:{cd_office_port()}"},
environ_overrides={"SERVER_PORT": "5000"},
)
assert res.status_code == 403
def test_mode_post_office_200_and_invalid_400(dash_client):
client, mode_path, _, _ = dash_client
office = {"Host": f"localhost:{cd_office_port()}"}
+69
View File
@@ -343,3 +343,72 @@ def test_database_manager_insert_with_missing_optional_fields():
finally:
if os.path.exists(db_path):
os.remove(db_path)
def test_insert_finalized_batch_preserves_box_do_and_net_columns(tmp_path):
"""Test that insert_finalized_batch on a fresh DatabaseManager DB preserves box, net, mode, plate, and attaches DOs."""
import sqlite3
from src.persistence import DatabaseManager
db_path = str(tmp_path / "fresh.db")
db_manager = DatabaseManager(db_path)
# Seed a staged delivery order in delivery_orders table
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute(
"INSERT INTO delivery_orders (counting_date, photo_path, no_do, plate, expected_sack, expected_box, status) "
"VALUES (?, ?, ?, ?, ?, ?, 'staged')",
("2026-10-19", "do_photos/1.jpg", "DO-001", "H1234AB", 100, 10),
)
do_id = cur.lastrowid
conn.commit()
conn.close()
ok = db_manager.insert_finalized_batch(
batch_info={
"counting_date": "2026-10-19",
"batch_number": 1,
"plate": "H1234AB",
"do_numbers": ["DO-001"],
"expected_sack": 100,
"expected_box": 10,
"do_ids": [do_id],
},
final_count=98,
start_time_iso="2026-10-19T08:00:00",
end_time_iso="2026-10-19T08:30:00",
camera_name="CC1",
object_label="karung-pakan",
box_final_count=12,
box_unloading_count=2,
model_mode="C",
unloading_count=3,
)
assert ok is True
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
row = conn.execute("SELECT * FROM batches WHERE batch_number = 1").fetchone()
do_row = conn.execute("SELECT * FROM delivery_orders WHERE id = ?", (do_id,)).fetchone()
conn.close()
assert row["count"] == 98
assert row["box_loading"] == 12
assert row["box_unloading"] == 2
assert row["model_mode"] == "C"
assert row["plate"] == "H1234AB"
assert row["net_sack"] == 95
assert row["net_box"] == 10
assert do_row["status"] == "attached"
assert do_row["batch_id"] == row["id"]
def test_state_manager_load_batch_mode_default_seed(tmp_path):
"""Test that StateManager.load_batch_mode honors a custom default_mode when file is missing."""
from src.persistence import StateManager
sm = StateManager(str(tmp_path / "state.json"), str(tmp_path / "missing_mode.json"))
assert sm.load_batch_mode(default_mode="manual") == "manual"
assert sm.load_batch_mode() == "auto"
+50
View File
@@ -12,3 +12,53 @@ def test_predict_integration():
pipeline = CountingPipeline("config.yaml")
assert pipeline is not None
def test_deploy_to_jetson_includes_src_modules():
"""Verify deploy_to_jetson.py syncs all refactored src modules required by predict.py."""
import deploy_to_jetson
local_files = {src for src, _ in deploy_to_jetson.files_to_sync}
for required in (
"src/pipeline.py",
"src/ui.py",
"src/persistence.py",
"src/validation.py",
"src/config_loader.py",
):
assert required in local_files, f"Missing {required} in deploy_to_jetson.files_to_sync"
def test_build_model_pipeline_loads_pt_before_engine(monkeypatch, tmp_path):
"""Verify build_model_pipeline loads PyTorch .pt models before TensorRT .engine models."""
import predict
from src.config_loader import load_config
cfg = load_config("config.yaml")
# Create dummy files so cfg.engine_path resolves them as-is
models_dir = tmp_path / "models"
models_dir.mkdir(exist_ok=True)
(models_dir / "v4-best.engine").write_bytes(b"0")
(models_dir / "box.pt").write_bytes(b"0")
cfg.models.paths["combined"] = "models/v4-best.engine"
cfg.models.paths["box"] = "models/box.pt"
loaded_order = []
class DummyYOLO:
def __init__(self, model_path):
loaded_order.append(str(model_path))
def __call__(self, *args, **kwargs):
return []
monkeypatch.setattr(predict, "YOLO", DummyYOLO)
monkeypatch.setattr(predict, "ByteTrackTracker", lambda *a, **kw: object())
monkeypatch.setattr(predict, "TruckDetector", lambda *a, **kw: object())
predict.build_model_pipeline("C", cfg, "cpu", str(tmp_path))
assert len(loaded_order) == 2
assert loaded_order[0].endswith(".pt"), f"Expected .pt loaded before .engine, got {loaded_order}"
assert loaded_order[1].endswith(".engine")
+9 -2
View File
@@ -6,12 +6,19 @@ import os
from unittest.mock import Mock, patch
def test_ui_frame_writer():
def test_ui_frame_writer(tmp_path):
from src.ui import LiveFrameWriter
writer = LiveFrameWriter()
out_file = tmp_path / "live_frame.JPG"
writer = LiveFrameWriter(output_path=str(out_file))
assert writer is not None
assert hasattr(writer, 'write_frame')
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
writer.write_frame(frame, preview=True, quality=60, full=True)
assert out_file.exists()
prev_file = tmp_path / "live_frame_480.JPG"
assert prev_file.exists()
def test_dashboard_overlay_initialization():
"""Test that DashboardOverlay initializes correctly."""
+4
View File
@@ -30,9 +30,13 @@ def test_input_validation():
# Test video source validation - HTTPS URL (valid)
assert validator.validate_video_source("https://example.com/stream") == True
# Test video source validation - RTSP URL with credentials (valid)
assert validator.validate_video_source("rtsp://admin:secret123@192.168.192.96:554/Streaming/Channels/101") == True
# Test video source validation - invalid URL format (should raise)
try:
validator.validate_video_source("not-a-valid-source")
assert False, "Should have raised ValidationError for invalid URL"
except ValidationError:
pass