Files
..

Chicken Weighing System (Sukawarna)

Automated computer vision and allometric growth model pipeline for flock weight estimation and uniformity analytics.


📂 Project Directory Structure

chicken-weighing-sukawarna/
├── 📁 models/                     # Trained ML & allometric model artifacts (.pkl)
│   ├── best_weight_model.pkl              # Active production hybrid allometric-RF model
│   ├── best_weight_model_mask.pkl         # Segmentation mask-trained hybrid model
│   ├── candidate_weight_models.pkl        # Candidate model evaluations (bbox)
│   └── candidate_weight_models_mask.pkl   # Candidate model evaluations (mask)
│
├── 📁 data/                       # Parquet datasets and scale references
│   ├── full_cycle_detections.parquet      # Raw cycle detection features
│   ├── full_cycle_predictions.parquet     # Bounding-box daily weight predictions
│   ├── full_cycle_predictions_mask.parquet# Segmentation mask daily predictions
│   ├── historical_weights_avg.csv         # Physical scale reference benchmarks
│   ├── full_cycle_mask_comparison.csv     # Bbox vs mask daily comparisons
│   ├── predictions_export.csv             # Exported prediction summary (CSV)
│   └── predictions_export.parquet         # Exported prediction summary (Parquet)
│
├── 📁 scripts/                    # Model training, testing & comparison scripts
│   ├── train_and_compare_models.py        # Model benchmarking suite (bbox)
│   ├── train_and_compare_models_mask.py   # Model benchmarking suite (mask)
│   ├── test_segmentation_weighing.py      # Mask inference & feature extraction
│   └── compare_cycle_masks.py             # Mask vs bbox analysis & CSV export
│
├── 📁 reports/                    # Benchmark metrics, logs & visualizations
│   ├── model_benchmark_summary.csv        # Cross-validation MAE / MAPE rankings
│   ├── model_benchmark_summary_mask.csv   # Segmentation cross-validation metrics
│   ├── model_evaluation_comparison.csv    # Day-by-day error analysis
│   ├── model_evaluation_comparison_mask.csv
│   ├── model_extrapolation_comparison.csv # Unseen late-cycle extrapolation
│   ├── segmentation_comparison_report.csv # Uniformity & weight diffs (Days 0-12)
│   ├── train_log.txt / train_log_mask.txt # Training console outputs
│   ├── weight_prediction_plot.png         # Growth curves vs manual scales (bbox)
│   ├── weight_prediction_plot_mask.png    # Growth curves vs manual scales (mask)
│   └── seg_vs_bbox_overlay.jpg            # Visual verification overlay sample
│
├── 📁 services/                   # Systemd service units & automation shell runners
│   ├── chicken-weighing.service           # Daily batch weighing runner unit
│   ├── chicken-weighing.timer             # Daily trigger timer (06:00 WIB)
│   ├── chicken-weighing-dashboard.service # Dedicated live dashboard API (Port 8095)
│   ├── run_daily_weighing.sh              # 06:00 WIB execution script
│   ├── start_weighing_dashboard.sh        # API & dashboard server launcher
│   ├── run_weighing_segmentation_test.sh  # Test runner for mask pipeline
│   └── install_service.sh                 # Systemd registration script
│
├── 📁 docs/                       # Technical specifications & breakdown context
│   └── weighing_system_plan_breakdown.md  # Algorithms, MAD Z-score, uniformity formulas
│
├── 📁 db/                         # Local database storage
│   └── weighing_predictions.db           # SQLite database for standalone API cache
│
├── weighing_inference.py          # Primary production inference & sync pipeline
└── weighing_dashboard.py          # Port 8095 lightweight API and web dashboard

For seamless interoperability with upstream repositories (such as chicken-counting-sukawarna-det) and existing systemd user services, root-level symlinks are maintained:

