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

28 KiB
Raw Permalink Blame History

Quick Start Guide

This guide gets a new developer up and running from scratch.


1. Prerequisites

  • Python 3.10+
  • ffmpeg on PATH (for video compression)
  • NVIDIA GPU + CUDA drivers (optional but recommended for inference speed)

2. First-Time Setup

# Clone / copy the project folder, then enter it
cd chicken-counting-sukawarna-det

# Create a virtual environment and install all dependencies
python3 -m venv venv
venv/bin/pip install --upgrade pip
venv/bin/pip install -r requirements.txt
venv/bin/pip install -e .

Note

: The venv steps are for fresh installs. The deployed machines already have an environment; the runner scripts fall back to python3 when no venv/ exists. If moving the project from another machine, always recreate the venv — do NOT copy the venv/ folder (it contains absolute paths baked in from the source machine).


3. Project Layout

chicken-counting-sukawarna-det/
├── configs/
│   ├── floor_config/                 ← Lightweight floor configs (K1-L1..K3-L3, K4-L1/L2, K5-L1/L2)
│   │   ├── K1-L1.yaml .. K5-L2.yaml  ← Extends cycle7_batch_optimized.yaml
│   │   └── kandang-atas.yaml         ← Extends cycle7_batch_optimized.yaml
│   ├── cycle7_batch_optimized.yaml   ← Main base batch processing config
│   ├── cycle7_batch.yaml             ← Alternate batch config
│   ├── cycle7_batch_segmentation.yaml
│   ├── cycle7_batch_segmentation_masking.yaml
│   ├── mortality_config.yaml         ← Mortality (carcass) detection config
│   ├── sites.yaml                    ← Static site profiles (site_a / site_b)
│   ├── simulation_experiment.yaml
│   ├── cameras/example_camera.yaml   ← Single-camera run config template
│   └── trackers/botsort_chicken.yaml ← BoT-SORT tracker settings
├── db/
│   └── chicken_counts.db             ← SQLite database (auto-created)
├── docs/                             ← Troubleshooting notes & internal plans
├── models/                           ← Detection (.pt/.onnx/.engine), mortality seg, weight models (.joblib)
│   ├── chicken-detection-model-v26n-300e-best-2026-05-02-NEW.pt   ← Batch default (PyTorch; onnxruntime not installed)
│   ├── chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx ← ONNX export (used by cycle7_batch.yaml)
│   ├── chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine ← Hardware-tuned TensorRT
│   └── chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt   ← Used by mortality (PyTorch Segmentation)
├── scripts/                          ← Model training scripts
├── src/chicken_counter/              ← Main Python package (counting, tracking, motion, weight/, engine_utils)
├── tests/                            ← Unit tests (python3 -m unittest discover -s tests)
├── templates/                        ← Dashboard HTML
├── weights/, runs/, logs/            ← YOLO runtime artifacts (gitignored)
├── dashboard.py                      ← Live API + Dashboard server
├── export_engine.py                  ← Manual TensorRT export utility
├── export_excel_report.py            ← Excel reporting & analytics generator
├── generate_count_weight_report.py   ← Count vs manual-scale verification workbook
├── store_results.py                  ← counts_*.json → SQLite importer
├── run_all_coops.sh                  ← Master multi-coop batch runner (all configured floors)
├── run_daily_counting.sh             ← Daily counting runner (batch --task count + SIM pass)
├── run_daily_weighing.sh             ← Daily weighing runner (delegates to chicken-weighing-sukawarna)
├── run_mortality_all.sh              ← Daily mortality runner (all coops)
├── simulate_daily_cycle.sh           ← Daily full-cycle simulation (archive videos)
├── sim_map.sh                        ← Date→archive video mapping for the simulation
├── start_dashboard.sh                ← Portable dashboard launcher ← USE THIS
├── install_service.sh                ← Installs user-level systemd units + timers
├── chicken-*.service / .timer        ← User-level systemd units
├── test_run_folder/                  ← Archive of test run scripts and logs
├── pyproject.toml
└── requirements.txt

4. Model Setup & Engine Verification Toggle

Put your model files in the models/ directory.

Purpose File Notes
Batch video counting models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.pt Batch default (PyTorch; configs/cycle7_batch_optimized.yaml — onnxruntime not installed on deployment machines)
ONNX export models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx ONNX Runtime GPU (CUDAExecutionProvider ~318 FPS); used by cycle7_batch.yaml / example_camera.yaml
High-throughput TensorRT Engine models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine Maximum GPU throughput (export with export_engine.py)
Mortality detection models/chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt Direct segmentation model (PyTorch, 2-pass disabled)

