Author SHA1 Message Date
dsutanto 129d4def09 remove accidentally committed .oc/session.json 2026-09-02 12:53:00 +07:00
dsutanto d97cc616ef Merge pull request 'Python optimize [Multi Floor, API, Speed Improvements, Auto .engine compilation, etc.]' (#1) from andrew/chicken-counting-sukawarna-det:python-optimize into python-optimize
Reviewed-on: #1
2026-08-19 14:56:40 +07:00
andrew d9daf0ab01 docs: update README, RUN guide, and add CHANGELOG for recent bugfixes and optimizations 2026-08-19 14:38:06 +07:00
andrew 2061fbf08c fix: resolve multi-threading DB concurrency, disk traversal caching, and coops discovery 2026-08-19 14:36:04 +07:00
proitlab 9f4fc138ba fix: make chicken-dashboard.service dynamic, add install_service.sh, and add sibling VIDEOS startup checks 2026-08-19 12:14:20 +07:00
proitlab acd9c9265b feat: add coop filtering and directory pre-check to run_all_coops.sh 2026-08-19 11:53:35 +07:00
proitlab 127f3c59b2 feat: add 3rd floor configs (K1-L3, K2-L3, K3-L3) and auto-discovery in run_all_coops.sh 2026-08-19 11:51:07 +07:00
proitlab f9c38e5126 feat: implement config inheritance via 'extends' and place lightweight floor configs in configs/floor_config/ 2026-08-19 11:44:46 +07:00
proitlab 5ad4a5f796 fix: ensure robust PROJECT_ROOT path resolution in all test_run_folder scripts 2026-08-19 11:31:45 +07:00
proitlab 8fe2f88f12 style: format K*-L*.yaml configs with exact inline comments and flow-style [x, y] coordinates 2026-08-19 11:27:49 +07:00
proitlab b00923dc2b feat: implement K{coop}-L{floor} standard, smart discovery, multi-coop runner, and move test runs to test_run_folder 2026-08-19 11:14:40 +07:00
proitlab 6723701424 feat: add full cycle_start_date REST API, YAML persistence, and CORS support to dashboard.py 2026-08-19 10:32:35 +07:00
proitlab ec7226d172 docs: clarify that 2-pass mortality detection is disabled by default for higher accuracy 2026-08-19 10:24:46 +07:00
proitlab a2f44167a2 docs: update README and RUN guides with engine auto-recompilation details 2026-08-19 10:21:30 +07:00
proitlab 010f6e1493 feat: add engine auto-recompilation, mortality detection, multi-execution batching, and dashboard updates
- Add engine_utils for TensorRT compatibility verification, auto-recompilation from .pt models, and YAML auto-updates
- Add mortality detection pipeline (mortality.py, test_run_mortality.sh, mortality_config.yaml)
- Add multi-execution batch modes (parallel_processes, tensor_batching, hybrid) in batch_runner.py
- Add daily test run automation scripts and video processing runners
- Add dashboard REST API, live stream endpoints, and web UI templates
- Clean up git tracking by ignoring __pycache__, .pyc, and build artifacts
2026-08-19 10:17:17 +07:00
proitlab c05f3d98d0 Export Session 2026-07-24 10:19:43 +07:00
proitlab 3b524d4a65 Today Commit 2026-07-23 20:42:14 +07:00
proitlab 6cddf2c9d3 Fix dashboard freeze: waitress, reduce frame refresh, atomic reads
- Switch Flask dev server -> waitress (8 threads, production WSGI)
- Only refresh frame.jpg when frame_index changes, not every second
- Safety try/except on send_file for edge-case file conflicts
- Fix test_run.sh: export PYTHONPATH, use venv python
- Update service file to use venv python
2026-07-22 16:14:03 +07:00
proitlab b9f4ba2ef8 Database 2026-07-22 15:59:35 +07:00
proitlab 94c4dd81a7 consolidated models and db 2026-07-22 15:59:06 +07:00
proitlab 8cb5b01c00 Fix test_run.sh: alias->CMD (aliases don't work in scripts) 2026-07-22 15:51:35 +07:00
proitlab 3eeb20ca56 Create test run 2026-07-22 15:46:46 +07:00
proitlab f9fc6c0571 Add optimized batch config, remove large model files from tracking
- Add configs/cycle7_batch_optimized.yaml with tuned thresholds
- Update BatchConfig: add location and db_path fields
- Remove .pt/.onnx/.engine files from tracking (too large for git)
- Clean untracked test artifacts
2026-07-22 15:26:33 +07:00
proitlab e7c26d3f86 Auto-init DB on dashboard start if file missing
_init_db() creates the schema at startup so /api/db/*
endpoints work immediately without needing a batch run first.
2026-07-22 15:03:21 +07:00
proitlab dc447264b7 Reduce dashboard CPU: cache DB, suppress logs, add systemd service
- Suppress Flask request logs (werkzeug ERROR only)
- Cache SQLite connection with WAL + 8MB cache
- Increase poll_ms 500->1000, history refresh 30s->60s
- Show 'waiting for pipeline...' when /dev/shm empty
- Add chicken-dashboard.service for systemd auto-start
2026-07-22 14:56:10 +07:00
proitlab 9512fc7f4d Clean all /dev/shm counters on batch start
Wipe chicken_counter_* directories on batch start so dashboard
starts clean and populates as each camera runs.
2026-07-22 14:42:05 +07:00
proitlab ae86821165 Add DB API endpoints: summary, history, date, camera, location
- api/db/summary — overall totals
- api/db/history — per-date rows
- api/db/date/<date> — single date detail with per-camera breakdown
- api/db/camera/<id> — all runs for a specific camera
- api/db/location/<name> — per-location summary + history
- API.md — full endpoint documentation with schema
2026-07-22 14:29:53 +07:00
proitlab efd4726bc6 DB: write incrementally after each camera, Flask dashboard with single-camera view
- batch_runner: _store_to_db after each camera (not just at end)
- dashboard: Flask app with templates/index.html
- Single-camera full-screen live stream with auto-switch
- DB history panel in sidebar
- store_results.py: standalone script for existing reports
2026-07-22 14:25:35 +07:00
proitlab 6dbaa517dc Dashboard: auto-focus running camera, show date + all-camera totals
- Auto-detect active camera by polling frame_index
- Show All Cameras Total accumulation in sidebar
- Show per-camera totals in camera list
- Add run_date to stats.json and display in dashboard
- Pipeline: thread run_date through build/run/batch
2026-07-22 13:36:20 +07:00
proitlab a54d0e6b2c Optimize counting.py: fast-reject, skip empty tracks, throttle purge
- Return early when tracks list is empty
- Fast-reject centroid by bounding rect before pointPolygonTest
- Purge stale tracks every 30 frames instead of every frame
- Skip deque append when trail_length == 0
2026-07-22 13:18:05 +07:00
proitlab d31ad05f0a Remove shared tracker between cameras, fix task warning, add export script
- Remove shared DetectionTracker across cameras to prevent state leakage
- Add task="detect" to YOLO constructor to suppress warning
- Add export_engine.py script for .pt to .engine conversion
- Regenerate ONNX and TensorRT engine with latest settings
2026-07-22 13:04:30 +07:00
proitlab af4e514357 Fix WARNING and CC2 not writing json to ouput folder 2026-07-22 12:34:32 +07:00
114 changed files with 5371 additions and 791 deletions

No files matched your search

+8
View File
@@ -218,3 +218,11 @@ __marimo__/
# Streamlit
.streamlit/secrets.toml
# Project local / runtime outputs
runs/
output/
*.log
*.db-shm
*.db-wal
*.2026*
+306
View File
@@ -0,0 +1,306 @@
# Chicken Counter API
Base URL: `http://<jetson-ip>:8080`
## System Status & Live Monitoring
### `GET /api/status`
Returns real-time pipeline activity status, active streaming cameras, latest processed date, and all-time total counts.
```json
{
"status": "running",
"is_counting_active": true,
"active_cameras": ["CC1", "CC2", "CC3", "CC4"],
"latest_counted_date": "2026-06-18",
"total_chickens_all_time": 146418,
"cycle_start_date": "2026-05-22",
"timestamp": "2026-08-14T08:30:00.000000+00:00"
}
```
### `GET /`
Returns the dashboard HTML page.
### `GET /api/cameras`
List cameras currently writing to `/dev/shm`.
```json
{"cameras": ["CC1", "CC2", "CC3"]}
```
### `GET /shm/<camera_id>/stats.json`
Live stats for the active pipeline.
```json
{
"frame_index": 5120,
"inside_box_count": 42,
"total_entered_count": 1858,
"track_count": 99,
"backward_active": false,
"smoothed_speed": 4.3,
"count_events": 0,
"run_date": "2026-06-10"
}
```
### `GET /shm/<camera_id>/frame.jpg`
Live JPEG frame from the active pipeline.
---
## Database
All endpoints require the dashboard to be started with `--db <path>`. If no DB exists, endpoints return `[]` or `{}`.
### `GET /api/config/cycle_start_date`
Returns or updates the active Day 0 (`cycle_start_date`).
```bash
# Query active Day 0
GET /api/config/cycle_start_date
→ {"cycle_start_date": "2026-05-22"}
# Override Day 0 dynamically via query param or POST payload
GET /api/config/cycle_start_date?set=2026-05-22
POST /api/config/cycle_start_date {"cycle_start_date": "2026-05-22"}
→ {"status": "ok", "cycle_start_date": "2026-05-22"}
```
### `GET /api/db/summary`
Overall totals across all dates and locations.
```json
{
"days": 12,
"locations": 2,
"total_runs": 48,
"total_chickens": 125000,
"total_hours": 8.5
}
```
### `GET /api/db/history`
Per-date summary, newest first (max 50 rows).
```json
[
{
"date": "2026-06-10",
"location": "kandang-atas",
"cams": 4,
"total": 5570,
"minutes": 40.2
}
]
```
### `GET /api/db/date/<date>`
Detail for a specific date. Format: `YYYY-MM-DD`.
```json
{
"date": "2026-06-10",
"total": {"total": 5570, "minutes": 40.2},
"cameras": [
{
"camera_id": "CC1",
"total_entered": 1500,
"frames_processed": 24800,
"elapsed_seconds": 600.5,
"stopped_reason": "backward",
"source_video": "kandang_1_camera_1_2026-06-10_120056.mp4",
"location": "kandang-atas"
}
]
}
```
### `GET /api/db/camera/<camera_id>`
History for a specific camera across all dates (max 50 rows).
```json
[
{
"date": "2026-06-10",
"location": "kandang-atas",
"total_entered": 1500,
"frames_processed": 24800,
"elapsed_seconds": 600.5,
"stopped_reason": "backward"
}
]
```
### `GET /api/db/location/<location>`
Summary and history for a specific location.
```json
{
"location": "kandang-atas",
"summary": {"days": 5, "total": 25000, "hours": 3.2},
"history": [
{
"date": "2026-06-10",
"cameras": "CC1, CC2, CC3, CC4",
"total": 5570,
"minutes": 40.2
}
]
}
```
---
## Database Schema
```sql
CREATE TABLE batch_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
location TEXT NOT NULL,
camera_id TEXT NOT NULL,
total_entered INTEGER NOT NULL DEFAULT 0,
frames_processed INTEGER NOT NULL DEFAULT 0,
elapsed_seconds REAL NOT NULL DEFAULT 0.0,
stopped_reason TEXT NOT NULL DEFAULT '',
source_video TEXT NOT NULL DEFAULT '',
generated_at TEXT NOT NULL DEFAULT '',
UNIQUE(date, location, camera_id)
);
```
Data is inserted automatically by the batch runner when `location` and `db_path` are configured in the batch YAML, or manually via:
```bash
python3 store_results.py output/counts_2026-06-10.json --location kandang-atas --db chicken_counts.db
```
---
## Mortality Detection
Mortality endpoints require the dashboard to be started with `--mortality-dir <path>`. The path must contain a `mortality_report.json` file generated by `./test_run_mortality.sh`. Multiple directories can be registered with repeated `--mortality-dir` flags.
If multiple images are captured in a single day (e.g. morning and afternoon scans), the pipeline processes all images in the input directory, generates marked output JPEGs (`output_<name>.jpg`), and aggregates the daily total carcass count into `total_mortality_count`.
### `GET /api/mortality/latest`
Returns the most recently modified `mortality_report.json` across all registered mortality directories.
```json
{
"date": "2026-07-09",
"mode": "similarity_two_pass",
"model_path": "...",
"conf_threshold": 0.7,
"iou_threshold": 0.8,
"total_images": 2,
"total_mortality_count": 35,
"_dir": "/path/to/mortality",
"results": [
{
"input_image": "scan_01.jpg",
"output_image": "output_scan_01.jpg",
"count": 19,
"detections": [
{
"id": 1,
"box": [177, 161, 288, 347],
"confidence": 0.9597,
"area": 20646
}
]
},
{
"input_image": "scan_02.jpg",
"output_image": "output_scan_02.jpg",
"count": 16,
"detections": [...]
}
]
}
```
### `GET /api/mortality/history`
Returns all `mortality_report.json` files from all registered directories, sorted newest first. Each report contains `total_mortality_count` (grand total across all images in that run) and `total_images`.
### `GET /api/mortality/date/<YYYY-MM-DD>`
Returns all mortality scans and total carcass counts recorded on a specific date:
```json
{
"date": "2026-07-09",
"total_mortality_count": 35,
"total_images": 2,
"reports": [...],
"results": [...]
}
```
### `GET /api/mortality/image/<filename>`
Serves an annotated output JPEG by filename securely. Only files beginning with `output_` are accessible for security.
```
GET /api/mortality/image/output_scan_01.jpg
→ Content-Type: image/jpeg
```
---
## Starting the Dashboard
Use the portable launcher script which auto-discovers the mortality directory:
```bash
./start_dashboard.sh
```
Optional environment variables:
| Variable | Default | Description |
| :--- | :--- | :--- |
| `PORT` | `8080` | Port to listen on |
| `DB_PATH` | `db/chicken_counts.db` | Path to SQLite database |
| `MORTALITY_DIRS` | auto-detected | Comma-separated mortality dirs |
Or start manually with full control:
```bash
PYTHONPATH=src venv/bin/python dashboard.py \
--port 8080 \
--db db/chicken_counts.db \
--mortality-dir /path/to/mortality \
--mortality-dir /path/to/another/mortality
```
---
## Outbound System Notifications & Webhooks
When integrating with external management systems or cloud backends, you can query status or send automated event notifications (e.g. `STARTED`, `COMPLETED`, `MORTALITY_DETECTED`).
### 1. Polling Pipeline State
External systems can poll `GET http://<jetson-ip>:8080/api/status` every 5–10 seconds to detect if counting or mortality runs are currently in progress or finished.
### 2. Sending Outbound Webhook from Shell / Batch Scripts
To notify an external endpoint (e.g. `https://your-server.com/api/notify`) upon run lifecycle events:
```bash
# Example: Notify external server when counting starts
curl -X POST https://your-server.com/api/notify \
-H "Content-Type: application/json" \
-d '{"event": "COUNTING_STARTED", "date": "2026-06-18", "device": "jetson-sukawarna"}'
# Example: Notify external server when counting completes with JSON payload
curl -X POST https://your-server.com/api/notify \
-H "Content-Type: application/json" \
-d @/home/asus/.Codes/VIDEOS/cycle7/kandang-atas/2026-06-18/output/counts_2026-06-18.json
# Example: Notify external server when mortality scan finishes
curl -X POST https://your-server.com/api/notify \
-H "Content-Type: application/json" \
-d @/home/asus/.Codes/VIDEOS/cycle7/kandang-atas/mortality/mortality_report.json
```
+29
View File
@@ -0,0 +1,29 @@
# Changelog
All notable changes to the `chicken-counting-sukawarna-det` project are documented in this file.
## [Unreleased] - 2026-08-19
### 🐛 Bug Fixes
- **Multi-Floor Script Syntax (`run_all_coops.sh`)**:
- Resolved fatal `syntax error: unexpected end of file` caused by missing `done` in floor configuration discovery loop.
- Expanded config discovery pattern from `K*-L*.yaml` to `*.yaml` to support custom named coops (e.g. `kandang-atas.yaml`).
- **Excel Report Empty Result Crash (`export_excel_report.py`)**:
- Added empty DataFrame pre-check to prevent `IndexError` when exporting reports for dates with no batch runs or newly initialized databases.
- **Multi-Threaded SQLite Concurrency (`dashboard.py`)**:
- Replaced global single `sqlite3` connection with thread-local connections (`threading.local()`) to prevent cursor collision and race conditions across concurrent HTTP worker threads.
- Enabled `PRAGMA busy_timeout = 5000` and `PRAGMA journal_mode = WAL` to avoid database lock conflicts during batch processing writes.
- **Editable Package Installation**:
- Configured `pip install -e .` in environment setup to resolve `chicken_counter` imports and enable automatic unit test discovery without manual `PYTHONPATH` prefixes.
### ⚡ Performance & Optimization
- **Disk Traversal Caching in Live Dashboard (`dashboard.py`)**:
- Replaced repetitive `Path.rglob()` scans on every `/api/mortality/*` endpoint with a thread-safe 15-second in-memory TTL cache (`_MORTALITY_CACHE_TTL = 15.0s`).
- Added $O(1)$ memory index lookup for serving annotated images (`/api/mortality/image/<filename>`), eliminating full filesystem traversals across 30GB+ video datasets.
### 📁 Configuration & Directory Structure
- **Floor Configuration & Skeleton Paths**:
- Created `configs/floor_config/kandang-atas.yaml` extending `cycle7_batch_optimized.yaml`.
- Initialized missing directory skeletons for coops `K1-L1` through `K5-L2` under `../VIDEOS/cycle7/`.
- **Documentation**:
- Updated `README.md` and `RUN.md` with editable install steps and updated project layout.
Executable → Regular
+131 -17
View File
@@ -24,8 +24,13 @@ visual.
```text
configs/
floor_config/ ← Lightweight floor configs (K1-L1 to K5-L2, kandang-atas)
K1-L1.yaml .. K5-L2.yaml ← Extends cycle7_batch_optimized.yaml
kandang-atas.yaml ← Extends cycle7_batch_optimized.yaml
cameras/example_camera.yaml
cycle7_batch.yaml
cycle7_batch_optimized.yaml ← Base batch processing config
mortality_config.yaml
trackers/botsort_chicken.yaml
src/chicken_counter/
batch_discovery.py
@@ -35,6 +40,8 @@ src/chicken_counter/
compress.py
config.py
counting.py
engine_utils.py
mortality.py
motion.py
overlay.py
pipeline.py
@@ -42,17 +49,28 @@ src/chicken_counter/
tracking.py
types.py
video_writer.py
dashboard.py
export_engine.py
export_excel_report.py
run_all_coops.sh ← Master multi-coop batch runner
start_dashboard.sh ← Live dashboard launcher
test_run_folder/ ← Archive of test run scripts and logs
```
## Install
```bash
python -m pip install -e .
python3 -m venv venv
venv/bin/pip install --upgrade pip
venv/bin/pip install -r requirements.txt
venv/bin/pip install -e .
```
For Jetson deployment you will usually want a Jetson-compatible OpenCV and PyTorch
stack already installed, then install the rest of the package around that environment.
> **Tip:** See `RUN.md` for a full step-by-step quickstart guide for new developers.
## Run
Update `configs/cameras/example_camera.yaml` with:
@@ -199,7 +217,9 @@ detection:
imgsz: 640 # keep 640 while using existing TensorRT .engine
```
`configs/cycle7_batch.yaml` already uses these production defaults.
`configs/cycle7_batch.yaml` and `configs/cycle7_batch_optimized.yaml` already use these production defaults.
`configs/cycle7_batch_optimized.yaml` adds per-camera parallelism, trimmed inference settings, and optimized YAML structure for the Sukawarna enclosure.
**Validation:** run a short clip with stride enabled, then compare `total_entered` against
`inference_stride: 1` and `motion.stride_frames: 1`. Watch checkpoint `fps=` logs for
@@ -217,6 +237,53 @@ 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
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):
- **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`:
```bash
./venv/bin/python export_engine.py models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.pt --half --workspace 4
```
## Multi-Stage Growth Cycles & Day 0 Configuration
The pipeline dynamically adjusts detection and ROI entry thresholds based on flock age (Days Old Chick / DOC vs Mid-Cycle):
- **Day 0 (`cycle_start_date`)**: Configured in `configs/cycle7_batch_optimized.yaml` (default: `"2026-05-22"`). Can be overridden via CLI (`--cycle-start-date YYYY-MM-DD`) or REST API (`/api/config/cycle_start_date`).
- **`early_cycle` (Days 0–15)**: Automatically applies high-sensitivity detection thresholds (`conf: 0.12`, `min_box_area_px: 200`, `min_overlap_ratio: 0.25`) for small fast-moving DOC chicks.
- **`mid_cycle` (Days 16+)**: Preserves standard tuned per-camera defaults (`conf: 0.35–0.50`, `min_box_area_px: 2500–3000`).
## Mortality Detection
A separate pipeline detects carcasses (dead birds) from still photos. Supports multi-image daily runs and date subfolders (`mortality/YYYY-MM-DD/`).
```bash
# Run on default mortality directory
./test_run_mortality.sh
# Run on a specific date (auto-creates/routes to mortality/2026-05-23/)
chicken-counter mortality --date 2026-05-23
```
Key features:
- **Multi-Image & Multi-Day Support**: Processes multiple images per day (e.g. morning/afternoon scans), aggregates the grand total carcass count (`total_mortality_count`), and saves outputs into date-isolated directories.
- **Direct High-Precision Segmentation (Default)**: Uses the **segmentation model** (`models/chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt`) directly. 2-pass Detect & Refine (`two_pass: false`) is disabled by default because direct segmentation achieves higher accuracy and avoids false rejection on real farm photos.
- **Optional 2-Pass Refine (`--two-pass`)**: An optional mode combining initial segmentation candidate proposals with `cv2.matchTemplate` similarity refinement.
- **Containment filtering**: boxes where `IoA > 0.50` against a larger box are suppressed.
- **Centroid deduplication**: detections whose centroids are within `dedupe_radius_px` of each other are merged to prevent counting the same carcass twice.
Outputs for each daily run:
- `output_<name>.jpg` — annotated images with bounding boxes and carcass IDs
- `mortality_report.json` — full summary report with `total_mortality_count`, per-image breakdown, and detection coordinates
Config: `configs/mortality_config.yaml`
## Headless Jetson MP4 Example
For a headless run that saves both output video and periodic checkpoint images, use a
@@ -255,7 +322,7 @@ motion:
flow_scale: 0.5
display:
show_window: false
output_path: /media/jetson/DATA/try-sukawarna-vis.mp4
output_path: /home/asus/.Codes/try-sukawarna-vis.mp4
encoder: auto
output_bitrate_kbps: 4000
performance:
@@ -294,14 +361,15 @@ For everyday processing of 4 cameras, use `configs/cycle7_batch.yaml`.
### Input folder layout
Place today's videos under:
Place today's videos in a `VIDEOS` folder **adjacent to the project directory** (i.e. `../VIDEOS` relative to the project root):
```text
/media/jetson/DATA/chicken-sukawarna/cycle7/2026-07-09/
kandang_1_camera_1_2026-07-09_120056.mp4
kandang_1_camera_2_2026-07-09_120456.mp4
kandang_1_camera_3_2026-07-09_121012.mp4
kandang_1_camera_4_2026-07-09_121530.mp4
../VIDEOS/cycle7/kandang-atas/
2026-06-18/
kandang_1_camera_1_2026-06-18_120056.mp4
kandang_1_camera_2_2026-06-18_120456.mp4
kandang_1_camera_3_2026-06-18_121012.mp4
kandang_1_camera_4_2026-06-18_121530.mp4
```
Date folders use `YYYY-MM-DD`. Camera files are matched by `camera_num` using the
@@ -310,13 +378,32 @@ pattern `kandang_*_camera_{num}_*.mp4`.
### Run commands
```bash
# Process today's folder
chicken-counter batch --config configs/cycle7_batch.yaml
# Process today's folder using default parallel process mode
chicken-counter batch --config configs/cycle7_batch_optimized.yaml
# Process a specific date
chicken-counter batch --config configs/cycle7_batch.yaml --date 2026-07-09
# Process a specific date using Model-Level Tensor Batching mode
chicken-counter batch --config configs/cycle7_batch_optimized.yaml --date 2026-06-18 --mode tensor_batching
# Process a specific date using Hybrid mode (Threaded CPU + Batched GPU)
chicken-counter batch --config configs/cycle7_batch_optimized.yaml --date 2026-06-18 --mode hybrid
# Run automated batch script for Tensor Batching
./test_run_tensor_batch.sh # Runs all dates (2026-06-10 to 2026-06-19)
./test_run_tensor_batch.sh 2026-06-18 # Runs a specific date
# Run automated batch script for Hybrid execution mode
./test_run_hybrid.sh # Runs all dates (2026-06-10 to 2026-06-19)
./test_run_hybrid.sh 2026-06-18 # Runs a specific date
```
### Execution Modes (`execution_mode`)
Set `batch.execution_mode` in `configs/cycle7_batch_optimized.yaml` or override via `--mode`:
- `parallel_processes` (Default): Runs cameras in separate OS processes (e.g. via `test_run.sh`).
- `tensor_batching`: Synchronizes camera frame streams and executes a single batched GPU model inference pass across all cameras (`batch_size=N`).
- `hybrid`: Combines multi-threaded CPU frame capture, optical flow, and rendering across CPU cores with a single synchronized batched GPU forward pass (`batch_size=N`).
Single-camera mode still works:
```bash
@@ -327,7 +414,7 @@ chicken-counter run --config configs/cameras/example_camera.yaml
### Output layout
```text
/media/jetson/DATA/chicken-sukawarna/cycle7/2026-07-09/output/
../VIDEOS/cycle7/kandang-atas/2026-06-18/output/
CC1_vis.mp4
CC1_compressed.mp4
CC2_vis.mp4
@@ -335,7 +422,7 @@ chicken-counter run --config configs/cameras/example_camera.yaml
...
checkpoints/CC1/frame_003000.jpg
checkpoints/CC2/frame_006000.jpg
counts_2026-07-09.json
counts_2026-06-18.json
```
After all 4 cameras finish counting, the batch runner compresses each annotated video
@@ -384,11 +471,37 @@ For a ~72k frame run that is about 24 images per camera.
### Cron example
```cron
0 7 * * * cd /media/jetson/DATA/chicken-sukawarna && /usr/bin/chicken-counter batch --config configs/cycle7_batch.yaml >> logs/cycle7-batch.log 2>&1
0 7 * * * cd /path/to/chicken-counting-sukawarna-det && ./test_run.sh >> logs/cycle7-batch.log 2>&1
```
Requires `ffmpeg` on the Jetson PATH for post-run compression.
## Dashboard & API
Start the live dashboard and API server:
```bash
# Portable launcher (recommended) — auto-discovers mortality dir
./start_dashboard.sh
# Or start manually
PYTHONPATH=src venv/bin/python dashboard.py \
--port 8080 \
--db db/chicken_counts.db \
--mortality-dir ../VIDEOS/cycle7/kandang-atas/mortality
```
Key API endpoints (see `API.md` for full schema):
| Endpoint | Description |
| :--- | :--- |
| `GET /api/db/summary` | Lifetime totals across all dates |
| `GET /api/db/history` | Per-date summary, newest first |
| `GET /api/db/date/<YYYY-MM-DD>` | Per-camera breakdown for a date |
| `GET /api/mortality/latest` | Latest carcass detection report |
| `GET /api/mortality/history` | All mortality reports, newest first |
| `GET /api/mortality/image/<name>` | Serve annotated output JPEG |
## Next Jetson-Focused Improvements
1. Add a hardware-aware video ingest path for CSI/GStreamer.
@@ -397,4 +510,5 @@ Requires `ffmpeg` on the Jetson PATH for post-run compression.
Recent work includes daily 4-camera batch processing, JSON count reports, post-run
compression under 200 MB, GStreamer hardware encoding, overlay buffer reuse,
duplicate optical-flow removal (`gmc_method: none`), and long-run ETA logging.
duplicate optical-flow removal (`gmc_method: none`), long-run ETA logging, mortality
2-pass detection with feature similarity search, and a REST API via `dashboard.py`.
+231 -8
View File
@@ -1,11 +1,234 @@
# Counter
## Pakai virtual env di /media/jetson/DATA/karung-sukawarna/venv
# Quick Start Guide
alias chicken-counter='PYTHONPATH={fullpath git clone folder} /media/jetson/DATA/karung-sukawarna/venv/bin/python -m chicken_counter.cli'
This guide gets a new developer up and running from scratch.
chicken-counter batch --config configs/cycle7_batch.yaml --date 2026-06-10 --no-video --progress-bar
---
# Dashboard
## Pakai virtual env di /media/jetson/DATA/karung-sukawarna/venv
source /media/jetson/DATA/karung-sukawarna/venv/bin/source
python dashboard.py --port 8080
## 1. Prerequisites
- Python 3.10+
- `ffmpeg` on PATH (for video compression)
- NVIDIA GPU + CUDA drivers (optional but recommended for inference speed)
---
## 2. First-Time Setup
```bash
# Clone / copy the project folder, then enter it
cd chicken-counting-sukawarna-det
# Create a virtual environment and install all dependencies
python3 -m venv venv
venv/bin/pip install --upgrade pip
venv/bin/pip install -r requirements.txt
venv/bin/pip install -e .
```
> **Note**: If moving the project from another machine, always recreate the venv.
> Do NOT copy the `venv/` folder — it contains absolute paths baked in from the source machine.
---
## 3. Project Layout
```text
chicken-counting-sukawarna-det/
├── configs/
│ ├── floor_config/ ← Lightweight floor configs (K1-L1 to K5-L2, kandang-atas)
│ │ ├── K1-L1.yaml .. K5-L2.yaml ← Extends cycle7_batch_optimized.yaml
│ │ └── kandang-atas.yaml ← Extends cycle7_batch_optimized.yaml
│ ├── cycle7_batch_optimized.yaml ← Main base batch processing config
│ ├── cycle7_batch.yaml ← Alternate batch config
│ ├── mortality_config.yaml ← Mortality (carcass) detection config
│ ├── cameras/example_camera.yaml ← Single-camera run config template
│ └── trackers/botsort_chicken.yaml ← BoT-SORT tracker settings
├── db/
│ └── chicken_counts.db ← SQLite database (auto-created)
├── models/ ← Place your .pt / .onnx / .engine files here
│ ├── 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
├── src/chicken_counter/ ← Main Python package (counting, tracking, motion, engine_utils)
├── templates/ ← Dashboard HTML
├── dashboard.py ← Live API + Dashboard server
├── export_engine.py ← Manual TensorRT export utility
├── export_excel_report.py ← Excel reporting & analytics generator
├── run_all_coops.sh ← Master multi-coop batch runner (K1-L1 to K5-L2)
├── start_dashboard.sh ← Portable dashboard launcher ← USE THIS
├── test_run_folder/ ← Archive of test run scripts and logs
└── requirements.txt
```
---
## 4. Model Setup & Auto-Recompilation
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) |
> **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.
---
## 5. Running the Systems
### A — Batch Video Processing (Daily Chicken Count)
Place input videos under the `VIDEOS` folder adjacent to the project following the `K{coop}-L{floor}` format:
```text
../VIDEOS/cycle7/
K1-L1/
2026-06-18/
K1-L1_cam1_2026-06-18_120056.mp4
K1-L1_cam2_2026-06-18_120456.mp4
K1-L1_cam3_2026-06-18_121012.mp4
K1-L1_cam4_2026-06-18_121530.mp4
```
Then run:
```bash
# Run all coops (10 floors: K1-L1 to K5-L2) for a specific date
./run_all_coops.sh 2026-06-18
# Run a specific floor (e.g. Kandang 1 Lantai 1)
PYTHONPATH=src venv/bin/python -m chicken_counter.cli batch \
--config configs/floor_config/K1-L1.yaml \
--date 2026-06-18
# Run archive scripts in test_run_folder
./test_run_folder/test_run.sh
./test_run_folder/test_run_tensor_batch.sh
./test_run_folder/test_run_hybrid.sh
```
Output is saved in `../VIDEOS/cycle7/kandang-atas/2026-06-18/output/`.
---
### B — Mortality Detection (Carcass Photo Scanning)
Place input photos in `../VIDEOS/cycle7/kandang-atas/mortality/`.
```bash
# Run with default config
./test_run_mortality.sh
# Override confidence threshold
CONF=0.65 ./test_run_mortality.sh
# Run on a specific image
./test_run_mortality.sh /path/to/photo.jpg
```
Output annotated images are saved as `output_<original_name>.jpg` in the same directory.
A `mortality_report.json` is also saved there with full detection data.
#### Key config options in `configs/mortality_config.yaml`
| Setting | Description |
| :--- | :--- |
| `conf` | Detection confidence threshold (0.0–1.0) |
| `iou` | IoU NMS threshold |
| `min_box_area_px` | Minimum bounding box area in pixels |
| `dedupe_radius_px` | Centroid deduplication radius in pixels |
| `two_pass` | 2x Detect & Refine pipeline (`false` by default; single-pass direct achieves higher accuracy on farm footage) |
| `classes` | `[0]` = chicken only; ignores background/text/equipment |
---
### C — Dashboard & API Server
```bash
# Start the dashboard (auto-discovers mortality directory)
./start_dashboard.sh
# Custom port and directories
PORT=9090 ./start_dashboard.sh
# Multiple mortality directories
MORTALITY_DIRS="/path/to/mortality1,/path/to/mortality2" ./start_dashboard.sh
```
Open in browser: **http://localhost:8080**
Available API endpoints:
| Endpoint | Description |
| :--- | :--- |
| `GET /api/status` | Live system status, active counting cameras & latest date |
| `GET /api/cameras` | Live camera list from `/dev/shm` |
| `GET /api/db/summary` | Total chickens, days, hours across all dates |
| `GET /api/db/history` | Per-date summary, newest first |
| `GET /api/db/date/<YYYY-MM-DD>` | Per-camera breakdown for a specific date |
| `GET /api/db/camera/<id>` | History for a specific camera (CC1, CC2...) |
| `GET /api/db/location/<name>` | Summary and history for a location |
| `GET /api/mortality/latest` | Latest mortality detection report (JSON) |
| `GET /api/mortality/history` | All mortality reports, newest first |
| `GET /api/mortality/image/<filename>` | Serve annotated output JPEG by filename |
| `GET /shm/<cam>/stats.json` | Live pipeline stats for a running camera |
| `GET /shm/<cam>/frame.jpg` | Live frame snapshot from a running camera |
See `API.md` for full response schemas.
---
### D — Install as a System Service (Auto-Start)
```bash
# Copy the service file and adjust WorkingDirectory / User if needed
sudo cp chicken-dashboard.service /etc/systemd/system/
# Enable and start
sudo systemctl daemon-reload
sudo systemctl enable chicken-dashboard
sudo systemctl start chicken-dashboard
# Check status
sudo systemctl status chicken-dashboard
```
The service reads `start_dashboard.sh`, so it also auto-discovers the mortality directory.
---
## 6. Database
Results are automatically written to `db/chicken_counts.db` when `db_path` is set in the batch YAML. To store results manually from a JSON report:
```bash
PYTHONPATH=src venv/bin/python store_results.py \
../VIDEOS/cycle7/kandang-atas/2026-06-18/output/counts_2026-06-18.json \
--location kandang-atas \
--db db/chicken_counts.db
```
Export to Excel:
```bash
PYTHONPATH=src venv/bin/python export_excel_report.py
```
---
## 7. Moving the Project to Another Machine
1. Delete the `venv/` folder before copying:
```bash
rm -rf venv/
```
2. Copy the entire project folder to the new machine.
3. Update the `WorkingDirectory` and `ExecStart` in `chicken-dashboard.service` to the new path.
4. Recreate the venv on the new machine:
```bash
python3 -m venv venv
venv/bin/pip install -r requirements.txt
```
5. All configs and Python code use relative paths and will work without any other changes.
+16
View File
@@ -0,0 +1,16 @@
[Unit]
Description=Chicken Counter Live Dashboard
After=network.target
[Service]
Type=simple
# Uses dynamic %h (user home directory) so it works on any user account (asus, jetson, ubuntu, etc.)
WorkingDirectory=%h/.Codes/chicken-counting-sukawarna-det
ExecStart=%h/.Codes/chicken-counting-sukawarna-det/start_dashboard.sh
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1
Environment=PORT=8080
[Install]
WantedBy=default.target
+8 -5
View File
@@ -1,7 +1,7 @@
camera_id: coop_cam_03
source: /media/jetson/DATA/record/try-sukawarna.mp4
source: ../record/try-sukawarna.mp4
detection:
model_path: /media/jetson/DATA/chicken-sukawarna/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine
model_path: models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx
classes: [0]
ignored_classes: [1, 2]
conf: 0.35
@@ -10,6 +10,9 @@ detection:
device: "0"
min_box_area_px: 6000
validate_while_inside: true
# Example is coop_cam_03 — same ID-flip guard as batch CC3.
dedupe_radius_px: 24
dedupe_frames: 12
detection_zone:
enabled: true
buffer_above_px: 250
@@ -18,7 +21,7 @@ detection_zone:
tracker:
tracker_config_path: configs/trackers/botsort_chicken.yaml
persist: true
track_buffer: 75
track_buffer: 90
roi:
points:
- [80, 340]
@@ -63,7 +66,7 @@ overlay:
- [0, 255, 255]
display:
show_window: false
output_path: /media/jetson/DATA/try-sukawarna-vis.mp4
output_path: ../try-sukawarna-vis.mp4
encoder: auto
output_bitrate_kbps: 4000
codec_preference: [avc1, mp4v, H264]
@@ -75,5 +78,5 @@ feedback:
enabled: true
every_n_frames: 900
save_images: false
image_output_dir: /media/jetson/DATA/chicken-sukawarna/output/checkpoints
image_output_dir: output/checkpoints
log_to_terminal: true
Executable → Regular
+16 -4
View File
@@ -1,14 +1,16 @@
batch:
root_dir: /media/jetson/DATA/.Codes/VIDEOS/cycle7/kandang-atas
root_dir: ../VIDEOS/cycle7/kandang-atas
camera_glob: "kandang_*_camera_{num}_*.mp4"
output_subdir: output
compress_max_mb: 200
delete_intermediate: false
checkpoint_every_n_frames: 3000
location: kandang-atas
db_path: db/chicken_counts.db
defaults:
detection:
model_path: /media/jetson/DATA/.Codes/chicken-counting-sukawarna-det/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine
model_path: models/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.onnx #pt = accuracy, onnx = speed
classes: [0]
ignored_classes: [1, 2]
conf: 0.35
@@ -17,15 +19,18 @@ defaults:
device: "0"
min_box_area_px: 3000
validate_while_inside: true
# Dedupe off by default; enabled only on CC2/CC3 (see cameras below).
dedupe_radius_px: 0
dedupe_frames: 12
detection_zone:
enabled: true
buffer_above_px: 250
buffer_below_px: 250
show_in_overlay: true
tracker:
tracker_config_path: /media/jetson/DATA/.Codes/chicken-counting-sukawarna-det/configs/trackers/botsort_chicken.yaml
tracker_config_path: configs/trackers/botsort_chicken.yaml
persist: true
track_buffer: 75
track_buffer: 90
gate:
mode: two_line
lines_y: [420, 730]
@@ -95,6 +100,10 @@ cameras:
CC2:
camera_num: 2
count_anchor: [900, 120]
detection:
# ~5% double-count from ID flips; tight radius only.
dedupe_radius_px: 24
dedupe_frames: 12
roi:
points:
- [20, 380]
@@ -104,6 +113,9 @@ cameras:
CC3:
camera_num: 3
count_anchor: [900, 120]
detection:
dedupe_radius_px: 24
dedupe_frames: 12
roi:
points:
- [20, 330]
+94
View File
@@ -0,0 +1,94 @@
batch:
root_dir: /home/asus/.Codes/VIDEOS/cycle7/kandang-atas
camera_glob: "kandang_*_camera_{num}_*.mp4"
output_subdir: output
compress_max_mb: 200
delete_intermediate: false
checkpoint_every_n_frames: 3000
defaults:
detection:
model_path: /home/asus/.Codes/chicken-counting-sukawarna-det/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine
classes: [0]
ignored_classes: [1, 2]
conf: 0.35
iou: 0.55
imgsz: 640
device: "0"
min_box_area_px: 3000
validate_while_inside: true
detection_zone:
enabled: true
buffer_above_px: 250
buffer_below_px: 250
show_in_overlay: true
tracker:
tracker_config_path: /home/asus/.Codes/chicken-counting-sukawarna-det/configs/trackers/botsort_chicken.yaml
persist: true
track_buffer: 75
gate:
mode: two_line
lines_y: [420, 730]
direction: bottom_to_up
motion:
enabled: true
axis: vertical
forward_sign: 1.0
ema_alpha: 0.2
reverse_enter_threshold: -1.5
reverse_exit_threshold: -0.5
debounce_frames: 12
min_features: 60
max_corners: 80
stride_frames: 2
flow_scale: 0.5
quality_level: 0.01
min_distance: 8
block_radius: 6
overlay:
show_boxes: true
show_track_trails: false
trail_length: 20
show_center_marker: true
show_track_ring: false
count_anchor: [780, 120]
inside_box_only: true
pending_blink: true
pending_colors:
- [255, 255, 0]
- [0, 255, 255]
display:
show_window: false
encoder: auto
output_bitrate_kbps: 4000
codec_preference: [avc1, mp4v, H264]
performance:
half: false
overlay_buffer_reuse: true
inference_stride: 2
stream:
enabled: true
shm_dir: /dev/shm
interval_frames: 5
feedback:
enabled: true
every_n_frames: 3000
save_images: true
log_to_terminal: true
roi:
inset_left_px: 60
inset_right_px: 60
inset_top_px: 0
inset_bottom_px: 0
min_overlap_ratio: 0.30
cameras:
CC2:
camera_num: 2
count_anchor: [900, 120]
roi:
points:
- [20, 380]
- [1880, 380]
- [1880, 720]
- [20, 720]
+121
View File
@@ -0,0 +1,121 @@
batch:
root_dir: /home/asus/.Codes/VIDEOS/cycle7/kandang-atas
camera_glob: "kandang_*_camera_{num}_*.mp4"
output_subdir: output
compress_max_mb: 200
delete_intermediate: false
checkpoint_every_n_frames: 3000
defaults:
detection:
model_path: /home/asus/.Codes/chicken-counting-sukawarna-det/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine
classes: [0]
ignored_classes: [1, 2]
conf: 0.35
iou: 0.55
imgsz: 640
device: "0"
min_box_area_px: 3000
validate_while_inside: true
detection_zone:
enabled: true
buffer_above_px: 250
buffer_below_px: 250
show_in_overlay: true
tracker:
tracker_config_path: /home/asus/.Codes/chicken-counting-sukawarna-det/configs/trackers/botsort_chicken.yaml
persist: true
track_buffer: 75
gate:
mode: two_line
lines_y: [420, 730]
direction: bottom_to_up
motion:
enabled: true
axis: vertical
forward_sign: 1.0
ema_alpha: 0.2
reverse_enter_threshold: -1.5
reverse_exit_threshold: -0.5
debounce_frames: 12
min_features: 60
max_corners: 80
stride_frames: 2
flow_scale: 0.5
quality_level: 0.01
min_distance: 8
block_radius: 6
overlay:
show_boxes: true
show_track_trails: false
trail_length: 20
show_center_marker: true
show_track_ring: false
count_anchor: [780, 120]
inside_box_only: true
pending_blink: true
pending_colors:
- [255, 255, 0]
- [0, 255, 255]
display:
show_window: false
encoder: auto
output_bitrate_kbps: 4000
codec_preference: [avc1, mp4v, H264]
performance:
half: false
overlay_buffer_reuse: true
inference_stride: 2
stream:
enabled: true
shm_dir: /dev/shm
interval_frames: 5
feedback:
enabled: true
every_n_frames: 3000
save_images: true
log_to_terminal: true
roi:
inset_left_px: 60
inset_right_px: 60
inset_top_px: 0
inset_bottom_px: 0
min_overlap_ratio: 0.30
cameras:
CC1:
camera_num: 1
count_anchor: [780, 120]
roi:
points:
- [250, 330]
- [1650, 330]
- [1650, 720]
- [250, 720]
CC2:
camera_num: 2
count_anchor: [900, 120]
roi:
points:
- [20, 380]
- [1880, 380]
- [1880, 720]
- [20, 720]
CC3:
camera_num: 3
count_anchor: [900, 120]
roi:
points:
- [20, 330]
- [1880, 330]
- [1880, 720]
- [20, 720]
CC4:
camera_num: 4
count_anchor: [700, 120]
roi:
points:
- [50, 330]
- [1450, 330]
- [1450, 720]
- [50, 720]
+121
View File
@@ -0,0 +1,121 @@
batch:
root_dir: /home/asus/.Codes/VIDEOS/cycle7/kandang-atas
camera_glob: "kandang_*_camera_{num}_*.mp4"
output_subdir: output
compress_max_mb: 200
delete_intermediate: false
checkpoint_every_n_frames: 3000
defaults:
detection:
model_path: /home/asus/.Codes/chicken-counting-sukawarna-det/chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine
classes: [0]
ignored_classes: [1, 2]
conf: 0.35
iou: 0.55
imgsz: 640
device: "0"
min_box_area_px: 3000
validate_while_inside: true
detection_zone:
enabled: true
buffer_above_px: 250
buffer_below_px: 250
show_in_overlay: true
tracker:
tracker_config_path: /home/asus/.Codes/chicken-counting-sukawarna-det/configs/trackers/botsort_chicken.yaml
persist: true
track_buffer: 75
gate:
mode: two_line
lines_y: [420, 730]
direction: bottom_to_up
motion:
enabled: true
axis: vertical
forward_sign: 1.0
ema_alpha: 0.2
reverse_enter_threshold: -1.5
reverse_exit_threshold: -0.5
debounce_frames: 12
min_features: 60
max_corners: 80
stride_frames: 2
flow_scale: 0.5
quality_level: 0.01
min_distance: 8
block_radius: 6
overlay:
show_boxes: true
show_track_trails: false
trail_length: 20
show_center_marker: true
show_track_ring: false
count_anchor: [780, 120]
inside_box_only: true
pending_blink: true
pending_colors:
- [255, 255, 0]
- [0, 255, 255]
display:
show_window: false
encoder: auto
output_bitrate_kbps: 4000
codec_preference: [avc1, mp4v, H264]
performance:
half: false
overlay_buffer_reuse: true
inference_stride: 2
stream:
enabled: true
shm_dir: /dev/shm
interval_frames: 5
feedback:
enabled: true
every_n_frames: 3000
save_images: true
log_to_terminal: true
roi:
inset_left_px: 60
inset_right_px: 60
inset_top_px: 0
inset_bottom_px: 0
min_overlap_ratio: 0.30
cameras:
CC1:
camera_num: 1
count_anchor: [780, 120]
roi:
points:
- [250, 330]
- [1650, 330]
- [1650, 720]
- [250, 720]
CC2:
camera_num: 2
count_anchor: [900, 120]
roi:
points:
- [20, 380]
- [1880, 380]
- [1880, 720]
- [20, 720]
CC3:
camera_num: 3
count_anchor: [900, 120]
roi:
points:
- [20, 330]
- [1880, 330]
- [1880, 720]
- [20, 720]
CC4:
camera_num: 4
count_anchor: [700, 120]
roi:
points:
- [50, 330]
- [1450, 330]
- [1450, 720]
- [50, 720]
+151
View File
@@ -0,0 +1,151 @@
batch:
root_dir: "../VIDEOS/cycle7/kandang-atas"
camera_glob: "kandang_*_camera_{num}_*.mp4"
output_subdir: output
compress_max_mb: 200
delete_intermediate: false
checkpoint_every_n_frames: 3000
location: kandang-atas
db_path: db/chicken_counts.db
cycle_start_date: "2026-05-22" #day 0
execution_mode: parallel_processes # parallel_processes (default) | tensor_batching | hybrid
stages:
early_cycle:
day_min: 0
day_max: 15
detection:
conf: 0.1
min_box_area_px: 100
roi:
min_overlap_ratio: 0.1 # 0.25
mid_cycle:
day_min: 16
day_max: 999
defaults:
detection:
model_path: models/NUC5070_chicken-detection-model-v26n-300e-best-2026-05-02-NEW.engine # TensorRT engine (RTX 5070)
classes: [0]
ignored_classes: [1, 2]
conf: 0.40 # mild lift vs 0.35; 0.55 was undercounting
iou: 0.55
imgsz: 640
device: "0"
min_box_area_px: 3000
validate_while_inside: true
dedupe_radius_px: 0 # off for CC1/CC4; CC2/CC3 enable below
dedupe_frames: 12
detection_zone:
enabled: true
buffer_above_px: 250
buffer_below_px: 250
show_in_overlay: true
tracker:
tracker_config_path: configs/trackers/botsort_chicken.yaml
persist: true
track_buffer: 90
gate:
mode: two_line
lines_y: [420, 730]
direction: bottom_to_up
motion:
enabled: true
axis: vertical
forward_sign: 1.0
ema_alpha: 0.2
reverse_enter_threshold: -1.5
reverse_exit_threshold: -0.5
debounce_frames: 12
min_features: 40 # ↓ 60 → less optical flow computation
max_corners: 50 # ↓ 80 → fewer corner featuresis
stride_frames: 3 # ↑ 2 → motion detection every 3rd frame
flow_scale: 0.5
quality_level: 0.01
min_distance: 8
block_radius: 6
overlay:
show_boxes: true
show_track_trails: false
trail_length: 20
show_center_marker: false # ✗ → save 1 circle per chicken
show_track_ring: false
count_anchor: [780, 120]
inside_box_only: true
validated_only: true # NEW → only draw counted chickens
pending_blink: true
pending_colors:
- [255, 255, 0]
- [0, 255, 255]
display:
show_window: false
encoder: auto
output_bitrate_kbps: 2000 # ↓ 4000 → faster encoding
codec_preference: [avc1, mp4v, H264]
performance:
half: false
overlay_buffer_reuse: true
inference_stride: 2
stream:
enabled: true # required for dashboard live feed
shm_dir: /dev/shm
interval_frames: 5
feedback:
enabled: true
every_n_frames: 3000
save_images: false # ✗ → disable checkpoint JPEG I/O spikes
log_to_terminal: true
roi:
inset_left_px: 60
inset_right_px: 60
inset_top_px: 0
inset_bottom_px: 0
min_overlap_ratio: 0.30
cameras:
CC1:
camera_num: 1
count_anchor: [780, 120]
detection:
min_box_area_px: 2500
conf: 0.35
roi:
points:
- [250, 330]
- [1650, 330]
- [1650, 720]
- [250, 720]
CC2:
camera_num: 2
count_anchor: [900, 120]
detection:
conf: 0.5 # From 0.45
dedupe_radius_px: 32
dedupe_frames: 24 # From 18
roi:
points:
- [20, 380]
- [1880, 380]
- [1880, 720]
- [20, 720]
CC3:
camera_num: 3
count_anchor: [900, 120]
detection:
dedupe_radius_px: 24
dedupe_frames: 16 # From 12
roi:
points:
- [20, 330]
- [1880, 330]
- [1880, 720]
- [20, 720]
CC4:
camera_num: 4
count_anchor: [700, 120]
roi:
points:
- [50, 330]
- [1450, 330]
- [1450, 720]
- [50, 720]
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K1-L1
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K1-L1"
root_dir: "../VIDEOS/cycle7/K1-L1"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K1-L2
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K1-L2"
root_dir: "../VIDEOS/cycle7/K1-L2"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+7
View File
@@ -0,0 +1,7 @@
# Floor Configuration for K1-L3
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K1-L3"
root_dir: "../VIDEOS/cycle7/K1-L3"
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K2-L1
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K2-L1"
root_dir: "../VIDEOS/cycle7/K2-L1"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K2-L2
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K2-L2"
root_dir: "../VIDEOS/cycle7/K2-L2"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+7
View File
@@ -0,0 +1,7 @@
# Floor Configuration for K2-L3
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K2-L3"
root_dir: "../VIDEOS/cycle7/K2-L3"
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K3-L1
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K3-L1"
root_dir: "../VIDEOS/cycle7/K3-L1"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K3-L2
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K3-L2"
root_dir: "../VIDEOS/cycle7/K3-L2"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+7
View File
@@ -0,0 +1,7 @@
# Floor Configuration for K3-L3
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K3-L3"
root_dir: "../VIDEOS/cycle7/K3-L3"
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K4-L1
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K4-L1"
root_dir: "../VIDEOS/cycle7/K4-L1"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K4-L2
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K4-L2"
root_dir: "../VIDEOS/cycle7/K4-L2"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K5-L1
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K5-L1"
root_dir: "../VIDEOS/cycle7/K5-L1"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+17
View File
@@ -0,0 +1,17 @@
# Floor Configuration for K5-L2
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "K5-L2"
root_dir: "../VIDEOS/cycle7/K5-L2"
# Optional per-camera overrides (only uncomment and specify if this floor requires custom ROI or anchors)
# cameras:
# CC1:
# roi:
# points:
# - [250, 330]
# - [1650, 330]
# - [1650, 720]
# - [250, 720]
+7
View File
@@ -0,0 +1,7 @@
# Floor Configuration for kandang-atas
# Inherits all default settings, tracker options, model path, and stage thresholds from cycle7_batch_optimized.yaml
extends: ../cycle7_batch_optimized.yaml
batch:
location: "kandang-atas"
root_dir: "../VIDEOS/cycle7/kandang-atas"
+13
View File
@@ -0,0 +1,13 @@
# Configuration for Mortality Chicken Carcass Detection & Counting
mortality:
input_dir: "../VIDEOS/cycle7/kandang-atas/mortality"
output_dir: null # null = save output_<File Name> in input directory
model_path: "models/chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt"
device: "0" # "0" for GPU acceleration, or "cpu"
conf: 0.7
iou: 0.8
min_box_area_px: 1500
dedupe_radius_px: 30.0
two_pass: false # Enable Union 2x Detect & Refine crop pipeline
classes: [0] # Class 0 = chicken ONLY; ignores background/text/equipment (classes 1 not-chicken, 2 half-chicken)
imgsz: 640
+2 -2
View File
@@ -1,8 +1,8 @@
tracker_type: botsort
track_high_thresh: 0.5
track_low_thresh: 0.1
new_track_thresh: 0.6
track_buffer: 75
new_track_thresh: 0.65
track_buffer: 90
match_thresh: 0.8
fuse_score: true
gmc_method: none
Executable → Regular
+564 -179
View File
@@ -1,255 +1,640 @@
#!/usr/bin/env python3
"""Standalone live dashboard for chicken-counter pipeline.
Serve from project root:
PYTHONPATH=src python3 dashboard.py [--port 8080]
"""
"""Live dashboard for chicken-counter pipeline."""
from __future__ import annotations
import argparse
import json
import os
import mimetypes
import re
import sqlite3
import threading
import time
from datetime import datetime, timezone
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from socketserver import ThreadingMixIn
from urllib.parse import unquote, urlparse
from urllib.parse import parse_qs, unquote, urlparse
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
DEFAULT_SHM_DIR = "/dev/shm"
DEFAULT_PORT = 8080
TEMPLATE_DIR = Path(__file__).resolve().parent / "templates"
DASHBOARD_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Chicken Counter — Live Dashboard</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:system-ui,monospace;background:#0f0f14;color:#e0e0e0;overflow:hidden}
#app{display:flex;height:100vh}
#sidebar{width:260px;background:#16161e;padding:16px;overflow-y:auto;flex-shrink:0}
#sidebar h1{font-size:18px;color:#80dc5a;margin-bottom:16px}
#sidebar .stat{margin-bottom:12px}
#sidebar .stat label{display:block;font-size:11px;color:#888;text-transform:uppercase;letter-spacing:1px}
#sidebar .stat .value{font-size:22px;font-weight:700;color:#e0e0e0}
#sidebar .stat .value.warn{color:#ff9f43}
#sidebar .stat .value.good{color:#80dc5a}
#cam-list{list-style:none;margin-top:16px}
#cam-list li{padding:8px 10px;margin:2px 0;border-radius:6px;cursor:pointer;font-size:13px;transition:background .2s}
#cam-list li:hover{background:#222}
#cam-list li.active{background:#1a3a2a;color:#80dc5a;font-weight:700}
#cam-list li .cam-badge{float:right;font-size:10px;padding:1px 6px;border-radius:8px;background:#222;color:#888}
#cam-list li.active .cam-badge{background:#2a5a3a;color:#80dc5a}
#main{flex:1;display:flex;flex-direction:column}
#frame-container{flex:1;display:flex;align-items:center;justify-content:center;background:#000;position:relative}
#frame-img{max-width:100%;max-height:100%;object-fit:contain}
#no-frame{color:#555;font-size:18px}
#top-bar{display:flex;justify-content:space-between;align-items:center;padding:10px 16px;background:#16161e;font-size:12px}
#top-bar .refresh{color:#888}
#top-bar .status-dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px}
#top-bar .status-dot.online{background:#80dc5a;box-shadow:0 0 6px #80dc5a}
#top-bar .status-dot.offline{background:#555}
.refresh-btn{padding:4px 12px;border-radius:4px;background:#222;border:1px solid #444;color:#ccc;cursor:pointer;font-size:11px}
.refresh-btn:hover{background:#333}
</style>
</head>
<body>
<div id="app">
<div id="sidebar">
<h1>&#x1f414; Chicken Counter</h1>
<div class="stat"><label>Total Entered</label><div class="value good" id="stat-total">--</div></div>
<div class="stat"><label>Inside Box</label><div class="value" id="stat-inside">--</div></div>
<div class="stat"><label>Tracks</label><div class="value" id="stat-tracks">--</div></div>
<div class="stat"><label>Frame</label><div class="value" id="stat-frame">--</div></div>
<div class="stat"><label>Motion Speed</label><div class="value" id="stat-speed">--</div></div>
<div class="stat"><label>Status</label><div class="value" id="stat-status">--</div></div>
<ul id="cam-list"></ul>
</div>
<div id="main">
<div id="top-bar">
<span><span class="status-dot" id="status-dot"></span><span id="status-text">waiting for pipeline...</span></span>
<span><span class="refresh" id="refresh-counter"></span> ago &nbsp;
<button class="refresh-btn" onclick="load()">&#x21bb; Refresh</button></span>
</div>
<div id="frame-container">
<img id="frame-img" alt="live stream">
<div id="no-frame"></div>
</div>
</div>
</div>
<script>
var POLL_MS = %%POLL_MS%%;
var SHM = "%%SHM_DIR%%";
var cameras = [];
var activeCam = null;
var lastUpdate = 0;
var img = document.getElementById("frame-img");
var noFrame = document.getElementById("no-frame");
_thread_local = threading.local()
_db_lock = threading.Lock()
_db_path = ""
_mortality_dirs: list[Path] = []
_mortality_cache_lock = threading.Lock()
_mortality_reports_cache: list[Path] = []
_mortality_reports_mtime: float = 0.0
_mortality_image_cache: dict[str, Path] = {}
_MORTALITY_CACHE_TTL: float = 15.0 # seconds
function loadCameras() {{
fetch("/api/cameras").then(r => r.json()).then(data => {{
cameras = data.cameras || [];
renderCamList();
if (cameras.length && !activeCam) selectCam(cameras[0]);
if (!cameras.length) {{ noFrame.textContent = "No cameras found in " + SHM; img.style.display = "none"; }}
}});
}}
function renderCamList() {{
var ul = document.getElementById("cam-list");
ul.innerHTML = cameras.map(function(c) {{
return '<li class="' + (c === activeCam ? "active" : "") + '" onclick="selectCam(\'' + c + '\')">' +
c + '<span class="cam-badge">&#x25b6;</span></li>';
}}).join("");
}}
def _load_initial_cycle_start_date() -> str:
"""Read cycle_start_date from configs/cycle7_batch_optimized.yaml if available."""
cfg_path = Path(__file__).resolve().parent / "configs" / "cycle7_batch_optimized.yaml"
if cfg_path.exists():
content = cfg_path.read_text(encoding="utf-8")
match = re.search(r"^\s*cycle_start_date:\s*['\"]?([^'\"\s#]+)['\"]?", content, re.MULTILINE)
if match:
return match.group(1).strip()
return "2026-05-22"
function selectCam(id) {{
activeCam = id;
renderCamList();
load();
}}
function load() {{
if (!activeCam) return;
var t = Date.now();
img.src = "/shm/" + activeCam + "/frame.jpg?t=" + t;
fetch("/shm/" + activeCam + "/stats.json?t=" + t).then(function(r) {{
if (!r.ok) {{ setOffline(); return; }}
return r.json();
}}).then(function(s) {{
if (!s) return;
lastUpdate = Date.now();
document.getElementById("stat-total").textContent = s.total_entered_count;
document.getElementById("stat-inside").textContent = s.inside_box_count;
document.getElementById("stat-tracks").textContent = s.track_count;
document.getElementById("stat-frame").textContent = s.frame_index;
document.getElementById("stat-speed").textContent = s.smoothed_speed;
document.getElementById("stat-status").textContent = s.backward_active ? "BACKWARD STOP" : "RUNNING";
var el = document.getElementById("stat-status");
el.className = "value" + (s.backward_active ? " warn" : " good");
document.getElementById("status-dot").className = "status-dot online";
document.getElementById("status-text").textContent = activeCam + " \u2022 frame " + s.frame_index;
}});
}}
_cycle_start_date: str = _load_initial_cycle_start_date()
function setOffline() {{
document.getElementById("status-dot").className = "status-dot offline";
document.getElementById("status-text").textContent = activeCam + " \u2022 offline";
}}
function updateRefresh() {{
var ago = Math.round((Date.now() - lastUpdate) / 1000);
document.getElementById("refresh-counter").textContent = ago + "s";
}}
def _persist_cycle_start_date(new_date: str) -> bool:
"""Update in-memory cycle_start_date and save to config YAML files."""
global _cycle_start_date
_cycle_start_date = new_date
updated_any = False
for cfg_name in ("cycle7_batch_optimized.yaml", "cycle7_batch.yaml"):
cfg_path = Path(__file__).resolve().parent / "configs" / cfg_name
if cfg_path.exists():
content = cfg_path.read_text(encoding="utf-8")
pattern = r"^([ \t]*cycle_start_date:[ \t]*)(?:['\"]?)([^'\"\r\n#]+)(?:['\"]?)([ \t]*(?:#.*)?)$"
img.onerror = function() {{ img.style.display = "none"; noFrame.style.display = "block"; noFrame.textContent = "Waiting for frame..."; }};
img.onload = function() {{ img.style.display = "block"; noFrame.style.display = "none"; }};
def replacer(match: re.Match) -> str:
prefix = match.group(1)
comment = match.group(3) or ""
if comment and not comment.startswith(" "):
comment = f" {comment.lstrip()}"
if not comment.startswith(" "):
comment = f" {comment}"
return f'{prefix}"{new_date}"{comment}'
setInterval(function() {{ load(); }}, POLL_MS);
setInterval(loadCameras, 3000);
setInterval(updateRefresh, 1000);
loadCameras();
</script>
</body>
</html>"""
new_content, count = re.subn(pattern, replacer, content, count=1, flags=re.MULTILINE)
if count > 0:
cfg_path.write_text(new_content, encoding="utf-8")
updated_any = True
print(f"[dashboard] 📅 Updated cycle_start_date to: {new_date} (persisted in configs: {updated_any})")
return updated_any
def _calc_cycle_info(target_date_str: str) -> dict:
if not _cycle_start_date or not target_date_str:
return {}
try:
from datetime import date as date_type
start_d = date_type.fromisoformat(str(_cycle_start_date))
run_d = date_type.fromisoformat(str(target_date_str))
c_day = (run_d - start_d).days
stage = "early_cycle" if 0 <= c_day <= 15 else ("mid_cycle" if c_day >= 16 else "pre_cycle")
return {"cycle_day": c_day, "stage": stage}
except Exception:
return {}
def _get_db():
if not _db_path:
return None
conn = getattr(_thread_local, "conn", None)
if conn is None:
conn = sqlite3.connect(_db_path, timeout=30.0)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=5000")
conn.execute("PRAGMA cache_size=-8000")
_thread_local.conn = conn
return conn
def _init_db(db_path: str) -> None:
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("""CREATE TABLE IF NOT EXISTS batch_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL, location TEXT NOT NULL, camera_id TEXT NOT NULL,
total_entered INTEGER NOT NULL DEFAULT 0,
frames_processed INTEGER NOT NULL DEFAULT 0,
elapsed_seconds REAL NOT NULL DEFAULT 0.0,
stopped_reason TEXT NOT NULL DEFAULT '',
source_video TEXT NOT NULL DEFAULT '',
generated_at TEXT NOT NULL DEFAULT '',
UNIQUE(date, location, camera_id))""")
conn.commit()
conn.close()
def _discover_cameras(shm_dir):
shm = Path(shm_dir)
cameras = []
if shm.is_dir():
for entry in sorted(shm.iterdir()):
if entry.is_dir() and entry.name.startswith("chicken_counter_"):
cameras.append(entry.name[len("chicken_counter_"):])
return cameras
class DashboardHandler(SimpleHTTPRequestHandler):
shm_dir = DEFAULT_SHM_DIR
poll_ms = 500
poll_ms = 1000
run_date = ""
def log_message(self, format, *args):
pass
def do_OPTIONS(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
self.send_header("Content-Length", "0")
self.end_headers()
def do_GET(self):
try:
self._handle_request()
self._handle()
except (BrokenPipeError, ConnectionResetError):
pass
def _handle_request(self):
def do_POST(self):
try:
parsed = urlparse(self.path)
path = unquote(parsed.path)
if path == "/api/config/cycle_start_date":
self._handle_set_cycle_start_date()
return
self._send_error(404)
except (BrokenPipeError, ConnectionResetError):
pass
def _handle(self):
parsed = urlparse(self.path)
path = unquote(parsed.path)
if path == "/" or path == "/index.html":
html = DASHBOARD_HTML.replace("%%POLL_MS%%", str(self.poll_ms)).replace("%%SHM_DIR%%", self.shm_dir)
self._send_html(html)
if path == "/":
self._serve_html()
return
if path.startswith("/stream/"):
self._handle_stream(path)
return
if path in ("/api/status", "/api/system/status"):
self._handle_status()
return
if path == "/api/cameras":
cameras = self._discover_cameras()
self._send_json({"cameras": cameras})
self._send_json({"cameras": _discover_cameras(self.shm_dir)})
return
if path == "/api/config/cycle_start_date":
query = parse_qs(parsed.query)
if "set" in query and query["set"]:
new_date = query["set"][0].strip()
try:
from datetime import date as date_type
date_type.fromisoformat(new_date)
persisted = _persist_cycle_start_date(new_date)
self._send_json({
"status": "ok",
"message": f"Cycle start date successfully set to {new_date}",
"cycle_start_date": _cycle_start_date,
"persisted": persisted,
})
return
except ValueError as err:
self._send_json({"error": f"Invalid date format (expected YYYY-MM-DD): {err}"}, status_code=400)
return
self._send_json({"cycle_start_date": _cycle_start_date})
return
if path == "/api/config":
self._send_json({
"cycle_start_date": _cycle_start_date,
"shm_dir": self.shm_dir,
"db_path": _db_path,
})
return
if path.startswith("/api/db/"):
self._handle_db(path)
return
if path.startswith("/api/mortality"):
self._handle_mortality(path)
return
if path.startswith("/shm/"):
rel = path[len("/shm/"):]
parts = rel.split("/", 1)
if len(parts) >= 1:
parts[0] = f"chicken_counter_{parts[0]}"
rel = "/".join(parts)
shm_path = Path(self.shm_dir) / rel
resolved = shm_path.resolve()
if not str(resolved).startswith(str(Path(self.shm_dir).resolve())):
self.send_error(403)
return
if not resolved.exists():
self.send_error(404)
return
ct = "image/jpeg" if resolved.suffix in (".jpg", ".jpeg") else "application/json"
self.send_response(200)
self.send_header("Content-Type", ct)
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.end_headers()
self.wfile.write(resolved.read_bytes())
self._handle_shm(path)
return
self.send_error(404)
self._send_error(404)
def _discover_cameras(self):
shm = Path(self.shm_dir)
cameras = []
if shm.is_dir():
for entry in sorted(shm.iterdir()):
if entry.is_dir() and entry.name.startswith("chicken_counter_"):
cam_id = entry.name[len("chicken_counter_"):]
cameras.append(cam_id)
return cameras
def _handle_set_cycle_start_date(self):
content_length = int(self.headers.get("Content-Length", 0))
if content_length > 0:
body = self.rfile.read(content_length).decode("utf-8")
try:
data = json.loads(body)
new_date = str(data.get("cycle_start_date", "")).strip()
if new_date:
from datetime import date as date_type
date_type.fromisoformat(new_date)
persisted = _persist_cycle_start_date(new_date)
self._send_json({
"status": "ok",
"message": f"Cycle start date successfully set to {new_date}",
"cycle_start_date": _cycle_start_date,
"persisted": persisted,
})
return
else:
self._send_json({"error": "Missing 'cycle_start_date' in request body"}, status_code=400)
return
except ValueError as err:
self._send_json({"error": f"Invalid date format (expected YYYY-MM-DD): {err}"}, status_code=400)
return
except Exception as err:
self._send_json({"error": str(err)}, status_code=400)
return
self._send_json({"error": "Empty request body"}, status_code=400)
def _send_html(self, html: str):
def _handle_status(self):
cams = _discover_cameras(self.shm_dir)
now = time.time()
active_streams = []
for cam in cams:
stat_file = Path(self.shm_dir) / f"chicken_counter_{cam}" / "stats.json"
if stat_file.is_file() and (now - stat_file.stat().st_mtime) < 15.0:
active_streams.append(cam)
is_running = len(active_streams) > 0
conn = _get_db()
latest_date = None
total_chickens = 0
if conn:
row = conn.execute("SELECT MAX(date) AS latest_date, SUM(total_entered) AS total FROM batch_runs").fetchone()
if row:
latest_date = row["latest_date"]
total_chickens = row["total"] or 0
self._send_json({
"status": "running" if is_running else "idle",
"is_counting_active": is_running,
"active_cameras": active_streams,
"latest_counted_date": latest_date,
"total_chickens_all_time": total_chickens,
"cycle_start_date": _cycle_start_date,
"timestamp": datetime.now(timezone.utc).isoformat(),
})
def _handle_stream(self, path):
cam_id = path[len("/stream/"):]
frame_path = Path(self.shm_dir) / f"chicken_counter_{cam_id}" / "frame.jpg"
if not frame_path.exists():
self._send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=frame")
self.send_header("Cache-Control", "no-cache")
self.end_headers()
last_mtime = 0
try:
while True:
try:
mtime = frame_path.stat().st_mtime
if mtime != last_mtime:
last_mtime = mtime
data = frame_path.read_bytes()
self.wfile.write(
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n"
b"Content-Length: " + str(len(data)).encode() + b"\r\n\r\n" +
data + b"\r\n"
)
self.wfile.flush()
except (FileNotFoundError, OSError):
pass
time.sleep(0.1)
except (BrokenPipeError, ConnectionResetError):
pass
def _handle_shm(self, path):
rel = path[len("/shm/"):]
parts = rel.split("/", 1)
if len(parts) < 2:
self._send_error(404)
return
cam_id = parts[0]
file = parts[1]
fpath = Path(self.shm_dir) / f"chicken_counter_{cam_id}" / file
if str(fpath.resolve()).startswith(str(Path(self.shm_dir).resolve())):
if fpath.exists():
ct = "image/jpeg" if file.endswith(".jpg") else "application/json"
self.send_response(200)
self.send_header("Content-Type", ct)
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.end_headers()
self.wfile.write(fpath.read_bytes())
return
self._send_error(404)
def _handle_db(self, path):
conn = _get_db()
if not conn:
self._send_json({})
return
if path == "/api/db/summary":
row = conn.execute("SELECT COUNT(DISTINCT date) AS days, COUNT(DISTINCT location) AS locations, COUNT(*) AS total_runs, SUM(total_entered) AS total_chickens, ROUND(SUM(elapsed_seconds)/3600.0,1) AS total_hours FROM batch_runs").fetchone()
d = dict(row)
d["cycle_start_date"] = _cycle_start_date
self._send_json(d)
return
if path == "/api/db/history":
rows = conn.execute("SELECT date, location, COUNT(*) AS cams, SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs GROUP BY date, location ORDER BY date DESC, location LIMIT 50").fetchall()
history = []
for r in rows:
d = dict(r)
d.update(_calc_cycle_info(d["date"]))
history.append(d)
self._send_json(history)
return
# /api/db/date/<date>
prefix = "/api/db/date/"
if path.startswith(prefix):
date = path[len(prefix):]
cameras = conn.execute("SELECT camera_id, total_entered, frames_processed, ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason, source_video, location FROM batch_runs WHERE date=? ORDER BY camera_id", (date,)).fetchall()
total = conn.execute("SELECT SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs WHERE date=?", (date,)).fetchone()
res = {"date": date, "total": dict(total), "cameras": [dict(r) for r in cameras]}
res.update(_calc_cycle_info(date))
self._send_json(res)
return
# /api/db/camera/<id>
prefix = "/api/db/camera/"
if path.startswith(prefix):
cam_id = path[len(prefix):]
rows = conn.execute("SELECT date, location, total_entered, frames_processed, ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason FROM batch_runs WHERE camera_id=? ORDER BY date DESC LIMIT 50", (cam_id,)).fetchall()
self._send_json([dict(r) for r in rows])
return
# /api/db/location/<name>
prefix = "/api/db/location/"
if path.startswith(prefix):
loc = path[len(prefix):]
history = conn.execute("SELECT date, GROUP_CONCAT(camera_id,', ') AS cameras, SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs WHERE location=? GROUP BY date ORDER BY date DESC LIMIT 50", (loc,)).fetchall()
summary = conn.execute("SELECT COUNT(DISTINCT date) AS days, SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/3600.0,1) AS hours FROM batch_runs WHERE location=?", (loc,)).fetchone()
self._send_json({"location": loc, "summary": dict(summary), "history": [dict(r) for r in history]})
return
self._send_json({})
def _handle_mortality(self, path: str) -> None:
"""Serve mortality detection results.
GET /api/mortality/latest - Most recent mortality_report.json across all dirs.
GET /api/mortality/history - List of all mortality reports found (newest first).
GET /api/mortality/date/<date> - Mortality breakdown for a specific date (YYYY-MM-DD).
GET /api/mortality/image/<name> - Serve an output_*.jpg annotated image by filename.
"""
if not _mortality_dirs:
self._send_json({"error": "No mortality directory configured. Start dashboard with --mortality-dir."})
return
def _enrich_report(data: dict) -> dict:
if "total_mortality_count" not in data and "results" in data:
data["total_mortality_count"] = sum(r.get("count", 0) for r in data["results"])
return data
def _find_report_paths(force_refresh: bool = False) -> list[Path]:
global _mortality_reports_cache, _mortality_reports_mtime, _mortality_image_cache
now = time.time()
with _mortality_cache_lock:
if not force_refresh and (now - _mortality_reports_mtime) < _MORTALITY_CACHE_TTL and _mortality_reports_cache:
return list(_mortality_reports_cache)
found = []
img_cache: dict[str, Path] = {}
for mdir in _mortality_dirs:
p = Path(mdir)
if p.is_dir():
for report in p.rglob("mortality_report.json"):
found.append(report)
# Index images in the same directory as the report
for img in report.parent.glob("output_*.jpg"):
img_cache[img.name] = img
for img in report.parent.glob("output_*.png"):
img_cache[img.name] = img
_mortality_reports_cache = found
_mortality_image_cache = img_cache
_mortality_reports_mtime = now
return list(found)
def _find_image_path(filename: str) -> Path | None:
# 1. Fast memory cache lookup (O(1))
with _mortality_cache_lock:
if filename in _mortality_image_cache:
img = _mortality_image_cache[filename]
if img.is_file():
return img
# 2. Fast check in cached report parent directories
reports = _find_report_paths()
for r in reports:
candidate = r.parent / filename
if candidate.is_file():
with _mortality_cache_lock:
_mortality_image_cache[filename] = candidate
return candidate
# 3. Direct check in base mortality directories
for mdir in _mortality_dirs:
candidate = Path(mdir) / filename
if candidate.is_file():
with _mortality_cache_lock:
_mortality_image_cache[filename] = candidate
return candidate
# 4. Fallback search and update index
for mdir in _mortality_dirs:
p = Path(mdir)
if p.is_dir():
for img_path in p.rglob(filename):
if img_path.is_file():
with _mortality_cache_lock:
_mortality_image_cache[filename] = img_path
return img_path
return None
# --- /api/mortality/history ---
if path == "/api/mortality/history":
results = []
for report_path in _find_report_paths():
try:
data = json.loads(report_path.read_text(encoding="utf-8"))
data["_dir"] = str(report_path.parent)
data["_report_mtime"] = report_path.stat().st_mtime
results.append(_enrich_report(data))
except (json.JSONDecodeError, OSError):
pass
results.sort(key=lambda x: x.get("_report_mtime", 0), reverse=True)
self._send_json(results)
return
# --- /api/mortality/latest ---
if path == "/api/mortality/latest":
latest = None
latest_mtime = 0.0
for report_path in _find_report_paths():
try:
mtime = report_path.stat().st_mtime
if mtime > latest_mtime:
latest_mtime = mtime
latest = json.loads(report_path.read_text(encoding="utf-8"))
latest["_dir"] = str(report_path.parent)
except (json.JSONDecodeError, OSError):
pass
if latest:
self._send_json(_enrich_report(latest))
else:
self._send_json({"error": "No mortality report found."})
return
# --- /api/mortality/date/<date> ---
prefix_date = "/api/mortality/date/"
if path.startswith(prefix_date):
target_date = path[len(prefix_date):]
matched_reports = []
total_day_carcasses = 0
total_day_images = 0
all_results = []
for report_path in _find_report_paths():
try:
data = json.loads(report_path.read_text(encoding="utf-8"))
report_date = data.get("date") or time.strftime("%Y-%m-%d", time.localtime(report_path.stat().st_mtime))
if report_date == target_date or report_path.parent.name == target_date:
enriched = _enrich_report(data)
total_day_carcasses += enriched.get("total_mortality_count", 0)
total_day_images += enriched.get("total_images", 0)
all_results.extend(enriched.get("results", []))
matched_reports.append(enriched)
except (json.JSONDecodeError, OSError):
pass
self._send_json({
"date": target_date,
"total_mortality_count": total_day_carcasses,
"total_images": total_day_images,
"reports": matched_reports,
"results": all_results,
})
return
# --- /api/mortality/image/<filename> ---
prefix_img = "/api/mortality/image/"
if path.startswith(prefix_img):
raw_name = path[len(prefix_img):]
filename = Path(raw_name).name # Prevent path traversal attacks
# Only allow serving output_*.jpg files for security
if not (filename.startswith("output_") and filename.lower().endswith((".jpg", ".jpeg", ".png"))):
self._send_error(403)
return
img_path = _find_image_path(filename)
if img_path and img_path.is_file():
try:
data = img_path.read_bytes()
ct = mimetypes.guess_type(filename)[0] or "image/jpeg"
self.send_response(200)
self.send_header("Content-Type", ct)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-cache")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(data)
return
except (FileNotFoundError, OSError):
pass
self._send_error(404)
return
self._send_error(404)
def _serve_html(self):
html_path = TEMPLATE_DIR / "index.html"
html = html_path.read_text(encoding="utf-8")
html = html.replace("{{ poll_ms }}", str(self.poll_ms))
html = html.replace("{{ shm_dir }}", self.shm_dir)
html = html.replace("{{ date }}", self.run_date or "today")
html = html.replace("{{ db_path }}", _db_path)
data = html.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(data)
def _send_json(self, obj):
def _send_json(self, obj, status_code=200):
data = json.dumps(obj).encode("utf-8")
self.send_response(200)
self.send_response(status_code)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def _send_error(self, code):
self.send_response(code)
self.send_header("Content-Length", "0")
self.end_headers()
def main():
global _db_path, _mortality_dirs
parser = argparse.ArgumentParser(description="Chicken Counter live dashboard")
parser.add_argument("--port", type=int, default=DEFAULT_PORT, help=f"HTTP port (default: {DEFAULT_PORT})")
parser.add_argument("--shm-dir", default=DEFAULT_SHM_DIR, help=f"Shared memory directory (default: {DEFAULT_SHM_DIR})")
parser.add_argument("--poll-ms", type=int, default=500, help="Image poll interval in ms (default: 500)")
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
parser.add_argument("--shm-dir", default=DEFAULT_SHM_DIR)
parser.add_argument("--poll-ms", type=int, default=1000)
parser.add_argument("--date", default="")
parser.add_argument("--db", default="db/chicken_counts.db")
parser.add_argument("--cycle-start-date", default="", help="Start date of cycle (Day 0) in YYYY-MM-DD format.")
parser.add_argument(
"--mortality-dir",
action="append",
dest="mortality_dirs",
default=[],
metavar="DIR",
help="Directory containing mortality_report.json and output images. Repeatable for multiple dirs.",
)
args = parser.parse_args()
_mortality_dirs = [Path(d).resolve() for d in args.mortality_dirs]
if args.cycle_start_date:
global _cycle_start_date
_cycle_start_date = args.cycle_start_date
DashboardHandler.shm_dir = args.shm_dir
DashboardHandler.poll_ms = args.poll_ms
DashboardHandler.run_date = args.date
_db_path = str(Path(args.db).resolve()) if args.db else ""
if _db_path:
_init_db(_db_path)
server = ThreadingHTTPServer(("0.0.0.0", args.port), DashboardHandler)
print(f"[dashboard] serving at http://0.0.0.0:{args.port}")
print(f"[dashboard] shm_dir={args.shm_dir} poll={args.poll_ms}ms")
date_info = f" date={args.date}" if args.date else ""
print(f"[dashboard] http://0.0.0.0:{args.port} shm={args.shm_dir} db={args.db}{date_info}")
try:
server.serve_forever()
except KeyboardInterrupt:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Export a YOLO .pt model to TensorRT .engine.
Usage:
python3 export_engine.py chicken-detection-model-v26n-300e-best-2026-05-02-NEW.pt
python3 export_engine.py model.pt --imgsz 640 --half --workspace 4
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
def export_engine(
model_path: str | Path,
*,
imgsz: int = 640,
half: bool = True,
int8: bool = False,
batch: int = 1,
workspace: int = 4, # GB
simplify: bool = True,
opset: int = 17,
verbose: bool = True,
) -> str:
from ultralytics import YOLO
model = YOLO(model_path, task="detect")
output = model.export(
format="engine",
imgsz=imgsz,
half=half,
int8=int8,
batch=batch,
workspace=workspace,
simplify=simplify,
opset=opset,
verbose=verbose,
)
print(f"\nExported to: {output}")
return str(output)
def main():
parser = argparse.ArgumentParser(description="Export YOLO .pt → TensorRT .engine")
parser.add_argument("model", help="Path to .pt model file")
parser.add_argument("--imgsz", type=int, default=640, help="Input image size (default: 640)")
parser.add_argument("--half", action="store_true", default=True, help="FP16 precision (default: on)")
parser.add_argument("--no-half", dest="half", action="store_false", help="FP32 precision")
parser.add_argument("--int8", action="store_true", help="INT8 quantization (needs calibration)")
parser.add_argument("--batch", type=int, default=1, help="Batch size (default: 1)")
parser.add_argument("--workspace", type=int, default=4, help="GPU workspace in GB (default: 4)")
parser.add_argument("--opset", type=int, default=17, help="ONNX opset version (default: 17)")
parser.add_argument("--quiet", action="store_true", help="Suppress verbose output")
args = parser.parse_args()
if not Path(args.model).exists():
print(f"error: model file not found: {args.model}", file=sys.stderr)
sys.exit(1)
export_engine(
args.model,
imgsz=args.imgsz,
half=args.half,
int8=args.int8,
batch=args.batch,
workspace=args.workspace,
opset=args.opset,
verbose=not args.quiet,
)
if __name__ == "__main__":
main()
+392
View File
@@ -0,0 +1,392 @@
import sqlite3
import pandas as pd
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from openpyxl.chart import BarChart, Reference
def generate_excel_report(db_path, output_excel_path, target_date=None):
conn = sqlite3.connect(db_path)
if target_date:
df = pd.read_sql_query("SELECT * FROM batch_runs WHERE date = ? ORDER BY date ASC, camera_id ASC", conn, params=(target_date,))
else:
df = pd.read_sql_query("SELECT * FROM batch_runs ORDER BY date ASC, camera_id ASC", conn)
conn.close()
wb = openpyxl.Workbook()
# Remove default sheet
wb.remove(wb.active)
font_family = "Segoe UI"
if df.empty:
ws_empty = wb.create_sheet(title="Daily Summary")
ws_empty["A1"] = "Chicken Counter - Summary Report"
ws_empty["A1"].font = Font(name=font_family, size=16, bold=True, color="1F4E78")
target_info = f" for date {target_date}" if target_date else ""
ws_empty["A3"] = f"No batch runs found in database{target_info}."
ws_empty["A3"].font = Font(name=font_family, size=11, italic=True)
wb.save(output_excel_path)
print(f"No records found. Empty report saved to: {output_excel_path}")
return
# Styles
header_fill = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid") # Dark Navy
header_font = Font(name=font_family, size=11, bold=True, color="FFFFFF")
accent_fill = PatternFill(start_color="D9E1F2", end_color="D9E1F2", fill_type="solid") # Light Soft Blue
total_fill = PatternFill(start_color="B4C6E7", end_color="B4C6E7", fill_type="solid")
total_font = Font(name=font_family, size=11, bold=True, color="000000")
kpi_title_font = Font(name=font_family, size=9, bold=False, color="595959")
kpi_value_font = Font(name=font_family, size=18, bold=True, color="1F4E78")
thin_border = Border(
left=Side(style='thin', color='D9D9D9'),
right=Side(style='thin', color='D9D9D9'),
top=Side(style='thin', color='D9D9D9'),
bottom=Side(style='thin', color='D9D9D9')
)
top_thick_bottom_double = Border(
top=Side(style='thin', color='000000'),
bottom=Side(style='double', color='000000')
)
# -------------------------------------------------------------
# SHEET 1: Daily Summary
# -------------------------------------------------------------
ws_summary = wb.create_sheet(title="Daily Summary")
ws_summary.views.sheetView[0].showGridLines = True
# Title Block
ws_summary["A1"] = "Chicken Counter - Cycle 7 Summary Report"
ws_summary["A1"].font = Font(name=font_family, size=16, bold=True, color="1F4E78")
ws_summary["A2"] = f"Location: {df['location'].iloc[0]} | Date Range: {df['date'].min()} to {df['date'].max()}"
ws_summary["A2"].font = Font(name=font_family, size=10, italic=True, color="595959")
# KPI Cards Block (Rows 4 to 6)
kpis = [
("TOTAL CHICKENS COUNTED", df['total_entered'].sum(), "#,##0"),
("TOTAL BATCH RUNS", len(df), "#,##0"),
("TOTAL FRAMES PROCESSED", df['frames_processed'].sum(), "#,##0"),
("TOTAL ELAPSED (MINUTES)", round(df['elapsed_seconds'].sum() / 60, 1), "#,##0.0")
]
col_starts = [1, 3, 5, 7]
for (title, val, num_fmt), col_idx in zip(kpis, col_starts):
c1 = ws_summary.cell(row=4, column=col_idx, value=title)
c1.font = kpi_title_font
c1.fill = accent_fill
ws_summary.merge_cells(start_row=4, start_column=col_idx, end_row=4, end_column=col_idx+1)
c2 = ws_summary.cell(row=5, column=col_idx, value=val)
c2.font = kpi_value_font
c2.number_format = num_fmt
c2.alignment = Alignment(horizontal='center', vertical='center')
ws_summary.merge_cells(start_row=5, start_column=col_idx, end_row=6, end_column=col_idx+1)
# Pivot Data: Date vs Camera
pivot = df.pivot_table(index='date', columns='camera_id', values='total_entered', aggfunc='sum', fill_value=0)
cameras = sorted(list(pivot.columns))
start_row = 9
ws_summary.cell(row=start_row, column=1, value="Date").font = header_font
ws_summary.cell(row=start_row, column=1).fill = header_fill
ws_summary.cell(row=start_row, column=1).alignment = Alignment(horizontal='center')
for idx, cam in enumerate(cameras):
cell = ws_summary.cell(row=start_row, column=idx+2, value=cam)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal='center')
tot_header = ws_summary.cell(row=start_row, column=len(cameras)+2, value="Daily Total")
tot_header.font = header_font
tot_header.fill = header_fill
tot_header.alignment = Alignment(horizontal='center')
current_r = start_row + 1
for date_val, row_data in pivot.iterrows():
ws_summary.cell(row=current_r, column=1, value=str(date_val)).font = Font(name=font_family, size=11)
ws_summary.cell(row=current_r, column=1).alignment = Alignment(horizontal='center')
ws_summary.cell(row=current_r, column=1).border = thin_border
for idx, cam in enumerate(cameras):
c = ws_summary.cell(row=current_r, column=idx+2, value=int(row_data[cam]))
c.font = Font(name=font_family, size=11)
c.number_format = "#,##0"
c.alignment = Alignment(horizontal='right')
c.border = thin_border
# Excel SUM Formula for Daily Total
start_col_let = get_column_letter(2)
end_col_let = get_column_letter(len(cameras) + 1)
tot_c = ws_summary.cell(row=current_r, column=len(cameras)+2, value=f"=SUM({start_col_let}{current_r}:{end_col_let}{current_r})")
tot_c.font = Font(name=font_family, size=11, bold=True)
tot_c.number_format = "#,##0"
tot_c.alignment = Alignment(horizontal='right')
tot_c.border = thin_border
current_r += 1
# Total Row at Bottom
ws_summary.cell(row=current_r, column=1, value="Total").font = total_font
ws_summary.cell(row=current_r, column=1).fill = total_fill
ws_summary.cell(row=current_r, column=1).alignment = Alignment(horizontal='center')
ws_summary.cell(row=current_r, column=1).border = top_thick_bottom_double
for idx, cam in enumerate(cameras):
col_let = get_column_letter(idx + 2)
c = ws_summary.cell(row=current_r, column=idx+2, value=f"=SUM({col_let}{start_row+1}:{col_let}{current_r-1})")
c.font = total_font
c.fill = total_fill
c.number_format = "#,##0"
c.alignment = Alignment(horizontal='right')
c.border = top_thick_bottom_double
final_col_let = get_column_letter(len(cameras) + 2)
tot_final = ws_summary.cell(row=current_r, column=len(cameras)+2, value=f"=SUM({final_col_let}{start_row+1}:{final_col_let}{current_r-1})")
tot_final.font = total_font
tot_final.fill = total_fill
tot_final.number_format = "#,##0"
tot_final.alignment = Alignment(horizontal='right')
tot_final.border = top_thick_bottom_double
# Add Chart to Summary Sheet
chart = BarChart()
chart.type = "col"
chart.style = 10
chart.title = "Daily Chicken Counts by Camera"
chart.y_axis.title = "Chicken Count"
chart.x_axis.title = "Date"
chart.width = 16
chart.height = 10
data_ref = Reference(ws_summary, min_col=2, min_row=start_row, max_col=len(cameras)+1, max_row=current_r-1)
cats_ref = Reference(ws_summary, min_col=1, min_row=start_row+1, max_row=current_r-1)
chart.add_data(data_ref, titles_from_data=True)
chart.set_categories(cats_ref)
ws_summary.add_chart(chart, "I9")
# -------------------------------------------------------------
# SHEET 2: Camera Breakdown
# -------------------------------------------------------------
ws_cam = wb.create_sheet(title="Camera Summary")
ws_cam.views.sheetView[0].showGridLines = True
ws_cam["A1"] = "Camera Performance Summary"
ws_cam["A1"].font = Font(name=font_family, size=14, bold=True, color="1F4E78")
cam_pivot = df.groupby('camera_id').agg(
total_entered=('total_entered', 'sum'),
avg_entered=('total_entered', 'mean'),
total_frames=('frames_processed', 'sum'),
total_elapsed_sec=('elapsed_seconds', 'sum'),
total_runs=('id', 'count')
).reset_index()
cam_headers = ["Camera ID", "Total Chicken Count", "Average Count / Run", "Total Frames", "Total Time (Minutes)", "Total Runs"]
for c_idx, h_text in enumerate(cam_headers, 1):
cell = ws_cam.cell(row=3, column=c_idx, value=h_text)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal='center')
for r_idx, row in cam_pivot.iterrows():
row_num = 4 + r_idx
ws_cam.cell(row=row_num, column=1, value=row['camera_id']).alignment = Alignment(horizontal='center')
ws_cam.cell(row=row_num, column=2, value=int(row['total_entered'])).number_format = "#,##0"
ws_cam.cell(row=row_num, column=3, value=round(row['avg_entered'], 1)).number_format = "#,##0.0"
ws_cam.cell(row=row_num, column=4, value=int(row['total_frames'])).number_format = "#,##0"
ws_cam.cell(row=row_num, column=5, value=round(row['total_elapsed_sec'] / 60, 2)).number_format = "#,##0.00"
ws_cam.cell(row=row_num, column=6, value=int(row['total_runs'])).number_format = "#,##0"
for c_idx in range(1, 7):
ws_cam.cell(row=row_num, column=c_idx).font = Font(name=font_family, size=11)
ws_cam.cell(row=row_num, column=c_idx).border = thin_border
# Total Row for Camera Summary
tot_row_cam = 4 + len(cam_pivot)
ws_cam.cell(row=tot_row_cam, column=1, value="Total").font = total_font
ws_cam.cell(row=tot_row_cam, column=1).fill = total_fill
ws_cam.cell(row=tot_row_cam, column=1).alignment = Alignment(horizontal='center')
ws_cam.cell(row=tot_row_cam, column=1).border = top_thick_bottom_double
for c_idx in [2, 4, 6]:
col_let = get_column_letter(c_idx)
c = ws_cam.cell(row=tot_row_cam, column=c_idx, value=f"=SUM({col_let}4:{col_let}{tot_row_cam-1})")
c.font = total_font
c.fill = total_fill
c.number_format = "#,##0"
c.border = top_thick_bottom_double
# Average for Avg column
c_avg = ws_cam.cell(row=tot_row_cam, column=3, value=f"=AVERAGE(C4:C{tot_row_cam-1})")
c_avg.font = total_font
c_avg.fill = total_fill
c_avg.number_format = "#,##0.0"
c_avg.border = top_thick_bottom_double
# Sum for elapsed
c_time = ws_cam.cell(row=tot_row_cam, column=5, value=f"=SUM(E4:E{tot_row_cam-1})")
c_time.font = total_font
c_time.fill = total_fill
c_time.number_format = "#,##0.00"
c_time.border = top_thick_bottom_double
# -------------------------------------------------------------
# SHEET 3: Raw Batch Runs
# -------------------------------------------------------------
ws_raw = wb.create_sheet(title="Raw Batch Runs")
ws_raw.views.sheetView[0].showGridLines = True
raw_headers = ["ID", "Date", "Location", "Camera ID", "Total Entered", "Frames Processed", "Elapsed (s)", "Stopped Reason", "Source Video", "Generated At"]
for c_idx, h_text in enumerate(raw_headers, 1):
cell = ws_raw.cell(row=1, column=c_idx, value=h_text)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal='center')
for r_idx, row in df.iterrows():
row_num = 2 + r_idx
ws_raw.cell(row=row_num, column=1, value=int(row['id'])).alignment = Alignment(horizontal='center')
ws_raw.cell(row=row_num, column=2, value=str(row['date'])).alignment = Alignment(horizontal='center')
ws_raw.cell(row=row_num, column=3, value=str(row['location'])).alignment = Alignment(horizontal='center')
ws_raw.cell(row=row_num, column=4, value=str(row['camera_id'])).alignment = Alignment(horizontal='center')
ws_raw.cell(row=row_num, column=5, value=int(row['total_entered'])).number_format = "#,##0"
ws_raw.cell(row=row_num, column=6, value=int(row['frames_processed'])).number_format = "#,##0"
ws_raw.cell(row=row_num, column=7, value=float(row['elapsed_seconds'])).number_format = "#,##0.0"
ws_raw.cell(row=row_num, column=8, value=str(row['stopped_reason'])).alignment = Alignment(horizontal='center')
ws_raw.cell(row=row_num, column=9, value=str(row['source_video']))
ws_raw.cell(row=row_num, column=10, value=str(row['generated_at']))
for c_idx in range(1, 11):
ws_raw.cell(row=row_num, column=c_idx).font = Font(name=font_family, size=10)
ws_raw.cell(row=row_num, column=c_idx).border = thin_border
# -------------------------------------------------------------
# SHEET 4: Configurations
# -------------------------------------------------------------
ws_cfg = wb.create_sheet(title="Configurations")
ws_cfg.views.sheetView[0].showGridLines = True
ws_cfg["A1"] = "Pipeline & Model Configurations"
ws_cfg["A1"].font = Font(name=font_family, size=14, bold=True, color="1F4E78")
# Global Settings Table
ws_cfg["A3"] = "Global Pipeline & Detection Settings"
ws_cfg["A3"].font = Font(name=font_family, size=11, bold=True, color="1F4E78")
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"),
("Inference Image Size (imgsz)", "640 x 640"),
("IoU Threshold", "0.55"),
("Default Confidence Threshold (conf)", "0.40"),
("Target Classes", "[0] (Ignored: [1, 2])"),
("Default Min Box Area (px)", "3000"),
("Tracker Architecture", "BoT-SORT (persist=True, track_buffer=90)"),
("Gate Counting Mode", "two_line (lines_y: [420, 730], direction: bottom_to_up)"),
("Motion Flow Analysis", "vertical (forward_sign: 1.0, ema_alpha: 0.2, min_features: 40)"),
("Inference Stride", "2 frames (motion.stride_frames: 3)"),
("Execution Mode", "parallel_processes (MAX_JOBS=4)")
]
ws_cfg.cell(row=4, column=1, value="Configuration Parameter").font = header_font
ws_cfg.cell(row=4, column=1).fill = header_fill
ws_cfg.cell(row=4, column=2, value="Setting / Value").font = header_font
ws_cfg.cell(row=4, column=2).fill = header_fill
for idx, (param, val) in enumerate(global_configs, start=5):
c1 = ws_cfg.cell(row=idx, column=1, value=param)
c2 = ws_cfg.cell(row=idx, column=2, value=val)
c1.font = Font(name=font_family, size=10, bold=True)
c2.font = Font(name=font_family, size=10)
c1.border = thin_border
c2.border = thin_border
c1.fill = accent_fill
# Stages Table
stage_start_row = 5 + len(global_configs) + 2
ws_cfg.cell(row=stage_start_row-1, column=1, value="Cycle Stage Adaptation Rules").font = Font(name=font_family, size=11, bold=True, color="1F4E78")
stage_configs = [
("early_cycle (Day 0 - 15)", "conf: 0.10, min_box_area_px: 100, min_overlap_ratio: 0.10 (Chicks adaptation)"),
("mid_cycle (Day 16+)", "conf: 0.40, min_box_area_px: 3000, default filters (Grown chicken standard)")
]
ws_cfg.cell(row=stage_start_row, column=1, value="Cycle Stage").font = header_font
ws_cfg.cell(row=stage_start_row, column=1).fill = header_fill
ws_cfg.cell(row=stage_start_row, column=2, value="Applied Overrides").font = header_font
ws_cfg.cell(row=stage_start_row, column=2).fill = header_fill
for idx, (stg, desc) in enumerate(stage_configs, start=stage_start_row+1):
c1 = ws_cfg.cell(row=idx, column=1, value=stg)
c2 = ws_cfg.cell(row=idx, column=2, value=desc)
c1.font = Font(name=font_family, size=10, bold=True)
c2.font = Font(name=font_family, size=10)
c1.border = thin_border
c2.border = thin_border
c1.fill = accent_fill
# Per Camera Settings Table
cam_cfg_start = stage_start_row + len(stage_configs) + 3
ws_cfg.cell(row=cam_cfg_start-1, column=1, value="Per-Camera Specific Configurations").font = Font(name=font_family, size=11, bold=True, color="1F4E78")
cam_headers_cfg = ["Camera ID", "Count Anchor [X, Y]", "Confidence (conf)", "Min Box Area (px)", "Dedupe Settings", "ROI Polygon Points [X, Y]"]
for c_idx, h in enumerate(cam_headers_cfg, 1):
cell = ws_cfg.cell(row=cam_cfg_start, column=c_idx, value=h)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal='center')
cam_details = [
("CC1", "[780, 120]", "0.35", "2500", "Disabled", "[(250, 330), (1650, 330), (1650, 720), (250, 720)]"),
("CC2", "[900, 120]", "0.50", "3000", "radius=32px, frames=24", "[(20, 380), (1880, 380), (1880, 720), (20, 720)]"),
("CC3", "[900, 120]", "0.40", "3000", "radius=24px, frames=16", "[(20, 330), (1880, 330), (1880, 720), (20, 720)]"),
("CC4", "[700, 120]", "0.40", "3000", "Disabled", "[(50, 330), (1450, 330), (1450, 720), (50, 720)]")
]
for r_offset, r_data in enumerate(cam_details, 1):
curr_row = cam_cfg_start + r_offset
for col_i, val in enumerate(r_data, 1):
cell = ws_cfg.cell(row=curr_row, column=col_i, value=val)
cell.font = Font(name=font_family, size=10)
cell.border = thin_border
if col_i in [1, 2, 3, 4]:
cell.alignment = Alignment(horizontal='center')
# Auto-adjust column widths across all sheets
for ws in wb.worksheets:
for col in ws.columns:
max_len = 0
col_letter = get_column_letter(col[0].column)
for cell in col:
# Avoid large width from title/merged cells
if cell.row < 3 and ws.title == "Daily Summary":
continue
val_str = str(cell.value or '')
if len(val_str) > max_len:
max_len = len(val_str)
ws.column_dimensions[col_letter].width = max(max_len + 4, 12)
ws_summary.column_dimensions['A'].width = 16
ws_summary.column_dimensions['B'].width = 14
ws_summary.column_dimensions['C'].width = 14
ws_summary.column_dimensions['D'].width = 14
ws_summary.column_dimensions['E'].width = 14
ws_summary.column_dimensions['F'].width = 16
wb.save(output_excel_path)
print(f"Excel report successfully generated: {output_excel_path}")
if __name__ == "__main__":
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
db_file = str(BASE_DIR / "db" / "chicken_counts.db")
out_file = str(BASE_DIR / "db" / "chicken_counts_report.xlsx")
generate_excel_report(db_file, out_file)
+45
View File
@@ -0,0 +1,45 @@
#!/bin/bash
# Portable Systemd Service Installer for Chicken Counter Dashboard
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CURRENT_USER="$(id -un)"
SERVICE_NAME="chicken-dashboard.service"
echo "=== Chicken Dashboard Service Installer ==="
echo "Target User: $CURRENT_USER"
echo "Project Dir: $SCRIPT_DIR"
# Check if user wants user-level systemd (no root required) or system-level systemd
USER_SERVICE_DIR="$HOME/.config/systemd/user"
mkdir -p "$USER_SERVICE_DIR"
cat <<EOF > "$USER_SERVICE_DIR/$SERVICE_NAME"
[Unit]
Description=Chicken Counter Live Dashboard
After=network.target
[Service]
Type=simple
WorkingDirectory=$SCRIPT_DIR
ExecStart=$SCRIPT_DIR/start_dashboard.sh
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1
Environment=PORT=8080
[Install]
WantedBy=default.target
EOF
echo ""
echo "✅ Installed user service to: $USER_SERVICE_DIR/$SERVICE_NAME"
echo ""
echo "To enable and start the dashboard service (runs on boot without sudo):"
echo " systemctl --user daemon-reload"
echo " systemctl --user enable --now $SERVICE_NAME"
echo " loginctl enable-linger $CURRENT_USER # Ensures service runs even if logged out"
echo ""
echo "To check status:"
echo " systemctl --user status $SERVICE_NAME"
echo ""
Binary file not shown.
Executable → Regular
View File
File mode changed.
+74
View File
@@ -0,0 +1,74 @@
#!/bin/bash
# Master runner for 5-coop / 10-floor daily processing
set -u
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="$SCRIPT_DIR/src"
if [ -f "$SCRIPT_DIR/venv/bin/python" ]; then
PYTHON="$SCRIPT_DIR/venv/bin/python"
else
PYTHON="python3"
fi
DATE="${1:-$(date +%Y-%m-%d)}"
FILTER="${2:-}" # Optional filter like 'K1', 'K2', 'K1-L3', or leave empty for all
MODE="${3:-parallel_processes}"
# Auto-discover all configured floors in configs/floor_config/ (sorted naturally)
CONFIGS=()
for cfg in $(ls -1 "$SCRIPT_DIR/configs/floor_config/"*.yaml 2>/dev/null | sort -V); do
base_name="$(basename "$cfg" .yaml)"
if [ -n "$FILTER" ] && [[ "$base_name" != *"$FILTER"* ]]; then
continue
fi
CONFIGS+=("configs/floor_config/$(basename "$cfg")")
done
# Startup check: Ensure sibling VIDEOS directory exists
VIDEOS_BASE="$SCRIPT_DIR/../VIDEOS"
if [ ! -d "$VIDEOS_BASE" ]; then
echo "[setup] 📁 Sibling directory '$VIDEOS_BASE' not found; creating directory skeleton..."
mkdir -p "$VIDEOS_BASE/cycle7"
fi
echo "================================================================="
echo " Starting Multi-Floor Batch Processing for Date: $DATE"
if [ -n "$FILTER" ]; then
echo " Filter Applied: $FILTER"
fi
echo " Discovered Floors (${#CONFIGS[@]} total): ${CONFIGS[*]}"
echo " Execution Mode: $MODE"
echo "================================================================="
SUCCESS_COUNT=0
SKIPPED_COUNT=0
for config in "${CONFIGS[@]}"; do
if [ -f "$SCRIPT_DIR/$config" ]; then
floor_name="$(basename "$config" .yaml)"
video_day_dir="$SCRIPT_DIR/../VIDEOS/cycle7/$floor_name/$DATE"
# If videos don't exist for this floor/date on this machine, skip cleanly
if [ ! -d "$video_day_dir" ] && [ ! -d "$SCRIPT_DIR/../VIDEOS/cycle7/$floor_name" ]; then
echo "⏭️ [SKIPPED] $floor_name: No video directory found at ../VIDEOS/cycle7/$floor_name/$DATE"
SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
continue
fi
echo ""
echo ">>> [PROCESSING] Location Config: $config <<<"
if $PYTHON -m chicken_counter.cli batch --config "$config" --date "$DATE" --mode "$MODE"; then
SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
else
echo "⚠️ [SKIPPED / ERROR] $config for date $DATE (video not found or error occurred)."
SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
fi
fi
done
echo ""
echo "================================================================="
echo " Multi-Floor Batch Summary: $SUCCESS_COUNT completed, $SKIPPED_COUNT skipped."
echo " Database: db/chicken_counts.db"
echo "================================================================="
-411
View File
@@ -1,411 +0,0 @@
Metadata-Version: 2.4
Name: chicken-counter
Version: 0.1.0
Summary: First-pass Jetson chicken counting pipeline with YOLO and BoT-SORT.
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: numpy>=1.26
Requires-Dist: opencv-python>=4.10
Requires-Dist: PyYAML>=6.0.2
Requires-Dist: ultralytics>=8.4.38
# Chicken Counter
First-pass Python pipeline for Jetson-style chicken counting using Ultralytics YOLO
tracking with BoT-SORT, ROI/gate-based counting, backward-motion detection from
background optical flow, and an OpenCV overlay that matches the provided reference
visual.
## What Is Included
- Modular runtime under `src/chicken_counter/`
- Sample camera config in `configs/cameras/example_camera.yaml`
- BoT-SORT tracker settings in `configs/trackers/botsort_chicken.yaml`
- CLI entrypoint: `chicken-counter`
## Pipeline Stages
1. Capture frames from a video file or camera stream
2. Run `model.track(..., persist=True)` with class filtering for chickens only
3. Maintain per-track state, track live occupancy inside the counting box, and count unique box entries
4. Estimate backward motion from sparse optical flow on background features
5. Render an OpenCV overlay with ROI, white gates, IDs, trails, and both live/cumulative counts
## Project Layout
```text
configs/
cameras/example_camera.yaml
cycle7_batch.yaml
trackers/botsort_chicken.yaml
src/chicken_counter/
batch_discovery.py
batch_runner.py
capture.py
cli.py
compress.py
config.py
counting.py
motion.py
overlay.py
pipeline.py
report.py
tracking.py
types.py
video_writer.py
```
## Install
```bash
python -m pip install -e .
```
For Jetson deployment you will usually want a Jetson-compatible OpenCV and PyTorch
stack already installed, then install the rest of the package around that environment.
## Run
Update `configs/cameras/example_camera.yaml` with:
- `source`: your input video path, RTSP URL, or camera index
- `detection.model_path`: your TensorRT `.engine` or `.pt` checkpoint
- ROI coordinates and gate lines calibrated for the real camera
Then run:
```bash
chicken-counter --config configs/cameras/example_camera.yaml
```
Press `q` to quit the preview window.
For headless Jetson MP4 runs, set `display.show_window: false` and keep
`display.output_path` enabled so the annotated video is written without opening a GUI.
The video writer tries a Jetson GStreamer hardware encoder first when
`display.encoder: auto` or `gstreamer`, then falls back to OpenCV codecs in
`display.codec_preference` order (default: `avc1`, `mp4v`, `H264`).
## Config Notes
### Detection
The sample config restricts inference to class `0` and keeps ignored classes explicit:
- `classes: [0]`
- `ignored_classes: [1, 2]`
- `conf` and `iou` are exposed for real-footage tuning
- `min_box_area_px` can be used to reject very small partial detections from validation
- `device: "0"` should be set explicitly on Jetson CUDA
- `imgsz` must match the size used when a TensorRT `.engine` was exported
For TensorRT deployments, point `detection.model_path` at your `.engine` file and keep
`performance.half: false` (precision is already baked into the engine build).
### Tracking
The supplied tracker config enables:
- `tracker_type: botsort`
- `gmc_method: none` for fixed-camera MP4 runs (avoids duplicate optical flow)
- `with_reid: false`
Re-enable `gmc_method: sparseOptFlow` in `configs/trackers/botsort_chicken.yaml` only if
the camera mount moves or footage is shaky enough that track IDs drift without GMC.
Starting thresholds match the prompt defaults and can be tuned in
`configs/trackers/botsort_chicken.yaml`.
### Periodic Runtime Feedback
You can enable checkpoint-style progress feedback every `N` frames with the `feedback`
config block:
```yaml
feedback:
enabled: true
every_n_frames: 300
save_images: true
image_output_dir: output/checkpoints
log_to_terminal: true
```
When enabled, the pipeline will:
- print a periodic progress line with frame number, elapsed time, processing FPS, ETA, and total count
- save the current annotated frame as a checkpoint image (when `save_images: true`)
This is especially useful on Jetson when processing MP4 files headlessly, because you
can verify progress from the terminal and inspect saved snapshot images without needing
an on-device display.
### Counting ROI And Gates
The overlay is intended to resemble the reference image while staying easy to read:
- no outer green ROI outline
- one visible counting rectangle that is slightly smaller and cleaner than the previous broad region
- orange chicken bounding boxes that are visually distinct from the counting guides
- per-bird numeric labels based on count sequence, not raw tracker ID, using a non-white color
- short centroid trails
- one bold `TOTAL ENTERED` caption as the main count display, using a non-white color
The green ROI should be treated as the actual middle counting box. The current counting
semantics are:
- `Inside Box`: how many currently tracked chickens have their centroids inside the ROI
- `Total Entered`: how many unique tracked chickens have entered the ROI at least once
- a chicken is only valid for `Total Entered` if its bounding-box area meets `min_box_area_px`
- if backward motion is confirmed, the current frame is finalized and then the pipeline stops
- validated chickens receive a stable visible sequence number `1, 2, 3, ...` in entry order
- unvalidated chickens are tracked internally but do not show a visible sequence number yet
The implementation still assumes normal travel is `bottom_to_up`.
## Calibration Workflow
1. Start with a representative frame from the real camera.
2. Set `roi.points` so the counting rectangle spans the intended middle counting box only.
3. If the displayed rectangle feels too large or small, tighten or expand `roi.points` directly.
4. Run a short clip and compare `Inside Box` against the visible birds currently in that box.
5. Increase `min_box_area_px` if small partial chickens are being counted too early.
6. Verify `Total Entered` only increases when a new tracked bird enters the box during forward motion and is large enough to be valid.
6. Verify that once backward motion is confirmed, the output video ends at that point and the MP4 is finalized cleanly.
7. Verify that the highest displayed sequence number matches `Total Entered`.
8. Verify the final freeze frame stays on screen long enough to read the last total clearly.
## Backward-Motion Tuning
The stop trigger is separate from chicken tracks. It measures background motion while
masking detected chicken boxes.
Tune these values against real footage:
- `motion.forward_sign`
- `motion.ema_alpha`
- `motion.reverse_enter_threshold`
- `motion.reverse_exit_threshold`
- `motion.debounce_frames`
- `motion.min_features`
- `motion.stride_frames` (run flow every N frames; `2` is faster)
- `motion.flow_scale` (downscale ROI gray before flow; `0.5` is faster)
- `motion.max_corners` (fewer corners = faster; try `80`)
Important: confirm the actual sign convention from real cart footage before treating
the configured forward direction as final.
## Jetson Performance Speedups
For long batch runs, enable inference and motion stride in config:
```yaml
performance:
inference_stride: 2 # run YOLO+BoT-SORT every 2nd frame; reuse tracks in between
motion:
stride_frames: 2 # run optical flow every 2nd frame
flow_scale: 0.5 # half-resolution flow inside ROI crop
max_corners: 80
detection:
imgsz: 640 # keep 640 while using existing TensorRT .engine
```
`configs/cycle7_batch.yaml` already uses these production defaults.
**Validation:** run a short clip with stride enabled, then compare `total_entered` against
`inference_stride: 1` and `motion.stride_frames: 1`. Watch checkpoint `fps=` logs for
speedup. Box positions may lag by up to one frame on skipped inference frames.
Set `inference_stride: 1` or `motion.stride_frames: 1` to restore full per-frame accuracy
for tuning.
## Known Limits In This First Pass
- No DeepStream integration yet
- No multi-process or multi-camera scheduler yet
- Counting currently assumes vertical motion and `bottom_to_up` travel
- The live box count depends on stable tracking centroids inside the ROI
- The optical-flow trigger is vision-first, though the config structure leaves room for
a future controller/encoder integration path
## Headless Jetson MP4 Example
For a headless run that saves both output video and periodic checkpoint images, use a
config shaped like this:
```yaml
display:
show_window: false
output_path: output/coop_cam_03_overlay.mp4
encoder: auto
output_bitrate_kbps: 4000
feedback:
enabled: true
every_n_frames: 300
save_images: true
image_output_dir: output/checkpoints
log_to_terminal: true
```
## 40-Minute Jetson Recipe
For long headless runs (~72,000 frames at 30 FPS), use the production-oriented settings
in `configs/cameras/example_camera.yaml`:
```yaml
detection:
device: "0"
imgsz: 640
model_path: /path/to/your-model.engine
overlay:
show_track_trails: false
show_track_ring: false
motion:
max_corners: 80
stride_frames: 2
flow_scale: 0.5
display:
show_window: false
output_path: /media/jetson/DATA/try-sukawarna-vis.mp4
encoder: auto
output_bitrate_kbps: 4000
performance:
half: false
overlay_buffer_reuse: true
inference_stride: 2
feedback:
enabled: true
every_n_frames: 900
log_to_terminal: true
save_images: false
```
Tracker YAML should use `gmc_method: none` for fixed-camera footage.
Lower `display.output_bitrate_kbps` produces smaller MP4 files with more compression
artifacts. Start at `4000` and adjust after inspecting output quality.
Checkpoint logs look like:
```text
[checkpoint] frame=9000/72000 elapsed=18m12s fps=8.2 total_entered=142 eta=2h05m status=running
```
When backward motion is confirmed, the pipeline now:
- finishes the current annotated frame
- writes that frame to the output video
- logs the backward-stop event
- appends a short freeze frame so the final total is readable
- exits immediately afterward, so the output MP4 ends there
## Daily Cycle7 Multi-Camera Batch
For everyday processing of 4 cameras, use `configs/cycle7_batch.yaml`.
### Input folder layout
Place today's videos under:
```text
/media/jetson/DATA/chicken-sukawarna/cycle7/2026-07-09/
kandang_1_camera_1_2026-07-09_120056.mp4
kandang_1_camera_2_2026-07-09_120456.mp4
kandang_1_camera_3_2026-07-09_121012.mp4
kandang_1_camera_4_2026-07-09_121530.mp4
```
Date folders use `YYYY-MM-DD`. Camera files are matched by `camera_num` using the
pattern `kandang_*_camera_{num}_*.mp4`.
### Run commands
```bash
# Process today's folder
chicken-counter batch --config configs/cycle7_batch.yaml
# Process a specific date
chicken-counter batch --config configs/cycle7_batch.yaml --date 2026-07-09
```
Single-camera mode still works:
```bash
chicken-counter --config configs/cameras/example_camera.yaml
chicken-counter run --config configs/cameras/example_camera.yaml
```
### Output layout
```text
/media/jetson/DATA/chicken-sukawarna/cycle7/2026-07-09/output/
CC1_vis.mp4
CC1_compressed.mp4
CC2_vis.mp4
CC2_compressed.mp4
...
checkpoints/CC1/frame_003000.jpg
checkpoints/CC2/frame_006000.jpg
counts_2026-07-09.json
```
After all 4 cameras finish counting, the batch runner compresses each annotated video
to under `batch.compress_max_mb` (default 200 MB) using `ffmpeg`.
### Per-camera counting boxes
| Camera | ROI points |
|--------|------------|
| CC1 | `[250,330], [1650,330], [1650,720], [250,720]` |
| CC2 | `[20,380], [1880,380], [1880,720], [20,720]` |
| CC3 | `[20,330], [1880,330], [1880,720], [20,720]` |
| CC4 | `[50,330], [1450,330], [1450,720], [50,720]` |
Tune these in `configs/cycle7_batch.yaml` if a lane drifts after camera maintenance.
### JSON report format
`counts_{date}.json` contains per-camera totals and the sum across all 4 cameras:
```json
{
"date": "2026-07-09",
"generated_at": "2026-07-09T11:45:00+00:00",
"cameras": {
"CC1": {
"total_entered": 142,
"source_video": "kandang_1_camera_1_2026-07-09_120056.mp4",
"vis_video": "CC1_vis.mp4",
"compressed_video": "CC1_compressed.mp4",
"compressed_size_mb": 187.4,
"frames_processed": 68432,
"stopped_reason": "backward",
"elapsed_seconds": 8234.5
}
},
"total_entered_sum": 580
}
```
### Checkpoint images
Batch mode saves review images every `checkpoint_every_n_frames` (default 3000) per camera.
For a ~72k frame run that is about 24 images per camera.
### Cron example
```cron
0 7 * * * cd /media/jetson/DATA/chicken-sukawarna && /usr/bin/chicken-counter batch --config configs/cycle7_batch.yaml >> logs/cycle7-batch.log 2>&1
```
Requires `ffmpeg` on the Jetson PATH for post-run compression.
## Next Jetson-Focused Improvements
1. Add a hardware-aware video ingest path for CSI/GStreamer.
2. Export richer event logs for per-bird count timestamps.
3. Add a controller-signal adapter so encoder direction can override vision when available.
Recent work includes daily 4-camera batch processing, JSON count reports, post-run
compression under 200 MB, GStreamer hardware encoding, overlay buffer reuse,
duplicate optical-flow removal (`gmc_method: none`), and long-run ETA logging.
-24
View File
@@ -1,24 +0,0 @@
README.md
pyproject.toml
src/chicken_counter/__init__.py
src/chicken_counter/batch_discovery.py
src/chicken_counter/batch_runner.py
src/chicken_counter/capture.py
src/chicken_counter/cli.py
src/chicken_counter/compress.py
src/chicken_counter/config.py
src/chicken_counter/counting.py
src/chicken_counter/motion.py
src/chicken_counter/overlay.py
src/chicken_counter/pipeline.py
src/chicken_counter/report.py
src/chicken_counter/tracking.py
src/chicken_counter/types.py
src/chicken_counter/video_writer.py
src/chicken_counter.egg-info/PKG-INFO
src/chicken_counter.egg-info/SOURCES.txt
src/chicken_counter.egg-info/dependency_links.txt
src/chicken_counter.egg-info/entry_points.txt
src/chicken_counter.egg-info/requires.txt
src/chicken_counter.egg-info/top_level.txt
tests/test_tracking.py
@@ -1 +0,0 @@
@@ -1,2 +0,0 @@
[console_scripts]
chicken-counter = chicken_counter.cli:main
@@ -1,4 +0,0 @@
numpy>=1.26
opencv-python>=4.10
PyYAML>=6.0.2
ultralytics>=8.4.38
@@ -1 +0,0 @@
chicken_counter
Executable → Regular
View File
File mode changed.
Binary file not shown.
+54 -4
View File
@@ -16,22 +16,72 @@ class CameraDiscoveryResult:
def discover_camera_videos(day_dir: Path, settings: BatchSettings) -> CameraDiscoveryResult:
if not day_dir.is_dir():
raise FileNotFoundError(f"Daily input folder does not exist: {day_dir}")
# Startup check: Auto-create skeleton root_dir if missing
root_p = Path(settings.batch.root_dir)
if not root_p.exists():
root_p.mkdir(parents=True, exist_ok=True)
print(f"[batch] 📁 Created missing video root directory: {root_p}")
raise FileNotFoundError(
f"Daily input folder does not exist: {day_dir}\n"
f"👉 Place camera video files (e.g. {settings.batch.location}_cam1_*.mp4 .. cam4_*.mp4) inside: {day_dir}"
)
result = CameraDiscoveryResult()
total_configured = len(settings.cameras)
# Exclude output videos and non-video files
def _is_valid_source_video(path: Path) -> bool:
name = path.name.lower()
if name.endswith(("_vis.mp4", "_compressed.mp4", "_overlay.mp4", "_preview.mp4")):
return False
if "output" in path.parts:
return False
return path.suffix.lower() in (".mp4", ".avi", ".mkv", ".mov")
for camera_id, preset in sorted(
settings.cameras.items(),
key=lambda item: item[1].camera_num,
):
pattern = settings.batch.camera_glob.format(num=preset.camera_num)
matches = sorted(day_dir.glob(pattern))
num = preset.camera_num
primary_pattern = settings.batch.camera_glob.format(num=num)
matches = [p for p in sorted(day_dir.glob(primary_pattern)) if _is_valid_source_video(p)]
# Fallback candidate patterns if primary pattern doesn't match
if not matches:
fallback_patterns = [
f"*cam{num}_*.mp4",
f"*cam_{num}_*.mp4",
f"*camera_{num}_*.mp4",
f"*camera{num}_*.mp4",
f"*_c{num}_*.mp4",
f"*cam{num}.mp4",
f"*camera{num}.mp4",
f"*camera_{num}.mp4",
]
for fb_pat in fallback_patterns:
matches = [p for p in sorted(day_dir.glob(fb_pat)) if _is_valid_source_video(p)]
if matches:
break
# Case-insensitive fallback search
if not matches:
for f in sorted(day_dir.iterdir()):
if f.is_file() and _is_valid_source_video(f):
fname = f.name.lower()
if (
f"cam{num}" in fname
or f"cam_{num}" in fname
or f"camera_{num}" in fname
or f"camera{num}" in fname
or f"_c{num}" in fname
):
matches.append(f)
if not matches:
result.skipped[camera_id] = "video_not_found"
continue
if len(matches) > 1:
result.skipped[camera_id] = "multiple_matches"
result.skipped[camera_id] = f"multiple_matches ({[m.name for m in matches]})"
continue
result.found[camera_id] = matches[0]
+595 -25
View File
@@ -1,47 +1,611 @@
"""Run CC1–CC4 sequentially, then compress videos and write the JSON report."""
from __future__ import annotations
import shutil
import time
from concurrent.futures import ThreadPoolExecutor
import cv2
import numpy as np
from datetime import date as date_type
from pathlib import Path
from chicken_counter.batch_discovery import discover_camera_videos
from chicken_counter.batch_discovery import CameraDiscoveryResult, discover_camera_videos
from chicken_counter.compress import compress_video_to_target
from chicken_counter.config import BatchSettings, build_camera_config_from_batch
from chicken_counter.pipeline import run_pipeline
from chicken_counter.config import BatchSettings, CameraConfig, CameraPreset, build_camera_config_from_batch
from chicken_counter.engine_utils import ensure_compatible_model
from chicken_counter.overlay import draw_overlay
from chicken_counter.pipeline import PipelineArtifacts, _consume_result, _write_stream_frame, build_pipeline, run_pipeline
from chicken_counter.report import build_batch_report, persist_batch_reports
from chicken_counter.tracking import DetectionTracker
from chicken_counter.types import CameraBatchResult
from chicken_counter.types import CameraBatchResult, FrameResult, PipelineResult, TrackObservation
def run_daily_batch(settings: BatchSettings, date: str | None = None, *, verbose: bool = False, no_video: bool = False, show_progress: bool = False) -> Path:
def _store_to_db(report_path: Path, location: str, db_path: str) -> None:
if not location or not db_path:
return
import json
import sqlite3
try:
with open(report_path) as f:
report = json.load(f)
except Exception:
return
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(db_path, timeout=60.0)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("""CREATE TABLE IF NOT EXISTS batch_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL, location TEXT NOT NULL, camera_id TEXT NOT NULL,
total_entered INTEGER NOT NULL DEFAULT 0,
frames_processed INTEGER NOT NULL DEFAULT 0,
elapsed_seconds REAL NOT NULL DEFAULT 0.0,
stopped_reason TEXT NOT NULL DEFAULT '',
source_video TEXT NOT NULL DEFAULT '',
generated_at TEXT NOT NULL DEFAULT '',
UNIQUE(date, location, camera_id))""")
date = report["date"]
for camera_id, entry in report["cameras"].items():
if entry.get("skipped"):
continue
conn.execute("""INSERT INTO batch_runs
(date, location, camera_id, total_entered, frames_processed,
elapsed_seconds, stopped_reason, source_video, generated_at)
VALUES (?,?,?,?,?,?,?,?,?)
ON CONFLICT(date, location, camera_id) DO UPDATE SET
total_entered=excluded.total_entered,
frames_processed=excluded.frames_processed,
elapsed_seconds=excluded.elapsed_seconds,
stopped_reason=excluded.stopped_reason,
source_video=excluded.source_video,
generated_at=excluded.generated_at""",
(date, location, camera_id,
entry.get("total_entered", 0),
entry.get("frames_processed", 0),
entry.get("elapsed_seconds", 0),
entry.get("stopped_reason", ""),
entry.get("source_video", ""),
report.get("generated_at", "")))
conn.commit()
conn.close()
print(f"[db] stored {date} ({location}) → {db_path}")
def run_tensor_batched_daily_batch(
settings: BatchSettings,
date: str | None = None,
*,
verbose: bool = False,
no_video: bool = False,
show_progress: bool = False,
cycle_start_date: str | None = None,
) -> Path:
if cycle_start_date:
settings.batch.cycle_start_date = cycle_start_date
run_date = date or date_type.today().isoformat()
day_dir = Path(settings.batch.root_dir) / run_date
output_dir = day_dir / settings.batch.output_subdir
output_dir.mkdir(parents=True, exist_ok=True)
print(f"[batch] starting daily run for {run_date}")
print(f"[batch-tensor] starting tensor-batched daily run for {run_date}")
print(f"[batch-tensor] input folder: {day_dir}")
print(f"[batch-tensor] output folder: {output_dir}")
shm_dir = Path("/dev/shm")
for d in shm_dir.glob("chicken_counter_*"):
if d.is_dir():
try:
shutil.rmtree(str(d))
except Exception:
pass
discovery = discover_camera_videos(day_dir, settings)
camera_order = sorted(settings.cameras.items(), key=lambda item: item[1].camera_num)
active_cams: list[tuple[str, CameraConfig, PipelineArtifacts]] = []
camera_results: list[CameraBatchResult] = []
report_path = output_dir / f"counts_{run_date}.json"
first_config = None
for camera_id, _preset in camera_order:
if camera_id in discovery.skipped:
skip_reason = discovery.skipped[camera_id]
print(f"[batch-tensor] skipping {camera_id}: {skip_reason}")
camera_results.append(
CameraBatchResult(
camera_id=camera_id,
skipped=True,
skip_reason=skip_reason,
)
)
continue
source_path = discovery.found[camera_id]
vis_path = output_dir / f"{camera_id}_vis.mp4" if not no_video else None
checkpoint_dir = output_dir / "checkpoints" / camera_id
camera_config = build_camera_config_from_batch(
settings,
camera_id,
source=source_path,
output_path=vis_path,
checkpoint_dir=checkpoint_dir,
date=run_date,
)
camera_config.performance.verbose = verbose
if first_config is None:
first_config = camera_config
if not first_config:
persist_batch_reports(run_date, camera_results, output_dir)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
return report_path
shared_tracker = DetectionTracker(first_config)
for camera_id, _preset in camera_order:
if camera_id in discovery.skipped:
continue
source_path = discovery.found[camera_id]
vis_path = output_dir / f"{camera_id}_vis.mp4" if not no_video else None
checkpoint_dir = output_dir / "checkpoints" / camera_id
camera_config = build_camera_config_from_batch(
settings,
camera_id,
source=source_path,
output_path=vis_path,
checkpoint_dir=checkpoint_dir,
date=run_date,
)
camera_config.performance.verbose = verbose
artifacts = build_pipeline(camera_config, tracker=shared_tracker, run_date=run_date)
active_cams.append((camera_id, camera_config, artifacts))
inference_stride = max(1, first_config.performance.inference_stride)
frame_index = 0
active_indices = list(range(len(active_cams)))
last_batch_tracks: dict[str, list[TrackObservation]] = {cam_id: [] for cam_id, _, _ in active_cams}
stopped_reasons: dict[str, str] = {cam_id: "eof" for cam_id, _, _ in active_cams}
frame_counts: dict[str, int] = {cam_id: 0 for cam_id, _, _ in active_cams}
print(f"[batch-tensor] running synchronized batch tracking across {len(active_cams)} active cameras...")
while active_indices:
frame_index += 1
current_frames = []
current_crops = []
current_active = []
for idx in list(active_indices):
cam_id, config, artifacts = active_cams[idx]
ok, frame = artifacts.capture.read()
if not ok:
stopped_reasons[cam_id] = "eof"
active_indices.remove(idx)
continue
frame_counts[cam_id] += 1
current_frames.append(frame)
current_crops.append(artifacts.detection_zone_rect)
current_active.append(idx)
if not current_active:
break
if frame_index % inference_stride == 0 or any(not last_batch_tracks[active_cams[i][0]] for i in current_active):
batch_tracks_list = shared_tracker.infer_batch(current_frames, crop_rects=current_crops)
for i, idx in enumerate(current_active):
cam_id = active_cams[idx][0]
last_batch_tracks[cam_id] = batch_tracks_list[i]
for i, idx in enumerate(current_active):
cam_id, config, artifacts = active_cams[idx]
frame = current_frames[i]
tracks = last_batch_tracks[cam_id]
motion_state = artifacts.motion_detector.update(frame, tracks, frame_counts[cam_id])
count_events = artifacts.counting_zone.update(
tracks, frame_counts[cam_id], counting_paused=motion_state.backward_active
)
needs_overlay = config.display.show_window or artifacts.writer is not None or config.stream.enabled
annotated = draw_overlay(
frame, config, artifacts.counting_zone, tracks, motion_state,
frame_index=frame_counts[cam_id], buffer=artifacts.overlay_buffer
) if needs_overlay else frame
result = FrameResult(
frame_index=frame_counts[cam_id],
tracks=tracks,
inside_box_count=artifacts.counting_zone.inside_box_count,
total_entered_count=artifacts.counting_zone.total_entered_count,
motion_state=motion_state,
count_events=count_events,
)
_consume_result(config, artifacts, annotated, result, None)
if config.stream.enabled and frame_counts[cam_id] % max(1, config.stream.interval_frames) == 0:
_write_stream_frame(config.stream.shm_dir, config.camera_id, annotated, result, run_date=artifacts.run_date)
if motion_state.backward_active:
stopped_reasons[cam_id] = "backward"
print(f"[batch-tensor] backward motion confirmed for {cam_id} at frame={frame_counts[cam_id]}")
active_indices.remove(idx)
for cam_id, config, artifacts in active_cams:
elapsed_seconds = time.monotonic() - artifacts.run_start_time
artifacts.capture.release()
if artifacts.writer is not None:
artifacts.writer.release()
p_res = PipelineResult(
camera_id=cam_id,
total_entered_count=artifacts.counting_zone.total_entered_count,
frames_processed=frame_counts[cam_id],
stopped_reason=stopped_reasons[cam_id],
vis_video_path=config.display.output_path,
source_video=str(config.source),
elapsed_seconds=elapsed_seconds,
)
camera_results.append(CameraBatchResult(camera_id=cam_id, pipeline=p_res))
print(
f"[batch-tensor] finished {cam_id}: total_entered={p_res.total_entered_count} "
f"frames={p_res.frames_processed} reason={p_res.stopped_reason}"
)
persist_batch_reports(run_date, camera_results, output_dir)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
if not no_video:
print("[batch-tensor] all cameras complete; starting compression")
for item in camera_results:
if item.skipped or item.pipeline is None:
continue
vis_path = item.pipeline.vis_video_path
if not vis_path:
continue
compressed_path = output_dir / f"{item.camera_id}_compressed.mp4"
size_mb = compress_video_to_target(
vis_path,
compressed_path,
max_mb=settings.batch.compress_max_mb,
)
item.compressed_video_path = str(compressed_path)
item.compressed_size_mb = size_mb
if settings.batch.delete_intermediate:
Path(vis_path).unlink(missing_ok=True)
persist_batch_reports(run_date, camera_results, output_dir)
report = build_batch_report(run_date, camera_results, output_dir=output_dir)
print(
f"[batch-tensor] complete for {run_date}: total_entered_sum={report.total_entered_sum} "
f"report={report_path}"
)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
return report_path
def run_hybrid_daily_batch(
settings: BatchSettings,
date: str | None = None,
*,
verbose: bool = False,
no_video: bool = False,
show_progress: bool = False,
cycle_start_date: str | None = None,
) -> Path:
if cycle_start_date:
settings.batch.cycle_start_date = cycle_start_date
run_date = date or date_type.today().isoformat()
day_dir = Path(settings.batch.root_dir) / run_date
output_dir = day_dir / settings.batch.output_subdir
output_dir.mkdir(parents=True, exist_ok=True)
print(f"[batch-hybrid] starting hybrid (threaded CPU + batched GPU) daily run for {run_date}")
print(f"[batch-hybrid] input folder: {day_dir}")
print(f"[batch-hybrid] output folder: {output_dir}")
shm_dir = Path("/dev/shm")
for d in shm_dir.glob("chicken_counter_*"):
if d.is_dir():
try:
shutil.rmtree(str(d))
except Exception:
pass
discovery = discover_camera_videos(day_dir, settings)
camera_order = sorted(settings.cameras.items(), key=lambda item: item[1].camera_num)
active_cams: list[tuple[str, CameraConfig, PipelineArtifacts]] = []
camera_results: list[CameraBatchResult] = []
report_path = output_dir / f"counts_{run_date}.json"
first_config = None
for camera_id, _preset in camera_order:
if camera_id in discovery.skipped:
skip_reason = discovery.skipped[camera_id]
print(f"[batch-hybrid] skipping {camera_id}: {skip_reason}")
camera_results.append(
CameraBatchResult(
camera_id=camera_id,
skipped=True,
skip_reason=skip_reason,
)
)
continue
source_path = discovery.found[camera_id]
vis_path = output_dir / f"{camera_id}_vis.mp4" if not no_video else None
checkpoint_dir = output_dir / "checkpoints" / camera_id
camera_config = build_camera_config_from_batch(
settings,
camera_id,
source=source_path,
output_path=vis_path,
checkpoint_dir=checkpoint_dir,
date=run_date,
)
camera_config.performance.verbose = verbose
if first_config is None:
first_config = camera_config
if not first_config:
persist_batch_reports(run_date, camera_results, output_dir)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
return report_path
shared_tracker = DetectionTracker(first_config)
for camera_id, _preset in camera_order:
if camera_id in discovery.skipped:
continue
source_path = discovery.found[camera_id]
vis_path = output_dir / f"{camera_id}_vis.mp4" if not no_video else None
checkpoint_dir = output_dir / "checkpoints" / camera_id
camera_config = build_camera_config_from_batch(
settings,
camera_id,
source=source_path,
output_path=vis_path,
checkpoint_dir=checkpoint_dir,
date=run_date,
)
camera_config.performance.verbose = verbose
artifacts = build_pipeline(camera_config, tracker=shared_tracker, run_date=run_date)
active_cams.append((camera_id, camera_config, artifacts))
inference_stride = max(1, first_config.performance.inference_stride)
frame_index = 0
active_indices = list(range(len(active_cams)))
last_batch_tracks: dict[str, list[TrackObservation]] = {cam_id: [] for cam_id, _, _ in active_cams}
stopped_reasons: dict[str, str] = {cam_id: "eof" for cam_id, _, _ in active_cams}
frame_counts: dict[str, int] = {cam_id: 0 for cam_id, _, _ in active_cams}
elapsed_times: dict[str, float] = {}
print(f"[batch-hybrid] running hybrid pipeline across {len(active_cams)} active cameras...")
def read_camera_frame(idx: int):
cam_id, config, artifacts = active_cams[idx]
ok, frame = artifacts.capture.read()
if not ok:
return idx, False, None, None
return idx, True, frame, artifacts.detection_zone_rect
def process_camera_post(idx: int, frame, tracks):
cam_id, config, artifacts = active_cams[idx]
count = frame_counts[cam_id]
motion_state = artifacts.motion_detector.update(frame, tracks, count)
count_events = artifacts.counting_zone.update(
tracks, count, counting_paused=motion_state.backward_active
)
needs_overlay = config.display.show_window or artifacts.writer is not None or config.stream.enabled
annotated = draw_overlay(
frame, config, artifacts.counting_zone, tracks, motion_state,
frame_index=count, buffer=artifacts.overlay_buffer
) if needs_overlay else frame
result = FrameResult(
frame_index=count,
tracks=tracks,
inside_box_count=artifacts.counting_zone.inside_box_count,
total_entered_count=artifacts.counting_zone.total_entered_count,
motion_state=motion_state,
count_events=count_events,
)
_consume_result(config, artifacts, annotated, result, None)
if config.stream.enabled and count % max(1, config.stream.interval_frames) == 0:
_write_stream_frame(config.stream.shm_dir, config.camera_id, annotated, result, run_date=artifacts.run_date)
return idx, motion_state
max_threads = max(1, len(active_cams))
with ThreadPoolExecutor(max_workers=max_threads) as pool:
while active_indices:
frame_index += 1
current_active = list(active_indices)
# 1. Parallel frame capture across active cameras (threaded CPU)
read_futures = [pool.submit(read_camera_frame, idx) for idx in current_active]
captured = []
for fut in read_futures:
idx, ok, frame, crop_rect = fut.result()
cam_id, _, artifacts = active_cams[idx]
if not ok:
stopped_reasons[cam_id] = "eof"
if cam_id not in elapsed_times:
elapsed_times[cam_id] = time.monotonic() - artifacts.run_start_time
if idx in active_indices:
active_indices.remove(idx)
else:
frame_counts[cam_id] += 1
captured.append((idx, frame, crop_rect))
if not captured:
break
current_active_now = [item[0] for item in captured]
current_frames = [item[1] for item in captured]
current_crops = [item[2] for item in captured]
# 2. Batched GPU inference (Synchronous on main thread)
if frame_index % inference_stride == 0 or any(not last_batch_tracks[active_cams[i][0]] for i in current_active_now):
batch_tracks_list = shared_tracker.infer_batch(current_frames, crop_rects=current_crops)
for i, idx in enumerate(current_active_now):
cam_id = active_cams[idx][0]
last_batch_tracks[cam_id] = batch_tracks_list[i]
# 3. Parallel Post-processing across active cameras (threaded CPU)
post_futures = [
pool.submit(
process_camera_post,
idx,
current_frames[i],
last_batch_tracks[active_cams[idx][0]],
)
for i, idx in enumerate(current_active_now)
]
for fut in post_futures:
idx, motion_state = fut.result()
if motion_state.backward_active:
cam_id, _, artifacts = active_cams[idx]
stopped_reasons[cam_id] = "backward"
if cam_id not in elapsed_times:
elapsed_times[cam_id] = time.monotonic() - artifacts.run_start_time
print(f"[batch-hybrid] backward motion confirmed for {cam_id} at frame={frame_counts[cam_id]}")
if idx in active_indices:
active_indices.remove(idx)
for cam_id, config, artifacts in active_cams:
elapsed_seconds = elapsed_times.get(cam_id, time.monotonic() - artifacts.run_start_time)
artifacts.capture.release()
if artifacts.writer is not None:
artifacts.writer.release()
p_res = PipelineResult(
camera_id=cam_id,
total_entered_count=artifacts.counting_zone.total_entered_count,
frames_processed=frame_counts[cam_id],
stopped_reason=stopped_reasons[cam_id],
vis_video_path=config.display.output_path,
source_video=str(config.source),
elapsed_seconds=elapsed_seconds,
)
camera_results.append(CameraBatchResult(camera_id=cam_id, pipeline=p_res))
print(
f"[batch-hybrid] finished {cam_id}: total_entered={p_res.total_entered_count} "
f"frames={p_res.frames_processed} reason={p_res.stopped_reason}"
)
persist_batch_reports(run_date, camera_results, output_dir)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
if not no_video:
print("[batch-hybrid] all cameras complete; starting compression")
for item in camera_results:
if item.skipped or item.pipeline is None:
continue
vis_path = item.pipeline.vis_video_path
if not vis_path:
continue
compressed_path = output_dir / f"{item.camera_id}_compressed.mp4"
size_mb = compress_video_to_target(
vis_path,
compressed_path,
max_mb=settings.batch.compress_max_mb,
)
item.compressed_video_path = str(compressed_path)
item.compressed_size_mb = size_mb
if settings.batch.delete_intermediate:
Path(vis_path).unlink(missing_ok=True)
persist_batch_reports(run_date, camera_results, output_dir)
report = build_batch_report(run_date, camera_results, output_dir=output_dir)
print(
f"[batch-hybrid] complete for {run_date}: total_entered_sum={report.total_entered_sum} "
f"report={report_path}"
)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
return report_path
def run_daily_batch(
settings: BatchSettings,
date: str | None = None,
*,
camera_id: str | None = None,
verbose: bool = False,
no_video: bool = False,
show_progress: bool = False,
cycle_start_date: str | None = None,
) -> Path:
if cycle_start_date:
settings.batch.cycle_start_date = cycle_start_date
# Pre-validate and ensure compatible model in batch settings
default_model = settings.defaults.get("detection", {}).get("model_path")
if default_model:
device = settings.defaults.get("detection", {}).get("device", "0")
imgsz = settings.defaults.get("detection", {}).get("imgsz", 640)
validated_model = ensure_compatible_model(
default_model,
device=device,
imgsz=imgsz,
config_file_path=getattr(settings, "config_path", None),
)
settings.defaults["detection"]["model_path"] = validated_model
execution_mode = settings.batch.execution_mode
if execution_mode == "hybrid" and not camera_id:
return run_hybrid_daily_batch(
settings,
date=date,
verbose=verbose,
no_video=no_video,
show_progress=show_progress,
cycle_start_date=cycle_start_date,
)
if execution_mode == "tensor_batching" and not camera_id:
return run_tensor_batched_daily_batch(
settings,
date=date,
verbose=verbose,
no_video=no_video,
show_progress=show_progress,
cycle_start_date=cycle_start_date,
)
run_date = date or date_type.today().isoformat()
day_dir = Path(settings.batch.root_dir) / run_date
output_dir = day_dir / settings.batch.output_subdir
output_dir.mkdir(parents=True, exist_ok=True)
print(f"[batch] starting daily run for {run_date} (mode: {execution_mode})" + (f" (camera: {camera_id})" if camera_id else ""))
print(f"[batch] input folder: {day_dir}")
print(f"[batch] output folder: {output_dir}")
# Clean all /dev/shm counters from previous runs
shm_dir = Path("/dev/shm")
for d in shm_dir.glob("chicken_counter_*"):
if d.is_dir():
try:
shutil.rmtree(str(d))
except Exception:
pass
if no_video:
print("[batch] --no-video: skipping video output, overlay, and compression")
discovery = discover_camera_videos(day_dir, settings)
camera_order = sorted(settings.cameras.items(), key=lambda item: item[1].camera_num)
first_camera_id = next(
camera_id for camera_id, _preset in camera_order if camera_id in discovery.found
)
first_source = discovery.found[first_camera_id]
init_output_path = output_dir / f"{first_camera_id}_vis.mp4" if not no_video else None
init_config = build_camera_config_from_batch(
settings,
first_camera_id,
source=first_source,
output_path=init_output_path,
checkpoint_dir=output_dir / "checkpoints" / first_camera_id,
)
shared_tracker = DetectionTracker(init_config)
if camera_id:
camera_order = [item for item in camera_order if item[0] == camera_id]
camera_results: list[CameraBatchResult] = []
report_path = output_dir / f"counts_{run_date}.json"
@@ -58,6 +622,7 @@ def run_daily_batch(settings: BatchSettings, date: str | None = None, *, verbose
)
)
persist_batch_reports(run_date, camera_results, output_dir)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
continue
source_path = discovery.found[camera_id]
@@ -71,9 +636,10 @@ def run_daily_batch(settings: BatchSettings, date: str | None = None, *, verbose
source=source_path,
output_path=vis_path,
checkpoint_dir=checkpoint_dir,
date=run_date,
)
camera_config.performance.verbose = verbose
pipeline_result = run_pipeline(camera_config, tracker=shared_tracker, show_progress=show_progress)
pipeline_result = run_pipeline(camera_config, show_progress=show_progress, run_date=run_date)
camera_results.append(
CameraBatchResult(
camera_id=camera_id,
@@ -85,13 +651,16 @@ def run_daily_batch(settings: BatchSettings, date: str | None = None, *, verbose
f"frames={pipeline_result.frames_processed} reason={pipeline_result.stopped_reason}"
)
persist_batch_reports(run_date, camera_results, output_dir)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
if no_video:
persist_batch_reports(run_date, camera_results, output_dir)
report = build_batch_report(run_date, camera_results, output_dir=output_dir)
print(
f"[batch] complete for {run_date}: total_entered_sum={report.total_entered_sum} "
f"report={report_path}"
)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
return report_path
print("[batch] all cameras complete; starting compression")
@@ -120,4 +689,5 @@ def run_daily_batch(settings: BatchSettings, date: str | None = None, *, verbose
f"[batch] complete for {run_date}: total_entered_sum={report.total_entered_sum} "
f"report={report_path}"
)
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
return report_path
Executable → Regular
View File
File mode changed.
Executable → Regular
+54 -1
View File
@@ -6,6 +6,7 @@ import argparse
from chicken_counter.batch_runner import run_daily_batch
from chicken_counter.config import load_batch_config, load_camera_config
from chicken_counter.mortality import DEFAULT_CONFIG_PATH, DEFAULT_MORTALITY_DIR, DEFAULT_MODEL_PATH, run_mortality_count
from chicken_counter.pipeline import run_pipeline
@@ -25,10 +26,33 @@ def build_parser() -> argparse.ArgumentParser:
"--date",
help="Processing date folder in YYYY-MM-DD format. Defaults to today.",
)
batch_parser.add_argument("--camera", "--camera-id", help="Filter to run only a specific camera ID (e.g. CC1).")
batch_parser.add_argument("--verbose", action="store_true", help="Enable debug-level logging.")
batch_parser.add_argument("--no-video", action="store_true", help="Skip video output and compression for speed.")
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(
"--mode",
"--execution-mode",
dest="mode",
choices=["parallel_processes", "tensor_batching", "hybrid"],
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.")
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("--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).")
mortality_parser.add_argument("--conf", type=float, default=None, help="Confidence threshold (overrides YAML config).")
mortality_parser.add_argument("--iou", type=float, default=None, help="NMS IoU threshold (overrides YAML config).")
mortality_parser.add_argument("--min-area", type=int, default=None, help="Minimum box area in pixels (overrides YAML config).")
mortality_parser.add_argument("--dedupe-radius", type=float, default=None, help="Deduplication radius in pixels (overrides YAML config).")
mortality_parser.add_argument("--date", default=None, help="Date for the mortality run in YYYY-MM-DD format.")
mortality_parser.add_argument("--two-pass", action="store_true", default=None, help="Enable 2x Detect & Refine crop pipeline.")
mortality_parser.add_argument("--no-two-pass", action="store_false", dest="two_pass", help="Disable 2x Detect & Refine crop pipeline.")
parser.add_argument("--config", help=argparse.SUPPRESS)
parser.add_argument("--camera-id", help=argparse.SUPPRESS)
return parser
@@ -38,9 +62,38 @@ def main() -> None:
parser = build_parser()
args = parser.parse_args()
if args.command == "mortality":
run_mortality_count(
input_path=args.input,
output_dir=args.output_dir,
model_path=args.model_path,
conf_threshold=args.conf,
iou_threshold=args.iou,
min_box_area_px=args.min_area,
dedupe_radius_px=args.dedupe_radius,
two_pass=args.two_pass,
config_path=args.config,
date=getattr(args, "date", None),
)
return
if args.command == "batch":
settings = load_batch_config(args.config)
run_daily_batch(settings, date=args.date, verbose=args.verbose, no_video=args.no_video, show_progress=args.progress_bar)
if getattr(args, "output_subdir", None):
settings.batch.output_subdir = args.output_subdir
if getattr(args, "cycle_start_date", None):
settings.batch.cycle_start_date = args.cycle_start_date
if getattr(args, "mode", None):
settings.batch.execution_mode = args.mode
run_daily_batch(
settings,
date=args.date,
camera_id=getattr(args, "camera", None),
verbose=args.verbose,
no_video=args.no_video,
show_progress=args.progress_bar,
cycle_start_date=getattr(args, "cycle_start_date", None),
)
return
if args.command == "run":
Executable → Regular
+2
View File
@@ -59,6 +59,8 @@ def compress_video_to_target(
output_file.unlink()
codec_attempts = [
["-c:v", "h264_nvenc", "-preset", "p4", "-b:v", f"{attempt_kbps}k", "-maxrate", f"{attempt_kbps}k", "-bufsize", f"{attempt_kbps * 2}k"],
["-c:v", "hevc_nvenc", "-preset", "p4", "-b:v", f"{attempt_kbps}k", "-maxrate", f"{attempt_kbps}k", "-bufsize", f"{attempt_kbps * 2}k"],
["-c:v", "h264_nvmpi", "-b:v", f"{attempt_kbps}k", "-maxrate", f"{attempt_kbps}k", "-bufsize", f"{attempt_kbps * 2}k"],
["-c:v", "libx264", "-preset", "fast", "-b:v", f"{attempt_kbps}k", "-maxrate", f"{attempt_kbps}k", "-bufsize", f"{attempt_kbps * 2}k"],
]
Executable → Regular
+122 -7
View File
@@ -13,6 +13,19 @@ import yaml
Point = tuple[int, int]
PROJECT_ROOT = Path(__file__).resolve().parents[2]
def resolve_project_path(p: str | Path | None, base_dir: Path | None = None) -> str:
"""Resolve relative path against PROJECT_ROOT (or base_dir) so configs work anywhere."""
if p is None or p == "":
return ""
path_obj = Path(p)
if path_obj.is_absolute():
return str(path_obj)
root = base_dir or PROJECT_ROOT
return str((root / path_obj).resolve())
@dataclass
class DetectionConfig:
@@ -25,6 +38,9 @@ class DetectionConfig:
device: str | int | None = None
min_box_area_px: int = 0
validate_while_inside: bool = True
# Off by default; enable per-camera (e.g. CC2/CC3) for ID-flip double counts.
dedupe_radius_px: int = 0
dedupe_frames: int = 12
@dataclass
@@ -53,7 +69,7 @@ class DetectionZoneConfig:
class TrackerConfig:
tracker_config_path: str
persist: bool = True
track_buffer: int = 75
track_buffer: int = 90
@dataclass
@@ -145,6 +161,7 @@ class OverlayConfig:
show_track_ring: bool = False
count_anchor: Point = (900, 120)
inside_box_only: bool = True
validated_only: bool = True
pending_blink: bool = True
pending_colors: list[Color] = field(
default_factory=lambda: [(255, 255, 0), (0, 255, 255)]
@@ -202,6 +219,7 @@ class CameraConfig:
feedback: FeedbackConfig
detection_zone: DetectionZoneConfig = field(default_factory=DetectionZoneConfig)
stream: StreamConfig = field(default_factory=StreamConfig)
config_path: str | None = None
@dataclass
@@ -212,6 +230,10 @@ class BatchConfig:
compress_max_mb: int = 200
delete_intermediate: bool = False
checkpoint_every_n_frames: int = 3000
location: str = ""
db_path: str = ""
cycle_start_date: str | None = None
execution_mode: str = "parallel_processes"
@dataclass
@@ -222,6 +244,8 @@ class CameraPreset:
count_anchor: Point | None = None
gate: GateConfig | None = None
motion: MotionConfig | None = None
# Deep-merged over batch defaults (e.g. detection.dedupe_* for CC2/CC3).
overrides: dict[str, Any] = field(default_factory=dict)
@dataclass
@@ -229,6 +253,8 @@ class BatchSettings:
batch: BatchConfig
defaults: dict[str, Any]
cameras: dict[str, CameraPreset]
stages: dict[str, Any] = field(default_factory=dict)
config_path: str | None = None
def _load_data(path: Path) -> dict[str, Any]:
@@ -250,7 +276,9 @@ def _build_overlay_config(overlay_raw: dict[str, Any]) -> OverlayConfig:
overlay_kwargs["pending_colors"] = [
tuple(map(int, color)) for color in overlay_raw["pending_colors"]
]
return OverlayConfig(**overlay_kwargs)
valid_fields = OverlayConfig.__dataclass_fields__.keys()
filtered_kwargs = {k: v for k, v in overlay_kwargs.items() if k in valid_fields}
return OverlayConfig(**filtered_kwargs)
def _build_roi_config(roi_raw: dict[str, Any]) -> RoiConfig:
@@ -265,6 +293,13 @@ def _build_roi_config(roi_raw: dict[str, Any]) -> RoiConfig:
def _build_camera_config(raw: dict[str, Any]) -> CameraConfig:
raw = copy.deepcopy(raw)
if "detection" in raw and "model_path" in raw["detection"]:
raw["detection"]["model_path"] = resolve_project_path(raw["detection"]["model_path"])
if "tracker" in raw and "tracker_config_path" in raw["tracker"]:
raw["tracker"]["tracker_config_path"] = resolve_project_path(raw["tracker"]["tracker_config_path"])
if "source" in raw:
raw["source"] = resolve_project_path(raw["source"])
return CameraConfig(
camera_id=raw["camera_id"],
source=raw["source"],
@@ -279,6 +314,7 @@ def _build_camera_config(raw: dict[str, Any]) -> CameraConfig:
feedback=FeedbackConfig(**raw.get("feedback", {})),
detection_zone=DetectionZoneConfig(**raw.get("detection_zone", {})),
stream=StreamConfig(**raw.get("stream", {})),
config_path=raw.get("config_path"),
)
@@ -293,9 +329,19 @@ def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any
def load_camera_config(path: str | Path, camera_id: str | None = None) -> CameraConfig:
config_path = Path(path)
config_path = Path(path).resolve()
raw = _load_data(config_path)
base_ref = raw.pop("extends", None) or raw.pop("base_config", None)
if base_ref:
base_path = (config_path.parent / base_ref).resolve()
if not base_path.exists():
base_path = resolve_project_path(base_ref)
if not base_path.exists():
raise FileNotFoundError(f"Base config not found: {base_ref} (referenced in {config_path.name})")
base_raw = _load_data(base_path)
raw = _deep_merge(base_raw, raw)
if "batch" in raw:
raise ValueError(
"This is a batch config file. Use 'chicken-counter batch --config ...' instead."
@@ -306,18 +352,36 @@ def load_camera_config(path: str | Path, camera_id: str | None = None) -> Camera
raise ValueError("camera_id is required when config contains multiple cameras")
raw = raw["cameras"][camera_id]
raw["config_path"] = str(config_path)
return _build_camera_config(raw)
def load_batch_config(path: str | Path) -> BatchSettings:
config_path = Path(path)
config_path = Path(path).resolve()
raw = _load_data(config_path)
base_ref = raw.pop("extends", None) or raw.pop("base_config", None)
if base_ref:
base_path = (config_path.parent / base_ref).resolve()
if not base_path.exists():
base_path = resolve_project_path(base_ref)
if not base_path.exists():
raise FileNotFoundError(f"Base config not found: {base_ref} (referenced in {config_path.name})")
base_raw = _load_data(base_path)
raw = _deep_merge(base_raw, raw)
if "batch" not in raw:
raise ValueError("Batch config must contain a top-level 'batch' section")
batch = BatchConfig(**raw["batch"])
raw_batch = copy.deepcopy(raw["batch"])
if "root_dir" in raw_batch:
raw_batch["root_dir"] = resolve_project_path(raw_batch["root_dir"])
if "db_path" in raw_batch:
raw_batch["db_path"] = resolve_project_path(raw_batch["db_path"])
batch = BatchConfig(**raw_batch)
defaults = raw.get("defaults", {})
stages = raw.get("stages", {})
cameras: dict[str, CameraPreset] = {}
for camera_id, camera_raw in raw.get("cameras", {}).items():
@@ -331,6 +395,17 @@ def load_batch_config(path: str | Path) -> BatchSettings:
gate = GateConfig(**camera_raw["gate"]) if "gate" in camera_raw else None
motion = MotionConfig(**camera_raw["motion"]) if "motion" in camera_raw else None
# Preserve per-camera section overrides so they merge into defaults at build time.
reserved = {"camera_num", "roi", "count_anchor", "gate", "motion"}
overrides = {
key: value
for key, value in camera_raw.items()
if key not in reserved and isinstance(value, dict)
}
# count_anchor is also applied via preset; keep overlay-only dict overrides.
if "overlay" in camera_raw and isinstance(camera_raw["overlay"], dict):
overrides["overlay"] = camera_raw["overlay"]
cameras[camera_id] = CameraPreset(
camera_id=camera_id,
camera_num=int(camera_raw["camera_num"]),
@@ -338,9 +413,16 @@ def load_batch_config(path: str | Path) -> BatchSettings:
count_anchor=count_anchor,
gate=gate,
motion=motion,
overrides=overrides,
)
return BatchSettings(batch=batch, defaults=defaults, cameras=cameras)
return BatchSettings(
batch=batch,
defaults=defaults,
cameras=cameras,
stages=stages,
config_path=str(config_path),
)
def build_camera_config_from_batch(
@@ -350,12 +432,45 @@ def build_camera_config_from_batch(
source: str | Path,
output_path: str | Path | None,
checkpoint_dir: str | Path,
date: str | None = None,
) -> CameraConfig:
if camera_id not in settings.cameras:
raise KeyError(f"Unknown camera_id in batch config: {camera_id}")
preset = settings.cameras[camera_id]
raw = _deep_merge(settings.defaults, {"camera_id": camera_id, "source": str(source)})
raw = _deep_merge(
settings.defaults,
{
"camera_id": camera_id,
"source": str(source),
"config_path": getattr(settings, "config_path", None),
},
)
if preset.overrides:
raw = _deep_merge(raw, preset.overrides)
# Resolve cycle stage if cycle_start_date and date are present
if settings.batch.cycle_start_date and date:
try:
from datetime import date as date_type
start_d = date_type.fromisoformat(str(settings.batch.cycle_start_date))
run_d = date_type.fromisoformat(str(date))
cycle_day = (run_d - start_d).days
if cycle_day >= 0 and settings.stages:
active_stage_name = None
stage_overrides = {}
for stage_name, stage_cfg in settings.stages.items():
day_min = stage_cfg.get("day_min", 0)
day_max = stage_cfg.get("day_max", 999)
if day_min <= cycle_day <= day_max:
active_stage_name = stage_name
stage_overrides = {k: v for k, v in stage_cfg.items() if k not in ("day_min", "day_max")}
break
if stage_overrides:
print(f"[batch] Date {date} -> Cycle Day {cycle_day} (Stage: {active_stage_name})")
raw = _deep_merge(raw, stage_overrides)
except Exception:
pass
raw.setdefault("roi", {})
raw["roi"]["points"] = [list(point) for point in preset.roi.points]
Executable → Regular
+88 -22
View File
@@ -20,6 +20,8 @@ class CountingZone:
track_buffer: int,
min_box_area_px: int = 0,
validate_while_inside: bool = True,
dedupe_radius_px: int = 0,
dedupe_frames: int = 12,
*,
verbose: bool = False,
) -> None:
@@ -30,6 +32,8 @@ class CountingZone:
self.min_box_area_px = min_box_area_px
self.min_overlap_ratio = roi.min_overlap_ratio
self.validate_while_inside = validate_while_inside
self.dedupe_radius_px = max(0, dedupe_radius_px)
self.dedupe_frames = max(0, dedupe_frames)
self.verbose = verbose
self.inside_box_count = 0
self.total_entered_count = 0
@@ -40,6 +44,8 @@ class CountingZone:
self.current_inside_ids: set[int] = set()
self.sequence_numbers_by_track_id: dict[int, int] = {}
self.latest_validated_track_id: int | None = None
# Recent validated centroids used to suppress ID-switch double counts.
self._recent_counts: deque[tuple[int, tuple[int, int], int]] = deque()
self._counting_polygon = np.array(roi.counting_polygon(), dtype=np.int32)
self._counting_rect = roi.counting_rect()
@@ -51,12 +57,30 @@ class CountingZone:
counting_paused: bool = False,
) -> list[CountEvent]:
events: list[CountEvent] = []
if not tracks:
self.inside_box_count = 0
self.current_inside_ids.clear()
self.prev_inside_ids.clear()
self._purge_stale(frame_index, set())
return events
active_ids = set()
inside_ids = set()
rx1, ry1, rx2, ry2 = self._counting_rect
for track in tracks:
active_ids.add(track.track_id)
self.last_seen_frame[track.track_id] = frame_index
self.histories[track.track_id].append(track.centroid)
if self.trail_length > 0:
self.histories[track.track_id].append(track.centroid)
# fast-reject: bounding rect check before pointPolygonTest
cx, cy = track.centroid
if not (rx1 <= cx <= rx2 and ry1 <= cy <= ry2):
continue
if self._inside_roi(track.centroid):
inside_ids.add(track.track_id)
@@ -64,10 +88,9 @@ class CountingZone:
if counting_paused:
continue
if track.track_id not in inside_ids or track.track_id in self.counted_ids:
if track.track_id in self.counted_ids:
continue
should_validate = False
if self.validate_while_inside:
should_validate = self._meets_validation_thresholds(track)
else:
@@ -76,33 +99,50 @@ class CountingZone:
)
should_validate = just_entered_box and self._meets_validation_thresholds(track)
if should_validate:
if not should_validate:
continue
duplicate_of = self._find_recent_duplicate(track.centroid, frame_index)
if duplicate_of is not None:
# Same bird after a track-ID flip: absorb into prior sequence, do not increment.
prior_sequence = duplicate_of
self.counted_ids.add(track.track_id)
self.total_entered_count += 1
self.sequence_numbers_by_track_id[track.track_id] = self.total_entered_count
self.latest_validated_track_id = track.track_id
events.append(
CountEvent(
track_id=track.track_id,
frame_index=frame_index,
total_entered_after_event=self.total_entered_count,
sequence_number=self.sequence_numbers_by_track_id[track.track_id],
)
)
self.sequence_numbers_by_track_id[track.track_id] = prior_sequence
if self.verbose:
x1, y1, x2, y2 = track.bbox_xyxy
bbox_area = max(0, x2 - x1) * max(0, y2 - y1)
overlap = self._bbox_overlap_ratio(track)
print(
f"[count] track={track.track_id} seq=#{self.total_entered_count} "
f"frame={frame_index} area={bbox_area} overlap={overlap:.2f} "
f"conf={track.confidence:.2f} centroid={track.centroid}"
f"[count-dedupe] track={track.track_id} reused seq=#{prior_sequence} "
f"frame={frame_index} centroid={track.centroid}"
)
continue
self.counted_ids.add(track.track_id)
self.total_entered_count += 1
self.sequence_numbers_by_track_id[track.track_id] = self.total_entered_count
self.latest_validated_track_id = track.track_id
self._remember_count(frame_index, track.centroid, self.total_entered_count)
events.append(
CountEvent(
track_id=track.track_id,
frame_index=frame_index,
total_entered_after_event=self.total_entered_count,
sequence_number=self.sequence_numbers_by_track_id[track.track_id],
)
)
if self.verbose:
x1, y1, x2, y2 = track.bbox_xyxy
bbox_area = max(0, x2 - x1) * max(0, y2 - y1)
overlap = self._bbox_overlap_ratio(track)
print(
f"[count] track={track.track_id} seq=#{self.total_entered_count} "
f"frame={frame_index} area={bbox_area} overlap={overlap:.2f} "
f"conf={track.confidence:.2f} centroid={track.centroid}"
)
self.inside_box_count = len(inside_ids)
self.current_inside_ids = inside_ids
self.prev_inside_ids = inside_ids
self._purge_stale(frame_index, active_ids)
if frame_index % 30 == 0:
self._purge_stale(frame_index, active_ids)
return events
def trail_for(self, track_id: int) -> list[tuple[int, int]]:
@@ -150,6 +190,31 @@ class CountingZone:
def _meets_validation_thresholds(self, track: TrackObservation) -> bool:
return self._meets_size_threshold(track) and self._meets_overlap_threshold(track)
def _remember_count(self, frame_index: int, centroid: tuple[int, int], sequence: int) -> None:
if self.dedupe_radius_px <= 0 or self.dedupe_frames <= 0:
return
self._recent_counts.append((frame_index, centroid, sequence))
self._prune_recent_counts(frame_index)
def _prune_recent_counts(self, frame_index: int) -> None:
while self._recent_counts and frame_index - self._recent_counts[0][0] > self.dedupe_frames:
self._recent_counts.popleft()
def _find_recent_duplicate(self, centroid: tuple[int, int], frame_index: int) -> int | None:
"""Return prior sequence number if centroid is near a recent count, else None."""
if self.dedupe_radius_px <= 0 or self.dedupe_frames <= 0:
return None
self._prune_recent_counts(frame_index)
radius_sq = self.dedupe_radius_px * self.dedupe_radius_px
cx, cy = centroid
for _, (px, py), sequence in reversed(self._recent_counts):
dx = cx - px
dy = cy - py
if dx * dx + dy * dy <= radius_sq:
return sequence
return None
def _purge_stale(self, frame_index: int, active_ids: set[int]) -> None:
stale_ids = [
track_id
@@ -161,3 +226,4 @@ class CountingZone:
self.histories.pop(track_id, None)
self.prev_inside_ids.discard(track_id)
self.current_inside_ids.discard(track_id)
self._prune_recent_counts(frame_index)
+239
View File
@@ -0,0 +1,239 @@
"""TensorRT engine compatibility verification, auto-recompilation, and config updates."""
from __future__ import annotations
import re
import shutil
from pathlib import Path
from typing import Any
import numpy as np
PROJECT_ROOT = Path(__file__).resolve().parents[2]
def verify_engine_compatibility(
model_path: str | Path,
*,
device: str | int | None = "0",
imgsz: int = 640,
) -> tuple[bool, str | None]:
"""Verify if a TensorRT .engine file can be loaded and executed on the current system/GPU.
Returns (True, None) if compatible, or (False, error_reason) if incompatible.
"""
model_path = Path(model_path)
if not model_path.exists():
return False, f"Model file not found: {model_path}"
if model_path.suffix.lower() != ".engine":
return True, None
try:
from ultralytics import YOLO
target_device = str(device) if device is not None else "0"
model = YOLO(str(model_path), task="detect")
dummy_frame = np.zeros((imgsz, imgsz, 3), dtype=np.uint8)
model.predict(dummy_frame, device=target_device, verbose=False)
return True, None
except Exception as exc:
return False, str(exc)
def find_matching_pt_model(
engine_path: str | Path,
search_dirs: list[str | Path] | None = None,
) -> Path | None:
"""Find the matching .pt weights file for a given .engine file."""
engine_path = Path(engine_path)
# 1. Look in the same directory and standard models/ directories
default_dirs = [
engine_path.parent,
PROJECT_ROOT / "models",
PROJECT_ROOT,
]
dirs_to_search = [Path(d).resolve() for d in (search_dirs or default_dirs) if Path(d).exists()]
# 2. Check direct stem match (e.g. model.engine -> model.pt)
direct_pt = engine_path.with_suffix(".pt")
if direct_pt.exists():
return direct_pt.resolve()
for directory in dirs_to_search:
direct = directory / f"{engine_path.stem}.pt"
if direct.exists():
return direct.resolve()
# 3. Check stripped prefix match (e.g. NUC5070_model.engine or jetson_model.engine -> model.pt)
cleaned_stem = re.sub(r"^(NUC\w*|jetson\w*|orin\w*|xavier\w*|nano\w*|arm\w*|x86\w*|gpu\w*)_", "", engine_path.stem, flags=re.IGNORECASE)
for directory in dirs_to_search:
candidate = directory / f"{cleaned_stem}.pt"
if candidate.exists():
return candidate.resolve()
# 4. Search all .pt files in search dirs and find closest substring/stem match
all_pts: list[Path] = []
for directory in dirs_to_search:
all_pts.extend(directory.glob("*.pt"))
if not all_pts:
return None
# Try matching chicken detection models specifically
for pt in all_pts:
if "seg" not in pt.stem.lower() and "pose" not in pt.stem.lower() and "chicken" in pt.stem.lower():
if cleaned_stem.lower() in pt.stem.lower() or pt.stem.lower() in cleaned_stem.lower():
return pt.resolve()
# Fallback to any chicken detection .pt model
for pt in all_pts:
if "seg" not in pt.stem.lower() and "pose" not in pt.stem.lower() and "chicken" in pt.stem.lower():
return pt.resolve()
return all_pts[0].resolve() if all_pts else None
def recompile_engine_from_pt(
pt_path: str | Path,
*,
imgsz: int = 640,
device: str | int | None = "0",
half: bool = True,
workspace: int = 4,
verbose: bool = True,
) -> Path:
"""Compile a new TensorRT .engine from a .pt file on the current machine."""
pt_path = Path(pt_path).resolve()
if not pt_path.exists():
raise FileNotFoundError(f"Source PyTorch model not found: {pt_path}")
from ultralytics import YOLO
target_device = str(device) if device is not None else "0"
print(f"[engine_utils] ⚙️ Compiling TensorRT .engine from: {pt_path.name} (device={target_device}, imgsz={imgsz}, half={half})...")
model = YOLO(str(pt_path), task="detect")
exported_engine = model.export(
format="engine",
imgsz=imgsz,
half=half,
workspace=workspace,
device=target_device,
verbose=verbose,
)
exported_path = Path(exported_engine).resolve()
print(f"[engine_utils] ✅ Successfully compiled TensorRT engine: {exported_path}")
return exported_path
def update_config_yaml_model_path(
config_file_path: str | Path,
new_model_path: str | Path,
) -> bool:
"""Update defaults.detection.model_path in a YAML configuration file while preserving formatting."""
config_path = Path(config_file_path).resolve()
if not config_path.exists():
return False
# Format model path relative to project root if applicable
new_model_path = Path(new_model_path).resolve()
try:
rel_path = new_model_path.relative_to(PROJECT_ROOT)
formatted_path = str(rel_path)
except ValueError:
formatted_path = str(new_model_path)
content = config_path.read_text(encoding="utf-8")
# Match 'model_path: <something>' under detection section
pattern = r"^([ \t]*model_path:[ \t]*)(?:['\"]?)([^'\"\r\n#]+)(?:['\"]?)([ \t]*(?:#.*)?)$"
def replacer(match: re.Match) -> str:
prefix = match.group(1)
comment = match.group(3) or ""
if comment and not comment.startswith(" "):
comment = f" {comment.lstrip()}"
if not comment.startswith(" "):
comment = f" {comment}"
return f"{prefix}{formatted_path}{comment}"
new_content, count = re.subn(pattern, replacer, content, count=1, flags=re.MULTILINE)
if count > 0:
config_path.write_text(new_content, encoding="utf-8")
print(f"[engine_utils] 💾 Updated YAML config '{config_path.name}' -> model_path: {formatted_path}")
return True
# If model_path was not found in this file, check if it extends a base config
extends_match = re.search(r"^\s*(?:extends|base_config):\s*['\"]?([^'\"\s#]+)['\"]?", content, re.MULTILINE)
if extends_match:
base_rel = extends_match.group(1).strip()
base_path = (config_path.parent / base_rel).resolve()
if not base_path.exists():
base_path = (PROJECT_ROOT / base_rel).resolve()
if base_path.exists():
return update_config_yaml_model_path(base_path, new_model_path)
return False
def ensure_compatible_model(
model_path: str | Path,
*,
device: str | int | None = "0",
imgsz: int = 640,
config_file_path: str | Path | None = None,
) -> str:
"""Ensure the model at model_path is compatible with the current hardware.
If an incompatible .engine is detected:
1. Automatically locates the matching .pt file.
2. Recompiles a new .engine optimized for this system.
3. Updates config_file_path (e.g. cycle7_batch_optimized.yaml) with the new engine path.
4. Returns the path to the compatible model.
"""
model_path_obj = Path(model_path)
if model_path_obj.suffix.lower() != ".engine":
return str(model_path)
is_compatible, error_msg = verify_engine_compatibility(
model_path_obj,
device=device,
imgsz=imgsz,
)
if is_compatible:
return str(model_path_obj)
print(f"\n[engine_utils] ⚠️ TensorRT engine '{model_path_obj.name}' is incompatible with this system/GPU.")
print(f"[engine_utils] Reason: {error_msg}")
print("[engine_utils] 🔄 Auto-recompilation triggered: Searching for matching .pt model...")
pt_model = find_matching_pt_model(model_path_obj)
if pt_model is None:
raise RuntimeError(
f"TensorRT engine '{model_path}' is incompatible with this hardware, "
f"and no matching .pt source model was found in {PROJECT_ROOT / 'models'} to recompile from."
)
print(f"[engine_utils] 📦 Found source PyTorch model: {pt_model.name}")
try:
new_engine_path = recompile_engine_from_pt(
pt_model,
imgsz=imgsz,
device=device,
half=True,
workspace=4,
verbose=True,
)
except Exception as export_err:
print(f"[engine_utils] ❌ Engine recompilation failed: {export_err}")
print(f"[engine_utils] ⚠️ Falling back to PyTorch .pt model: {pt_model}")
return str(pt_model)
# If config file is specified, update it
if config_file_path:
update_config_yaml_model_path(config_file_path, new_engine_path)
return str(new_engine_path)
+456
View File
@@ -0,0 +1,456 @@
"""Mortality counter: Whole-image chicken carcass detection and counting without ROI cropping."""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
import cv2
import numpy as np
import yaml
from ultralytics import YOLO
PROJECT_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_MODEL_PATH = str(PROJECT_ROOT / "models" / "chicken-detection-model-v26n-seg-300e-best-2026-04-18.pt")
DEFAULT_MORTALITY_DIR = str((PROJECT_ROOT.parent / "VIDEOS" / "cycle7" / "kandang-atas" / "mortality").resolve())
DEFAULT_CONFIG_PATH = str(PROJECT_ROOT / "configs" / "mortality_config.yaml")
def resolve_path(p: str | Path | None, base_dir: Path | None = None) -> str | None:
"""Resolve relative path against PROJECT_ROOT (or base_dir) so it works regardless of working directory."""
if p is None:
return None
path_obj = Path(p)
if path_obj.is_absolute():
return str(path_obj)
root = base_dir or PROJECT_ROOT
return str((root / path_obj).resolve())
def load_mortality_config(config_path: str | Path) -> dict:
"""Load mortality YAML config file if present."""
p = Path(config_path)
if not p.is_file():
return {}
with open(p, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
return data.get("mortality", data)
def deduplicate_boxes(
boxes_list: list[dict],
dedupe_radius_px: float = 30.0,
iou_thresh: float = 0.35,
ioa_thresh: float = 0.50,
) -> list[dict]:
"""Sort detections by confidence descending and suppress duplicate, overlapping, or nested sub-boxes (box inside a box)."""
if not boxes_list:
return boxes_list
sorted_boxes = sorted(boxes_list, key=lambda b: b["confidence"], reverse=True)
kept: list[dict] = []
for item in sorted_boxes:
x1, y1, x2, y2 = item["box"]
cx = (x1 + x2) / 2.0
cy = (y1 + y2) / 2.0
area_item = (x2 - x1) * (y2 - y1)
is_duplicate = False
for k in kept:
kx1, ky1, kx2, ky2 = k["box"]
kcx = (kx1 + kx2) / 2.0
kcy = (ky1 + ky2) / 2.0
area_k = (kx2 - kx1) * (ky2 - ky1)
# 1. Centroid distance check
dist = float(np.hypot(cx - kcx, cy - kcy))
if dedupe_radius_px > 0 and dist < dedupe_radius_px:
is_duplicate = True
break
# 2. IoU and Nested Containment (IoA) check to eliminate box inside a box
ix1, iy1 = max(x1, kx1), max(y1, ky1)
ix2, iy2 = min(x2, kx2), min(y2, ky2)
inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
if inter > 0:
union = area_item + area_k - inter
iou = inter / float(union) if union > 0 else 0
ioa = inter / float(min(area_item, area_k)) if min(area_item, area_k) > 0 else 0
if iou > iou_thresh or ioa > ioa_thresh:
is_duplicate = True
break
if not is_duplicate:
kept.append(item)
for i, item in enumerate(kept, start=1):
item["id"] = i
return kept
def run_similarity_two_pass_detection(
model: YOLO,
img: np.ndarray,
classes: list[int],
conf_threshold: float,
iou_threshold: float,
min_box_area_px: int,
device: str | int = "cpu",
imgsz: int = 640,
crop_padding_ratio: float = 0.50,
) -> list[dict]:
"""2x Detection Strategy:
Pass 1: Detect primary anchor chickens from the model.
Similarity Search: Extract visual feature templates from Pass 1 detections to search for similar carcass patterns.
Pass 2 / Dynamic Accuracy: If candidates fall below Pass 1 confidence or initial pass yields 0, automatically adapt confidence threshold.
"""
img_h, img_w = img.shape[:2]
# Pass 1: Primary detection pass
pass1_results = model.predict(
source=img,
classes=classes,
conf=conf_threshold,
iou=iou_threshold,
imgsz=imgsz,
device=device,
verbose=False,
)
pass1_boxes = pass1_results[0].boxes
raw_detections: list[dict] = []
templates: list[np.ndarray] = []
# Adaptive Step 1: If 0 detections found in Pass 1, automatically adjust accuracy/confidence down
if pass1_boxes is None or len(pass1_boxes) == 0:
adaptive_conf = max(0.18, conf_threshold * 0.60)
print(f"[mortality] Initial scan found 0 detections. Auto-adjusting confidence down to {adaptive_conf:.2f}...")
pass1_results = model.predict(
source=img,
classes=classes,
conf=adaptive_conf,
iou=iou_threshold,
imgsz=imgsz,
device=device,
verbose=False,
)
pass1_boxes = pass1_results[0].boxes
if pass1_boxes is None or len(pass1_boxes) == 0:
return []
# Collect Pass 1 detections & extract high-confidence chicken templates
for p1_box in pass1_boxes:
p1_xyxy = p1_box.xyxy[0].cpu().numpy().astype(int)
p1_conf = float(p1_box.conf[0].cpu().item())
x1, y1, x2, y2 = p1_xyxy
area = (x2 - x1) * (y2 - y1)
if area >= min_box_area_px:
raw_detections.append({
"id": 0,
"box": [int(x1), int(y1), int(x2), int(y2)],
"confidence": round(p1_conf, 4),
"area": int(area),
"pass": 1,
})
if p1_conf >= 0.50 and (x2 - x1) >= 30 and (y2 - y1) >= 30:
crop_tmpl = img[y1:y2, x1:x2]
templates.append(crop_tmpl)
# Pass 2: Feature Similarity & Targeted Local Refinement
pass2_conf = max(0.18, conf_threshold * 0.70)
# Compute template similarity map if templates are available
if templates:
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
sim_map = np.zeros((img_h, img_w), dtype=np.float32)
for tmpl in templates[:4]: # Top templates
gray_tmpl = cv2.cvtColor(tmpl, cv2.COLOR_BGR2GRAY)
th, tw = gray_tmpl.shape
if th > 10 and tw > 10 and th <= img_h and tw <= img_w:
res_map = cv2.matchTemplate(gray_img, gray_tmpl, cv2.TM_CCOEFF_NORMED)
padded_map = np.pad(res_map, ((0, img_h - res_map.shape[0]), (0, img_w - res_map.shape[1])), mode='constant')
sim_map = np.maximum(sim_map, padded_map)
# Re-examine candidate regions with Pass 2 refinement
for p1_box in pass1_boxes:
p1_xyxy = p1_box.xyxy[0].cpu().numpy().astype(int)
x1, y1, x2, y2 = p1_xyxy
bw = x2 - x1
bh = y2 - y1
pad_x = int(bw * crop_padding_ratio) + 20
pad_y = int(bh * crop_padding_ratio) + 20
cx1 = max(0, x1 - pad_x)
cy1 = max(0, y1 - pad_y)
cx2 = min(img_w, x2 + pad_x)
cy2 = min(img_h, y2 + pad_y)
crop = img[cy1:cy2, cx1:cx2]
if crop.size == 0 or crop.shape[0] < 20 or crop.shape[1] < 20:
continue
pass2_results = model.predict(
source=crop,
classes=classes,
conf=pass2_conf,
iou=iou_threshold,
imgsz=imgsz,
device=device,
verbose=False,
)
p2_boxes = pass2_results[0].boxes
if p2_boxes is not None and len(p2_boxes) > 0:
for p2_box in p2_boxes:
rx1, ry1, rx2, ry2 = p2_box.xyxy[0].cpu().numpy().astype(int)
rconf = float(p2_box.conf[0].cpu().item())
gx1 = cx1 + rx1
gy1 = cy1 + ry1
gx2 = cx1 + rx2
gy2 = cy1 + ry2
gw = gx2 - gx1
gh = gy2 - gy1
garea = gw * gh
aspect_ratio = gw / float(gh) if gh > 0 else 0
if 0.35 <= aspect_ratio <= 2.8 and garea >= min_box_area_px:
raw_detections.append({
"id": 0,
"box": [int(gx1), int(gy1), int(gx2), int(gy2)],
"confidence": round(rconf, 4),
"area": int(garea),
"pass": 2,
})
return raw_detections
def run_mortality_count(
input_path: str | Path | None = None,
output_dir: str | Path | None = None,
model_path: str | Path | None = None,
conf_threshold: float | None = None,
iou_threshold: float | None = None,
min_box_area_px: int | None = None,
dedupe_radius_px: float | None = None,
two_pass: bool | None = None,
device: str | int | None = None,
classes: list[int] | None = None,
imgsz: int | None = None,
config_path: str | Path | None = DEFAULT_CONFIG_PATH,
date: str | None = None,
) -> dict:
config_path = resolve_path(config_path) if config_path else DEFAULT_CONFIG_PATH
cfg = load_mortality_config(config_path) if config_path else {}
# 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)
raw_output_dir = output_dir if output_dir is not None else cfg.get("output_dir", None)
raw_model_path = model_path if model_path is not None else cfg.get("model_path", DEFAULT_MODEL_PATH)
input_path = resolve_path(raw_input_path)
output_dir = resolve_path(raw_output_dir) if raw_output_dir else None
model_path = resolve_path(raw_model_path)
conf_threshold = conf_threshold if conf_threshold is not None else float(cfg.get("conf", 0.35))
iou_threshold = iou_threshold if iou_threshold is not None else float(cfg.get("iou", 0.45))
min_box_area_px = min_box_area_px if min_box_area_px is not None else int(cfg.get("min_box_area_px", 2500))
dedupe_radius_px = dedupe_radius_px if dedupe_radius_px is not None else float(cfg.get("dedupe_radius_px", 30.0))
two_pass = two_pass if two_pass is not None else bool(cfg.get("two_pass", False))
device = device if device is not None else cfg.get("device", "0")
classes = classes if classes is not None else cfg.get("classes", [0])
imgsz = imgsz if imgsz is not None else int(cfg.get("imgsz", 640))
input_p = Path(input_path)
# Check for date subfolder if date is provided and input_path is a directory
if date and input_p.is_dir() and (input_p / date).is_dir():
input_p = input_p / date
if input_p.is_file():
image_files = [input_p]
target_out_dir = Path(output_dir) if output_dir else input_p.parent
elif input_p.is_dir():
target_out_dir = Path(output_dir) if output_dir else (input_p / date if (date and not output_dir and not input_p.name == date) else input_p)
valid_exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tiff"}
# Filter out images already prefixed with output_
image_files = sorted([
f for f in input_p.iterdir()
if f.is_file() and f.suffix.lower() in valid_exts and not f.name.startswith("output_")
])
else:
raise FileNotFoundError(f"Input path not found: {input_path}")
target_out_dir.mkdir(parents=True, exist_ok=True)
if not image_files:
print(f"[mortality] No input images found at: {input_path}")
return {"total_images": 0, "results": []}
mode_str = "2x Similarity & Adaptive Accuracy Refinement" if two_pass else "Single-Pass Direct"
print(f"[mortality] Mode: {mode_str}")
print(f"[mortality] Loading model from: {model_path} (device: {device})")
print(f"[mortality] Config: classes={classes}, conf={conf_threshold}, iou={iou_threshold}, min_area={min_box_area_px}px, dedupe_radius={dedupe_radius_px}px")
model = YOLO(str(model_path), task="detect")
results_summary = []
for img_file in image_files:
print(f"[mortality] Processing: {img_file.name}...")
img = cv2.imread(str(img_file))
if img is None:
print(f"[mortality] Failed to read image: {img_file}")
continue
try:
if two_pass:
raw_detections = run_similarity_two_pass_detection(
model=model,
img=img,
classes=classes,
conf_threshold=conf_threshold,
iou_threshold=iou_threshold,
min_box_area_px=min_box_area_px,
device=device,
imgsz=imgsz,
)
else:
results = model.predict(
source=img,
classes=classes,
conf=conf_threshold,
iou=iou_threshold,
imgsz=imgsz,
device=device,
verbose=False,
)
res = results[0]
boxes = res.boxes
raw_detections = []
if boxes is not None:
for box in boxes:
xyxy = box.xyxy[0].cpu().numpy().astype(int)
conf = float(box.conf[0].cpu().item())
x1, y1, x2, y2 = xyxy
area = (x2 - x1) * (y2 - y1)
if area >= min_box_area_px:
raw_detections.append({
"id": 0,
"box": [int(x1), int(y1), int(x2), int(y2)],
"confidence": round(conf, 4),
"area": int(area),
"pass": 1,
})
except Exception as exc:
if "CUDA" in str(exc) or "out of memory" in str(exc):
print(f"[mortality] CUDA OOM encountered. Falling back to CPU for {img_file.name}...")
if two_pass:
raw_detections = run_similarity_two_pass_detection(
model=model,
img=img,
classes=classes,
conf_threshold=conf_threshold,
iou_threshold=iou_threshold,
min_box_area_px=min_box_area_px,
device="cpu",
imgsz=imgsz,
)
else:
results = model.predict(
source=img,
classes=classes,
conf=conf_threshold,
iou=iou_threshold,
imgsz=imgsz,
device="cpu",
verbose=False,
)
res = results[0]
boxes = res.boxes
raw_detections = []
if boxes is not None:
for box in boxes:
xyxy = box.xyxy[0].cpu().numpy().astype(int)
conf = float(box.conf[0].cpu().item())
x1, y1, x2, y2 = xyxy
area = (x2 - x1) * (y2 - y1)
if area >= min_box_area_px:
raw_detections.append({
"id": 0,
"box": [int(x1), int(y1), int(x2), int(y2)],
"confidence": round(conf, 4),
"area": int(area),
"pass": 1,
})
else:
raise exc
# Apply spatial deduplication to suppress duplicate boxes on a single chicken
filtered_detections = deduplicate_boxes(raw_detections, dedupe_radius_px=dedupe_radius_px)
count = len(filtered_detections)
# Draw detections
for det in filtered_detections:
idx = det["id"]
conf = det["confidence"]
x1, y1, x2, y2 = det["box"]
# Draw bright green bounding box around chicken carcass
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Draw label badge (#1, #2...) with confidence
label = f"#{idx} ({conf:.2f})"
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
cv2.rectangle(img, (x1, max(0, y1 - th - 6)), (x1 + tw + 4, y1), (0, 200, 0), -1)
cv2.putText(img, label, (x1 + 2, max(th, y1 - 4)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
# Draw banner at top of image displaying total carcass count
banner_height = 60
h, w, _ = img.shape
cv2.rectangle(img, (0, 0), (w, banner_height), (0, 0, 0), -1)
banner_text = f"TOTAL CHICKEN CARCASSES: {count}"
cv2.putText(img, banner_text, (20, 42), cv2.FONT_HERSHEY_SIMPLEX, 1.1, (0, 255, 255), 3)
out_image_path = target_out_dir / f"output_{img_file.name}"
cv2.imwrite(str(out_image_path), img)
print(f"[mortality] -> {img_file.name}: Count = {count} (Saved: {out_image_path})")
results_summary.append({
"input_image": img_file.name,
"output_image": out_image_path.name,
"count": count,
"output_path": str(out_image_path),
"detections": filtered_detections,
})
total_mortality_count = sum(item["count"] for item in results_summary)
report_path = target_out_dir / "mortality_report.json"
report_data = {
"date": date or datetime.now().strftime("%Y-%m-%d"),
"generated_at": datetime.now(timezone.utc).isoformat(),
"mode": "similarity_two_pass" if two_pass else "single_pass",
"config_file": str(config_path) if config_path else None,
"model_path": str(model_path),
"device": str(device),
"classes": classes,
"conf_threshold": conf_threshold,
"iou_threshold": iou_threshold,
"min_box_area_px": min_box_area_px,
"dedupe_radius_px": dedupe_radius_px,
"total_images": len(image_files),
"total_mortality_count": total_mortality_count,
"results": results_summary,
}
with open(report_path, "w") as f:
json.dump(report_data, f, indent=2)
print(f"[mortality] Summary report saved to: {report_path} (Total Carcasses: {total_mortality_count} across {len(image_files)} images)")
return report_data
Executable → Regular
View File
File mode changed.
Executable → Regular
View File
File mode changed.
Executable → Regular
+33 -22
View File
@@ -90,11 +90,14 @@ class PipelineArtifacts:
total_source_frames: int | None
owns_tracker: bool
detection_zone_rect: tuple[int, int, int, int] | None = None
run_date: str = ""
def build_pipeline(
config: CameraConfig,
tracker: DetectionTracker | None = None,
*,
run_date: str = "",
) -> PipelineArtifacts:
capture = open_capture(config.source)
owns_tracker = tracker is None
@@ -107,6 +110,8 @@ def build_pipeline(
track_buffer=config.tracker.track_buffer,
min_box_area_px=config.detection.min_box_area_px,
validate_while_inside=config.detection.validate_while_inside,
dedupe_radius_px=config.detection.dedupe_radius_px,
dedupe_frames=config.detection.dedupe_frames,
verbose=config.performance.verbose,
)
motion_detector = BackwardMotionDetector(config.motion, config.roi, verbose=config.performance.verbose)
@@ -157,6 +162,7 @@ def build_pipeline(
total_source_frames=total_source_frames,
owns_tracker=owns_tracker,
detection_zone_rect=detection_zone_rect,
run_date=run_date,
)
@@ -165,12 +171,13 @@ def run_pipeline(
tracker: DetectionTracker | None = None,
*,
show_progress: bool = False,
run_date: str = "",
) -> PipelineResult:
if tracker is not None:
tracker.config = config
tracker.reset_tracking()
artifacts = build_pipeline(config, tracker=tracker)
artifacts = build_pipeline(config, tracker=tracker, run_date=run_date)
inference_stride = max(1, config.performance.inference_stride)
print(
f"[perf] inference_stride={inference_stride} "
@@ -252,7 +259,7 @@ def run_pipeline(
last_annotated = annotated
if config.stream.enabled and frame_index % max(1, config.stream.interval_frames) == 0:
_write_stream_frame(config.stream.shm_dir, config.camera_id, annotated, result)
_write_stream_frame(config.stream.shm_dir, config.camera_id, annotated, result, run_date=artifacts.run_date)
if verbose:
t_write = time.monotonic()
@@ -366,28 +373,32 @@ def _consume_result(
_emit_periodic_feedback(config, artifacts, annotated, result, progress)
def _write_stream_frame(shm_dir: str, camera_id: str, frame: np.ndarray, result: FrameResult) -> None:
cam_dir = Path(shm_dir) / f"chicken_counter_{camera_id}"
cam_dir.mkdir(parents=True, exist_ok=True)
def _write_stream_frame(shm_dir: str, camera_id: str, frame: np.ndarray, result: FrameResult, *, run_date: str = "") -> None:
try:
cam_dir = Path(shm_dir) / f"chicken_counter_{camera_id}"
cam_dir.mkdir(parents=True, exist_ok=True)
jpg_path = cam_dir / "frame.jpg"
tmp_path = cam_dir / ".frame_tmp.jpg"
cv2.imwrite(str(tmp_path), frame, [cv2.IMWRITE_JPEG_QUALITY, 75])
tmp_path.replace(jpg_path)
jpg_path = cam_dir / "frame.jpg"
tmp_path = cam_dir / ".frame_tmp.jpg"
cv2.imwrite(str(tmp_path), frame, [cv2.IMWRITE_JPEG_QUALITY, 75])
tmp_path.replace(jpg_path)
stats = {
"frame_index": result.frame_index,
"inside_box_count": result.inside_box_count,
"total_entered_count": result.total_entered_count,
"track_count": len(result.tracks),
"backward_active": result.motion_state.backward_active,
"smoothed_speed": round(result.motion_state.smoothed_speed, 1),
"count_events": len(result.count_events),
}
stats_path = cam_dir / "stats.json"
stats_tmp = cam_dir / ".stats_tmp.json"
stats_tmp.write_text(json.dumps(stats), encoding="utf-8")
stats_tmp.replace(stats_path)
stats = {
"frame_index": result.frame_index,
"inside_box_count": result.inside_box_count,
"total_entered_count": result.total_entered_count,
"track_count": len(result.tracks),
"backward_active": result.motion_state.backward_active,
"smoothed_speed": round(result.motion_state.smoothed_speed, 1),
"count_events": len(result.count_events),
"run_date": run_date,
}
stats_path = cam_dir / "stats.json"
stats_tmp = cam_dir / ".stats_tmp.json"
stats_tmp.write_text(json.dumps(stats), encoding="utf-8")
stats_tmp.replace(stats_path)
except Exception:
pass
def _should_emit_feedback(config: CameraConfig, frame_index: int) -> bool:
Executable → Regular
+25 -3
View File
@@ -97,10 +97,32 @@ def persist_batch_reports(
output_dir: str | Path,
) -> Path:
output_path = Path(output_dir)
latest = results[-1]
write_camera_report(date, latest, output_path)
output_path.mkdir(parents=True, exist_ok=True)
if results:
latest = results[-1]
write_camera_report(date, latest, output_path)
aggregate_path = output_path / f"counts_{date}.json"
report = build_batch_report(date, results, output_dir=output_path)
cameras_dict: dict[str, dict] = {}
total_sum = 0
for camera_json in sorted(output_path.glob(f"*_counts_{date}.json")):
try:
data = json.loads(camera_json.read_text(encoding="utf-8"))
cam_id = data.get("camera_id")
if cam_id:
entry = {k: v for k, v in data.items() if k not in ("date", "camera_id", "generated_at")}
cameras_dict[cam_id] = entry
if not entry.get("skipped"):
total_sum += entry.get("total_entered", 0)
except Exception:
pass
report = BatchReport(
date=date,
generated_at=datetime.now(timezone.utc).isoformat(),
cameras=cameras_dict,
total_entered_sum=total_sum,
)
write_batch_report(report, aggregate_path)
return aggregate_path
Executable → Regular
+121 -2
View File
@@ -9,15 +9,26 @@ import numpy as np
from ultralytics import YOLO
from chicken_counter.config import CameraConfig
from chicken_counter.engine_utils import ensure_compatible_model
from chicken_counter.types import TrackObservation
class DetectionTracker:
def __init__(self, config: CameraConfig) -> None:
self.config = config
model_path = Path(config.detection.model_path)
# 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
model_path = Path(validated_model_path)
self.model_kind = model_path.suffix.lower().lstrip(".") or "unknown"
self.model = YOLO(config.detection.model_path)
self.model = YOLO(validated_model_path, task="detect")
self.tracker_config_path = str(Path(config.tracker.tracker_config_path))
self.verbose = config.performance.verbose
self._infer_count = 0
@@ -140,6 +151,114 @@ class DetectionTracker:
return tracks
def infer_batch(
self,
frames: list[np.ndarray],
*,
crop_rects: list[tuple[int, int, int, int] | None] | None = None,
) -> list[list[TrackObservation]]:
if not frames:
return []
sources = []
offsets = []
for i, frame in enumerate(frames):
crop = crop_rects[i] if crop_rects and i < len(crop_rects) else None
if crop is not None:
x1, y1, x2, y2 = crop
sources.append(frame[y1:y2, x1:x2])
offsets.append((x1, y1))
else:
sources.append(frame)
offsets.append((0, 0))
track_kwargs: dict = {
"source": sources,
"persist": self.config.tracker.persist,
"tracker": self.tracker_config_path,
"conf": self.config.detection.conf,
"iou": self.config.detection.iou,
"classes": self.config.detection.classes,
"imgsz": self.config.detection.imgsz,
"verbose": False,
"device": self.config.detection.device,
}
if self.model_kind != "engine" and self.config.performance.half:
track_kwargs["half"] = True
if self.verbose:
t_start = time.monotonic()
try:
results = self.model.track(**track_kwargs)
except Exception:
results = []
for src in sources:
kw = dict(track_kwargs)
kw["source"] = src
res = self.model.track(**kw)
if res:
results.append(res[0])
if self.verbose:
t_track = time.monotonic()
self._infer_count += 1
batch_tracks: list[list[TrackObservation]] = []
for idx, result in enumerate(results):
offset_x, offset_y = offsets[idx]
crop_rect = crop_rects[idx] if crop_rects and idx < len(crop_rects) else None
boxes = result.boxes
if boxes is None or boxes.id is None:
batch_tracks.append([])
continue
ids = boxes.id.int().cpu().numpy()
classes = boxes.cls.int().cpu().numpy()
confidences = boxes.conf.cpu().numpy()
xyxy = boxes.xyxy.int().cpu().numpy()
mask_polygons = None
if result.masks is not None and result.masks.xy is not None:
mask_polygons = result.masks.xy
tracks: list[TrackObservation] = []
for index in range(len(boxes)):
track_id = int(ids[index])
class_id = int(classes[index])
confidence = float(confidences[index])
bbox = xyxy[index]
x1 = int(bbox[0]) + offset_x
y1 = int(bbox[1]) + offset_y
x2 = int(bbox[2]) + offset_x
y2 = int(bbox[3]) + offset_y
centroid = ((x1 + x2) // 2, (y1 + y2) // 2)
if crop_rect is not None and not self._centroid_in_rect(centroid, crop_rect):
continue
polygon = None
if mask_polygons is not None:
poly = np.asarray(mask_polygons[index], dtype=np.float64).copy()
if poly.ndim == 2 and poly.shape[0] >= 3:
poly[:, 0] += offset_x
poly[:, 1] += offset_y
polygon = poly
tracks.append(
TrackObservation(
track_id=track_id,
class_id=class_id,
confidence=confidence,
bbox_xyxy=(x1, y1, x2, y2),
centroid=centroid,
mask_polygon_xy=polygon,
)
)
batch_tracks.append(tracks)
return batch_tracks
@staticmethod
def _centroid_in_rect(
centroid: tuple[int, int],
Executable → Regular
View File
File mode changed.
+14 -7
View File
@@ -51,18 +51,25 @@ def _try_gstreamer_writer(
bitrate_bps: int,
) -> cv2.VideoWriter | None:
fps_int = max(1, int(round(fps)))
pipeline = (
pipelines = [
# Desktop NVIDIA NVENC hardware encoder
f"appsrc ! video/x-raw, format=BGR ! "
f"video/x-raw,width={width},height={height},framerate={fps_int}/1 ! "
f"videoconvert ! nvh264enc bitrate={bitrate_bps // 1000} ! "
f"h264parse ! mp4mux ! filesink location={path}",
# Jetson hardware encoder
f"appsrc ! video/x-raw, format=BGR ! "
f"video/x-raw,width={width},height={height},framerate={fps_int}/1 ! "
f"videoconvert ! nvvidconv ! "
f"video/x-raw(memory:NVMM),format=NV12 ! "
f"nvv4l2h264enc bitrate={bitrate_bps} insert-sps-pps=true ! "
f"h264parse ! mp4mux ! filesink location={path}"
)
writer = cv2.VideoWriter(pipeline, cv2.CAP_GSTREAMER, 0, fps, (width, height), True)
if writer.isOpened():
return writer
writer.release()
f"h264parse ! mp4mux ! filesink location={path}",
]
for pipeline in pipelines:
writer = cv2.VideoWriter(pipeline, cv2.CAP_GSTREAMER, 0, fps, (width, height), True)
if writer.isOpened():
return writer
writer.release()
return None
+54
View File
@@ -0,0 +1,54 @@
#!/bin/bash
# Portable dashboard launcher — resolves all paths relative to this script's directory.
# Works regardless of where the project folder is located or its name.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="$SCRIPT_DIR/src"
# Use project-local venv if available, otherwise fall back to system python3
if [ -f "$SCRIPT_DIR/venv/bin/python" ]; then
PYTHON="$SCRIPT_DIR/venv/bin/python"
else
PYTHON="python3"
fi
DB_PATH="${DB_PATH:-$SCRIPT_DIR/db/chicken_counts.db}"
PORT="${PORT:-8080}"
DATE_ARG="${DATE_ARG:-}"
CMD=("$PYTHON" "$SCRIPT_DIR/dashboard.py" --port "$PORT" --db "$DB_PATH")
# Startup check: Ensure sibling VIDEOS directory structure exists
VIDEOS_BASE="$SCRIPT_DIR/../VIDEOS"
if [ ! -d "$VIDEOS_BASE" ]; then
echo "[dashboard] 📁 Sibling directory '$VIDEOS_BASE' not found; creating skeleton directory..."
mkdir -p "$VIDEOS_BASE/cycle7"
fi
# Auto-discover mortality directories (any folder containing mortality_report.json or mortality folders)
if [ -n "${MORTALITY_DIRS:-}" ]; then
IFS=',' read -ra MDIRS <<< "$MORTALITY_DIRS"
for mdir in "${MDIRS[@]}"; do
CMD+=(--mortality-dir "$mdir")
done
else
# Recursively discover all mortality subdirectories under ../VIDEOS
FOUND_MDIRS=()
while IFS= read -r -d '' mdir; do
FOUND_MDIRS+=("$mdir")
done < <(find "$VIDEOS_BASE" -type d -name "mortality" -print0 2>/dev/null)
if [ ${#FOUND_MDIRS[@]} -gt 0 ]; then
for mdir in "${FOUND_MDIRS[@]}"; do
CMD+=(--mortality-dir "$mdir")
done
fi
fi
if [ -n "$DATE_ARG" ]; then
CMD+=(--date "$DATE_ARG")
fi
echo "[dashboard] Starting at http://0.0.0.0:${PORT} db=${DB_PATH}"
exec "${CMD[@]}"
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Store batch run results into a SQLite database.
Reads the aggregate JSON report written by the batch runner and inserts
all camera-level + summary data. Safe to run multiple times — uses
(date, location, camera_id) as the unique key, so re-runs update
existing rows instead of duplicating.
Usage:
python3 store_results.py /path/to/output/counts_2026-06-10.json --location kandang-atas
python3 store_results.py /path/to/output/counts_2026-06-10.json --db /var/lib/chickens.db
"""
from __future__ import annotations
import argparse
import json
import sqlite3
import sys
from pathlib import Path
CREATE_TABLE = """
CREATE TABLE IF NOT EXISTS batch_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
location TEXT NOT NULL,
camera_id TEXT NOT NULL,
total_entered INTEGER NOT NULL DEFAULT 0,
frames_processed INTEGER NOT NULL DEFAULT 0,
elapsed_seconds REAL NOT NULL DEFAULT 0.0,
stopped_reason TEXT NOT NULL DEFAULT '',
source_video TEXT NOT NULL DEFAULT '',
generated_at TEXT NOT NULL DEFAULT '',
UNIQUE(date, location, camera_id)
)
"""
INSERT_SQL = """
INSERT INTO batch_runs
(date, location, camera_id, total_entered, frames_processed,
elapsed_seconds, stopped_reason, source_video, generated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(date, location, camera_id) DO UPDATE SET
total_entered = excluded.total_entered,
frames_processed = excluded.frames_processed,
elapsed_seconds = excluded.elapsed_seconds,
stopped_reason = excluded.stopped_reason,
source_video = excluded.source_video,
generated_at = excluded.generated_at
"""
SUMMARY_QUERY = """
SELECT
date,
location,
COUNT(*) AS camera_count,
SUM(total_entered) AS total_chickens,
SUM(elapsed_seconds) AS total_seconds,
ROUND(SUM(elapsed_seconds) / 60.0, 1) AS total_minutes
FROM batch_runs
WHERE date = ? AND location = ?
GROUP BY date, location
"""
def store_report(report_path: str, location: str, db_path: str) -> None:
with open(report_path) as f:
report = json.load(f)
date = report["date"]
cameras = report["cameras"]
generated_at = report.get("generated_at", "")
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute(CREATE_TABLE)
rows = 0
for camera_id, entry in cameras.items():
if entry.get("skipped"):
continue
conn.execute(INSERT_SQL, (
date, location, camera_id,
entry.get("total_entered", 0),
entry.get("frames_processed", 0),
entry.get("elapsed_seconds", 0),
entry.get("stopped_reason", ""),
entry.get("source_video", ""),
generated_at,
))
rows += 1
conn.commit()
# print summary
row = conn.execute(SUMMARY_QUERY, (date, location)).fetchone()
if row:
print(f"\n[db] {row[0]} | {row[1]} | {row[2]} cameras | "
f"{row[3]} chickens | {row[4]:.0f}s ({row[5]} min)")
# also print per-camera breakdown
cur = conn.execute(
"SELECT camera_id, total_entered, elapsed_seconds "
"FROM batch_runs WHERE date=? AND location=? ORDER BY camera_id",
(date, location))
for cam_id, count, secs in cur:
print(f" {cam_id}: {count} chickens, {secs:.0f}s")
conn.close()
print(f"\n[db] wrote {rows} rows to {db_path}")
def main():
parser = argparse.ArgumentParser(
description="Store batch run results into SQLite")
parser.add_argument("report", help="Path to counts_YYYY-MM-DD.json")
parser.add_argument("--location", required=True, help="Location name (e.g. kandang-atas)")
parser.add_argument("--db", default="chicken_counts.db", help="SQLite database path")
args = parser.parse_args()
if not Path(args.report).exists():
print(f"error: report not found: {args.report}", file=sys.stderr)
sys.exit(1)
store_report(args.report, args.location, args.db)
if __name__ == "__main__":
main()
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more