Files
andrew 631b3ea1da feat(weighing): integrate hybrid allometric-RF weight model into counting repo
- growth_model.py: load best_weight_model.pkl (hybrid_allometric_rf) with local chicken-weighing/ path first, external as fallback
- aggregation.py: pass minor/major axis medians into predict_chicken_weight
- run_daily_weighing.sh: run local chicken-weighing/weighing_inference.py
- vendor chicken-weighing/ mirror (models, db, services, dashboard)
- configs: stage boundaries 0-14 early / 15+ mid; floor_config extends simulation_experiment
- services: fix paths to Project_FOLDER/.Codes
- requirements: add scikit-learn, lightgbm, pytest
- docs: sync README/RUN/API/ERD/CHANGELOG/CENTRAL_DASHBOARD to current code state
2026-10-20 15:54:31 +07:00

36 KiB
Raw Permalink Blame History

Changelog

All notable changes to the chicken-counting-sukawarna-det project are documented in this file.

[Unreleased]

📚 Documentation Sync (2026-10-14)

  • RUN.md, API.md, ERD.md: rebuilt layout trees against the actual repo tree; venv note (fresh clone needs make setup); model table marks .pt default (onnxruntime not installed); Day-0 default 2026-10-01, stages 0–14 early / 15+ mid; --task count / --task weight / --task all documented; install via ./install_service.sh (user-level systemd, not system-level); sibling weighing repo integration section added; batch_runs.uniformity, batch_execution_jobs (GET /api/db/jobs), and weight_predictions (legacy training-only ledger) documented; stale /home/asus/.Codes/... paths corrected to /home/asus/Project_FOLDER/.Codes/...; weight uniformity corrected to ±10% of median area (matches aggregation.py/curation.py).

⚖️ Weight Pipeline Fixes (2026-10-13/14)

  • GBM weight correction disabled at the aggregation call site; predictions use hybrid allometric + Gompertz baseline only, loading the external model from chicken-weighing-sukawarna (best_weight_model.pkl, type hybrid_allometric_rf, base_params=[7.85634424, 1.38571042]).
  • K2-L1 day-138 rows purged from db/chicken_counts.db.
  • Dashboard SQLite auto-reconnect: connection dropped and re-opened when the DB file inode changes (replaced in place), so long-running dashboards pick up restored databases without restart.
  • WAL checkpoint after purge: ed0c64a checkpoints WAL so storage_lifecycle purges actually land in the committed .db file.

🔀 Count/Weight Service Split & Cycle Handling (2026-10-13)

  • Services split (4bcd422): counting and weighing run as separate units; day-0 handling isolated (Day 0 = DOC count only, weight starts day 1+).
  • Batch job ledger: every batch run upserts into batch_execution_jobs (status, started_at refreshed on upsert, default FAILED if never completed); surfaced via GET /api/db/jobs.
  • Config rework: counting/weighing YAML sections wired through batch config; location label and absolute footage root pinned (e0b6b83, eeb1a3a); dead weighing keys dropped from count-task defaults.
  • Current stage boundaries (configs/cycle7_batch_optimized.yaml): early 0–14 (conf 0.10, area 50, area_rel 0.10), mid 15+ (conf 0.40, area 3000).

📦 Parquet-Only Cycle Consolidation, Auto-Run Daily (2026-10-06)

  • Merged output renamed weight_and_parquet_data/ → cycle_weight_parquet_data/ (folder name now a single CYCLE_WEIGHT_DIR_NAME constant shared by weight/storage.py, weight/daily_size_comparison.py, and the dashboard.py coop/location skip-list, so it cannot half-rename again).
  • Merged CSVs dropped by default: full_cycle_detections.csv was 8.4× the parquet (235.8 MB vs 28.8 MB on a 49-day cycle) and duplicated the parquet rows. consolidate_full_cycle_datasets(..., with_csv=False) is now the default; chicken-counter consolidate-parquets --with-csv restores the CSV exports. Per-date daily exports keep writing CSV as before.
  • simulate_daily_cycle.sh consolidates automatically after each successful daily batch (no exec on the batch call anymore), so the cycle folder stays current without a manual step. Consolidation failure only warns — the day's SQLite rows are already stored.
  • Consolidation is idempotent: rows dedupe on (date, camera_id, track_id, frame_index), so manual reruns never duplicate.
  • Verified on the 6-day sim dataset: 118,427 merged rows == sum of daily parquets, 0 duplicates, daily_size_comparison.xlsx generated. 49 unit tests pass.