Engine Verification Toggle: By default, the pipeline bypasses startup engine verification loops for instant execution with PyTorch .pt models. If you use a .engine and want to enable auto-verification/recompilation on a new machine or GPU, pass the --verify-engine CLI flag or set verify_engine: true in your YAML config. If an .engine ever fails to load, DetectionTracker automatically falls back to the matching .pt model.


5. Running the Systems

A — Batch Video Processing (Daily Chicken Count)

Place input videos under the VIDEOS folder adjacent to the project following the K{coop}-L{floor} format:

../VIDEOS/cycle7/
  K1-L1/
    2026-06-18/
      K1-L1_cam1_2026-06-18_120056.mp4
      K1-L1_cam2_2026-06-18_120456.mp4
      K1-L1_cam3_2026-06-18_121012.mp4
      K1-L1_cam4_2026-06-18_121530.mp4

Then run:

# Run all coops & floors (static site profiles; auto-discovery off) for a specific date
./run_all_coops.sh 2026-06-18

# Run a specific floor using its config file
PYTHONPATH=src venv/bin/python -m chicken_counter.cli batch \
  --config configs/floor_config/K1-L1.yaml \
  --date 2026-06-18

# Run directly on ANY discovered floor (virtual config — zero YAML required!)
PYTHONPATH=src venv/bin/python -m chicken_counter.cli batch \
  --floor K6-L1 \
  --date 2026-06-18

# Automatically scan VIDEOS and generate boilerplate YAMLs for any newly added floors
PYTHONPATH=src venv/bin/python -m chicken_counter.cli sync-configs

Output is saved in ../VIDEOS/cycle7/<coop>/<floor>/<date>/output/.

Parallel Multi-Video Processing (Dynamic Sliding-Window Pool)

To process hundreds of surveillance videos across multiple dates at maximum hardware speed:

# Run the parallel sliding-window runner (defaults to MAX_JOBS=4)
./test_run_folder/test_run.sh

# Run standard object detection batch runner (defaults to MAX_JOBS=4)
MAX_JOBS=4 ./test_run_folder/test_run.sh

# Run PyTorch instance segmentation runner with true polygon mask geometry (defaults to MAX_JOBS=2)
./test_run_folder/test_run_full_cycle7_segmentation_masking.sh 2 --mask

# Or run with bounding-box fallback geometry toggle
./test_run_folder/test_run_full_cycle7_segmentation_masking.sh 2 --bbox
  • Zero Barrier Waiting: Processes continuously slide into the worker pool without waiting for entire date batches to finish.
  • Process Signal Trapping: Cleanly catches Ctrl+C / SIGINT to safely terminate child worker processes.

Full-Cycle Parquet Consolidation & Daily Size Comparison

To consolidate all processed date directories into unified datasets and generate the comparative Excel workbook:

# Run consolidation across all dates under a dataset directory:
PYTHONPATH=src venv/bin/python -m chicken_counter.cli consolidate-parquets \
  --root-dir /path/to/cycle7/FULL_Cycle_Kandang_Atas_Test

# Add CSV exports (~8x larger):
PYTHONPATH=src venv/bin/python -m chicken_counter.cli consolidate-parquets \
  --root-dir /path/to/cycle7/FULL_Cycle_Kandang_Atas_Test --with-csv

Outputs are automatically generated in cycle_weight_parquet_data/:

  • full_cycle_detections.parquet: Master dataset of all curated bird observations across all 4 cameras (CC1–CC4).
  • full_cycle_cage_features.parquet: 5 rows per date (CC1..CC4 + FUSED).
  • full_cycle_predictions.parquet: 5 prediction rows per date.
  • full_cycle_curation_summary.json: Consolidated multi-camera outlier rejection statistics.
  • daily_size_comparison.xlsx: Multi-sheet comparative workbook (all_days, per_camera, legend) with manual ground-truth error metrics.

simulate_daily_cycle.sh already runs this consolidation after each successful daily batch.


B — Mortality Detection (Per-Coop Carcass Photo Scanning)