Root Symlink Destination Purpose
best_weight_model.pkl models/best_weight_model.pkl Loaded by growth_model.py and external pipelines
run_daily_weighing.sh services/run_daily_weighing.sh Targeted by chicken-weighing.service ExecStart
start_weighing_dashboard.sh services/start_weighing_dashboard.sh Targeted by chicken-weighing-dashboard.service
weighing_system_plan_breakdown.md docs/weighing_system_plan_breakdown.md Context & presentation documentation
full_cycle_detections.parquet data/full_cycle_detections.parquet Dataset cache
full_cycle_predictions.parquet data/full_cycle_predictions.parquet Daily predictions
full_cycle_predictions_mask.parquet data/full_cycle_predictions_mask.parquet Segmentation daily predictions
test_segmentation_weighing.py scripts/test_segmentation_weighing.py Root entry point for the segmentation test runner
train_and_compare_models.py scripts/train_and_compare_models.py Model benchmarking suite (bbox)
train_and_compare_models_mask.py scripts/train_and_compare_models_mask.py Model benchmarking suite (mask)
historical_weights_avg.csv data/historical_weights_avg.csv Physical scale reference benchmarks
predictions_export.csv data/predictions_export.csv Latest prediction export (CSV)
predictions_export.parquet data/predictions_export.parquet Latest prediction export (Parquet)
install_service.sh services/install_service.sh Systemd registration script (must still be run as services/install_service.sh, see Operational Footguns)

🚀 Key Commands

Daily Weighing Inference

./run_daily_weighing.sh            # must run from repo root (symlink form)

Run Segmentation Mask Test

./run_weighing_segmentation_test.sh  # must run from repo root (symlink form)

Install / Update Systemd Services

services/install_service.sh          # must run from services/ (NOT via root symlink)

Check Dashboard & API Status

systemctl --user status chicken-weighing-dashboard.service
curl -s http://127.0.0.1:8095/api/weight/predictions/$(date +%F)

📦 Dependencies

No requirements.txt is shipped; dependencies per entry point:

Entry point Third-party Stdlib only extras
weighing_inference.py numpy, pandas, pyarrow pickle, sqlite3, os, sys, pathlib
weighing_dashboard.py — (stdlib only) http.server, json, sqlite3, urllib.parse
scripts/train_and_compare_models.py, train_and_compare_models_mask.py numpy, pandas, scikit-learn, scipy, matplotlib —
scripts/test_segmentation_weighing.py, compare_cycle_masks.py opencv-python, ultralytics, pandas, numpy —

Stages 1–2 (YOLO detection, px→cm calibration, MAD curation) run in the sibling repo chicken-counting-sukawarna-det and are not needed here — production only consumes the curated parquet.


⚙️ Installation & Services

Systemd user units (all run as your user, no root):

Unit Type Schedule Executes
chicken-weighing.timer timer *-*-* 06:00:00 (Persistent=true) chicken-weighing.service
chicken-weighing.service oneshot daily 06:00 WIB root symlink run_daily_weighing.sh → weighing_inference.py
chicken-weighing-dashboard.service simple, Restart=always always-on root symlink start_weighing_dashboard.sh → weighing_dashboard.py on port 8095

Install:

services/install_service.sh    # copies units, daemon-reload, enables timer + dashboard
loginctl enable-linger $USER   # keep user units alive across logout (already Linger=yes on production host)

Uninstall:

systemctl --user disable --now chicken-weighing.timer chicken-weighing-dashboard.service
rm ~/.config/systemd/user/chicken-weighing.{service,timer} ~/.config/systemd/user/chicken-weighing-dashboard.service
systemctl --user daemon-reload

🌐 API Endpoints (port 8095)

Route Returns
GET / Dashboard HTML UI
GET /health {"service","status","flock","model"} liveness probe
GET /api/weight/predictions[?coop=][&location=] {"predictions":[…],"total_records"}
GET /api/weight/predictions/<YYYY-MM-DD>[?coop=][&location=] Fused record + frequency, excluded, uniformity
anything else 404 JSON
curl -s http://127.0.0.1:8095/api/weight/predictions/2026-10-13

🗄️ Database Schema

Primary DB — db/weighing_predictions.db (this repo), table weight_predictions (one fused row per date, upserted ON CONFLICT(date)):

