Files
zenai-apc-allinone/counter_dashboard.py

2603 lines
94 KiB
Python

#!/usr/bin/env python3
"""
ZenAI APC Ngoro — operational dashboard.
Reads apc_ngoro.db + current_batch.json from the edge counter stack.
Default port 5000.
"""
import json
import logging
import os
import re
import sqlite3
import threading
import time
from io import BytesIO
from datetime import datetime, timedelta
from pathlib import Path
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from openpyxl.utils import get_column_letter
from flask import Flask, render_template, jsonify, request, Response, send_file
from werkzeug.serving import WSGIRequestHandler
from dotenv import load_dotenv
from cutoff_utils import (
compute_counting_date,
ensure_cutoff_tables,
get_effective_cutoff,
load_cutoff_config,
reconcile_batches_for_cutoff_change,
update_env_cutoff,
validate_cutoff_time,
)
from retention_utils import active_counting_dates
load_dotenv()
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
_DEFAULT_DIR = "/home/admin123/ngoro_project"
DB_PATH = os.getenv("DB_PATH", f"{_DEFAULT_DIR}/apc_ngoro.db")
CURRENT_BATCH_PATH = os.getenv(
"STATE_FILE",
os.getenv("CURRENT_BATCH_PATH", "/tmp/apc_ngoro_current_batch.json"),
)
CUTOFF_TIME = os.getenv("CUTOFF_TIME", os.getenv("DAILY_CUTOFF_TIME", "20:00"))
LIVE_STREAM_FRAME_PATH = os.getenv(
"LIVE_STREAM_FRAME_PATH", "/dev/shm/apc-ngoro/live_frame.jpg"
)
SHM_DIR = os.getenv("SHM_DIR", "/dev/shm/apc-ngoro")
BATCH_VIDEO_DIR = Path(os.getenv("BATCH_VIDEO_DIR", f"{_DEFAULT_DIR}/batch_videos"))
RECOUNT_OUTPUT_DIR = Path(os.getenv("RECOUNT_OUTPUT_DIR", f"{_DEFAULT_DIR}/recount_output"))
RECOUNT_LIVE_FRAME_PATH = Path(
os.getenv("RECOUNT_LIVE_FRAME_PATH", "/dev/shm/apc-ngoro/recount_live_frame.jpg")
)
SITE_NAME = os.getenv("SITE_NAME", "SITE NGORO")
CAMERA_NAME = os.getenv("CAMERA_NAME", "")
TEMPLATE = os.getenv("DASHBOARD_TEMPLATE", "dashboard_operational.html")
STREAM_FPS_DISPLAY = os.getenv("STREAM_FPS_DISPLAY", "30.0")
STREAM_RESOLUTION_DISPLAY = os.getenv("STREAM_RESOLUTION_DISPLAY", "1280x720")
STREAM_ACCURACY_PCT = os.getenv("STREAM_ACCURACY_PCT", "98")
BATCH_RUNNING_THRESHOLD_SEC = int(os.getenv("BATCH_RUNNING_THRESHOLD_SEC", "30"))
PREVIEW_WARM_WHEN_BUSY = os.getenv("PREVIEW_WARM_WHEN_BUSY", "false").lower() == "true"
PREVIEW_CACHE_DIR = Path(os.getenv("PREVIEW_CACHE_DIR", "/tmp/apc-preview-cache"))
RECOUNT_LIVE_MJPEG_INTERVAL = float(os.getenv("RECOUNT_LIVE_MJPEG_INTERVAL", "0.12"))
RECOUNT_LIVE_MJPEG_INTERVAL_BUSY = float(
os.getenv("RECOUNT_LIVE_MJPEG_INTERVAL_BUSY", "0.35")
)
RECOUNT_ENGINE_URL = os.getenv(
"RECOUNT_ENGINE_URL",
os.getenv("NANOPI2_URL", "http://127.0.0.1:8765"),
).rstrip("/")
NANOPI2_URL = RECOUNT_ENGINE_URL
RECOUNT_STUB = os.getenv("RECOUNT_STUB", "false").lower() == "true"
_stub_delta_raw = os.getenv("RECOUNT_STUB_DELTA", "").strip()
RECOUNT_STUB_DELTA = int(_stub_delta_raw) if _stub_delta_raw else None
RECOUNT_PROXY_POLL_SEC = float(os.getenv("RECOUNT_PROXY_POLL_SEC", "0.5"))
RECOUNT_START_COUNT = int(os.getenv("RECOUNT_START_COUNT", "1"))
DASHBOARD_PORT = int(os.getenv("DASHBOARD_PORT", "5000"))
DASHBOARD_HOST = os.getenv("DASHBOARD_HOST", "0.0.0.0")
FLASK_DEBUG = os.getenv("FLASK_DEBUG", "false").lower() == "true"
MAIN_BATCH_MIN_COUNT = int(os.getenv("MAIN_BATCH_MIN_COUNT", "700"))
app = Flask(__name__, template_folder="templates", static_folder="static")
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "change-me-in-production")
@app.errorhandler(404)
def _json_404(_e):
return jsonify(
{"success": False, "error": "Not found", "path": request.path}
), 404
@app.errorhandler(405)
def _json_405(_e):
return jsonify(
{
"success": False,
"error": "Method not allowed",
"path": request.path,
"method": request.method,
}
), 405
# In-memory recount job state (phase-1 stub; single job at a time)
_recount_lock = threading.Lock()
_recount_cancel = threading.Event()
_recount_thread = None
_recount_state = {
"status": "IDLE",
"progress": 0,
"current_count": 0,
"recount_count": None,
"delta": None,
"batch_id": None,
"original_count": 0,
"video_url": None,
"error": None,
}
def _dashboard_ctx():
eff_co, is_override, default_co, _, _ = _get_today_cutoff_info()
return dict(
site_name=SITE_NAME,
camera_name=CAMERA_NAME,
cutoff_time=eff_co,
default_cutoff_time=default_co,
cutoff_is_override=is_override,
stream_fps=STREAM_FPS_DISPLAY,
stream_resolution=STREAM_RESOLUTION_DISPLAY,
stream_accuracy=STREAM_ACCURACY_PCT,
batch_videos_dir=str(BATCH_VIDEO_DIR),
motioneye_media_dir=str(BATCH_VIDEO_DIR),
)
def _derive_batch_status(last_detection_time):
if not last_detection_time:
return "IDLE"
try:
last_dt = datetime.fromisoformat(last_detection_time)
delta = (datetime.now() - last_dt).total_seconds()
return "RUNNING" if delta < BATCH_RUNNING_THRESHOLD_SEC else "IDLE"
except (ValueError, TypeError):
return "IDLE"
def _counter_busy() -> bool:
"""True when live counter has an active RUNNING batch — protect CPU/NPU."""
try:
with open(CURRENT_BATCH_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
return _derive_batch_status(data.get("last_detection_time")) == "RUNNING"
except Exception:
return False
@app.route("/api/live-video")
def api_live_video():
if not os.path.isfile(LIVE_STREAM_FRAME_PATH):
return jsonify({"success": False, "error": "Live stream frame not available yet"}), 503
def generate():
consecutive_fails = 0
max_fails = 30
while True:
try:
with open(LIVE_STREAM_FRAME_PATH, "rb") as f:
jpeg = f.read()
consecutive_fails = 0
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n"
)
except FileNotFoundError:
consecutive_fails += 1
if consecutive_fails >= max_fails:
return
time.sleep(1.0)
continue
except Exception:
consecutive_fails += 1
if consecutive_fails >= max_fails:
return
time.sleep(0.5)
continue
time.sleep(0.05)
return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
def _ensure_db():
conn = sqlite3.connect(DB_PATH, timeout=10.0)
cur = conn.cursor()
cur.execute("PRAGMA journal_mode=WAL")
cur.execute("PRAGMA synchronous=NORMAL")
cur.execute("PRAGMA busy_timeout=5000")
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)
)
"""
)
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)
)
"""
)
for col, decl in (
("video_filename", "TEXT"),
("video_url", "TEXT"),
("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}")
except sqlite3.OperationalError:
pass
conn.commit()
ensure_cutoff_tables(conn, default_cutoff=CUTOFF_TIME)
conn.close()
_ensure_db()
def get_db():
conn = sqlite3.connect(DB_PATH, timeout=10.0)
conn.execute("PRAGMA busy_timeout=5000")
conn.row_factory = sqlite3.Row
return conn
def _get_today_cutoff_info(conn=None, counting_date=None):
own_conn = False
try:
if conn is None:
conn = get_db()
own_conn = True
default_co, overrides = load_cutoff_config(conn, CUTOFF_TIME)
c_date = counting_date or compute_counting_date(None, default_co, overrides)
eff_co = overrides.get(c_date, default_co)
is_override = c_date in overrides
return eff_co, is_override, default_co, c_date, overrides
except Exception:
eff = CUTOFF_TIME
c_date = counting_date or compute_counting_date(None, eff)
return eff, False, eff, c_date, {}
finally:
if own_conn and conn is not None:
conn.close()
def get_counting_date(dt=None, cutoff_str=None):
if cutoff_str is not None:
return compute_counting_date(dt, cutoff_str)
try:
conn = get_db()
try:
default_co, overrides = load_cutoff_config(conn, CUTOFF_TIME)
finally:
conn.close()
return compute_counting_date(dt, default_co, overrides)
except Exception:
return compute_counting_date(dt, CUTOFF_TIME)
def _fetch_last_active_day(cur, before_date):
"""Most recent counting day with batches, strictly before before_date (ISO)."""
cur.execute(
"""
SELECT counting_date,
COALESCE(total_count, 0) as total_count,
COALESCE(total_batches, 0) as total_batches
FROM daily_summaries
WHERE counting_date < ?
AND COALESCE(total_batches, 0) > 0
ORDER BY counting_date DESC
LIMIT 1
""",
(before_date,),
)
return cur.fetchone()
def _active_counting_dates(cur, limit, table="batches"):
"""Latest distinct counting dates that have rows (skip empty calendar days)."""
return active_counting_dates(cur.connection, limit=limit, table=table)
@app.route("/")
def index():
return render_template(TEMPLATE, **_dashboard_ctx())
@app.route("/recounting")
def recounting_page():
return render_template("dashboard_recounting.html", **_dashboard_ctx())
def _current_batch_payload():
"""Current-batch dict shared by /api/current-batch and the SSE stream."""
try:
with open(CURRENT_BATCH_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
last_detection = data.get("last_detection_time")
return {
"success": True,
"counting_date": data.get("counting_date"),
"batch_number": data.get("batch_number"),
"count": data.get("count", 0),
"start_time": data.get("start_time"),
"last_detection_time": last_detection,
"status": _derive_batch_status(last_detection),
}
except FileNotFoundError:
return {
"success": False,
"error": "No active batch",
"count": 0,
"batch_number": None,
"counting_date": None,
"status": "IDLE",
}
except Exception as e:
return {
"success": False,
"error": str(e),
"count": 0,
"batch_number": None,
"counting_date": None,
"status": "IDLE",
}
@app.route("/api/current-batch")
def api_current_batch():
payload = _current_batch_payload()
status = 200 if payload.get("success") or payload.get("error") == "No active batch" else 500
return jsonify(payload), status
@app.route("/api/stream")
def api_stream():
"""SSE stream: current-batch + recount-status, pushed only when changed.
ponytail: change-detect at ~200ms poll; push-per-change from a file watcher
(inotify) if this ever gets hot on CPU.
"""
def _sse(event, payload):
return f"event: {event}\ndata: {json.dumps(payload)}\n\n"
def generate():
last_current = None
last_recount = None
last_ping = time.monotonic()
try:
while True:
cur = _current_batch_payload()
rec = _recount_status_payload()
if cur != last_current:
yield _sse("current-batch", cur)
last_current = cur
if rec != last_recount:
yield _sse("recount-status", rec)
last_recount = rec
if time.monotonic() - last_ping >= 15:
yield ": ping\n\n"
last_ping = time.monotonic()
time.sleep(0.2)
except GeneratorExit:
return
return Response(
generate(),
mimetype="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
},
)
@app.route("/api/health")
def api_health():
"""Readiness probe for gunicorn / monitoring. Cheap SELECT 1 + state file check."""
db_ok = False
db_error = None
try:
conn = get_db()
conn.execute("SELECT 1")
conn.close()
db_ok = True
except Exception as e:
db_error = str(e)
state_ok = os.path.isfile(CURRENT_BATCH_PATH)
payload = {
"success": db_ok,
"service": "apc-ngoro-dashboard",
"site_name": SITE_NAME,
"db": "ok" if db_ok else "error",
"state_file": "ok" if state_ok else "missing",
"time": datetime.now().isoformat(timespec="seconds"),
}
if db_error:
payload["db_error"] = db_error
return jsonify(payload), (200 if db_ok else 500)
@app.route("/api/previous-batch")
def api_previous_batch():
try:
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
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
"""
)
row = cur.fetchone()
conn.close()
if row:
return jsonify(
{
"success": True,
"date": row["counting_date"],
"batch_number": row["batch_number"],
"count": row["count"],
"start_time": row["start_time"],
"end_time": row["end_time"],
"duration_minutes": row["duration_minutes"],
}
)
return jsonify({"success": False, "error": "No previous batch"}), 200
except sqlite3.OperationalError as e:
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/summary")
def api_summary():
try:
conn = get_db()
cur = conn.cursor()
eff_co, is_override, default_co, today, _ = _get_today_cutoff_info(conn)
cur.execute(
"""
SELECT COALESCE(total_count, 0) as total_count,
COALESCE(total_batches, 0) as total_batches
FROM daily_summaries
WHERE counting_date = ?
""",
(today,),
)
today_row = cur.fetchone()
yesterday_row = _fetch_last_active_day(cur, today)
yesterday = yesterday_row["counting_date"] if yesterday_row else ""
cur.execute(
"""
SELECT COALESCE(SUM(total_count), 0) as grand_total,
COALESCE(SUM(total_batches), 0) as grand_batches,
COUNT(DISTINCT counting_date) as total_days
FROM daily_summaries
WHERE COALESCE(total_batches, 0) > 0
"""
)
all_time = cur.fetchone()
cur.execute(
"""
SELECT ROUND(AVG(total_count), 1) as avg_per_day
FROM daily_summaries
WHERE COALESCE(total_batches, 0) > 0
"""
)
avg = cur.fetchone()
cur.execute(
"""
SELECT counting_date, total_count
FROM daily_summaries
WHERE COALESCE(total_batches, 0) > 0
ORDER BY total_count DESC
LIMIT 1
"""
)
best = cur.fetchone()
conn.close()
today_count = today_row["total_count"] if today_row else 0
yesterday_count = yesterday_row["total_count"] if yesterday_row else 0
if yesterday_count > 0:
trend_pct = round(((today_count - yesterday_count) / yesterday_count) * 100, 1)
elif today_count > 0:
trend_pct = 100.0
else:
trend_pct = 0.0
average_per_day = avg["avg_per_day"] or 0
if average_per_day > 0:
vs_avg_pct = round(((today_count - average_per_day) / average_per_day) * 100, 1)
elif today_count > 0:
vs_avg_pct = 100.0
else:
vs_avg_pct = 0.0
grand_batches = all_time["grand_batches"] or 0
grand_total = all_time["grand_total"] or 0
avg_per_batch = round(grand_total / grand_batches, 1) if grand_batches > 0 else 0
return jsonify(
{
"today": {
"date": today,
"total_count": today_count,
"total_batches": today_row["total_batches"] if today_row else 0,
"trend_pct": trend_pct,
"vs_avg_pct": vs_avg_pct,
},
"yesterday": {
"date": yesterday,
"total_count": yesterday_count,
"total_batches": yesterday_row["total_batches"] if yesterday_row else 0,
"is_last_active": True,
},
"all_time": {
"grand_total": grand_total,
"grand_batches": grand_batches,
"total_days": all_time["total_days"],
"avg_per_batch": avg_per_batch,
},
"average_per_day": average_per_day,
"best_day": {
"date": best["counting_date"] if best else None,
"count": best["total_count"] if best else 0,
},
"cutoff_time": eff_co,
"default_cutoff_time": default_co,
"cutoff_is_override": is_override,
"site_name": SITE_NAME,
}
)
except sqlite3.OperationalError as e:
return jsonify(
{
"success": False,
"error": f"Database unavailable: {e}",
"today": {
"date": datetime.now().date().isoformat(),
"total_count": 0,
"total_batches": 0,
"trend_pct": 0,
"vs_avg_pct": 0,
},
"yesterday": {"date": "", "total_count": 0, "total_batches": 0},
"all_time": {"grand_total": 0, "grand_batches": 0, "total_days": 0, "avg_per_batch": 0},
"average_per_day": 0,
"best_day": {"date": None, "count": 0},
"cutoff_time": CUTOFF_TIME,
"default_cutoff_time": CUTOFF_TIME,
"cutoff_is_override": False,
"site_name": SITE_NAME,
}
), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/daily-data")
def api_daily_data():
try:
date_arg = (request.args.get("date") or "").strip()
if date_arg:
# Optional from-date filter (YYYY-MM-DD); ignores days when set.
date_from = date_arg
else:
days = request.args.get("days", 30, type=int)
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
SELECT counting_date, total_count, total_batches,
ROUND(CAST(total_count AS FLOAT) / total_batches, 1) as avg_per_batch
FROM daily_summaries
WHERE counting_date >= ?
ORDER BY counting_date ASC
""",
(date_from,),
)
daily_data = [
{
"date": row["counting_date"],
"total_count": row["total_count"],
"total_batches": row["total_batches"],
"avg_per_batch": row["avg_per_batch"] or 0,
}
for row in cur.fetchall()
]
conn.close()
return jsonify(daily_data)
except sqlite3.OperationalError:
return jsonify([]), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/day-detail/<date>")
def api_day_detail(date):
try:
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
SELECT batch_number, count, start_time, end_time,
camera_name, object_label,
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 = ?
ORDER BY start_time ASC, id ASC
""",
(date,),
)
batches = []
total_duration = 0
has_seen_main = False
current_main_num = 1
sub_letter_idx = 0
rows = cur.fetchall()
for idx, row in enumerate(rows):
duration = row["duration_minutes"] or 0
total_duration += duration
b_num_str = str(row["batch_number"]).strip()
count_val = row["count"] or 0
has_letter = bool(re.search(r"[a-zA-Z]", b_num_str))
# Preserve historical first batches (<= 2026-11-18); from 2026-11-19 onward
# or if explicitly suffixed, leading sub-batches merge forward into Batch 1.
if idx == 0 and not has_letter and str(date or "") <= "2026-11-18":
is_child = False
else:
is_child = has_letter or (count_val < MAIN_BATCH_MIN_COUNT)
if is_child:
if has_letter:
display_batch_num = b_num_str
m = re.match(r"^(\d+)([a-zA-Z]+)$", b_num_str)
if m:
if has_seen_main:
current_main_num = int(m.group(1))
sfx = m.group(2).lower()
if len(sfx) == 1:
sub_letter_idx = max(sub_letter_idx, ord(sfx) - ord("a") + 1)
else:
target_main = current_main_num if has_seen_main else 1
letter = chr(ord('a') + sub_letter_idx) if sub_letter_idx < 26 else f"a{sub_letter_idx}"
sub_letter_idx += 1
display_batch_num = f"{target_main}{letter}"
else:
if not has_seen_main:
has_seen_main = True
current_main_num = 1
else:
current_main_num += 1
sub_letter_idx = 0
display_batch_num = str(current_main_num)
batches.append(
{
"batch_number": display_batch_num,
"count": count_val,
"is_child": is_child,
"batch_type": "Sub" if is_child else "Main",
"status": row["status"] if "status" in row.keys() else "VALID",
"start_time": row["start_time"],
"end_time": row["end_time"],
"duration_minutes": duration,
"camera_name": row["camera_name"],
"object_label": row["object_label"],
"recount_count": row["recount_count"],
"recount_delta": row["recount_delta"],
"video_url": row["video_url"],
}
)
cur.execute(
"""
SELECT total_count, total_batches
FROM daily_summaries
WHERE counting_date = ?
""",
(date,),
)
summary = cur.fetchone()
conn.close()
return jsonify(
{
"date": date,
"total_count": summary["total_count"] if summary else 0,
"total_batches": summary["total_batches"] if summary else 0,
"total_duration_minutes": round(total_duration, 1),
"avg_duration_minutes": round(total_duration / len(batches), 1) if batches else 0,
"batches": batches,
}
)
except sqlite3.OperationalError as e:
return jsonify(
{
"date": date,
"total_count": 0,
"total_batches": 0,
"total_duration_minutes": 0,
"avg_duration_minutes": 0,
"batches": [],
"error": f"Database unavailable: {e}",
}
), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/recent-batches")
def api_recent_batches():
try:
limit = request.args.get("limit", 10, type=int)
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
SELECT counting_date, batch_number, count, start_time, end_time,
camera_name, object_label,
recount_count, recount_delta, video_url,
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
FROM batches
ORDER BY end_time DESC
LIMIT ?
""",
(limit,),
)
batches = []
for row in cur.fetchall():
b_str = str(row["batch_number"]).strip()
has_letter = bool(re.search(r"[a-zA-Z]", b_str))
d_str = str(row["counting_date"] or "")
is_child = has_letter or (
(b_str != "1" or d_str > "2026-11-18")
and ((row["count"] or 0) < MAIN_BATCH_MIN_COUNT)
)
batches.append(
{
"date": row["counting_date"],
"batch_number": row["batch_number"],
"count": row["count"],
"is_child": is_child,
"batch_type": "Sub" if is_child else "Main",
"start_time": row["start_time"],
"end_time": row["end_time"],
"duration_minutes": row["duration_minutes"] or 0,
"camera_name": row["camera_name"],
"object_label": row["object_label"],
"recount_count": row["recount_count"],
"recount_delta": row["recount_delta"],
"video_url": row["video_url"],
}
)
conn.close()
return jsonify(batches)
except sqlite3.OperationalError:
return jsonify([]), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/available-dates")
def api_available_dates():
try:
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
SELECT counting_date, total_count, total_batches
FROM daily_summaries
ORDER BY counting_date DESC
"""
)
dates = [
{
"date": row["counting_date"],
"total_count": row["total_count"],
"total_batches": row["total_batches"],
}
for row in cur.fetchall()
]
conn.close()
return jsonify(dates)
except sqlite3.OperationalError:
return jsonify([]), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/cutoff-settings", methods=["GET", "POST"])
def api_cutoff_settings():
global CUTOFF_TIME
if request.method == "GET":
try:
conn = get_db()
try:
eff_co, is_override, default_co, today_date, overrides = _get_today_cutoff_info(conn)
finally:
conn.close()
yesterday_date = (datetime.fromisoformat(today_date).date() - timedelta(days=1)).isoformat()
return jsonify(
{
"success": True,
"default_cutoff_time": default_co,
"effective_cutoff_time": eff_co,
"is_override": is_override,
"today_date": today_date,
"yesterday_date": yesterday_date,
"overrides": overrides,
}
)
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
data = request.get_json(silent=True) or {}
scope = (data.get("scope") or "date").strip().lower()
if scope not in ("date", "default"):
return jsonify({"success": False, "error": "scope harus 'date' atau 'default'"}), 400
reset = bool(data.get("reset", False))
recalc = bool(data.get("recalculate_batches", True))
conn = None
try:
conn = get_db()
ensure_cutoff_tables(conn, default_cutoff=CUTOFF_TIME)
_, _, _, today_date, _ = _get_today_cutoff_info(conn)
raw_target_date = (data.get("target_date") or today_date).strip()
try:
target_date = datetime.strptime(raw_target_date, "%Y-%m-%d").date().isoformat()
except ValueError:
return jsonify({"success": False, "error": "target_date tidak valid (YYYY-MM-DD)"}), 400
cur = conn.cursor()
if reset and scope == "date":
cur.execute("DELETE FROM cutoff_overrides WHERE counting_date = ?", (target_date,))
conn.commit()
else:
cutoff_time = validate_cutoff_time(data.get("cutoff_time") or "")
if scope == "default":
cur.execute(
'''
INSERT INTO site_settings (key, value, updated_at)
VALUES ('default_cutoff_time', ?, CURRENT_TIMESTAMP)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = CURRENT_TIMESTAMP
''',
(cutoff_time,),
)
conn.commit()
CUTOFF_TIME = cutoff_time
prod_db = os.getenv("DB_PATH", f"{_DEFAULT_DIR}/apc_ngoro.db")
try:
if Path(DB_PATH).resolve() == Path(prod_db).resolve():
update_env_cutoff(Path(_DEFAULT_DIR) / ".env", cutoff_time)
except Exception:
pass
else:
cur.execute(
'''
INSERT INTO cutoff_overrides (counting_date, cutoff_time, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(counting_date) DO UPDATE SET
cutoff_time = excluded.cutoff_time,
updated_at = CURRENT_TIMESTAMP
''',
(target_date, cutoff_time),
)
conn.commit()
reconcile_result = None
if recalc:
rec_date = target_date if scope == "date" else today_date
reconcile_result = reconcile_batches_for_cutoff_change(
conn,
rec_date,
main_batch_min_count=MAIN_BATCH_MIN_COUNT,
fallback_default=CUTOFF_TIME,
)
eff_co, is_override, default_co, new_today, overrides = _get_today_cutoff_info(conn)
yesterday_date = (datetime.fromisoformat(new_today).date() - timedelta(days=1)).isoformat()
return jsonify(
{
"success": True,
"default_cutoff_time": default_co,
"effective_cutoff_time": eff_co,
"is_override": is_override,
"today_date": new_today,
"yesterday_date": yesterday_date,
"overrides": overrides,
"reconcile": reconcile_result,
}
)
except ValueError as ve:
return jsonify({"success": False, "error": str(ve)}), 400
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
finally:
if conn is not None:
conn.close()
def _excel_response(wb, filename):
output = BytesIO()
wb.save(output)
output.seek(0)
return Response(
output.getvalue(),
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": f"attachment; filename={filename}"},
)
def _style_header(ws, cols, row_idx=1):
header_font = Font(bold=True, color="FFFFFF", size=11)
header_fill = PatternFill(start_color="0F4C75", end_color="0F4C75", fill_type="solid")
thin_border = Border(
left=Side(style="thin", color="CBD5E1"), right=Side(style="thin", color="CBD5E1"),
top=Side(style="thin", color="CBD5E1"), bottom=Side(style="thin", color="CBD5E1"),
)
for col_idx, (_, text) in enumerate(cols, 1):
cell = ws.cell(row=row_idx, column=col_idx, value=text)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center", vertical="center")
cell.border = thin_border
ws.row_dimensions[row_idx].height = 24
def _style_section_banner(ws, text, row_idx, num_cols):
banner_font = Font(bold=True, color="FFFFFF", size=11)
banner_fill = PatternFill(start_color="1B2A4A", end_color="1B2A4A", fill_type="solid")
for col_idx in range(1, num_cols + 1):
c = ws.cell(row=row_idx, column=col_idx)
c.fill = banner_fill
ws.merge_cells(start_row=row_idx, start_column=1, end_row=row_idx, end_column=num_cols)
cell = ws.cell(row=row_idx, column=1, value=text)
cell.font = banner_font
cell.alignment = Alignment(horizontal="left", vertical="center", indent=1)
ws.row_dimensions[row_idx].height = 24
def _auto_width(ws):
for col_idx, col in enumerate(ws.columns, 1):
max_len = 0
col_letter = get_column_letter(col_idx)
for cell in col:
if cell.value is not None and type(cell).__name__ != 'MergedCell':
val_str = str(cell.value)
if len(val_str) <= 45:
max_len = max(max_len, len(val_str))
ws.column_dimensions[col_letter].width = max(max_len + 4, 12)
def _prepare_batches_for_export(rows):
"""
Builds explicit rows for export, returning:
1. raw_rows: All batch runs as counted (Main and Sub), raw counts.
2. fixed_rows: Only the consolidated fixed batches (after adjustments), excluding batches with 0 chickens.
"""
main_min = MAIN_BATCH_MIN_COUNT
groups = []
current_group = None
leading_children = []
current_date = None
main_seq = 1
def _flush_leading():
if leading_children and current_group is None:
groups.append(
{
"main_id": "1",
"main_row": None,
"pre_children": list(leading_children),
"children": [],
}
)
leading_children.clear()
for r in rows:
row = dict(r)
d = row.get("counting_date")
b_num_str = str(row["batch_number"]).strip()
count = row.get("count") or 0
# Reset state on date boundary
if d != current_date:
_flush_leading()
current_date = d
current_group = None
main_seq = 1
has_letter = bool(re.search(r"[a-zA-Z]", b_num_str))
is_first_of_day = (current_group is None and not leading_children)
# Preserve historical days (<= 2026-11-18) where batch 1 was main;
# from 2026-11-19 onward or if suffixed, leading sub-batches merge forward into Batch 1.
if is_first_of_day:
is_child = has_letter or (count < main_min and str(d or "") > "2026-11-18")
else:
is_child = has_letter or (count < main_min)
if is_child and current_group is None:
if not has_letter:
sub_idx = len(leading_children)
letter = chr(ord('a') + sub_idx) if sub_idx < 26 else f"a{sub_idx}"
row["batch_number"] = f"1{letter}"
leading_children.append(row)
elif not is_child:
if current_group is None:
main_seq = 1
main_id = "1"
row["batch_number"] = "1"
pre_children = list(leading_children)
leading_children.clear()
else:
main_seq += 1
main_id = str(main_seq)
row["batch_number"] = main_id
pre_children = []
current_group = {
"main_id": main_id,
"main_row": row,
"pre_children": pre_children,
"children": [],
}
groups.append(current_group)
else:
if not has_letter:
sub_idx = len(current_group["pre_children"]) + len(current_group["children"])
letter = chr(ord('a') + sub_idx) if sub_idx < 26 else f"a{sub_idx}"
row["batch_number"] = f"{current_group['main_id']}{letter}"
current_group["children"].append(row)
_flush_leading()
raw_rows = []
fixed_rows = []
for grp in groups:
main_r = grp["main_row"]
pre_children = grp["pre_children"]
children = grp["children"]
all_children = pre_children + children
child_labels = [str(c["batch_number"]) for c in all_children]
for c in pre_children:
parent_id = grp["main_id"]
raw_rows.append(
{
"counting_date": c.get("counting_date"),
"batch_number": c["batch_number"],
"batch_type": "Sub",
"count": c.get("count") or 0,
"notes": f"Digabung ke Batch {parent_id}",
"start_time": c.get("start_time"),
"end_time": c.get("end_time"),
"duration_minutes": c.get("duration_minutes") or 0,
}
)
if main_r is not None:
main_raw = main_r.get("count") or 0
main_notes = f"Main (termasuk {', '.join(child_labels)})" if all_children else "-"
raw_rows.append(
{
"counting_date": main_r.get("counting_date"),
"batch_number": main_r["batch_number"],
"batch_type": "Main",
"count": main_raw,
"notes": main_notes,
"start_time": main_r.get("start_time"),
"end_time": main_r.get("end_time"),
"duration_minutes": main_r.get("duration_minutes") or 0,
}
)
else:
main_raw = 0
for c in children:
parent_id = grp["main_id"]
raw_rows.append(
{
"counting_date": c.get("counting_date"),
"batch_number": c["batch_number"],
"batch_type": "Sub",
"count": c.get("count") or 0,
"notes": f"Digabung ke Batch {parent_id}",
"start_time": c.get("start_time"),
"end_time": c.get("end_time"),
"duration_minutes": c.get("duration_minutes") or 0,
}
)
child_raw_sum = sum(c.get("count") or 0 for c in all_children)
consolidated_total = main_raw + child_raw_sum
# Standalone fixed batch (NO 0-chicken batches!)
if consolidated_total > 0:
timeline_rows = pre_children + ([main_r] if main_r is not None else []) + children
fixed_date = (
main_r.get("counting_date")
if main_r is not None
else timeline_rows[0].get("counting_date")
)
fixed_start = timeline_rows[0].get("start_time")
fixed_end = timeline_rows[-1].get("end_time")
combined_dur = round(
sum(x.get("duration_minutes") or 0 for x in timeline_rows), 1
)
fixed_notes = f"Termasuk {', '.join(child_labels)}" if all_children else "-"
fixed_rows.append(
{
"counting_date": fixed_date,
"batch_number": grp["main_id"],
"batch_type": "Main",
"count": consolidated_total,
"notes": fixed_notes,
"start_time": fixed_start,
"end_time": fixed_end,
"duration_minutes": combined_dur,
}
)
return raw_rows, fixed_rows
@app.route("/api/export-daily-csv")
@app.route("/api/export-daily-xlsx")
def export_daily_xlsx():
try:
days = request.args.get("days", 30, type=int)
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
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 >= ?
ORDER BY counting_date ASC, start_time ASC, id ASC
""",
(date_from,),
)
rows = cur.fetchall()
conn.close()
except sqlite3.OperationalError as e:
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 503
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
raw_rows, fixed_rows = _prepare_batches_for_export(rows)
wb = Workbook()
ws = wb.active
ws.title = "Laporan Harian"
child_font = Font(color="B45309", bold=True)
child_fill = PatternFill(start_color="FEF3C7", end_color="FEF3C7", fill_type="solid")
total_font = Font(bold=True, color="0F172A", size=11)
total_fill = PatternFill(start_color="F1F5F9", end_color="F1F5F9", fill_type="solid")
total_border = Border(
top=Side(style="thin", color="0F172A"),
bottom=Side(style="double", color="0F172A"),
left=Side(style="thin", color="CBD5E1"),
right=Side(style="thin", color="CBD5E1"),
)
avg_font = Font(bold=True, italic=True, color="334155", size=10)
avg_fill = PatternFill(start_color="F8FAFC", end_color="F8FAFC", fill_type="solid")
avg_border = Border(
top=Side(style="thin", color="E2E8F0"),
bottom=Side(style="thin", color="94A3B8"),
left=Side(style="thin", color="E2E8F0"),
right=Side(style="thin", color="E2E8F0"),
)
cur_row = 1
# ── TABEL 1: HITUNG AYAM POTONG (RINCIAN SELURUH BATCH) ──
_style_section_banner(ws, "1. HITUNG AYAM POTONG (RINCIAN SELURUH BATCH)", cur_row, 8)
cur_row += 1
t1_headers = [
("A", "Tanggal"),
("B", "Batch #"),
("C", "Tipe Batch"),
("D", "Hitung Ayam Potong"),
("E", "Catatan"),
("F", "Mulai"),
("G", "Selesai"),
("H", "Durasi (menit)"),
]
_style_header(ws, t1_headers, cur_row)
cur_row += 1
for row in raw_rows:
ws.cell(row=cur_row, column=1, value=row["counting_date"])
ws.cell(row=cur_row, column=2, value=str(row["batch_number"]))
type_cell = ws.cell(row=cur_row, column=3, value=row["batch_type"])
if row["batch_type"] == "Sub":
type_cell.font = child_font
type_cell.fill = child_fill
ws.cell(row=cur_row, column=4, value=row["count"]).number_format = '#,##0'
ws.cell(row=cur_row, column=5, value=row["notes"])
ws.cell(row=cur_row, column=6, value=row["start_time"])
ws.cell(row=cur_row, column=7, value=row["end_time"])
ws.cell(row=cur_row, column=8, value=row["duration_minutes"] or 0).number_format = '#,##0.0'
cur_row += 1
if raw_rows:
total_raw = sum(r["count"] for r in raw_rows)
total_raw_dur = round(sum(r.get("duration_minutes") or 0 for r in raw_rows), 1)
main_count = sum(1 for r in raw_rows if r["batch_type"] == "Main")
sub_count = sum(1 for r in raw_rows if r["batch_type"] == "Sub")
earliest_start = raw_rows[0]["start_time"]
latest_end = raw_rows[-1]["end_time"]
avg_raw = round(total_raw / len(raw_rows), 1)
avg_raw_dur = round(total_raw_dur / len(raw_rows), 1)
# TOTAL ROW Table 1
ws.cell(row=cur_row, column=1, value="TOTAL")
ws.cell(row=cur_row, column=2, value=f"{len(raw_rows)} Batch")
ws.cell(row=cur_row, column=3, value=f"{main_count} Main, {sub_count} Sub")
ws.cell(row=cur_row, column=4, value=total_raw)
ws.cell(row=cur_row, column=5, value="Semua batch terhitung")
ws.cell(row=cur_row, column=6, value=earliest_start)
ws.cell(row=cur_row, column=7, value=latest_end)
ws.cell(row=cur_row, column=8, value=total_raw_dur)
for col_idx in range(1, 9):
c = ws.cell(row=cur_row, column=col_idx)
c.font = total_font
c.fill = total_fill
c.border = total_border
if col_idx == 4:
c.number_format = '#,##0'
elif col_idx == 8:
c.number_format = '#,##0.0'
elif col_idx in (1, 2, 3, 5):
c.alignment = Alignment(horizontal="center")
cur_row += 1
# AVERAGE ROW Table 1
ws.cell(row=cur_row, column=1, value="RATA-RATA")
ws.cell(row=cur_row, column=2, value="-")
ws.cell(row=cur_row, column=3, value="-")
ws.cell(row=cur_row, column=4, value=avg_raw)
ws.cell(row=cur_row, column=5, value="-")
ws.cell(row=cur_row, column=6, value="-")
ws.cell(row=cur_row, column=7, value="-")
ws.cell(row=cur_row, column=8, value=avg_raw_dur)
for col_idx in range(1, 9):
c = ws.cell(row=cur_row, column=col_idx)
c.font = avg_font
c.fill = avg_fill
c.border = avg_border
if col_idx == 4:
c.number_format = '#,##0'
elif col_idx == 8:
c.number_format = '#,##0.0'
else:
c.alignment = Alignment(horizontal="center")
cur_row += 1
# 2 Empty Rows
cur_row += 2
# ── TABEL 2: BATCH DISESUAIKAN (SETELAH PENYESUAIAN) ──
_style_section_banner(ws, "2. BATCH DISESUAIKAN (SETELAH PENYESUAIAN) - HANYA BATCH TETAP", cur_row, 8)
cur_row += 1
t2_headers = [
("A", "Tanggal"),
("B", "Batch #"),
("C", "Tipe Batch"),
("D", "Batch Disesuaikan"),
("E", "Catatan"),
("F", "Mulai"),
("G", "Selesai"),
("H", "Durasi (menit)"),
]
_style_header(ws, t2_headers, cur_row)
cur_row += 1
for row in fixed_rows:
ws.cell(row=cur_row, column=1, value=row["counting_date"])
ws.cell(row=cur_row, column=2, value=str(row["batch_number"]))
ws.cell(row=cur_row, column=3, value=row["batch_type"])
ws.cell(row=cur_row, column=4, value=row["count"]).number_format = '#,##0'
ws.cell(row=cur_row, column=5, value=row["notes"])
ws.cell(row=cur_row, column=6, value=row["start_time"])
ws.cell(row=cur_row, column=7, value=row["end_time"])
ws.cell(row=cur_row, column=8, value=row["duration_minutes"] or 0).number_format = '#,##0.0'
cur_row += 1
if fixed_rows:
total_fixed = sum(r["count"] for r in fixed_rows)
total_fixed_dur = round(sum(r.get("duration_minutes") or 0 for r in fixed_rows), 1)
fixed_start = fixed_rows[0]["start_time"]
fixed_end = fixed_rows[-1]["end_time"]
avg_fixed = round(total_fixed / len(fixed_rows), 1)
avg_fixed_dur = round(total_fixed_dur / len(fixed_rows), 1)
# TOTAL ROW Table 2
ws.cell(row=cur_row, column=1, value="TOTAL")
ws.cell(row=cur_row, column=2, value=f"{len(fixed_rows)} Batch")
ws.cell(row=cur_row, column=3, value=f"{len(fixed_rows)} Main Batch")
ws.cell(row=cur_row, column=4, value=total_fixed)
ws.cell(row=cur_row, column=5, value="Semua batch tetap")
ws.cell(row=cur_row, column=6, value=fixed_start)
ws.cell(row=cur_row, column=7, value=fixed_end)
ws.cell(row=cur_row, column=8, value=total_fixed_dur)
for col_idx in range(1, 9):
c = ws.cell(row=cur_row, column=col_idx)
c.font = total_font
c.fill = total_fill
c.border = total_border
if col_idx == 4:
c.number_format = '#,##0'
elif col_idx == 8:
c.number_format = '#,##0.0'
elif col_idx in (1, 2, 3, 5):
c.alignment = Alignment(horizontal="center")
cur_row += 1
# AVERAGE ROW Table 2
ws.cell(row=cur_row, column=1, value="RATA-RATA")
ws.cell(row=cur_row, column=2, value="-")
ws.cell(row=cur_row, column=3, value="-")
ws.cell(row=cur_row, column=4, value=avg_fixed)
ws.cell(row=cur_row, column=5, value="-")
ws.cell(row=cur_row, column=6, value="-")
ws.cell(row=cur_row, column=7, value="-")
ws.cell(row=cur_row, column=8, value=avg_fixed_dur)
for col_idx in range(1, 9):
c = ws.cell(row=cur_row, column=col_idx)
c.font = avg_font
c.fill = avg_fill
c.border = avg_border
if col_idx == 4:
c.number_format = '#,##0'
elif col_idx == 8:
c.number_format = '#,##0.0'
else:
c.alignment = Alignment(horizontal="center")
_auto_width(ws)
filename = f"{SITE_NAME}_laporan_harian_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
return _excel_response(wb, filename)
@app.route("/api/export-day-csv/<date>")
@app.route("/api/export-day-xlsx/<date>")
def export_day_xlsx(date):
try:
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
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 = ?
ORDER BY start_time ASC, id ASC
""",
(date,),
)
rows = cur.fetchall()
conn.close()
except sqlite3.OperationalError as e:
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 503
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
raw_rows, fixed_rows = _prepare_batches_for_export(rows)
wb = Workbook()
ws = wb.active
ws.title = f"Hari {date}"
child_font = Font(color="B45309", bold=True)
child_fill = PatternFill(start_color="FEF3C7", end_color="FEF3C7", fill_type="solid")
total_font = Font(bold=True, color="0F172A", size=11)
total_fill = PatternFill(start_color="F1F5F9", end_color="F1F5F9", fill_type="solid")
total_border = Border(
top=Side(style="thin", color="0F172A"),
bottom=Side(style="double", color="0F172A"),
left=Side(style="thin", color="CBD5E1"),
right=Side(style="thin", color="CBD5E1"),
)
avg_font = Font(bold=True, italic=True, color="334155", size=10)
avg_fill = PatternFill(start_color="F8FAFC", end_color="F8FAFC", fill_type="solid")
avg_border = Border(
top=Side(style="thin", color="E2E8F0"),
bottom=Side(style="thin", color="94A3B8"),
left=Side(style="thin", color="E2E8F0"),
right=Side(style="thin", color="E2E8F0"),
)
cur_row = 1
# ── TABEL 1: HITUNG AYAM POTONG (RINCIAN SELURUH BATCH) ──
_style_section_banner(ws, f"1. HITUNG AYAM POTONG (RINCIAN SELURUH BATCH) - TANGGAL {date}", cur_row, 7)
cur_row += 1
t1_headers = [
("A", "Batch #"),
("B", "Tipe Batch"),
("C", "Hitung Ayam Potong"),
("D", "Catatan"),
("E", "Mulai"),
("F", "Selesai"),
("G", "Durasi (menit)"),
]
_style_header(ws, t1_headers, cur_row)
cur_row += 1
for row in raw_rows:
ws.cell(row=cur_row, column=1, value=str(row["batch_number"]))
type_cell = ws.cell(row=cur_row, column=2, value=row["batch_type"])
if row["batch_type"] == "Sub":
type_cell.font = child_font
type_cell.fill = child_fill
ws.cell(row=cur_row, column=3, value=row["count"]).number_format = '#,##0'
ws.cell(row=cur_row, column=4, value=row["notes"])
ws.cell(row=cur_row, column=5, value=row["start_time"])
ws.cell(row=cur_row, column=6, value=row["end_time"])
ws.cell(row=cur_row, column=7, value=row["duration_minutes"] or 0).number_format = '#,##0.0'
cur_row += 1
if raw_rows:
total_raw = sum(r["count"] for r in raw_rows)
total_raw_dur = round(sum(r.get("duration_minutes") or 0 for r in raw_rows), 1)
main_count = sum(1 for r in raw_rows if r["batch_type"] == "Main")
sub_count = sum(1 for r in raw_rows if r["batch_type"] == "Sub")
earliest_start = raw_rows[0]["start_time"]
latest_end = raw_rows[-1]["end_time"]
avg_raw = round(total_raw / len(raw_rows), 1)
avg_raw_dur = round(total_raw_dur / len(raw_rows), 1)
# TOTAL ROW Table 1
ws.cell(row=cur_row, column=1, value="TOTAL")
ws.cell(row=cur_row, column=2, value=f"{main_count} Main, {sub_count} Sub")
ws.cell(row=cur_row, column=3, value=total_raw)
ws.cell(row=cur_row, column=4, value=f"{len(raw_rows)} Batch Total")
ws.cell(row=cur_row, column=5, value=earliest_start)
ws.cell(row=cur_row, column=6, value=latest_end)
ws.cell(row=cur_row, column=7, value=total_raw_dur)
for col_idx in range(1, 8):
c = ws.cell(row=cur_row, column=col_idx)
c.font = total_font
c.fill = total_fill
c.border = total_border
if col_idx == 3:
c.number_format = '#,##0'
elif col_idx == 7:
c.number_format = '#,##0.0'
elif col_idx in (1, 2, 4):
c.alignment = Alignment(horizontal="center")
cur_row += 1
# AVERAGE ROW Table 1
ws.cell(row=cur_row, column=1, value="RATA-RATA")
ws.cell(row=cur_row, column=2, value="-")
ws.cell(row=cur_row, column=3, value=avg_raw)
ws.cell(row=cur_row, column=4, value="-")
ws.cell(row=cur_row, column=5, value="-")
ws.cell(row=cur_row, column=6, value="-")
ws.cell(row=cur_row, column=7, value=avg_raw_dur)
for col_idx in range(1, 8):
c = ws.cell(row=cur_row, column=col_idx)
c.font = avg_font
c.fill = avg_fill
c.border = avg_border
if col_idx == 3:
c.number_format = '#,##0'
elif col_idx == 7:
c.number_format = '#,##0.0'
else:
c.alignment = Alignment(horizontal="center")
cur_row += 1
# 2 Empty Rows
cur_row += 2
# ── TABEL 2: BATCH DISESUAIKAN (SETELAH PENYESUAIAN) ──
_style_section_banner(ws, "2. BATCH DISESUAIKAN (SETELAH PENYESUAIAN) - HANYA BATCH TETAP", cur_row, 7)
cur_row += 1
t2_headers = [
("A", "Batch #"),
("B", "Tipe Batch"),
("C", "Batch Disesuaikan"),
("D", "Catatan"),
("E", "Mulai"),
("F", "Selesai"),
("G", "Durasi (menit)"),
]
_style_header(ws, t2_headers, cur_row)
cur_row += 1
for row in fixed_rows:
ws.cell(row=cur_row, column=1, value=str(row["batch_number"]))
ws.cell(row=cur_row, column=2, value=row["batch_type"])
ws.cell(row=cur_row, column=3, value=row["count"]).number_format = '#,##0'
ws.cell(row=cur_row, column=4, value=row["notes"])
ws.cell(row=cur_row, column=5, value=row["start_time"])
ws.cell(row=cur_row, column=6, value=row["end_time"])
ws.cell(row=cur_row, column=7, value=row["duration_minutes"] or 0).number_format = '#,##0.0'
cur_row += 1
if fixed_rows:
total_fixed = sum(r["count"] for r in fixed_rows)
total_fixed_dur = round(sum(r.get("duration_minutes") or 0 for r in fixed_rows), 1)
fixed_start = fixed_rows[0]["start_time"]
fixed_end = fixed_rows[-1]["end_time"]
avg_fixed = round(total_fixed / len(fixed_rows), 1)
avg_fixed_dur = round(total_fixed_dur / len(fixed_rows), 1)
# TOTAL ROW Table 2
ws.cell(row=cur_row, column=1, value="TOTAL")
ws.cell(row=cur_row, column=2, value=f"{len(fixed_rows)} Main Batch")
ws.cell(row=cur_row, column=3, value=total_fixed)
ws.cell(row=cur_row, column=4, value="Semua batch tetap")
ws.cell(row=cur_row, column=5, value=fixed_start)
ws.cell(row=cur_row, column=6, value=fixed_end)
ws.cell(row=cur_row, column=7, value=total_fixed_dur)
for col_idx in range(1, 8):
c = ws.cell(row=cur_row, column=col_idx)
c.font = total_font
c.fill = total_fill
c.border = total_border
if col_idx == 3:
c.number_format = '#,##0'
elif col_idx == 7:
c.number_format = '#,##0.0'
elif col_idx in (1, 2, 4):
c.alignment = Alignment(horizontal="center")
cur_row += 1
# AVERAGE ROW Table 2
ws.cell(row=cur_row, column=1, value="RATA-RATA")
ws.cell(row=cur_row, column=2, value="-")
ws.cell(row=cur_row, column=3, value=avg_fixed)
ws.cell(row=cur_row, column=4, value="-")
ws.cell(row=cur_row, column=5, value="-")
ws.cell(row=cur_row, column=6, value="-")
ws.cell(row=cur_row, column=7, value=avg_fixed_dur)
for col_idx in range(1, 8):
c = ws.cell(row=cur_row, column=col_idx)
c.font = avg_font
c.fill = avg_fill
c.border = avg_border
if col_idx == 3:
c.number_format = '#,##0'
elif col_idx == 7:
c.number_format = '#,##0.0'
else:
c.alignment = Alignment(horizontal="center")
_auto_width(ws)
filename = f"{SITE_NAME}_detail_{date}.xlsx"
return _excel_response(wb, filename)
@app.route("/api/reset", methods=["POST"])
def api_reset():
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Reset API called")
paths = {CURRENT_BATCH_PATH}
sf = os.getenv("STATE_FILE")
if sf:
paths.add(sf)
cb = os.getenv("CURRENT_BATCH_PATH")
if cb:
paths.add(cb)
try:
for p in paths:
Path(p).unlink(missing_ok=True)
Path(LIVE_STREAM_FRAME_PATH).unlink(missing_ok=True)
except Exception as e:
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Reset state file cleanup error: {e}")
try:
Path(SHM_DIR).mkdir(parents=True, exist_ok=True)
reset_path = f"{SHM_DIR}/.reset"
Path(reset_path).touch()
print(
f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Reset done — "
f"cleared state + live frame + SHM flag at {reset_path}"
)
except Exception as e:
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Reset SHM error: {e}")
return jsonify({"success": False, "error": f"SHM reset failed: {e}"}), 500
reset_path = f"{SHM_DIR}/.reset"
return jsonify({
"success": True,
"message": "State + live frame cleared",
"shm_reset": reset_path,
"shm_exists": Path(reset_path).exists(),
})
def _parse_batch_id(batch_id):
"""Expect '{counting_date}-{batch_number}' e.g. 2026-09-09-42 or 2026-10-30-6a."""
if not batch_id or not isinstance(batch_id, str):
return None, None
parts = batch_id.rsplit("-", 1)
if len(parts) != 2:
return None, None
date_part, num_part = parts
if len(date_part) != 10 or not num_part:
return None, None
return date_part, str(num_part)
def _lookup_batch(counting_date, batch_number):
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
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, status
FROM batches
WHERE counting_date = ? AND (batch_number = ? OR batch_number = ?)
ORDER BY id DESC
LIMIT 1
""",
(counting_date, str(batch_number), int(batch_number) if str(batch_number).isdigit() else str(batch_number)),
)
row = cur.fetchone()
conn.close()
return dict(row) if row else None
def _lookup_batch_by_video_key(video_key):
"""
Find batch by MotionEye video key/filename/URL.
video_key may be e.g. '2026-11-02-17' or 'batch_2026-11-02-17.mp4'.
"""
if not video_key or not isinstance(video_key, str):
return None
raw_key = video_key.strip()
fn = raw_key if raw_key.endswith(".mp4") else f"batch_{raw_key}.mp4"
file_id = raw_key.replace("batch_", "").replace(".mp4", "")
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
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, status
FROM batches
WHERE video_filename = ?
OR video_url LIKE ?
ORDER BY id DESC
LIMIT 1
""",
(fn, f"%/{file_id}"),
)
row = cur.fetchone()
conn.close()
return dict(row) if row else None
def _resolve_local_batch_video(batch_id, batch_row=None):
"""Resolve batch video MP4 on local NVMe storage (BATCH_VIDEO_DIR).
Supports both batch_<id>.mp4 and <id>.mp4 naming schemes.
"""
candidates = []
if batch_id:
clean_id = str(batch_id).strip()
stripped_id = clean_id.replace("batch_", "", 1)
candidates.extend([
f"batch_{stripped_id}.mp4",
f"{stripped_id}.mp4",
f"batch_{clean_id}.mp4",
clean_id if clean_id.endswith(".mp4") else f"{clean_id}.mp4",
])
if batch_row:
vfn = (batch_row.get("video_filename") or "").strip()
if vfn:
vfn_name = Path(vfn).name
candidates.append(vfn_name)
if vfn_name.startswith("batch_"):
candidates.append(vfn_name.replace("batch_", "", 1))
else:
candidates.append(f"batch_{vfn_name}")
vurl = (batch_row.get("video_url") or "").strip()
if vurl.startswith("file://"):
cand = Path(vurl[7:])
if cand.is_file() and cand.stat().st_size > 0:
return cand
elif vurl.startswith("/") and not vurl.startswith("/api/"):
cand = Path(vurl)
if cand.is_file() and cand.stat().st_size > 0:
return cand
for marker in ("/files/", "/source/"):
if marker in vurl:
tail = vurl.rsplit(marker, 1)[-1].split("?", 1)[0].strip("/")
if tail:
stripped_tail = tail.replace("batch_", "", 1).replace(".mp4", "")
candidates.extend([
f"batch_{stripped_tail}.mp4",
f"{stripped_tail}.mp4",
tail if tail.endswith(".mp4") else f"{tail}.mp4",
])
seen = set()
for name in candidates:
if not name or name in seen:
continue
seen.add(name)
cand = BATCH_VIDEO_DIR / name
if cand.is_file() and cand.stat().st_size > 0:
return cand
return None
def _resolve_batch_video_url(batch_id, batch_row):
"""Return local batch video path if present on disk."""
local = _resolve_local_batch_video(batch_id, batch_row)
return str(local) if local is not None else None
def _resolve_remote_batch_id(batch_id, batch_row=None):
"""Return canonical batch_id (local recount_engine accepts main and sub-batches)."""
return batch_id
def _decode_remote_batch_id(remote_bid):
"""Convert remote batch ID back to logical batch ID if needed."""
if not remote_bid or not isinstance(remote_bid, str):
return remote_bid
counting_date, batch_number = _parse_batch_id(remote_bid)
if counting_date and _lookup_batch(counting_date, batch_number):
return remote_bid
return remote_bid
def _proxy_video_url(remote_url):
"""Rewrite local recount engine media URLs to dashboard paths."""
if not remote_url:
return None
if remote_url.startswith("/"):
return remote_url
prefix = f"{RECOUNT_ENGINE_URL}/media/"
if remote_url.startswith(prefix):
name = remote_url[len(prefix):]
return f"/api/v1/recount/video/{name}"
if "/media/" in remote_url and remote_url.startswith(("http://127.0.0.1", "http://localhost")):
name = remote_url.rsplit("/media/", 1)[-1]
return f"/api/v1/recount/video/{name}"
return remote_url
def _update_recount_state(d):
with _recount_lock:
d["ts"] = time.time()
_recount_state.update(d)
def _http_json(method, url, payload=None, timeout=30):
import urllib.error
import urllib.request
data = None
headers = {"Accept": "application/json"}
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
body = resp.read().decode("utf-8")
return resp.status, json.loads(body) if body else {}
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="replace")
try:
parsed = json.loads(body) if body else {}
except json.JSONDecodeError:
parsed = {"error": body[:300]}
return e.code, parsed
except Exception as e:
return 0, {"error": str(e)}
def _persist_recount_result(batch_id, recount_count, delta, video_url, batch_db_id=None):
conn = get_db()
cur = conn.cursor()
if batch_db_id:
cur.execute(
"""
UPDATE batches
SET recount_count = ?, recount_delta = ?, recount_video_url = ?
WHERE id = ?
""",
(recount_count, delta, video_url, batch_db_id),
)
else:
counting_date, batch_number = _parse_batch_id(batch_id)
if not counting_date:
conn.close()
return
cur.execute(
"""
UPDATE batches
SET recount_count = ?, recount_delta = ?, recount_video_url = ?
WHERE counting_date = ? AND (batch_number = ? OR batch_number = ?)
""",
(
recount_count,
delta,
video_url,
counting_date,
str(batch_number),
int(batch_number) if str(batch_number).isdigit() else str(batch_number),
),
)
conn.commit()
conn.close()
def _run_recount_remote(batch_id, original_count, video_url, remote_batch_id=None, batch_db_id=None):
"""Proxy a local recount engine job into _recount_state."""
global _recount_state
target_remote_bid = remote_batch_id or batch_id
status_code, start_body = _http_json(
"POST",
f"{RECOUNT_ENGINE_URL}/api/v1/recount/start",
{
"batch_id": target_remote_bid,
"video_url": video_url,
"original_count": original_count,
},
timeout=60,
)
# Engine already busy: adopt same batch, otherwise ask user to Stop.
if status_code == 409:
code, remote = _http_json(
"GET", f"{RECOUNT_ENGINE_URL}/api/v1/recount/status", timeout=15
)
remote_status = (remote.get("status") or "IDLE") if code == 200 else "IDLE"
remote_bid = remote.get("batch_id") if code == 200 else None
if remote_status == "PROCESSING" and remote_bid in (batch_id, target_remote_bid):
print(
f"[recount] adopt existing recount job {batch_id} (remote={target_remote_bid})",
flush=True,
)
_update_recount_state(
{
"status": "PROCESSING",
"progress": int(remote.get("progress") or 0),
"current_count": int(remote.get("current_count") or 0),
"batch_id": batch_id,
"original_count": int(
remote.get("original_count") or original_count
),
"error": None,
}
)
# Fall through to poll loop (do not return).
else:
busy = remote_bid or "?"
err = (
f"Recount batch {busy} sedang berjalan di Recount Engine. "
"Tekan Stop, lalu Mulai lagi."
)
_update_recount_state(
{
"status": "IDLE",
"progress": 0,
"error": err,
"video_url": None,
}
)
return
elif status_code not in (200, 201) or not start_body.get("success"):
err = start_body.get("error") or f"Recount Engine HTTP {status_code}"
_update_recount_state(
{
"status": "IDLE",
"progress": 0,
"error": err,
"video_url": None,
}
)
return
while not _recount_cancel.is_set():
code, remote = _http_json("GET", f"{RECOUNT_ENGINE_URL}/api/v1/recount/status", timeout=15)
if code != 200:
_update_recount_state(
{
"status": "IDLE",
"error": remote.get("error") or f"status HTTP {code}",
}
)
return
remote_status = remote.get("status") or "IDLE"
proxied = _proxy_video_url(remote.get("video_url"))
_update_recount_state(
{
"status": remote_status if remote_status != "IDLE" else _recount_state.get("status"),
"progress": int(remote.get("progress") or 0),
"current_count": int(remote.get("current_count") or 0),
"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":
_persist_recount_result(
batch_id,
remote.get("recount_count"),
remote.get("delta"),
proxied,
batch_db_id=batch_db_id,
)
_update_recount_state({"status": "COMPLETED"})
return
# IDLE (with or without error) is terminal — stop proxy poll so UI can settle.
if remote_status == "IDLE":
err_msg = remote.get("error")
_update_recount_state({"status": "IDLE", "error": err_msg} if err_msg else {"status": "IDLE"})
return
time.sleep(RECOUNT_PROXY_POLL_SEC)
_http_json("POST", f"{RECOUNT_ENGINE_URL}/api/v1/recount/stop", {}, timeout=10)
_update_recount_state(
{
"status": "IDLE",
"progress": 0,
"error": "Dibatalkan",
"video_url": None,
}
)
def _recount_status_payload():
with _recount_lock:
return dict(_recount_state)
def _run_recount_stub(batch_id, original_count):
"""Simulate NanoPi 2 progress locally when RECOUNT_STUB=true."""
global _recount_state
steps = 20
target = original_count
if RECOUNT_STUB_DELTA is not None:
target = max(0, original_count + RECOUNT_STUB_DELTA)
for i in range(1, steps + 1):
if _recount_cancel.is_set():
with _recount_lock:
_recount_state.update(
{
"status": "IDLE",
"progress": 0,
"current_count": 0,
"recount_count": None,
"delta": None,
"video_url": None,
"error": "Dibatalkan",
}
)
return
progress = int(round(i * 100 / steps))
current = int(round(target * i / steps))
with _recount_lock:
_recount_state.update(
{
"status": "PROCESSING",
"progress": progress,
"current_count": current,
"batch_id": batch_id,
"original_count": original_count,
"error": None,
}
)
time.sleep(0.35)
delta = target - original_count
with _recount_lock:
_recount_state.update(
{
"status": "COMPLETED",
"progress": 100,
"current_count": target,
"recount_count": target,
"delta": delta,
"batch_id": batch_id,
"original_count": original_count,
"video_url": None,
"error": None,
}
)
@app.route("/api/v1/recount/batches")
def api_recount_batches():
days = request.args.get("days", 3, type=int)
days = max(1, min(days or 3, 14))
try:
conn = get_db()
cur = conn.cursor()
# Last N active counting dates (skip weekends/empty calendar days).
active_dates = _active_counting_dates(cur, days, table="batches")
if not active_dates:
conn.close()
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,
status
FROM batches
WHERE counting_date IN ({placeholders})
ORDER BY counting_date DESC, start_time DESC
""",
active_dates,
)
groups = {}
partial_groups = {}
for row in cur.fetchall():
d = row["counting_date"]
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']}"
local_video = _resolve_local_batch_video(batch_id, dict(row))
browser_video = f"/api/v1/recount/source/{batch_id}" if local_video else None
rc = row["recount_count"] if "recount_count" in row.keys() else None
raw_recount = (
row["recount_video_url"] if "recount_video_url" in row.keys() else None
)
recount_file = RECOUNT_OUTPUT_DIR / f"batch_{batch_id}_recount.mp4"
recount_video = None
if recount_file.is_file() and recount_file.stat().st_size > 0:
recount_video = f"/api/v1/recount/video/{recount_file.name}"
elif raw_recount:
proxied = _proxy_video_url(raw_recount)
if proxied:
cand_name = proxied.rsplit("/", 1)[-1]
cand_file = RECOUNT_OUTPUT_DIR / cand_name
if cand_file.is_file() and cand_file.stat().st_size > 0:
recount_video = proxied
b_num_str = str(row["batch_number"]).strip()
has_letter = bool(re.search(r"[a-zA-Z]", b_num_str))
is_child = has_letter or (
(b_num_str != "1" or str(d or "") > "2026-11-18")
and (row["count"] or 0) < MAIN_BATCH_MIN_COUNT
)
target_dict[d].append(
{
"batch_id": batch_id,
"batch_number": row["batch_number"],
"is_child": is_child,
"batch_type": "Sub" if is_child else "Main",
"original_count": row["count"],
"status": status,
"start_time": row["start_time"],
"end_time": row["end_time"],
"video_url": browser_video,
"recount_count": rc,
"delta": row["recount_delta"] if "recount_delta" in row.keys() else None,
"recount_video_url": recount_video,
}
)
conn.close()
# Preserve active-date order (newest first), not Python dict insertion quirks.
result = [
{"date": date, "batches": groups[date]}
for date in active_dates
if date in groups
]
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": [], "partial_groups": [], "error": str(e)}), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/v1/recount/start", methods=["POST"])
def api_recount_start():
global _recount_thread
data = request.get_json(silent=True) or {}
batch_id = data.get("batch_id")
counting_date, batch_number = _parse_batch_id(batch_id)
if not counting_date:
return jsonify({"success": False, "error": "batch_id tidak valid (format: YYYY-MM-DD-N)"}), 400
batch = _lookup_batch(counting_date, batch_number)
if not batch:
return jsonify({"success": False, "error": f"Batch {batch_id} tidak ditemukan"}), 404
with _recount_lock:
if _recount_state.get("status") in ("PROCESSING", "PREPARING"):
return jsonify({"success": False, "error": "Recount sedang berjalan"}), 409
original = int(batch["count"] or 0)
video_url = None
if not RECOUNT_STUB:
local_video = _resolve_local_batch_video(batch_id, batch)
if local_video is None:
return jsonify(
{
"success": False,
"error": f"Video sumber batch {batch_id} tidak ditemukan di {BATCH_VIDEO_DIR}",
}
), 404
video_url = str(local_video)
_recount_cancel.clear()
with _recount_lock:
_recount_state.update(
{
"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…",
}
)
if RECOUNT_STUB:
_recount_thread = threading.Thread(
target=_run_recount_stub,
args=(batch_id, original),
daemon=True,
)
_recount_thread.start()
return jsonify(
{
"success": True,
"batch_id": batch_id,
"original_count": original,
"status": "PROCESSING",
"stub": True,
}
)
remote_bid = _resolve_remote_batch_id(batch_id, batch)
_recount_thread = threading.Thread(
target=_run_recount_remote,
args=(batch_id, original, video_url, remote_bid, batch.get("id")),
daemon=True,
)
_recount_thread.start()
return jsonify(
{
"success": True,
"batch_id": batch_id,
"original_count": original,
"status": "PROCESSING",
"stub": False,
"video_url": video_url,
"recount_engine_url": RECOUNT_ENGINE_URL,
}
)
@app.route("/api/v1/recount/status")
def api_recount_status():
payload = _recount_status_payload()
# Rehydrate UI when local recount engine is still running after a dashboard restart.
if (
not RECOUNT_STUB
and payload.get("status") not in ("PROCESSING", "PREPARING")
):
code, remote = _http_json(
"GET", f"{RECOUNT_ENGINE_URL}/api/v1/recount/status", timeout=5
)
if code == 200 and (remote.get("status") or "") in ("PROCESSING", "PREPARING"):
remote_bid = remote.get("batch_id")
logical_bid = _decode_remote_batch_id(remote_bid) if remote_bid else None
counting_date, batch_number = _parse_batch_id(logical_bid) if logical_bid else (None, None)
batch = _lookup_batch(counting_date, batch_number) if counting_date else None
if not batch and remote_bid:
batch = _lookup_batch_by_video_key(remote_bid)
active_bid = _recount_state.get("batch_id")
if not active_bid and batch:
active_bid = f"{batch['counting_date']}-{batch['batch_number']}"
elif not active_bid:
active_bid = logical_bid or remote_bid
orig_cnt = int(remote.get("original_count") or (batch.get("count") if batch else 0) or 0)
_update_recount_state(
{
"status": remote.get("status") or "PROCESSING",
"progress": int(remote.get("progress") or 0),
"current_count": int(remote.get("current_count") or 0),
"batch_id": active_bid,
"batch_number": (batch.get("batch_number") if batch else None) 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"),
}
)
with _recount_lock:
payload = dict(_recount_state)
# Ensure a proxy poller is attached so COMPLETED gets persisted.
global _recount_thread
if remote_bid and (
_recount_thread is None or not _recount_thread.is_alive()
):
_recount_cancel.clear()
_recount_thread = threading.Thread(
target=_poll_recount_remote,
args=(
active_bid,
int(payload.get("original_count") or 0),
batch.get("id") if batch else None,
),
daemon=True,
)
_recount_thread.start()
payload["success"] = True
payload["stub"] = RECOUNT_STUB
return jsonify(payload)
def _poll_recount_remote(batch_id, original_count, batch_db_id=None):
"""Attach to an already-running local recount job (no /start)."""
global _recount_state
while not _recount_cancel.is_set():
code, remote = _http_json(
"GET", f"{RECOUNT_ENGINE_URL}/api/v1/recount/status", timeout=15
)
if code != 200:
with _recount_lock:
_recount_state.update(
{
"status": "IDLE",
"error": remote.get("error") or f"status HTTP {code}",
}
)
return
remote_status = remote.get("status") or "IDLE"
proxied = _proxy_video_url(remote.get("video_url"))
with _recount_lock:
_recount_state.update(
{
"status": (
remote_status
if remote_status != "IDLE"
else _recount_state.get("status")
),
"progress": int(remote.get("progress") or 0),
"current_count": int(remote.get("current_count") or 0),
"recount_count": remote.get("recount_count"),
"delta": remote.get("delta"),
"batch_id": batch_id,
"original_count": original_count,
"video_url": proxied,
"error": remote.get("error"),
}
)
if remote_status == "COMPLETED":
_persist_recount_result(
batch_id,
remote.get("recount_count"),
remote.get("delta"),
proxied,
batch_db_id=batch_db_id,
)
with _recount_lock:
_recount_state["status"] = "COMPLETED"
return
if remote_status == "IDLE":
with _recount_lock:
_recount_state["status"] = "IDLE"
if remote.get("error"):
_recount_state["error"] = remote.get("error")
return
time.sleep(RECOUNT_PROXY_POLL_SEC)
_http_json("POST", f"{RECOUNT_ENGINE_URL}/api/v1/recount/stop", {}, timeout=10)
with _recount_lock:
_recount_state.update(
{
"status": "IDLE",
"progress": 0,
"error": "Dibatalkan",
"video_url": None,
}
)
@app.route("/api/v1/recount/stop", methods=["POST"])
def api_recount_stop():
"""Always cancel local proxy and recount engine — even if local state already IDLE."""
_recount_cancel.set()
remote_msg = None
if not RECOUNT_STUB:
code, body = _http_json(
"POST", f"{RECOUNT_ENGINE_URL}/api/v1/recount/stop", {}, timeout=10
)
if code not in (200, 201):
remote_msg = (body or {}).get("error") or f"Recount engine stop HTTP {code}"
with _recount_lock:
_recount_state.update(
{
"status": "IDLE",
"progress": 0,
"error": remote_msg, # None on clean stop
"video_url": None,
}
)
st = dict(_recount_state)
return jsonify(
{
"success": True,
"message": "Pembatalan diminta",
"status": st.get("status"),
"error": st.get("error"),
}
)
@app.route("/api/v1/recount/live-frame")
def api_recount_live_frame():
"""Single annotated JPEG from local recount engine / shared memory."""
import urllib.request
if RECOUNT_LIVE_FRAME_PATH.is_file():
try:
data = RECOUNT_LIVE_FRAME_PATH.read_bytes()
if data:
return Response(
data,
mimetype="image/jpeg",
headers={"Cache-Control": "no-store, no-cache, must-revalidate"},
)
except Exception:
pass
remote = f"{RECOUNT_ENGINE_URL}/api/v1/recount/live-frame"
try:
with urllib.request.urlopen(remote, timeout=5) as resp:
data = resp.read()
if not data:
return jsonify({"success": False, "error": "empty frame"}), 503
return Response(
data,
mimetype="image/jpeg",
headers={"Cache-Control": "no-store, no-cache, must-revalidate"},
)
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 503
@app.route("/api/v1/recount/warmup", methods=["POST"])
def api_recount_warmup():
"""Verify local batch video availability and pre-notify local recount engine."""
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)
local_video = _resolve_local_batch_video(batch_id, batch or {})
if local_video is None:
return jsonify({"success": False, "cached": False, "error": "Video lokal tidak ditemukan"}), 404
remote_bid = _resolve_remote_batch_id(batch_id, batch or {})
status_code, body = _http_json(
"POST",
f"{RECOUNT_ENGINE_URL}/api/v1/recount/warmup",
{"batch_id": remote_bid, "video_url": str(local_video)},
timeout=5,
)
if status_code in (200, 201) and isinstance(body, dict):
return jsonify(body), status_code
return jsonify({"success": True, "cached": True, "local_path": str(local_video)}), 200
@app.route("/api/v1/recount/live-video")
def api_recount_live_video():
"""
Zero-latency chunked MJPEG stream proxy of local recount engine live frames.
"""
import urllib.request
remote_stream = f"{RECOUNT_ENGINE_URL}/api/v1/recount/live-video"
def generate():
try:
req = urllib.request.Request(
remote_stream,
headers={"Accept": "multipart/x-mixed-replace; boundary=frame"},
)
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",
headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
)
@app.route("/api/v1/recount/video/<path:filename>")
def api_recount_video_proxy(filename):
"""Serve local recount output directly from RECOUNT_OUTPUT_DIR (supports Range)."""
if ".." in filename or "/" in filename or "\\" in filename:
return jsonify({"error": "invalid"}), 400
local_path = RECOUNT_OUTPUT_DIR / filename
if local_path.is_file() and local_path.stat().st_size > 0:
return send_file(local_path, mimetype="video/mp4", conditional=True)
return jsonify({"error": "not found"}), 404
@app.route("/api/v1/recount/warm-source/<batch_id>", methods=["POST", "GET"])
def api_recount_warm_source(batch_id):
"""Check whether local batch video file exists on NVMe storage."""
if not re.match(r"^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]*$", batch_id or ""):
return jsonify({"success": False, "error": "invalid batch_id"}), 400
counting_date, batch_number = _parse_batch_id(batch_id)
batch = _lookup_batch(counting_date, batch_number) if counting_date else None
if not batch:
batch = _lookup_batch_by_video_key(batch_id)
local_video = _resolve_local_batch_video(batch_id, batch)
if local_video is not None:
return jsonify(
{
"success": True,
"ready": True,
"batch_id": batch_id,
"bytes": local_video.stat().st_size,
}
)
return jsonify(
{
"success": False,
"ready": False,
"error": f"Video sumber {batch_id} tidak ditemukan di {BATCH_VIDEO_DIR}",
"batch_id": batch_id,
}
), 404
@app.route("/api/v1/recount/source/<batch_id>")
def api_recount_source_proxy(batch_id):
"""
Serve source batch video directly from local NVMe BATCH_VIDEO_DIR (Range-enabled).
Pass ?download=1 for Content-Disposition: attachment.
"""
if not re.match(r"^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]*$", batch_id or ""):
return jsonify({"error": "invalid batch_id"}), 400
as_download = request.args.get("download", "").lower() in ("1", "true", "yes")
filename = f"{batch_id}.mp4"
counting_date, batch_number = _parse_batch_id(batch_id)
batch = _lookup_batch(counting_date, batch_number) if counting_date else None
if not batch:
batch = _lookup_batch_by_video_key(batch_id)
local_video = _resolve_local_batch_video(batch_id, batch)
if local_video is None:
return jsonify(
{
"success": False,
"error": f"Video sumber {batch_id} tidak ditemukan di {BATCH_VIDEO_DIR}",
}
), 404
return send_file(
local_video,
mimetype="video/mp4",
conditional=True,
download_name=filename,
as_attachment=as_download,
)
if __name__ == "__main__":
WSGIRequestHandler.protocol_version = "HTTP/1.1"
print(f"ZenAI APC dashboard at http://{DASHBOARD_HOST}:{DASHBOARD_PORT}")
print(f"DB: {DB_PATH}")
print(f"State: {CURRENT_BATCH_PATH}")
print(f"Recount stub: {RECOUNT_STUB} | Recount Engine: {RECOUNT_ENGINE_URL}")
print(f"Batch Videos: {BATCH_VIDEO_DIR} | Recount Output: {RECOUNT_OUTPUT_DIR}")
app.run(host=DASHBOARD_HOST, port=DASHBOARD_PORT, debug=FLASK_DEBUG)