Files
zenai-apc-ngoro/counter_dashboard.py
2026-11-03 10:35:25 +07:00

2517 lines
89 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
from werkzeug.serving import WSGIRequestHandler
from dotenv import load_dotenv
from retention_utils import active_counting_dates
load_dotenv()
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
_DEFAULT_DIR = "/opt/apc-ngoro"
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")
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")
)
NANOPI2_URL = os.getenv("NANOPI2_URL", "http://192.168.192.16:8765").rstrip("/")
MOTIONEYE_URL = os.getenv("MOTIONEYE_URL", "http://192.168.192.251:8081").rstrip("/")
MOTIONEYE_INGEST_URL = os.getenv(
"MOTIONEYE_INGEST_URL", "http://192.168.192.251:8090"
).rstrip("/")
RECOUNT_STUB = os.getenv("RECOUNT_STUB", "true").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():
return dict(
site_name=SITE_NAME,
camera_name=CAMERA_NAME,
cutoff_time=CUTOFF_TIME,
stream_fps=STREAM_FPS_DISPLAY,
stream_resolution=STREAM_RESOLUTION_DISPLAY,
stream_accuracy=STREAM_ACCURACY_PCT,
motioneye_media_dir=os.getenv("MOTIONEYE_MEDIA_DIR", "/data/media/Camera1"),
)
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)
cur = conn.cursor()
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()
conn.close()
_ensure_db()
def get_db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def get_counting_date(dt=None, cutoff_str=CUTOFF_TIME):
if dt is None:
dt = datetime.now()
cutoff = datetime.strptime(cutoff_str, "%H:%M").time()
if dt.time() < cutoff:
return dt.date().isoformat()
return (dt.date() + timedelta(days=1)).isoformat()
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()
today = get_counting_date()
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": CUTOFF_TIME,
"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,
"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
""",
(date,),
)
batches = []
total_duration = 0
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
# Rule 1: Sub-batch does not apply to the first batch
if idx == 0:
is_child = False
current_main_num = 1
sub_letter_idx = 0
display_batch_num = "1"
else:
has_letter = bool(re.search(r"[a-zA-Z]", b_num_str))
if has_letter:
is_child = True
display_batch_num = b_num_str
m = re.match(r"^(\d+)", b_num_str)
if m:
current_main_num = int(m.group(1))
elif count_val < MAIN_BATCH_MIN_COUNT:
is_child = True
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"{current_main_num}{letter}"
else:
is_child = False
sub_letter_idx = 0
m = re.match(r"^(\d+)", b_num_str)
current_main_num = int(m.group(1)) if m else (current_main_num + 1)
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()
# Rule 1: first batch (batch_number '1') is never child
is_child = (b_str != "1") and (bool(re.search(r"[a-zA-Z]", b_str)) or ((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
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
current_date = None
main_seq = 1
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
dur = row.get("duration_minutes") or 0
# Reset state on date boundary
if d != current_date:
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)
# Rule 1: Sub-batch does not apply to the first batch of the day
if is_first_of_day:
is_child = False
main_id = "1"
row["batch_number"] = "1"
elif has_letter:
is_child = True
elif count < main_min:
is_child = True
else:
is_child = False
if not is_child or current_group is None:
if not is_first_of_day:
main_seq += 1
main_id = str(main_seq)
row["batch_number"] = main_id
current_group = {
"main_id": main_id,
"main_row": row,
"children": [],
}
groups.append(current_group)
else:
if not has_letter:
sub_idx = 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)
raw_rows = []
fixed_rows = []
for grp in groups:
main_r = grp["main_row"]
children = grp["children"]
main_raw = main_r.get("count") or 0
child_raw_sum = sum(c.get("count") or 0 for c in children)
consolidated_total = main_raw + child_raw_sum
child_labels = [str(c["batch_number"]) for c in children]
main_notes = f"Main (termasuk {', '.join(child_labels)})" if 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,
}
)
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,
}
)
# Standalone fixed batch (NO 0-chicken batches!)
if consolidated_total > 0:
fixed_end = children[-1].get("end_time") if children and children[-1].get("end_time") else main_r.get("end_time")
combined_dur = round((main_r.get("duration_minutes") or 0) + sum(c.get("duration_minutes") or 0 for c in children), 1)
fixed_notes = f"Termasuk {', '.join(child_labels)}" if children else "-"
fixed_rows.append(
{
"counting_date": main_r.get("counting_date"),
"batch_number": grp["main_id"],
"batch_type": "Main",
"count": consolidated_total,
"notes": fixed_notes,
"start_time": main_r.get("start_time"),
"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, CAST(batch_number AS INTEGER) ASC, batch_number 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
""",
(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_batch_video_url(batch_id, batch_row):
"""Prefer DB video_url; fall back to MotionEye ingest file URL."""
if batch_row and batch_row.get("video_url"):
return batch_row["video_url"]
return f"{MOTIONEYE_INGEST_URL}/files/{batch_id}"
def _resolve_remote_batch_id(batch_id, batch_row=None):
"""
Ensure the batch ID passed to NanoPi 2 is accepted by its validator (digits only)
and avoids collisions with stale source caches on NanoPi 2.
"""
if not batch_id or not isinstance(batch_id, str):
return batch_id
import re as _re
# Sub-batch e.g. 2026-11-02-15a -> 2026-11-02-1501
m_sub = _re.match(r"^(\d{4}-\d{2}-\d{2})-(\d+)([a-zA-Z])$", batch_id)
if m_sub:
d_part, num_part, letter = m_sub.groups()
suffix_num = ord(letter.lower()) - ord("a") + 1
return f"{d_part}-{num_part}{suffix_num:02d}"
# If this batch's physical video file differs from its batch number (e.g. Batch 16 recorded in file 17),
# generate a unique numeric identifier (e.g. 2026-11-02-16017) so NanoPi 2 never uses a stale
# cached _src_2026-11-02-16.mp4 from an earlier shifted run.
if batch_row:
raw_video = batch_row.get("video_url") or ""
m_vid = _re.search(r"/files/\d{4}-\d{2}-\d{2}-(\d+)", raw_video)
if m_vid:
file_num = int(m_vid.group(1))
parts = batch_id.rsplit("-", 1)
if len(parts) == 2 and parts[1].isdigit():
if int(parts[1]) != file_num:
return f"{parts[0]}-{parts[1]}0{file_num:02d}"
# Standard numeric batch ID without divergence: use directly
if _re.match(r"^\d{4}-\d{2}-\d{2}-\d+$", batch_id):
return batch_id
return batch_id
def _decode_remote_batch_id(remote_bid):
"""
Convert mapped remote batch ID back to logical batch ID.
e.g. 2026-11-02-16017 -> 2026-11-02-16
2026-11-02-1501 -> 2026-11-02-15a
"""
if not remote_bid or not isinstance(remote_bid, str):
return remote_bid
# First check if remote_bid directly matches a batch in DB
counting_date, batch_number = _parse_batch_id(remote_bid)
if counting_date and _lookup_batch(counting_date, batch_number):
return remote_bid
import re as _re
parts = remote_bid.rsplit("-", 1)
if len(parts) != 2:
return remote_bid
d_part, num_str = parts
# 1. Sub-batch check (e.g. 1501 -> 15a)
m_sub = _re.match(r"^(\d+?)(\d{2})$", num_str)
if m_sub:
main_part, suffix_num_str = m_sub.groups()
s_num = int(suffix_num_str)
if 1 <= s_num <= 26:
candidate_bn = f"{main_part}{chr(ord('a') + s_num - 1)}"
if _lookup_batch(d_part, candidate_bn):
return f"{d_part}-{candidate_bn}"
# 2. Divergent file suffix check (e.g. 16017 -> 16)
for L in range(len(num_str) - 1, 0, -1):
cand_bn = num_str[:L]
if _lookup_batch(d_part, cand_bn):
return f"{d_part}-{cand_bn}"
return remote_bid
def _proxy_video_url(remote_url):
"""Rewrite NanoPi2 / ingest URLs through this dashboard for browser access."""
if not remote_url:
return None
if remote_url.startswith("/"):
return remote_url
# NanoPi 2 media
prefix = f"{NANOPI2_URL}/media/"
if remote_url.startswith(prefix):
name = remote_url[len(prefix) :]
return f"/api/v1/recount/video/{name}"
# MotionEye ingest source (stream through logical proxy)
ingest_prefix = f"{MOTIONEYE_INGEST_URL}/files/"
if remote_url.startswith(ingest_prefix):
batch = _lookup_batch_by_video_key(remote_url)
if batch:
return f"/api/v1/recount/source/{batch['counting_date']}-{batch['batch_number']}"
batch_id = remote_url[len(ingest_prefix) :]
return f"/api/v1/recount/source/{batch_id}"
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 NanoPi 2 recount job into local _recount_state."""
global _recount_state
target_remote_bid = remote_batch_id or batch_id
status_code, start_body = _http_json(
"POST",
f"{NANOPI2_URL}/api/v1/recount/start",
{
"batch_id": target_remote_bid,
"video_url": video_url,
"original_count": original_count,
},
timeout=60,
)
# NP2 already busy: adopt same batch, otherwise ask user to Stop.
if status_code == 409:
code, remote = _http_json(
"GET", f"{NANOPI2_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 NP2 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 NanoPi 2. "
"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"NanoPi2 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"{NANOPI2_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"{NANOPI2_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']}"
raw_video = row["video_url"] if "video_url" in row.keys() else None
# Browser-safe same-origin proxy (laptop may not reach MotionEye :8090)
if raw_video:
browser_video = f"/api/v1/recount/source/{batch_id}"
else:
browser_video = None
raw_recount = (
row["recount_video_url"] if "recount_video_url" in row.keys() else None
)
recount_video = _proxy_video_url(raw_recount) if raw_recount else None
rc = row["recount_count"] if "recount_count" in row.keys() else None
# 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"
b_num_str = str(row["batch_number"]).strip()
has_letter = bool(re.search(r"[a-zA-Z]", b_num_str))
# Rule 1: first batch is never sub
is_child = has_letter or (b_num_str != "1" 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 = _resolve_batch_video_url(batch_id, batch)
_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,
"nanopi2_url": NANOPI2_URL,
}
)
@app.route("/api/v1/recount/status")
def api_recount_status():
payload = _recount_status_payload()
# Rehydrate UI when NP2 still running but local proxy already went IDLE
# (e.g. start got 409, dashboard restart, or lost proxy thread).
if (
not RECOUNT_STUB
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 "") 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 NP2 job (no /start)."""
global _recount_state
while not _recount_cancel.is_set():
code, remote = _http_json(
"GET", f"{NANOPI2_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"{NANOPI2_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 NanoPi 2 — even if local state already IDLE."""
_recount_cancel.set()
remote_msg = None
if not RECOUNT_STUB:
code, body = _http_json(
"POST", f"{NANOPI2_URL}/api/v1/recount/stop", {}, timeout=10
)
if code not in (200, 201):
remote_msg = (body or {}).get("error") or f"NP2 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 NanoPi 2 (preferred by the recount UI poller)."""
import urllib.request
remote = f"{NANOPI2_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():
"""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 {})
remote_bid = _resolve_remote_batch_id(batch_id, batch or {})
status_code, body = _http_json(
"POST",
f"{NANOPI2_URL}/api/v1/recount/warmup",
{"batch_id": remote_bid, "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():
"""
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_stream = f"{NANOPI2_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):
"""Stream NanoPi 2 recount output (supports Range; no full-file buffer)."""
if ".." in filename or filename.startswith("/"):
return jsonify({"error": "invalid"}), 400
remote = f"{NANOPI2_URL}/media/{filename}"
return _stream_remote_video(remote)
_PREVIEW_CACHE_DIR = PREVIEW_CACHE_DIR
_preview_lock = threading.Lock()
_preview_warming = set()
_preview_errors = {}
def _ensure_faststart_source(batch_id: str):
"""
Cache a faststart remux of the MotionEye source so <video> can play
before the whole file finishes downloading.
"""
import subprocess
import urllib.request
_PREVIEW_CACHE_DIR.mkdir(parents=True, exist_ok=True)
cached = _PREVIEW_CACHE_DIR / f"{batch_id}.mp4"
if cached.is_file() and cached.stat().st_size > 0:
return cached
with _preview_lock:
if cached.is_file() and cached.stat().st_size > 0:
return cached
raw = _PREVIEW_CACHE_DIR / f"{batch_id}.raw.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)
if batch and batch.get("video_url"):
remote = batch["video_url"]
else:
remote_bid = _resolve_remote_batch_id(batch_id, batch)
remote = f"{MOTIONEYE_INGEST_URL}/files/{remote_bid}"
try:
urllib.request.urlretrieve(remote, str(raw))
tmp = _PREVIEW_CACHE_DIR / f"{batch_id}.fs.mp4"
# Nice ffmpeg when counter is busy so live detect keeps CPU.
nice_prefix = ["nice", "-n", "15"] if _counter_busy() else []
subprocess.run(
nice_prefix
+ [
"ffmpeg",
"-y",
"-i",
str(raw),
"-c",
"copy",
"-movflags",
"+faststart",
str(tmp),
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=600,
)
tmp.replace(cached)
_preview_errors.pop(batch_id, None)
except Exception as exc:
_preview_errors[batch_id] = str(exc)
raise
finally:
raw.unlink(missing_ok=True)
(_PREVIEW_CACHE_DIR / f"{batch_id}.fs.mp4").unlink(missing_ok=True)
_preview_warming.discard(batch_id)
return cached
def _warm_source_async(batch_id: str, force: bool = False):
"""Kick remux only when counter is idle (unless force / PREVIEW_WARM_WHEN_BUSY)."""
if batch_id in _preview_warming:
return
cached = _PREVIEW_CACHE_DIR / f"{batch_id}.mp4"
if cached.is_file() and cached.stat().st_size > 0:
return
if not force and not PREVIEW_WARM_WHEN_BUSY and _counter_busy():
return
_preview_warming.add(batch_id)
def _job():
try:
# Wait out a busy counter before downloading/remuxing.
for _ in range(120):
if PREVIEW_WARM_WHEN_BUSY or force or not _counter_busy():
break
time.sleep(1.0)
else:
return
_ensure_faststart_source(batch_id)
except Exception:
pass
finally:
_preview_warming.discard(batch_id)
threading.Thread(target=_job, daemon=True).start()
def _stream_remote_video(remote_url: str, download_name: str | None = None):
"""Chunked proxy with Range forwarding — browser can start sooner."""
import urllib.error
import urllib.request
range_hdr = request.headers.get("Range")
req = urllib.request.Request(remote_url)
req.add_header("User-Agent", "apc-ngoro-dashboard/1.0")
if range_hdr:
req.add_header("Range", range_hdr)
try:
upstream = urllib.request.urlopen(req, timeout=120)
except urllib.error.HTTPError as e:
if e.code == 416:
return Response(status=416)
return jsonify({"success": False, "error": str(e)}), 502
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 502
status = getattr(upstream, "status", 200) or 200
headers = {
"Accept-Ranges": "bytes",
"Cache-Control": "public, max-age=60",
}
cl = upstream.headers.get("Content-Length")
if cl:
headers["Content-Length"] = cl
cr = upstream.headers.get("Content-Range")
if cr:
headers["Content-Range"] = cr
ctype = upstream.headers.get("Content-Type") or "video/mp4"
if download_name:
safe = download_name.replace('"', "")
headers["Content-Disposition"] = f'attachment; filename="{safe}"'
def generate():
try:
while True:
chunk = upstream.read(256 * 1024)
if not chunk:
break
yield chunk
finally:
try:
upstream.close()
except Exception:
pass
return Response(generate(), status=status, mimetype=ctype, headers=headers, direct_passthrough=True)
@app.route("/api/v1/recount/warm-source/<batch_id>", methods=["POST", "GET"])
def api_recount_warm_source(batch_id):
"""Kick off / poll local faststart preview cache (non-blocking)."""
import re as _re
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
cached = _PREVIEW_CACHE_DIR / f"{batch_id}.mp4"
if cached.is_file() and cached.stat().st_size > 0:
return jsonify(
{
"success": True,
"ready": True,
"batch_id": batch_id,
"bytes": cached.stat().st_size,
}
)
err = _preview_errors.get(batch_id)
if err and batch_id not in _preview_warming:
return jsonify({"success": False, "ready": False, "error": err}), 502
busy = _counter_busy()
if busy and not PREVIEW_WARM_WHEN_BUSY:
return jsonify(
{
"success": True,
"ready": False,
"warming": False,
"deferred": True,
"reason": "counter_busy",
"batch_id": batch_id,
}
), 202
_warm_source_async(batch_id)
return jsonify(
{
"success": True,
"ready": False,
"warming": True,
"batch_id": batch_id,
}
), 202
@app.route("/api/v1/recount/source/<batch_id>")
def api_recount_source_proxy(batch_id):
"""
Serve source preview from a local faststart cache when ready;
otherwise stream upstream so playback can start without waiting for remux.
Pass ?download=1 for Content-Disposition: attachment.
"""
import re as _re
from flask import send_file
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"
cached = _PREVIEW_CACHE_DIR / f"{batch_id}.mp4"
if cached.is_file() and cached.stat().st_size > 0:
return send_file(
cached,
mimetype="video/mp4",
conditional=True,
download_name=filename,
as_attachment=as_download,
)
# Remux only when counter idle; always allow direct upstream stream.
if not _counter_busy() or PREVIEW_WARM_WHEN_BUSY:
_warm_source_async(batch_id)
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)
if batch and batch.get("video_url"):
remote = batch["video_url"]
else:
remote_bid = _resolve_remote_batch_id(batch_id, batch)
remote = f"{MOTIONEYE_INGEST_URL}/files/{remote_bid}"
return _stream_remote_video(
remote, download_name=filename if as_download else None
)
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} | NanoPi2: {NANOPI2_URL} | MotionEye: {MOTIONEYE_URL}")
print(f"Ingest: {MOTIONEYE_INGEST_URL}")
app.run(host=DASHBOARD_HOST, port=DASHBOARD_PORT, debug=FLASK_DEBUG)