Each coop (or central mortality table) is equipped with a dedicated stationary camera (RTSP stream or USB camera) mounted above the inspection area:

  1. Open the Webapp: From any phone, tablet, or terminal on the farm local network, navigate to http://<JETSON-IP>:8090.
  2. Open Mortality Inspector: Under the sidebar 💀 Mortality Scans, tap 📷 Upload / Capture.
  3. Select Coop & Inspect View:
    • Choose the coop (e.g. K1).
    • The live preview from that coop's stationary camera displays on screen so the worker can verify the chickens are spread out properly on the table.
  4. Capture Batch 1:
    • Tap 📸 Snap & Count Batch from Camera.
    • The system grabs the frame from the camera, runs YOLO carcass detection, and shows the count (e.g. "Batch 1: 18 carcasses detected").
  5. Capture Subsequent Batches (if needed):
    • Clear the table and place the next batch of chickens.
    • Tap 📸 Snap & Count Next Batch.
    • The system automatically captures capture_02_...jpg, runs detection, and increments the daily total: "Total for K1 Today: 30 carcasses across 2 batches".
  6. All high-res captures and output detection overlays are saved permanently in VIDEOS/cycle7/<Coop>/mortality/<YYYY-MM-DD>/.

Camera Configuration (configs/sites.yaml - Single Source of Truth)

Configure the 1 stationary mortality camera RTSP link per site in configs/sites.yaml:

active_site: site_a  # Active site profile on this machine

sites:
  site_a:
    mortality_camera: "rtsp://admin:admin@192.168.1.100:554/live" # 1 stationary camera for Site A
  site_b:
    mortality_camera: "rtsp://admin:admin@192.168.2.100:554/live" # 1 stationary camera for Site B

(Optional: override via export MORTALITY_CAMERA_URL="rtsp://..." or camera_source in mortality_config.yaml)

Method 2: Command Line Batch Run

Place input photos inside each coop's mortality directory (e.g. ../VIDEOS/cycle7/K1/mortality/, ../VIDEOS/cycle7/K2/mortality/, etc.).

# Run mortality detection across ALL discovered coops (K1..K5, etc.)
./run_mortality_all.sh

# Run for a specific coop
./run_mortality_all.sh K1
# or via CLI:
PYTHONPATH=src venv/bin/python -m chicken_counter.cli mortality --coop K1

# Run across all coops for a specific date
./run_mortality_all.sh 2026-06-18

# Run directly on a specific image file
PYTHONPATH=src venv/bin/python -m chicken_counter.cli mortality -i /path/to/photo.jpg

Output annotated images are saved as output_<original_name>.jpg in each coop's mortality directory. A mortality_report.json is generated for each coop, tagging the coop name and all covered floors (e.g., ["K1-L1", "K1-L2", "K1-L3"]).

Key config options in configs/mortality_config.yaml

Setting Description
conf Detection confidence threshold (0.0–1.0)
iou IoU NMS threshold
min_box_area_px Minimum bounding box area in pixels
dedupe_radius_px Centroid deduplication radius in pixels
two_pass 2x Detect & Refine pipeline (false by default; single-pass direct achieves higher accuracy on farm footage)
classes [0] = chicken only; ignores background/text/equipment

C — Dashboard & API Server

# Start the dashboard on default port 8090 (auto-discovers mortality directories)
./start_dashboard.sh

# (Optional) Override default port to 9090 if port 8090 is already in use
PORT=9090 ./start_dashboard.sh

# (Optional) Specify explicit multiple mortality directories
MORTALITY_DIRS="/path/to/mortality1,/path/to/mortality2" ./start_dashboard.sh

Open in browser: http://localhost:8090 (or custom port if overridden)

Available API endpoints:

Endpoint Description
GET /api/status Live system status, active counting cameras, DOC weight & latest date
GET /stream/<cam> Real-time multipart MJPEG video stream from SHM buffer
GET /api/cameras Live camera list from /dev/shm
GET /api/config Master runtime config (cycle_start_date, doc_weight_g, shm_dir, db_path)
GET /api/config/doc_weight Query / set Day 0 arrival weight (?set=43.5 or POST)
GET /api/config/cycle_start_date Query / set Day 0 cycle date (?set=YYYY-MM-DD or POST)
GET /api/db/summary Total chickens, days, hours across all dates
GET /api/db/history Per-date summary, newest first
GET /api/db/date/<YYYY-MM-DD> Per-camera breakdown for a specific date
GET /api/db/camera/<id> History for a specific camera (CC1, CC2...)
GET /api/db/location/<name> Summary and history for a location
GET /api/db/jobs Batch execution job ledger (status, timing, errors)
GET /api/weight/predictions All predicted flock weights across cycle dates
GET /api/weight/predictions/<date> Fused & per-camera weight predictions for a date
GET /api/weight/coops Coop summary with weight data
GET /api/weight/coop/<coop_id> Weight predictions filtered by coop
GET /api/weight/features/<date> Aggregated metric feature distributions for a date
GET /api/weight/curation/<date>/<camera_id> FatChicken curation & MAD outlier audit
GET /api/mortality/latest Latest mortality detection report (JSON)
GET /api/mortality/history All mortality reports, newest first
GET /api/mortality/coops Coop summary with mortality data
GET /api/mortality/coop/<coop_id> Mortality reports filtered by coop
GET /api/mortality/date/<YYYY-MM-DD> Mortality breakdown for a specific date
GET /api/mortality/cameras Registered stationary cameras per coop
GET /api/mortality/camera/preview Live JPEG snapshot from a coop camera
POST /api/mortality/capture Snap & count batch from stationary camera
POST /api/mortality/upload Upload photo(s) and run carcass detection
POST /api/mortality/scan Re-scan an existing coop directory
POST /api/mortality/delete Delete a mortality scan and recalc totals
GET /api/mortality/image/<filename> Serve annotated output JPEG by filename
GET /shm/<cam>/stats.json Live pipeline stats for a running camera
GET /shm/<cam>/frame.jpg Live frame snapshot from a running camera

See API.md for full response schemas.


D — Install as a System Service (Auto-Start)

Services are user-level systemd units (no sudo). install_service.sh copies the unit files to ~/.config/systemd/user/, runs daemon-reload, enables the timers and the dashboard service, and starts the dashboard:

./install_service.sh

Units installed:

Unit Type Schedule / Role
chicken-counting.service + .timer oneshot + timer run_daily_counting.sh
chicken-weighing.service + .timer oneshot + timer run_daily_weighing.sh at 06:00
chicken-daily-batch.service + .timer oneshot + timer simulate_daily_cycle.sh
chicken-dashboard.service long-running start_dashboard.sh (port 8090)

Useful commands:

systemctl --user status chicken-counting.timer
systemctl --user list-timers
journalctl --user -u chicken-counting.service -n 50

loginctl enable-linger $USER keeps user units running after logout.


6. Database

Results are automatically written to db/chicken_counts.db when db_path is set in the batch YAML. To store results manually from a JSON report:

PYTHONPATH=src venv/bin/python store_results.py \
  ../VIDEOS/cycle7/kandang-atas/2026-06-18/output/counts_2026-06-18.json \
  --location kandang-atas \
  --db db/chicken_counts.db

Export to Excel:

PYTHONPATH=src venv/bin/python export_excel_report.py

7. Storage Lifecycle & Disk Retention

To prevent edge NVMe drives from running out of disk space during multi-week cycles:

A — Automatic Raw Video Purge (Post-Validation)

When enabled in BatchConfig (purge_raw_videos: true) or via CLI:

# Run daily batch and purge raw video once Parquets and MP4s are validated
PYTHONPATH=src venv/bin/python -m chicken_counter.cli batch \
  --config configs/cycle7_batch_optimized.yaml \
  --purge-raw-videos
  • Safety Guard: Deletion is only executed if all output artifacts (counts_*.json, detections_*.parquet, and *_compressed.mp4) pass strict integrity checks.

B — On-Demand Retention Cleanup

Purge raw uncompressed video from historical date folders older than N days (while preserving compressed MP4s and Parquet datasets):

# Preview what would be cleaned up (dry-run)
PYTHONPATH=src venv/bin/python -m chicken_counter.cli cleanup --days 7 --dry-run

# Execute cleanup across all coops & floors
PYTHONPATH=src venv/bin/python -m chicken_counter.cli cleanup --days 7

8. Moving the Project to Another Machine

  1. Delete the venv/ folder before copying:
    rm -rf venv/
    
  2. Copy the entire project folder to the new machine.
  3. Update the WorkingDirectory and ExecStart paths in the chicken-*.service unit files (they hardcode %h/Project_FOLDER/.Codes/chicken-counting-sukawarna-det), then reinstall via ./install_service.sh.
  4. Recreate the venv on the new machine:
    python3 -m venv venv
    venv/bin/pip install -r requirements.txt
    
  5. All configs and Python code use relative paths and will work without any other changes.

9. Single-Machine Per-Site Deployment (ROG NUC)

Each farm site has 1 dedicated edge machine (ROG NUC) that handles only that site's cameras:

