feat: migrate chicken counting to ONNX, add 2-site deployment (19 floors), and auto-discovery toggle
This commit is contained in:
1 parent
56bbc50102
commit
d033c4fe6a
23 files changed
+567
-114
No files matched your search
+29
-1
@@ -2,7 +2,35 @@
|
||||
|
||||
All notable changes to the `chicken-counting-sukawarna-det` project are documented in this file.
|
||||
|
||||
## [Unreleased] - 2026-08-20
|
||||
## [Unreleased] - 2026-08-21
|
||||
|
||||
### 🚀 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`)**:
|
||||
|
||||
@@ -237,16 +237,15 @@ for tuning.
|
||||
- The optical-flow trigger is vision-first, though the config structure leaves room for
|
||||
a future controller/encoder integration path
|
||||
|
||||
## Cross-Machine Portability & Self-Healing Engine Auto-Recompilation
|
||||
## Cross-Machine Portability & Model Compatibility
|
||||
|
||||
TensorRT `.engine` files are compiled specifically for the host GPU architecture and TensorRT version. When copying the project to a different machine (e.g. from Jetson to NUC or across different RTX GPUs):
|
||||
The pipeline supports ONNX (`.onnx`), PyTorch (`.pt`), and hardware-accelerated TensorRT (`.engine`) models:
|
||||
|
||||
- **Automatic Compatibility Check**: `src/chicken_counter/engine_utils.py` runs a fast health check on the specified `.engine` before counting starts.
|
||||
- **Self-Healing Recompilation**: If an incompatibility (e.g. platform tag mismatch or different compute capability) is detected:
|
||||
1. The system automatically searches `models/` for the matching base `.pt` model weights (stripping hardware prefixes like `NUC5070_` or `jetson_`).
|
||||
2. Automatically compiles a new optimized `.engine` on the host machine using FP16 precision.
|
||||
3. Updates `defaults.detection.model_path` in `configs/cycle7_batch_optimized.yaml` automatically.
|
||||
- **Manual Export Tool**: You can also compile engines manually anytime using `export_engine.py`:
|
||||
- **Default ONNX `.onnx` Weights**: By default, batch counting configurations use `models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx` with `CUDAExecutionProvider` for high-throughput (~318 FPS) cross-hardware GPU acceleration.
|
||||
- **Mortality Detection**: Strictly uses the dedicated segmentation model `models/chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt`.
|
||||
- **Engine Verification Toggle (`--verify-engine`)**: When using `.engine` models across different GPUs/machines, pass `--verify-engine` (or set `verify_engine: true` in YAML) to trigger automated hardware compatibility checking and self-healing recompilation.
|
||||
- **Runtime Fail-Safe**: If an `.engine` model fails to load at runtime, `DetectionTracker` automatically falls back to the corresponding `.pt` or `.onnx` weights in `models/`.
|
||||
- **Manual Export Tool**: You can compile TensorRT engines anytime using `export_engine.py`:
|
||||
```bash
|
||||
./venv/bin/python export_engine.py models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.pt --half --workspace 4
|
||||
```
|
||||
|
||||
@@ -46,9 +46,10 @@ chicken-counting-sukawarna-det/
|
||||
├── db/
|
||||
│ └── chicken_counts.db ← SQLite database (auto-created)
|
||||
├── models/ ← Place your .pt / .onnx / .engine files here
|
||||
│ ├── chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx ← Default ONNX model (GPU accelerated)
|
||||
│ ├── chicken-detection-model-v26n-300e-best-2026-05-02-NEW.pt ← Source PyTorch model
|
||||
│ ├── 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
|
||||
│ └── chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt ← Used by mortality (PyTorch Segmentation)
|
||||
├── src/chicken_counter/ ← Main Python package (counting, tracking, motion, engine_utils)
|
||||
├── templates/ ← Dashboard HTML
|
||||
├── dashboard.py ← Live API + Dashboard server
|
||||
@@ -62,17 +63,18 @@ chicken-counting-sukawarna-det/
|
||||
|
||||
---
|
||||
|
||||
## 4. Model Setup & Auto-Recompilation
|
||||
## 4. Model Setup & Engine Verification Toggle
|
||||
|
||||
Put your model files in the `models/` directory.
|
||||
|
||||
| Purpose | File | Notes |
|
||||
| :--- | :--- | :--- |
|
||||
| Batch video counting (TensorRT) | `models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine` | Maximum GPU throughput |
|
||||
| Base PyTorch weights | `models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.pt` | Used for portable runs and auto-recompiling engines |
|
||||
| Mortality detection | `models/chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt` | Direct segmentation model (2-pass disabled by default for accuracy) |
|
||||
| Batch video counting (Default) | `models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx` | ONNX Runtime GPU (CUDAExecutionProvider ~318 FPS) |
|
||||
| Fallback / Training Source | `models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.pt` | Universal PyTorch weights |
|
||||
| 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) |
|
||||
|
||||
> **Self-Healing Recompilation on New Machines**: If you move the project to a new machine with a different GPU or OS, the pipeline will detect any incompatible `.engine`, automatically locate the matching `.pt` model, recompile a new `.engine` for the host machine, and update `configs/cycle7_batch_optimized.yaml` automatically.
|
||||
> **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.
|
||||
|
||||
---
|
||||
|
||||
@@ -149,18 +151,19 @@ Each coop (or central mortality table) is equipped with a dedicated stationary c
|
||||
- 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/mortality_config.yaml`)
|
||||
Map each coop to its RTSP stream URL, HTTP snapshot URL, or USB device index:
|
||||
#### Camera Configuration (`configs/sites.yaml` - Single Source of Truth)
|
||||
Configure the 1 stationary mortality camera RTSP link per site in `configs/sites.yaml`:
|
||||
|
||||
```yaml
|
||||
mortality:
|
||||
cameras:
|
||||
K1: "rtsp://admin:admin@192.168.1.101:554/live"
|
||||
K2: "rtsp://admin:admin@192.168.1.102:554/live"
|
||||
K3: "rtsp://admin:admin@192.168.1.103:554/live"
|
||||
K4: "rtsp://admin:admin@192.168.1.104:554/live"
|
||||
K5: "rtsp://admin:admin@192.168.1.105:554/live"
|
||||
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.).
|
||||
@@ -285,3 +288,55 @@ PYTHONPATH=src venv/bin/python export_excel_report.py
|
||||
venv/bin/pip install -r requirements.txt
|
||||
```
|
||||
5. All configs and Python code use relative paths and will work without any other changes.
|
||||
|
||||
---
|
||||
|
||||
## 8. Single-Machine Per-Site Deployment (ROG NUC)
|
||||
|
||||
Each farm site has **1 dedicated edge machine (ROG NUC)** that handles only that site's cameras:
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ 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)│
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Configuring a Machine for its Site
|
||||
|
||||
On **Machine A (Site A)**:
|
||||
In `configs/sites.yaml`, ensure:
|
||||
```yaml
|
||||
active_site: site_a
|
||||
auto_discover: false
|
||||
```
|
||||
|
||||
On **Machine B (Site B)**:
|
||||
In `configs/sites.yaml`, change:
|
||||
```yaml
|
||||
active_site: site_b
|
||||
auto_discover: false
|
||||
```
|
||||
*(Or set `export FARM_SITE=site_b` in `~/.bashrc`)*
|
||||
|
||||
### Daily Operation on Each ROG NUC
|
||||
|
||||
When technicians execute batch counting on each machine, the runner automatically targets that site:
|
||||
|
||||
```bash
|
||||
# Automatically runs all floors for the machine's configured site
|
||||
./run_all_coops.sh
|
||||
|
||||
# Run mortality detection for the machine's configured site
|
||||
./run_mortality_all.sh
|
||||
```
|
||||
|
||||
All SQLite database rows and JSON outputs will automatically be stamped with `"site": "site_a"` or `"site": "site_b"`, allowing seamless copying and consolidation on a central server.
|
||||
@@ -2,6 +2,7 @@ camera_id: coop_cam_03
|
||||
source: ../record/try-sukawarna.mp4
|
||||
detection:
|
||||
model_path: models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx
|
||||
verify_engine: false
|
||||
classes: [0]
|
||||
ignored_classes: [1, 2]
|
||||
conf: 0.35
|
||||
|
||||
@@ -10,7 +10,8 @@ batch:
|
||||
|
||||
defaults:
|
||||
detection:
|
||||
model_path: models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx #pt = accuracy, onnx = speed
|
||||
model_path: models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx
|
||||
verify_engine: false
|
||||
classes: [0]
|
||||
ignored_classes: [1, 2]
|
||||
conf: 0.35
|
||||
|
||||
@@ -6,6 +6,8 @@ batch:
|
||||
delete_intermediate: false
|
||||
checkpoint_every_n_frames: 3000
|
||||
location: kandang-atas
|
||||
site: site_a # Target site profile ('site_a' 5 coops x 2 floors, 'site_b' 3 coops x 3 floors)
|
||||
auto_discover: false # Default: off. Set to true to enable dynamic directory scanning
|
||||
db_path: db/chicken_counts.db
|
||||
cycle_start_date: "2026-05-22" #day 0
|
||||
execution_mode: parallel_processes # parallel_processes (default) | tensor_batching | hybrid
|
||||
@@ -25,7 +27,8 @@ stages:
|
||||
|
||||
defaults:
|
||||
detection:
|
||||
model_path: models/NUC5070_chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine # TensorRT engine (RTX 5070)
|
||||
model_path: models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx # ONNX model weights (high throughput, universal compatibility)
|
||||
verify_engine: false # Toggle to enable .engine compatibility verification/recompilation loop
|
||||
classes: [0]
|
||||
ignored_classes: [1, 2]
|
||||
conf: 0.40 # mild lift vs 0.35; 0.55 was undercounting
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Configuration for Mortality Chicken Carcass Detection & Counting
|
||||
mortality:
|
||||
# Base directory for multi-coop auto-discovery (K1..K5 and arbitrary coops)
|
||||
site: "site_a" # Target farm site ('site_a' or 'site_b')
|
||||
auto_discover: false # Default: off. Set to true or use --auto-discover to enable dynamic directory scanning
|
||||
coops_root_dir: "../VIDEOS/cycle7"
|
||||
# Default single-coop input directory (or override via --coop K1 / --all-coops)
|
||||
input_dir: "../VIDEOS/cycle7/K1/mortality"
|
||||
@@ -15,11 +16,7 @@ mortality:
|
||||
classes: [0] # Class 0 = chicken ONLY; ignores background/text/equipment (classes 1 not-chicken, 2 half-chicken)
|
||||
imgsz: 640
|
||||
|
||||
# Dedicated stationary camera streams per coop (RTSP URL, HTTP snapshot URL, or USB device index)
|
||||
cameras:
|
||||
K1: "rtsp://admin:admin@192.168.1.101:554/live"
|
||||
K2: "rtsp://admin:admin@192.168.1.102:554/live"
|
||||
K3: "rtsp://admin:admin@192.168.1.103:554/live"
|
||||
K4: "rtsp://admin:admin@192.168.1.104:554/live"
|
||||
K5: "rtsp://admin:admin@192.168.1.105:554/live"
|
||||
kandang-atas: "rtsp://admin:admin@192.168.1.100:554/live"
|
||||
# Stationary camera source:
|
||||
# Defaults to 'mortality_camera' configured in configs/sites.yaml for the active site.
|
||||
# Set 'camera_source' below ONLY if you wish to override the site default.
|
||||
camera_source: null # Optional override: "rtsp://admin:admin@192.168.1.100:554/live"
|
||||
@@ -0,0 +1,49 @@
|
||||
# Multi-Site Farm Configuration for Chicken Counting & Mortality
|
||||
# Site A: 5 coops, 2 floors each (10 floors total) + 1 dedicated mortality camera
|
||||
# Site B: 3 coops, 3 floors each (9 floors total) + 1 dedicated mortality camera
|
||||
# Total: 19 floors across 2 sites
|
||||
|
||||
auto_discover: false # Default: off. Set to true or use --auto-discover to enable dynamic scanning
|
||||
active_site: site_a # Active site for this physical machine ('site_a' or 'site_b', or set FARM_SITE env var)
|
||||
|
||||
sites:
|
||||
site_a:
|
||||
name: "Site A"
|
||||
description: "Site A - 5 coops with 2 floors each (10 floors)"
|
||||
coops:
|
||||
K1: ["L1", "L2"]
|
||||
K2: ["L1", "L2"]
|
||||
K3: ["L1", "L2"]
|
||||
K4: ["L1", "L2"]
|
||||
K5: ["L1", "L2"]
|
||||
floors:
|
||||
- "K1-L1"
|
||||
- "K1-L2"
|
||||
- "K2-L1"
|
||||
- "K2-L2"
|
||||
- "K3-L1"
|
||||
- "K3-L2"
|
||||
- "K4-L1"
|
||||
- "K4-L2"
|
||||
- "K5-L1"
|
||||
- "K5-L2"
|
||||
mortality_camera: "rtsp://admin:admin@192.168.1.100:554/live" # 1 mortality camera per site
|
||||
|
||||
site_b:
|
||||
name: "Site B"
|
||||
description: "Site B - 3 coops with 3 floors each (9 floors)"
|
||||
coops:
|
||||
K1: ["L1", "L2", "L3"]
|
||||
K2: ["L1", "L2", "L3"]
|
||||
K3: ["L1", "L2", "L3"]
|
||||
floors:
|
||||
- "K1-L1"
|
||||
- "K1-L2"
|
||||
- "K1-L3"
|
||||
- "K2-L1"
|
||||
- "K2-L2"
|
||||
- "K2-L3"
|
||||
- "K3-L1"
|
||||
- "K3-L2"
|
||||
- "K3-L3"
|
||||
mortality_camera: "rtsp://admin:admin@192.168.2.100:554/live" # 1 mortality camera per site
|
||||
Binary file not shown.
@@ -282,8 +282,8 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
|
||||
global_configs = [
|
||||
("Hardware / Target Platform", "ASUS NUC (AMD Ryzen 9 9955HX + NVIDIA GeForce RTX 5070 8GB)"),
|
||||
("Model Path (Engine)", "models/NUC5070_chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine"),
|
||||
("Model Architecture", "YOLOv8/v26n TensorRT FP16 compiled engine"),
|
||||
("Model Path (Weights)", "models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx"),
|
||||
("Model Architecture", "YOLOv8/v26n ONNX Model (.onnx, CUDAExecutionProvider)"),
|
||||
("Inference Image Size (imgsz)", "640 x 640"),
|
||||
("IoU Threshold", "0.55"),
|
||||
("Default Confidence Threshold (conf)", "0.40"),
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,114 @@
|
||||
#!/bin/bash
|
||||
# run_all_coops.sh - Master runner for batch chicken counting across farm sites and floors
|
||||
# Supports:
|
||||
# ./run_all_coops.sh site_a -> Run Site A (5 coops x 2 floors = 10 floors)
|
||||
# ./run_all_coops.sh site_b -> Run Site B (3 coops x 3 floors = 9 floors)
|
||||
# ./run_all_coops.sh all -> Run All 19 floors across both sites
|
||||
# ./run_all_coops.sh site_a 2026-06-18 -> Run Site A for a specific date
|
||||
# ./run_all_coops.sh K1-L1 -> Run specific floor
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
export PYTHONPATH="$SCRIPT_DIR/src"
|
||||
|
||||
if [ -f "$SCRIPT_DIR/venv/bin/python" ]; then
|
||||
PYTHON="$SCRIPT_DIR/venv/bin/python"
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
|
||||
TARGET="${1:-site_a}"
|
||||
DATE="${2:-}"
|
||||
MAX_JOBS="${MAX_JOBS:-2}"
|
||||
NO_VIDEO_FLAG="--no-video"
|
||||
|
||||
SITE_A_FLOORS=(
|
||||
"K1-L1" "K1-L2"
|
||||
"K2-L1" "K2-L2"
|
||||
"K3-L1" "K3-L2"
|
||||
"K4-L1" "K4-L2"
|
||||
"K5-L1" "K5-L2"
|
||||
)
|
||||
|
||||
SITE_B_FLOORS=(
|
||||
"K1-L1" "K1-L2" "K1-L3"
|
||||
"K2-L1" "K2-L2" "K2-L3"
|
||||
"K3-L1" "K3-L2" "K3-L3"
|
||||
)
|
||||
|
||||
floors=()
|
||||
|
||||
case "${TARGET,,}" in
|
||||
site_a|site-a|"a")
|
||||
echo "🏢 Target: Site A (5 coops, 2 floors each = 10 floors)"
|
||||
floors=("${SITE_A_FLOORS[@]}")
|
||||
;;
|
||||
site_b|site-b|"b")
|
||||
echo "🏢 Target: Site B (3 coops, 3 floors each = 9 floors)"
|
||||
floors=("${SITE_B_FLOORS[@]}")
|
||||
;;
|
||||
all|"both")
|
||||
echo "🏢 Target: All Sites (19 floors total)"
|
||||
# Combined distinct floor configurations
|
||||
floors=(
|
||||
"K1-L1" "K1-L2" "K1-L3"
|
||||
"K2-L1" "K2-L2" "K2-L3"
|
||||
"K3-L1" "K3-L2" "K3-L3"
|
||||
"K4-L1" "K4-L2"
|
||||
"K5-L1" "K5-L2"
|
||||
)
|
||||
;;
|
||||
*)
|
||||
# Single floor config (e.g. K1-L1 or kandang-atas)
|
||||
echo "📍 Target Floor: $TARGET"
|
||||
floors=("$TARGET")
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "======================================================================"
|
||||
echo "🚀 Starting Multi-Floor Batch Processing"
|
||||
echo " Floors to Process : ${#floors[@]} floors (${floors[*]})"
|
||||
echo " Auto-Discovery : OFF (Using static site profiles)"
|
||||
echo " Max Parallel Jobs : $MAX_JOBS"
|
||||
if [ -n "$DATE" ]; then
|
||||
echo " Target Date : $DATE"
|
||||
fi
|
||||
echo "======================================================================"
|
||||
|
||||
start_time=$(date +%s)
|
||||
success_count=0
|
||||
fail_count=0
|
||||
|
||||
for fl in "${floors[@]}"; do
|
||||
echo ""
|
||||
echo "----------------------------------------------------------------------"
|
||||
echo "▶️ Processing Floor: $fl"
|
||||
echo "----------------------------------------------------------------------"
|
||||
|
||||
cfg_file="$SCRIPT_DIR/configs/floor_config/${fl}.yaml"
|
||||
if [ ! -f "$cfg_file" ]; then
|
||||
cfg_file="$fl"
|
||||
fi
|
||||
|
||||
cmd=("$PYTHON" -m chicken_counter.cli batch --config "$cfg_file" $NO_VIDEO_FLAG)
|
||||
if [ -n "$DATE" ]; then
|
||||
cmd+=(--date "$DATE")
|
||||
fi
|
||||
|
||||
if "${cmd[@]}"; then
|
||||
success_count=$((success_count + 1))
|
||||
echo "✅ Finished floor: $fl"
|
||||
else
|
||||
fail_count=$((fail_count + 1))
|
||||
echo "❌ Failed floor: $fl"
|
||||
fi
|
||||
done
|
||||
|
||||
elapsed=$(( $(date +%s) - start_time ))
|
||||
echo ""
|
||||
echo "======================================================================"
|
||||
echo "✨ Batch Run Finished in ${elapsed}s!"
|
||||
echo " Successful Floors : $success_count"
|
||||
echo " Failed Floors : $fail_count"
|
||||
echo "======================================================================"
|
||||
@@ -1 +1,24 @@
|
||||
"""Chicken counting pipeline package for Jetson single-camera and daily batch runs."""
|
||||
"""Chicken counting pipeline package for single-camera and daily batch runs."""
|
||||
|
||||
import ctypes
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _preload_nvidia_cuda_libs() -> None:
|
||||
"""Preload bundled NVIDIA CUDA/cuDNN shared libraries from virtualenv into global process namespace.
|
||||
|
||||
This ensures onnxruntime-gpu and PyTorch can locate CUDA 12/13 .so libraries without manual LD_LIBRARY_PATH.
|
||||
"""
|
||||
for p in sys.path:
|
||||
nvidia_path = Path(p) / "nvidia"
|
||||
if nvidia_path.is_dir():
|
||||
for lib_dir in sorted(nvidia_path.glob("*/lib")):
|
||||
for so in sorted(lib_dir.glob("*.so*")):
|
||||
try:
|
||||
ctypes.CDLL(str(so), mode=ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
_preload_nvidia_cuda_libs()
|
||||
@@ -569,9 +569,10 @@ def run_daily_batch(
|
||||
if cycle_start_date:
|
||||
settings.batch.cycle_start_date = cycle_start_date
|
||||
|
||||
# Pre-validate and ensure compatible model in batch settings
|
||||
# Pre-validate and ensure compatible model in batch settings only if verify_engine toggle is enabled
|
||||
default_model = settings.defaults.get("detection", {}).get("model_path")
|
||||
if default_model:
|
||||
verify_engine = settings.defaults.get("detection", {}).get("verify_engine", False)
|
||||
if default_model and verify_engine:
|
||||
device = settings.defaults.get("detection", {}).get("device", "0")
|
||||
imgsz = settings.defaults.get("detection", {}).get("imgsz", 640)
|
||||
validated_model = ensure_compatible_model(
|
||||
|
||||
@@ -26,6 +26,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
run_parser.add_argument("--camera-id", help="Camera ID when using a multi-camera config file.")
|
||||
run_parser.add_argument("--verbose", action="store_true", help="Enable debug-level logging.")
|
||||
run_parser.add_argument("--progress-bar", action="store_true", help="Show a terminal progress bar.")
|
||||
run_parser.add_argument("--verify-engine", action="store_true", help="Enable TensorRT engine compatibility verification/recompilation.")
|
||||
|
||||
batch_parser = subparsers.add_parser("batch", help="Run the daily Cycle7 multi-camera batch.")
|
||||
batch_parser.add_argument(
|
||||
@@ -48,6 +49,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
batch_parser.add_argument("--output-dir", help="Override base output directory.")
|
||||
batch_parser.add_argument("--output-subdir", help="Override output subdirectory name.")
|
||||
batch_parser.add_argument("--cycle-start-date", help="Override start date of cycle (Day 0) in YYYY-MM-DD format.")
|
||||
batch_parser.add_argument("--site", default=None, help="Target farm site ID (e.g. site_a, site_b).")
|
||||
batch_parser.add_argument(
|
||||
"--mode",
|
||||
"--execution-mode",
|
||||
@@ -56,17 +58,23 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
help="Batch execution mode: 'parallel_processes' (default), 'tensor_batching', or 'hybrid'.",
|
||||
)
|
||||
batch_parser.add_argument("--progress-bar", action="store_true", help="Show a terminal progress bar.")
|
||||
batch_parser.add_argument("--verify-engine", action="store_true", help="Enable TensorRT engine compatibility verification/recompilation.")
|
||||
batch_parser.add_argument("--auto-discover", action="store_true", default=False, help="Enable dynamic coop/floor auto-discovery (default: off).")
|
||||
|
||||
sync_parser = subparsers.add_parser("sync-configs", help="Auto-generate missing configs/floor_config/*.yaml files from VIDEOS.")
|
||||
sync_parser.add_argument("--videos-root", default=None, help="Base VIDEOS directory.")
|
||||
sync_parser.add_argument("--configs-dir", default=None, help="Destination configs directory.")
|
||||
sync_parser.add_argument("--site", default=None, help="Target farm site ID (e.g. site_a, site_b).")
|
||||
sync_parser.add_argument("--auto-discover", action="store_true", default=False, help="Scan VIDEOS directory structure dynamically.")
|
||||
sync_parser.add_argument("--dry-run", action="store_true", help="Preview generated configs without writing files.")
|
||||
|
||||
mortality_parser = subparsers.add_parser("mortality", help="Run whole-image mortality chicken detection on photo(s).")
|
||||
mortality_parser.add_argument("--config", default=DEFAULT_CONFIG_PATH, help="Path to mortality YAML config file.")
|
||||
mortality_parser.add_argument("--input", "-i", default=None, help="Path to image file or directory containing images.")
|
||||
mortality_parser.add_argument("--coop", default=None, help="Specific coop/cage ID to process (e.g. K1, K2).")
|
||||
mortality_parser.add_argument("--all-coops", action="store_true", help="Batch-process mortality for ALL discovered coops.")
|
||||
mortality_parser.add_argument("--site", default=None, help="Target farm site ID (e.g. site_a, site_b).")
|
||||
mortality_parser.add_argument("--all-coops", action="store_true", help="Batch-process mortality for ALL coops.")
|
||||
mortality_parser.add_argument("--auto-discover", action="store_true", default=False, help="Enable dynamic coop auto-discovery (default: off).")
|
||||
mortality_parser.add_argument("--videos-root", default=None, help="Base VIDEOS directory (defaults to ../VIDEOS).")
|
||||
mortality_parser.add_argument("--output-dir", "-o", default=None, help="Directory to save annotated images and report.")
|
||||
mortality_parser.add_argument("--model-path", "-m", default=None, help="Path to YOLO model (.onnx/.pt/.engine).")
|
||||
@@ -91,6 +99,8 @@ def main() -> None:
|
||||
sync_floor_configs(
|
||||
videos_root=args.videos_root,
|
||||
configs_dir=args.configs_dir,
|
||||
auto_discover=getattr(args, "auto_discover", False),
|
||||
site=getattr(args, "site", None),
|
||||
dry_run=args.dry_run,
|
||||
)
|
||||
return
|
||||
@@ -105,13 +115,17 @@ def main() -> None:
|
||||
iou_threshold=args.iou,
|
||||
model_path=args.model_path,
|
||||
two_pass=args.two_pass,
|
||||
site=getattr(args, "site", None),
|
||||
auto_discover=getattr(args, "auto_discover", False),
|
||||
)
|
||||
return
|
||||
|
||||
input_path = args.input
|
||||
target_coop = getattr(args, "coop", None)
|
||||
target_site = getattr(args, "site", None)
|
||||
auto_disc = getattr(args, "auto_discover", False)
|
||||
if not input_path and target_coop:
|
||||
farm_struct = discover_farm_structure(args.videos_root)
|
||||
farm_struct = discover_farm_structure(args.videos_root, auto_discover=auto_disc, site=target_site)
|
||||
coop_info = farm_struct.get_coop(target_coop)
|
||||
if coop_info and coop_info.mortality_dir and coop_info.mortality_dir.is_dir():
|
||||
input_path = str(coop_info.mortality_dir)
|
||||
@@ -130,6 +144,8 @@ def main() -> None:
|
||||
config_path=args.config,
|
||||
date=getattr(args, "date", None),
|
||||
coop=target_coop,
|
||||
site=target_site,
|
||||
auto_discover=auto_disc,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -145,6 +161,8 @@ def main() -> None:
|
||||
settings.batch.cycle_start_date = args.cycle_start_date
|
||||
if getattr(args, "mode", None):
|
||||
settings.batch.execution_mode = args.mode
|
||||
if getattr(args, "verify_engine", False):
|
||||
settings.defaults.setdefault("detection", {})["verify_engine"] = True
|
||||
run_daily_batch(
|
||||
settings,
|
||||
date=args.date,
|
||||
@@ -159,6 +177,8 @@ def main() -> None:
|
||||
if args.command == "run":
|
||||
config = load_camera_config(args.config, args.camera_id)
|
||||
config.performance.verbose = args.verbose
|
||||
if getattr(args, "verify_engine", False):
|
||||
config.detection.verify_engine = True
|
||||
result = run_pipeline(config, show_progress=args.progress_bar)
|
||||
print(
|
||||
f"[done] camera={result.camera_id} total_entered={result.total_entered_count} "
|
||||
@@ -169,6 +189,8 @@ def main() -> None:
|
||||
if args.config:
|
||||
config = load_camera_config(args.config, args.camera_id)
|
||||
config.performance.verbose = args.verbose
|
||||
if getattr(args, "verify_engine", False):
|
||||
config.detection.verify_engine = True
|
||||
result = run_pipeline(config, show_progress=args.progress_bar)
|
||||
print(
|
||||
f"[done] camera={result.camera_id} total_entered={result.total_entered_count} "
|
||||
|
||||
@@ -41,6 +41,7 @@ class DetectionConfig:
|
||||
# Off by default; enable per-camera (e.g. CC2/CC3) for ID-flip double counts.
|
||||
dedupe_radius_px: int = 0
|
||||
dedupe_frames: int = 12
|
||||
verify_engine: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -235,6 +236,8 @@ class BatchConfig:
|
||||
db_path: str = ""
|
||||
cycle_start_date: str | None = None
|
||||
execution_mode: str = "parallel_processes"
|
||||
site: str | None = None
|
||||
auto_discover: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -9,6 +9,8 @@ from pathlib import Path
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
DEFAULT_VIDEOS_ROOT = (PROJECT_ROOT.parent / "VIDEOS").resolve()
|
||||
DEFAULT_CONFIGS_DIR = (PROJECT_ROOT / "configs" / "floor_config").resolve()
|
||||
DEFAULT_SITES_CONFIG = (PROJECT_ROOT / "configs" / "sites.yaml").resolve()
|
||||
DEFAULT_AUTO_DISCOVER = False
|
||||
|
||||
# Patterns for coop & floor extraction
|
||||
COOP_FLOOR_PATTERN = re.compile(
|
||||
@@ -18,6 +20,20 @@ COOP_FLOOR_PATTERN = re.compile(
|
||||
FLOOR_SUBDIR_PATTERN = re.compile(r"^(?:[Ll]|floor)[-_]?(?P<num>\d+)$", re.IGNORECASE)
|
||||
|
||||
|
||||
def load_sites_config(sites_path: Path | str | None = None) -> dict:
|
||||
"""Load site definitions from configs/sites.yaml if present."""
|
||||
p = Path(sites_path).resolve() if sites_path else DEFAULT_SITES_CONFIG
|
||||
if not p.is_file():
|
||||
return {}
|
||||
try:
|
||||
import yaml
|
||||
with open(p, "r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
return data
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
@dataclass
|
||||
class CoopInfo:
|
||||
"""Represents a detected coop/cage (e.g. K1, K2) with its constituent floors and mortality folder."""
|
||||
@@ -45,10 +61,12 @@ class CoopInfo:
|
||||
|
||||
@dataclass
|
||||
class FarmStructure:
|
||||
"""Complete dynamic farm structure of coops and floors detected on this site."""
|
||||
"""Complete farm structure of coops and floors for a site."""
|
||||
|
||||
coops: dict[str, CoopInfo] = field(default_factory=dict)
|
||||
videos_root: Path | None = None
|
||||
site_id: str | None = None
|
||||
auto_discovered: bool = False
|
||||
|
||||
def get_coop(self, coop_id: str) -> CoopInfo | None:
|
||||
"""Get CoopInfo by coop_id (case-insensitive)."""
|
||||
@@ -135,21 +153,29 @@ def resolve_floor_video_dir(
|
||||
def discover_farm_structure(
|
||||
videos_root: Path | str | None = None,
|
||||
configs_dir: Path | str | None = None,
|
||||
auto_discover: bool = DEFAULT_AUTO_DISCOVER,
|
||||
site: str | None = None,
|
||||
sites_config_path: Path | str | None = None,
|
||||
) -> FarmStructure:
|
||||
"""Dynamically discover all coops, floors, and mortality directories on the local machine.
|
||||
"""Discover or load farm structure of coops, floors, and mortality directories.
|
||||
|
||||
Searches:
|
||||
1. Hierarchical coop folders: `VIDEOS/<cycle>/<coop>/[L1..Ln, mortality]`
|
||||
2. Legacy/flat floor folders: `VIDEOS/<cycle>/<coop>-<floor>/`
|
||||
3. Config files: `configs/floor_config/<coop>-<floor>.yaml`
|
||||
Modes:
|
||||
1. Static / Config-Driven (Default, auto_discover=False):
|
||||
- If `site` is specified (e.g. 'site_a' with 5 coops x 2 floors = 10 floors,
|
||||
or 'site_b' with 3 coops x 3 floors = 9 floors), loads strictly the defined site layout.
|
||||
- Otherwise, loads configured floors from `configs/floor_config/*.yaml` without recursive disk walks.
|
||||
2. Dynamic / Auto-Discovery (auto_discover=True):
|
||||
- Actively scans `VIDEOS/` hierarchy across arbitrary directories.
|
||||
"""
|
||||
v_root = Path(videos_root).resolve() if videos_root else DEFAULT_VIDEOS_ROOT
|
||||
c_dir = Path(configs_dir).resolve() if configs_dir else DEFAULT_CONFIGS_DIR
|
||||
sites_cfg = load_sites_config(sites_config_path)
|
||||
import os
|
||||
effective_site = site or os.environ.get("FARM_SITE") or sites_cfg.get("active_site")
|
||||
|
||||
coops: dict[str, CoopInfo] = {}
|
||||
|
||||
def _get_or_create_coop(cid: str, cdir: Path | None = None) -> CoopInfo:
|
||||
# Canonical key
|
||||
key = cid.upper() if re.match(r"^[Kk]\d+$", cid) else cid
|
||||
if key not in coops:
|
||||
coops[key] = CoopInfo(coop_id=key, coop_dir=cdir)
|
||||
@@ -157,8 +183,26 @@ def discover_farm_structure(
|
||||
coops[key].coop_dir = cdir
|
||||
return coops[key]
|
||||
|
||||
# 1. Scan VIDEOS directory hierarchy
|
||||
if v_root.is_dir():
|
||||
# Mode 1: Static site profile (site_a or site_b)
|
||||
if effective_site and not auto_discover:
|
||||
normalized_site = str(effective_site).lower().replace("-", "_")
|
||||
sites_map = sites_cfg.get("sites", {})
|
||||
if normalized_site in sites_map:
|
||||
site_info = sites_map[normalized_site]
|
||||
site_coops = site_info.get("coops", {})
|
||||
for cid, floor_list in site_coops.items():
|
||||
coop_obj = _get_or_create_coop(cid, v_root / "cycle7" / cid)
|
||||
coop_mort = v_root / "cycle7" / cid / "mortality"
|
||||
if coop_mort.is_dir():
|
||||
coop_obj.mortality_dir = coop_mort
|
||||
for fl in floor_list:
|
||||
fl_name = f"{cid}-{fl.upper()}"
|
||||
fl_path = v_root / "cycle7" / cid / fl.upper()
|
||||
coop_obj.floors[fl_name] = fl_path
|
||||
return FarmStructure(coops=coops, videos_root=v_root, site_id=normalized_site, auto_discovered=False)
|
||||
|
||||
# Mode 2: Dynamic Auto-Discovery (explicitly enabled)
|
||||
if auto_discover and v_root.is_dir():
|
||||
search_roots = [v_root]
|
||||
for sub in v_root.iterdir():
|
||||
if sub.is_dir() and (sub.name.startswith("cycle") or sub.name.startswith("202")):
|
||||
@@ -173,7 +217,6 @@ def discover_farm_structure(
|
||||
|
||||
# Case A: Hierarchical Coop Directory (e.g. K1, K2, kandang-atas)
|
||||
coop_name = item.name
|
||||
# Check if it has floor subfolders (L1, L2) or mortality folder
|
||||
has_mortality = (item / "mortality").is_dir()
|
||||
has_floors = False
|
||||
|
||||
@@ -201,29 +244,35 @@ def discover_farm_structure(
|
||||
if floor_name not in coop_obj.floors:
|
||||
coop_obj.floors[floor_name] = item
|
||||
|
||||
# 2. Augment with configured floor YAMLs in configs/floor_config/
|
||||
# Mode 3: Config-Driven Floor Loading from configs/floor_config/*.yaml (Static Default)
|
||||
if c_dir.is_dir():
|
||||
for cfg_file in sorted(c_dir.glob("*.yaml")):
|
||||
stem = cfg_file.stem
|
||||
coop_id = get_coop_for_location(stem)
|
||||
coop_obj = _get_or_create_coop(coop_id)
|
||||
coop_dir = v_root / "cycle7" / coop_id if v_root else None
|
||||
coop_obj = _get_or_create_coop(coop_id, coop_dir)
|
||||
if stem not in coop_obj.floors:
|
||||
# Store placeholder floor reference
|
||||
coop_obj.floors[stem] = cfg_file
|
||||
|
||||
# 3. Auto-populate mortality_dir if present in coop_dir
|
||||
# Auto-link mortality_dir for each detected coop
|
||||
for coop_obj in coops.values():
|
||||
if not coop_obj.mortality_dir and coop_obj.coop_dir:
|
||||
mort_cand = coop_obj.coop_dir / "mortality"
|
||||
if mort_cand.is_dir():
|
||||
coop_obj.mortality_dir = mort_cand
|
||||
if not coop_obj.mortality_dir:
|
||||
cand = v_root / "cycle7" / coop_obj.coop_id / "mortality" if v_root else None
|
||||
if cand and cand.is_dir():
|
||||
coop_obj.mortality_dir = cand
|
||||
elif coop_obj.coop_dir and (coop_obj.coop_dir / "mortality").is_dir():
|
||||
coop_obj.mortality_dir = coop_obj.coop_dir / "mortality"
|
||||
|
||||
return FarmStructure(coops=coops, videos_root=v_root)
|
||||
return FarmStructure(coops=coops, videos_root=v_root, site_id=site, auto_discovered=auto_discover)
|
||||
|
||||
|
||||
def discover_all_mortality_dirs(videos_root: Path | str | None = None) -> dict[str, Path]:
|
||||
def discover_all_mortality_dirs(
|
||||
videos_root: Path | str | None = None,
|
||||
auto_discover: bool = DEFAULT_AUTO_DISCOVER,
|
||||
site: str | None = None,
|
||||
) -> dict[str, Path]:
|
||||
"""Find all mortality directories grouped by coop_id."""
|
||||
structure = discover_farm_structure(videos_root)
|
||||
structure = discover_farm_structure(videos_root=videos_root, auto_discover=auto_discover, site=site)
|
||||
return structure.all_mortality_dirs()
|
||||
|
||||
|
||||
@@ -231,14 +280,16 @@ def sync_floor_configs(
|
||||
videos_root: Path | str | None = None,
|
||||
configs_dir: Path | str | None = None,
|
||||
base_config_rel: str = "../cycle7_batch_optimized.yaml",
|
||||
auto_discover: bool = DEFAULT_AUTO_DISCOVER,
|
||||
site: str | None = None,
|
||||
dry_run: bool = False,
|
||||
) -> list[Path]:
|
||||
"""Scan VIDEOS for all discovered floors and auto-create missing configs/floor_config/*.yaml files."""
|
||||
"""Scan VIDEOS or site layout for all floors and auto-create missing configs/floor_config/*.yaml files."""
|
||||
v_root = Path(videos_root).resolve() if videos_root else DEFAULT_VIDEOS_ROOT
|
||||
c_dir = Path(configs_dir).resolve() if configs_dir else DEFAULT_CONFIGS_DIR
|
||||
c_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
structure = discover_farm_structure(videos_root=v_root, configs_dir=c_dir)
|
||||
structure = discover_farm_structure(videos_root=v_root, configs_dir=c_dir, auto_discover=auto_discover, site=site)
|
||||
created: list[Path] = []
|
||||
|
||||
for coop_id, coop_info in sorted(structure.coops.items()):
|
||||
|
||||
@@ -41,22 +41,68 @@ def load_mortality_config(config_path: str | Path) -> dict:
|
||||
return data.get("mortality", data)
|
||||
|
||||
|
||||
def get_camera_source_for_coop(coop_id: str, config_path: str | Path | None = None) -> str | int | None:
|
||||
"""Retrieve configured stationary camera source (RTSP URL, device index, or snapshot URL) for a coop."""
|
||||
def get_camera_source_for_coop(
|
||||
coop_id: str | None = None,
|
||||
config_path: str | Path | None = None,
|
||||
site: str | None = None,
|
||||
) -> str | int | None:
|
||||
"""Retrieve configured stationary camera source for a coop or site.
|
||||
|
||||
Resolution Priority (Single Source of Truth):
|
||||
1. Runtime Environment Variable: MORTALITY_CAMERA_URL
|
||||
2. Direct override in mortality_config.yaml: 'camera_source'
|
||||
3. Site definition in configs/sites.yaml: sites[site].mortality_camera (Primary SSOT)
|
||||
4. Legacy / custom cameras mapping in mortality_config.yaml
|
||||
"""
|
||||
import os
|
||||
|
||||
# 1. Environment variable override
|
||||
env_url = os.environ.get("MORTALITY_CAMERA_URL")
|
||||
if env_url:
|
||||
return env_url
|
||||
|
||||
cfg = load_mortality_config(config_path or DEFAULT_CONFIG_PATH)
|
||||
|
||||
# 2. Direct explicit camera override in mortality_config.yaml
|
||||
if cfg.get("camera_source"):
|
||||
return cfg["camera_source"]
|
||||
|
||||
# 3. Lookup in configs/sites.yaml (Single Source of Truth for site topology)
|
||||
from chicken_counter.discovery import load_sites_config
|
||||
sites_cfg = load_sites_config()
|
||||
current_site = site or cfg.get("site") or os.environ.get("FARM_SITE") or sites_cfg.get("active_site", "site_a")
|
||||
|
||||
if current_site:
|
||||
site_key = str(current_site).lower().replace("-", "_")
|
||||
sites_map = sites_cfg.get("sites", {})
|
||||
if site_key in sites_map and "mortality_camera" in sites_map[site_key]:
|
||||
return sites_map[site_key]["mortality_camera"]
|
||||
|
||||
# 4. Fallback: Legacy / custom cameras mapping in mortality_config.yaml
|
||||
cameras = cfg.get("cameras", {})
|
||||
if not cameras:
|
||||
return None
|
||||
if coop_id in cameras:
|
||||
return cameras[coop_id]
|
||||
for k, v in cameras.items():
|
||||
if str(k).upper() == str(coop_id).upper():
|
||||
return v
|
||||
if current_site:
|
||||
site_key = str(current_site).lower().replace("-", "_")
|
||||
if site_key in cameras:
|
||||
return cameras[site_key]
|
||||
if f"site_{site_key}" in cameras:
|
||||
return cameras[f"site_{site_key}"]
|
||||
|
||||
if coop_id:
|
||||
if coop_id in cameras:
|
||||
return cameras[coop_id]
|
||||
for k, v in cameras.items():
|
||||
if str(k).upper() == str(coop_id).upper():
|
||||
return v
|
||||
|
||||
if len(cameras) == 1:
|
||||
return next(iter(cameras.values()))
|
||||
|
||||
if "default" in cameras:
|
||||
default_tmpl = str(cameras["default"])
|
||||
num_m = re.search(r"\d+", coop_id)
|
||||
num_m = re.search(r"\d+", coop_id or "1")
|
||||
coop_num = num_m.group(0) if num_m else "1"
|
||||
return default_tmpl.format(coop=coop_id, coop_num=coop_num)
|
||||
return default_tmpl.format(coop=coop_id or "K1", coop_num=coop_num)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@@ -315,9 +361,13 @@ def run_mortality_count(
|
||||
config_path: str | Path | None = DEFAULT_CONFIG_PATH,
|
||||
date: str | None = None,
|
||||
coop: str | None = None,
|
||||
site: str | None = None,
|
||||
auto_discover: bool = False,
|
||||
) -> dict:
|
||||
config_path = resolve_path(config_path) if config_path else DEFAULT_CONFIG_PATH
|
||||
cfg = load_mortality_config(config_path) if config_path else {}
|
||||
site = site or cfg.get("site")
|
||||
auto_discover = auto_discover or cfg.get("auto_discover", False)
|
||||
|
||||
# 2. CLI / function arguments override YAML config defaults if specified
|
||||
raw_input_path = input_path if input_path is not None else cfg.get("input_dir", DEFAULT_MORTALITY_DIR)
|
||||
@@ -360,7 +410,7 @@ def run_mortality_count(
|
||||
|
||||
if not image_files:
|
||||
print(f"[mortality] No input images found at: {input_path}")
|
||||
return {"total_images": 0, "results": []}
|
||||
return {"total_images": 0, "results": [], "site": site, "coop": coop}
|
||||
|
||||
# Resolve parent coop and covered floors
|
||||
inferred_coop = coop
|
||||
@@ -371,7 +421,7 @@ def run_mortality_count(
|
||||
break
|
||||
inferred_coop = inferred_coop or "kandang-atas"
|
||||
|
||||
farm_struct = discover_farm_structure()
|
||||
farm_struct = discover_farm_structure(auto_discover=auto_discover, site=site)
|
||||
covered_floors = farm_struct.get_covered_floors(inferred_coop)
|
||||
covered_str = ", ".join(covered_floors)
|
||||
|
||||
@@ -518,6 +568,7 @@ def run_mortality_count(
|
||||
report_path = target_out_dir / "mortality_report.json"
|
||||
report_data = {
|
||||
"date": date or datetime.now().strftime("%Y-%m-%d"),
|
||||
"site": site,
|
||||
"coop": inferred_coop,
|
||||
"location": inferred_coop,
|
||||
"covered_floors": covered_floors,
|
||||
@@ -551,17 +602,24 @@ def run_all_coop_mortality(
|
||||
model_path: str | Path | None = None,
|
||||
device: str | int | None = None,
|
||||
two_pass: bool | None = None,
|
||||
site: str | None = None,
|
||||
auto_discover: bool = False,
|
||||
) -> dict[str, dict]:
|
||||
"""Batch-process mortality detection across all discovered coop mortality folders."""
|
||||
farm_struct = discover_farm_structure(videos_root)
|
||||
cfg = load_mortality_config(config_path or DEFAULT_CONFIG_PATH)
|
||||
site = site or cfg.get("site")
|
||||
auto_discover = auto_discover or cfg.get("auto_discover", False)
|
||||
|
||||
farm_struct = discover_farm_structure(videos_root, auto_discover=auto_discover, site=site)
|
||||
all_m_dirs = farm_struct.all_mortality_dirs()
|
||||
if not all_m_dirs:
|
||||
print(f"[mortality-batch] ⚠️ No coop mortality directories found under {farm_struct.videos_root}")
|
||||
return {}
|
||||
|
||||
site_str = f" (Site: {site})" if site else ""
|
||||
print(f"\n=================================================================")
|
||||
print(f" Starting Batch Mortality Detection across {len(all_m_dirs)} Coops")
|
||||
print(f" Discovered Coops: {', '.join(sorted(all_m_dirs.keys()))}")
|
||||
print(f" Starting Batch Mortality Detection across {len(all_m_dirs)} Coops{site_str}")
|
||||
print(f" Target Coops: {', '.join(sorted(all_m_dirs.keys()))}")
|
||||
if date:
|
||||
print(f" Target Date: {date}")
|
||||
print(f"=================================================================\n")
|
||||
@@ -588,6 +646,8 @@ def run_all_coop_mortality(
|
||||
model_path=model_path,
|
||||
device=device,
|
||||
two_pass=two_pass,
|
||||
site=site,
|
||||
auto_discover=auto_discover,
|
||||
)
|
||||
summary[coop_id] = res
|
||||
c_count = res.get("total_mortality_count", 0)
|
||||
|
||||
@@ -21,14 +21,17 @@ class DetectionTracker:
|
||||
def __init__(self, config: CameraConfig) -> None:
|
||||
self.config = config
|
||||
|
||||
# Ensure model is compatible on this machine / GPU, recompiling .engine from .pt if needed
|
||||
validated_model_path = ensure_compatible_model(
|
||||
config.detection.model_path,
|
||||
device=config.detection.device,
|
||||
imgsz=config.detection.imgsz,
|
||||
config_file_path=getattr(config, "config_path", None),
|
||||
)
|
||||
config.detection.model_path = validated_model_path
|
||||
# Verify / recompile .engine only if verify_engine toggle is enabled
|
||||
if getattr(config.detection, "verify_engine", False):
|
||||
validated_model_path = ensure_compatible_model(
|
||||
config.detection.model_path,
|
||||
device=config.detection.device,
|
||||
imgsz=config.detection.imgsz,
|
||||
config_file_path=getattr(config, "config_path", None),
|
||||
)
|
||||
config.detection.model_path = validated_model_path
|
||||
else:
|
||||
validated_model_path = config.detection.model_path
|
||||
|
||||
model_path = Path(validated_model_path)
|
||||
self.model_kind = model_path.suffix.lower().lstrip(".") or "unknown"
|
||||
|
||||
@@ -32,32 +32,29 @@ class TestFlexibleDiscovery(unittest.TestCase):
|
||||
structure = discover_farm_structure()
|
||||
self.assertIsNotNone(structure)
|
||||
|
||||
# Check detected coops in workspace
|
||||
# Check detected coops in workspace (Site A: 5 coops)
|
||||
self.assertIn("K1", structure.coops)
|
||||
self.assertIn("K2", structure.coops)
|
||||
self.assertIn("K3", structure.coops)
|
||||
self.assertIn("K4", structure.coops)
|
||||
self.assertIn("K5", structure.coops)
|
||||
|
||||
# Verify covered floors for K1 (3 floors) and K4 (2 floors)
|
||||
# Verify covered floors for Site A (2 floors per coop)
|
||||
k1_floors = structure.get_covered_floors("K1")
|
||||
self.assertIn("K1-L1", k1_floors)
|
||||
self.assertIn("K1-L2", k1_floors)
|
||||
self.assertIn("K1-L3", k1_floors)
|
||||
self.assertEqual(len(k1_floors), 2)
|
||||
|
||||
k4_floors = structure.get_covered_floors("K4")
|
||||
self.assertIn("K4-L1", k4_floors)
|
||||
self.assertIn("K4-L2", k4_floors)
|
||||
self.assertEqual(len(k4_floors), 2)
|
||||
|
||||
# Verify mortality directories
|
||||
mort_dirs = structure.all_mortality_dirs()
|
||||
self.assertIn("K1", mort_dirs)
|
||||
self.assertIn("K2", mort_dirs)
|
||||
self.assertIn("K3", mort_dirs)
|
||||
self.assertIn("K4", mort_dirs)
|
||||
self.assertIn("K5", mort_dirs)
|
||||
self.assertEqual(mort_dirs["K1"].name, "mortality")
|
||||
self.assertEqual(mort_dirs["K1"].parent.name, "K1")
|
||||
# Dynamic auto-discovery on workspace
|
||||
dyn_struct = discover_farm_structure(auto_discover=True)
|
||||
dyn_k1_floors = dyn_struct.get_covered_floors("K1")
|
||||
self.assertIn("K1-L1", dyn_k1_floors)
|
||||
self.assertIn("K1-L2", dyn_k1_floors)
|
||||
|
||||
def test_flexible_discovery_arbitrary_site(self):
|
||||
"""Test that discovery dynamically adapts to arbitrary site layouts with varying coops and floors."""
|
||||
@@ -79,7 +76,7 @@ class TestFlexibleDiscovery(unittest.TestCase):
|
||||
(tmp / "cycle1" / "K10" / "L1").mkdir(parents=True)
|
||||
(tmp / "cycle1" / "K10" / "L2").mkdir(parents=True)
|
||||
|
||||
structure = discover_farm_structure(videos_root=tmp)
|
||||
structure = discover_farm_structure(videos_root=tmp, auto_discover=True)
|
||||
|
||||
self.assertTrue("KANDANG-UTAMA" in structure.coops or "Kandang-Utama" in structure.coops)
|
||||
coop_u = structure.get_coop("Kandang-Utama")
|
||||
@@ -126,7 +123,7 @@ class TestFlexibleDiscovery(unittest.TestCase):
|
||||
(vid_dir / "K8" / "L2").mkdir(parents=True)
|
||||
(vid_dir / "K8" / "L3").mkdir(parents=True)
|
||||
|
||||
created = sync_floor_configs(videos_root=vid_dir.parent, configs_dir=cfg_dir)
|
||||
created = sync_floor_configs(videos_root=vid_dir.parent, configs_dir=cfg_dir, auto_discover=True)
|
||||
self.assertEqual(len(created), 3)
|
||||
|
||||
# Check that files were written
|
||||
@@ -139,7 +136,7 @@ class TestFlexibleDiscovery(unittest.TestCase):
|
||||
self.assertIn('root_dir: "../VIDEOS/cycle7/K8/L1"', content)
|
||||
|
||||
# Running sync again should create 0 files
|
||||
created_again = sync_floor_configs(videos_root=vid_dir.parent, configs_dir=cfg_dir)
|
||||
created_again = sync_floor_configs(videos_root=vid_dir.parent, configs_dir=cfg_dir, auto_discover=True)
|
||||
self.assertEqual(len(created_again), 0)
|
||||
|
||||
def test_load_or_synthesize_floor_config(self):
|
||||
@@ -160,20 +157,49 @@ class TestFlexibleDiscovery(unittest.TestCase):
|
||||
report = mort_day / "mortality_report.json"
|
||||
report.write_text('{"date":"2026-08-20","total_mortality_count":15,"results":[]}')
|
||||
|
||||
structure = discover_farm_structure(videos_root=tmp)
|
||||
structure = discover_farm_structure(videos_root=tmp, auto_discover=True)
|
||||
self.assertIn("K1", structure.coops)
|
||||
self.assertIsNotNone(structure.coops["K1"].mortality_dir)
|
||||
|
||||
def test_stationary_camera_config(self):
|
||||
"""Test retrieving stationary camera sources for farm coops."""
|
||||
def test_site_a_profile(self):
|
||||
"""Test Site A profile with 5 coops and 2 floors each (10 floors total)."""
|
||||
structure = discover_farm_structure(site="site_a")
|
||||
self.assertEqual(len(structure.coops), 5)
|
||||
self.assertEqual(sorted(structure.coops.keys()), ["K1", "K2", "K3", "K4", "K5"])
|
||||
|
||||
all_floors = []
|
||||
for coop in structure.coops.values():
|
||||
self.assertEqual(len(coop.covered_floors), 2)
|
||||
all_floors.extend(coop.covered_floors)
|
||||
self.assertEqual(len(all_floors), 10)
|
||||
self.assertIn("K1-L1", all_floors)
|
||||
self.assertIn("K5-L2", all_floors)
|
||||
|
||||
def test_site_b_profile(self):
|
||||
"""Test Site B profile with 3 coops and 3 floors each (9 floors total)."""
|
||||
structure = discover_farm_structure(site="site_b")
|
||||
self.assertEqual(len(structure.coops), 3)
|
||||
self.assertEqual(sorted(structure.coops.keys()), ["K1", "K2", "K3"])
|
||||
|
||||
all_floors = []
|
||||
for coop in structure.coops.values():
|
||||
self.assertEqual(len(coop.covered_floors), 3)
|
||||
all_floors.extend(coop.covered_floors)
|
||||
self.assertEqual(len(all_floors), 9)
|
||||
self.assertIn("K1-L3", all_floors)
|
||||
self.assertIn("K3-L3", all_floors)
|
||||
|
||||
def test_stationary_camera_config_site_camera(self):
|
||||
"""Test retrieving stationary camera sources with 1 camera per site support."""
|
||||
from chicken_counter.mortality import capture_camera_snapshot, get_camera_source_for_coop
|
||||
|
||||
cam_k1 = get_camera_source_for_coop("K1")
|
||||
self.assertIsNotNone(cam_k1)
|
||||
self.assertTrue("192.168.1.101" in str(cam_k1) or "rtsp" in str(cam_k1))
|
||||
cam_site_a = get_camera_source_for_coop("K1", site="site_a")
|
||||
self.assertIsNotNone(cam_site_a)
|
||||
self.assertTrue("192.168.1.100" in str(cam_site_a) or "rtsp" in str(cam_site_a))
|
||||
|
||||
cam_k5 = get_camera_source_for_coop("K5")
|
||||
self.assertIsNotNone(cam_k5)
|
||||
cam_site_b = get_camera_source_for_coop("K1", site="site_b")
|
||||
self.assertIsNotNone(cam_site_b)
|
||||
self.assertTrue("192.168.2.100" in str(cam_site_b))
|
||||
|
||||
# Non-existent camera stream capture should return None gracefully without raising
|
||||
invalid_cap = capture_camera_snapshot("rtsp://invalid-non-existent-host.local:554/live", timeout_sec=0.5, warmup_frames=1)
|
||||
|
||||
+19
-2
@@ -14,8 +14,7 @@ class MultiCameraTrackerIsolationTests(unittest.TestCase):
|
||||
cfg = load_camera_config("configs/cameras/example_camera.yaml")
|
||||
|
||||
# Test get_or_create_tracker instantiates isolated instances for different stream IDs
|
||||
with patch("chicken_counter.tracking.ensure_compatible_model", return_value=cfg.detection.model_path), \
|
||||
patch("chicken_counter.tracking.YOLO"):
|
||||
with patch("chicken_counter.tracking.YOLO"):
|
||||
from chicken_counter.tracking import DetectionTracker
|
||||
|
||||
tracker_manager = DetectionTracker(cfg)
|
||||
@@ -31,6 +30,24 @@ class MultiCameraTrackerIsolationTests(unittest.TestCase):
|
||||
self.assertNotIn("CC1", tracker_manager._stream_trackers)
|
||||
self.assertIn("CC2", tracker_manager._stream_trackers)
|
||||
|
||||
def test_verify_engine_toggle(self) -> None:
|
||||
cfg = load_camera_config("configs/cameras/example_camera.yaml")
|
||||
from chicken_counter.tracking import DetectionTracker
|
||||
|
||||
# 1. By default verify_engine is False, so ensure_compatible_model should NOT be called
|
||||
with patch("chicken_counter.tracking.ensure_compatible_model") as mock_ensure, \
|
||||
patch("chicken_counter.tracking.YOLO"):
|
||||
cfg.detection.verify_engine = False
|
||||
_ = DetectionTracker(cfg)
|
||||
mock_ensure.assert_not_called()
|
||||
|
||||
# 2. When verify_engine is True, ensure_compatible_model SHOULD be called
|
||||
with patch("chicken_counter.tracking.ensure_compatible_model", return_value=cfg.detection.model_path) as mock_ensure, \
|
||||
patch("chicken_counter.tracking.YOLO"):
|
||||
cfg.detection.verify_engine = True
|
||||
_ = DetectionTracker(cfg)
|
||||
mock_ensure.assert_called_once()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user