streaming and recounting optimized

This commit is contained in:
proitlab committed 2026-10-29 14:04:29 +07:00
1 parent dcef027801
commit 31922e1e1f
5 files changed
+685 -279

No files matched your search

+77 -43
View File
@@ -99,6 +99,7 @@ class BatchStore:
("recount_count", "INTEGER"),
("recount_delta", "INTEGER"),
("recount_video_url", "TEXT"),
("status", "TEXT DEFAULT 'VALID'"),
):
try:
cur.execute(f"ALTER TABLE batches ADD COLUMN {col} {decl}")
@@ -126,13 +127,25 @@ class BatchStore:
f"State file belongs to previous counting day ({state.get('counting_date')}). "
'Finalizing before fresh start.'
)
self._insert_batch(
state['counting_date'],
state['batch_number'],
state['count'],
state['start_time'],
datetime.now().isoformat(),
)
st_count = state.get('count', 0)
if st_count >= self.min_object_per_batch:
self._insert_batch(
state['counting_date'],
state['batch_number'],
st_count,
state['start_time'],
datetime.now().isoformat(),
status='VALID',
)
elif st_count > 1:
self._insert_batch(
state['counting_date'],
state['batch_number'],
st_count,
state['start_time'],
datetime.now().isoformat(),
status='PARTIAL',
)
self.state_file.unlink(missing_ok=True)
return None
self.log(
@@ -287,15 +300,20 @@ class BatchStore:
batch_id = f"{state['counting_date']}-{state['batch_number']}"
if (state['count'] < self.min_object_per_batch
or duration_seconds < self.min_duration_per_batch):
is_valid = not (
state['count'] < self.min_object_per_batch
or duration_seconds < self.min_duration_per_batch
)
is_partial = not is_valid and state['count'] > 1
if not is_valid and not is_partial:
self.current_state = None
self.save_state()
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
self.log(
f'Batch #{state["batch_number"]} discarded '
f'Batch #{state["batch_number"]} discarded as noise '
f'(count={state["count"]}, duration={duration_seconds:.0f}s)'
)
# Signal recorder to abort without blocking the detect/timer thread.
@@ -316,6 +334,7 @@ class BatchStore:
self.log(f'on_batch_closed error: {exc}')
return False
status = 'VALID' if is_valid else 'PARTIAL'
end_time = end_time_obj.isoformat()
try:
self._insert_batch(
@@ -324,12 +343,19 @@ class BatchStore:
state['count'],
state['start_time'],
end_time,
status=status,
)
cps = state['count'] / duration_seconds if duration_seconds > 0 else 0
self.log(
f'Batch #{state["batch_number"]} ended | count={state["count"]} | '
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by}'
)
if is_valid:
self.log(
f'Batch #{state["batch_number"]} ended | count={state["count"]} | '
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by}'
)
else:
self.log(
f'Batch #{state["batch_number"]} ended (PARTIAL) | count={state["count"]} | '
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by} (excluded from daily KPIs)'
)
except Exception as exc:
self.log(f'Failed to persist batch: {exc}')
return False
@@ -342,6 +368,8 @@ class BatchStore:
# Truthy return with metadata for video finalize/upload hooks
meta = {
"ok": True,
"status": status,
"is_partial": is_partial,
"batch_id": batch_id,
"counting_date": state["counting_date"],
"batch_number": state["batch_number"],
@@ -408,43 +436,49 @@ class BatchStore:
self.db.commit()
return cur.rowcount > 0
def _insert_batch(self, counting_date, batch_number, count, start_time, end_time):
def _insert_batch(self, counting_date, batch_number, count, start_time, end_time, status='VALID'):
cur = self.db.cursor()
cur.execute(
"""
INSERT INTO batches
(counting_date, batch_number, camera_name, object_label, count, start_time, end_time)
VALUES (?, ?, ?, ?, ?, ?, ?)
(counting_date, batch_number, camera_name, object_label, count, start_time, end_time, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(counting_date, batch_number, self.camera_name, self.object_label, count, start_time, end_time),
(counting_date, batch_number, self.camera_name, self.object_label, count, start_time, end_time, status),
)
cur.execute(
"""
INSERT INTO daily_summaries
(counting_date, camera_name, object_label, total_count, total_batches)
VALUES (?, ?, ?, ?, 1)
ON CONFLICT(counting_date, camera_name, object_label)
DO UPDATE SET
total_count = total_count + excluded.total_count,
total_batches = total_batches + excluded.total_batches,
updated_at = CURRENT_TIMESTAMP
""",
(counting_date, self.camera_name, self.object_label, count),
)
self.db.commit()
if status == 'VALID':
cur.execute(
"""
INSERT INTO daily_summaries
(counting_date, camera_name, object_label, total_count, total_batches)
VALUES (?, ?, ?, ?, 1)
ON CONFLICT(counting_date, camera_name, object_label)
DO UPDATE SET
total_count = total_count + excluded.total_count,
total_batches = total_batches + excluded.total_batches,
updated_at = CURRENT_TIMESTAMP
""",
(counting_date, self.camera_name, self.object_label, count),
)
self.db.commit()
cur.execute(
"""
SELECT total_count, total_batches
FROM daily_summaries
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
""",
(counting_date, self.camera_name, self.object_label),
)
row = cur.fetchone()
if row:
cur.execute(
"""
SELECT total_count, total_batches
FROM daily_summaries
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
""",
(counting_date, self.camera_name, self.object_label),
)
row = cur.fetchone()
if row:
self.log(
f'Daily totals for {counting_date}: {row[0]} objects across {row[1]} batch(es)'
)
else:
self.db.commit()
self.log(
f'Daily totals for {counting_date}: {row[0]} objects across {row[1]} batch(es)'
f'Batch #{batch_number} saved as PARTIAL ({count} objects) - excluded from daily_summaries'
)
def cutoff_watcher_loop(self):
+126 -69
View File
@@ -216,6 +216,7 @@ def _ensure_db():
("recount_count", "INTEGER"),
("recount_delta", "INTEGER"),
("recount_video_url", "TEXT"),
("status", "TEXT DEFAULT 'VALID'"),
):
try:
cur.execute(f"ALTER TABLE batches ADD COLUMN {col} {decl}")
@@ -398,6 +399,7 @@ def api_previous_batch():
SELECT counting_date, batch_number, count, start_time, end_time,
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
FROM batches
WHERE COALESCE(status, 'VALID') = 'VALID'
ORDER BY end_time DESC
LIMIT 1
"""
@@ -594,7 +596,7 @@ def api_day_detail(date):
"""
SELECT batch_number, count, start_time, end_time,
camera_name, object_label,
recount_count, recount_delta, video_url,
recount_count, recount_delta, video_url, status,
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
FROM batches
WHERE counting_date = ?
@@ -611,6 +613,7 @@ def api_day_detail(date):
{
"batch_number": row["batch_number"],
"count": row["count"],
"status": row["status"] if "status" in row.keys() else "VALID",
"start_time": row["start_time"],
"end_time": row["end_time"],
"duration_minutes": duration,
@@ -774,7 +777,7 @@ def export_daily_xlsx():
cur = conn.cursor()
cur.execute(
"""
SELECT counting_date, batch_number, count, start_time, end_time,
SELECT counting_date, batch_number, count, status, start_time, end_time,
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
FROM batches
WHERE counting_date >= ?
@@ -798,19 +801,28 @@ def export_daily_xlsx():
("A", "Tanggal"),
("B", "Batch #"),
("C", "Total Terhitung"),
("D", "Mulai"),
("E", "Selesai"),
("F", "Durasi (menit)"),
("D", "Status"),
("E", "Mulai"),
("F", "Selesai"),
("G", "Durasi (menit)"),
],
)
warn_font = Font(color="B45309", bold=True)
warn_fill = PatternFill(start_color="FEF3C7", end_color="FEF3C7", fill_type="solid")
for r_idx, row in enumerate(rows, 2):
ws.cell(row=r_idx, column=1, value=row["counting_date"])
ws.cell(row=r_idx, column=2, value=row["batch_number"])
ws.cell(row=r_idx, column=3, value=row["count"])
ws.cell(row=r_idx, column=4, value=row["start_time"])
ws.cell(row=r_idx, column=5, value=row["end_time"])
ws.cell(row=r_idx, column=6, value=row["duration_minutes"] or 0)
status_val = row["status"] or "VALID"
status_cell = ws.cell(row=r_idx, column=4, value=status_val)
if status_val == "PARSIAL" or status_val == "PARTIAL":
status_cell.font = warn_font
status_cell.fill = warn_fill
ws.cell(row=r_idx, column=5, value=row["start_time"])
ws.cell(row=r_idx, column=6, value=row["end_time"])
ws.cell(row=r_idx, column=7, value=row["duration_minutes"] or 0)
_auto_width(ws)
filename = f"{SITE_NAME}_laporan_harian_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
@@ -825,7 +837,7 @@ def export_day_xlsx(date):
cur = conn.cursor()
cur.execute(
"""
SELECT batch_number, count, start_time, end_time,
SELECT batch_number, count, status, start_time, end_time,
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
FROM batches
WHERE counting_date = ?
@@ -848,18 +860,27 @@ def export_day_xlsx(date):
[
("A", "Batch"),
("B", "Total Terhitung"),
("C", "Mulai"),
("D", "Selesai"),
("E", "Durasi (menit)"),
("C", "Status"),
("D", "Mulai"),
("E", "Selesai"),
("F", "Durasi (menit)"),
],
)
warn_font = Font(color="B45309", bold=True)
warn_fill = PatternFill(start_color="FEF3C7", end_color="FEF3C7", fill_type="solid")
for r_idx, row in enumerate(rows, 2):
ws.cell(row=r_idx, column=1, value=row["batch_number"])
ws.cell(row=r_idx, column=2, value=row["count"])
ws.cell(row=r_idx, column=3, value=row["start_time"])
ws.cell(row=r_idx, column=4, value=row["end_time"])
ws.cell(row=r_idx, column=5, value=row["duration_minutes"] or 0)
status_val = row["status"] or "VALID"
status_cell = ws.cell(row=r_idx, column=3, value=status_val)
if status_val == "PARSIAL" or status_val == "PARTIAL":
status_cell.font = warn_font
status_cell.fill = warn_fill
ws.cell(row=r_idx, column=4, value=row["start_time"])
ws.cell(row=r_idx, column=5, value=row["end_time"])
ws.cell(row=r_idx, column=6, value=row["duration_minutes"] or 0)
_auto_width(ws)
filename = f"{SITE_NAME}_detail_{date}.xlsx"
@@ -928,7 +949,7 @@ def _lookup_batch(counting_date, batch_number):
"""
SELECT id, counting_date, batch_number, count, start_time, end_time,
camera_name, object_label, video_filename, video_url,
recount_count, recount_delta, recount_video_url
recount_count, recount_delta, recount_video_url, status
FROM batches
WHERE counting_date = ? AND batch_number = ?
ORDER BY id DESC
@@ -1101,9 +1122,12 @@ def _run_recount_remote(batch_id, original_count, video_url):
"recount_count": remote.get("recount_count"),
"delta": remote.get("delta"),
"batch_id": batch_id,
"batch_number": _recount_state.get("batch_number"),
"start_time": _recount_state.get("start_time"),
"original_count": original_count,
"video_url": proxied,
"error": remote.get("error"),
"message": remote.get("message"),
}
)
if remote_status == "COMPLETED":
@@ -1208,13 +1232,14 @@ def api_recount_batches():
active_dates = _active_counting_dates(cur, days, table="batches")
if not active_dates:
conn.close()
return jsonify({"success": True, "days": days, "groups": []})
return jsonify({"success": True, "days": days, "groups": [], "partial_groups": []})
placeholders = ",".join("?" * len(active_dates))
cur.execute(
f"""
SELECT counting_date, batch_number, count, start_time, end_time,
video_url, recount_count, recount_delta, recount_video_url
video_url, recount_count, recount_delta, recount_video_url,
status
FROM batches
WHERE counting_date IN ({placeholders})
ORDER BY counting_date DESC, batch_number DESC
@@ -1222,10 +1247,16 @@ def api_recount_batches():
active_dates,
)
groups = {}
partial_groups = {}
for row in cur.fetchall():
d = row["counting_date"]
if d not in groups:
groups[d] = []
status = row["status"] if "status" in row.keys() else "VALID"
is_partial = (status == "PARSIAL" or status == "PARTIAL")
target_dict = partial_groups if is_partial else groups
if d not in target_dict:
target_dict[d] = []
batch_id = f"{d}-{row['batch_number']}"
raw_video = row["video_url"] if "video_url" in row.keys() else None
# Browser-safe same-origin proxy (laptop may not reach MotionEye :8090)
@@ -1241,11 +1272,12 @@ def api_recount_batches():
# Fallback: annotated output naming convention on NanoPi 2
if not recount_video and rc is not None:
recount_video = f"/api/v1/recount/video/batch_{batch_id}_recount.mp4"
groups[d].append(
target_dict[d].append(
{
"batch_id": batch_id,
"batch_number": row["batch_number"],
"original_count": row["count"],
"status": status,
"start_time": row["start_time"],
"end_time": row["end_time"],
"video_url": browser_video,
@@ -1261,9 +1293,19 @@ def api_recount_batches():
for date in active_dates
if date in groups
]
return jsonify({"success": True, "days": days, "groups": result})
partial_result = [
{"date": date, "batches": partial_groups[date]}
for date in active_dates
if date in partial_groups
]
return jsonify({
"success": True,
"days": days,
"groups": result,
"partial_groups": partial_result,
})
except sqlite3.OperationalError as e:
return jsonify({"success": True, "days": days, "groups": [], "error": str(e)}), 200
return jsonify({"success": True, "days": days, "groups": [], "partial_groups": [], "error": str(e)}), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@@ -1281,8 +1323,11 @@ def api_recount_start():
if not batch:
return jsonify({"success": False, "error": f"Batch {batch_id} tidak ditemukan"}), 404
if batch.get("status") in ("PARSIAL", "PARTIAL"):
return jsonify({"success": False, "error": "Batch parsial hanya dapat diunduh, tidak dapat direcount."}), 400
with _recount_lock:
if _recount_state.get("status") == "PROCESSING":
if _recount_state.get("status") in ("PROCESSING", "PREPARING"):
return jsonify({"success": False, "error": "Recount sedang berjalan"}), 409
original = int(batch["count"] or 0)
@@ -1292,15 +1337,18 @@ def api_recount_start():
with _recount_lock:
_recount_state.update(
{
"status": "PROCESSING",
"status": "PREPARING",
"progress": 0,
"current_count": 0,
"recount_count": None,
"delta": None,
"batch_id": batch_id,
"batch_number": batch_number,
"start_time": batch.get("start_time"),
"original_count": original,
"video_url": None,
"error": None,
"message": "Menyiapkan video sumber…",
}
)
@@ -1347,27 +1395,29 @@ def api_recount_status():
# (e.g. start got 409, dashboard restart, or lost proxy thread).
if (
not RECOUNT_STUB
and payload.get("status") not in ("PROCESSING",)
and payload.get("status") not in ("PROCESSING", "PREPARING")
):
code, remote = _http_json(
"GET", f"{NANOPI2_URL}/api/v1/recount/status", timeout=5
)
if code == 200 and (remote.get("status") or "") == "PROCESSING":
if code == 200 and (remote.get("status") or "") in ("PROCESSING", "PREPARING"):
remote_bid = remote.get("batch_id")
counting_date, batch_number = _parse_batch_id(remote_bid) if remote_bid else (None, None)
batch = _lookup_batch(counting_date, batch_number) if counting_date else None
orig_cnt = int(remote.get("original_count") or (batch.get("count") if batch else 0) or 0)
with _recount_lock:
_recount_state.update(
{
"status": "PROCESSING",
"status": remote.get("status") or "PROCESSING",
"progress": int(remote.get("progress") or 0),
"current_count": int(remote.get("current_count") or 0),
"batch_id": remote_bid or _recount_state.get("batch_id"),
"original_count": int(
remote.get("original_count")
or _recount_state.get("original_count")
or 0
),
"batch_number": (batch.get("batch_number") if batch else batch_number) or _recount_state.get("batch_number"),
"start_time": (batch.get("start_time") if batch else None) or _recount_state.get("start_time"),
"original_count": orig_cnt or _recount_state.get("original_count") or 0,
"error": None,
"video_url": _proxy_video_url(remote.get("video_url")),
"message": remote.get("message"),
}
)
payload = dict(_recount_state)
@@ -1508,52 +1558,59 @@ def api_recount_live_frame():
return jsonify({"success": False, "error": str(e)}), 503
@app.route("/api/v1/recount/warmup", methods=["POST"])
def api_recount_warmup():
"""Background pre-download of batch video on NanoPi 2 when selected."""
data = request.get_json(silent=True) or {}
batch_id = data.get("batch_id")
if not batch_id:
return jsonify({"success": False, "error": "batch_id missing"}), 400
counting_date, batch_number = _parse_batch_id(batch_id)
if not counting_date:
return jsonify({"success": False, "error": "batch_id tidak valid"}), 400
batch = _lookup_batch(counting_date, batch_number)
video_url = _resolve_batch_video_url(batch_id, batch or {})
status_code, body = _http_json(
"POST",
f"{NANOPI2_URL}/api/v1/recount/warmup",
{"batch_id": batch_id, "video_url": video_url},
timeout=5,
)
return jsonify(body if isinstance(body, dict) else {"success": status_code in (200, 201)}), status_code
@app.route("/api/v1/recount/live-video")
def api_recount_live_video():
"""
MJPEG proxy of NanoPi 2 annotated live frames — same pattern as /api/live-video.
Zero-latency chunked MJPEG stream proxy of NanoPi 2 live frames using urllib.request.
Maintains a persistent streaming connection to NanoPi 2.
"""
import urllib.request
remote = f"{NANOPI2_URL}/api/v1/recount/live-frame"
remote_stream = f"{NANOPI2_URL}/api/v1/recount/live-video"
def generate():
consecutive_fails = 0
max_fails = 60
while True:
with _recount_lock:
st = _recount_state.get("status")
if st not in ("PROCESSING", "COMPLETED"):
consecutive_fails += 1
if consecutive_fails >= max_fails:
return
time.sleep(0.25)
continue
try:
with urllib.request.urlopen(remote, timeout=5) as resp:
jpeg = resp.read()
if not jpeg:
raise RuntimeError("empty frame")
consecutive_fails = 0
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n"
)
except Exception:
consecutive_fails += 1
if consecutive_fails >= max_fails:
return
time.sleep(0.25)
continue
# Re-check busy each frame so remux/proxy load eases when counting.
sleep_for = (
RECOUNT_LIVE_MJPEG_INTERVAL_BUSY
if _counter_busy()
else RECOUNT_LIVE_MJPEG_INTERVAL
try:
req = urllib.request.Request(
remote_stream,
headers={"Accept": "multipart/x-mixed-replace; boundary=frame"},
)
time.sleep(sleep_for)
with urllib.request.urlopen(req, timeout=300) as resp:
while True:
chunk = resp.read(4096)
if not chunk:
break
yield chunk
except Exception as exc:
log.warning(f"[recount] live-video proxy ended: {exc}")
return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
return Response(
generate(),
mimetype="multipart/x-mixed-replace; boundary=frame",
headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
)
@app.route("/api/v1/recount/video/<path:filename>")
+37 -47
View File
@@ -122,25 +122,12 @@ LINE_PULSE_FRAMES = 12
COUNT_PULSE_FRAMES = 15
BATCH_PULSE_FRAMES = 20
SKELETON = [(0, 1), (4, 3), (1, 2), (3, 2), (2, 6), (2, 5), (2, 7), (7, 8)]
SK_COLORS = [
(0, 255, 255),
(0, 255, 255),
(255, 0, 255),
(255, 0, 255),
(0, 255, 0),
(255, 255, 0),
(0, 0, 255),
(200, 200, 0),
]
C_PANEL = (28, 24, 18)
C_BORDER = (90, 85, 75)
C_ACCENT = (255, 200, 60)
C_GREEN = (80, 220, 100)
C_TEXT = (235, 235, 235)
C_MUTED = (150, 150, 150)
C_AYAM_BOX = (0, 165, 255)
C_TALENAN_BOX = (220, 120, 60)
C_LINE_CORE = (180, 220, 255)
C_LINE_GLOW = (100, 160, 220)
@@ -891,6 +878,23 @@ def draw_pill(img, text, x, y, bg, fg=C_TEXT, font_scale=0.45, pad_x=6, pad_y=4)
cv2.putText(img, text, (x + pad_x, y), font, font_scale, fg, 1, cv2.LINE_AA)
def track_badge_color(track_id):
hue = (int(track_id) * 37 + 125) % 60 + 120
hsv = np.uint8([[[hue, 210, 255]]])
return tuple(int(channel) for channel in cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)[0, 0])
def draw_track_marker(img, track_id, center_x, center_y, flash=False):
radius = max(15, int(round(img.shape[1] * 0.0357)))
center = (int(round(center_x)), int(round(center_y)))
color = track_badge_color(track_id)
if flash:
cv2.circle(img, center, radius + 3, C_GREEN, 2, cv2.LINE_AA)
cv2.circle(img, center, radius, C_PANEL, -1, cv2.LINE_AA)
cv2.circle(img, center, radius, color, 2, cv2.LINE_AA)
def draw_elegant_counting_line(
img,
line_x,
@@ -961,17 +965,16 @@ def draw_elegant_counting_line(
def draw_hero_count(img, line_x, h, count, pulse_remaining=0):
text = str(count)
font = cv2.FONT_HERSHEY_SIMPLEX
boost = 0.35 * (pulse_remaining / max(COUNT_PULSE_FRAMES, 1))
font_scale, thickness = 1.4 + boost, 3
boost = 0.2975 * (pulse_remaining / max(COUNT_PULSE_FRAMES, 1))
font_scale, thickness = 1.19 + boost, 3
(tw, th), _ = cv2.getTextSize(text, font, font_scale, thickness)
pad = 14
tx, ty = line_x - tw // 2, h // 3 + th // 2
overlay_rect(
img, tx - pad, ty - th - pad, tx + tw + pad, ty + pad, C_PANEL, alpha=0.78
)
cv2.rectangle(
img, (tx - pad, ty - th - pad), (tx + tw + pad, ty + pad), C_LINE_CORE, 2
)
pad = 12
radius = max(tw // 2 + pad, th // 2 + pad)
center = (line_x, h // 3)
ty = center[1] + (th // 2)
cv2.circle(img, center, radius, C_PANEL, -1, cv2.LINE_AA)
cv2.circle(img, center, radius, C_LINE_CORE, 2, cv2.LINE_AA)
tx = center[0] - tw // 2
cv2.putText(img, text, (tx, ty), font, font_scale, C_GREEN, thickness, cv2.LINE_AA)
@@ -1069,20 +1072,6 @@ def draw_footer(img, w, h, frame_idx, live_tag, inf_ms=0.0, model_name=""):
)
def draw_skeleton_bold(img, kpts):
for (a, b), color in zip(SKELETON, SK_COLORS):
if a < len(kpts) and b < len(kpts):
xa, ya = int(kpts[a][0]), int(kpts[a][1])
xb, yb = int(kpts[b][0]), int(kpts[b][1])
if xa > 0 and ya > 0 and xb > 0 and yb > 0:
cv2.line(img, (xa, ya), (xb, yb), color, 3, cv2.LINE_AA)
for kp in kpts:
x, y = int(kp[0]), int(kp[1])
if x > 0 and y > 0:
cv2.circle(img, (x, y), 6, (255, 255, 255), -1, cv2.LINE_AA)
cv2.circle(img, (x, y), 6, (40, 40, 40), 2, cv2.LINE_AA)
def draw_popups(img, popups, frame_idx):
alive = []
for pop in popups:
@@ -1208,8 +1197,9 @@ def run():
t0 = time.monotonic()
out_path = batch_recorder.finalize()
dt = time.monotonic() - t0
status_lbl = " [PARTIAL]" if meta.get("is_partial") else ""
log_msg(
f"Batch video finalize {meta.get('batch_id')} "
f"Batch video finalize {meta.get('batch_id')}{status_lbl} "
f"in {dt:.2f}s stats={batch_recorder.stats}"
)
if out_path:
@@ -1373,7 +1363,6 @@ def run():
if detections:
ayam_boxes_xyxy = []
ayam_scores = []
ayam_kpts_list = []
ayam_cx_list = []
ayam_cy_list = []
@@ -1400,7 +1389,6 @@ def run():
elif cls_id == ayam_cls:
ayam_boxes_xyxy.append(bbox)
ayam_scores.append(score)
ayam_kpts_list.append(kpts)
ayam_cx_list.append(cx)
ayam_cy_list.append(cy)
@@ -1415,6 +1403,7 @@ def run():
talenan_track_map, talenan_det_to_track, talenan_lost_map = (
talenan_tracker.update(talenan_boxes_xyxy, talenan_scores)
)
ayam_marker_positions = []
if os.getenv("DEBUG_TRACKING", "").lower() == "true":
if len(ayam_boxes_xyxy) > 0 or len(talenan_boxes_xyxy) > 0:
@@ -1574,14 +1563,15 @@ def run():
if tid is None:
continue
bbox = ayam_boxes_xyxy[di]
x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
flash = ayam_cross_flash.get(tid, 0)
color = C_GREEN if flash > 0 else C_AYAM_BOX
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 3 if flash > 0 else 2)
draw_pill(frame, f"ID {tid}", x1, y1 - 4, color)
kpts = ayam_kpts_list[di] if di < len(ayam_kpts_list) else None
if kpts is not None:
draw_skeleton_bold(frame, kpts)
center_x = (bbox[0] + bbox[2]) / 2
center_y = (bbox[1] + bbox[3]) / 2
ayam_marker_positions.append((tid, center_x, center_y, flash > 0))
if ayam_marker_positions:
marker_y = float(np.median([item[2] for item in ayam_marker_positions]))
for tid, center_x, _, flash in ayam_marker_positions:
draw_track_marker(frame, tid, center_x, marker_y, flash)
if ayam_crossed_frame:
line_pulse = LINE_PULSE_FRAMES
+193 -21
View File
@@ -31,8 +31,6 @@ load_dotenv(_ROOT / ".env")
from collections import deque
from counter_live_rknn_bytetrack import ( # noqa: E402
C_AYAM_BOX,
C_GREEN,
COUNT_PULSE_FRAMES,
CROSS_FLASH_FRAMES,
LINE_PULSE_FRAMES,
@@ -45,9 +43,8 @@ from counter_live_rknn_bytetrack import ( # noqa: E402
draw_footer,
draw_hero_count,
draw_hud,
draw_pill,
draw_popups,
draw_skeleton_bold,
draw_track_marker,
)
app = Flask(__name__)
@@ -249,6 +246,77 @@ def _download(url: str, dest: Path):
urlretrieve(url, str(dest))
_warmup_lock = threading.Lock()
_warmup_batch_id = None
_download_progress = {}
def _download_with_progress(url: str, dest: Path, batch_id: str, is_active_job: bool = False) -> bool:
"""Download video with real-time percentage and MB progress reporting."""
dest.parent.mkdir(parents=True, exist_ok=True)
part_in = dest.with_suffix(dest.suffix + ".part")
t_last = 0.0
def _hook(blocks, bsize, total):
nonlocal t_last
now = time.monotonic()
downloaded = blocks * bsize
total_sz = max(0, total)
pct = min(99, int(downloaded * 100 / total_sz)) if total_sz > 0 else 0
if now - t_last < 0.1 and not (total_sz > 0 and downloaded >= total_sz):
return
t_last = now
dl_mb = downloaded / (1024 * 1024)
tot_mb = total_sz / (1024 * 1024) if total_sz > 0 else 0
if tot_mb > 0:
msg = f"Mengunduh video sumber {pct}% ({dl_mb:.1f}/{tot_mb:.1f} MB)"
else:
msg = f"Mengunduh video sumber ({dl_mb:.1f} MB)"
with _warmup_lock:
_download_progress[batch_id] = (pct, msg)
st = _get_state()
if is_active_job or (st.get("status") == "PREPARING" and st.get("batch_id") == batch_id):
_set_state(progress=pct, message=msg)
try:
urlretrieve(url, str(part_in), reporthook=_hook)
if part_in.is_file() and part_in.stat().st_size > 0:
part_in.replace(dest)
final_mb = dest.stat().st_size / (1024 * 1024)
msg = f"Video sumber siap ({final_mb:.1f} MB)"
with _warmup_lock:
_download_progress[batch_id] = (100, msg)
st = _get_state()
if is_active_job or (st.get("status") == "PREPARING" and st.get("batch_id") == batch_id):
_set_state(progress=100, message=msg)
return True
return False
except Exception as exc:
print(f"[recount] download error for {batch_id}: {exc}", flush=True)
part_in.unlink(missing_ok=True)
return False
finally:
with _warmup_lock:
_download_progress.pop(batch_id, None)
def _warmup_worker(batch_id: str, video_url: str):
"""Background pre-download of batch source video when user selects it in UI."""
global _warmup_batch_id
local_in = OUTPUT_DIR / f"_src_{batch_id}.mp4"
try:
if local_in.is_file() and local_in.stat().st_size > 0:
return
if not video_url or video_url.startswith("file://") or (video_url.startswith("/") and Path(video_url).is_file()):
return
print(f"[recount] warmup downloading {batch_id} from {video_url}", flush=True)
_download_with_progress(video_url, local_in, batch_id, is_active_job=False)
finally:
with _warmup_lock:
if _warmup_batch_id == batch_id:
_warmup_batch_id = None
def _probe_video_codec(path: Path) -> str:
try:
out = subprocess.check_output(
@@ -349,7 +417,7 @@ def _run_job(batch_id: str, video_url: str, original_count: int):
try:
_clear_live_frame()
_set_state(
status="PROCESSING",
status="PREPARING",
progress=0,
current_count=RECOUNT_START_COUNT,
recount_count=None,
@@ -358,6 +426,7 @@ def _run_job(batch_id: str, video_url: str, original_count: int):
original_count=original_count,
video_url=None,
error=None,
message="Menyiapkan video sumber…",
)
model = _load_model_once()
@@ -370,12 +439,38 @@ def _run_job(batch_id: str, video_url: str, original_count: int):
elif video_url.startswith("/") and Path(video_url).is_file():
local_in = Path(video_url)
else:
# Reuse cached source when present — avoid re-download every Mulai
# Check if cached or currently being warmed up
if local_in.is_file() and local_in.stat().st_size > 0:
print(f"[recount] using cached source {local_in}", flush=True)
else:
print(f"[recount] downloading source {video_url}", flush=True)
_download(video_url, local_in)
part_in = OUTPUT_DIR / f"_src_{batch_id}.mp4.part"
waited = 0
while part_in.is_file() and not local_in.is_file() and waited < 60:
if _cancel.is_set():
break
with _warmup_lock:
prog_info = _download_progress.get(batch_id)
if prog_info:
pct, msg = prog_info
_set_state(progress=pct, message=msg)
elif part_in.is_file():
try:
curr_bytes = part_in.stat().st_size
dl_mb = curr_bytes / (1024 * 1024)
_set_state(message=f"Mengunduh video sumber… ({dl_mb:.1f} MB)")
except Exception:
pass
time.sleep(0.3)
waited += 0.3
if not local_in.is_file():
print(f"[recount] downloading source {video_url}", flush=True)
ok = _download_with_progress(video_url, local_in, batch_id, is_active_job=True)
if not ok and not _cancel.is_set():
raise RuntimeError(f"Gagal mengunduh video sumber dari {video_url}")
if _cancel.is_set():
_set_state(status="IDLE", progress=0, error="Dibatalkan", video_url=None)
return
cap = cv2.VideoCapture(str(local_in))
if not cap.isOpened():
@@ -391,6 +486,28 @@ def _run_job(batch_id: str, video_url: str, original_count: int):
line_x = int(w * LINE_X_FRAC)
fps = fps_meta
# Pre-render Frame 0 immediately so browser displays stream before counting starts
ret0, frame0 = cap.read()
if ret0:
batch_num = batch_id.split("-")[-1] if "-" in str(batch_id) else batch_id
draw_elegant_counting_line(
frame0,
line_x,
h,
0,
CROSS_DIRECTION,
LINE_ZONE_WIDTH,
LINE_ZONE_Y_START_FRAC,
LINE_ZONE_Y_END_FRAC,
)
draw_hero_count(frame0, line_x, h, RECOUNT_START_COUNT, 0)
draw_hud(frame0, w, batch_num, RECOUNT_START_COUNT, RECOUNT_START_COUNT, 0.0, 0.0)
draw_footer(frame0, w, h, 0, "RECOUNT", 0.0, Path(MODEL_PATH).name)
_publish_live_frame(frame0)
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
_set_state(status="PROCESSING", progress=0, message=None)
writer = cv2.VideoWriter(
str(local_out),
cv2.VideoWriter_fourcc(*"mp4v"),
@@ -477,13 +594,12 @@ def _run_job(batch_id: str, video_url: str, original_count: int):
detections = model(frame)
inf_ms = inf_ms * 0.9 + (time.time() - inf_start) * 1000 * 0.1
boxes, scores, kpts_list = [], [], []
boxes, scores = [], []
for det in detections:
if int(det["cls"]) != AYAM_CLASS_ID:
continue
boxes.append(det["bbox"])
scores.append(det["score"])
kpts_list.append(det.get("keypoints"))
if boxes:
boxes_arr = np.array(boxes, dtype=np.float32)
@@ -495,11 +611,11 @@ def _run_job(batch_id: str, video_url: str, original_count: int):
np.zeros((0,), dtype=np.float32),
)
marker_positions = []
for di, bbox in enumerate(boxes):
tid = det_to_track.get(di)
if tid is None:
continue
x1, y1, x2, y2 = map(int, bbox)
cx = (bbox[0] + bbox[2]) / 2.0
cy = (bbox[1] + bbox[3]) / 2.0
prev_cx = tracked.get(tid)
@@ -517,13 +633,12 @@ def _run_job(batch_id: str, video_url: str, original_count: int):
_register_cross(tid, cx, bbox)
tracked[tid] = cx
flash = cross_flash.get(tid, 0)
color = C_GREEN if flash > 0 else C_AYAM_BOX
thickness = 3 if flash > 0 else 2
cv2.rectangle(frame, (x1, y1), (x2, y2), color, thickness)
draw_pill(frame, f"ID {tid}", x1, y1 - 4, color)
kpts = kpts_list[di] if di < len(kpts_list) else None
if kpts is not None:
draw_skeleton_bold(frame, kpts)
marker_positions.append((tid, cx, cy, flash > 0))
if marker_positions:
marker_y = float(np.median([item[2] for item in marker_positions]))
for tid, cx, _, flash in marker_positions:
draw_track_marker(frame, tid, cx, marker_y, flash)
# Match live: seed lost tracks only if unseen — never count on Kalman cross
for tid, lost_cx in lost_map.items():
@@ -646,6 +761,32 @@ def health():
)
@app.post("/api/v1/recount/warmup")
def warmup():
global _warmup_batch_id
st = _get_state().get("status")
if st in ("PROCESSING", "PREPARING"):
return jsonify({"success": False, "message": "Engine is busy"}), 200
data = request.get_json(silent=True) or {}
batch_id = (data.get("batch_id") or "").strip()
video_url = (data.get("video_url") or "").strip()
if not batch_id or not video_url:
return jsonify({"success": False, "error": "missing batch_id or video_url"}), 400
local_in = OUTPUT_DIR / f"_src_{batch_id}.mp4"
if local_in.is_file() and local_in.stat().st_size > 0:
return jsonify({"success": True, "cached": True}), 200
with _warmup_lock:
if _warmup_batch_id == batch_id:
return jsonify({"success": True, "warming": True}), 200
_warmup_batch_id = batch_id
threading.Thread(target=_warmup_worker, args=(batch_id, video_url), daemon=True).start()
return jsonify({"success": True, "started": True}), 200
@app.post("/api/v1/recount/start")
def start():
global _thread
@@ -660,7 +801,7 @@ def start():
return jsonify({"success": False, "error": "video_url required"}), 400
st = _get_state()
if st.get("status") == "PROCESSING":
if st.get("status") in ("PROCESSING", "PREPARING"):
return jsonify({"success": False, "error": "Recount sedang berjalan"}), 409
# Model must already be warm from service start; only load if somehow missing
@@ -679,7 +820,7 @@ def start():
"success": True,
"batch_id": batch_id,
"original_count": original_count,
"status": "PROCESSING",
"status": "PREPARING",
"model_loaded": _model is not None,
}
)
@@ -696,12 +837,43 @@ def status():
@app.post("/api/v1/recount/stop")
def stop():
st = _get_state()
if st.get("status") != "PROCESSING":
if st.get("status") not in ("PROCESSING", "PREPARING"):
return jsonify({"success": True, "message": "Tidak ada job aktif", "status": st.get("status")})
_cancel.set()
return jsonify({"success": True, "message": "Pembatalan diminta"})
@app.get("/api/v1/recount/live-video")
def live_video():
"""Native MJPEG stream of latest annotated recount frames directly from memory."""
def generate():
last_sent = None
consecutive_idle = 0
while True:
st = _get_state().get("status")
if st not in ("PROCESSING", "COMPLETED", "PREPARING"):
consecutive_idle += 1
if consecutive_idle > 120: # ~5s idle
return
time.sleep(0.04)
continue
consecutive_idle = 0
jpeg = _get_live_jpeg()
if jpeg and jpeg != last_sent:
last_sent = jpeg
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n"
)
time.sleep(0.04) # ~25 FPS pacing
return Response(
generate(),
mimetype="multipart/x-mixed-replace; boundary=frame",
headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
)
@app.get("/api/v1/recount/live-frame")
def live_frame():
"""Latest annotated JPEG for MJPEG clients (operational-style)."""
+252 -99
View File
@@ -299,6 +299,12 @@
gap: clamp(12px, 2vw, 20px);
align-items: stretch;
}
.sidebar-stack {
display: flex;
flex-direction: column;
gap: clamp(12px, 2vw, 20px);
min-height: 0;
}
.video-panel, .sidebar-panel {
padding: var(--space-card); background: var(--bg-card);
border-radius: 12px; border: 1px solid var(--border);
@@ -307,9 +313,16 @@
}
.sidebar-panel {
background: var(--bg-panel);
max-height: clamp(420px, 55vw, 520px);
max-height: clamp(380px, 45vw, 480px);
overflow: hidden;
}
.sidebar-panel.partial-card {
max-height: clamp(240px, 30vw, 320px);
border-color: rgba(245, 158, 11, 0.35);
}
.sidebar-panel.partial-card:hover {
border-color: rgba(245, 158, 11, 0.55);
}
.panel-head {
display: flex; justify-content: space-between; align-items: center; gap: 12px;
flex-shrink: 0; flex-wrap: wrap;
@@ -489,6 +502,28 @@
width: 16px; height: 16px; flex-shrink: 0; border-radius: 2px;
background: #EF618D;
}
.batch-item-icon.partial-icon {
background: var(--yellow);
}
.batch-item.batch-item-partial {
cursor: default;
}
.batch-item.batch-item-partial:hover {
background: #18192D;
}
html[data-theme="light"] .batch-item.batch-item-partial:hover {
background: #FFFFFF;
}
.download-only-tag {
font-size: 11px;
font-family: var(--mono);
color: var(--yellow);
background: var(--yellow-bg);
border: 1px solid var(--yellow);
padding: 2px 6px;
border-radius: 4px;
font-weight: 600;
}
.batch-item.selected .batch-item-icon {
background: var(--green);
box-shadow: 0 0 0 4px rgba(16,185,129,0.2);
@@ -513,6 +548,16 @@
text-decoration: none; font-size: 11px; font-weight: 600;
}
.batch-item-dl:hover { color: var(--blue-btn); border-color: var(--blue-btn); }
.batch-item-dl.btn-dl-active {
background: rgba(13, 148, 136, 0.15);
border-color: var(--teal);
color: var(--teal);
font-weight: 700;
}
.batch-item-dl.btn-dl-active:hover {
background: var(--teal);
color: #ffffff;
}
.sidebar-empty, .error-toast {
padding: 16px; text-align: center; color: var(--text-muted); font-size: 13px;
}
@@ -666,25 +711,42 @@
</div>
</section>
<aside class="sidebar-panel">
<div class="panel-head">
<div class="panel-title-row">
<div class="live-rings" aria-hidden="true"><span class="r1"></span><span class="r2"></span><span class="r3"></span></div>
<div class="panel-title" id="sidebar-panel-title">riwayat batch</div>
<span class="panel-subtitle">3 hari aktif terakhir</span>
<div class="sidebar-stack">
<aside class="sidebar-panel">
<div class="panel-head">
<div class="panel-title-row">
<div class="live-rings" aria-hidden="true"><span class="r1"></span><span class="r2"></span><span class="r3"></span></div>
<div class="panel-title" id="sidebar-panel-title">riwayat batch</div>
<span class="panel-subtitle">3 hari aktif terakhir</span>
</div>
</div>
</div>
<div class="path-hint" id="motioneye-path" title="{{ motioneye_media_dir }}">{{ motioneye_media_dir }}</div>
<div class="accordion" id="batch-accordion">
<div class="sidebar-empty">Memuat batch…</div>
</div>
<div class="sidebar-actions">
<button class="btn-primary" id="btn-start" type="button" disabled>Mulai Recounting</button>
<button class="btn-stop" id="btn-stop" type="button" disabled>Stop</button>
<button class="btn-ghost" id="btn-replay" type="button" disabled hidden>Putar ulang hasil</button>
</div>
<div class="error-toast" id="error-toast" hidden></div>
</aside>
<div class="path-hint" id="motioneye-path" title="{{ motioneye_media_dir }}">{{ motioneye_media_dir }}</div>
<div class="accordion" id="batch-accordion">
<div class="sidebar-empty">Memuat batch…</div>
</div>
<div class="sidebar-actions">
<button class="btn-primary" id="btn-start" type="button" disabled>Mulai Recounting</button>
<button class="btn-stop" id="btn-stop" type="button" disabled>Stop</button>
<button class="btn-ghost" id="btn-replay" type="button" disabled hidden>Putar ulang hasil</button>
</div>
<div class="error-toast" id="error-toast" hidden></div>
</aside>
<!-- NEW CARD: Partially Discarded Batches (Downloadable Only, No Preview) -->
<aside class="sidebar-panel partial-card" id="partial-batches-card">
<div class="panel-head">
<div class="panel-title-row">
<span class="status-badge warn" style="font-size: 10px; padding: 2px 6px;">PARSIAL</span>
<div class="panel-title" id="partial-sidebar-panel-title">batch terbuang / parsial</div>
<span class="panel-subtitle">2–9 ekor</span>
</div>
<span class="download-only-tag">Unduh Saja</span>
</div>
<div class="accordion" id="partial-batch-accordion">
<div class="sidebar-empty">Memuat batch parsial…</div>
</div>
</aside>
</div>
</div>
</main>
@@ -763,46 +825,90 @@ function formatTimestamp(startIso) {
async function loadBatches() {
const box = document.getElementById('batch-accordion');
const partialBox = document.getElementById('partial-batch-accordion');
try {
const res = await fetch('/api/v1/recount/batches?days=3');
const data = await res.json();
const groups = data.groups || [];
const partialGroups = data.partial_groups || [];
Object.keys(batchIndex).forEach(k => delete batchIndex[k]);
// Render valid batches (previewable & recountable)
if (!groups.length) {
box.innerHTML = '<div class="sidebar-empty">Belum ada batch dalam 3 hari aktif terakhir</div>';
return;
box.innerHTML = '<div class="sidebar-empty">Belum ada batch valid dalam 3 hari aktif terakhir</div>';
} else {
box.innerHTML = groups.map((g, idx) => {
g.batches.forEach(b => { batchIndex[b.batch_id] = b; });
return `
<div class="acc-day ${idx === 0 ? 'open' : ''}" data-date="${g.date}">
<button type="button" class="acc-day-head" onclick="toggleDay(this)">
<span>${formatDateID(g.date)}</span>
<span class="count-pill">${g.batches.length} batch</span>
</button>
<div class="acc-day-body">
${g.batches.map(b => `
<div class="batch-item" data-batch-id="${b.batch_id}"
role="button" tabindex="0"
onclick="selectBatchById('${b.batch_id}')"
onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();selectBatchById('${b.batch_id}');}">
<div class="batch-item-main">
<span class="batch-item-icon" aria-hidden="true"></span>
<span class="batch-item-title">Batch #${String(b.batch_number).padStart(4, '0')}</span>
</div>
<div class="batch-item-meta">
<span class="batch-item-sub">${Number(b.original_count).toLocaleString('id-ID')} ekor · ${formatTimeShort(b.start_time)}</span>
<a class="batch-item-dl" href="/api/v1/recount/source/${b.batch_id}?download=1"
download="${b.batch_id}.mp4" title="Unduh video sumber"
onclick="event.stopPropagation();">Unduh</a>
</div>
</div>
`).join('')}
</div>
</div>`;
}).join('');
}
box.innerHTML = groups.map((g, idx) => {
g.batches.forEach(b => { batchIndex[b.batch_id] = b; });
return `
<div class="acc-day ${idx === 0 ? 'open' : ''}" data-date="${g.date}">
<button type="button" class="acc-day-head" onclick="toggleDay(this)">
<span>${formatDateID(g.date)}</span>
<span class="count-pill">${g.batches.length} batch</span>
</button>
<div class="acc-day-body">
${g.batches.map(b => `
<div class="batch-item" data-batch-id="${b.batch_id}"
role="button" tabindex="0"
onclick="selectBatchById('${b.batch_id}')"
onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();selectBatchById('${b.batch_id}');}">
<div class="batch-item-main">
<span class="batch-item-icon" aria-hidden="true"></span>
<span class="batch-item-title">Batch #${String(b.batch_number).padStart(4, '0')}</span>
</div>
<div class="batch-item-meta">
<span class="batch-item-sub">${Number(b.original_count).toLocaleString('id-ID')} ekor · ${formatTimeShort(b.start_time)}</span>
<a class="batch-item-dl" href="/api/v1/recount/source/${b.batch_id}?download=1"
download="${b.batch_id}.mp4" title="Unduh video sumber"
onclick="event.stopPropagation();">Unduh</a>
</div>
// Re-apply active recount batch selection if one is active
if (activeRecountBatchId && batchIndex[activeRecountBatchId]) {
syncActiveBatch({ batch_id: activeRecountBatchId });
}
// Render partial batches (Download only - No selectBatchById, No preview)
if (partialBox) {
if (!partialGroups.length) {
partialBox.innerHTML = '<div class="sidebar-empty">Tidak ada batch parsial (2–9 ekor)</div>';
} else {
partialBox.innerHTML = partialGroups.map((g, idx) => {
return `
<div class="acc-day ${idx === 0 ? 'open' : ''}" data-date="${g.date}">
<button type="button" class="acc-day-head" onclick="toggleDay(this)">
<span>${formatDateID(g.date)}</span>
<span class="count-pill">${g.batches.length} batch</span>
</button>
<div class="acc-day-body">
${g.batches.map(b => `
<div class="batch-item batch-item-partial" data-batch-id="${b.batch_id}">
<div class="batch-item-main">
<span class="batch-item-icon partial-icon" aria-hidden="true"></span>
<span class="batch-item-title">Batch #${String(b.batch_number).padStart(4, '0')}</span>
</div>
<div class="batch-item-meta">
<span class="batch-item-sub" style="color: var(--yellow);">${Number(b.original_count).toLocaleString('id-ID')} ekor · ${formatTimeShort(b.start_time)}</span>
<a class="batch-item-dl btn-dl-active" href="/api/v1/recount/source/${b.batch_id}?download=1"
download="${b.batch_id}.mp4" title="Unduh rekaman batch parsial">Unduh</a>
</div>
</div>
`).join('')}
</div>
`).join('')}
</div>
</div>`;
}).join('');
</div>`;
}).join('');
}
}
} catch (err) {
box.innerHTML = `<div class="sidebar-empty">Gagal memuat batch: ${err.message}</div>`;
if (partialBox) {
partialBox.innerHTML = `<div class="sidebar-empty">Gagal memuat batch parsial: ${err.message}</div>`;
}
}
}
@@ -945,52 +1051,12 @@ function openLiveStream() {
startLiveMjpeg();
}
// MJPEG: one long-lived connection replaces the old 80ms JPEG fetch loop.
// MJPEG: direct persistent stream identical to dashboard_operational.html.
function startLiveMjpeg() {
const img = document.getElementById('recount-live-img');
liveFrameFallbackStarted = false;
img.onload = onRecountVideoLoad;
img.onerror = onRecountVideoError;
img.src = '/api/v1/recount/live-video';
// Watchdog: no first frame in 4s (proxy buffering / no MJPEG support)
// → fall back to single-frame fetch.
livePollTimer = setTimeout(() => {
if (videoActive && !liveFrameReady) startLiveFrameFallback();
}, 4000);
}
// Fallback: fetch single frames at 500ms when MJPEG is unavailable.
function startLiveFrameFallback() {
if (liveFrameFallbackStarted || !videoActive) return;
liveFrameFallbackStarted = true;
if (livePollTimer) {
clearTimeout(livePollTimer);
livePollTimer = null;
}
const img = document.getElementById('recount-live-img');
const ph = document.getElementById('video-placeholder');
img.onerror = null;
const tick = () => {
if (!videoActive) return;
const probe = new Image();
probe.onload = () => {
if (!videoActive) return;
liveFrameReady = true;
img.src = probe.src;
img.style.display = 'block';
ph.style.display = 'none';
};
probe.onerror = () => {
/* keep placeholder until a frame for this job arrives */
if (videoActive && !liveFrameReady) {
ph.style.display = 'block';
img.style.display = 'none';
}
};
probe.src = '/api/v1/recount/live-frame?t=' + Date.now();
livePollTimer = setTimeout(tick, 500);
};
tick();
img.src = '/api/v1/recount/live-video?' + Date.now();
}
function closeLiveStream(showPlaceholder = true) {
@@ -1025,11 +1091,69 @@ function onRecountVideoLoad() {
}
function onRecountVideoError() {
// MJPEG stream failed (proxy buffering / upstream down) → single-frame fallback.
if (videoActive) startLiveFrameFallback();
if (!videoActive) return;
// If the stream dropped while recounting is in progress, reconnect cleanly after 1s
if (livePollTimer) clearTimeout(livePollTimer);
livePollTimer = setTimeout(() => {
if (videoActive) {
const img = document.getElementById('recount-live-img');
img.src = '/api/v1/recount/live-video?' + Date.now();
}
}, 1000);
}
let activeRecountBatchId = null;
function syncActiveBatch(data) {
if (!data || !data.batch_id) return;
const bid = data.batch_id;
activeRecountBatchId = bid;
// 1. If batch metadata exists in batchIndex (from loadBatches), use it
if (batchIndex[bid]) {
const b = batchIndex[bid];
if (!selectedBatch || selectedBatch.batch_id !== bid) {
selectedBatch = b;
document.querySelectorAll('.batch-item').forEach(el => {
el.classList.toggle('selected', el.dataset.batchId === bid);
});
const itemEl = document.querySelector(`.batch-item[data-batch-id="${bid}"]`);
if (itemEl) {
const dayAcc = itemEl.closest('.acc-day');
if (dayAcc && !dayAcc.classList.contains('open')) {
dayAcc.classList.add('open');
}
}
document.getElementById('orig-batch-id').textContent =
'Batch #' + String(b.batch_number).padStart(4, '0');
document.getElementById('recount-batch-id').textContent = b.batch_id;
document.getElementById('orig-timestamp').textContent = formatTimestamp(b.start_time);
document.getElementById('orig-count').textContent = Number(b.original_count).toLocaleString('id-ID');
setOrigStatusBadge(true);
document.getElementById('video-batch-label').textContent = b.batch_id;
}
return;
}
// 2. If batchIndex is not yet loaded, populate the Real-time card directly from data payload
if (!selectedBatch || selectedBatch.batch_id !== bid) {
const bNum = data.batch_number || (bid.includes('-') ? bid.split('-').pop() : '—');
document.getElementById('orig-batch-id').textContent = 'Batch #' + String(bNum).padStart(4, '0');
document.getElementById('recount-batch-id').textContent = bid;
if (data.start_time) {
document.getElementById('orig-timestamp').textContent = formatTimestamp(data.start_time);
}
document.getElementById('orig-count').textContent = Number(data.original_count || 0).toLocaleString('id-ID');
setOrigStatusBadge(true);
document.getElementById('video-batch-label').textContent = bid;
}
}
function selectBatch(batch) {
if (pollActive && activeRecountBatchId && batch.batch_id !== activeRecountBatchId) {
showError(`Recount sedang berjalan untuk Batch ${activeRecountBatchId}. Tekan Stop jika ingin mengganti batch.`);
return;
}
selectedBatch = batch;
document.querySelectorAll('.batch-item').forEach(el => {
el.classList.toggle('selected', el.dataset.batchId === batch.batch_id);
@@ -1046,6 +1170,15 @@ function selectBatch(batch) {
showError('');
document.getElementById('video-batch-label').textContent = batch.batch_id;
// Background pre-warm source video on NanoPi 2 if valid batch
if (batch && batch.batch_id && batch.status !== 'PARSIAL' && batch.status !== 'PARTIAL') {
fetch('/api/v1/recount/warmup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ batch_id: batch.batch_id }),
}).catch(() => {});
}
if (!isProcessing) {
if (batch.recount_count != null && batch.recount_count !== '') {
showRecountState('COMPLETED');
@@ -1122,20 +1255,39 @@ function applyStatus(data) {
if (data.batch_id) {
document.getElementById('recount-batch-id').textContent = data.batch_id;
}
if (status === 'PROCESSING') {
if (status === 'PREPARING') {
showRecountState('PROCESSING');
const p = data.progress || 0;
const label = p >= 99 ? 'Finalisasi…' : `${p}%`;
document.getElementById('progress-pct').textContent = label;
if (!pollActive) startPolling();
const p = data.progress != null ? data.progress : 0;
const msg = data.message || `Mengunduh video sumber… ${p}%`;
document.getElementById('progress-pct').textContent = `${p}%`;
document.getElementById('progress-fill').style.width = `${Math.min(100, p)}%`;
document.getElementById('live-recount-count').textContent =
Number(data.current_count || 0).toLocaleString('id-ID');
document.getElementById('live-recount-count').textContent = '1';
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-stop').disabled = false;
setReplayButton(null);
if (!videoActive) openLiveStream();
if (!liveFrameReady) {
setPlaceholder(`Menyiapkan Video Sumber (${p}%)`, msg);
}
syncActiveBatch(data);
} else if (status === 'PROCESSING') {
showRecountState('PROCESSING');
if (!pollActive) startPolling();
const p = data.progress != null ? data.progress : 0;
const label = p >= 99 ? 'Finalisasi…' : `${p}%`;
document.getElementById('progress-pct').textContent = label;
document.getElementById('progress-fill').style.width = `${Math.min(100, p)}%`;
document.getElementById('live-recount-count').textContent =
Number(data.current_count || 1).toLocaleString('id-ID');
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-stop').disabled = false;
setReplayButton(null);
if (!videoActive) openLiveStream();
syncActiveBatch(data);
} else if (status === 'COMPLETED') {
showRecountState('COMPLETED');
syncActiveBatch(data);
document.getElementById('final-recount-count').textContent =
Number(data.recount_count || 0).toLocaleString('id-ID');
renderDeltaBadge(data.delta, data.original_count || 0);
@@ -1283,6 +1435,7 @@ async function startRecount() {
document.getElementById('progress-fill').style.width = '0%';
document.getElementById('live-recount-count').textContent = '1';
document.getElementById('btn-stop').disabled = false;
activeRecountBatchId = selectedBatch.batch_id;
openLiveStream();
startPolling();
} catch (err) {