forked from dsutanto/chicken-counting-sukawarna-det
1043 lines
43 KiB
Python
1043 lines
43 KiB
Python
#!/usr/bin/env python3
|
|
"""Live dashboard for chicken-counter pipeline."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import mimetypes
|
|
import os
|
|
import re
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
from datetime import datetime, timezone
|
|
from http.server import HTTPServer, SimpleHTTPRequestHandler
|
|
from pathlib import Path
|
|
from socketserver import ThreadingMixIn
|
|
from urllib.parse import parse_qs, unquote, urlparse
|
|
|
|
from chicken_counter.discovery import (
|
|
DEFAULT_VIDEOS_ROOT,
|
|
discover_all_mortality_dirs,
|
|
discover_farm_structure,
|
|
get_coop_for_location,
|
|
)
|
|
from chicken_counter.mortality import (
|
|
DEFAULT_CONFIG_PATH,
|
|
capture_camera_snapshot,
|
|
get_camera_source_for_coop,
|
|
load_mortality_config,
|
|
run_mortality_count,
|
|
)
|
|
|
|
|
|
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
|
|
daemon_threads = True
|
|
|
|
|
|
DEFAULT_SHM_DIR = "/dev/shm"
|
|
DEFAULT_PORT = 8080
|
|
TEMPLATE_DIR = Path(__file__).resolve().parent / "templates"
|
|
|
|
_thread_local = threading.local()
|
|
_db_lock = threading.Lock()
|
|
_config_write_lock = threading.Lock()
|
|
_db_path = ""
|
|
_mortality_dirs: list[Path] = []
|
|
_mortality_cache_lock = threading.Lock()
|
|
_mortality_reports_cache: list[Path] = []
|
|
_mortality_reports_mtime: float = 0.0
|
|
_mortality_image_cache: dict[str, Path] = {}
|
|
_MORTALITY_CACHE_TTL: float = 15.0 # seconds
|
|
|
|
|
|
def _load_initial_cycle_start_date() -> str:
|
|
"""Read cycle_start_date from configs/cycle7_batch_optimized.yaml if available."""
|
|
cfg_path = Path(__file__).resolve().parent / "configs" / "cycle7_batch_optimized.yaml"
|
|
if cfg_path.exists():
|
|
content = cfg_path.read_text(encoding="utf-8")
|
|
match = re.search(r"^\s*cycle_start_date:\s*['\"]?([^'\"\s#]+)['\"]?", content, re.MULTILINE)
|
|
if match:
|
|
return match.group(1).strip()
|
|
return "2026-05-22"
|
|
|
|
|
|
_cycle_start_date: str = _load_initial_cycle_start_date()
|
|
|
|
|
|
def _persist_cycle_start_date(new_date: str) -> bool:
|
|
"""Update in-memory cycle_start_date and save to config YAML files atomically."""
|
|
global _cycle_start_date
|
|
updated_any = False
|
|
with _config_write_lock:
|
|
_cycle_start_date = new_date
|
|
for cfg_name in ("cycle7_batch_optimized.yaml", "cycle7_batch.yaml"):
|
|
cfg_path = Path(__file__).resolve().parent / "configs" / cfg_name
|
|
if cfg_path.exists():
|
|
try:
|
|
content = cfg_path.read_text(encoding="utf-8")
|
|
pattern = r"^([ \t]*cycle_start_date:[ \t]*)(?:['\"]?)([^'\"\r\n#]+)(?:['\"]?)([ \t]*(?:#.*)?)$"
|
|
|
|
def replacer(match: re.Match) -> str:
|
|
prefix = match.group(1)
|
|
comment = match.group(3) or ""
|
|
if comment and not comment.startswith(" "):
|
|
comment = f" {comment.lstrip()}"
|
|
if not comment.startswith(" "):
|
|
comment = f" {comment}"
|
|
return f'{prefix}"{new_date}"{comment}'
|
|
|
|
new_content, count = re.subn(pattern, replacer, content, count=1, flags=re.MULTILINE)
|
|
if count > 0:
|
|
tmp_path = cfg_path.with_suffix(f".tmp.{os.getpid()}")
|
|
tmp_path.write_text(new_content, encoding="utf-8")
|
|
os.replace(tmp_path, cfg_path)
|
|
updated_any = True
|
|
except Exception as err:
|
|
print(f"[dashboard] ⚠️ Error atomically updating {cfg_name}: {err}")
|
|
print(f"[dashboard] 📅 Updated cycle_start_date to: {new_date} (persisted in configs: {updated_any})")
|
|
return updated_any
|
|
|
|
|
|
def _calc_cycle_info(target_date_str: str) -> dict:
|
|
if not _cycle_start_date or not target_date_str:
|
|
return {}
|
|
try:
|
|
from datetime import date as date_type
|
|
start_d = date_type.fromisoformat(str(_cycle_start_date))
|
|
run_d = date_type.fromisoformat(str(target_date_str))
|
|
c_day = (run_d - start_d).days
|
|
stage = "early_cycle" if 0 <= c_day <= 15 else ("mid_cycle" if c_day >= 16 else "pre_cycle")
|
|
return {"cycle_day": c_day, "stage": stage}
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def _get_db():
|
|
if not _db_path:
|
|
return None
|
|
conn = getattr(_thread_local, "conn", None)
|
|
if conn is None:
|
|
conn = sqlite3.connect(_db_path, timeout=30.0)
|
|
conn.row_factory = sqlite3.Row
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
conn.execute("PRAGMA busy_timeout=5000")
|
|
conn.execute("PRAGMA cache_size=-8000")
|
|
_thread_local.conn = conn
|
|
return conn
|
|
|
|
|
|
def _init_db(db_path: str) -> None:
|
|
conn = sqlite3.connect(db_path)
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
conn.execute("""CREATE TABLE IF NOT EXISTS batch_runs (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
date TEXT NOT NULL, location TEXT NOT NULL, camera_id TEXT NOT NULL,
|
|
total_entered INTEGER NOT NULL DEFAULT 0,
|
|
frames_processed INTEGER NOT NULL DEFAULT 0,
|
|
elapsed_seconds REAL NOT NULL DEFAULT 0.0,
|
|
stopped_reason TEXT NOT NULL DEFAULT '',
|
|
source_video TEXT NOT NULL DEFAULT '',
|
|
generated_at TEXT NOT NULL DEFAULT '',
|
|
UNIQUE(date, location, camera_id))""")
|
|
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_date ON batch_runs (date)")
|
|
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_camera ON batch_runs (camera_id)")
|
|
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_location ON batch_runs (location)")
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
|
|
def _discover_cameras(shm_dir):
|
|
shm = Path(shm_dir)
|
|
cameras = []
|
|
if shm.is_dir():
|
|
for entry in sorted(shm.iterdir()):
|
|
if entry.is_dir() and entry.name.startswith("chicken_counter_"):
|
|
cameras.append(entry.name[len("chicken_counter_"):])
|
|
return cameras
|
|
|
|
|
|
def _parse_multipart(rfile, headers) -> tuple[dict[str, str], list[tuple[str, bytes]]]:
|
|
"""Parse multipart/form-data payload into fields dict and list of (filename, file_bytes)."""
|
|
import email
|
|
content_type = headers.get("content-type", "")
|
|
content_length = int(headers.get("content-length", 0))
|
|
if not content_length:
|
|
return {}, []
|
|
|
|
raw_data = rfile.read(content_length)
|
|
msg_bytes = b"Content-Type: " + content_type.encode("utf-8") + b"\r\n\r\n" + raw_data
|
|
msg = email.message_from_bytes(msg_bytes)
|
|
|
|
fields: dict[str, str] = {}
|
|
files: list[tuple[str, bytes]] = []
|
|
|
|
for part in msg.walk():
|
|
cd = part.get("Content-Disposition", "")
|
|
if "form-data" not in cd:
|
|
continue
|
|
name_m = re.search(r'name="([^"]+)"', cd)
|
|
filename_m = re.search(r'filename="([^"]+)"', cd)
|
|
|
|
if filename_m:
|
|
fn = Path(filename_m.group(1)).name
|
|
payload = part.get_payload(decode=True)
|
|
if fn and payload is not None:
|
|
files.append((fn, payload))
|
|
elif name_m:
|
|
val = part.get_payload(decode=True)
|
|
if val is not None:
|
|
fields[name_m.group(1)] = val.decode("utf-8", errors="replace").strip()
|
|
|
|
return fields, files
|
|
|
|
|
|
class DashboardHandler(SimpleHTTPRequestHandler):
|
|
shm_dir = DEFAULT_SHM_DIR
|
|
poll_ms = 1000
|
|
run_date = ""
|
|
|
|
def log_message(self, format, *args):
|
|
pass
|
|
|
|
def do_OPTIONS(self):
|
|
self.send_response(200)
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
|
|
def do_GET(self):
|
|
try:
|
|
self._handle()
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
pass
|
|
|
|
def do_OPTIONS(self):
|
|
self.send_response(200)
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
|
|
def do_POST(self):
|
|
try:
|
|
parsed = urlparse(self.path)
|
|
path = unquote(parsed.path)
|
|
if path == "/api/config/cycle_start_date":
|
|
self._handle_set_cycle_start_date()
|
|
return
|
|
if path == "/api/mortality/upload":
|
|
self._handle_mortality_upload()
|
|
return
|
|
if path == "/api/mortality/capture":
|
|
self._handle_mortality_capture()
|
|
return
|
|
if path == "/api/mortality/scan":
|
|
self._handle_mortality_scan()
|
|
return
|
|
self._send_error(404)
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
pass
|
|
except Exception as err:
|
|
self._send_json({"status": "error", "message": str(err)}, status_code=500)
|
|
|
|
def _handle_mortality_capture(self):
|
|
content_type = self.headers.get("content-type", "")
|
|
coop = "K1"
|
|
date_str = datetime.now().strftime("%Y-%m-%d")
|
|
source = None
|
|
conf = None
|
|
two_pass = False
|
|
|
|
if "multipart/form-data" in content_type:
|
|
fields, _ = _parse_multipart(self.rfile, self.headers)
|
|
coop = fields.get("coop", "").strip() or "K1"
|
|
date_str = fields.get("date", "").strip() or date_str
|
|
source = fields.get("source", "").strip() or None
|
|
if fields.get("conf"):
|
|
conf = float(fields.get("conf"))
|
|
two_pass = fields.get("two_pass", "false").lower() in ("true", "1", "yes")
|
|
elif "application/json" in content_type:
|
|
length = int(self.headers.get("content-length", 0))
|
|
body = self.rfile.read(length).decode("utf-8") if length > 0 else "{}"
|
|
try:
|
|
payload = json.loads(body)
|
|
coop = payload.get("coop", "").strip() or "K1"
|
|
date_str = payload.get("date", "").strip() or date_str
|
|
source = payload.get("source", "").strip() or None
|
|
if payload.get("conf"):
|
|
conf = float(payload.get("conf"))
|
|
two_pass = bool(payload.get("two_pass", False))
|
|
except Exception:
|
|
pass
|
|
else:
|
|
parsed = urlparse(self.path)
|
|
q = parse_qs(parsed.query)
|
|
if "coop" in q and q["coop"]:
|
|
coop = q["coop"][0].strip()
|
|
if "date" in q and q["date"]:
|
|
date_str = q["date"][0].strip()
|
|
if "source" in q and q["source"]:
|
|
source = q["source"][0].strip()
|
|
|
|
cam_source = source or get_camera_source_for_coop(coop)
|
|
if not cam_source:
|
|
self._send_json({
|
|
"status": "error",
|
|
"message": f"No stationary camera configured for Coop {coop}. Please set camera RTSP/device in configs/mortality_config.yaml.",
|
|
"coop": coop,
|
|
}, status_code=400)
|
|
return
|
|
|
|
print(f"[dashboard] 📷 Grabbing snapshot from stationary camera ({cam_source}) for Coop {coop} ({date_str})...")
|
|
frame = capture_camera_snapshot(cam_source)
|
|
if frame is None:
|
|
self._send_json({
|
|
"status": "error",
|
|
"message": f"Failed to connect or capture frame from camera: {cam_source}",
|
|
"coop": coop,
|
|
"camera_source": str(cam_source),
|
|
}, status_code=502)
|
|
return
|
|
|
|
target_dir = DEFAULT_VIDEOS_ROOT / "cycle7" / coop / "mortality" / date_str
|
|
target_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
existing_captures = list(target_dir.glob("capture_*.jpg"))
|
|
next_num = len(existing_captures) + 1
|
|
timestamp_str = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
filename = f"capture_{next_num:02d}_{timestamp_str}.jpg"
|
|
dest_path = target_dir / filename
|
|
|
|
import cv2
|
|
cv2.imwrite(str(dest_path), frame)
|
|
print(f"[dashboard] 💾 Saved camera capture #{next_num}: {dest_path}")
|
|
|
|
try:
|
|
report_data = run_mortality_count(
|
|
input_path=target_dir,
|
|
date=date_str,
|
|
coop=coop,
|
|
conf_threshold=conf,
|
|
two_pass=two_pass,
|
|
)
|
|
with _mortality_cache_lock:
|
|
global _mortality_reports_mtime
|
|
_mortality_reports_mtime = 0.0
|
|
|
|
latest_det = next((r for r in report_data.get("results", []) if r.get("input_image") == filename), None)
|
|
|
|
self._send_json({
|
|
"status": "success",
|
|
"message": f"Captured photo #{next_num} from {coop} camera ({latest_det.get('count', 0) if latest_det else 0} carcasses)",
|
|
"coop": coop,
|
|
"date": date_str,
|
|
"camera_source": str(cam_source),
|
|
"captured_file": filename,
|
|
"batch_count": latest_det.get("count", 0) if latest_det else 0,
|
|
"total_images": report_data.get("total_images", next_num),
|
|
"total_mortality_count": report_data.get("total_mortality_count", 0),
|
|
"results": report_data.get("results", []),
|
|
"report": report_data,
|
|
})
|
|
except Exception as e:
|
|
self._send_json({
|
|
"status": "error",
|
|
"message": f"Detection error on capture: {str(e)}",
|
|
"coop": coop,
|
|
"captured_file": filename,
|
|
}, status_code=500)
|
|
|
|
def _handle_mortality_upload(self):
|
|
fields, files = _parse_multipart(self.rfile, self.headers)
|
|
if not files:
|
|
self._send_json({"status": "error", "message": "No image files uploaded."}, status_code=400)
|
|
return
|
|
|
|
coop = fields.get("coop", "").strip() or "K1"
|
|
date_str = fields.get("date", "").strip() or datetime.now().strftime("%Y-%m-%d")
|
|
conf_str = fields.get("conf", "").strip()
|
|
conf = float(conf_str) if conf_str else None
|
|
two_pass = fields.get("two_pass", "false").lower() in ("true", "1", "yes")
|
|
|
|
# Target directory: VIDEOS/cycle7/<coop>/mortality/<date>/
|
|
target_dir = DEFAULT_VIDEOS_ROOT / "cycle7" / coop / "mortality" / date_str
|
|
target_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
saved_files = []
|
|
for orig_name, file_bytes in files:
|
|
clean_name = re.sub(r"[^a-zA-Z0-9_.-]", "_", Path(orig_name).name)
|
|
if not clean_name:
|
|
clean_name = f"scan_{int(time.time()*1000)}.jpg"
|
|
dest = target_dir / clean_name
|
|
dest.write_bytes(file_bytes)
|
|
saved_files.append(dest)
|
|
|
|
print(f"[dashboard] 📥 Received {len(saved_files)} mortality photo(s) for Coop {coop} ({date_str}) in {target_dir}")
|
|
|
|
try:
|
|
report_data = run_mortality_count(
|
|
input_path=target_dir,
|
|
date=date_str,
|
|
coop=coop,
|
|
conf_threshold=conf,
|
|
two_pass=two_pass,
|
|
)
|
|
# Invalidate cached report paths to reflect new report immediately
|
|
with _mortality_cache_lock:
|
|
global _mortality_reports_mtime
|
|
_mortality_reports_mtime = 0.0
|
|
|
|
self._send_json({
|
|
"status": "success",
|
|
"message": f"Processed {len(saved_files)} image(s) for {coop}",
|
|
"coop": coop,
|
|
"date": date_str,
|
|
"total_images": report_data.get("total_images", len(saved_files)),
|
|
"total_mortality_count": report_data.get("total_mortality_count", 0),
|
|
"results": report_data.get("results", []),
|
|
"report": report_data,
|
|
})
|
|
except Exception as e:
|
|
self._send_json({
|
|
"status": "error",
|
|
"message": f"Detection error: {str(e)}",
|
|
"coop": coop,
|
|
"saved_files": [f.name for f in saved_files],
|
|
}, status_code=500)
|
|
|
|
def _handle_mortality_scan(self):
|
|
length = int(self.headers.get("content-length", 0))
|
|
body = self.rfile.read(length).decode("utf-8") if length > 0 else "{}"
|
|
try:
|
|
payload = json.loads(body)
|
|
except Exception:
|
|
payload = {}
|
|
|
|
coop = payload.get("coop", "K1").strip()
|
|
date_str = payload.get("date", "").strip() or datetime.now().strftime("%Y-%m-%d")
|
|
|
|
target_dir = DEFAULT_VIDEOS_ROOT / "cycle7" / coop / "mortality"
|
|
if (target_dir / date_str).is_dir():
|
|
target_dir = target_dir / date_str
|
|
|
|
if not target_dir.is_dir():
|
|
self._send_json({"status": "error", "message": f"Mortality directory not found: {target_dir}"}, status_code=404)
|
|
return
|
|
|
|
report_data = run_mortality_count(input_path=target_dir, date=date_str, coop=coop)
|
|
with _mortality_cache_lock:
|
|
global _mortality_reports_mtime
|
|
_mortality_reports_mtime = 0.0
|
|
self._send_json({"status": "success", "report": report_data})
|
|
|
|
def _handle(self):
|
|
parsed = urlparse(self.path)
|
|
path = unquote(parsed.path)
|
|
|
|
if path == "/":
|
|
self._serve_html()
|
|
return
|
|
|
|
if path.startswith("/stream/"):
|
|
self._handle_stream(path)
|
|
return
|
|
|
|
if path in ("/api/status", "/api/system/status"):
|
|
self._handle_status()
|
|
return
|
|
|
|
if path == "/api/cameras":
|
|
self._send_json({"cameras": _discover_cameras(self.shm_dir)})
|
|
return
|
|
|
|
if path == "/api/config/cycle_start_date":
|
|
query = parse_qs(parsed.query)
|
|
if "set" in query and query["set"]:
|
|
new_date = query["set"][0].strip()
|
|
try:
|
|
from datetime import date as date_type
|
|
date_type.fromisoformat(new_date)
|
|
persisted = _persist_cycle_start_date(new_date)
|
|
self._send_json({
|
|
"status": "ok",
|
|
"message": f"Cycle start date successfully set to {new_date}",
|
|
"cycle_start_date": _cycle_start_date,
|
|
"persisted": persisted,
|
|
})
|
|
return
|
|
except ValueError as err:
|
|
self._send_json({"error": f"Invalid date format (expected YYYY-MM-DD): {err}"}, status_code=400)
|
|
return
|
|
self._send_json({"cycle_start_date": _cycle_start_date})
|
|
return
|
|
|
|
if path == "/api/config":
|
|
self._send_json({
|
|
"cycle_start_date": _cycle_start_date,
|
|
"shm_dir": self.shm_dir,
|
|
"db_path": _db_path,
|
|
})
|
|
return
|
|
|
|
if path.startswith("/api/db/"):
|
|
self._handle_db(path)
|
|
return
|
|
|
|
if path.startswith("/api/mortality"):
|
|
self._handle_mortality(path)
|
|
return
|
|
|
|
if path.startswith("/shm/"):
|
|
self._handle_shm(path)
|
|
return
|
|
|
|
self._send_error(404)
|
|
|
|
def _handle_set_cycle_start_date(self):
|
|
content_length = int(self.headers.get("Content-Length", 0))
|
|
if content_length > 0:
|
|
body = self.rfile.read(content_length).decode("utf-8")
|
|
try:
|
|
data = json.loads(body)
|
|
new_date = str(data.get("cycle_start_date", "")).strip()
|
|
if new_date:
|
|
from datetime import date as date_type
|
|
date_type.fromisoformat(new_date)
|
|
persisted = _persist_cycle_start_date(new_date)
|
|
self._send_json({
|
|
"status": "ok",
|
|
"message": f"Cycle start date successfully set to {new_date}",
|
|
"cycle_start_date": _cycle_start_date,
|
|
"persisted": persisted,
|
|
})
|
|
return
|
|
else:
|
|
self._send_json({"error": "Missing 'cycle_start_date' in request body"}, status_code=400)
|
|
return
|
|
except ValueError as err:
|
|
self._send_json({"error": f"Invalid date format (expected YYYY-MM-DD): {err}"}, status_code=400)
|
|
return
|
|
except Exception as err:
|
|
self._send_json({"error": str(err)}, status_code=400)
|
|
return
|
|
self._send_json({"error": "Empty request body"}, status_code=400)
|
|
|
|
def _handle_status(self):
|
|
cams = _discover_cameras(self.shm_dir)
|
|
now = time.time()
|
|
active_streams = []
|
|
for cam in cams:
|
|
stat_file = Path(self.shm_dir) / f"chicken_counter_{cam}" / "stats.json"
|
|
if stat_file.is_file() and (now - stat_file.stat().st_mtime) < 15.0:
|
|
active_streams.append(cam)
|
|
|
|
is_running = len(active_streams) > 0
|
|
conn = _get_db()
|
|
latest_date = None
|
|
total_chickens = 0
|
|
if conn:
|
|
row = conn.execute("SELECT MAX(date) AS latest_date, SUM(total_entered) AS total FROM batch_runs").fetchone()
|
|
if row:
|
|
latest_date = row["latest_date"]
|
|
total_chickens = row["total"] or 0
|
|
|
|
self._send_json({
|
|
"status": "running" if is_running else "idle",
|
|
"is_counting_active": is_running,
|
|
"active_cameras": active_streams,
|
|
"latest_counted_date": latest_date,
|
|
"total_chickens_all_time": total_chickens,
|
|
"cycle_start_date": _cycle_start_date,
|
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
})
|
|
|
|
def _handle_stream(self, path):
|
|
cam_id = path[len("/stream/"):]
|
|
frame_path = Path(self.shm_dir) / f"chicken_counter_{cam_id}" / "frame.jpg"
|
|
if not frame_path.exists():
|
|
self._send_error(404)
|
|
return
|
|
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=frame")
|
|
self.send_header("Cache-Control", "no-cache")
|
|
self.end_headers()
|
|
|
|
last_mtime = 0.0
|
|
last_write_time = time.time()
|
|
keepalive_interval = 3.0
|
|
|
|
try:
|
|
while True:
|
|
now = time.time()
|
|
frame_written = False
|
|
try:
|
|
mtime = frame_path.stat().st_mtime
|
|
if mtime != last_mtime:
|
|
last_mtime = mtime
|
|
data = frame_path.read_bytes()
|
|
self.wfile.write(
|
|
b"--frame\r\n"
|
|
b"Content-Type: image/jpeg\r\n"
|
|
b"Content-Length: " + str(len(data)).encode() + b"\r\n\r\n" +
|
|
data + b"\r\n"
|
|
)
|
|
self.wfile.flush()
|
|
last_write_time = now
|
|
frame_written = True
|
|
except (FileNotFoundError, OSError):
|
|
pass
|
|
|
|
# If idle (no new frames), send a lightweight keepalive ping to detect disconnected clients
|
|
if not frame_written and (now - last_write_time) >= keepalive_interval:
|
|
self.wfile.write(b"--frame\r\n\r\n")
|
|
self.wfile.flush()
|
|
last_write_time = now
|
|
|
|
time.sleep(0.1)
|
|
except (BrokenPipeError, ConnectionResetError, OSError):
|
|
pass
|
|
|
|
def _handle_shm(self, path):
|
|
rel = path[len("/shm/"):]
|
|
parts = rel.split("/", 1)
|
|
if len(parts) < 2:
|
|
self._send_error(404)
|
|
return
|
|
|
|
cam_id = parts[0]
|
|
file = parts[1]
|
|
fpath = Path(self.shm_dir) / f"chicken_counter_{cam_id}" / file
|
|
|
|
if str(fpath.resolve()).startswith(str(Path(self.shm_dir).resolve())):
|
|
if fpath.exists():
|
|
ct = "image/jpeg" if file.endswith(".jpg") else "application/json"
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", ct)
|
|
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
self.end_headers()
|
|
self.wfile.write(fpath.read_bytes())
|
|
return
|
|
self._send_error(404)
|
|
|
|
def _handle_db(self, path):
|
|
conn = _get_db()
|
|
if not conn:
|
|
self._send_json({})
|
|
return
|
|
|
|
if path == "/api/db/summary":
|
|
row = conn.execute("SELECT COUNT(DISTINCT date) AS days, COUNT(DISTINCT location) AS locations, COUNT(*) AS total_runs, SUM(total_entered) AS total_chickens, ROUND(SUM(elapsed_seconds)/3600.0,1) AS total_hours FROM batch_runs").fetchone()
|
|
d = dict(row)
|
|
d["cycle_start_date"] = _cycle_start_date
|
|
self._send_json(d)
|
|
return
|
|
|
|
if path == "/api/db/history":
|
|
rows = conn.execute("SELECT date, location, COUNT(*) AS cams, SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs GROUP BY date, location ORDER BY date DESC, location LIMIT 50").fetchall()
|
|
history = []
|
|
for r in rows:
|
|
d = dict(r)
|
|
d.update(_calc_cycle_info(d["date"]))
|
|
history.append(d)
|
|
self._send_json(history)
|
|
return
|
|
|
|
# /api/db/date/<date>
|
|
prefix = "/api/db/date/"
|
|
if path.startswith(prefix):
|
|
date = path[len(prefix):]
|
|
cameras = conn.execute("SELECT camera_id, total_entered, frames_processed, ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason, source_video, location FROM batch_runs WHERE date=? ORDER BY camera_id", (date,)).fetchall()
|
|
total = conn.execute("SELECT SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs WHERE date=?", (date,)).fetchone()
|
|
res = {"date": date, "total": dict(total), "cameras": [dict(r) for r in cameras]}
|
|
res.update(_calc_cycle_info(date))
|
|
self._send_json(res)
|
|
return
|
|
|
|
# /api/db/camera/<id>
|
|
prefix = "/api/db/camera/"
|
|
if path.startswith(prefix):
|
|
cam_id = path[len(prefix):]
|
|
rows = conn.execute("SELECT date, location, total_entered, frames_processed, ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason FROM batch_runs WHERE camera_id=? ORDER BY date DESC LIMIT 50", (cam_id,)).fetchall()
|
|
self._send_json([dict(r) for r in rows])
|
|
return
|
|
|
|
# /api/db/location/<name>
|
|
prefix = "/api/db/location/"
|
|
if path.startswith(prefix):
|
|
loc = path[len(prefix):]
|
|
history = conn.execute("SELECT date, GROUP_CONCAT(camera_id,', ') AS cameras, SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs WHERE location=? GROUP BY date ORDER BY date DESC LIMIT 50", (loc,)).fetchall()
|
|
summary = conn.execute("SELECT COUNT(DISTINCT date) AS days, SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/3600.0,1) AS hours FROM batch_runs WHERE location=?", (loc,)).fetchone()
|
|
self._send_json({"location": loc, "summary": dict(summary), "history": [dict(r) for r in history]})
|
|
return
|
|
|
|
self._send_json({})
|
|
|
|
def _handle_mortality(self, path: str) -> None:
|
|
"""Serve mortality detection results.
|
|
|
|
GET /api/mortality/coops - Summary list of all detected coops with mortality data.
|
|
GET /api/mortality/coop/<coop_id> - Mortality reports filtered by specific coop (e.g. K1).
|
|
GET /api/mortality/latest - Most recent mortality_report.json across all dirs.
|
|
GET /api/mortality/history - List of all mortality reports found (newest first).
|
|
GET /api/mortality/date/<date> - Mortality breakdown for a specific date (YYYY-MM-DD).
|
|
GET /api/mortality/image/<name> - Serve an output_*.jpg annotated image by filename.
|
|
"""
|
|
global _mortality_dirs
|
|
if not _mortality_dirs:
|
|
_mortality_dirs = list(discover_all_mortality_dirs().values())
|
|
|
|
if not _mortality_dirs:
|
|
self._send_json({"error": "No mortality directory configured or detected. Start dashboard with --mortality-dir."})
|
|
return
|
|
|
|
def _infer_coop_and_floors(data: dict, report_path: Path) -> tuple[str, list[str]]:
|
|
coop = data.get("coop") or data.get("location")
|
|
if not coop:
|
|
for part in reversed(report_path.parts):
|
|
if part != "mortality_report.json" and part.lower() != "mortality" and not re.match(r"^\d{4}-\d{2}-\d{2}$", part):
|
|
coop = get_coop_for_location(part)
|
|
break
|
|
coop = coop or "kandang-atas"
|
|
floors = data.get("covered_floors")
|
|
if not floors:
|
|
farm_struct = discover_farm_structure()
|
|
floors = farm_struct.get_covered_floors(coop)
|
|
return coop, floors
|
|
|
|
def _enrich_report(data: dict, report_path: Path) -> dict:
|
|
coop, floors = _infer_coop_and_floors(data, report_path)
|
|
data["coop"] = coop
|
|
data["location"] = coop
|
|
data["covered_floors"] = floors
|
|
if "total_mortality_count" not in data and "results" in data:
|
|
data["total_mortality_count"] = sum(r.get("count", 0) for r in data["results"])
|
|
for res in data.get("results", []):
|
|
res["coop"] = coop
|
|
res["covered_floors"] = floors
|
|
return data
|
|
|
|
def _find_report_paths(force_refresh: bool = False) -> list[Path]:
|
|
global _mortality_reports_cache, _mortality_reports_mtime, _mortality_image_cache, _mortality_dirs
|
|
now = time.time()
|
|
with _mortality_cache_lock:
|
|
if not force_refresh and (now - _mortality_reports_mtime) < _MORTALITY_CACHE_TTL and _mortality_reports_cache:
|
|
return list(_mortality_reports_cache)
|
|
|
|
if not _mortality_dirs:
|
|
_mortality_dirs = list(discover_all_mortality_dirs().values())
|
|
|
|
found = []
|
|
img_cache: dict[str, Path] = {}
|
|
for mdir in _mortality_dirs:
|
|
p = Path(mdir)
|
|
if p.is_dir():
|
|
for report in p.rglob("mortality_report.json"):
|
|
found.append(report)
|
|
for img in report.parent.glob("output_*.jpg"):
|
|
img_cache[img.name] = img
|
|
for img in report.parent.glob("output_*.png"):
|
|
img_cache[img.name] = img
|
|
|
|
_mortality_reports_cache = found
|
|
_mortality_image_cache = img_cache
|
|
_mortality_reports_mtime = now
|
|
return list(found)
|
|
|
|
def _find_image_path(filename: str) -> Path | None:
|
|
# 1. Fast memory cache lookup (O(1))
|
|
with _mortality_cache_lock:
|
|
if filename in _mortality_image_cache:
|
|
img = _mortality_image_cache[filename]
|
|
if img.is_file():
|
|
return img
|
|
|
|
# 2. Fast check in cached report parent directories
|
|
reports = _find_report_paths()
|
|
for r in reports:
|
|
candidate = r.parent / filename
|
|
if candidate.is_file():
|
|
with _mortality_cache_lock:
|
|
_mortality_image_cache[filename] = candidate
|
|
return candidate
|
|
|
|
# 3. Direct check in base mortality directories
|
|
for mdir in _mortality_dirs:
|
|
candidate = Path(mdir) / filename
|
|
if candidate.is_file():
|
|
with _mortality_cache_lock:
|
|
_mortality_image_cache[filename] = candidate
|
|
return candidate
|
|
|
|
# 4. Fallback search and update index
|
|
for mdir in _mortality_dirs:
|
|
p = Path(mdir)
|
|
if p.is_dir():
|
|
for img_path in p.rglob(filename):
|
|
if img_path.is_file():
|
|
with _mortality_cache_lock:
|
|
_mortality_image_cache[filename] = img_path
|
|
return img_path
|
|
return None
|
|
|
|
# --- /api/mortality/cameras ---
|
|
if path == "/api/mortality/cameras":
|
|
cfg = load_mortality_config(DEFAULT_CONFIG_PATH)
|
|
cameras = cfg.get("cameras", {})
|
|
self._send_json({"cameras": cameras})
|
|
return
|
|
|
|
# --- /api/mortality/camera/preview ---
|
|
if path == "/api/mortality/camera/preview":
|
|
parsed = urlparse(self.path)
|
|
q = parse_qs(parsed.query)
|
|
coop = q.get("coop", ["K1"])[0].strip()
|
|
cam_source = q.get("source", [""])[0].strip() or get_camera_source_for_coop(coop)
|
|
if not cam_source:
|
|
self._send_error(404)
|
|
return
|
|
|
|
frame = capture_camera_snapshot(cam_source, timeout_sec=3.0, warmup_frames=2)
|
|
if frame is None:
|
|
self._send_error(502)
|
|
return
|
|
|
|
import cv2
|
|
ret, buf = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 80])
|
|
if not ret:
|
|
self._send_error(500)
|
|
return
|
|
data = buf.tobytes()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "image/jpeg")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
return
|
|
|
|
# --- /api/mortality/coops ---
|
|
if path == "/api/mortality/coops":
|
|
coops_summary: dict[str, dict] = {}
|
|
for report_path in _find_report_paths():
|
|
try:
|
|
data = json.loads(report_path.read_text(encoding="utf-8"))
|
|
enriched = _enrich_report(data, report_path)
|
|
cid = enriched.get("coop", "unknown")
|
|
if cid not in coops_summary:
|
|
coops_summary[cid] = {
|
|
"coop": cid,
|
|
"covered_floors": enriched.get("covered_floors", [cid]),
|
|
"total_carcasses": 0,
|
|
"total_scans": 0,
|
|
"latest_date": enriched.get("date", ""),
|
|
"latest_count": enriched.get("total_mortality_count", 0),
|
|
}
|
|
coops_summary[cid]["total_carcasses"] += enriched.get("total_mortality_count", 0)
|
|
coops_summary[cid]["total_scans"] += len(enriched.get("results", []))
|
|
if enriched.get("date", "") >= coops_summary[cid]["latest_date"]:
|
|
coops_summary[cid]["latest_date"] = enriched.get("date", "")
|
|
coops_summary[cid]["latest_count"] = enriched.get("total_mortality_count", 0)
|
|
except (json.JSONDecodeError, OSError):
|
|
pass
|
|
self._send_json(sorted(list(coops_summary.values()), key=lambda x: x["coop"]))
|
|
return
|
|
|
|
# --- /api/mortality/coop/<coop_id> ---
|
|
prefix_coop = "/api/mortality/coop/"
|
|
if path.startswith(prefix_coop):
|
|
target_coop = path[len(prefix_coop):].upper()
|
|
coop_reports = []
|
|
for report_path in _find_report_paths():
|
|
try:
|
|
data = json.loads(report_path.read_text(encoding="utf-8"))
|
|
enriched = _enrich_report(data, report_path)
|
|
if enriched.get("coop", "").upper() == target_coop:
|
|
enriched["_dir"] = str(report_path.parent)
|
|
enriched["_report_mtime"] = report_path.stat().st_mtime
|
|
coop_reports.append(enriched)
|
|
except (json.JSONDecodeError, OSError):
|
|
pass
|
|
coop_reports.sort(key=lambda x: x.get("_report_mtime", 0), reverse=True)
|
|
self._send_json(coop_reports)
|
|
return
|
|
|
|
# --- /api/mortality/history ---
|
|
if path == "/api/mortality/history":
|
|
results = []
|
|
for report_path in _find_report_paths():
|
|
try:
|
|
data = json.loads(report_path.read_text(encoding="utf-8"))
|
|
data["_dir"] = str(report_path.parent)
|
|
data["_report_mtime"] = report_path.stat().st_mtime
|
|
results.append(_enrich_report(data, report_path))
|
|
except (json.JSONDecodeError, OSError):
|
|
pass
|
|
results.sort(key=lambda x: x.get("_report_mtime", 0), reverse=True)
|
|
self._send_json(results)
|
|
return
|
|
|
|
# --- /api/mortality/latest ---
|
|
if path == "/api/mortality/latest":
|
|
latest = None
|
|
latest_mtime = 0.0
|
|
for report_path in _find_report_paths():
|
|
try:
|
|
mtime = report_path.stat().st_mtime
|
|
if mtime > latest_mtime:
|
|
latest_mtime = mtime
|
|
latest = json.loads(report_path.read_text(encoding="utf-8"))
|
|
latest["_dir"] = str(report_path.parent)
|
|
latest = _enrich_report(latest, report_path)
|
|
except (json.JSONDecodeError, OSError):
|
|
pass
|
|
if latest:
|
|
self._send_json(latest)
|
|
else:
|
|
self._send_json({"error": "No mortality report found."})
|
|
return
|
|
|
|
# --- /api/mortality/date/<date> ---
|
|
prefix_date = "/api/mortality/date/"
|
|
if path.startswith(prefix_date):
|
|
target_date = path[len(prefix_date):]
|
|
matched_reports = []
|
|
total_day_carcasses = 0
|
|
total_day_images = 0
|
|
all_results = []
|
|
|
|
for report_path in _find_report_paths():
|
|
try:
|
|
data = json.loads(report_path.read_text(encoding="utf-8"))
|
|
report_date = data.get("date") or time.strftime("%Y-%m-%d", time.localtime(report_path.stat().st_mtime))
|
|
if report_date == target_date or report_path.parent.name == target_date:
|
|
enriched = _enrich_report(data, report_path)
|
|
total_day_carcasses += enriched.get("total_mortality_count", 0)
|
|
total_day_images += enriched.get("total_images", 0)
|
|
all_results.extend(enriched.get("results", []))
|
|
matched_reports.append(enriched)
|
|
except (json.JSONDecodeError, OSError):
|
|
pass
|
|
|
|
self._send_json({
|
|
"date": target_date,
|
|
"total_mortality_count": total_day_carcasses,
|
|
"total_images": total_day_images,
|
|
"reports": matched_reports,
|
|
"results": all_results,
|
|
})
|
|
return
|
|
|
|
# --- /api/mortality/image/<filename> ---
|
|
prefix_img = "/api/mortality/image/"
|
|
if path.startswith(prefix_img):
|
|
raw_name = path[len(prefix_img):]
|
|
filename = Path(raw_name).name # Prevent path traversal attacks
|
|
# Only allow serving output_*.jpg files for security
|
|
if not (filename.startswith("output_") and filename.lower().endswith((".jpg", ".jpeg", ".png"))):
|
|
self._send_error(403)
|
|
return
|
|
img_path = _find_image_path(filename)
|
|
if img_path and img_path.is_file():
|
|
try:
|
|
data = img_path.read_bytes()
|
|
ct = mimetypes.guess_type(filename)[0] or "image/jpeg"
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", ct)
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.send_header("Cache-Control", "no-cache")
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
return
|
|
except (FileNotFoundError, OSError):
|
|
pass
|
|
self._send_error(404)
|
|
return
|
|
|
|
self._send_error(404)
|
|
|
|
def _serve_html(self):
|
|
html_path = TEMPLATE_DIR / "index.html"
|
|
html = html_path.read_text(encoding="utf-8")
|
|
html = html.replace("{{ poll_ms }}", str(self.poll_ms))
|
|
html = html.replace("{{ shm_dir }}", self.shm_dir)
|
|
html = html.replace("{{ date }}", self.run_date or "today")
|
|
html = html.replace("{{ db_path }}", _db_path)
|
|
data = html.encode("utf-8")
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def _send_json(self, obj, status_code=200):
|
|
data = json.dumps(obj).encode("utf-8")
|
|
self.send_response(status_code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def _send_error(self, code):
|
|
self.send_response(code)
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
|
|
|
|
def main():
|
|
global _db_path, _mortality_dirs
|
|
|
|
parser = argparse.ArgumentParser(description="Chicken Counter live dashboard")
|
|
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
|
|
parser.add_argument("--shm-dir", default=DEFAULT_SHM_DIR)
|
|
parser.add_argument("--poll-ms", type=int, default=1000)
|
|
parser.add_argument("--date", default="")
|
|
parser.add_argument("--db", default="db/chicken_counts.db")
|
|
parser.add_argument("--cycle-start-date", default="", help="Start date of cycle (Day 0) in YYYY-MM-DD format.")
|
|
parser.add_argument(
|
|
"--mortality-dir",
|
|
action="append",
|
|
dest="mortality_dirs",
|
|
default=[],
|
|
metavar="DIR",
|
|
help="Directory containing mortality_report.json and output images. Repeatable for multiple dirs.",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
_mortality_dirs = [Path(d).resolve() for d in args.mortality_dirs]
|
|
if args.cycle_start_date:
|
|
global _cycle_start_date
|
|
_cycle_start_date = args.cycle_start_date
|
|
|
|
DashboardHandler.shm_dir = args.shm_dir
|
|
DashboardHandler.poll_ms = args.poll_ms
|
|
DashboardHandler.run_date = args.date
|
|
_db_path = str(Path(args.db).resolve()) if args.db else ""
|
|
|
|
if _db_path:
|
|
_init_db(_db_path)
|
|
|
|
server = ThreadingHTTPServer(("0.0.0.0", args.port), DashboardHandler)
|
|
date_info = f" date={args.date}" if args.date else ""
|
|
print(f"[dashboard] http://0.0.0.0:{args.port} shm={args.shm_dir} db={args.db}{date_info}")
|
|
try:
|
|
server.serve_forever()
|
|
except KeyboardInterrupt:
|
|
print("\n[dashboard] stopped")
|
|
server.server_close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|