⚡ True Multi-Process Parallel Cameras & Daily Full-Cycle Simulation (2026-10-01)

  • parallel_processes implemented for real (batch_runner.py): the mode previously fell through to the serial loop (only hybrid/tensor_batching had dispatch branches). It now runs all cameras concurrently through ProcessPoolExecutor (spawn, max_workers=N), one worker process per camera on the shared GPU — no tensor batching. Each worker builds its own config/pipeline in-process (pickling-safe).
  • Benchmark: 4-camera daily job = ~3.4 min (204 s) wall incl. model load, aggregation, weight & DB vs ~6.7 min serial (~2× speedup). Counts identical (total 13858, FUSED 45.4 g).
  • New simulate_daily_cycle.sh + cron: daily 08:00 WIB full counting + weight run under FULL_CYCLE_1_FLOOR_SIM; maps today onto 49 archived source days (2026-05-22..2026-07-09, wraps), symlinks into ../VIDEOS/cycle7/FULL_CYCLE_1_FLOOR_SIM/<date>/, location K1-L1 (coop K1), GPU preflight skip, skip-if-source-missing. (Correction 2026-10-14: never had flock or skip-if-exists on the output side — overlapping cron runs are still possible if a run exceeds 24 h.) Verified via /api/db/date/2026-10-01 + /api/weight/predictions?location=K1-L1.
  • Config (configs/cycle7_batch_optimized.yaml): early-cycle stage tuning (day_max 15→10, mid-cycle day_min 16→11, min_box_area_px 100→50, added iou: 0.7); detection weights .onnx → .pt (onnxruntime not installed).

🗺️ ERD Synchronized with Central Dashboard ERD (v31.4.5)

  • Full sync of ERD.md against ERD_central_dashboard.json (now deleted, single source of truth is ERD.md):
    • USER_ACCESS: replaced password_hash varchar(255) with central password varchar(30) (hashed in backend); added display_name, last_login, is_superuser, is_staff, is_active.
    • CYCLES: end_date is now nullable per central; added proposed_end_date, close_requested_at, close_requested_by_id (FK \to USER_ACCESS), feed_initial_balance, feed_initial_balance_date.
    • MANUAL_INPUT: added feed_out_manual and feed_out_manual_total alongside existing feed_in_* / feed_use_* fields.
    • API_KEYS (new table): machine credentials for header-based API auth (id, user_id FK, name, prefix, key_hash, is_active, last_used_at, created_at, updated_at); related as USER_ACCESS ||--|{ API_KEYS.
    • Relationships: added CYCLES }|--o| USER_ACCESS (close_requested_by) edge; Tier 1 description now documents API_KEYS and the cycle close-out workflow.

📖 Documentation Sync (Edge-Facing Docs)

  • CENTRAL_DASHBOARD_INTEGRATION.md (guide for central devs consuming the edge API):
    • Added API_KEYS machine-credential note to the farm hierarchy section (central-only, header auth, no edge endpoint yet).
    • Added Section D (CYCLES close-out & feed-balance fields), Section E (API_KEYS table mapping), and Section F (MANUAL_INPUT feed-out fields) — all flagged as ⚠️ not yet available from edge API where applicable.
    • Added central-schema note to the weight-predictions example (doc_weight, average_daily_gain, timestamps on CHICKEN_WEIGHT; cycle-level fields live on central CYCLES).
  • RUN.md:
    • Completed the Section C endpoints table with the newer coop/weight/mortality routes (/api/weight/coops, /api/weight/coop/<id>, /api/weight/features/<date>, /api/weight/curation/..., /api/mortality/coops, /api/mortality/coop/<id>, /api/mortality/date/<date>, /api/mortality/cameras, /camera/preview, POST capture/upload/scan/delete).
    • Added a machine-auth note to Step 5 pointing at the central API_KEYS table (header auth, provisioned centrally, no edge endpoint yet).
  • API.md: verified current — correctly documents edge-only APIs (already includes coop/location filtering); no central-table docs added by design.