┌─────────────────────────────────────────────────────────┐
│ Machine A (ROG NUC at Site A)                           │
│ • Handles: 5 coops x 2 floors = 10 floors (K1..K5)      │
│ • Handles: 1 stationary mortality camera (site_a)       │
│ • Config: active_site: site_a (or export FARM_SITE=site_a)│
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ Machine B (ROG NUC at Site B)                           │
│ • Handles: 3 coops x 3 floors = 9 floors (K1..K3)       │
│ • Handles: 1 stationary mortality camera (site_b)       │
│ • Config: active_site: site_b (or export FARM_SITE=site_b)│
└─────────────────────────────────────────────────────────┘

📋 Step-by-Step Production Deployment Checklist

Follow these 6 steps in order when setting up a new machine or starting a new flock cycle on a farm:

Step 1: Set Active Farm Site

In configs/sites.yaml, set the active site profile for this physical machine:

active_site: site_a   # 'site_a' (5 coops x 2 floors) or 'site_b' (3 coops x 3 floors)
auto_discover: false

(Or set export FARM_SITE=site_a in ~/.bashrc)

Step 2: Configure Stationary Mortality RTSP IP Camera

In configs/sites.yaml, replace the placeholder RTSP URL with the actual stationary IP camera stream at this site:

sites:
  site_a:
    mortality_camera: "rtsp://admin:password@192.168.1.100:554/live"

Step 3: Generate & Verify Floor Configs

Run the automatic config synchronization tool to generate/verify all floor YAMLs under configs/floor_config/:

PYTHONPATH=src venv/bin/python -m chicken_counter.cli sync-configs --site site_a

This ensures each floor (K1-L1.yaml through K5-L2.yaml) is configured with optimal camera calibrations.

Step 4: Place Raw Videos in Production Directory Hierarchy

⚠️ Note on Test Folders: Folders such as VIDEOS/cycle7/kandang-atas and FULL_Cycle_Kandang_Atas_Test are benchmarking test datasets. In production, videos must follow the canonical Coop-Floor structure:

../VIDEOS/cycle7/
├── K1-L1/
│   └── 2026-06-18/
│       ├── K1-L1_cam1_2026-06-18_120056.mp4
│       ├── K1-L1_cam2_2026-06-18_120456.mp4
│       ├── K1-L1_cam3_2026-06-18_121012.mp4
│       └── K1-L1_cam4_2026-06-18_121530.mp4
├── K1-L2/2026-06-18/...
└── K5-L2/2026-06-18/...

Step 5: Initialize Day 0 Remotely from Central Dashboard (REST API)

When chicks arrive, the Central Dashboard configures the edge machine remotely via REST API (no local on-screen UI setup wizard required):

# 1. Set Day 0 DOC arrival date (persists atomically to YAML configs)
curl -X POST http://<edge-ip>:8090/api/config/cycle_start_date \
  -H "Content-Type: application/json" \
  -d '{"cycle_start_date": "2026-08-28"}'

# 2. Set Day 0 manual scale arrival baseline weight in grams
curl -X POST http://<edge-ip>:8090/api/config/doc_weight \
  -H "Content-Type: application/json" \
  -d '{"doc_weight_g": 43.5}'

Machine auth (planned): The central schema (ERD.md) defines an API_KEYS table so edge/client machines can authenticate via request header instead of a username/password session. No edge endpoint manages these keys yet — provision them directly in the central dashboard and pass the key via header on the calls above once supported.

Step 6: Daily Batch Counting & Mortality Operations

Run automated processing across all coops and floors:

# Process all floors for today (or pass a specific date: ./run_all_coops.sh 2026-06-18)
./run_all_coops.sh

# Run mortality carcass detection across all coops
./run_mortality_all.sh

📸 Mortality Web UI: Production Workflow vs. Testing

