feat(zones): add debug zone toggles, cursor coords, hot-reload, and update line/truck zones
This commit is contained in:
1 parent
6bf2ceb340
commit
95a63e1c8e
6 files changed
+389
-73
No files matched your search
@@ -59,11 +59,14 @@ Indonesian (`karung`=sack, `truk`=truck); YOLO class names are English
|
||||
`models/v4-best.engine` > `.pt` > `v4-best (1).pt` > `models/model_karung_truk.*`.
|
||||
`src/config.py` defaults: `models/best.engine` (sack) / `models/truck-detector.engine`.
|
||||
- **Zones**: `zones.json` is the source of truth for palet/truck/counting polygons.
|
||||
`predict.py` reads it at startup (1920×1080 native, auto-scaled to 1280×720;
|
||||
set `coord_space: 1280x720` to skip scaling); restart `karung-counter` after
|
||||
edits. Fallback to hardcoded defaults if missing/invalid. Debug view: set
|
||||
`DEBUG_ZONES=1` in the service env to overlay polygons + vertex coords;
|
||||
`/api/zones/debug` (office port) returns raw polygons.
|
||||
`predict.py` reads it at startup and hot-reloads on file mtime changes
|
||||
(1920×1080 native, auto-scaled to 1280×720; set `coord_space: 1280x720` to
|
||||
skip scaling). Fallback to hardcoded defaults if missing/invalid. Debug view:
|
||||
set `DEBUG_ZONES=1` in the service env to overlay polygons + vertex coords, or
|
||||
use the office-only runtime toggles (`GET/POST /api/debug-zones` backed by
|
||||
`/dev/shm/jetson-counter/debug_zones.json`; buttons + live `[x, y]` cursor
|
||||
coordinate inspector in the `:5721` monitoring view); `/api/zones/debug`
|
||||
returns raw polygons.
|
||||
- Counting trigger is the bbox **top edge (y1)** vs a truck-anchored line band
|
||||
(`src/counting.py`, `src/truck_roi.py`); truck detect runs every 15th frame only.
|
||||
- Auto-mode batch timers (`config.yaml batch:`): `timeout_seconds` = sack-idle
|
||||
|
||||
+54
-1
@@ -21,7 +21,7 @@ from flask import Flask, render_template, jsonify, request, Response, send_file
|
||||
from werkzeug.serving import WSGIRequestHandler
|
||||
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
load_dotenv(override=True)
|
||||
|
||||
# Unified config (config.yaml canonical; .env supplies secrets/deployment-only
|
||||
# values: RTSP_URL, dashboard host/ports/secret/site). Env vars still override
|
||||
@@ -99,6 +99,28 @@ else:
|
||||
|
||||
# Who is watching: predict.py reads this (S1/S2) to skip encodes nobody sees.
|
||||
_VIEWERS_PATH = os.path.join(os.path.dirname(LIVE_STREAM_FRAME_PATH), "viewers.json")
|
||||
DEBUG_ZONES_FILE = os.path.join(os.path.dirname(LIVE_STREAM_FRAME_PATH), "debug_zones.json")
|
||||
_DEBUG_ZONE_TYPES = ("palet", "truck", "counting", "line")
|
||||
|
||||
|
||||
def _read_debug_zones():
|
||||
try:
|
||||
with open(DEBUG_ZONES_FILE, "r", encoding="utf-8") as f:
|
||||
data = json.load(f) or {}
|
||||
except Exception:
|
||||
default_on = os.getenv("DEBUG_ZONES") == "1"
|
||||
data = {k: default_on for k in _DEBUG_ZONE_TYPES}
|
||||
return {k: bool(data.get(k, False)) for k in _DEBUG_ZONE_TYPES}
|
||||
|
||||
|
||||
def _write_debug_zones(state):
|
||||
os.makedirs(os.path.dirname(DEBUG_ZONES_FILE), exist_ok=True)
|
||||
tmp = DEBUG_ZONES_FILE + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(state, f)
|
||||
os.replace(tmp, DEBUG_ZONES_FILE)
|
||||
|
||||
|
||||
_VIEWERS_LOCK = threading.Lock()
|
||||
_viewers = {"total": 0, "full": 0}
|
||||
|
||||
@@ -127,6 +149,37 @@ def api_zones_debug():
|
||||
return jsonify({"success": False, "error": str(e)}), 404
|
||||
|
||||
|
||||
@app.route("/api/debug-zones", methods=["GET", "POST"])
|
||||
def api_debug_zones():
|
||||
if not is_office_request():
|
||||
return jsonify({"success": False, "error": "Office port only"}), 403
|
||||
state = _read_debug_zones()
|
||||
if request.method == "POST":
|
||||
payload = request.get_json(silent=True) or {}
|
||||
if "all" in payload:
|
||||
val = bool(payload.get("all"))
|
||||
state = {k: val for k in _DEBUG_ZONE_TYPES}
|
||||
else:
|
||||
ztype = payload.get("type")
|
||||
if ztype not in _DEBUG_ZONE_TYPES:
|
||||
return jsonify({"success": False, "error": "invalid type"}), 400
|
||||
if "enabled" not in payload:
|
||||
return jsonify({"success": False, "error": "missing enabled"}), 400
|
||||
state[ztype] = bool(payload.get("enabled"))
|
||||
_write_debug_zones(state)
|
||||
zones_path = CFG.zones.config_file
|
||||
if not os.path.isabs(zones_path):
|
||||
zones_path = os.path.join(os.path.dirname(_CONFIG_PATH), zones_path)
|
||||
coord_space = "1920x1080"
|
||||
try:
|
||||
with open(zones_path, "r", encoding="utf-8") as f:
|
||||
zdata = json.load(f) or {}
|
||||
coord_space = str(zdata.get("coord_space", "1920x1080")).lower()
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify({"success": True, "toggles": state, "coord_space": coord_space})
|
||||
|
||||
|
||||
@app.route("/api/live-video")
|
||||
def api_live_video():
|
||||
# ?full=1 -> 1280x720 q80; default -> 854x480 q60 preview (predict writes both).
|
||||
|
||||
+198
-65
@@ -540,6 +540,29 @@ 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
|
||||
|
||||
|
||||
# =====================================================================
|
||||
@@ -697,10 +720,13 @@ def run_prediction(model_path, source_path,
|
||||
# ----------------------------------------------------------------
|
||||
# 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.
|
||||
# "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 load_zones_config
|
||||
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"
|
||||
@@ -718,71 +744,123 @@ def run_prediction(model_path, source_path,
|
||||
"roi": [600, 343, 1404, 1078],
|
||||
}
|
||||
|
||||
try:
|
||||
with open(_zones_path, "r", encoding="utf-8") as _zf:
|
||||
_raw = _json.load(_zf)
|
||||
# warn on legacy knobs (config_loader handles this; call for side effect)
|
||||
def _parse_zones_from_disk():
|
||||
try:
|
||||
load_zones_config(_zones_path)
|
||||
except Exception:
|
||||
pass
|
||||
_coord = str(_raw.get("coord_space", "1920x1080")).lower()
|
||||
if _coord == "1280x720":
|
||||
_sx, _sy = 1.0, 1.0
|
||||
else:
|
||||
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",
|
||||
}
|
||||
|
||||
def _sc(pts):
|
||||
return [[int(p[0] * _sx), int(p[1] * _sy)] for p in (pts or [])]
|
||||
|
||||
_palet_pts = _sc(_raw.get("palet")) or _sc(_DEFAULT_NATIVE["palet"])
|
||||
_truck_pts = _sc(_raw.get("truck")) or _sc(_DEFAULT_NATIVE["truck"])
|
||||
_counting_pts = _sc(_raw.get("counting")) or _sc(_DEFAULT_NATIVE["counting"])
|
||||
_line_y = int(_raw.get("line_y", _DEFAULT_NATIVE["line_y_native"]) * _sy) if "line_y" in _raw else int(_DEFAULT_NATIVE["line_y_native"] * _sy)
|
||||
_line_xs = int(_raw.get("line_x_start", _DEFAULT_NATIVE["line_x_start_native"]) * _sx) if "line_x_start" in _raw else int(_DEFAULT_NATIVE["line_x_start_native"] * _sx)
|
||||
_line_xe = int(_raw.get("line_x_end", _DEFAULT_NATIVE["line_x_end_native"]) * _sx) if "line_x_end" in _raw else int(_DEFAULT_NATIVE["line_x_end_native"] * _sx)
|
||||
_roi = _raw.get("roi")
|
||||
if _roi and len(_roi) == 4:
|
||||
_roi = [int(_roi[0] * _sx), int(_roi[1] * _sy), int(_roi[2] * _sx), int(_roi[3] * _sy)]
|
||||
else:
|
||||
_roi = [int(v * (_sx if i % 2 == 0 else _sy)) for i, v in enumerate(_DEFAULT_NATIVE["roi"])]
|
||||
print(f"[INFO] Zones loaded from {_zones_path} (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
|
||||
_palet_pts = [[int(p[0] * _sx), int(p[1] * _sy)] for p in _DEFAULT_NATIVE["palet"]]
|
||||
_truck_pts = [[int(p[0] * _sx), int(p[1] * _sy)] for p in _DEFAULT_NATIVE["truck"]]
|
||||
_counting_pts = [[int(p[0] * _sx), int(p[1] * _sy)] for p in _DEFAULT_NATIVE["counting"]]
|
||||
_line_y = int(_DEFAULT_NATIVE["line_y_native"] * _sy)
|
||||
_line_xs = int(_DEFAULT_NATIVE["line_x_start_native"] * _sx)
|
||||
_line_xe = int(_DEFAULT_NATIVE["line_x_end_native"] * _sx)
|
||||
_roi = [int(_DEFAULT_NATIVE["roi"][0] * _sx), int(_DEFAULT_NATIVE["roi"][1] * _sy),
|
||||
int(_DEFAULT_NATIVE["roi"][2] * _sx), int(_DEFAULT_NATIVE["roi"][3] * _sy)]
|
||||
|
||||
# expose for debug
|
||||
LOADED_ZONES = _parse_zones_from_disk()
|
||||
print(f"[INFO] Zones loaded from {_zones_path} (coord_space={LOADED_ZONES['coord_space']})")
|
||||
try:
|
||||
LOADED_ZONES = {
|
||||
"palet": _palet_pts, "truck": _truck_pts, "counting": _counting_pts,
|
||||
"line_y": _line_y, "line_x_start": _line_xs, "line_x_end": _line_xe,
|
||||
"roi": _roi, "coord_space": _coord if "_coord" in locals() else "1920x1080",
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
_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 = _counting_pts
|
||||
detection_poly_pts = LOADED_ZONES["counting"]
|
||||
detection_polygon = Polygon(detection_poly_pts)
|
||||
|
||||
static_line_y = _line_y
|
||||
static_line_x_start = _line_xs
|
||||
static_line_x_end = _line_xe
|
||||
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 = _truck_pts
|
||||
truck_poly_pts = LOADED_ZONES["truck"]
|
||||
truck_polygon = Polygon(truck_poly_pts)
|
||||
|
||||
from src.truck_roi import TruckROI
|
||||
_roi = LOADED_ZONES["roi"]
|
||||
static_roi = TruckROI(
|
||||
x1=_roi[0],
|
||||
y1=_roi[1],
|
||||
@@ -792,6 +870,37 @@ def run_prediction(model_path, source_path,
|
||||
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
|
||||
@@ -899,6 +1008,7 @@ def run_prediction(model_path, source_path,
|
||||
|
||||
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.
|
||||
@@ -1271,22 +1381,46 @@ def run_prediction(model_path, source_path,
|
||||
waiting_duration=batch_mgr.waiting_duration if current_batch_mode == "auto" else 0,
|
||||
)
|
||||
|
||||
# Debug: draw zone polygons + vertex coords when DEBUG_ZONES=1
|
||||
if os.getenv("DEBUG_ZONES") == "1" and globals().get("LOADED_ZONES"):
|
||||
_lz = globals()["LOADED_ZONES"]
|
||||
# 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):
|
||||
cv2.circle(viz, (int(_x), int(_y)), 4, _colors[_name], -1)
|
||||
cv2.putText(viz, f"{_name}[{_i}] ({_x},{_y})", (int(_x) + 4, int(_y) - 4),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.35, _colors[_name], 1)
|
||||
cv2.line(viz, (_lz.get("line_x_start", 0), _lz.get("line_y", 0)),
|
||||
(_lz.get("line_x_end", 0), _lz.get("line_y", 0)), (255, 0, 255), 2)
|
||||
_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:
|
||||
@@ -1394,11 +1528,10 @@ def run_prediction(model_path, source_path,
|
||||
if __name__ == "__main__":
|
||||
args = parse_args()
|
||||
|
||||
# Load .env (systemd already injects env via EnvironmentFile; load_dotenv
|
||||
# never overrides existing vars, so this is a safe no-op in production)
|
||||
# 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)
|
||||
load_dotenv(args.env, override=True)
|
||||
except ImportError:
|
||||
print("[WARN] python-dotenv tidak tersedia, memakai environment apa adanya.")
|
||||
|
||||
|
||||
@@ -312,6 +312,12 @@ class LineCrossCounter:
|
||||
self._loading_count = int(loading or 0)
|
||||
self._unloading_count = int(unloading or 0)
|
||||
|
||||
def update_line(self, line_y: int, line_x_start: int, line_x_end: int) -> None:
|
||||
"""Update line geometry in-place without resetting batch counts."""
|
||||
self._line_y = int(line_y)
|
||||
self._line_x_start = int(line_x_start)
|
||||
self._line_x_end = int(line_x_end)
|
||||
|
||||
|
||||
class MultiClassLineCounter:
|
||||
"""Sack + box counting on one shared line (Option 2: dual counters).
|
||||
@@ -444,6 +450,10 @@ class MultiClassLineCounter:
|
||||
self._sack.set_counts(loading, unloading)
|
||||
self._box.set_counts(box_loading, box_unloading)
|
||||
|
||||
def update_line(self, line_y: int, line_x_start: int, line_x_end: int) -> None:
|
||||
self._sack.update_line(line_y, line_x_start, line_x_end)
|
||||
self._box.update_line(line_y, line_x_start, line_x_end)
|
||||
|
||||
|
||||
def _bbox_iou(a, b) -> float:
|
||||
ax1, ay1, ax2, ay2 = a
|
||||
|
||||
@@ -347,6 +347,22 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% if show_nav %}
|
||||
<div class="debug-zones-panel" style="margin:10px 0;display:flex;gap:8px;flex-wrap:wrap;align-items:center;justify-content:space-between;">
|
||||
<div style="display:flex;gap:6px;flex-wrap:wrap;align-items:center;">
|
||||
<span style="font-size:12px;color:var(--text-secondary);font-weight:600;">Debug Zones:</span>
|
||||
<button type="button" id="dbgBtn-palet" class="btn btn-secondary btn-sm" onclick="toggleDebugZone('palet')">Palet</button>
|
||||
<button type="button" id="dbgBtn-truck" class="btn btn-secondary btn-sm" onclick="toggleDebugZone('truck')">Truck</button>
|
||||
<button type="button" id="dbgBtn-counting" class="btn btn-secondary btn-sm" onclick="toggleDebugZone('counting')">Counting</button>
|
||||
<button type="button" id="dbgBtn-line" class="btn btn-secondary btn-sm" onclick="toggleDebugZone('line')">Line</button>
|
||||
<button type="button" class="btn btn-secondary btn-sm" onclick="setAllDebugZones(true)">Show All</button>
|
||||
<button type="button" class="btn btn-secondary btn-sm" onclick="setAllDebugZones(false)">Hide All</button>
|
||||
</div>
|
||||
<div id="dbgCursorReadout" style="font-size:12px;font-family:monospace;color:var(--text-secondary);background:var(--bg-base);border:1px solid var(--border-color);padding:4px 10px;border-radius:var(--radius-sm);">
|
||||
Hover video for [x, y] (click to copy)
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="video-container">
|
||||
<!-- Fetch direct live frame stream from local dashboard Flask -->
|
||||
<img id="liveVideoFeed" class="video-feed" src="" alt="CCTV Stream Feed" style="display: none;" onerror="handleStreamError()">
|
||||
@@ -902,5 +918,103 @@
|
||||
loadDoSettings();
|
||||
pollCurrentBatch();
|
||||
pollFinalizedBatch();
|
||||
|
||||
{% if show_nav %}
|
||||
let dbgZonesState = { palet: false, truck: false, counting: false, line: false };
|
||||
let dbgCoordSpace = '1920x1080';
|
||||
|
||||
function paintDebugZoneBtns() {
|
||||
['palet', 'truck', 'counting', 'line'].forEach(function (k) {
|
||||
const btn = document.getElementById('dbgBtn-' + k);
|
||||
if (!btn) return;
|
||||
const active = Boolean(dbgZonesState[k]);
|
||||
btn.className = active ? 'btn btn-primary btn-sm' : 'btn btn-secondary btn-sm';
|
||||
btn.setAttribute('aria-pressed', active ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
|
||||
async function loadDebugZones() {
|
||||
try {
|
||||
const res = await fetch('/api/debug-zones');
|
||||
const data = await res.json();
|
||||
if (data.success && data.toggles) {
|
||||
dbgZonesState = data.toggles;
|
||||
if (data.coord_space) dbgCoordSpace = data.coord_space;
|
||||
paintDebugZoneBtns();
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
async function toggleDebugZone(type) {
|
||||
const nextVal = !dbgZonesState[type];
|
||||
try {
|
||||
const res = await fetch('/api/debug-zones', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: type, enabled: nextVal })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success && data.toggles) {
|
||||
dbgZonesState = data.toggles;
|
||||
if (data.coord_space) dbgCoordSpace = data.coord_space;
|
||||
paintDebugZoneBtns();
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
async function setAllDebugZones(val) {
|
||||
try {
|
||||
const res = await fetch('/api/debug-zones', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ all: Boolean(val) })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success && data.toggles) {
|
||||
dbgZonesState = data.toggles;
|
||||
if (data.coord_space) dbgCoordSpace = data.coord_space;
|
||||
paintDebugZoneBtns();
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
(function initCursorCoordinateInspector() {
|
||||
const feed = document.getElementById('liveVideoFeed');
|
||||
const readout = document.getElementById('dbgCursorReadout');
|
||||
if (!feed || !readout) return;
|
||||
|
||||
function computeCoords(ev) {
|
||||
const r = feed.getBoundingClientRect();
|
||||
if (!r.width || !r.height) return null;
|
||||
const normX = Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width));
|
||||
const normY = Math.max(0, Math.min(1, (ev.clientY - r.top) / r.height));
|
||||
const maxW = (dbgCoordSpace === '1280x720') ? 1280 : 1920;
|
||||
const maxH = (dbgCoordSpace === '1280x720') ? 720 : 1080;
|
||||
return [Math.round(normX * maxW), Math.round(normY * maxH)];
|
||||
}
|
||||
|
||||
feed.addEventListener('mousemove', function (ev) {
|
||||
const pt = computeCoords(ev);
|
||||
if (!pt) return;
|
||||
readout.textContent = 'zones.json (' + dbgCoordSpace + '): [' + pt[0] + ', ' + pt[1] + '] (click to copy)';
|
||||
});
|
||||
|
||||
feed.addEventListener('mouseleave', function () {
|
||||
readout.textContent = 'Hover video for [x, y] (click to copy)';
|
||||
});
|
||||
|
||||
feed.addEventListener('click', function (ev) {
|
||||
const pt = computeCoords(ev);
|
||||
if (!pt) return;
|
||||
const text = '[' + pt[0] + ', ' + pt[1] + ']';
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
navigator.clipboard.writeText(text).catch(function () {});
|
||||
}
|
||||
readout.textContent = 'Copied ' + text + ' (' + dbgCoordSpace + ')';
|
||||
});
|
||||
})();
|
||||
|
||||
loadDebugZones();
|
||||
{% endif %}
|
||||
</script>
|
||||
{% endblock %}
|
||||
+5
-2
@@ -18,10 +18,10 @@
|
||||
]
|
||||
],
|
||||
"truck": [
|
||||
[600, 385],
|
||||
[600, 290],
|
||||
[609, 1076],
|
||||
[1404, 1078],
|
||||
[1381, 343]
|
||||
[1381, 290]
|
||||
],
|
||||
"counting": [
|
||||
[574, 50],
|
||||
@@ -29,6 +29,9 @@
|
||||
[1418, 1076],
|
||||
[1397, 50]
|
||||
],
|
||||
"line_y": 285,
|
||||
"line_x_start": 577,
|
||||
"line_x_end": 1401,
|
||||
"sack_side_exit_left": [
|
||||
[1380, 300],
|
||||
[1383, 350],
|
||||
|
||||
Reference in new issue
Block a user