📍 Camera Location & Coop Identification in Weight Estimation API

  • End-to-End Coop (coop) and Floor Location (location) Metadata Integration:

    • Enhanced weight pipeline (src/chicken_counter/weight/aggregation.py) to propagate parent coop (e.g. K1 for Kandang 1) and floor location (e.g. K1-L1 or test-coop-1) across aggregate_camera_features and build_cage_day_features_and_predictions.
    • Added automatic coop derivation via get_coop_for_location(location) when only floor/location is provided.
    • Included coop and location in all individual camera records, the FUSED flock record, and cage_day_features.
    • Extended intermediate observation Parquet schema (DETECTION_PARQUET_COLUMNS) in storage.py with coop and location.
    • Added coop and location tracking in save_curation_summary to curation_{date}_{camera_id}.json.
  • REST API Enhancements & Multi-Coop Disambiguation (dashboard.py):

    • New Endpoints:
      • GET /api/weight/coops: Summary list of all detected coops with available weight predictions, covered floors, and latest flock weight.
      • GET /api/weight/coop/<coop_id>: Historical weight predictions filtered specifically for a coop (e.g. K1).
    • Deduplication Fix: Fixed the date-collision bug in GET /api/weight/predictions where records were deduplicated by date alone. Keying on (date, coop, location, camera_id) now preserves multiple coops on the same date.
    • Query Parameter Filtering: Added ?coop= and ?location= filtering to /api/weight/predictions, /api/weight/predictions/<date>, /api/weight/features/<date>, and /api/weight/curation/....
    • Frequency, Excluded, and Uniformity Metrics: Added explicit frequency (sample count used for weight calculation), excluded (discarded MAD outliers / duplicates), and uniformity (flock uniformity percentage within \pm 10\% of median area, per poultry standard) to all weight estimation records, /api/weight/predictions, /api/weight/predictions/<date>, /api/weight/features/<date>, /api/weight/curation/..., and /api/db/date/<date>.
    • Dynamic Farm Discovery: Expanded root discovery using discover_farm_structure() and added automatic fallback inference (_infer_coop_and_location) to enrich legacy datasets from folder path hierarchy.
    • Telemetry & SQL Integration: Updated GET /api/db/date/<date> to return predicted_weight_g, area_cm2_median, cycle_day, coop, frequency, excluded, and uniformity for all cameras, matching Central Dashboard specifications.
    • FUSED Flock Weight Persistence: Updated batch_runner.py and store_results.py to persist overall FUSED flock predictions into SQLite batch_runs table with camera_id='FUSED'.
  • Documentation & ERD Updates:

    • Updated ERD.md: Added coop and location to DETECTIONS, CHICKEN_WEIGHT, CHICKEN_COUNTING, and BATCH_RUNS.
    • Updated CENTRAL_DASHBOARD_INTEGRATION.md: Added coop and location field mappings to Table CHICKEN_WEIGHT and updated Section 4.4 examples.
    • Updated API.md: Documented new coop endpoints, query parameters, and updated Parquet intermediate schema table.

[0.3.0] - 2026-08-27

🧹 Automated Storage Lifecycle & Validated Raw Video Purging

  • Strict Multi-Camera Artifact Validation & Purge (src/chicken_counter/storage_lifecycle.py):
    • Implemented validate_daily_run_artifacts() which verifies that all required output artifacts (Parquet datasets, compressed MP4s, and JSON counts reports) exist and are uncorrupted before any raw uncompressed source video is purged.
    • Implemented purge_raw_input_videos() and enforce_retention_policy() to reclaim hundreds of gigabytes of disk space on edge NVMe drives across multi-day broiler cycles.
    • Added --purge-raw-videos, --retention-days, and a standalone chicken-counter cleanup subcommand.

🔌 UPS Power-Cut Recovery & SQLite WAL Checkpointing

  • Hardware Failure & Power Loss Safety (src/chicken_counter/db_utils.py):
    • Standardized SQLite connections with PRAGMA journal_mode=WAL;, PRAGMA synchronous=NORMAL;, and PRAGMA busy_timeout=60000;.
    • Added explicit WAL truncate checkpointing (checkpoint_sqlite_wal()) to guarantee all transactions in -wal are consolidated into the primary .db file.
    • Implemented signal handlers (SIGTERM, SIGINT, SIGHUP) across batch processing and the dashboard daemon to ensure clean database flushing during UPS low-battery shutdown or systemd service stops.

⚖️ Configurable Day 0 (DOC) Arrival Baseline Weight

  • End-to-End DOC Weight Calibration (growth_model.py, aggregation.py, batch_runner.py, config.py, cli.py, dashboard.py):
    • Implemented configurable doc_weight_g across YAML configs, CLI (--doc-weight), and REST API (GET/POST /api/config/doc_weight).
    • Enhanced Gompertz growth model baseline to anchor age predictions to custom Day 0 hatchery arrival scale weights with an exponential decay curve into mature broiler weights.
    • Added atomic YAML configuration persistence for doc_weight_g in dashboard.py and included doc_weight_g in /api/status.

