- 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
36 KiB
36 KiB
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 needsmake setup); model table marks.ptdefault (onnxruntime not installed); Day-0 default2026-10-01, stages 0–14 early / 15+ mid;--task count/--task weight/--task alldocumented; 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), andweight_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 (matchesaggregation.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, typehybrid_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:
ed0c64acheckpoints WAL sostorage_lifecyclepurges actually land in the committed.dbfile.
🔀 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_atrefreshed on upsert, defaultFAILEDif never completed); surfaced viaGET /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 singleCYCLE_WEIGHT_DIR_NAMEconstant shared byweight/storage.py,weight/daily_size_comparison.py, and thedashboard.pycoop/location skip-list, so it cannot half-rename again). - Merged CSVs dropped by default:
full_cycle_detections.csvwas 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-csvrestores the CSV exports. Per-date daily exports keep writing CSV as before. simulate_daily_cycle.shconsolidates automatically after each successful daily batch (noexecon 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.xlsxgenerated. 49 unit tests pass.
⚡ True Multi-Process Parallel Cameras & Daily Full-Cycle Simulation (2026-10-01)
parallel_processesimplemented for real (batch_runner.py): the mode previously fell through to the serial loop (onlyhybrid/tensor_batchinghad dispatch branches). It now runs all cameras concurrently throughProcessPoolExecutor(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 underFULL_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>/, locationK1-L1(coopK1), GPU preflight skip, skip-if-source-missing. (Correction 2026-10-14: never hadflockor 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_max15→10, mid-cycleday_min16→11,min_box_area_px100→50, addediou: 0.7); detection weights.onnx→.pt(onnxruntime not installed).
🗺️ ERD Synchronized with Central Dashboard ERD (v31.4.5)
- Full sync of
ERD.mdagainstERD_central_dashboard.json(now deleted, single source of truth isERD.md):USER_ACCESS: replacedpassword_hash varchar(255)with centralpassword varchar(30)(hashed in backend); addeddisplay_name,last_login,is_superuser,is_staff,is_active.CYCLES:end_dateis now nullable per central; addedproposed_end_date,close_requested_at,close_requested_by_id(FK\toUSER_ACCESS),feed_initial_balance,feed_initial_balance_date.MANUAL_INPUT: addedfeed_out_manualandfeed_out_manual_totalalongside existingfeed_in_*/feed_use_*fields.API_KEYS(new table): machine credentials for header-based API auth (id,user_idFK,name,prefix,key_hash,is_active,last_used_at,created_at,updated_at); related asUSER_ACCESS ||--|{ API_KEYS.- Relationships: added
CYCLES }|--o| USER_ACCESS(close_requested_by) edge; Tier 1 description now documentsAPI_KEYSand the cycle close-out workflow.
📖 Documentation Sync (Edge-Facing Docs)
CENTRAL_DASHBOARD_INTEGRATION.md(guide for central devs consuming the edge API):- Added
API_KEYSmachine-credential note to the farm hierarchy section (central-only, header auth, no edge endpoint yet). - Added Section D (
CYCLESclose-out & feed-balance fields), Section E (API_KEYStable mapping), and Section F (MANUAL_INPUTfeed-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 onCHICKEN_WEIGHT; cycle-level fields live on centralCYCLES).
- Added
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_KEYStable (header auth, provisioned centrally, no edge endpoint yet).
- Completed the Section C endpoints table with the newer coop/weight/mortality routes (
API.md: verified current — correctly documents edge-only APIs (already includescoop/locationfiltering); 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.K1for Kandang 1) and floor location (e.g.K1-L1ortest-coop-1) acrossaggregate_camera_featuresandbuild_cage_day_features_and_predictions. - Added automatic coop derivation via
get_coop_for_location(location)when only floor/location is provided. - Included
coopandlocationin all individual camera records, theFUSEDflock record, andcage_day_features. - Extended intermediate observation Parquet schema (
DETECTION_PARQUET_COLUMNS) instorage.pywithcoopandlocation. - Added
coopandlocationtracking insave_curation_summarytocuration_{date}_{camera_id}.json.
- Enhanced weight pipeline (
-
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/predictionswhere 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), anduniformity(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 returnpredicted_weight_g,area_cm2_median,cycle_day,coop,frequency,excluded, anduniformityfor all cameras, matching Central Dashboard specifications. - FUSED Flock Weight Persistence: Updated
batch_runner.pyandstore_results.pyto persist overallFUSEDflock predictions into SQLitebatch_runstable withcamera_id='FUSED'.
- New Endpoints:
-
Documentation & ERD Updates:
- Updated
ERD.md: AddedcoopandlocationtoDETECTIONS,CHICKEN_WEIGHT,CHICKEN_COUNTING, andBATCH_RUNS. - Updated
CENTRAL_DASHBOARD_INTEGRATION.md: Addedcoopandlocationfield mappings to TableCHICKEN_WEIGHTand updated Section 4.4 examples. - Updated
API.md: Documented new coop endpoints, query parameters, and updated Parquet intermediate schema table.
- Updated
[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()andenforce_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 standalonechicken-counter cleanupsubcommand.
- Implemented
🔌 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;, andPRAGMA busy_timeout=60000;. - Added explicit WAL truncate checkpointing (
checkpoint_sqlite_wal()) to guarantee all transactions in-walare consolidated into the primary.dbfile. - 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.
- Standardized SQLite connections with
⚖️ 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_gacross 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_gindashboard.pyand includeddoc_weight_gin/api/status.
- Implemented configurable
🛠️ Cross-Platform Portability & Dependency Hardening
- Production
requirements.txtCurated (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) andonnxruntime(ARM/macOS). - Pinned stable, production-grade cross-platform dependencies across all target platforms (Linux x86, Jetson ARM64, Docker, Windows/macOS).
- Removed all hardcoded absolute local Jetson file wheel links (
📐 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}) withcv2.minAreaRectfallback. - Guarantees valid major/minor axis estimation even on irregular, non-convex, or degenerate polygon masks where
cv2.fitEllipse(< 5 points) previously failed.
- Enhanced
🌐 Dashboard Frontend Syntax Fix
- JavaScript Template Placeholder (
templates/index.html):- Wrapped
{{ poll_ms }}withNumber("{{ poll_ms }}") || 1000on line 456 to eliminate IDE static syntax diagnostics while maintaining dynamic polling rate rendering.
- Wrapped
📖 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/deleteandDELETE /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_countandtotal_imagesinmortality_report.json.
- Implemented
🎭 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).
- Extracts true physical body surface area (
- Updated BoT-SORT tracker (
src/chicken_counter/tracking.py) to map and forward instance segmentation mask polygons (result.masks.xy) directly toTrackObservation.
- Implemented
- 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.yamlwithcalibration.use_mask_geometry: true. - Added
test_run_folder/test_run_full_cycle7_segmentation_masking.shsupporting toggleable geometry modes (--maskvs--bbox).
- Added
- SQLite WAL Concurrency Hardening (
src/chicken_counter/batch_runner.py,store_results.py):- Configured
PRAGMA journal_mode=WAL;,PRAGMA busy_timeout=60000;, andPRAGMA synchronous=NORMAL;across all database connection routines to eliminate database lock contention across simultaneous worker completions.
- Configured
📦 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 insideweight_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-cameraFUSEDsummaries. - 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\times5 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\times5 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, andarea_vs_day35_pct.per_camera: Complete 196-row camera-by-camera breakdown (49 dates\times4 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.
- Implemented
-
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.
- Fixed race condition where parallel per-camera worker processes (
-
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.shandtest_run_folder/test_run_full_cycle7.sh. - Cleaned up duplicate runner scripts in root and moved all active log files into
test_run_folder/.
- Added
📦 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}.parquetand daily combineddetections_{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, andcycle_day. - Implemented strict pandas type enforcement (
standardize_detection_dataframe) with nullable integers and zero string-corrupted numerics.
- Saves intermediate datasets
- 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=2concurrency for safe PyTorch instance segmentation processing.
- Added dedicated segmentation configuration and batch execution script with
⚖️ 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})) andmajor_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-cameraFUSEDrecords.
- Added
- SQLite Database Schema Migration & Weight Storage (
batch_runner.py,dashboard.py,store_results.py):- Extended
batch_runstable 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.
- Extended
- Cycle Day 0 Rule Enforcement (
batch_runner.py,growth_model.py):- Explicitly defined
cycle_start_dateas Day 0 (DOC arrival baseline 42.0g). - Weight counting and growth curves strictly begin at Cycle Day 1+, skipping weight estimation on Day 0.
- Explicitly defined
- 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), andValid 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.
- Sheet 1 (Daily Summary): Added KPI cards for Average Flock Weight (
[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
CalibrationConfigwith configurablepx_per_cmper 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, andperimeter_cm.
- Implemented
- 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 10days:|z| \le 3.011\dots 24days:|z| \le 2.5> 24days:|z| \le 2.0- Automatically activates when sample count
N \ge 30.
- Deduplicated per-track observations to exactly one best observation per
- 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
FUSEDsummary row weighted by valid sample counts.
- Computes distribution metrics (
- 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(orresidual_g),n_valid_samples, anddominant_camera.
- Standardized Storage & Export Handlers (
src/chicken_counter/weight/storage.py):- Per-track observations:
detections_{date}_{camera_id}.parquet(and.csvfallback). - Curation summary:
curation_{date}_{camera_id}.json. - Cage day features:
cage_day_features.parquet(and.csvfallback). - Weight predictions:
predictions_{date}.parquet(and.csvfallback).
- Per-track observations:
🚀 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.0withCUDAExecutionProviderachieving ~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.pyintact for on-demand TensorRT engine exports.
- Migrated counting detection model to ONNX weights:
- TensorRT Engine Verification & Auto-Recompilation Toggle (
config.py,tracking.py,batch_runner.py,cli.py):- Added
verify_engine: bool = Falseconfiguration field toDetectionConfigand batch YAML configurations. - Bypassed mandatory startup engine test inference and auto-recompilation loops by default for instantaneous pipeline initialization.
- Added
--verify-engineCLI flag tochicken-counter runandchicken-counter batchto enable manual engine validation and recompilation on-demand. - Maintained runtime fail-safe fallback in
DetectionTrackerthat gracefully loads matching.ptmodel weights if an invalid.engineis encountered.
- Added
- 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.yamlsupporting:- Site A: 5 coops
\times2 floors = 10 floors (K1-L1..K5-L2) with 1 dedicated stationary mortality camera (site_a). - Site B: 3 coops
\times3 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.
- Site A: 5 coops
- Added
sitemetadata tagging in batch reports and mortality JSON summaries ("site": "site_a" | "site_b"). - Populated
run_all_coops.shmaster 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).
- Implemented static multi-site farm configuration in
- Auto-Discovery Toggle (
auto_discover: falseby 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-discoverCLI flag tochicken-counter batch,chicken-counter mortality, andchicken-counter sync-configsto explicitly opt-in to filesystem scanning. - Updated
configs/mortality_config.yamlandconfigs/cycle7_batch_optimized.yamlwithauto_discover: false.
- Disabled dynamic unconstrained directory walks across
- Reporting & Unit Test Coverage (
export_excel_report.py,tests/test_tracking.py,tests/test_flexible_discovery.py):- Updated
export_excel_report.pyconfiguration metadata sheet to reflect PyTorch.ptmodel defaults. - Added automated unit tests covering
verify_enginetoggle flows, Site A/B profiles, and site-level mortality camera lookups (all 18 unit tests passing).
- Updated
[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).
- Implemented dynamic farm discovery engine (
- 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(...)andmortality_report.json. - Created
run_all_coop_mortality(...)and./run_mortality_all.shto batch-process mortality detection across all discovered coops with summary reports. - Added CLI flags
--coop <ID>and--all-coopstochicken-counter mortality.
- Added coop and covered floor metadata resolution in
- 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/captureendpoint to grab high-res still frames from a coop's stationary camera, timestamp and save them intoVIDEOS/cycle7/<Coop>/mortality/<YYYY-MM-DD>/, and run YOLO carcass detection. - Added
GET /api/mortality/camera/previewto stream live snapshot previews to workers in the webapp before snapping. - Added
GET /api/mortality/camerasto 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.
- Added support for dedicated per-coop stationary cameras (RTSP IP cameras, HTTP snapshots, and USB cameras) configured in
- Dynamic Floor Config Synthesis & Sync Tool (
config.py,discovery.py,cli.py):- Implemented
load_or_synthesize_floor_configallowingchicken-counter batch --floor <ID>to dynamically synthesize settings fromcycle7_batch_optimized.yamlin memory without requiring a physical YAML file. - Implemented
sync_floor_configsand CLI commandchicken-counter sync-configsto automatically scanVIDEOS/and generate boilerplate floor YAML configs for newly added coops/floors. - Updated
run_all_coops.shto dynamically discover all floors directly fromVIDEOS/orconfigs/floor_config/and seamlessly run physical YAMLs or virtual in-memory configs.
- Implemented
- 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.
- Implemented dynamic sliding window process pool with default
- Port 8090 Migration & Ecosystem Integration (
dashboard.py,start_dashboard.sh,chicken-dashboard.service):- Migrated the default web dashboard port from
8080to8090across the entire codebase, systemd service units, and documentation to prevent port collisions with other farm systems (e.g.fatchicken).
- Migrated the default web dashboard port from
- 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
.ptmodel fallback intracking.pyif a.engineTensorRT file fails to load or execute. - Fixed Ultralytics
BOTSORT/ByteTracktracker compatibility for CUDA box tensors by ensuring.cpu()conversion before numpy concatenation.
- Added post-compilation test inference verification in
- 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_idinDetectionTracker. - Fixed tracker state bleed and track ID jumping in
tensor_batchingand multi-camera batch modes when camera frames are processed or when active camera sets shrink. - Added unit test suite
tests/test_tracking.pycovering multi-stream tracker isolation.
- Implemented per-camera independent tracker instances keyed by
- Multi-Floor Script Syntax (
run_all_coops.sh):- Resolved fatal
syntax error: unexpected end of filecaused by missingdonein floor configuration discovery loop. - Expanded config discovery pattern from
K*-L*.yamlto*.yamlto support custom named coops (e.g.kandang-atas.yaml).
- Resolved fatal
- Excel Report Empty Result Crash (
export_excel_report.py):- Added empty DataFrame pre-check to prevent
IndexErrorwhen exporting reports for dates with no batch runs or newly initialized databases.
- Added empty DataFrame pre-check to prevent
- Multi-Threaded SQLite Concurrency (
dashboard.py):- Replaced global single
sqlite3connection with thread-local connections (threading.local()) to prevent cursor collision and race conditions across concurrent HTTP worker threads. - Enabled
PRAGMA busy_timeout = 5000andPRAGMA journal_mode = WALto avoid database lock conflicts during batch processing writes.
- Replaced global single
- Editable Package Installation:
- Configured
pip install -e .in environment setup to resolvechicken_counterimports and enable automatic unit test discovery without manualPYTHONPATHprefixes.
- Configured
⚡ Performance & Optimization
- Secondary Database Indexing (
dashboard.py,batch_runner.py,store_results.py):- Added
idx_batch_date,idx_batch_camera, andidx_batch_locationindexes onbatch_runsto accelerate single camera, location, and date historical queries.
- Added
- Atomic Config Persistence (
dashboard.py):- Added
_config_write_lockand atomic temporary file replacement (os.replace) in_persist_cycle_start_dateto prevent race conditions or half-written YAML reads.
- Added
- 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.
- Added an idle keepalive heartbeat (
- 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.
- Replaced repetitive
📁 Configuration & Directory Structure
- Floor Configuration & Skeleton Paths:
- Created
configs/floor_config/kandang-atas.yamlextendingcycle7_batch_optimized.yaml. - Initialized missing directory skeletons for coops
K1-L1throughK5-L2under../VIDEOS/cycle7/.
- Created
- Documentation:
- Updated
README.mdandRUN.mdwith editable install steps and updated project layout.
- Updated