CREATE TABLE weight_predictions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    date TEXT UNIQUE,               -- YYYY-MM-DD, remapped to production calendar
    cycle_day INTEGER,
    coop TEXT, location TEXT, camera_id TEXT,   -- literals: 'K1','K1-L1','FUSED'
    predicted_weight_g REAL,
    area_cm2_median REAL, minor_axis_cm_median REAL, major_axis_cm_median REAL,
    uniformity REAL, frequency INTEGER, rejection_rate REAL,
    doc_weight_g REAL,              -- Day-0 DOC reference weight (32.0)
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Central DB — sibling repo chicken-counting-sukawarna-det/db/chicken_counts.db, table batch_runs (shared with counting; weighing rows are keyed on date + location in code — the table itself carries UNIQUE(date, location, camera_id) — and fill cycle_day, area_cm2_median, minor_axis_cm_median, major_axis_cm_median, predicted_weight_g, n_weight_samples, rejection_rate, uniformity; camera_id is written only on first insert — weighing_inference.py:192-223).

Disk side effects — each daily run also rewrites every predictions_*.parquet / predictions_*.csv found under SIM_ROOT (/home/asus/Project_FOLDER/.Codes/VIDEOS/cycle7/FULL_CYCLE_1_FLOOR_SIM) and the counting repo (weighing_inference.py:229-266), plus data/predictions_export.{csv,parquet} in this repo.


🔁 Cross-Repo Dependencies

  • This repo consumes data/full_cycle_detections.parquet, produced by the counting repo's weight curation (chicken-counting-sukawarna-det/src/chicken_counter/weight/storage.py → <dataset_root>/cycle_weight_parquet_data/full_cycle_detections.parquet). No automatic sync: the copy in data/ must be refreshed manually when retraining.
  • This repo is consumed by the counting repo:
    • chicken-counting-sukawarna-det/src/chicken_counter/weight/growth_model.py:101 loads the root symlink best_weight_model.pkl by absolute path.
    • chicken-counting-sukawarna-det/run_daily_weighing.sh invokes this repo's weighing_inference.py by absolute path — a manual master runner; the live 06:00 schedule comes from this repo's chicken-weighing.timer instead.
  • All cross-repo references are hardcoded absolute paths (e.g. weighing_inference.py:12-23), so the repo must stay at /home/asus/Project_FOLDER/.Codes/chicken-weighing-sukawarna.

⚠️ Operational Footguns

  1. Which dir you run scripts from matters. run_daily_weighing.sh, start_weighing_dashboard.sh, and run_weighing_segmentation_test.sh resolve sibling .py files relative to their own location — those .py files exist only at the repo root, so the scripts must run from the root symlink form (./run_daily_weighing.sh). Running them as services/run_daily_weighing.sh fails (looks for services/weighing_inference.py, which does not exist). Conversely, install_service.sh copies the three systemd units from its own directory, and those units exist only in services/ — so install must run as services/install_service.sh; the root symlink form ./install_service.sh fails.
  2. Absolute-path coupling. weighing_inference.py:12-23 hardcodes BASE_DIR, CENTRAL_DB_PATH, and SIM_ROOT; moving or renaming either repo breaks the daily run and the central-DB sync.
  3. UI label vs actual model. Dashboard pages and /health say "Random Forest" (weighing_dashboard.py:5,186,272,382) but the deployed models/best_weight_model.pkl is the Hybrid Allometric-RF (model_name = "Hybrid Allometric-RF"); same artifact, stale label.
  4. rejection_rate is a placeholder. weighing_inference.py:133 writes 0.02 for every row; the API's excluded is derived from it, not from real MAD-curation stats.
  5. Day 0 bypasses the model. Cycle-day-0 rows are forced to 32.0 g (weighing_inference.py:101-102).
  6. Two 06:00 timers exist. chicken-weighing.timer (this repo) and chicken-counting.timer (counting repo, also 08:00) fire independently; the counting timer runs run_daily_counting.sh only — weighing runs solely via this repo's timer.