Files
zenai-fpc/counter_dashboard.py

864 lines
31 KiB
Python

#!/usr/bin/env python3
"""
Edge RKNN production counter dashboard.
Reads the counter database and active batch state for the sack counting flow.
"""
import json
import os
import sqlite3
import time
from io import BytesIO
from datetime import datetime, timedelta
import urllib.request
import urllib.error
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from flask import Flask, render_template, jsonify, request, Response
from werkzeug.serving import WSGIRequestHandler
from dotenv import load_dotenv
from batch_store import ensure_batch_schema
load_dotenv()
app = Flask(__name__, template_folder="templates", static_folder="static")
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "change-me-in-production")
_DEFAULT_DIR = "/opt/feedmill"
DB_PATH = os.getenv("DB_PATH", f"{_DEFAULT_DIR}/feedmill.db")
CURRENT_BATCH_PATH = os.getenv("STATE_FILE", os.getenv("CURRENT_BATCH_PATH", f"{_DEFAULT_DIR}/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/feedmill/live_frame.jpg")
SITE_NAME = os.getenv("SITE_NAME", "LIVE")
CAMERA_NAME = os.getenv("CAMERA_NAME", "")
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")
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"
COUNTER_CONTROL_HOST = os.getenv("COUNTER_CONTROL_HOST", "127.0.0.1")
COUNTER_CONTROL_PORT = int(os.getenv("COUNTER_CONTROL_PORT", "5001"))
COUNTER_CONTROL_URL = f"http://{COUNTER_CONTROL_HOST}:{COUNTER_CONTROL_PORT}"
BATCH_MODE = os.getenv("BATCH_MODE", "manual").strip().lower()
@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()
if not jpeg or len(jpeg) < 2 or jpeg[:2] != b"\xff\xd8":
consecutive_fails += 1
if consecutive_fails >= MAX_FAILS:
return
time.sleep(0.05)
continue
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():
try:
from pathlib import Path
Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DB_PATH)
ensure_batch_schema(conn)
conn.close()
except Exception as e:
print(f"[Warning] Could not initialize database at {DB_PATH}: {e}")
_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 get_next_batch_number_db(counting_date=None):
try:
if counting_date is None:
counting_date = get_counting_date()
conn = get_db()
cur = conn.cursor()
cur.execute(
"SELECT COALESCE(MAX(batch_number), 0) + 1 FROM batches WHERE counting_date = ?",
(counting_date,),
)
row = cur.fetchone()
conn.close()
return row[0] if row else 1
except Exception:
return 1
def _send_counter_command(endpoint, data=b""):
url = f"{COUNTER_CONTROL_URL}/{endpoint}"
req = urllib.request.Request(url, data=data, method="POST")
try:
with urllib.request.urlopen(req, timeout=4.0) as resp:
return json.loads(resp.read().decode("utf-8")), resp.status
except urllib.error.HTTPError as e:
try:
return json.loads(e.read().decode("utf-8")), e.code
except Exception:
return {"success": False, "error": f"HTTP {e.code}"}, e.code
except urllib.error.URLError as e:
return {
"success": False,
"error": "Engine counter tidak aktif. Pastikan service feedmill-counter berjalan.",
"detail": str(e.reason),
}, 503
except Exception as e:
return {"success": False, "error": str(e)}, 500
@app.route("/")
def index():
return render_template(
"dashboard.html",
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,
)
def _normalize_obj_label(raw_label):
val = str(raw_label or "").strip().lower()
if val in ("mixed", "all", "both"):
return "mixed"
return "box" if val == "box" else "sack"
def _separate_counts(raw_label, count, sack_count=None, box_count=None):
"""Return separate class counts while remaining compatible with legacy rows."""
total = int(count or 0)
if sack_count is not None or box_count is not None:
sacks = int(sack_count or 0)
boxes = int(box_count or 0)
elif _normalize_obj_label(raw_label) == "box":
sacks, boxes = 0, total
else:
sacks, boxes = total, 0
return sacks, boxes
def _resolve_batch_label(raw_label, sack_count, box_count):
"""Return 'sack', 'box', or 'mixed' based on actual counted contents."""
sacks = int(sack_count or 0)
boxes = int(box_count or 0)
if sacks > 0 and boxes > 0:
return "mixed"
if boxes > 0 and sacks == 0:
return "box"
if sacks > 0 and boxes == 0:
return "sack"
return _normalize_obj_label(raw_label)
@app.route("/api/current-batch")
def api_current_batch():
cdate = get_counting_date()
try:
with open(CURRENT_BATCH_PATH, "r") as f:
data = json.load(f)
sack_count, box_count = _separate_counts(
data.get("object_label"),
data.get("count", 0),
data.get("sack_count"),
data.get("box_count"),
)
return jsonify(
{
"success": True,
"active": True,
"status": "running",
"batch_mode": BATCH_MODE,
"counting_date": data.get("counting_date", cdate),
"batch_number": data.get("batch_number"),
"object_label": _normalize_obj_label(data.get("object_label")),
"count": data.get("count", 0),
"sack_count": sack_count,
"box_count": box_count,
"plate": data.get("plate") or None,
"start_time": data.get("start_time"),
"last_detection_time": data.get("last_detection_time"),
}
)
except FileNotFoundError:
next_batch = get_next_batch_number_db(cdate)
return jsonify(
{
"success": False,
"active": False,
"status": "stopped",
"batch_mode": BATCH_MODE,
"error": "No active batch",
"count": 0,
"sack_count": 0,
"box_count": 0,
"batch_number": None,
"object_label": None,
"plate": None,
"next_batch_number": next_batch,
"counting_date": cdate,
}
), 200
except Exception as e:
next_batch = get_next_batch_number_db(cdate)
return jsonify(
{
"success": False,
"active": False,
"status": "stopped",
"batch_mode": BATCH_MODE,
"error": str(e),
"count": 0,
"sack_count": 0,
"box_count": 0,
"batch_number": None,
"object_label": None,
"plate": None,
"next_batch_number": next_batch,
"counting_date": cdate,
}
), 500
def _get_peer_api_token():
env_token = os.getenv("PEER_API_TOKEN", "").strip()
if env_token:
return env_token
for candidate in (
os.path.join(_DEFAULT_DIR, "peer_sync_token.txt"),
os.path.join(_DEFAULT_DIR, "docs", "peer_sync_token.txt"),
):
if os.path.isfile(candidate):
try:
with open(candidate, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line.startswith("PEER_API_TOKEN="):
return line.split("=", 1)[1].strip()
except Exception:
pass
return ""
def _check_peer_api_key():
if "X-API-Key" not in request.headers:
return None
provided = request.headers.get("X-API-Key", "").strip()
expected = _get_peer_api_token()
if not expected or provided != expected:
return jsonify({"success": False, "error": "unauthorized"}), 401
return None
@app.route("/api/batch/start", methods=["POST"])
@app.route("/api/batch/start/<object_label>", methods=["POST"])
def api_batch_start(object_label=None):
auth_err = _check_peer_api_key()
if auth_err is not None:
return auth_err
raw = request.get_data()
data, code = (
_send_counter_command("start", data=raw)
if raw
else _send_counter_command("start")
)
return jsonify(data), code
@app.route("/api/batch/stop", methods=["POST"])
def api_batch_stop():
auth_err = _check_peer_api_key()
if auth_err is not None:
return auth_err
raw = request.get_data()
data, code = (
_send_counter_command("stop", data=raw)
if raw
else _send_counter_command("stop")
)
return jsonify(data), code
@app.route("/api/batch/status", methods=["GET"])
def api_batch_status():
url = f"{COUNTER_CONTROL_URL}/status"
req = urllib.request.Request(url, method="GET")
try:
with urllib.request.urlopen(req, timeout=2.0) as resp:
data = json.loads(resp.read().decode("utf-8"))
return jsonify(data), 200
except Exception:
state_data = None
if os.path.isfile(CURRENT_BATCH_PATH):
try:
with open(CURRENT_BATCH_PATH, "r") as f:
state_data = json.load(f)
except Exception:
pass
cdate = get_counting_date()
next_batch = get_next_batch_number_db(cdate)
if state_data:
sack_count, box_count = _separate_counts(
state_data.get("object_label"),
state_data.get("count", 0),
state_data.get("sack_count"),
state_data.get("box_count"),
)
return jsonify({
"success": True,
"active": True,
"status": "running",
"batch_mode": BATCH_MODE,
"batch_number": state_data.get("batch_number"),
"object_label": _normalize_obj_label(state_data.get("object_label")),
"count": state_data.get("count", 0),
"sack_count": sack_count,
"box_count": box_count,
"plate": state_data.get("plate") or None,
"counting_date": state_data.get("counting_date", cdate),
"start_time": state_data.get("start_time"),
"last_detection_time": state_data.get("last_detection_time"),
"engine_alive": False,
}), 200
else:
return jsonify({
"success": True,
"active": False,
"status": "stopped",
"batch_mode": BATCH_MODE,
"batch_number": None,
"object_label": None,
"plate": None,
"next_batch_number": next_batch,
"count": 0,
"sack_count": 0,
"box_count": 0,
"counting_date": cdate,
"start_time": None,
"last_detection_time": None,
"engine_alive": False,
}), 200
@app.route("/api/previous-batch")
def api_previous_batch():
try:
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
SELECT counting_date, batch_number, object_label, count, sack_count, box_count,
plate, start_time, end_time,
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
FROM batches
ORDER BY end_time DESC
LIMIT 1
"""
)
row = cur.fetchone()
conn.close()
if row:
sack_count, box_count = _separate_counts(
row["object_label"], row["count"], row["sack_count"], row["box_count"]
)
return jsonify(
{
"success": True,
"date": row["counting_date"],
"batch_number": row["batch_number"],
"object_label": _resolve_batch_label(
row["object_label"], sack_count, box_count
),
"count": row["count"],
"sack_count": sack_count,
"box_count": box_count,
"plate": row["plate"] or None,
"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(SUM(total_count), 0) as total_count,
COALESCE(SUM(total_batches), 0) as total_batches,
COALESCE(SUM(sack_count), 0) as sack_count,
COALESCE(SUM(box_count), 0) as box_count
FROM daily_summaries
WHERE counting_date = ?
""",
(today,),
)
today_row = cur.fetchone()
yesterday = (datetime.strptime(today, "%Y-%m-%d").date() - timedelta(days=1)).isoformat()
cur.execute(
"""
SELECT COALESCE(SUM(total_count), 0) as total_count,
COALESCE(SUM(total_batches), 0) as total_batches,
COALESCE(SUM(sack_count), 0) as sack_count,
COALESCE(SUM(box_count), 0) as box_count
FROM daily_summaries
WHERE counting_date = ?
""",
(yesterday,),
)
yesterday_row = cur.fetchone()
cur.execute(
"""
SELECT COALESCE(SUM(total_count), 0) as grand_total,
COALESCE(SUM(total_batches), 0) as grand_batches,
COALESCE(SUM(sack_count), 0) as sack_count,
COALESCE(SUM(box_count), 0) as box_count,
COUNT(DISTINCT counting_date) as total_days
FROM daily_summaries
"""
)
all_time = cur.fetchone()
cur.execute(
"""
SELECT ROUND(AVG(day_total), 1) as avg_per_day
FROM (
SELECT SUM(total_count) as day_total
FROM daily_summaries
GROUP BY counting_date
)
"""
)
avg = cur.fetchone()
cur.execute(
"""
SELECT counting_date, SUM(total_count) as total_count
FROM daily_summaries
GROUP BY counting_date
ORDER BY total_count DESC
LIMIT 1
"""
)
best = cur.fetchone()
conn.close()
return jsonify(
{
"today": {
"date": today,
"total_count": today_row["total_count"] if today_row else 0,
"total_batches": today_row["total_batches"] if today_row else 0,
"count": today_row["total_count"] if today_row else 0,
"sack_count": today_row["sack_count"] if today_row else 0,
"box_count": today_row["box_count"] if today_row else 0,
},
"yesterday": {
"date": yesterday,
"total_count": yesterday_row["total_count"] if yesterday_row else 0,
"total_batches": yesterday_row["total_batches"] if yesterday_row else 0,
"count": yesterday_row["total_count"] if yesterday_row else 0,
"sack_count": yesterday_row["sack_count"] if yesterday_row else 0,
"box_count": yesterday_row["box_count"] if yesterday_row else 0,
},
"all_time": {
"grand_total": all_time["grand_total"],
"grand_batches": all_time["grand_batches"],
"total_days": all_time["total_days"],
"count": all_time["grand_total"],
"sack_count": all_time["sack_count"],
"box_count": all_time["box_count"],
},
"average_per_day": avg["avg_per_day"] or 0,
"best_day": {
"date": best["counting_date"] if best else None,
"count": best["total_count"] if best else 0,
},
}
)
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}, "yesterday": {"date": "", "total_count": 0, "total_batches": 0}, "all_time": {"grand_total": 0, "grand_batches": 0, "total_days": 0}, "average_per_day": 0, "best_day": {"date": None, "count": 0}}), 200
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/daily-data")
def api_daily_data():
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,
SUM(total_count) as total_count,
SUM(total_batches) as total_batches,
ROUND(CAST(SUM(total_count) AS FLOAT) / SUM(total_batches), 1) as avg_per_batch
FROM daily_summaries
WHERE counting_date >= ?
GROUP BY 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 as e:
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, object_label, count, sack_count, box_count, plate, start_time, end_time,
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
FROM batches
WHERE counting_date = ?
ORDER BY batch_number ASC
""",
(date,),
)
batches = []
total_duration = 0
for row in cur.fetchall():
duration = row["duration_minutes"] or 0
total_duration += duration
sack_count, box_count = _separate_counts(
row["object_label"], row["count"], row["sack_count"], row["box_count"]
)
batches.append(
{
"batch_number": row["batch_number"],
"object_label": _resolve_batch_label(
row["object_label"], sack_count, box_count
),
"count": row["count"],
"sack_count": sack_count,
"box_count": box_count,
"plate": row["plate"] or None,
"start_time": row["start_time"],
"end_time": row["end_time"],
"duration_minutes": duration,
}
)
cur.execute(
"""
SELECT COALESCE(SUM(total_count), 0) as total_count,
COALESCE(SUM(total_batches), 0) as total_batches,
COALESCE(SUM(sack_count), 0) as sack_count,
COALESCE(SUM(box_count), 0) as box_count
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,
"sack_count": summary["sack_count"] if summary else 0,
"box_count": summary["box_count"] 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, "sack_count": 0, "box_count": 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, object_label, count, sack_count, box_count,
plate, start_time, end_time,
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():
sack_count, box_count = _separate_counts(
row["object_label"], row["count"], row["sack_count"], row["box_count"]
)
batches.append(
{
"date": row["counting_date"],
"batch_number": row["batch_number"],
"object_label": _resolve_batch_label(
row["object_label"], sack_count, box_count
),
"count": row["count"],
"sack_count": sack_count,
"box_count": box_count,
"plate": row["plate"] or None,
"start_time": row["start_time"],
"end_time": row["end_time"],
"duration_minutes": row["duration_minutes"] or 0,
}
)
conn.close()
return jsonify(batches)
except sqlite3.OperationalError as e:
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,
SUM(total_count) as total_count,
SUM(total_batches) as total_batches
FROM daily_summaries
GROUP BY counting_date
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 as e:
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):
header_font = Font(bold=True, color="FFFFFF", size=11)
header_fill = PatternFill(start_color="2F5496", end_color="2F5496", fill_type="solid")
thin_border = Border(
left=Side(style="thin"), right=Side(style="thin"),
top=Side(style="thin"), bottom=Side(style="thin"),
)
for col_idx, (col_letter, text) in enumerate(cols, 1):
cell = ws.cell(row=1, column=col_idx, value=text)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
ws.freeze_panes = "A2"
def _auto_width(ws):
for col in ws.columns:
max_len = 0
col_letter = col[0].column_letter
for cell in col:
if cell.value is not None:
max_len = max(max_len, len(str(cell.value)))
ws.column_dimensions[col_letter].width = max_len + 4
@app.route("/api/export-daily-csv")
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, object_label, count, sack_count, box_count,
plate, 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, 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
wb = Workbook()
ws = wb.active
ws.title = "Batch Details"
_style_header(ws, [("A", "Date"), ("B", "Batch #"), ("C", "Plate"), ("D", "Type"), ("E", "Sack"), ("F", "Box"), ("G", "Total"), ("H", "Start Time"), ("I", "End Time"), ("J", "Duration (min)")])
for r_idx, row in enumerate(rows, 2):
sack_count, box_count = _separate_counts(
row["object_label"], row["count"], row["sack_count"], row["box_count"]
)
ws.cell(row=r_idx, column=1, value=row["counting_date"])
ws.cell(row=r_idx, column=2, value=row["batch_number"])
ws.cell(row=r_idx, column=3, value=row["plate"] or "-")
ws.cell(row=r_idx, column=4, value=_resolve_batch_label(row["object_label"], sack_count, box_count).upper())
ws.cell(row=r_idx, column=5, value=sack_count)
ws.cell(row=r_idx, column=6, value=box_count)
ws.cell(row=r_idx, column=7, value=row["count"])
ws.cell(row=r_idx, column=8, value=row["start_time"])
ws.cell(row=r_idx, column=9, value=row["end_time"])
ws.cell(row=r_idx, column=10, value=row["duration_minutes"] or 0)
_auto_width(ws)
filename = f"{SITE_NAME}_daily_records_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
return _excel_response(wb, filename)
@app.route("/api/export-day-csv/<date>")
def export_day_xlsx(date):
try:
conn = get_db()
cur = conn.cursor()
cur.execute(
"""
SELECT batch_number, object_label, count, sack_count, box_count, plate, start_time, end_time,
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
FROM batches
WHERE counting_date = ?
ORDER BY batch_number 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
wb = Workbook()
ws = wb.active
ws.title = f"Day {date}"
_style_header(ws, [("A", "Batch Number"), ("B", "Plate"), ("C", "Type"), ("D", "Sack"), ("E", "Box"), ("F", "Total"), ("G", "Start Time"), ("H", "End Time"), ("I", "Duration (min)")])
for r_idx, row in enumerate(rows, 2):
sack_count, box_count = _separate_counts(
row["object_label"], row["count"], row["sack_count"], row["box_count"]
)
ws.cell(row=r_idx, column=1, value=row["batch_number"])
ws.cell(row=r_idx, column=2, value=row["plate"] or "-")
ws.cell(row=r_idx, column=3, value=_resolve_batch_label(row["object_label"], sack_count, box_count).upper())
ws.cell(row=r_idx, column=4, value=sack_count)
ws.cell(row=r_idx, column=5, value=box_count)
ws.cell(row=r_idx, column=6, value=row["count"])
ws.cell(row=r_idx, column=7, value=row["start_time"])
ws.cell(row=r_idx, column=8, value=row["end_time"])
ws.cell(row=r_idx, column=9, value=row["duration_minutes"] or 0)
_auto_width(ws)
filename = f"{SITE_NAME}_day_detail_{date}.xlsx"
return _excel_response(wb, filename)
if __name__ == "__main__":
WSGIRequestHandler.protocol_version = "HTTP/1.1"
print(f"RKNN counter dashboard at http://{DASHBOARD_HOST}:{DASHBOARD_PORT}")
print(f"DB: {DB_PATH}")
print(f"State: {CURRENT_BATCH_PATH}")
app.run(host=DASHBOARD_HOST, port=DASHBOARD_PORT, debug=FLASK_DEBUG)