- Propagate parent coop (e.g. K1) and floor location (e.g. K1-L1) across feature aggregation, predictions, and curation storage - Add REST API endpoints GET /api/weight/coops and GET /api/weight/coop/<coop_id> - Support multi-coop non-colliding predictions and ?coop= / ?location= filtering - Add dynamic farm root discovery and folder path fallback inference for legacy datasets - Persist FUSED flock weight in SQLite batch_runs table with camera_id='FUSED' - Update GET /api/db/date/<date> to return weight and coop metadata for all cameras - Update ERD.md, CHANGELOG.md, API.md, and CENTRAL_DASHBOARD_INTEGRATION.md - Add comprehensive unit tests in test_weight_estimation.py and test_dashboard_weight_api.py
268 lines
11 KiB
Python
268 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Store batch run results into a SQLite database.
|
|
|
|
Reads the aggregate JSON report written by the batch runner and inserts
|
|
all camera-level + summary data. Safe to run multiple times — uses
|
|
(date, location, camera_id) as the unique key, so re-runs update
|
|
existing rows instead of duplicating.
|
|
|
|
Usage:
|
|
python3 store_results.py /path/to/output/counts_2026-06-10.json --location kandang-atas
|
|
python3 store_results.py /path/to/output/counts_2026-06-10.json --db /var/lib/chickens.db
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sqlite3
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
CREATE_TABLE = """
|
|
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 '',
|
|
cycle_day INTEGER NOT NULL DEFAULT 0,
|
|
area_cm2_median REAL NOT NULL DEFAULT 0.0,
|
|
minor_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
|
major_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
|
predicted_weight_g REAL NOT NULL DEFAULT 0.0,
|
|
gompertz_baseline_g REAL NOT NULL DEFAULT 0.0,
|
|
vision_gain_g REAL NOT NULL DEFAULT 0.0,
|
|
n_weight_samples INTEGER NOT NULL DEFAULT 0,
|
|
rejection_rate REAL NOT NULL DEFAULT 0.0,
|
|
UNIQUE(date, location, camera_id)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_batch_date ON batch_runs (date);
|
|
CREATE INDEX IF NOT EXISTS idx_batch_camera ON batch_runs (camera_id);
|
|
CREATE INDEX IF NOT EXISTS idx_batch_location ON batch_runs (location);
|
|
"""
|
|
|
|
INSERT_SQL = """
|
|
INSERT INTO batch_runs
|
|
(date, location, camera_id, total_entered, frames_processed,
|
|
elapsed_seconds, stopped_reason, source_video, generated_at,
|
|
cycle_day, area_cm2_median, minor_axis_cm_median, major_axis_cm_median,
|
|
predicted_weight_g, gompertz_baseline_g, vision_gain_g, n_weight_samples, rejection_rate)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(date, location, camera_id) DO UPDATE SET
|
|
total_entered = excluded.total_entered,
|
|
frames_processed = excluded.frames_processed,
|
|
elapsed_seconds = excluded.elapsed_seconds,
|
|
stopped_reason = excluded.stopped_reason,
|
|
source_video = excluded.source_video,
|
|
generated_at = excluded.generated_at,
|
|
cycle_day = excluded.cycle_day,
|
|
area_cm2_median = excluded.area_cm2_median,
|
|
minor_axis_cm_median = excluded.minor_axis_cm_median,
|
|
major_axis_cm_median = excluded.major_axis_cm_median,
|
|
predicted_weight_g = excluded.predicted_weight_g,
|
|
gompertz_baseline_g = excluded.gompertz_baseline_g,
|
|
vision_gain_g = excluded.vision_gain_g,
|
|
n_weight_samples = excluded.n_weight_samples,
|
|
rejection_rate = excluded.rejection_rate
|
|
"""
|
|
|
|
SUMMARY_QUERY = """
|
|
SELECT
|
|
date,
|
|
location,
|
|
COUNT(*) AS camera_count,
|
|
SUM(total_entered) AS total_chickens,
|
|
SUM(elapsed_seconds) AS total_seconds,
|
|
ROUND(SUM(elapsed_seconds) / 60.0, 1) AS total_minutes,
|
|
ROUND(AVG(predicted_weight_g), 1) AS avg_pred_weight
|
|
FROM batch_runs
|
|
WHERE date = ? AND location = ?
|
|
GROUP BY date, location
|
|
"""
|
|
|
|
|
|
def migrate_db_schema(conn: sqlite3.Connection) -> None:
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
conn.execute("PRAGMA busy_timeout=60000")
|
|
conn.execute("PRAGMA synchronous=NORMAL")
|
|
conn.executescript(CREATE_TABLE)
|
|
|
|
cursor = conn.execute("PRAGMA table_info(batch_runs)")
|
|
existing_cols = {row[1] for row in cursor.fetchall()}
|
|
new_cols = [
|
|
("cycle_day", "INTEGER NOT NULL DEFAULT 0"),
|
|
("area_cm2_median", "REAL NOT NULL DEFAULT 0.0"),
|
|
("minor_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
|
("major_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
|
("predicted_weight_g", "REAL NOT NULL DEFAULT 0.0"),
|
|
("gompertz_baseline_g", "REAL NOT NULL DEFAULT 0.0"),
|
|
("vision_gain_g", "REAL NOT NULL DEFAULT 0.0"),
|
|
("n_weight_samples", "INTEGER NOT NULL DEFAULT 0"),
|
|
("rejection_rate", "REAL NOT NULL DEFAULT 0.0"),
|
|
]
|
|
for col_name, col_type in new_cols:
|
|
if col_name not in existing_cols:
|
|
try:
|
|
conn.execute(f"ALTER TABLE batch_runs ADD COLUMN {col_name} {col_type}")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def load_companion_weight_data(report_dir: Path, date: str) -> dict[str, dict]:
|
|
"""Load per-camera weight and dimensional metrics from companion prediction files."""
|
|
weight_map: dict[str, dict] = {}
|
|
|
|
# 1. Try predictions_{date}.parquet or .csv
|
|
for ext in (".parquet", ".csv"):
|
|
pred_file = report_dir / f"predictions_{date}{ext}"
|
|
if pred_file.is_file():
|
|
try:
|
|
import pandas as pd
|
|
df = pd.read_parquet(pred_file) if ext == ".parquet" else pd.read_csv(pred_file)
|
|
for _, row in df.iterrows():
|
|
cid = str(row.get("camera_id", ""))
|
|
if cid:
|
|
weight_map[cid] = {
|
|
"cycle_day": int(row.get("cycle_day", 0)),
|
|
"area_cm2_median": float(row.get("area_cm2_median", row.get("median_area_cm2", 0.0))),
|
|
"minor_axis_cm_median": float(row.get("minor_axis_cm_median", 0.0)),
|
|
"major_axis_cm_median": float(row.get("major_axis_cm_median", 0.0)),
|
|
"predicted_weight_g": float(row.get("predicted_weight_g", 0.0)),
|
|
"gompertz_baseline_g": float(row.get("gompertz_baseline_g", 0.0)),
|
|
"vision_gain_g": float(row.get("vision_gain_g", 0.0)),
|
|
"n_weight_samples": int(row.get("n_valid_samples", 0)),
|
|
"rejection_rate": float(row.get("rejection_rate", 0.0)),
|
|
}
|
|
if weight_map:
|
|
return weight_map
|
|
except Exception:
|
|
pass
|
|
|
|
# 2. Try cage_day_features.parquet or .csv if predictions not directly mapped
|
|
for ext in (".parquet", ".csv"):
|
|
feat_file = report_dir / f"cage_day_features{ext}"
|
|
if feat_file.is_file():
|
|
try:
|
|
import pandas as pd
|
|
df = pd.read_parquet(feat_file) if ext == ".parquet" else pd.read_csv(feat_file)
|
|
for _, row in df.iterrows():
|
|
cid = str(row.get("camera_id", ""))
|
|
if cid and cid not in weight_map:
|
|
weight_map[cid] = {
|
|
"cycle_day": int(row.get("cycle_day", 0)),
|
|
"area_cm2_median": float(row.get("bbox_area_cm2_median", 0.0)),
|
|
"minor_axis_cm_median": float(row.get("minor_axis_cm_median", 0.0)),
|
|
"major_axis_cm_median": float(row.get("major_axis_cm_median", 0.0)),
|
|
"predicted_weight_g": 0.0,
|
|
"gompertz_baseline_g": 0.0,
|
|
"vision_gain_g": 0.0,
|
|
"n_weight_samples": int(row.get("n_valid_samples", 0)),
|
|
"rejection_rate": float(row.get("rejection_rate", 0.0)),
|
|
}
|
|
except Exception:
|
|
pass
|
|
|
|
return weight_map
|
|
|
|
|
|
def store_report(report_path: str, location: str, db_path: str) -> None:
|
|
rep_p = Path(report_path)
|
|
with open(rep_p) as f:
|
|
report = json.load(f)
|
|
|
|
date = report["date"]
|
|
cameras = report["cameras"]
|
|
generated_at = report.get("generated_at", "")
|
|
|
|
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
|
conn = sqlite3.connect(db_path)
|
|
migrate_db_schema(conn)
|
|
|
|
weight_data = load_companion_weight_data(rep_p.parent, date)
|
|
|
|
rows = 0
|
|
for camera_id, entry in cameras.items():
|
|
if entry.get("skipped"):
|
|
continue
|
|
w_info = weight_data.get(camera_id, {})
|
|
conn.execute(INSERT_SQL, (
|
|
date, location, camera_id,
|
|
entry.get("total_entered", 0),
|
|
entry.get("frames_processed", 0),
|
|
entry.get("elapsed_seconds", 0),
|
|
entry.get("stopped_reason", ""),
|
|
entry.get("source_video", ""),
|
|
generated_at,
|
|
w_info.get("cycle_day", 0),
|
|
w_info.get("area_cm2_median", 0.0),
|
|
w_info.get("minor_axis_cm_median", 0.0),
|
|
w_info.get("major_axis_cm_median", 0.0),
|
|
w_info.get("predicted_weight_g", 0.0),
|
|
w_info.get("gompertz_baseline_g", 0.0),
|
|
w_info.get("vision_gain_g", 0.0),
|
|
w_info.get("n_weight_samples", 0),
|
|
w_info.get("rejection_rate", 0.0),
|
|
))
|
|
rows += 1
|
|
|
|
if "FUSED" in weight_data:
|
|
w_fused = weight_data["FUSED"]
|
|
conn.execute(INSERT_SQL, (
|
|
date, location, "FUSED",
|
|
0, 0, 0.0, "fused_flock_weight", "", generated_at,
|
|
w_fused.get("cycle_day", 0),
|
|
w_fused.get("area_cm2_median", 0.0),
|
|
w_fused.get("minor_axis_cm_median", 0.0),
|
|
w_fused.get("major_axis_cm_median", 0.0),
|
|
w_fused.get("predicted_weight_g", 0.0),
|
|
w_fused.get("gompertz_baseline_g", 0.0),
|
|
w_fused.get("vision_gain_g", 0.0),
|
|
w_fused.get("n_weight_samples", 0),
|
|
w_fused.get("rejection_rate", 0.0),
|
|
))
|
|
|
|
conn.commit()
|
|
|
|
# print summary
|
|
row = conn.execute(SUMMARY_QUERY, (date, location)).fetchone()
|
|
if row:
|
|
print(f"\n[db] {row[0]} | {row[1]} | {row[2]} cameras | "
|
|
f"{row[3]} chickens | {row[4]:.0f}s ({row[5]} min) | avg weight: {row[6]}g")
|
|
|
|
# also print per-camera breakdown
|
|
cur = conn.execute(
|
|
"SELECT camera_id, total_entered, elapsed_seconds, predicted_weight_g, area_cm2_median, minor_axis_cm_median, major_axis_cm_median "
|
|
"FROM batch_runs WHERE date=? AND location=? ORDER BY camera_id",
|
|
(date, location))
|
|
for cam_id, count, secs, pw, area, minor_ax, major_ax in cur:
|
|
print(f" {cam_id}: {count} chickens, {secs:.0f}s, weight: {pw:.1f}g (area: {area:.1f}cm², minor: {minor_ax:.1f}cm, major: {major_ax:.1f}cm)")
|
|
|
|
conn.close()
|
|
print(f"\n[db] wrote {rows} rows to {db_path}")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Store batch run results into SQLite")
|
|
parser.add_argument("report", help="Path to counts_YYYY-MM-DD.json")
|
|
parser.add_argument("--location", required=True, help="Location name (e.g. kandang-atas)")
|
|
parser.add_argument("--db", default="chicken_counts.db", help="SQLite database path")
|
|
args = parser.parse_args()
|
|
|
|
if not Path(args.report).exists():
|
|
print(f"error: report not found: {args.report}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
store_report(args.report, args.location, args.db)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|