🛠️ Cross-Platform Portability & Dependency Hardening

  • Production requirements.txt Curated (requirements.txt):
    • Removed all hardcoded absolute local Jetson file wheel links (@ file:///opt/... and @ file:///home/jetson/...).
    • Removed un-installable Ubuntu-specific host system packages (python-apt, python-debian, ufw, ubuntu-pro-client, xkit).
    • Added universal environment markers for onnxruntime-gpu (Linux/x86_64 NVIDIA) and onnxruntime (ARM/macOS).
    • Pinned stable, production-grade cross-platform dependencies across all target platforms (Linux x86, Jetson ARM64, Docker, Windows/macOS).

📐 Robust Mask Anatomical Axes Calculation

  • Second-Order Central Moments / Inertia Tensor (src/chicken_counter/weight/calibration.py):
    • Enhanced compute_metric_mask() to compute orientation-invariant major and minor axes using second-order central moments (\mu_{20}, \mu_{02}, \mu_{11}) with cv2.minAreaRect fallback.
    • Guarantees valid major/minor axis estimation even on irregular, non-convex, or degenerate polygon masks where cv2.fitEllipse (< 5 points) previously failed.

🌐 Dashboard Frontend Syntax Fix

  • JavaScript Template Placeholder (templates/index.html):
    • Wrapped {{ poll_ms }} with Number("{{ poll_ms }}") || 1000 on line 456 to eliminate IDE static syntax diagnostics while maintaining dynamic polling rate rendering.

📖 Configuration Documentation

  • Comprehensive Inline Comments (configs/cycle7_batch_optimized.yaml):
    • Documented all batch parameters, multi-stage chick vs mature sensitivities, optical flow backward detection variables, performance flags, and per-camera lane calibration metrics.

[0.2.0] - 2026-08-24

☠️ Dedicated Mortality Inspector Tab & Deletion Workflow

  • Top-Level Navigation & Split-View UI (templates/index.html):
    • Moved carcass detection from sidebar into a dedicated top-level Mortality Inspector tab.
    • Implemented split-screen inspection layout: high-resolution image preview on left, filterable cards and control pane on right.
    • Added multi-dimension live filtering: by Coop (ALL, K1..K5), by Date (dropdown), and by Status (All, >0 Carcasses, Clean 0).
    • Added real-time search bar for scan name and coop filtering.
  • Image Deletion Workflow with Confirmation Dialog (dashboard.py, templates/index.html, API.md):
    • Implemented POST /api/mortality/delete and DELETE /api/mortality/image/<filename> endpoints.
    • Added dark-mode confirmation modal before permanent file removal.
    • Safely deletes output JPEG, raw input photo, and mask files while automatically recalculating total_mortality_count and total_images in mortality_report.json.

🎭 Instance Segmentation Masking & Weight Estimation

  • True Anatomical Mask Geometry Extraction (src/chicken_counter/weight/calibration.py, pipeline.py, tracking.py):
    • Implemented compute_metric_mask(mask_polygon, bbox_xyxy, centroid, px_per_cm):
      • Extracts true physical body surface area (\text{area\_cm2} = \text{cv2.contourArea(contour)} / \text{px\_per\_cm}^2) and contour perimeter (\text{perimeter\_cm}).
      • Fits orientation-invariant anatomical ellipses (cv2.fitEllipse) to calculate true bird body length (major_axis_cm) and body width (minor_axis_cm), eliminating background floor corners.
      • Tags rows with geometry_source: "mask" (or "bbox" when fallback is used).
    • Updated BoT-SORT tracker (src/chicken_counter/tracking.py) to map and forward instance segmentation mask polygons (result.masks.xy) directly to TrackObservation.
  • Toggleable Runner & Config (configs/cycle7_batch_segmentation_masking.yaml, test_run_folder/test_run_full_cycle7_segmentation_masking.sh):
    • Added configs/cycle7_batch_segmentation_masking.yaml with calibration.use_mask_geometry: true.
    • Added test_run_folder/test_run_full_cycle7_segmentation_masking.sh supporting toggleable geometry modes (--mask vs --bbox).
  • SQLite WAL Concurrency Hardening (src/chicken_counter/batch_runner.py, store_results.py):
    • Configured PRAGMA journal_mode=WAL;, PRAGMA busy_timeout=60000;, and PRAGMA synchronous=NORMAL; across all database connection routines to eliminate database lock contention across simultaneous worker completions.

📦 Full-Cycle Parquet & Weight Dataset Consolidation (weight_and_parquet_data)

  • Full-Cycle Dataset Consolidation Engine (src/chicken_counter/weight/storage.py, cli.py):

    • Implemented consolidate_full_cycle_datasets(dataset_root_dir, output_dir) to automatically scan all processed date directories and generate unified full-cycle datasets inside weight_and_parquet_data/ aligned with the date directories.
    • Multi-camera aware: Discovers all per-camera datasets (detections_{date}_CC*.parquet), merges them into daily combined files, and computes camera-level features plus multi-camera FUSED summaries.
    • Generates:
      • full_cycle_detections.parquet (29 MB) & full_cycle_detections.csv (230 MB): Master dataset containing all 736,089 curated bird track observations across all 4 cameras (CC1: 187,638, CC2: 171,116, CC3: 194,285, CC4: 183,050).
      • full_cycle_cage_features.parquet (137 KB) & full_cycle_cage_features.csv (96 KB): Full chronological distribution ledger across cameras and fused summaries (245 rows: 49 dates \times 5 rows).
      • full_cycle_predictions.parquet (23 KB) & full_cycle_predictions.csv (22 KB): Daily Gompertz vs vision weight predictions across the complete cycle (245 rows: 49 dates \times 5 rows).
      • full_cycle_curation_summary.json (66 KB): Consolidated multi-camera curation and outlier rejection metrics.
      • daily_size_comparison.xlsx (18 KB): Multi-sheet comparative workbook matching FatChicken reference with:
        • all_days: Multi-camera FUSED medians, ground truth manual scale weights (manual_g), vision predictions (vision_pred_g), % error vs manual, and area_vs_day35_pct.
        • per_camera: Complete 196-row camera-by-camera breakdown (49 dates \times 4 cameras).
        • legend: Metric definitions, error formulas, and post-market thinning highlights (day >= 36).
        • Ground-truth integrity: Unmeasured days (Day 0 arrival and Day 48+) remain blank (None) without synthetic data.
  • Parallel Worker Race-Condition Fix (src/chicken_counter/batch_runner.py):

    • Fixed race condition where parallel per-camera worker processes (--camera CC*) previously overwrote daily combined files (detections_{date}.parquet, cage_day_features.parquet, predictions_{date}.parquet).
    • Workers now discover and incrementally merge on-disk camera parquets for that date, preserving all 4 cameras' data.
  • CLI Subcommand & Test Runner Integration (cli.py, test_run_folder/):

    • Added chicken-counter consolidate-parquets --root-dir <path> CLI command.
    • Integrated automatic dataset consolidation into test_run_folder/test_run_full_cycle7_segmentation.sh and test_run_folder/test_run_full_cycle7.sh.
    • Cleaned up duplicate runner scripts in root and moved all active log files into test_run_folder/.

📦 Detection Parquet Dataset Generation for Weight Estimation & Retraining

  • Canonical 31-Column Parquet Schema (src/chicken_counter/weight/storage.py, ERD.md, API.md):
    • Saves intermediate datasets detections_{date}_{camera_id}.parquet and daily combined detections_{date}.parquet.
    • Added full geometric morphometrics: bbox_area, area_cm2, perimeter_cm, major_axis_cm, minor_axis_cm, eccentricity, aspect_ratio, equiv_diameter_cm, centroid_x_cm, centroid_y_cm.
    • Added quality and curation traceability flags: is_validated, is_outlier, outlier_reason, kept_for_aggregation, sequence_number, source_video, and cycle_day.
    • Implemented strict pandas type enforcement (standardize_detection_dataframe) with nullable integers and zero string-corrupted numerics.
  • Dedicated Cycle 7 Segmentation Runner (configs/cycle7_batch_segmentation.yaml, test_run_folder/test_run_full_cycle7_segmentation.sh):
    • Added dedicated segmentation configuration and batch execution script with MAX_JOBS=2 concurrency for safe PyTorch instance segmentation processing.

⚖️ Chicken Weight Database Storage & Excel Report Analytics

  • Minor & Major Axis Geometry Extraction (calibration.py, aggregation.py):
    • Added minor_axis_cm (\min(\text{width}, \text{height})) and major_axis_cm (\max(\text{width}, \text{height})) to per-track metric observations.
    • Added full distribution statistics (minor_axis_cm_median, major_axis_cm_median, etc.) to camera aggregation and multi-camera FUSED records.
  • SQLite Database Schema Migration & Weight Storage (batch_runner.py, dashboard.py, store_results.py):
    • Extended batch_runs table with weight & dimensional columns: 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.
    • Implemented automatic non-destructive column migration (migrate_db_schema) on existing database files.
    • Added automatic database updating of weight metrics upon completion of daily batch processing.
  • Cycle Day 0 Rule Enforcement (batch_runner.py, growth_model.py):
    • Explicitly defined cycle_start_date as Day 0 (DOC arrival baseline 42.0g).
    • Weight counting and growth curves strictly begin at Cycle Day 1+, skipping weight estimation on Day 0.
  • Excel Report Generator Enhancement (export_excel_report.py):
    • Sheet 1 (Daily Summary): Added KPI cards for Average Flock Weight (g) and Median Bird Area (cm^2), plus daily weight columns in summary table.
    • Sheet 2 (Camera Summary): Added Avg Pred Weight (g), Median Area (cm²), Median Minor Axis (cm), Median Major Axis (cm), and Valid Samples.
    • Sheet 3 (Raw Batch Runs): Added full weight, size dimension, and Gompertz baseline breakdown columns.
    • Sheet 4 (Weight & Growth Analytics): Added new dedicated growth tracking worksheet with Day 1+ growth ledger and dual-series Line Chart comparing Predicted Weight vs. Gompertz Baseline Curve over cycle days.

[1.2.1] - 2026-08-21

⚖️ Weight Estimation, Track Curation & Parquet Storage Pipeline

  • Metric Centimeter Conversion & Camera Calibration (src/chicken_counter/weight/calibration.py, config.py):
    • Implemented CalibrationConfig with configurable px_per_cm per camera (e.g. CC1: 19.5, CC2: 20.2, CC3: 19.8, CC4: 19.2, default: 20.0).
    • Added on-the-fly metric conversion generating px_per_cm, bbox_area_cm2, width_cm, height_cm, aspect_ratio_cm, centroid_x_cm, centroid_y_cm, and perimeter_cm.
  • FatChicken Track Curation & Outlier Elimination (src/chicken_counter/weight/curation.py):
    • Deduplicated per-track observations to exactly one best observation per track_id (highest confidence upon count event trigger).
    • Implemented age-adaptive MAD Z-score outlier rejection on bbox_area_cm2 (z = 0.6745 \times (x - \text{median}) / \text{MAD}):
      • \le 10 days: |z| \le 3.0
      • 11\dots 24 days: |z| \le 2.5
      • > 24 days: |z| \le 2.0
      • Automatically activates when sample count N \ge 30.
  • Camera-Day Statistical Aggregation & Multi-Camera Fusion (src/chicken_counter/weight/aggregation.py):
    • Computes distribution metrics (mean, median, p25, p75, std, cv, iqr) for all metric features (bbox_area_cm2, width_cm, height_cm, aspect_ratio_cm, perimeter_cm).
    • Generates multi-camera FUSED summary row weighted by valid sample counts.
  • Broiler Growth Model & Audited Weight Predictions (src/chicken_counter/weight/growth_model.py):
    • Integrated Ross 308 / Cobb 500 Gompertz growth curve and standard daily DOC weight baseline table.
    • Generates audited weight records containing predicted_weight_g, doc_weight_g, gompertz_baseline_g, vision_gain_g (or residual_g), n_valid_samples, and dominant_camera.
  • Standardized Storage & Export Handlers (src/chicken_counter/weight/storage.py):
    • Per-track observations: detections_{date}_{camera_id}.parquet (and .csv fallback).
    • Curation summary: curation_{date}_{camera_id}.json.
    • Cage day features: cage_day_features.parquet (and .csv fallback).
    • Weight predictions: predictions_{date}.parquet (and .csv fallback).

🚀 Model & Runtime Configuration Improvements

  • Counting Pipeline Migration to ONNX Weights (configs/cycle7_batch_optimized.yaml, configs/cycle7_batch.yaml, configs/cameras/example_camera.yaml):
    • Migrated counting detection model to ONNX weights: models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx.
    • Installed and validated onnxruntime-gpu==1.29.0 with CUDAExecutionProvider achieving ~318+ FPS inference throughput on NVIDIA GPU.
    • Left chicken mortality detection strictly on the dedicated segmentation model: models/chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt.
    • Retained export_engine.py intact for on-demand TensorRT engine exports.
  • TensorRT Engine Verification & Auto-Recompilation Toggle (config.py, tracking.py, batch_runner.py, cli.py):
    • Added verify_engine: bool = False configuration field to DetectionConfig and batch YAML configurations.
    • Bypassed mandatory startup engine test inference and auto-recompilation loops by default for instantaneous pipeline initialization.
    • Added --verify-engine CLI flag to chicken-counter run and chicken-counter batch to enable manual engine validation and recompilation on-demand.
    • Maintained runtime fail-safe fallback in DetectionTracker that gracefully loads matching .pt model weights if an invalid .engine is encountered.
  • Multi-Site Staging Deployment (19 Floors Total) & Central Consolidation Architecture (configs/sites.yaml, discovery.py, mortality.py, run_all_coops.sh):
    • Implemented static multi-site farm configuration in configs/sites.yaml supporting:
      • Site A: 5 coops \times 2 floors = 10 floors (K1-L1..K5-L2) with 1 dedicated stationary mortality camera (site_a).
      • Site B: 3 coops \times 3 floors = 9 floors (K1-L1..K3-L3) with 1 dedicated stationary mortality camera (site_b).
      • Total Deployment: 19 floors across 2 sites ready for edge execution and subsequent data consolidation/merging on a central server.
    • Added site metadata tagging in batch reports and mortality JSON summaries ("site": "site_a" | "site_b").
    • Populated run_all_coops.sh master batch script with site-aware target selection (./run_all_coops.sh site_a, ./run_all_coops.sh site_b, or ./run_all_coops.sh all).
  • Auto-Discovery Toggle (auto_discover: false by default) (discovery.py, config.py, cli.py, mortality_config.yaml):
    • Disabled dynamic unconstrained directory walks across VIDEOS/ by default (auto_discover: false), switching to predictable static config/site profile loading.
    • Added --auto-discover CLI flag to chicken-counter batch, chicken-counter mortality, and chicken-counter sync-configs to explicitly opt-in to filesystem scanning.
    • Updated configs/mortality_config.yaml and configs/cycle7_batch_optimized.yaml with auto_discover: false.
  • Reporting & Unit Test Coverage (export_excel_report.py, tests/test_tracking.py, tests/test_flexible_discovery.py):
    • Updated export_excel_report.py configuration metadata sheet to reflect PyTorch .pt model defaults.
    • Added automated unit tests covering verify_engine toggle flows, Site A/B profiles, and site-level mortality camera lookups (all 18 unit tests passing).

[1.2.0] - 2026-08-20

🚀 Features & Architectural Improvements

  • Hierarchical Per-Coop & Flexible Cage/Floor Discovery (discovery.py):
    • Implemented dynamic farm discovery engine (discover_farm_structure, get_coop_for_location, resolve_floor_video_dir).
    • Added support for hierarchical coop folders (VIDEOS/cycle7/<Coop>/[L1..Ln, mortality]) where all floors and mortality sit on the same level per coop.
    • Fully dynamic site layout discovery without hardcoding assumptions about numbers of coops (e.g. K1..K5 or custom names) or floors per coop (e.g. 2 floors vs 3 floors).
  • Multi-Coop Mortality Pipeline & Batch Runner (mortality.py, cli.py, run_mortality_all.sh):
    • Added coop and covered floor metadata resolution in run_mortality_count(...) and mortality_report.json.
    • Created run_all_coop_mortality(...) and ./run_mortality_all.sh to batch-process mortality detection across all discovered coops with summary reports.
    • Added CLI flags --coop <ID> and --all-coops to chicken-counter mortality.
  • Dedicated Stationary Inspection Camera Capture & Live API (mortality.py, dashboard.py, templates/index.html):
    • Added support for dedicated per-coop stationary cameras (RTSP IP cameras, HTTP snapshots, and USB cameras) configured in configs/mortality_config.yaml.
    • Added POST /api/mortality/capture endpoint to grab high-res still frames from a coop's stationary camera, timestamp and save them into VIDEOS/cycle7/<Coop>/mortality/<YYYY-MM-DD>/, and run YOLO carcass detection.
    • Added GET /api/mortality/camera/preview to stream live snapshot previews to workers in the webapp before snapping.
    • Added GET /api/mortality/cameras to list all registered coop stationary camera sources.
    • Web UI Mortality Inspector: Integrated live camera preview, one-click "📸 Snap & Count Batch from Camera" button, and support for multi-batch counting per coop per day with cumulative totals.
    • Added fallback manual file upload tab for disk-based images.
  • Dynamic Floor Config Synthesis & Sync Tool (config.py, discovery.py, cli.py):
    • Implemented load_or_synthesize_floor_config allowing chicken-counter batch --floor <ID> to dynamically synthesize settings from cycle7_batch_optimized.yaml in memory without requiring a physical YAML file.
    • Implemented sync_floor_configs and CLI command chicken-counter sync-configs to automatically scan VIDEOS/ and generate boilerplate floor YAML configs for newly added coops/floors.
    • Updated run_all_coops.sh to dynamically discover all floors directly from VIDEOS/ or configs/floor_config/ and seamlessly run physical YAMLs or virtual in-memory configs.
  • Dynamic Sliding-Window Task Runner (test_run_folder/test_run.sh):
    • Implemented dynamic sliding window process pool with default MAX_JOBS=4.
    • Removed date-barrier wait: as soon as any single video job finishes, the next pending video starts immediately, maximizing GPU utilization.
    • Added clean signal trapping (SIGINT, SIGTERM) to reliably terminate child workers on exit.
  • Port 8090 Migration & Ecosystem Integration (dashboard.py, start_dashboard.sh, chicken-dashboard.service):
    • Migrated the default web dashboard port from 8080 to 8090 across the entire codebase, systemd service units, and documentation to prevent port collisions with other farm systems (e.g. fatchicken).
  • Multi-Tier Model Loading & TensorRT Fail-Safe (tracking.py, engine_utils.py):
    • Added post-compilation test inference verification in engine_utils.py.
    • Added runtime PyTorch .pt model fallback in tracking.py if a .engine TensorRT file fails to load or execute.
    • Fixed Ultralytics BOTSORT/ByteTrack tracker compatibility for CUDA box tensors by ensuring .cpu() conversion before numpy concatenation.
  • High-Performance Native Ingestion Architecture (capture.py, decoder.py):
    • Retained clean native C++ OpenCV video ingestion with zero IPC overhead and direct NumPy buffer sharing for optimal CPU-GPU balance across 4 parallel streams.
  • Unit Test Suite (tests/test_flexible_discovery.py, tests/test_counting.py):
    • Added automated test cases validating dynamic coop and floor extraction, arbitrary site layout adaptation, path resolution, config synchronization, virtual floor config synthesis, and dated mortality discovery.
    • Resolved OpenCV import stub shadowing to allow full unit test discovery.

[1.1.0] - 2026-08-19

🐛 Bug Fixes

  • Multi-Camera Tracker State Isolation (tracking.py & batch_runner.py):
    • Implemented per-camera independent tracker instances keyed by stream_id in DetectionTracker.
    • Fixed tracker state bleed and track ID jumping in tensor_batching and multi-camera batch modes when camera frames are processed or when active camera sets shrink.
    • Added unit test suite tests/test_tracking.py covering multi-stream tracker isolation.
  • Multi-Floor Script Syntax (run_all_coops.sh):
    • Resolved fatal syntax error: unexpected end of file caused by missing done in floor configuration discovery loop.
    • Expanded config discovery pattern from K*-L*.yaml to *.yaml to support custom named coops (e.g. kandang-atas.yaml).
  • Excel Report Empty Result Crash (export_excel_report.py):
    • Added empty DataFrame pre-check to prevent IndexError when exporting reports for dates with no batch runs or newly initialized databases.
  • Multi-Threaded SQLite Concurrency (dashboard.py):
    • Replaced global single sqlite3 connection with thread-local connections (threading.local()) to prevent cursor collision and race conditions across concurrent HTTP worker threads.
    • Enabled PRAGMA busy_timeout = 5000 and PRAGMA journal_mode = WAL to avoid database lock conflicts during batch processing writes.
  • Editable Package Installation:
    • Configured pip install -e . in environment setup to resolve chicken_counter imports and enable automatic unit test discovery without manual PYTHONPATH prefixes.

⚡ Performance & Optimization

  • Secondary Database Indexing (dashboard.py, batch_runner.py, store_results.py):
    • Added idx_batch_date, idx_batch_camera, and idx_batch_location indexes on batch_runs to accelerate single camera, location, and date historical queries.
  • Atomic Config Persistence (dashboard.py):
    • Added _config_write_lock and atomic temporary file replacement (os.replace) in _persist_cycle_start_date to prevent race conditions or half-written YAML reads.
  • Streaming Socket Keepalive (dashboard.py):
    • Added an idle keepalive heartbeat (b"--frame\r\n\r\n") every 3 seconds to immediately detect and terminate disconnected MJPEG streaming threads during pipeline idle periods.
  • Disk Traversal Caching in Live Dashboard (dashboard.py):
    • Replaced repetitive Path.rglob() scans on every /api/mortality/* endpoint with a thread-safe 15-second in-memory TTL cache (_MORTALITY_CACHE_TTL = 15.0s).
    • Added O(1) memory index lookup for serving annotated images (/api/mortality/image/<filename>), eliminating full filesystem traversals across 30GB+ video datasets.

📁 Configuration & Directory Structure

  • Floor Configuration & Skeleton Paths:
    • Created configs/floor_config/kandang-atas.yaml extending cycle7_batch_optimized.yaml.
    • Initialized missing directory skeletons for coops K1-L1 through K5-L2 under ../VIDEOS/cycle7/.
  • Documentation:
    • Updated README.md and RUN.md with editable install steps and updated project layout.