The Web Dashboard (http://localhost:8090) provides dedicated tooling for carcass inspection:

  1. Production Standard — Stationary RTSP IP Camera:

    • Live Camera Preview: View the real-time stationary RTSP camera stream directly in the browser modal (GET /api/mortality/camera/preview).
    • Virtual Snap Button: Click 📸 Snap & Count Next Batch (POST /api/mortality/capture). The server captures a high-resolution frame from the fixed, calibrated stationary camera, timestamps and stores it into VIDEOS/cycle7/<Coop>/mortality/<Date>/, runs YOLO carcass detection, and updates the daily mortality total.
    • Why: Fixed camera geometry and controlled lighting eliminate angle distortions and prevent accidental duplicate counting.
  2. Testing & QA Tool — Manual Photo Upload:

    • For Testing / Benchmarking Only: The web interface allows manual file uploads (e.g. smartphone photos or historical test datasets) for developer validation and model testing.
    • ⚠️ Operational Rule: Manual phone photo uploads should NOT be used by field operators in daily production to prevent false positives and duplicate carcass tallies.

10. Weight Estimation, Curation & Storage System

The edge chicken counting pipeline aggregates physical metric measurements and predicts chicken weights during daily counting runs. Full architecture and schema mapping are documented in ERD.md.

Day 0 vs. Day 1+ Lifecycle Rule

  • Day 0 (cycle_start_date): Day-Old Chicks (DOC) arrival date. Counting ONLY to establish starting inventory headcount. Vision weight estimation begins at Cycle Day 1 (as each cycle has its own specific DOC arrival weigh-in).
  • Day 1+: Counting AND Weight Estimation runs daily across all floor camera feeds.

Data Architecture & Storage Files

Each daily run saves the following datasets into the floor's output directory (../VIDEOS/cycle7/<coop>/<floor>/<date>/output/):

File Format Description
detections_{date}.parquet Parquet + CSV fallback Combined multi-camera detection dataset across all cameras for that date (33 columns including all morphometrics & quality flags).
detections_{date}_{camera_id}.parquet Parquet + CSV fallback Per-camera detection dataset (1 row per counted track with pixel bbox, bbox_area, area_cm2, minor_axis_cm, major_axis_cm, eccentricity, aspect_ratio, equiv_diameter_cm, perimeter_cm, is_validated, is_outlier, outlier_reason, kept_for_aggregation).
curation_{date}_{camera_id}.json JSON Curation audit summary (raw tracks, validated, saved, outliers discarded, rejection rate, median area).
cage_day_features.parquet Parquet + CSV fallback Aggregated statistical distribution (mean, median, p25, p75, std, cv, iqr) per camera and FUSED.
predictions_{date}.parquet Parquet + CSV fallback Audited weight predictions (predicted_weight_g, doc_weight_g, gompertz_baseline_g, vision_gain_g, residual_g, gbm_model_used, minor_axis_cm_median, major_axis_cm_median, frequency, excluded, uniformity, dominant_camera, rejection_rate).

FatChicken Curation & MAD Outlier Elimination

  1. Track Deduplication: Exactly one best observation per track_id (highest detection confidence upon count validation).
  2. MAD Z-Score Outlier Filter: z = 0.6745 \times (x - \text{median}) / \text{MAD} on bbox_area_cm2.
    • Age \le 10 days: |z| \le 3.0
    • Age 11\dots 24 days: |z| \le 2.5
    • Age > 24 days: |z| \le 2.0
    • Active only when sample count N \ge 30.
  3. Multi-Camera Fusion: Weighted aggregation across all cameras with dominant camera tracking.
  4. Database Persistence: Automatic storage into SQLite batch_runs table (db/chicken_counts.db).

Sibling Weighing Repo

Production daily weights run in /home/asus/Project_FOLDER/.Codes/chicken-weighing-sukawarna: run_daily_weighing.sh (06:00 timer) delegates to its weighing_inference.py, which reads this repo's consolidated parquet datasets and upserts into batch_runs. Its best_weight_model.pkl (Hybrid Allometric-RF) is also the active predictor inside growth_model.predict_chicken_weight when present. See README "Weighing Integration".


11. Multi-Sheet Excel Reporting

Generate structured Excel reports containing count summaries, camera performance, growth charts, and raw batch logs:

PYTHONPATH=src venv/bin/python export_excel_report.py

Outputs db/chicken_counts_report.xlsx containing:

  1. Daily Summary: Overall headcount KPIs, Avg Flock Weight (g), Median Bird Area (cm^2), Daily pivot table, and count bar chart.
  2. Camera Summary: Per-camera metrics (Avg Pred Weight (g), Median Area (cm²), Median Minor Axis (cm), Median Major Axis (cm), Valid Samples).
  3. Weight & Growth Analytics: Day 1+ growth ledger with headcount, weight samples, area/minor/major medians, predicted weight, Gompertz baseline, and an embedded Growth Trajectory Line Chart.
  4. Raw Batch Runs: Complete granular logs for every camera run.
  5. Configurations: Full parameters, spatial calibrations (px_per_cm), and Gompertz growth models.