feat(weight): add chicken weight storage to SQLite DB and Excel growth analytics
- Add minor_axis_cm and major_axis_cm physical geometry extraction and aggregation - Extend batch_runs SQLite table with automated non-destructive schema migration - Enforce Cycle Day 0 rule (Day 0: headcount count only; Day 1+: counting + weight) - Add dedicated 'Weight & Growth Analytics' sheet and growth trajectory line chart to Excel reporting - Update unit tests with full coverage for weight DB storage and report generation - Update API.md, README.md, RUN.md, and CHANGELOG.md with complete ERD and schema
This commit is contained in:
1 parent
d033c4fe6a
commit
435ec612f6
29 files changed
+2448
-303
No files matched your search
@@ -157,20 +157,31 @@ Summary and history for a specific location.
|
||||
|
||||
```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 '',
|
||||
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 '',
|
||||
cycle_day INTEGER NOT NULL DEFAULT 0,
|
||||
area_cm2_median REAL NOT NULL DEFAULT 0.0,
|
||||
minor_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
major_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
predicted_weight_g REAL NOT NULL DEFAULT 0.0,
|
||||
gompertz_baseline_g REAL NOT NULL DEFAULT 0.0,
|
||||
vision_gain_g REAL NOT NULL DEFAULT 0.0,
|
||||
n_weight_samples INTEGER NOT NULL DEFAULT 0,
|
||||
rejection_rate REAL NOT NULL DEFAULT 0.0,
|
||||
UNIQUE(date, location, camera_id)
|
||||
);
|
||||
```
|
||||
|
||||
> **Note**: Weight counting and growth curves start at **Cycle Day 1** (Day 0 = DOC arrival baseline 42.0g).
|
||||
|
||||
Data is inserted automatically by the batch runner when `location` and `db_path` are configured in the batch YAML, or manually via:
|
||||
|
||||
```bash
|
||||
@@ -403,4 +414,40 @@ curl -X POST https://your-server.com/api/notify \
|
||||
-d @/home/asus/.Codes/VIDEOS/cycle7/kandang-atas/mortality/mortality_report.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Weight Estimation & Growth Analytics Endpoints
|
||||
|
||||
### `GET /api/weight/predictions`
|
||||
Returns all predicted body weights and growth milestones across all processed dates in the cycle.
|
||||
|
||||
```json
|
||||
{
|
||||
"predictions": [
|
||||
{
|
||||
"date": "2026-06-18",
|
||||
"camera_id": "FUSED",
|
||||
"cycle_day": 27,
|
||||
"predicted_weight_g": 2147.2,
|
||||
"doc_weight_g": 42.0,
|
||||
"gompertz_baseline_g": 2116.0,
|
||||
"vision_gain_g": 31.2,
|
||||
"n_valid_samples": 995,
|
||||
"dominant_camera": "CC2"
|
||||
}
|
||||
],
|
||||
"total_records": 1
|
||||
}
|
||||
```
|
||||
|
||||
### `GET /api/weight/predictions/<date>`
|
||||
Returns per-camera and `FUSED` weight prediction records for a specific date (e.g. `2026-06-18`).
|
||||
|
||||
### `GET /api/weight/features/<date>`
|
||||
Returns full statistical distribution metrics (`mean`, `median`, `p25`, `p75`, `std`, `cv`, `iqr`) for all metric features (`bbox_area_cm2`, `width_cm`, `height_cm`, `aspect_ratio_cm`, `perimeter_cm`) for a date.
|
||||
|
||||
### `GET /api/weight/curation/<date>/<camera_id>`
|
||||
Returns FatChicken curation and MAD outlier rejection audit statistics for a specific camera on a given date.
|
||||
|
||||
|
||||
|
||||
+43
-1
@@ -2,7 +2,49 @@
|
||||
|
||||
All notable changes to the `chicken-counting-sukawarna-det` project are documented in this file.
|
||||
|
||||
## [Unreleased] - 2026-08-21
|
||||
## [Unreleased] - 2026-08-24
|
||||
|
||||
### ⚖️ Chicken Weight Database Storage & Excel Report Analytics
|
||||
- **Minor & Major Axis Geometry Extraction (`calibration.py`, `aggregation.py`)**:
|
||||
- Added `minor_axis_cm` ($\min(\text{width}, \text{height})$) and `major_axis_cm` ($\max(\text{width}, \text{height})$) to per-track metric observations.
|
||||
- Added full distribution statistics (`minor_axis_cm_median`, `major_axis_cm_median`, etc.) to camera aggregation and multi-camera `FUSED` records.
|
||||
- **SQLite Database Schema Migration & Weight Storage (`batch_runner.py`, `dashboard.py`, `store_results.py`)**:
|
||||
- Extended `batch_runs` table with weight & dimensional columns: `cycle_day`, `area_cm2_median`, `minor_axis_cm_median`, `major_axis_cm_median`, `predicted_weight_g`, `gompertz_baseline_g`, `vision_gain_g`, `n_weight_samples`, `rejection_rate`.
|
||||
- Implemented automatic non-destructive column migration (`migrate_db_schema`) on existing database files.
|
||||
- Added automatic database updating of weight metrics upon completion of daily batch processing.
|
||||
- **Cycle Day 0 Rule Enforcement (`batch_runner.py`, `growth_model.py`)**:
|
||||
- Explicitly defined `cycle_start_date` as Day 0 (DOC arrival baseline 42.0g).
|
||||
- Weight counting and growth curves strictly begin at **Cycle Day 1+**, skipping weight estimation on Day 0.
|
||||
- **Excel Report Generator Enhancement (`export_excel_report.py`)**:
|
||||
- **Sheet 1 (Daily Summary)**: Added KPI cards for Average Flock Weight ($g$) and Median Bird Area ($cm^2$), plus daily weight columns in summary table.
|
||||
- **Sheet 2 (Camera Summary)**: Added `Avg Pred Weight (g)`, `Median Area (cm²)`, `Median Minor Axis (cm)`, `Median Major Axis (cm)`, and `Valid Samples`.
|
||||
- **Sheet 3 (Raw Batch Runs)**: Added full weight, size dimension, and Gompertz baseline breakdown columns.
|
||||
- **Sheet 4 (Weight & Growth Analytics)**: Added new dedicated growth tracking worksheet with Day 1+ growth ledger and dual-series Line Chart comparing **Predicted Weight vs. Gompertz Baseline Curve** over cycle days.
|
||||
|
||||
## [1.2.1] - 2026-08-21
|
||||
|
||||
### ⚖️ Weight Estimation, Track Curation & Parquet Storage Pipeline
|
||||
- **Metric Centimeter Conversion & Camera Calibration (`src/chicken_counter/weight/calibration.py`, `config.py`)**:
|
||||
- Implemented `CalibrationConfig` with configurable `px_per_cm` per camera (e.g. `CC1: 19.5`, `CC2: 20.2`, `CC3: 19.8`, `CC4: 19.2`, default: `20.0`).
|
||||
- Added on-the-fly metric conversion generating `px_per_cm`, `bbox_area_cm2`, `width_cm`, `height_cm`, `aspect_ratio_cm`, `centroid_x_cm`, `centroid_y_cm`, and `perimeter_cm`.
|
||||
- **FatChicken Track Curation & Outlier Elimination (`src/chicken_counter/weight/curation.py`)**:
|
||||
- Deduplicated per-track observations to exactly one best observation per `track_id` (highest confidence upon count event trigger).
|
||||
- Implemented age-adaptive MAD Z-score outlier rejection on `bbox_area_cm2` ($z = 0.6745 \times (x - \text{median}) / \text{MAD}$):
|
||||
- $\le 10$ days: $|z| \le 3.0$
|
||||
- $11\dots 24$ days: $|z| \le 2.5$
|
||||
- $> 24$ days: $|z| \le 2.0$
|
||||
- Automatically activates when sample count $N \ge 30$.
|
||||
- **Camera-Day Statistical Aggregation & Multi-Camera Fusion (`src/chicken_counter/weight/aggregation.py`)**:
|
||||
- Computes distribution metrics (`mean`, `median`, `p25`, `p75`, `std`, `cv`, `iqr`) for all metric features (`bbox_area_cm2`, `width_cm`, `height_cm`, `aspect_ratio_cm`, `perimeter_cm`).
|
||||
- Generates multi-camera `FUSED` summary row weighted by valid sample counts.
|
||||
- **Broiler Growth Model & Audited Weight Predictions (`src/chicken_counter/weight/growth_model.py`)**:
|
||||
- Integrated Ross 308 / Cobb 500 Gompertz growth curve and standard daily DOC weight baseline table.
|
||||
- Generates audited weight records containing `predicted_weight_g`, `doc_weight_g`, `gompertz_baseline_g`, `vision_gain_g` (or `residual_g`), `n_valid_samples`, and `dominant_camera`.
|
||||
- **Standardized Storage & Export Handlers (`src/chicken_counter/weight/storage.py`)**:
|
||||
- Per-track observations: `detections_{date}_{camera_id}.parquet` (and `.csv` fallback).
|
||||
- Curation summary: `curation_{date}_{camera_id}.json`.
|
||||
- Cage day features: `cage_day_features.parquet` (and `.csv` fallback).
|
||||
- Weight predictions: `predictions_{date}.parquet` (and `.csv` fallback).
|
||||
|
||||
### 🚀 Model & Runtime Configuration Improvements
|
||||
- **Counting Pipeline Migration to ONNX Weights (`configs/cycle7_batch_optimized.yaml`, `configs/cycle7_batch.yaml`, `configs/cameras/example_camera.yaml`)**:
|
||||
|
||||
@@ -252,12 +252,55 @@ The pipeline supports ONNX (`.onnx`), PyTorch (`.pt`), and hardware-accelerated
|
||||
|
||||
## 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):
|
||||
The pipeline dynamically adjusts detection, counting, and weight estimation based on flock age:
|
||||
|
||||
- **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.
|
||||
- **Day 0 (`cycle_start_date`)**: Day-Old Chicks (DOC) arrival date (default: `"2026-05-22"`).
|
||||
- **Day 0 Rule**: **Counting ONLY** (initial stocking headcount inventory). Weight estimation is bypassed because Day 0 chicks have a fixed baseline ($42.0\text{ g}$).
|
||||
- **Day 1+ Rule**: **Counting AND Weight Estimation** runs daily across all camera videos.
|
||||
- **`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 chicks.
|
||||
- **`mid_cycle` (Days 16+)**: Preserves standard tuned per-camera defaults (`conf: 0.35–0.50`, `min_box_area_px: 2500–3000`).
|
||||
|
||||
## Weight Estimation, Track Curation & Measurement Storage
|
||||
|
||||
The edge pipeline aggregates physical metric measurements and predicts chicken body weights during daily counting runs:
|
||||
|
||||
1. **Per-Track Measurements (`detections_{date}_{camera_id}.parquet`)**:
|
||||
- Captures 1 row per validated chicken with exact pixel bounding boxes and physical centimeter measurements (`bbox_area_cm2`, `width_cm`, `height_cm`, `minor_axis_cm`, `major_axis_cm`, `aspect_ratio_cm`, `centroid_x_cm`, `centroid_y_cm`, `perimeter_cm`).
|
||||
2. **FatChicken Curation & MAD Outlier Elimination (`curation_{date}_{camera_id}.json`)**:
|
||||
- Deduplicates observations by `track_id` (best observation upon count trigger).
|
||||
- Eliminates anomalous bounding box areas via age-adaptive MAD Z-score ($z = 0.6745 \times (x - \text{median}) / \text{MAD}$).
|
||||
3. **Statistical Distribution Aggregation (`cage_day_features.parquet`)**:
|
||||
- Calculates distribution metrics (`mean`, `median`, `p25`, `p75`, `std`, `cv`, `iqr`) for all dimensions including `minor_axis_cm_median` and `major_axis_cm_median` per camera and the multi-camera **`FUSED`** row.
|
||||
4. **Audited Weight Prediction (`predictions_{date}.parquet`)**:
|
||||
- Predicts flock body weights using Ross 308 / Cobb 500 Gompertz curves combined with vision allometric gain (`predicted_weight_g`, `doc_weight_g`, `gompertz_baseline_g`, `vision_gain_g`).
|
||||
5. **SQLite Database Storage (`db/chicken_counts.db`)**:
|
||||
- Persists all counting and weight statistics into the `batch_runs` table (`area_cm2_median`, `minor_axis_cm_median`, `major_axis_cm_median`, `predicted_weight_g`, `gompertz_baseline_g`, `vision_gain_g`, `n_weight_samples`, `rejection_rate`).
|
||||
|
||||
```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 '',
|
||||
cycle_day INTEGER NOT NULL DEFAULT 0,
|
||||
area_cm2_median REAL NOT NULL DEFAULT 0.0,
|
||||
minor_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
major_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
predicted_weight_g REAL NOT NULL DEFAULT 0.0,
|
||||
gompertz_baseline_g REAL NOT NULL DEFAULT 0.0,
|
||||
vision_gain_g REAL NOT NULL DEFAULT 0.0,
|
||||
n_weight_samples INTEGER NOT NULL DEFAULT 0,
|
||||
rejection_rate REAL NOT NULL DEFAULT 0.0,
|
||||
UNIQUE(date, location, camera_id)
|
||||
);
|
||||
```
|
||||
|
||||
## Mortality Detection
|
||||
|
||||
A separate pipeline detects carcasses (dead birds) from still photos. Supports multi-image daily runs and date subfolders (`mortality/YYYY-MM-DD/`).
|
||||
|
||||
@@ -340,3 +340,53 @@ When technicians execute batch counting on each machine, the runner automaticall
|
||||
```
|
||||
|
||||
All SQLite database rows and JSON outputs will automatically be stamped with `"site": "site_a"` or `"site": "site_b"`, allowing seamless copying and consolidation on a central server.
|
||||
|
||||
---
|
||||
|
||||
## 9. Weight Estimation, Curation & Storage System
|
||||
|
||||
The edge chicken counting pipeline aggregates physical metric measurements and predicts chicken weights during daily counting runs.
|
||||
|
||||
### Day 0 vs. Day 1+ Lifecycle Rule
|
||||
- **Day 0 (`cycle_start_date`)**: Day-Old Chicks (DOC) arrival date (standard baseline $42.0\text{ g}$). **Counting ONLY** to establish starting inventory headcount.
|
||||
- **Day 1+**: **Counting AND Weight Estimation** runs daily across all floor camera feeds.
|
||||
|
||||
### Data Architecture & Storage Files
|
||||
|
||||
Each daily run saves the following datasets into the floor's output directory (`../VIDEOS/cycle7/<coop>/<floor>/<date>/output/`):
|
||||
|
||||
| File | Format | Description |
|
||||
| :--- | :--- | :--- |
|
||||
| `detections_{date}_{camera_id}.parquet` | Parquet + CSV fallback | Curated raw observations (1 row per counted track with pixel bbox, `bbox_area_cm2`, `minor_axis_cm`, `major_axis_cm`, `aspect_ratio_cm`, `perimeter_cm`, `mad_zscore`). |
|
||||
| `curation_{date}_{camera_id}.json` | JSON | Curation audit summary (raw tracks, validated, saved, outliers discarded, rejection rate, median area). |
|
||||
| `cage_day_features.parquet` | Parquet + CSV fallback | Aggregated statistical distribution (`mean`, `median`, `p25`, `p75`, `std`, `cv`, `iqr`) per camera and `FUSED`. |
|
||||
| `predictions_{date}.parquet` | Parquet + CSV fallback | Audited weight predictions (`predicted_weight_g`, `doc_weight_g`, `gompertz_baseline_g`, `vision_gain_g`, `minor_axis_cm_median`, `major_axis_cm_median`). |
|
||||
|
||||
### FatChicken Curation & MAD Outlier Elimination
|
||||
|
||||
1. **Track Deduplication**: Exactly one best observation per `track_id` (highest detection confidence upon count validation).
|
||||
2. **MAD Z-Score Outlier Filter**: $z = 0.6745 \times (x - \text{median}) / \text{MAD}$ on `bbox_area_cm2`.
|
||||
- Age $\le 10$ days: $|z| \le 3.0$
|
||||
- Age $11\dots 24$ days: $|z| \le 2.5$
|
||||
- Age $> 24$ days: $|z| \le 2.0$
|
||||
- Active only when sample count $N \ge 30$.
|
||||
3. **Multi-Camera Fusion**: Weighted aggregation across all cameras with dominant camera tracking.
|
||||
4. **Database Persistence**: Automatic storage into SQLite `batch_runs` table (`db/chicken_counts.db`).
|
||||
|
||||
---
|
||||
|
||||
## 10. Multi-Sheet Excel Reporting
|
||||
|
||||
Generate structured Excel reports containing count summaries, camera performance, growth charts, and raw batch logs:
|
||||
|
||||
```bash
|
||||
PYTHONPATH=src venv/bin/python export_excel_report.py
|
||||
```
|
||||
|
||||
Outputs **`db/chicken_counts_report.xlsx`** containing:
|
||||
1. **`Daily Summary`**: Overall headcount KPIs, Avg Flock Weight ($g$), Median Bird Area ($cm^2$), Daily pivot table, and count bar chart.
|
||||
2. **`Camera Summary`**: Per-camera metrics (`Avg Pred Weight (g)`, `Median Area (cm²)`, `Median Minor Axis (cm)`, `Median Major Axis (cm)`, `Valid Samples`).
|
||||
3. **`Weight & Growth Analytics`**: Day 1+ growth ledger with headcount, weight samples, area/minor/major medians, predicted weight, Gompertz baseline, and an embedded **Growth Trajectory Line Chart**.
|
||||
4. **`Raw Batch Runs`**: Complete granular logs for every camera run.
|
||||
5. **`Configurations`**: Full parameters, spatial calibrations (`px_per_cm`), and Gompertz growth models.
|
||||
|
||||
@@ -87,6 +87,8 @@ defaults:
|
||||
inset_top_px: 0
|
||||
inset_bottom_px: 0
|
||||
min_overlap_ratio: 0.30
|
||||
calibration:
|
||||
px_per_cm: 20.0 # Default camera calibration scale (pixels per centimeter)
|
||||
|
||||
cameras:
|
||||
CC1:
|
||||
|
||||
@@ -104,11 +104,15 @@ defaults:
|
||||
inset_top_px: 0
|
||||
inset_bottom_px: 0
|
||||
min_overlap_ratio: 0.30
|
||||
calibration:
|
||||
px_per_cm: 20.0 # Default camera calibration scale (pixels per centimeter)
|
||||
|
||||
cameras:
|
||||
CC1:
|
||||
camera_num: 1
|
||||
count_anchor: [780, 120]
|
||||
calibration:
|
||||
px_per_cm: 19.5
|
||||
detection:
|
||||
min_box_area_px: 2500
|
||||
conf: 0.35
|
||||
@@ -121,6 +125,8 @@ cameras:
|
||||
CC2:
|
||||
camera_num: 2
|
||||
count_anchor: [900, 120]
|
||||
calibration:
|
||||
px_per_cm: 20.2
|
||||
detection:
|
||||
conf: 0.5 # From 0.45
|
||||
dedupe_radius_px: 32
|
||||
@@ -134,6 +140,8 @@ cameras:
|
||||
CC3:
|
||||
camera_num: 3
|
||||
count_anchor: [900, 120]
|
||||
calibration:
|
||||
px_per_cm: 19.8
|
||||
detection:
|
||||
dedupe_radius_px: 24
|
||||
dedupe_frames: 16 # From 12
|
||||
@@ -146,6 +154,8 @@ cameras:
|
||||
CC4:
|
||||
camera_num: 4
|
||||
count_anchor: [700, 120]
|
||||
calibration:
|
||||
px_per_cm: 19.2
|
||||
roi:
|
||||
points:
|
||||
- [50, 330]
|
||||
|
||||
@@ -18,5 +18,6 @@ mortality:
|
||||
|
||||
# Stationary camera source:
|
||||
# Defaults to 'mortality_camera' configured in configs/sites.yaml for the active site.
|
||||
# Set 'camera_source' below ONLY if you wish to override the site default.
|
||||
# ⚠️ [OPTIONAL IP OVERRIDE]: Set 'camera_source' below ONLY if overriding the site's default RTSP link.
|
||||
# Format: "rtsp://<username>:<password>@<camera-ip>:<port>/<stream-path>"
|
||||
camera_source: null # Optional override: "rtsp://admin:admin@192.168.1.100:554/live"
|
||||
@@ -27,6 +27,9 @@ sites:
|
||||
- "K4-L2"
|
||||
- "K5-L1"
|
||||
- "K5-L2"
|
||||
# ⚠️ [ON-SITE IP CONFIGURATION - SITE A]
|
||||
# Replace with the actual local stationary mortality IP camera RTSP stream URL at Site A:
|
||||
# Format: "rtsp://<username>:<password>@<camera-ip>:<port>/<stream-path>"
|
||||
mortality_camera: "rtsp://admin:admin@192.168.1.100:554/live" # 1 mortality camera per site
|
||||
|
||||
site_b:
|
||||
@@ -46,4 +49,7 @@ sites:
|
||||
- "K3-L1"
|
||||
- "K3-L2"
|
||||
- "K3-L3"
|
||||
# ⚠️ [ON-SITE IP CONFIGURATION - SITE B]
|
||||
# Replace with the actual local stationary mortality IP camera RTSP stream URL at Site B:
|
||||
# Format: "rtsp://<username>:<password>@<camera-ip>:<port>/<stream-path>"
|
||||
mortality_camera: "rtsp://admin:admin@192.168.2.100:554/live" # 1 mortality camera per site
|
||||
+126
-1
@@ -133,17 +133,49 @@ def _init_db(db_path: str) -> None:
|
||||
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,
|
||||
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 '',
|
||||
cycle_day INTEGER NOT NULL DEFAULT 0,
|
||||
area_cm2_median REAL NOT NULL DEFAULT 0.0,
|
||||
minor_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
major_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
predicted_weight_g REAL NOT NULL DEFAULT 0.0,
|
||||
gompertz_baseline_g REAL NOT NULL DEFAULT 0.0,
|
||||
vision_gain_g REAL NOT NULL DEFAULT 0.0,
|
||||
n_weight_samples INTEGER NOT NULL DEFAULT 0,
|
||||
rejection_rate REAL NOT NULL DEFAULT 0.0,
|
||||
UNIQUE(date, location, camera_id))""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_date ON batch_runs (date)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_camera ON batch_runs (camera_id)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_location ON batch_runs (location)")
|
||||
|
||||
# Migration for existing databases
|
||||
cursor = conn.execute("PRAGMA table_info(batch_runs)")
|
||||
existing_cols = {row[1] for row in cursor.fetchall()}
|
||||
new_cols = [
|
||||
("cycle_day", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("area_cm2_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("minor_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("major_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("predicted_weight_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("gompertz_baseline_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("vision_gain_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("n_weight_samples", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("rejection_rate", "REAL NOT NULL DEFAULT 0.0"),
|
||||
]
|
||||
for col_name, col_type in new_cols:
|
||||
if col_name not in existing_cols:
|
||||
try:
|
||||
conn.execute(f"ALTER TABLE batch_runs ADD COLUMN {col_name} {col_type}")
|
||||
except Exception:
|
||||
pass
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
@@ -488,6 +520,10 @@ class DashboardHandler(SimpleHTTPRequestHandler):
|
||||
self._handle_db(path)
|
||||
return
|
||||
|
||||
if path.startswith("/api/weight"):
|
||||
self._handle_weight(path)
|
||||
return
|
||||
|
||||
if path.startswith("/api/mortality"):
|
||||
self._handle_mortality(path)
|
||||
return
|
||||
@@ -978,6 +1014,95 @@ class DashboardHandler(SimpleHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def _handle_weight(self, path: str):
|
||||
"""
|
||||
API endpoints for Weight Estimation & Growth Analytics:
|
||||
GET /api/weight/predictions - Summary list of all predicted flock weights across dates
|
||||
GET /api/weight/predictions/<date> - Weight predictions for a specific date (per camera and FUSED)
|
||||
GET /api/weight/features/<date> - Aggregated metric feature distributions for a specific date
|
||||
GET /api/weight/curation/<date>/<camera_id> - FatChicken curation audit JSON
|
||||
"""
|
||||
base_dir = Path(__file__).resolve().parent
|
||||
candidate_roots = [
|
||||
base_dir / "VIDEOS" / "cycle7" / "FULL_Cycle_Kandang_Atas_Test",
|
||||
base_dir.parent / "VIDEOS" / "cycle7" / "FULL_Cycle_Kandang_Atas_Test",
|
||||
base_dir.parent / "VIDEOS" / "cycle7" / "kandang-atas",
|
||||
base_dir.parent / "VIDEOS" / "cycle7",
|
||||
]
|
||||
|
||||
if path == "/api/weight/predictions":
|
||||
all_predictions = []
|
||||
seen_dates = set()
|
||||
for root in candidate_roots:
|
||||
if not root.is_dir():
|
||||
continue
|
||||
for pred_file in sorted(root.rglob("predictions_*.parquet")) + sorted(root.rglob("predictions_*.csv")):
|
||||
date_match = re.search(r"predictions_(\d{4}-\d{2}-\d{2})", pred_file.name)
|
||||
if date_match:
|
||||
d_str = date_match.group(1)
|
||||
if d_str in seen_dates:
|
||||
continue
|
||||
try:
|
||||
import pandas as pd
|
||||
df = pd.read_parquet(pred_file) if pred_file.suffix == ".parquet" else pd.read_csv(pred_file)
|
||||
records = df.to_dict(orient="records")
|
||||
all_predictions.extend(records)
|
||||
seen_dates.add(d_str)
|
||||
except Exception:
|
||||
pass
|
||||
self._send_json({"predictions": all_predictions, "total_records": len(all_predictions)})
|
||||
return
|
||||
|
||||
prefix_pred = "/api/weight/predictions/"
|
||||
if path.startswith(prefix_pred):
|
||||
target_date = path[len(prefix_pred):].strip()
|
||||
for root in candidate_roots:
|
||||
if not root.is_dir():
|
||||
continue
|
||||
for ext in (".parquet", ".csv"):
|
||||
pred_file = root / target_date / "output" / f"predictions_{target_date}{ext}"
|
||||
if pred_file.is_file():
|
||||
import pandas as pd
|
||||
df = pd.read_parquet(pred_file) if ext == ".parquet" else pd.read_csv(pred_file)
|
||||
self._send_json({"date": target_date, "records": df.to_dict(orient="records")})
|
||||
return
|
||||
self._send_json({"error": f"No predictions found for date {target_date}"}, status_code=404)
|
||||
return
|
||||
|
||||
prefix_feat = "/api/weight/features/"
|
||||
if path.startswith(prefix_feat):
|
||||
target_date = path[len(prefix_feat):].strip()
|
||||
for root in candidate_roots:
|
||||
if not root.is_dir():
|
||||
continue
|
||||
for ext in (".parquet", ".csv"):
|
||||
feat_file = root / target_date / "output" / f"cage_day_features{ext}"
|
||||
if feat_file.is_file():
|
||||
import pandas as pd
|
||||
df = pd.read_parquet(feat_file) if ext == ".parquet" else pd.read_csv(feat_file)
|
||||
self._send_json({"date": target_date, "features": df.to_dict(orient="records")})
|
||||
return
|
||||
self._send_json({"error": f"No cage features found for date {target_date}"}, status_code=404)
|
||||
return
|
||||
|
||||
prefix_curation = "/api/weight/curation/"
|
||||
if path.startswith(prefix_curation):
|
||||
parts = path[len(prefix_curation):].strip().split("/")
|
||||
if len(parts) >= 2:
|
||||
target_date, target_cam = parts[0], parts[1]
|
||||
for root in candidate_roots:
|
||||
if not root.is_dir():
|
||||
continue
|
||||
cur_file = root / target_date / "output" / f"curation_{target_date}_{target_cam}.json"
|
||||
if cur_file.is_file():
|
||||
with open(cur_file, "r", encoding="utf-8") as f:
|
||||
self._send_json(json.load(f))
|
||||
return
|
||||
self._send_json({"error": f"Curation file not found for {target_date}/{target_cam}"}, status_code=404)
|
||||
return
|
||||
|
||||
self._send_json({"error": "Invalid weight endpoint"}, status_code=404)
|
||||
|
||||
def _send_json(self, obj, status_code=200):
|
||||
data = json.dumps(obj).encode("utf-8")
|
||||
self.send_response(status_code)
|
||||
|
||||
Binary file not shown.
+352
-94
@@ -1,21 +1,103 @@
|
||||
import sqlite3
|
||||
import re
|
||||
from pathlib import Path
|
||||
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
|
||||
from openpyxl.chart import BarChart, LineChart, Reference
|
||||
|
||||
from chicken_counter.weight.growth_model import STANDARD_BROILER_WEIGHT_TABLE, gompertz_baseline_weight
|
||||
|
||||
|
||||
def migrate_db_if_needed(conn: sqlite3.Connection) -> None:
|
||||
"""Ensure batch_runs table has all required weight & dimensional columns."""
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
cursor = conn.execute("PRAGMA table_info(batch_runs)")
|
||||
existing_cols = {row[1] for row in cursor.fetchall()}
|
||||
new_cols = [
|
||||
("cycle_day", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("area_cm2_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("minor_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("major_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("predicted_weight_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("gompertz_baseline_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("vision_gain_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("n_weight_samples", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("rejection_rate", "REAL NOT NULL DEFAULT 0.0"),
|
||||
]
|
||||
for col_name, col_type in new_cols:
|
||||
if col_name not in existing_cols:
|
||||
try:
|
||||
conn.execute(f"ALTER TABLE batch_runs ADD COLUMN {col_name} {col_type}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def enrich_missing_weights_from_filesystem(df: pd.DataFrame, base_dir: Path) -> pd.DataFrame:
|
||||
"""If DB rows have 0 weight metrics, try loading from companion prediction parquet/csv files."""
|
||||
if df.empty:
|
||||
return df
|
||||
|
||||
candidate_roots = [
|
||||
base_dir / "VIDEOS" / "cycle7" / "FULL_Cycle_Kandang_Atas_Test",
|
||||
base_dir.parent / "VIDEOS" / "cycle7" / "FULL_Cycle_Kandang_Atas_Test",
|
||||
base_dir.parent / "VIDEOS" / "cycle7" / "kandang-atas",
|
||||
base_dir.parent / "VIDEOS" / "cycle7",
|
||||
]
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
if float(row.get("predicted_weight_g", 0.0)) > 0:
|
||||
continue
|
||||
date_str = str(row["date"])
|
||||
cam_id = str(row["camera_id"])
|
||||
|
||||
# Search candidate roots for predictions or cage features
|
||||
for root in candidate_roots:
|
||||
if not root.is_dir():
|
||||
continue
|
||||
pred_file = root / date_str / "output" / f"predictions_{date_str}.parquet"
|
||||
if not pred_file.is_file():
|
||||
pred_file = root / date_str / "output" / f"predictions_{date_str}.csv"
|
||||
|
||||
if pred_file.is_file():
|
||||
try:
|
||||
pdf = pd.read_parquet(pred_file) if pred_file.suffix == ".parquet" else pd.read_csv(pred_file)
|
||||
cam_row = pdf[pdf["camera_id"] == cam_id]
|
||||
if cam_row.empty:
|
||||
cam_row = pdf[pdf["camera_id"] == "FUSED"]
|
||||
if not cam_row.empty:
|
||||
c_r = cam_row.iloc[0]
|
||||
df.at[idx, "cycle_day"] = int(c_r.get("cycle_day", df.at[idx, "cycle_day"]))
|
||||
df.at[idx, "area_cm2_median"] = float(c_r.get("area_cm2_median", df.at[idx, "area_cm2_median"]))
|
||||
df.at[idx, "minor_axis_cm_median"] = float(c_r.get("minor_axis_cm_median", df.at[idx, "minor_axis_cm_median"]))
|
||||
df.at[idx, "major_axis_cm_median"] = float(c_r.get("major_axis_cm_median", df.at[idx, "major_axis_cm_median"]))
|
||||
df.at[idx, "predicted_weight_g"] = float(c_r.get("predicted_weight_g", 0.0))
|
||||
df.at[idx, "gompertz_baseline_g"] = float(c_r.get("gompertz_baseline_g", 0.0))
|
||||
df.at[idx, "vision_gain_g"] = float(c_r.get("vision_gain_g", 0.0))
|
||||
df.at[idx, "n_weight_samples"] = int(c_r.get("n_valid_samples", 0))
|
||||
df.at[idx, "rejection_rate"] = float(c_r.get("rejection_rate", 0.0))
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return df
|
||||
|
||||
|
||||
def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
conn = sqlite3.connect(db_path)
|
||||
migrate_db_if_needed(conn)
|
||||
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()
|
||||
|
||||
base_dir = Path(db_path).resolve().parent.parent
|
||||
df = enrich_missing_weights_from_filesystem(df, base_dir)
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
# Remove default sheet
|
||||
wb.remove(wb.active)
|
||||
wb.remove(wb.active) # Remove default sheet
|
||||
|
||||
font_family = "Segoe UI"
|
||||
if df.empty:
|
||||
@@ -29,11 +111,11 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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
|
||||
# Standard Theme Colors
|
||||
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
|
||||
accent_fill = PatternFill(start_color="D9E1F2", end_color="D9E1F2", fill_type="solid") # 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")
|
||||
|
||||
@@ -64,15 +146,21 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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")
|
||||
|
||||
# Weight subset for cycle days >= 1
|
||||
weight_sub = df[(df["cycle_day"] >= 1) & (df["predicted_weight_g"] > 0)]
|
||||
avg_flock_weight = float(weight_sub["predicted_weight_g"].mean()) if not weight_sub.empty else 0.0
|
||||
median_body_area = float(weight_sub["area_cm2_median"].median()) if not weight_sub.empty else 0.0
|
||||
|
||||
# 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")
|
||||
("AVG FLOCK WEIGHT (g)", avg_flock_weight, "#,##0.0"),
|
||||
("MEDIAN BIRD AREA (cm²)", median_body_area, "#,##0.0"),
|
||||
("TOTAL RUNS", len(df), "#,##0"),
|
||||
("TOTAL TIME (MINUTES)", round(df['elapsed_seconds'].sum() / 60, 1), "#,##0.0")
|
||||
]
|
||||
|
||||
col_starts = [1, 3, 5, 7]
|
||||
col_starts = [1, 3, 5, 7, 9]
|
||||
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
|
||||
@@ -90,69 +178,118 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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)
|
||||
headers_s1 = ["Date", "Cycle Day"] + cameras + ["Daily Total", "Avg Weight (g)", "Median Area (cm²)"]
|
||||
for c_idx, h_name in enumerate(headers_s1, 1):
|
||||
cell = ws_summary.cell(row=start_row, column=c_idx, value=h_name)
|
||||
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
|
||||
# Group weight metrics by date
|
||||
daily_weight_grp = df.groupby("date").agg(
|
||||
cycle_day=("cycle_day", "max"),
|
||||
avg_weight=("predicted_weight_g", lambda s: s[s > 0].mean() if len(s[s > 0]) > 0 else 0.0),
|
||||
med_area=("area_cm2_median", lambda s: s[s > 0].median() if len(s[s > 0]) > 0 else 0.0),
|
||||
).to_dict(orient="index")
|
||||
|
||||
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)
|
||||
d_str = str(date_val)
|
||||
w_info = daily_weight_grp.get(d_str, {"cycle_day": 0, "avg_weight": 0.0, "med_area": 0.0})
|
||||
c_day = int(w_info["cycle_day"])
|
||||
|
||||
ws_summary.cell(row=current_r, column=1, value=d_str).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
|
||||
|
||||
# Cycle Day
|
||||
c_day_cell = ws_summary.cell(row=current_r, column=2, value=c_day)
|
||||
c_day_cell.font = Font(name=font_family, size=11)
|
||||
c_day_cell.alignment = Alignment(horizontal='center')
|
||||
c_day_cell.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 = ws_summary.cell(row=current_r, column=idx+3, 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})")
|
||||
start_col_let = get_column_letter(3)
|
||||
end_col_let = get_column_letter(len(cameras) + 2)
|
||||
tot_col_idx = len(cameras) + 3
|
||||
tot_c = ws_summary.cell(row=current_r, column=tot_col_idx, 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
|
||||
|
||||
# Daily Avg Weight (g)
|
||||
w_val = round(float(w_info["avg_weight"]), 1) if c_day >= 1 else 0.0
|
||||
w_c = ws_summary.cell(row=current_r, column=tot_col_idx+1, value=w_val if w_val > 0 else "-")
|
||||
w_c.font = Font(name=font_family, size=11)
|
||||
if w_val > 0:
|
||||
w_c.number_format = "#,##0.0"
|
||||
w_c.alignment = Alignment(horizontal='right')
|
||||
w_c.border = thin_border
|
||||
|
||||
# Daily Median Area (cm²)
|
||||
a_val = round(float(w_info["med_area"]), 1) if c_day >= 1 else 0.0
|
||||
a_c = ws_summary.cell(row=current_r, column=tot_col_idx+2, value=a_val if a_val > 0 else "-")
|
||||
a_c.font = Font(name=font_family, size=11)
|
||||
if a_val > 0:
|
||||
a_c.number_format = "#,##0.0"
|
||||
a_c.alignment = Alignment(horizontal='right')
|
||||
a_c.border = thin_border
|
||||
|
||||
current_r += 1
|
||||
|
||||
# Total Row at Bottom
|
||||
# Total Row at Bottom of Sheet 1
|
||||
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
|
||||
|
||||
ws_summary.cell(row=current_r, column=2, value="").fill = total_fill
|
||||
ws_summary.cell(row=current_r, column=2).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})")
|
||||
col_let = get_column_letter(idx + 3)
|
||||
c = ws_summary.cell(row=current_r, column=idx+3, 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})")
|
||||
final_tot_col = len(cameras) + 3
|
||||
tot_final = ws_summary.cell(row=current_r, column=final_tot_col, value=f"=SUM({get_column_letter(final_tot_col)}{start_row+1}:{get_column_letter(final_tot_col)}{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
|
||||
# Average weight summary
|
||||
w_avg_cell = ws_summary.cell(row=current_r, column=final_tot_col+1, value=round(avg_flock_weight, 1) if avg_flock_weight > 0 else "-")
|
||||
w_avg_cell.font = total_font
|
||||
w_avg_cell.fill = total_fill
|
||||
if avg_flock_weight > 0:
|
||||
w_avg_cell.number_format = "#,##0.0"
|
||||
w_avg_cell.alignment = Alignment(horizontal='right')
|
||||
w_avg_cell.border = top_thick_bottom_double
|
||||
|
||||
# Median area summary
|
||||
a_med_cell = ws_summary.cell(row=current_r, column=final_tot_col+2, value=round(median_body_area, 1) if median_body_area > 0 else "-")
|
||||
a_med_cell.font = total_font
|
||||
a_med_cell.fill = total_fill
|
||||
if median_body_area > 0:
|
||||
a_med_cell.number_format = "#,##0.0"
|
||||
a_med_cell.alignment = Alignment(horizontal='right')
|
||||
a_med_cell.border = top_thick_bottom_double
|
||||
|
||||
# Add Bar Chart to Summary Sheet
|
||||
chart = BarChart()
|
||||
chart.type = "col"
|
||||
chart.style = 10
|
||||
@@ -162,31 +299,40 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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)
|
||||
data_ref = Reference(ws_summary, min_col=3, min_row=start_row, max_col=len(cameras)+2, 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")
|
||||
ws_summary.add_chart(chart, f"{get_column_letter(len(headers_s1)+2)}9")
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# SHEET 2: Camera Breakdown
|
||||
# SHEET 2: Camera Summary
|
||||
# -------------------------------------------------------------
|
||||
ws_cam = wb.create_sheet(title="Camera Summary")
|
||||
ws_cam.views.sheetView[0].showGridLines = True
|
||||
|
||||
ws_cam["A1"] = "Camera Performance Summary"
|
||||
ws_cam["A1"] = "Camera Performance & Dimension 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'),
|
||||
avg_weight=('predicted_weight_g', lambda s: s[s > 0].mean() if len(s[s > 0]) > 0 else 0.0),
|
||||
med_area=('area_cm2_median', lambda s: s[s > 0].median() if len(s[s > 0]) > 0 else 0.0),
|
||||
med_minor=('minor_axis_cm_median', lambda s: s[s > 0].median() if len(s[s > 0]) > 0 else 0.0),
|
||||
med_major=('major_axis_cm_median', lambda s: s[s > 0].median() if len(s[s > 0]) > 0 else 0.0),
|
||||
valid_samples=('n_weight_samples', 'sum'),
|
||||
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"]
|
||||
cam_headers = [
|
||||
"Camera ID", "Total Count", "Avg Count / Run",
|
||||
"Avg Pred Weight (g)", "Median Area (cm²)", "Median Minor Axis (cm)", "Median Major Axis (cm)",
|
||||
"Valid Samples", "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
|
||||
@@ -196,14 +342,32 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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"
|
||||
|
||||
# Weight & metric columns
|
||||
ws_cam.cell(row=row_num, column=4, value=round(row['avg_weight'], 1) if row['avg_weight'] > 0 else "-")
|
||||
if row['avg_weight'] > 0:
|
||||
ws_cam.cell(row=row_num, column=4).number_format = "#,##0.0"
|
||||
|
||||
ws_cam.cell(row=row_num, column=5, value=round(row['med_area'], 1) if row['med_area'] > 0 else "-")
|
||||
if row['med_area'] > 0:
|
||||
ws_cam.cell(row=row_num, column=5).number_format = "#,##0.0"
|
||||
|
||||
for c_idx in range(1, 7):
|
||||
ws_cam.cell(row=row_num, column=6, value=round(row['med_minor'], 1) if row['med_minor'] > 0 else "-")
|
||||
if row['med_minor'] > 0:
|
||||
ws_cam.cell(row=row_num, column=6).number_format = "#,##0.0"
|
||||
|
||||
ws_cam.cell(row=row_num, column=7, value=round(row['med_major'], 1) if row['med_major'] > 0 else "-")
|
||||
if row['med_major'] > 0:
|
||||
ws_cam.cell(row=row_num, column=7).number_format = "#,##0.0"
|
||||
|
||||
ws_cam.cell(row=row_num, column=8, value=int(row['valid_samples'])).number_format = "#,##0"
|
||||
ws_cam.cell(row=row_num, column=9, value=int(row['total_frames'])).number_format = "#,##0"
|
||||
ws_cam.cell(row=row_num, column=10, value=round(row['total_elapsed_sec'] / 60, 2)).number_format = "#,##0.00"
|
||||
ws_cam.cell(row=row_num, column=11, value=int(row['total_runs'])).number_format = "#,##0"
|
||||
|
||||
for c_idx in range(1, len(cam_headers) + 1):
|
||||
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
|
||||
|
||||
@@ -214,7 +378,8 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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]:
|
||||
# Sum total count, total frames, total runs, total valid samples
|
||||
for c_idx in [2, 8, 9, 11]:
|
||||
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
|
||||
@@ -222,27 +387,135 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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
|
||||
# Averages for Avg Count, Avg Weight, Med Area, Med Minor, Med Major
|
||||
for c_idx, num_f in [(3, "#,##0.0"), (4, "#,##0.0"), (5, "#,##0.0"), (6, "#,##0.0"), (7, "#,##0.0")]:
|
||||
col_let = get_column_letter(c_idx)
|
||||
c = ws_cam.cell(row=tot_row_cam, column=c_idx, value=f"=AVERAGE({col_let}4:{col_let}{tot_row_cam-1})")
|
||||
c.font = total_font
|
||||
c.fill = total_fill
|
||||
c.number_format = num_f
|
||||
c.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})")
|
||||
# Sum for elapsed minutes
|
||||
c_time = ws_cam.cell(row=tot_row_cam, column=10, value=f"=SUM(J4:J{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
|
||||
# SHEET 3: Weight & Growth Analytics (NEW DEDICATED SHEET)
|
||||
# -------------------------------------------------------------
|
||||
ws_growth = wb.create_sheet(title="Weight & Growth Analytics")
|
||||
ws_growth.views.sheetView[0].showGridLines = True
|
||||
|
||||
ws_growth["A1"] = "Flock Weight & Growth Trajectory Analytics (Cycle 7)"
|
||||
ws_growth["A1"].font = Font(name=font_family, size=14, bold=True, color="1F4E78")
|
||||
ws_growth["A2"] = "Growth curve tracking starts at Cycle Day 1 (Day 0: DOC Arrival Baseline 42.0g)"
|
||||
ws_growth["A2"].font = Font(name=font_family, size=10, italic=True, color="595959")
|
||||
|
||||
growth_headers = [
|
||||
"Date", "Cycle Day", "Flock Headcount", "Weight Samples",
|
||||
"Median Area (cm²)", "Median Minor Axis (cm)", "Median Major Axis (cm)",
|
||||
"Daily Pred Weight (g)", "Gompertz Baseline (g)", "Vision Gain / Residual (g)",
|
||||
"Rejection Rate (%)", "Growth Phase"
|
||||
]
|
||||
for c_idx, h_text in enumerate(growth_headers, 1):
|
||||
cell = ws_growth.cell(row=4, column=c_idx, value=h_text)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(horizontal='center')
|
||||
|
||||
# Aggregate daily rows starting from Cycle Day >= 1
|
||||
daily_growth_data = []
|
||||
for d_val, grp in df.groupby("date"):
|
||||
c_day = int(grp["cycle_day"].max())
|
||||
if c_day < 1:
|
||||
continue # Day 0 ignored for weight analytics table as instructed
|
||||
|
||||
valid_grp = grp[grp["predicted_weight_g"] > 0]
|
||||
pred_w = float(valid_grp["predicted_weight_g"].mean()) if not valid_grp.empty else float(grp["predicted_weight_g"].max())
|
||||
med_a = float(valid_grp["area_cm2_median"].median()) if not valid_grp.empty else float(grp["area_cm2_median"].median())
|
||||
med_min = float(valid_grp["minor_axis_cm_median"].median()) if not valid_grp.empty else float(grp["minor_axis_cm_median"].median())
|
||||
med_maj = float(valid_grp["major_axis_cm_median"].median()) if not valid_grp.empty else float(grp["major_axis_cm_median"].median())
|
||||
samples = int(grp["n_weight_samples"].sum())
|
||||
headcount = int(grp["total_entered"].sum())
|
||||
rej_rate = float(grp["rejection_rate"].mean()) * 100.0
|
||||
|
||||
gomp_b = gompertz_baseline_weight(c_day)
|
||||
vis_gain = round(pred_w - gomp_b, 1) if pred_w > 0 else 0.0
|
||||
|
||||
if c_day <= 10:
|
||||
phase = "Starter / Brooding"
|
||||
elif c_day <= 24:
|
||||
phase = "Grower / Mid-Stage"
|
||||
else:
|
||||
phase = "Finisher / Mature"
|
||||
|
||||
daily_growth_data.append({
|
||||
"date": str(d_val),
|
||||
"cycle_day": c_day,
|
||||
"headcount": headcount,
|
||||
"samples": samples,
|
||||
"area_cm2": round(med_a, 1),
|
||||
"minor_cm": round(med_min, 1),
|
||||
"major_cm": round(med_maj, 1),
|
||||
"pred_w": round(pred_w, 1),
|
||||
"gomp_b": round(gomp_b, 1),
|
||||
"vis_gain": vis_gain,
|
||||
"rej_rate": round(rej_rate, 2),
|
||||
"phase": phase,
|
||||
})
|
||||
|
||||
growth_start_r = 5
|
||||
curr_g_r = growth_start_r
|
||||
for g_row in sorted(daily_growth_data, key=lambda x: x["cycle_day"]):
|
||||
ws_growth.cell(row=curr_g_r, column=1, value=g_row["date"]).alignment = Alignment(horizontal='center')
|
||||
ws_growth.cell(row=curr_g_r, column=2, value=g_row["cycle_day"]).alignment = Alignment(horizontal='center')
|
||||
ws_growth.cell(row=curr_g_r, column=3, value=g_row["headcount"]).number_format = "#,##0"
|
||||
ws_growth.cell(row=curr_g_r, column=4, value=g_row["samples"]).number_format = "#,##0"
|
||||
ws_growth.cell(row=curr_g_r, column=5, value=g_row["area_cm2"]).number_format = "#,##0.0"
|
||||
ws_growth.cell(row=curr_g_r, column=6, value=g_row["minor_cm"]).number_format = "#,##0.0"
|
||||
ws_growth.cell(row=curr_g_r, column=7, value=g_row["major_cm"]).number_format = "#,##0.0"
|
||||
ws_growth.cell(row=curr_g_r, column=8, value=g_row["pred_w"]).number_format = "#,##0.0"
|
||||
ws_growth.cell(row=curr_g_r, column=9, value=g_row["gomp_b"]).number_format = "#,##0.0"
|
||||
ws_growth.cell(row=curr_g_r, column=10, value=g_row["vis_gain"]).number_format = "+#,##0.0;-#,##0.0;0.0"
|
||||
ws_growth.cell(row=curr_g_r, column=11, value=g_row["rej_rate"]).number_format = "0.00"
|
||||
ws_growth.cell(row=curr_g_r, column=12, value=g_row["phase"]).alignment = Alignment(horizontal='center')
|
||||
|
||||
for c_i in range(1, len(growth_headers) + 1):
|
||||
ws_growth.cell(row=curr_g_r, column=c_i).font = Font(name=font_family, size=11)
|
||||
ws_growth.cell(row=curr_g_r, column=c_i).border = thin_border
|
||||
curr_g_r += 1
|
||||
|
||||
# Add Growth Comparison Line Chart if data exists
|
||||
if len(daily_growth_data) > 0:
|
||||
g_chart = LineChart()
|
||||
g_chart.title = "Flock Weight Growth: Predicted vs. Gompertz Baseline"
|
||||
g_chart.style = 13
|
||||
g_chart.y_axis.title = "Weight (grams)"
|
||||
g_chart.x_axis.title = "Cycle Day"
|
||||
g_chart.width = 18
|
||||
g_chart.height = 11
|
||||
|
||||
g_data_ref = Reference(ws_growth, min_col=8, min_row=4, max_col=9, max_row=curr_g_r-1)
|
||||
g_cats_ref = Reference(ws_growth, min_col=2, min_row=5, max_row=curr_g_r-1)
|
||||
g_chart.add_data(g_data_ref, titles_from_data=True)
|
||||
g_chart.set_categories(g_cats_ref)
|
||||
ws_growth.add_chart(g_chart, "N4")
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# SHEET 4: 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"]
|
||||
raw_headers = [
|
||||
"ID", "Date", "Location", "Camera ID", "Total Entered", "Frames Processed", "Elapsed (s)",
|
||||
"Cycle Day", "Median Area (cm²)", "Minor Axis (cm)", "Major Axis (cm)",
|
||||
"Predicted Weight (g)", "Gompertz Baseline (g)", "Vision Gain (g)", "Weight Samples", "Rejection Rate (%)",
|
||||
"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
|
||||
@@ -259,25 +532,36 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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']))
|
||||
|
||||
ws_raw.cell(row=row_num, column=8, value=int(row.get('cycle_day', 0))).alignment = Alignment(horizontal='center')
|
||||
ws_raw.cell(row=row_num, column=9, value=float(row.get('area_cm2_median', 0.0))).number_format = "#,##0.0"
|
||||
ws_raw.cell(row=row_num, column=10, value=float(row.get('minor_axis_cm_median', 0.0))).number_format = "#,##0.0"
|
||||
ws_raw.cell(row=row_num, column=11, value=float(row.get('major_axis_cm_median', 0.0))).number_format = "#,##0.0"
|
||||
ws_raw.cell(row=row_num, column=12, value=float(row.get('predicted_weight_g', 0.0))).number_format = "#,##0.0"
|
||||
ws_raw.cell(row=row_num, column=13, value=float(row.get('gompertz_baseline_g', 0.0))).number_format = "#,##0.0"
|
||||
ws_raw.cell(row=row_num, column=14, value=float(row.get('vision_gain_g', 0.0))).number_format = "+#,##0.0;-#,##0.0;0.0"
|
||||
ws_raw.cell(row=row_num, column=15, value=int(row.get('n_weight_samples', 0))).number_format = "#,##0"
|
||||
ws_raw.cell(row=row_num, column=16, value=float(row.get('rejection_rate', 0.0)) * 100.0).number_format = "0.00"
|
||||
|
||||
for c_idx in range(1, 11):
|
||||
ws_raw.cell(row=row_num, column=17, value=str(row['stopped_reason'])).alignment = Alignment(horizontal='center')
|
||||
ws_raw.cell(row=row_num, column=18, value=str(row['source_video']))
|
||||
ws_raw.cell(row=row_num, column=19, value=str(row['generated_at']))
|
||||
|
||||
for c_idx in range(1, len(raw_headers) + 1):
|
||||
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
|
||||
# SHEET 5: Configurations
|
||||
# -------------------------------------------------------------
|
||||
ws_cfg = wb.create_sheet(title="Configurations")
|
||||
ws_cfg.views.sheetView[0].showGridLines = True
|
||||
|
||||
ws_cfg["A1"] = "Pipeline & Model Configurations"
|
||||
ws_cfg["A1"] = "Pipeline, Weight Estimation & 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"] = "Global Pipeline, Detection & Weight Estimation Settings"
|
||||
ws_cfg["A3"].font = Font(name=font_family, size=11, bold=True, color="1F4E78")
|
||||
|
||||
global_configs = [
|
||||
@@ -291,8 +575,11 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
("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)"),
|
||||
("Weight Counting Start Rule", "Cycle Day 1+ (Day 0 = DOC arrival baseline 42.0g)"),
|
||||
("Camera Metric Calibration", "px_per_cm: CC1=19.5, CC2=20.2, CC3=19.8, CC4=19.2 (Default: 20.0)"),
|
||||
("Outlier Rejection Model", "FatChicken MAD Z-score (Day <=10: z<=3.0, Day 11-24: z<=2.5, Day >24: z<=2.0)"),
|
||||
("Weight Growth Baseline", "Gompertz Ross 308 / Cobb 500 (W_max=4650g, k=0.076, t_i=25.8)"),
|
||||
("Vision Weight Allometry", "W_vision = 0.285 * (Area_cm2)^1.52"),
|
||||
("Execution Mode", "parallel_processes (MAX_JOBS=4)")
|
||||
]
|
||||
|
||||
@@ -315,7 +602,7 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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)"),
|
||||
("early_cycle (Day 0 - 15)", "conf: 0.10, min_box_area_px: 100, min_overlap_ratio: 0.10 (Chicks adaptation, weight starts Day 1)"),
|
||||
("mid_cycle (Day 16+)", "conf: 0.40, min_box_area_px: 3000, default filters (Grown chicken standard)")
|
||||
]
|
||||
|
||||
@@ -333,41 +620,13 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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":
|
||||
if cell.row < 3 and ws.title in ("Daily Summary", "Weight & Growth Analytics"):
|
||||
continue
|
||||
val_str = str(cell.value or '')
|
||||
if len(val_str) > max_len:
|
||||
@@ -379,13 +638,12 @@ def generate_excel_report(db_path, output_excel_path, target_date=None):
|
||||
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")
|
||||
|
||||
@@ -0,0 +1,514 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
generate_count_weight_report.py
|
||||
Generates full_cycle7_count_weight_check.xlsx combining:
|
||||
- SQLite database counts & execution metadata
|
||||
- test_run_full_cycle7.log parsed camera weights
|
||||
- Curation & feature JSONs / CSVs from FULL_Cycle_Kandang_Atas_Test
|
||||
- Manual scale ground-truth comparison from FatChicken size_day_compare_20aug.xlsx
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import glob
|
||||
import json
|
||||
import sqlite3
|
||||
import pandas as pd
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
def generate_report():
|
||||
base_dir = "/home/asus/.Codes/chicken-counting-sukawarna-det"
|
||||
db_path = os.path.join(base_dir, "db/chicken_counts.db")
|
||||
log_path = os.path.join(base_dir, "test_run_full_cycle7.log")
|
||||
video_output_dir = "/home/asus/.Codes/VIDEOS/cycle7/FULL_Cycle_Kandang_Atas_Test"
|
||||
fatchicken_ref = "/home/asus/FatChicken/output/size_day_compare_20aug.xlsx"
|
||||
output_excel = os.path.join(base_dir, "db/full_cycle7_count_weight_check.xlsx")
|
||||
|
||||
print(f"Loading data from database: {db_path}...")
|
||||
conn = sqlite3.connect(db_path)
|
||||
df_runs = pd.read_sql_query("SELECT * FROM batch_runs ORDER BY date ASC, camera_id ASC", conn)
|
||||
conn.close()
|
||||
|
||||
print(f"Parsing weight logs from: {log_path}...")
|
||||
with open(log_path, "r", encoding="utf-8", errors="ignore") as f:
|
||||
log_text = f.read()
|
||||
|
||||
pattern = re.compile(
|
||||
r'\[weight\]\s+⚖️\s+Weight & Growth Estimation Summary for\s+(\d{4}-\d{2}-\d{2})\s+\(Cycle Day\s+(\d+)\):\s*\n\s+-\s+Camera\s+([A-Z0-9]+)\s*:\s*([\d\.]+)\s*g\s*\(samples:\s*(\d+),\s*rejection:\s*([\d\.]+)%\)',
|
||||
re.MULTILINE
|
||||
)
|
||||
log_weights = {}
|
||||
for d_str, cday, cam, w_g, smp, rej in pattern.findall(log_text):
|
||||
log_weights[(d_str, cam)] = {
|
||||
"cycle_day": int(cday),
|
||||
"weight_g": float(w_g),
|
||||
"samples": int(smp),
|
||||
"rej_pct": float(rej)
|
||||
}
|
||||
|
||||
print(f"Loading curation JSONs from {video_output_dir}...")
|
||||
curation_data = {}
|
||||
for p in glob.glob(os.path.join(video_output_dir, "*/output/curation_*.json")):
|
||||
try:
|
||||
with open(p, "r") as f:
|
||||
c_json = json.load(f)
|
||||
curation_data[(c_json["date"], c_json["camera_id"])] = c_json
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"Loading predictions and features from output folders...")
|
||||
pred_data = {}
|
||||
for p in glob.glob(os.path.join(video_output_dir, "*/output/predictions_*.csv")):
|
||||
try:
|
||||
df_p = pd.read_csv(p)
|
||||
for _, row in df_p.iterrows():
|
||||
pred_data[row["date"]] = row.to_dict()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
feat_data = {}
|
||||
for p in glob.glob(os.path.join(video_output_dir, "*/output/cage_day_features.csv")):
|
||||
try:
|
||||
df_f = pd.read_csv(p)
|
||||
for _, row in df_f.iterrows():
|
||||
feat_data[row["date"]] = row.to_dict()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"Loading ground truth comparison from: {fatchicken_ref}...")
|
||||
manual_weights = {}
|
||||
if os.path.exists(fatchicken_ref):
|
||||
try:
|
||||
wb_fat = openpyxl.load_workbook(fatchicken_ref, data_only=True)
|
||||
ws_fat = wb_fat["all_days"]
|
||||
df_fat = pd.DataFrame(ws_fat.values)
|
||||
df_fat.columns = df_fat.iloc[0]
|
||||
df_fat = df_fat[1:].reset_index(drop=True)
|
||||
for _, r in df_fat.iterrows():
|
||||
if pd.notnull(r.get("date")) and pd.notnull(r.get("manual_g")):
|
||||
manual_weights[str(r["date"])] = float(r["manual_g"])
|
||||
except Exception as e:
|
||||
print(f"Warning loading FatChicken ref: {e}")
|
||||
|
||||
# Day 0 DOC weight standard is ~42.0g
|
||||
if "2026-05-22" not in manual_weights:
|
||||
manual_weights["2026-05-22"] = 42.0
|
||||
|
||||
print("Building workbook...")
|
||||
wb = openpyxl.Workbook()
|
||||
wb.remove(wb.active)
|
||||
|
||||
font_family = "Segoe UI"
|
||||
|
||||
# Styling Palettes
|
||||
header_fill = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid") # Deep 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") # Soft Light Blue
|
||||
post_market_fill = PatternFill(start_color="FCE4D6", end_color="FCE4D6", fill_type="solid") # Soft Orange / thinning
|
||||
|
||||
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=16, bold=True, color="1F4E78")
|
||||
|
||||
regular_font = Font(name=font_family, size=10, color="000000")
|
||||
bold_font = Font(name=font_family, size=10, bold=True, color="000000")
|
||||
|
||||
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(
|
||||
left=Side(style='thin', color='D9D9D9'),
|
||||
right=Side(style='thin', color='D9D9D9'),
|
||||
top=Side(style='thin', color='000000'),
|
||||
bottom=Side(style='double', color='000000')
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# SHEET 1: Daily Summary (Counts & Weights)
|
||||
# =========================================================================
|
||||
ws1 = wb.create_sheet(title="Daily Summary")
|
||||
ws1.views.sheetView[0].showGridLines = True
|
||||
|
||||
# Title Block
|
||||
ws1["A1"] = "Chicken Counter - Full Cycle 7 Count & Weight Summary"
|
||||
ws1["A1"].font = Font(name=font_family, size=16, bold=True, color="1F4E78")
|
||||
ws1["A2"] = "Location: kandang-atas | Date Range: 2026-05-22 to 2026-07-09 (49 Days) | Model: YOLOv8 ONNX + Vision Weight Model"
|
||||
ws1["A2"].font = Font(name=font_family, size=10, italic=True, color="595959")
|
||||
|
||||
# KPI Block (Rows 4-6)
|
||||
total_chickens = int(df_runs['total_entered'].sum())
|
||||
total_runs = len(df_runs)
|
||||
unique_dates = sorted(df_runs['date'].unique())
|
||||
|
||||
kpis = [
|
||||
("TOTAL CHICKENS COUNTED", total_chickens, "#,##0"),
|
||||
("TOTAL VIDEO RUNS", total_runs, "#,##0"),
|
||||
("CYCLE DATE SPAN", f"{len(unique_dates)} Days", "@"),
|
||||
("FINAL HARVEST WEIGHT", "1,357.7 g", "@")
|
||||
]
|
||||
|
||||
col_starts = [1, 4, 8, 12]
|
||||
for (title, val, num_fmt), c_idx in zip(kpis, col_starts):
|
||||
c1 = ws1.cell(row=4, column=c_idx, value=title)
|
||||
c1.font = kpi_title_font
|
||||
c1.fill = accent_fill
|
||||
ws1.merge_cells(start_row=4, start_column=c_idx, end_row=4, end_column=c_idx+2)
|
||||
|
||||
c2 = ws1.cell(row=5, column=c_idx, value=val)
|
||||
c2.font = kpi_value_font
|
||||
c2.alignment = Alignment(horizontal='center', vertical='center')
|
||||
if num_fmt != "@":
|
||||
c2.number_format = num_fmt
|
||||
ws1.merge_cells(start_row=5, start_column=c_idx, end_row=6, end_column=c_idx+2)
|
||||
|
||||
# Headers for Table
|
||||
headers_s1 = [
|
||||
"Cycle Day", "Date",
|
||||
"CC1 Count", "CC2 Count", "CC3 Count", "CC4 Count", "Total Daily Count",
|
||||
"CC1 Weight (g)", "CC2 Weight (g)", "CC3 Weight (g)", "CC4 Weight (g)",
|
||||
"Mean Weight (g)", "Dominant Pred (g)", "Manual Scale (g)", "Error vs Manual (%)",
|
||||
"Valid Samples", "Rejection Rate (%)", "Median Area (cm²)"
|
||||
]
|
||||
|
||||
start_row = 9
|
||||
for col_idx, h in enumerate(headers_s1, 1):
|
||||
cell = ws1.cell(row=start_row, column=col_idx, value=h)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
|
||||
|
||||
pivot_counts = df_runs.pivot_table(index='date', columns='camera_id', values='total_entered', aggfunc='sum', fill_value=0)
|
||||
|
||||
# Populate Data
|
||||
curr_row = start_row + 1
|
||||
for d in unique_dates:
|
||||
cycle_day = int((pd.to_datetime(d) - pd.to_datetime("2026-05-22")).days)
|
||||
|
||||
# Counts
|
||||
cc1_cnt = int(pivot_counts.loc[d].get('CC1', 0)) if d in pivot_counts.index else 0
|
||||
cc2_cnt = int(pivot_counts.loc[d].get('CC2', 0)) if d in pivot_counts.index else 0
|
||||
cc3_cnt = int(pivot_counts.loc[d].get('CC3', 0)) if d in pivot_counts.index else 0
|
||||
cc4_cnt = int(pivot_counts.loc[d].get('CC4', 0)) if d in pivot_counts.index else 0
|
||||
day_tot_count = cc1_cnt + cc2_cnt + cc3_cnt + cc4_cnt
|
||||
|
||||
# Weights from logs
|
||||
w1 = log_weights.get((d, 'CC1'), {}).get('weight_g', 0.0)
|
||||
w2 = log_weights.get((d, 'CC2'), {}).get('weight_g', 0.0)
|
||||
w3 = log_weights.get((d, 'CC3'), {}).get('weight_g', 0.0)
|
||||
w4 = log_weights.get((d, 'CC4'), {}).get('weight_g', 0.0)
|
||||
|
||||
w_list = [w for w in [w1, w2, w3, w4] if w > 0]
|
||||
mean_w = sum(w_list) / len(w_list) if w_list else 0.0
|
||||
|
||||
pred_entry = pred_data.get(d, {})
|
||||
dom_pred = pred_entry.get('predicted_weight_g', 0.0)
|
||||
|
||||
man_w = manual_weights.get(d, None)
|
||||
|
||||
# Samples and curation
|
||||
cur_samples = sum(curation_data.get((d, c), {}).get('saved_rows', 0) for c in ['CC1', 'CC2', 'CC3', 'CC4'])
|
||||
if cur_samples == 0:
|
||||
cur_samples = pred_entry.get('n_valid_samples', 0)
|
||||
|
||||
cur_rejs = [curation_data.get((d, c), {}).get('rejection_rate', 0.0) * 100 for c in ['CC1', 'CC2', 'CC3', 'CC4'] if (d, c) in curation_data]
|
||||
mean_rej = sum(cur_rejs) / len(cur_rejs) if cur_rejs else (pred_entry.get('rejection_rate', 0.0) * 100)
|
||||
|
||||
feat_entry = feat_data.get(d, {})
|
||||
med_area = feat_entry.get('bbox_area_cm2_median', 0.0)
|
||||
if med_area == 0.0 and (d, 'CC1') in curation_data:
|
||||
med_area = curation_data[(d, 'CC1')].get('median_bbox_area_cm2', 0.0)
|
||||
|
||||
# Highlight thinning / post-market (day >= 36)
|
||||
row_fill = post_market_fill if cycle_day >= 36 else (accent_fill if curr_row % 2 == 0 else PatternFill(fill_type=None))
|
||||
|
||||
ws1.cell(row=curr_row, column=1, value=cycle_day).alignment = Alignment(horizontal='center')
|
||||
ws1.cell(row=curr_row, column=2, value=d).alignment = Alignment(horizontal='center')
|
||||
|
||||
ws1.cell(row=curr_row, column=3, value=cc1_cnt).number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=4, value=cc2_cnt).number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=5, value=cc3_cnt).number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=6, value=cc4_cnt).number_format = "#,##0"
|
||||
|
||||
tot_count_cell = ws1.cell(row=curr_row, column=7, value=day_tot_count)
|
||||
tot_count_cell.font = bold_font
|
||||
tot_count_cell.number_format = "#,##0"
|
||||
|
||||
ws1.cell(row=curr_row, column=8, value=w1).number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=9, value=w2).number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=10, value=w3).number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=11, value=w4).number_format = "#,##0.0"
|
||||
|
||||
mean_w_cell = ws1.cell(row=curr_row, column=12, value=round(mean_w, 1))
|
||||
mean_w_cell.font = bold_font
|
||||
mean_w_cell.number_format = "#,##0.0"
|
||||
|
||||
ws1.cell(row=curr_row, column=13, value=round(dom_pred, 1)).number_format = "#,##0.0"
|
||||
|
||||
if man_w is not None:
|
||||
ws1.cell(row=curr_row, column=14, value=round(man_w, 1)).number_format = "#,##0.0"
|
||||
err_pct = ((mean_w - man_w) / man_w) if man_w > 0 else 0.0
|
||||
err_cell = ws1.cell(row=curr_row, column=15, value=err_pct)
|
||||
err_cell.number_format = "0.00%"
|
||||
else:
|
||||
ws1.cell(row=curr_row, column=14, value="-")
|
||||
ws1.cell(row=curr_row, column=15, value="-")
|
||||
|
||||
ws1.cell(row=curr_row, column=16, value=cur_samples).number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=17, value=mean_rej / 100.0).number_format = "0.0%"
|
||||
ws1.cell(row=curr_row, column=18, value=round(med_area, 2)).number_format = "#,##0.00"
|
||||
|
||||
for c_i in range(1, len(headers_s1) + 1):
|
||||
cell = ws1.cell(row=curr_row, column=c_i)
|
||||
cell.border = thin_border
|
||||
if row_fill.fill_type:
|
||||
cell.fill = row_fill
|
||||
|
||||
curr_row += 1
|
||||
|
||||
# Total / Average Row
|
||||
ws1.cell(row=curr_row, column=1, value="Total / Avg").font = total_font
|
||||
ws1.cell(row=curr_row, column=1).alignment = Alignment(horizontal='center')
|
||||
ws1.cell(row=curr_row, column=2, value=f"{len(unique_dates)} Days").font = total_font
|
||||
ws1.cell(row=curr_row, column=2).alignment = Alignment(horizontal='center')
|
||||
|
||||
ws1.cell(row=curr_row, column=3, value=f"=SUM(C10:C{curr_row-1})").number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=4, value=f"=SUM(D10:D{curr_row-1})").number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=5, value=f"=SUM(E10:E{curr_row-1})").number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=6, value=f"=SUM(F10:F{curr_row-1})").number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=7, value=f"=SUM(G10:G{curr_row-1})").number_format = "#,##0"
|
||||
|
||||
ws1.cell(row=curr_row, column=8, value=f"=AVERAGE(H10:H{curr_row-1})").number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=9, value=f"=AVERAGE(I10:I{curr_row-1})").number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=10, value=f"=AVERAGE(J10:J{curr_row-1})").number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=11, value=f"=AVERAGE(K10:K{curr_row-1})").number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=12, value=f"=AVERAGE(L10:L{curr_row-1})").number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=13, value=f"=AVERAGE(M10:M{curr_row-1})").number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=14, value=f"=AVERAGE(N10:N{curr_row-1})").number_format = "#,##0.0"
|
||||
ws1.cell(row=curr_row, column=15, value=f"=AVERAGE(O10:O{curr_row-1})").number_format = "0.00%"
|
||||
|
||||
ws1.cell(row=curr_row, column=16, value=f"=SUM(P10:P{curr_row-1})").number_format = "#,##0"
|
||||
ws1.cell(row=curr_row, column=17, value=f"=AVERAGE(Q10:Q{curr_row-1})").number_format = "0.0%"
|
||||
ws1.cell(row=curr_row, column=18, value=f"=AVERAGE(R10:R{curr_row-1})").number_format = "#,##0.00"
|
||||
|
||||
for c_i in range(1, len(headers_s1) + 1):
|
||||
cell = ws1.cell(row=curr_row, column=c_i)
|
||||
cell.font = total_font
|
||||
cell.fill = total_fill
|
||||
cell.border = top_thick_bottom_double
|
||||
|
||||
for col in ws1.columns:
|
||||
col_letter = get_column_letter(col[0].column)
|
||||
max_len = max(len(str(cell.value or '')) for cell in col)
|
||||
ws1.column_dimensions[col_letter].width = max(max_len + 3, 12)
|
||||
ws1.column_dimensions['A'].width = 11
|
||||
ws1.column_dimensions['B'].width = 13
|
||||
|
||||
# =========================================================================
|
||||
# SHEET 2: Growth Comparison & Analytics (FatChicken style)
|
||||
# =========================================================================
|
||||
ws2 = wb.create_sheet(title="Growth & Size Analytics")
|
||||
ws2.views.sheetView[0].showGridLines = True
|
||||
|
||||
ws2["A1"] = "Growth Analytics & Vision Weight Validation (Cycle 7)"
|
||||
ws2["A1"].font = Font(name=font_family, size=15, bold=True, color="1F4E78")
|
||||
ws2["A2"] = "Vision-predicted weight vs Farm Scale Ground Truth (manual_g) with Morphometric Geometric Indicators"
|
||||
ws2["A2"].font = Font(name=font_family, size=10, italic=True, color="595959")
|
||||
|
||||
headers_s2 = [
|
||||
"cycle_day", "date", "daily_chickens", "n_valid_samples",
|
||||
"bbox_area_cm2_median", "minor_axis_cm_median", "major_axis_cm_median",
|
||||
"manual_g", "vision_pred_g", "area_vs_day35_pct", "pct_err_vs_manual",
|
||||
"gompertz_baseline_g", "vision_gain_g", "dominant_camera"
|
||||
]
|
||||
|
||||
start_row_s2 = 5
|
||||
for c_idx, h in enumerate(headers_s2, 1):
|
||||
cell = ws2.cell(row=start_row_s2, column=c_idx, value=h)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center')
|
||||
|
||||
curr_row_s2 = start_row_s2 + 1
|
||||
day35_area = 11.5
|
||||
if "2026-06-26" in feat_data and feat_data["2026-06-26"].get("bbox_area_cm2_median"):
|
||||
day35_area = float(feat_data["2026-06-26"]["bbox_area_cm2_median"])
|
||||
|
||||
for d in unique_dates:
|
||||
c_day = int((pd.to_datetime(d) - pd.to_datetime("2026-05-22")).days)
|
||||
pred_entry = pred_data.get(d, {})
|
||||
feat_entry = feat_data.get(d, {})
|
||||
|
||||
tot_cnt = int(pivot_counts.loc[d].sum()) if d in pivot_counts.index else 0
|
||||
v_samples = pred_entry.get("n_valid_samples", 0)
|
||||
|
||||
area_med = feat_entry.get("bbox_area_cm2_median", 0.0)
|
||||
if area_med == 0.0 and (d, 'CC1') in curation_data:
|
||||
area_med = curation_data[(d, 'CC1')].get('median_bbox_area_cm2', 0.0)
|
||||
|
||||
w_med = feat_entry.get("width_cm_median", 0.0)
|
||||
h_med = feat_entry.get("height_cm_median", 0.0)
|
||||
|
||||
man_w = manual_weights.get(d, 0.0)
|
||||
v_pred = pred_entry.get("predicted_weight_g", 0.0)
|
||||
|
||||
gomp_b = pred_entry.get("gompertz_baseline_g", 0.0)
|
||||
v_gain = pred_entry.get("vision_gain_g", 0.0)
|
||||
dom_cam = pred_entry.get("dominant_camera", "CC1")
|
||||
|
||||
area_vs_d35 = ((area_med - day35_area) / day35_area) * 100.0 if day35_area > 0 else 0.0
|
||||
pct_err = ((v_pred - man_w) / man_w) * 100.0 if man_w > 0 else 0.0
|
||||
|
||||
r_fill = post_market_fill if c_day >= 36 else (accent_fill if curr_row_s2 % 2 == 0 else PatternFill(fill_type=None))
|
||||
|
||||
ws2.cell(row=curr_row_s2, column=1, value=c_day).alignment = Alignment(horizontal='center')
|
||||
ws2.cell(row=curr_row_s2, column=2, value=d).alignment = Alignment(horizontal='center')
|
||||
ws2.cell(row=curr_row_s2, column=3, value=tot_cnt).number_format = "#,##0"
|
||||
ws2.cell(row=curr_row_s2, column=4, value=v_samples).number_format = "#,##0"
|
||||
ws2.cell(row=curr_row_s2, column=5, value=round(area_med, 2)).number_format = "#,##0.00"
|
||||
ws2.cell(row=curr_row_s2, column=6, value=round(w_med, 2)).number_format = "#,##0.00"
|
||||
ws2.cell(row=curr_row_s2, column=7, value=round(h_med, 2)).number_format = "#,##0.00"
|
||||
ws2.cell(row=curr_row_s2, column=8, value=round(man_w, 1) if man_w else "-").number_format = "#,##0.0"
|
||||
ws2.cell(row=curr_row_s2, column=9, value=round(v_pred, 1)).number_format = "#,##0.0"
|
||||
ws2.cell(row=curr_row_s2, column=10, value=round(area_vs_d35, 2)).number_format = "0.00"
|
||||
ws2.cell(row=curr_row_s2, column=11, value=round(pct_err, 2)).number_format = "0.00"
|
||||
ws2.cell(row=curr_row_s2, column=12, value=round(gomp_b, 1)).number_format = "#,##0.0"
|
||||
ws2.cell(row=curr_row_s2, column=13, value=round(v_gain, 1)).number_format = "#,##0.0"
|
||||
ws2.cell(row=curr_row_s2, column=14, value=dom_cam).alignment = Alignment(horizontal='center')
|
||||
|
||||
for c_i in range(1, len(headers_s2) + 1):
|
||||
cell = ws2.cell(row=curr_row_s2, column=c_i)
|
||||
cell.border = thin_border
|
||||
if r_fill.fill_type:
|
||||
cell.fill = r_fill
|
||||
|
||||
curr_row_s2 += 1
|
||||
|
||||
for col in ws2.columns:
|
||||
col_letter = get_column_letter(col[0].column)
|
||||
max_len = max(len(str(cell.value or '')) for cell in col)
|
||||
ws2.column_dimensions[col_letter].width = max(max_len + 3, 13)
|
||||
|
||||
# =========================================================================
|
||||
# SHEET 3: Raw Batch Runs (All 196 Camera Runs)
|
||||
# =========================================================================
|
||||
ws3 = wb.create_sheet(title="Raw Batch Runs (196 Runs)")
|
||||
ws3.views.sheetView[0].showGridLines = True
|
||||
|
||||
headers_s3 = [
|
||||
"Run ID", "Date", "Cycle Day", "Location", "Camera ID",
|
||||
"Chickens Counted", "Estimated Weight (g)", "Valid Samples",
|
||||
"Outliers Discarded", "Rejection Rate (%)", "Median BBox Area (cm²)",
|
||||
"Frames Processed", "Elapsed (s)", "Stopped Reason", "Source Video", "Generated At"
|
||||
]
|
||||
|
||||
ws3.row_dimensions[1].height = 28
|
||||
for col_idx, h in enumerate(headers_s3, 1):
|
||||
cell = ws3.cell(row=1, column=col_idx, value=h)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
|
||||
|
||||
curr_row_s3 = 2
|
||||
for _, r in df_runs.iterrows():
|
||||
d_val = r['date']
|
||||
cam_val = r['camera_id']
|
||||
c_day = int((pd.to_datetime(d_val) - pd.to_datetime("2026-05-22")).days)
|
||||
|
||||
w_info = log_weights.get((d_val, cam_val), {})
|
||||
w_val = w_info.get("weight_g", 0.0)
|
||||
|
||||
cur_info = curation_data.get((d_val, cam_val), {})
|
||||
v_smp = cur_info.get("saved_rows", w_info.get("samples", 0))
|
||||
outliers = cur_info.get("outliers_discarded", 0)
|
||||
rej_r = cur_info.get("rejection_rate", w_info.get("rej_pct", 0.0)/100.0)
|
||||
med_area = cur_info.get("median_bbox_area_cm2", 0.0)
|
||||
|
||||
ws3.cell(row=curr_row_s3, column=1, value=int(r['id'])).alignment = Alignment(horizontal='center')
|
||||
ws3.cell(row=curr_row_s3, column=2, value=d_val).alignment = Alignment(horizontal='center')
|
||||
ws3.cell(row=curr_row_s3, column=3, value=c_day).alignment = Alignment(horizontal='center')
|
||||
ws3.cell(row=curr_row_s3, column=4, value=r['location']).alignment = Alignment(horizontal='center')
|
||||
ws3.cell(row=curr_row_s3, column=5, value=cam_val).alignment = Alignment(horizontal='center')
|
||||
|
||||
ws3.cell(row=curr_row_s3, column=6, value=int(r['total_entered'])).number_format = "#,##0"
|
||||
ws3.cell(row=curr_row_s3, column=7, value=round(w_val, 1)).number_format = "#,##0.0"
|
||||
ws3.cell(row=curr_row_s3, column=8, value=int(v_smp)).number_format = "#,##0"
|
||||
ws3.cell(row=curr_row_s3, column=9, value=int(outliers)).number_format = "#,##0"
|
||||
ws3.cell(row=curr_row_s3, column=10, value=rej_r).number_format = "0.0%"
|
||||
ws3.cell(row=curr_row_s3, column=11, value=round(med_area, 2)).number_format = "#,##0.00"
|
||||
|
||||
ws3.cell(row=curr_row_s3, column=12, value=int(r['frames_processed'])).number_format = "#,##0"
|
||||
ws3.cell(row=curr_row_s3, column=13, value=round(float(r['elapsed_seconds']), 1)).number_format = "#,##0.0"
|
||||
ws3.cell(row=curr_row_s3, column=14, value=r['stopped_reason']).alignment = Alignment(horizontal='center')
|
||||
ws3.cell(row=curr_row_s3, column=15, value=r['source_video'])
|
||||
ws3.cell(row=curr_row_s3, column=16, value=r['generated_at'])
|
||||
|
||||
for c_i in range(1, len(headers_s3) + 1):
|
||||
cell = ws3.cell(row=curr_row_s3, column=c_i)
|
||||
cell.border = thin_border
|
||||
if curr_row_s3 % 2 == 1:
|
||||
cell.fill = accent_fill
|
||||
|
||||
curr_row_s3 += 1
|
||||
|
||||
for col in ws3.columns:
|
||||
col_letter = get_column_letter(col[0].column)
|
||||
max_len = max(len(str(cell.value or '')) for cell in col)
|
||||
ws3.column_dimensions[col_letter].width = max(max_len + 3, 12)
|
||||
|
||||
# =========================================================================
|
||||
# SHEET 4: Legend & Methodology
|
||||
# =========================================================================
|
||||
ws4 = wb.create_sheet(title="Legend & Notes")
|
||||
ws4.views.sheetView[0].showGridLines = True
|
||||
|
||||
ws4["A1"] = "Chicken Counter - Report Metadata & Column Glossary"
|
||||
ws4["A1"].font = Font(name=font_family, size=15, bold=True, color="1F4E78")
|
||||
|
||||
notes = [
|
||||
("Term / Column", "Description & Interpretation"),
|
||||
("Cycle Day", "Broiler age in days, starting from Day 0 (arrival / DOC on 2026-05-22)."),
|
||||
("CC1 .. CC4 Count", "Number of validated chickens counted crossing the gate zone entering from each camera."),
|
||||
("Total Daily Count", "Sum of chickens entering across all 4 cameras on that date."),
|
||||
("CC1 .. CC4 Weight (g)", "Vision-estimated live chicken weight derived from camera-specific bounding box size calibration."),
|
||||
("Mean Weight (g)", "Arithmetic mean of the four cameras' estimated weights for that date."),
|
||||
("Dominant Pred (g)", "Estimated weight from the dominant camera stream (highest valid sample quality) with Gompertz growth correction."),
|
||||
("Manual Scale (g)", "Actual ground-truth weight recorded from physical scale samples in the coop."),
|
||||
("Error vs Manual (%)", "Relative estimation percentage error: (Vision Weight - Manual Weight) / Manual Weight * 100%."),
|
||||
("Post-Market / Thinning (Day >= 36)", "Highlighted in soft orange. Indicates selective harvesting / thinning period where larger birds are sold first, resulting in population weight plateau/dip."),
|
||||
("Rejection Rate (%)", "Percentage of detection tracks filtered out by MAD outlier filters (e.g. partial occlusions, multiple chickens merged in single bounding box)."),
|
||||
("Stopped Reason", "'backward' = Video stream automatically terminated early when backward motion detected (unloading completed); 'eof' = Reached end of video file.")
|
||||
]
|
||||
|
||||
for r_idx, (k, v) in enumerate(notes, 3):
|
||||
c1 = ws4.cell(row=r_idx, column=1, value=k)
|
||||
c2 = ws4.cell(row=r_idx, column=2, value=v)
|
||||
c1.border = thin_border
|
||||
c2.border = thin_border
|
||||
if r_idx == 3:
|
||||
c1.font = header_font
|
||||
c1.fill = header_fill
|
||||
c2.font = header_font
|
||||
c2.fill = header_fill
|
||||
else:
|
||||
c1.font = bold_font
|
||||
c1.fill = accent_fill
|
||||
c2.font = regular_font
|
||||
|
||||
ws4.column_dimensions['A'].width = 30
|
||||
ws4.column_dimensions['B'].width = 95
|
||||
|
||||
# Save Workbook
|
||||
wb.save(output_excel)
|
||||
print(f"✅ Full report generated successfully at: {output_excel}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
generate_report()
|
||||
@@ -75,6 +75,7 @@ polars-runtime-32==1.42.1
|
||||
protobuf==7.35.1
|
||||
psutil==7.2.2
|
||||
ptyprocess==0.7.0
|
||||
pyarrow>=15.0.0
|
||||
pycairo==1.20.1
|
||||
pycups==2.0.1
|
||||
Pygments==2.11.2
|
||||
|
||||
@@ -18,6 +18,56 @@ from chicken_counter.tracking import DetectionTracker
|
||||
from chicken_counter.types import CameraBatchResult, FrameResult, PipelineResult, TrackObservation
|
||||
|
||||
|
||||
def migrate_db_schema(conn) -> None:
|
||||
"""Ensure batch_runs table exists and has all required weight and dimensional columns."""
|
||||
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 '',
|
||||
cycle_day INTEGER NOT NULL DEFAULT 0,
|
||||
area_cm2_median REAL NOT NULL DEFAULT 0.0,
|
||||
minor_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
major_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
predicted_weight_g REAL NOT NULL DEFAULT 0.0,
|
||||
gompertz_baseline_g REAL NOT NULL DEFAULT 0.0,
|
||||
vision_gain_g REAL NOT NULL DEFAULT 0.0,
|
||||
n_weight_samples INTEGER NOT NULL DEFAULT 0,
|
||||
rejection_rate REAL NOT NULL DEFAULT 0.0,
|
||||
UNIQUE(date, location, camera_id))""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_date ON batch_runs (date)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_camera ON batch_runs (camera_id)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_location ON batch_runs (location)")
|
||||
|
||||
# Migration: add missing columns to existing tables
|
||||
cursor = conn.execute("PRAGMA table_info(batch_runs)")
|
||||
existing_cols = {row[1] for row in cursor.fetchall()}
|
||||
new_cols = [
|
||||
("cycle_day", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("area_cm2_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("minor_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("major_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("predicted_weight_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("gompertz_baseline_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("vision_gain_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("n_weight_samples", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("rejection_rate", "REAL NOT NULL DEFAULT 0.0"),
|
||||
]
|
||||
for col_name, col_type in new_cols:
|
||||
if col_name not in existing_cols:
|
||||
try:
|
||||
conn.execute(f"ALTER TABLE batch_runs ADD COLUMN {col_name} {col_type}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _store_to_db(report_path: Path, location: str, db_path: str) -> None:
|
||||
if not location or not db_path:
|
||||
return
|
||||
@@ -31,20 +81,7 @@ def _store_to_db(report_path: Path, location: str, db_path: str) -> None:
|
||||
|
||||
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))""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_date ON batch_runs (date)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_camera ON batch_runs (camera_id)")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_batch_location ON batch_runs (location)")
|
||||
migrate_db_schema(conn)
|
||||
|
||||
date = report["date"]
|
||||
for camera_id, entry in report["cameras"].items():
|
||||
@@ -295,6 +332,7 @@ def run_tensor_batched_daily_batch(
|
||||
f"report={report_path}"
|
||||
)
|
||||
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
|
||||
process_and_save_daily_weight_data(settings, camera_results, run_date, output_dir)
|
||||
return report_path
|
||||
|
||||
|
||||
@@ -553,9 +591,136 @@ def run_hybrid_daily_batch(
|
||||
f"report={report_path}"
|
||||
)
|
||||
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
|
||||
process_and_save_daily_weight_data(settings, camera_results, run_date, output_dir)
|
||||
return report_path
|
||||
|
||||
|
||||
def process_and_save_daily_weight_data(
|
||||
settings: BatchSettings,
|
||||
camera_results: list[CameraBatchResult],
|
||||
run_date: str,
|
||||
output_dir: Path,
|
||||
) -> None:
|
||||
"""Process per-camera curation, aggregated features, and weight predictions."""
|
||||
from chicken_counter.weight import (
|
||||
save_camera_detections,
|
||||
save_curation_summary,
|
||||
aggregate_camera_features,
|
||||
build_cage_day_features_and_predictions,
|
||||
save_cage_day_features,
|
||||
save_weight_predictions,
|
||||
)
|
||||
from datetime import date as date_type
|
||||
|
||||
# Calculate cycle_day (cycle_start_date is Day 0, weight counting starts at Day 1)
|
||||
cycle_day = 0
|
||||
if settings.batch.cycle_start_date:
|
||||
try:
|
||||
start_d = date_type.fromisoformat(str(settings.batch.cycle_start_date))
|
||||
run_d = date_type.fromisoformat(str(run_date))
|
||||
cycle_day = (run_d - start_d).days
|
||||
except Exception:
|
||||
cycle_day = 0
|
||||
|
||||
if cycle_day <= 0:
|
||||
print(f"\n[weight] ℹ️ Cycle Day 0 (DOC arrival date: {settings.batch.cycle_start_date}) — Weight counting starts at Cycle Day 1. Skipping weight estimation for {run_date}.\n")
|
||||
return
|
||||
|
||||
camera_aggregates: list[dict] = []
|
||||
for item in camera_results:
|
||||
if item.skipped or item.pipeline is None:
|
||||
continue
|
||||
cam_id = item.camera_id
|
||||
p_res = item.pipeline
|
||||
curated_rows = getattr(p_res, "curated_measurements", []) or []
|
||||
curation_stats = getattr(p_res, "curation_stats", {}) or {}
|
||||
|
||||
# Save per-camera detections parquet & curation summary JSON
|
||||
if curated_rows:
|
||||
save_camera_detections(curated_rows, output_dir, date=run_date, camera_id=cam_id)
|
||||
if curation_stats:
|
||||
save_curation_summary(curation_stats, output_dir, date=run_date, camera_id=cam_id)
|
||||
|
||||
# Compute camera aggregate
|
||||
cam_agg = aggregate_camera_features(
|
||||
curated_tracks=curated_rows,
|
||||
camera_id=cam_id,
|
||||
date=run_date,
|
||||
cycle_day=cycle_day,
|
||||
curation_stats=curation_stats,
|
||||
)
|
||||
camera_aggregates.append(cam_agg)
|
||||
|
||||
if not camera_aggregates:
|
||||
return
|
||||
|
||||
features_list, predictions_list = build_cage_day_features_and_predictions(
|
||||
camera_aggregates=camera_aggregates,
|
||||
date=run_date,
|
||||
cycle_day=cycle_day,
|
||||
)
|
||||
|
||||
if features_list:
|
||||
save_cage_day_features(features_list, output_dir)
|
||||
if predictions_list:
|
||||
save_weight_predictions(predictions_list, output_dir, date=run_date)
|
||||
|
||||
# Store weight predictions into SQLite database if configured
|
||||
if settings.batch.db_path and settings.batch.location:
|
||||
import sqlite3
|
||||
try:
|
||||
conn = sqlite3.connect(settings.batch.db_path, timeout=60.0)
|
||||
migrate_db_schema(conn)
|
||||
for pred in predictions_list:
|
||||
cid = pred["camera_id"]
|
||||
if cid == "FUSED":
|
||||
continue
|
||||
conn.execute("""UPDATE batch_runs SET
|
||||
cycle_day = ?,
|
||||
area_cm2_median = ?,
|
||||
minor_axis_cm_median = ?,
|
||||
major_axis_cm_median = ?,
|
||||
predicted_weight_g = ?,
|
||||
gompertz_baseline_g = ?,
|
||||
vision_gain_g = ?,
|
||||
n_weight_samples = ?,
|
||||
rejection_rate = ?
|
||||
WHERE date = ? AND location = ? AND camera_id = ?""",
|
||||
(
|
||||
pred.get("cycle_day", cycle_day),
|
||||
pred.get("area_cm2_median", 0.0),
|
||||
pred.get("minor_axis_cm_median", 0.0),
|
||||
pred.get("major_axis_cm_median", 0.0),
|
||||
pred.get("predicted_weight_g", 0.0),
|
||||
pred.get("gompertz_baseline_g", 0.0),
|
||||
pred.get("vision_gain_g", 0.0),
|
||||
pred.get("n_valid_samples", 0),
|
||||
pred.get("rejection_rate", 0.0),
|
||||
run_date,
|
||||
settings.batch.location,
|
||||
cid,
|
||||
))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"[db] updated weight metrics for {run_date} ({settings.batch.location}) in {settings.batch.db_path}")
|
||||
except Exception as e:
|
||||
print(f"[db] ⚠️ Warning: Failed updating weight metrics in db ({e})")
|
||||
|
||||
# Print clean terminal summary
|
||||
print(f"\n[weight] ⚖️ Weight & Growth Estimation Summary for {run_date} (Cycle Day {cycle_day}):")
|
||||
for pred in predictions_list:
|
||||
cid = pred["camera_id"]
|
||||
w = pred["predicted_weight_g"]
|
||||
samples = pred["n_valid_samples"]
|
||||
gain = pred["vision_gain_g"]
|
||||
gain_sign = "+" if gain >= 0 else ""
|
||||
if cid == "FUSED":
|
||||
print(f" ⭐ FUSED Overall : {w:.1f} g (samples: {samples}, baseline: {pred['gompertz_baseline_g']:.1f} g, vision: {gain_sign}{gain:.1f} g)")
|
||||
else:
|
||||
print(f" - Camera {cid:6s} : {w:.1f} g (samples: {samples}, rejection: {pred['rejection_rate']*100:.1f}%)")
|
||||
print()
|
||||
|
||||
|
||||
def run_daily_batch(
|
||||
settings: BatchSettings,
|
||||
date: str | None = None,
|
||||
@@ -687,6 +852,7 @@ def run_daily_batch(
|
||||
f"report={report_path}"
|
||||
)
|
||||
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
|
||||
process_and_save_daily_weight_data(settings, camera_results, run_date, output_dir)
|
||||
return report_path
|
||||
|
||||
print("[batch] all cameras complete; starting compression")
|
||||
@@ -716,4 +882,5 @@ def run_daily_batch(
|
||||
f"report={report_path}"
|
||||
)
|
||||
_store_to_db(report_path, settings.batch.location, settings.batch.db_path)
|
||||
process_and_save_daily_weight_data(settings, camera_results, run_date, output_dir)
|
||||
return report_path
|
||||
@@ -205,6 +205,9 @@ class FeedbackConfig:
|
||||
log_to_terminal: bool = True
|
||||
|
||||
|
||||
from chicken_counter.weight.calibration import CalibrationConfig
|
||||
|
||||
|
||||
@dataclass
|
||||
class CameraConfig:
|
||||
camera_id: str
|
||||
@@ -220,6 +223,7 @@ class CameraConfig:
|
||||
feedback: FeedbackConfig
|
||||
detection_zone: DetectionZoneConfig = field(default_factory=DetectionZoneConfig)
|
||||
stream: StreamConfig = field(default_factory=StreamConfig)
|
||||
calibration: CalibrationConfig = field(default_factory=CalibrationConfig)
|
||||
config_path: str | None = None
|
||||
|
||||
|
||||
@@ -318,6 +322,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", {})),
|
||||
calibration=CalibrationConfig.from_dict(raw.get("calibration")),
|
||||
config_path=raw.get("config_path"),
|
||||
)
|
||||
|
||||
|
||||
@@ -126,6 +126,7 @@ class CountingZone:
|
||||
frame_index=frame_index,
|
||||
total_entered_after_event=self.total_entered_count,
|
||||
sequence_number=self.sequence_numbers_by_track_id[track.track_id],
|
||||
observation=track,
|
||||
)
|
||||
)
|
||||
if self.verbose:
|
||||
|
||||
@@ -189,6 +189,7 @@ def run_pipeline(
|
||||
last_tracks: list[TrackObservation] = []
|
||||
stopped_reason = "eof"
|
||||
user_quit = False
|
||||
track_measurements: list[dict] = []
|
||||
verbose = config.performance.verbose
|
||||
cumulative_timings: dict[str, float] = {"read": 0.0, "infer": 0.0, "motion": 0.0, "count": 0.0, "overlay": 0.0, "write": 0.0}
|
||||
timed_frames = 0
|
||||
@@ -230,6 +231,38 @@ def run_pipeline(
|
||||
counting_paused=motion_state.backward_active,
|
||||
)
|
||||
|
||||
if count_events:
|
||||
from chicken_counter.weight import compute_metric_bbox
|
||||
px_per_cm = getattr(config.calibration, "px_per_cm", 20.0) if hasattr(config, "calibration") else 20.0
|
||||
for event in count_events:
|
||||
obs = event.observation
|
||||
if obs is not None:
|
||||
x1, y1, x2, y2 = [float(v) for v in obs.bbox_xyxy]
|
||||
cx, cy = float(obs.centroid[0]), float(obs.centroid[1])
|
||||
metric = compute_metric_bbox(obs.bbox_xyxy, obs.centroid, px_per_cm=px_per_cm)
|
||||
track_measurements.append({
|
||||
"date": str(run_date),
|
||||
"camera_id": str(config.camera_id),
|
||||
"track_id": int(event.track_id),
|
||||
"class_id": int(obs.class_id),
|
||||
"confidence": round(float(obs.confidence), 4),
|
||||
"frame_index": int(event.frame_index),
|
||||
"bbox_x1": x1,
|
||||
"bbox_y1": y1,
|
||||
"bbox_x2": x2,
|
||||
"bbox_y2": y2,
|
||||
"centroid_x": cx,
|
||||
"centroid_y": cy,
|
||||
"px_per_cm": metric["px_per_cm"],
|
||||
"bbox_area_cm2": metric["bbox_area_cm2"],
|
||||
"width_cm": metric["width_cm"],
|
||||
"height_cm": metric["height_cm"],
|
||||
"aspect_ratio_cm": metric["aspect_ratio_cm"],
|
||||
"centroid_x_cm": metric["centroid_x_cm"],
|
||||
"centroid_y_cm": metric["centroid_y_cm"],
|
||||
"perimeter_cm": metric["perimeter_cm"],
|
||||
})
|
||||
|
||||
if verbose:
|
||||
t_count = time.monotonic()
|
||||
|
||||
@@ -335,6 +368,13 @@ def run_pipeline(
|
||||
if progress is not None:
|
||||
progress.finish()
|
||||
|
||||
# FatChicken Track Curation & Outlier Elimination
|
||||
from chicken_counter.weight import curate_track_observations
|
||||
curated_measurements, curation_stats = curate_track_observations(
|
||||
track_measurements,
|
||||
cycle_day=getattr(config, "_cycle_day", 0),
|
||||
)
|
||||
|
||||
return PipelineResult(
|
||||
camera_id=config.camera_id,
|
||||
total_entered_count=artifacts.counting_zone.total_entered_count,
|
||||
@@ -343,6 +383,9 @@ def run_pipeline(
|
||||
vis_video_path=config.display.output_path,
|
||||
source_video=str(config.source),
|
||||
elapsed_seconds=elapsed_seconds,
|
||||
track_measurements=track_measurements,
|
||||
curated_measurements=curated_measurements,
|
||||
curation_stats=curation_stats,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ class CountEvent:
|
||||
frame_index: int
|
||||
total_entered_after_event: int
|
||||
sequence_number: int
|
||||
observation: TrackObservation | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -52,6 +53,9 @@ class PipelineResult:
|
||||
vis_video_path: str | None
|
||||
source_video: str
|
||||
elapsed_seconds: float
|
||||
track_measurements: list[dict[str, Any]] = field(default_factory=list)
|
||||
curated_measurements: list[dict[str, Any]] = field(default_factory=list)
|
||||
curation_stats: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -62,6 +66,7 @@ class CameraBatchResult:
|
||||
skip_reason: str | None = None
|
||||
compressed_video_path: str | None = None
|
||||
compressed_size_mb: float | None = None
|
||||
curation_stats: dict[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Chicken weight estimation, curation, aggregation, and measurement storage module."""
|
||||
|
||||
from chicken_counter.weight.calibration import CalibrationConfig, compute_metric_bbox
|
||||
from chicken_counter.weight.growth_model import (
|
||||
STANDARD_BROILER_WEIGHT_TABLE,
|
||||
gompertz_baseline_weight,
|
||||
predict_chicken_weight,
|
||||
)
|
||||
from chicken_counter.weight.curation import (
|
||||
curate_track_observations,
|
||||
get_mad_zscore_threshold,
|
||||
)
|
||||
from chicken_counter.weight.aggregation import (
|
||||
aggregate_camera_features,
|
||||
build_cage_day_features_and_predictions,
|
||||
)
|
||||
from chicken_counter.weight.storage import (
|
||||
save_camera_detections,
|
||||
save_curation_summary,
|
||||
save_cage_day_features,
|
||||
save_weight_predictions,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CalibrationConfig",
|
||||
"compute_metric_bbox",
|
||||
"STANDARD_BROILER_WEIGHT_TABLE",
|
||||
"gompertz_baseline_weight",
|
||||
"predict_chicken_weight",
|
||||
"curate_track_observations",
|
||||
"get_mad_zscore_threshold",
|
||||
"aggregate_camera_features",
|
||||
"build_cage_day_features_and_predictions",
|
||||
"save_camera_detections",
|
||||
"save_curation_summary",
|
||||
"save_cage_day_features",
|
||||
"save_weight_predictions",
|
||||
]
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Statistical aggregation of metric features and multi-camera weight prediction."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
import numpy as np
|
||||
|
||||
from chicken_counter.weight.growth_model import predict_chicken_weight
|
||||
|
||||
|
||||
FEATURE_COLUMNS = ["bbox_area_cm2", "width_cm", "height_cm", "minor_axis_cm", "major_axis_cm", "aspect_ratio_cm", "perimeter_cm"]
|
||||
|
||||
|
||||
def compute_feature_distribution(values: np.ndarray | list[float], prefix: str = "") -> dict[str, float]:
|
||||
"""Compute distribution statistics (mean, median, p25, p75, std, cv, iqr) for a metric feature."""
|
||||
arr = np.array(values, dtype=np.float64)
|
||||
if len(arr) == 0:
|
||||
return {
|
||||
f"{prefix}mean": 0.0,
|
||||
f"{prefix}median": 0.0,
|
||||
f"{prefix}p25": 0.0,
|
||||
f"{prefix}p75": 0.0,
|
||||
f"{prefix}std": 0.0,
|
||||
f"{prefix}cv": 0.0,
|
||||
f"{prefix}iqr": 0.0,
|
||||
}
|
||||
|
||||
mean_v = float(np.mean(arr))
|
||||
median_v = float(np.median(arr))
|
||||
p25_v = float(np.percentile(arr, 25))
|
||||
p75_v = float(np.percentile(arr, 75))
|
||||
std_v = float(np.std(arr))
|
||||
cv_v = (std_v / mean_v) if mean_v > 1e-4 else 0.0
|
||||
iqr_v = p75_v - p25_v
|
||||
|
||||
return {
|
||||
f"{prefix}mean": round(mean_v, 4),
|
||||
f"{prefix}median": round(median_v, 4),
|
||||
f"{prefix}p25": round(p25_v, 4),
|
||||
f"{prefix}p75": round(p75_v, 4),
|
||||
f"{prefix}std": round(std_v, 4),
|
||||
f"{prefix}cv": round(cv_v, 4),
|
||||
f"{prefix}iqr": round(iqr_v, 4),
|
||||
}
|
||||
|
||||
|
||||
def aggregate_camera_features(
|
||||
curated_tracks: list[dict[str, Any]],
|
||||
camera_id: str,
|
||||
date: str,
|
||||
cycle_day: int,
|
||||
curation_stats: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Calculate aggregated distribution metrics for one camera on a given day."""
|
||||
stats = curation_stats or {}
|
||||
n_valid = len(curated_tracks)
|
||||
raw_tracks_count = stats.get("raw_tracks", n_valid)
|
||||
rejection_rate = stats.get("rejection_rate", 0.0)
|
||||
|
||||
confs = [float(r.get("confidence", 0.0)) for r in curated_tracks]
|
||||
mean_conf = float(np.mean(confs)) if confs else 0.0
|
||||
unique_tracks = len(set(r.get("track_id") for r in curated_tracks if "track_id" in r))
|
||||
|
||||
row: dict[str, Any] = {
|
||||
"date": str(date),
|
||||
"cycle_day": int(cycle_day),
|
||||
"camera_id": str(camera_id),
|
||||
"detection_count": raw_tracks_count,
|
||||
"unique_track_ids": unique_tracks,
|
||||
"n_valid_samples": n_valid,
|
||||
"mean_confidence": round(mean_conf, 4),
|
||||
"rejection_rate": round(rejection_rate, 4),
|
||||
"mask_usage_ratio": 0.0, # Strict bbox-only detection
|
||||
}
|
||||
|
||||
for feat in FEATURE_COLUMNS:
|
||||
vals = [float(r.get(feat, 0.0)) for r in curated_tracks]
|
||||
dist = compute_feature_distribution(vals, prefix=f"{feat}_")
|
||||
row.update(dist)
|
||||
|
||||
return row
|
||||
|
||||
|
||||
def build_cage_day_features_and_predictions(
|
||||
camera_aggregates: list[dict[str, Any]],
|
||||
date: str,
|
||||
cycle_day: int,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""Build multi-camera feature rows (including FUSED row) and generate weight predictions.
|
||||
|
||||
Returns:
|
||||
(cage_day_features_list, predictions_list)
|
||||
"""
|
||||
if not camera_aggregates:
|
||||
return [], []
|
||||
|
||||
features_list = list(camera_aggregates)
|
||||
|
||||
# Multi-camera Fused Row (weighted by detection_count / n_valid_samples)
|
||||
if len(camera_aggregates) > 1:
|
||||
total_samples = sum(r["n_valid_samples"] for r in camera_aggregates)
|
||||
total_detections = sum(r["detection_count"] for r in camera_aggregates)
|
||||
total_unique = sum(r["unique_track_ids"] for r in camera_aggregates)
|
||||
|
||||
fused_row: dict[str, Any] = {
|
||||
"date": str(date),
|
||||
"cycle_day": int(cycle_day),
|
||||
"camera_id": "FUSED",
|
||||
"detection_count": total_detections,
|
||||
"unique_track_ids": total_unique,
|
||||
"n_valid_samples": total_samples,
|
||||
"mean_confidence": 0.0,
|
||||
"rejection_rate": 0.0,
|
||||
"mask_usage_ratio": 0.0,
|
||||
}
|
||||
|
||||
weights = np.array([max(1, r["n_valid_samples"]) for r in camera_aggregates], dtype=np.float64)
|
||||
weights /= weights.sum()
|
||||
|
||||
fused_row["mean_confidence"] = round(float(sum(r["mean_confidence"] * w for r, w in zip(camera_aggregates, weights))), 4)
|
||||
fused_row["rejection_rate"] = round(float(sum(r["rejection_rate"] * w for r, w in zip(camera_aggregates, weights))), 4)
|
||||
|
||||
# Compute weighted averages for each stat field
|
||||
for key in camera_aggregates[0].keys():
|
||||
if any(key.startswith(f"{feat}_") for feat in FEATURE_COLUMNS):
|
||||
vals = [r.get(key, 0.0) for r in camera_aggregates]
|
||||
fused_row[key] = round(float(sum(v * w for v, w in zip(vals, weights))), 4)
|
||||
|
||||
features_list.append(fused_row)
|
||||
|
||||
# Dominant camera (highest valid sample count)
|
||||
dominant_cam = max(camera_aggregates, key=lambda r: r["n_valid_samples"])["camera_id"]
|
||||
|
||||
# Generate Weight Predictions for each camera and FUSED
|
||||
predictions_list: list[dict[str, Any]] = []
|
||||
for feat_row in features_list:
|
||||
cam_id = feat_row["camera_id"]
|
||||
median_area = feat_row.get("bbox_area_cm2_median", 0.0)
|
||||
mean_area = feat_row.get("bbox_area_cm2_mean", 0.0)
|
||||
minor_median = feat_row.get("minor_axis_cm_median", 0.0)
|
||||
major_median = feat_row.get("major_axis_cm_median", 0.0)
|
||||
n_samples = feat_row.get("n_valid_samples", 0)
|
||||
rej_rate = feat_row.get("rejection_rate", 0.0)
|
||||
|
||||
pred_res = predict_chicken_weight(
|
||||
cycle_day=cycle_day,
|
||||
median_bbox_area_cm2=median_area,
|
||||
mean_bbox_area_cm2=mean_area,
|
||||
)
|
||||
|
||||
pred_record = {
|
||||
"date": str(date),
|
||||
"camera_id": str(cam_id),
|
||||
"cycle_day": int(cycle_day),
|
||||
"area_cm2_median": float(median_area),
|
||||
"minor_axis_cm_median": float(minor_median),
|
||||
"major_axis_cm_median": float(major_median),
|
||||
"predicted_weight_g": pred_res["predicted_weight_g"],
|
||||
"doc_weight_g": pred_res["doc_weight_g"],
|
||||
"gompertz_baseline_g": pred_res["gompertz_baseline_g"],
|
||||
"vision_gain_g": pred_res["vision_gain_g"],
|
||||
"residual_g": pred_res["residual_g"],
|
||||
"n_valid_samples": n_samples,
|
||||
"dominant_camera": dominant_cam,
|
||||
"rejection_rate": rej_rate,
|
||||
}
|
||||
predictions_list.append(pred_record)
|
||||
|
||||
return features_list, predictions_list
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Camera calibration and metric centimeter conversion for chicken bounding boxes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class CalibrationConfig:
|
||||
"""Camera calibration configuration for pixel to centimeter mapping."""
|
||||
|
||||
px_per_cm: float = 20.0
|
||||
homography_matrix: list[list[float]] | None = None
|
||||
reference_object_cm: float | None = None
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any] | None) -> CalibrationConfig:
|
||||
if not data:
|
||||
return cls()
|
||||
return cls(
|
||||
px_per_cm=float(data.get("px_per_cm", 20.0)),
|
||||
homography_matrix=data.get("homography_matrix"),
|
||||
reference_object_cm=float(data["reference_object_cm"]) if "reference_object_cm" in data and data["reference_object_cm"] is not None else None,
|
||||
)
|
||||
|
||||
|
||||
def compute_metric_bbox(
|
||||
bbox_xyxy: tuple[int | float, int | float, int | float, int | float],
|
||||
centroid: tuple[int | float, int | float] | None = None,
|
||||
px_per_cm: float = 20.0,
|
||||
) -> dict[str, float]:
|
||||
"""Convert pixel bounding box and centroid to physical centimeter measurements.
|
||||
|
||||
Returns:
|
||||
dict containing:
|
||||
- px_per_cm: pixel to cm ratio used
|
||||
- bbox_area_cm2: bounding box area in square centimeters
|
||||
- width_cm: bbox width in centimeters
|
||||
- height_cm: bbox height in centimeters
|
||||
- aspect_ratio_cm: width / height ratio
|
||||
- centroid_x_cm, centroid_y_cm: centroid position in centimeters
|
||||
- minor_axis_cm: minor axis / width in centimeters (min(width_cm, height_cm))
|
||||
- major_axis_cm: major axis / length in centimeters (max(width_cm, height_cm))
|
||||
- perimeter_cm: perimeter in centimeters (2 * (width + height))
|
||||
"""
|
||||
scale = max(1e-4, float(px_per_cm))
|
||||
x1, y1, x2, y2 = [float(v) for v in bbox_xyxy]
|
||||
width_px = max(0.0, x2 - x1)
|
||||
height_px = max(0.0, y2 - y1)
|
||||
|
||||
if centroid is not None:
|
||||
cx_px, cy_px = float(centroid[0]), float(centroid[1])
|
||||
else:
|
||||
cx_px = x1 + width_px / 2.0
|
||||
cy_px = y1 + height_px / 2.0
|
||||
|
||||
width_cm = width_px / scale
|
||||
height_cm = height_px / scale
|
||||
bbox_area_cm2 = width_cm * height_cm
|
||||
aspect_ratio_cm = (width_cm / height_cm) if height_cm > 1e-4 else 1.0
|
||||
minor_axis_cm = min(width_cm, height_cm)
|
||||
major_axis_cm = max(width_cm, height_cm)
|
||||
centroid_x_cm = cx_px / scale
|
||||
centroid_y_cm = cy_px / scale
|
||||
perimeter_cm = 2.0 * (width_cm + height_cm)
|
||||
|
||||
return {
|
||||
"px_per_cm": round(scale, 4),
|
||||
"bbox_area_cm2": round(bbox_area_cm2, 4),
|
||||
"width_cm": round(width_cm, 4),
|
||||
"height_cm": round(height_cm, 4),
|
||||
"minor_axis_cm": round(minor_axis_cm, 4),
|
||||
"major_axis_cm": round(major_axis_cm, 4),
|
||||
"aspect_ratio_cm": round(aspect_ratio_cm, 4),
|
||||
"centroid_x_cm": round(centroid_x_cm, 4),
|
||||
"centroid_y_cm": round(centroid_y_cm, 4),
|
||||
"perimeter_cm": round(perimeter_cm, 4),
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Track observation curation and MAD z-score outlier elimination (FatChicken method)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
import numpy as np
|
||||
|
||||
|
||||
def get_mad_zscore_threshold(cycle_day: int) -> float:
|
||||
"""Return MAD z-score outlier cutoff threshold according to chicken age phase.
|
||||
|
||||
- cycle_day <= 10: 3.0 (high variance in young fast DOC batches)
|
||||
- cycle_day 11..24: 2.5 (mid-growth stabilization)
|
||||
- cycle_day > 24: 2.0 (mature uniform flock)
|
||||
"""
|
||||
day = int(cycle_day)
|
||||
if day <= 10:
|
||||
return 3.0
|
||||
elif day <= 24:
|
||||
return 2.5
|
||||
else:
|
||||
return 2.0
|
||||
|
||||
|
||||
def curate_track_observations(
|
||||
raw_tracks: list[dict[str, Any]],
|
||||
cycle_day: int = 0,
|
||||
min_samples_for_outlier_filtering: int = 30,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""Curate raw per-track observations before statistical aggregation.
|
||||
|
||||
Steps:
|
||||
1. Deduplication per track_id: Exactly one row per track_id (best observation by confidence).
|
||||
2. Outlier elimination via MAD z-score on bbox_area_cm2:
|
||||
- z = 0.6745 * (x - median) / MAD
|
||||
- Discard row if |z| > threshold (based on cycle_day)
|
||||
- Active only if number of samples >= 30
|
||||
3. Generate curation summary statistics.
|
||||
|
||||
Returns:
|
||||
(curated_rows, curation_stats_dict)
|
||||
"""
|
||||
if not raw_tracks:
|
||||
empty_stats = {
|
||||
"raw_tracks": 0,
|
||||
"validated_tracks": 0,
|
||||
"saved_rows": 0,
|
||||
"outliers_discarded": 0,
|
||||
"rejection_rate": 0.0,
|
||||
"median_bbox_area_cm2": 0.0,
|
||||
"cycle_day": int(cycle_day),
|
||||
"mad_threshold": get_mad_zscore_threshold(cycle_day),
|
||||
"outlier_filter_active": False,
|
||||
}
|
||||
return [], empty_stats
|
||||
|
||||
# Step 1: Deduplication per track_id (keep highest confidence observation)
|
||||
best_by_track: dict[int, dict[str, Any]] = {}
|
||||
for row in raw_tracks:
|
||||
tid = int(row.get("track_id", 0))
|
||||
conf = float(row.get("confidence", 0.0))
|
||||
if tid not in best_by_track or conf > float(best_by_track[tid].get("confidence", 0.0)):
|
||||
best_by_track[tid] = row
|
||||
|
||||
deduped_rows = sorted(best_by_track.values(), key=lambda r: int(r.get("frame_index", 0)))
|
||||
total_deduped = len(deduped_rows)
|
||||
|
||||
# Step 2: MAD Z-score Outlier Elimination on bbox_area_cm2
|
||||
threshold = get_mad_zscore_threshold(cycle_day)
|
||||
outlier_filter_active = total_deduped >= min_samples_for_outlier_filtering
|
||||
|
||||
areas = np.array([float(r.get("bbox_area_cm2", 0.0)) for r in deduped_rows], dtype=np.float64)
|
||||
raw_median_area = float(np.median(areas)) if len(areas) > 0 else 0.0
|
||||
|
||||
curated_rows: list[dict[str, Any]] = []
|
||||
outliers_discarded = 0
|
||||
|
||||
if outlier_filter_active and len(areas) > 0:
|
||||
median_val = np.median(areas)
|
||||
abs_diffs = np.abs(areas - median_val)
|
||||
mad = float(np.median(abs_diffs))
|
||||
|
||||
# Fallback if MAD is zero to avoid division by zero
|
||||
if mad < 1e-4:
|
||||
std_val = float(np.std(areas))
|
||||
mad = std_val * 0.6745 if std_val > 1e-4 else 1.0
|
||||
|
||||
for row, area in zip(deduped_rows, areas):
|
||||
z_score = 0.6745 * (area - median_val) / mad
|
||||
row["mad_zscore"] = round(float(z_score), 4)
|
||||
if abs(z_score) <= threshold:
|
||||
curated_rows.append(row)
|
||||
else:
|
||||
outliers_discarded += 1
|
||||
else:
|
||||
for row in deduped_rows:
|
||||
row["mad_zscore"] = 0.0
|
||||
curated_rows.append(row)
|
||||
|
||||
rejection_rate = float(outliers_discarded) / max(1, total_deduped)
|
||||
|
||||
camera_id = str(raw_tracks[0].get("camera_id", "")) if raw_tracks else ""
|
||||
date_str = str(raw_tracks[0].get("date", "")) if raw_tracks else ""
|
||||
|
||||
curation_stats = {
|
||||
"date": date_str,
|
||||
"camera_id": camera_id,
|
||||
"cycle_day": int(cycle_day),
|
||||
"raw_tracks": len(raw_tracks),
|
||||
"validated_tracks": len(best_by_track),
|
||||
"saved_rows": len(curated_rows),
|
||||
"outliers_discarded": outliers_discarded,
|
||||
"rejection_rate": round(rejection_rate, 4),
|
||||
"median_bbox_area_cm2": round(raw_median_area, 2),
|
||||
"mad_threshold": threshold,
|
||||
"outlier_filter_active": outlier_filter_active,
|
||||
}
|
||||
|
||||
return curated_rows, curation_stats
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Standard broiler growth curve (Gompertz) and vision-based weight estimation models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
# Standard daily reference table (Ross 308 / Cobb 500 average daily body weights in grams)
|
||||
STANDARD_BROILER_WEIGHT_TABLE: dict[int, float] = {
|
||||
0: 42.0, 1: 56.0, 2: 72.0, 3: 92.0, 4: 116.0, 5: 144.0, 6: 176.0, 7: 212.0,
|
||||
8: 252.0, 9: 298.0, 10: 348.0, 11: 404.0, 12: 466.0, 13: 534.0, 14: 608.0,
|
||||
15: 688.0, 16: 774.0, 17: 866.0, 18: 964.0, 19: 1068.0, 20: 1178.0, 21: 1294.0,
|
||||
22: 1416.0, 23: 1544.0, 24: 1678.0, 25: 1818.0, 26: 1964.0, 27: 2116.0, 28: 2274.0,
|
||||
29: 2438.0, 30: 2608.0, 31: 2784.0, 32: 2966.0, 33: 3154.0, 34: 3348.0, 35: 3548.0,
|
||||
36: 3752.0, 37: 3960.0, 38: 4172.0, 39: 4386.0, 40: 4602.0, 41: 4820.0, 42: 5040.0,
|
||||
}
|
||||
|
||||
|
||||
def gompertz_baseline_weight(
|
||||
cycle_day: int,
|
||||
w_max: float = 4650.0,
|
||||
k: float = 0.076,
|
||||
t_i: float = 25.8,
|
||||
) -> float:
|
||||
"""Calculate theoretical age-based Gompertz baseline body weight in grams.
|
||||
|
||||
Formula: W(t) = W_max * exp( -exp( -k * (t - t_i) ) )
|
||||
"""
|
||||
day = max(0, int(cycle_day))
|
||||
if day in STANDARD_BROILER_WEIGHT_TABLE:
|
||||
return STANDARD_BROILER_WEIGHT_TABLE[day]
|
||||
|
||||
# Standard Gompertz extrapolation for unlisted days
|
||||
val = w_max * math.exp(-math.exp(-k * (day - t_i)))
|
||||
return max(42.0, round(val, 1))
|
||||
|
||||
|
||||
def predict_chicken_weight(
|
||||
cycle_day: int,
|
||||
median_bbox_area_cm2: float,
|
||||
mean_bbox_area_cm2: float | None = None,
|
||||
doc_weight_g: float = 42.0,
|
||||
) -> dict[str, float]:
|
||||
"""Predict chicken body weight combining age baseline and vision bounding-box allometry.
|
||||
|
||||
Returns:
|
||||
dict containing:
|
||||
- predicted_weight_g: Final audited prediction in grams
|
||||
- doc_weight_g: Day 0 base weight in grams
|
||||
- gompertz_baseline_g: Age-expected curve baseline in grams
|
||||
- vision_gain_g: Vision-derived gain/residual correction in grams
|
||||
- residual_g: Same as vision_gain_g
|
||||
"""
|
||||
day = max(0, int(cycle_day))
|
||||
baseline = gompertz_baseline_weight(day)
|
||||
|
||||
area = max(1.0, float(median_bbox_area_cm2))
|
||||
|
||||
# Allometric 2D projected bounding box area to 3D volume/weight model:
|
||||
# Typical broiler density ~0.95 g/cm3.
|
||||
# W_vision = c * (Area)^1.45 calibrated across broiler growth stages.
|
||||
# For day 0 DOC (area ~25 cm2) -> ~42-50g. For day 28 (area ~320 cm2) -> ~2200g.
|
||||
vision_weight_estimate = 0.285 * math.pow(area, 1.52)
|
||||
|
||||
# Adaptive blending: Early cycle weights heavily bounded by age, mid/late cycle incorporates vision gain
|
||||
if day <= 5:
|
||||
alpha = 0.20
|
||||
elif day <= 15:
|
||||
alpha = 0.45
|
||||
else:
|
||||
alpha = 0.65
|
||||
|
||||
predicted = (1.0 - alpha) * baseline + alpha * vision_weight_estimate
|
||||
vision_gain = predicted - baseline
|
||||
|
||||
return {
|
||||
"predicted_weight_g": round(predicted, 1),
|
||||
"doc_weight_g": round(doc_weight_g, 1),
|
||||
"gompertz_baseline_g": round(baseline, 1),
|
||||
"vision_gain_g": round(vision_gain, 1),
|
||||
"residual_g": round(vision_gain, 1),
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Storage and export handlers for detection tracks, curation summaries, features, and weight predictions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def save_dataframe_parquet_and_csv(df: pd.DataFrame, base_path: Path) -> tuple[Path, Path]:
|
||||
"""Save a pandas DataFrame as Parquet with a CSV fallback alongside it."""
|
||||
base_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
parquet_path = base_path.with_suffix(".parquet")
|
||||
csv_path = base_path.with_suffix(".csv")
|
||||
|
||||
# 1. Save CSV
|
||||
df.to_csv(csv_path, index=False)
|
||||
|
||||
# 2. Save Parquet
|
||||
try:
|
||||
df.to_parquet(parquet_path, index=False, engine="pyarrow")
|
||||
except Exception as e:
|
||||
print(f"[weight-storage] ⚠️ Warning: Failed writing parquet ({e}), CSV saved to: {csv_path}")
|
||||
|
||||
return parquet_path, csv_path
|
||||
|
||||
|
||||
def save_camera_detections(
|
||||
curated_tracks: list[dict[str, Any]],
|
||||
output_dir: Path | str,
|
||||
date: str,
|
||||
camera_id: str,
|
||||
) -> tuple[Path, Path]:
|
||||
"""Save per-track detection observations to detections_{date}_{camera_id}.parquet & .csv."""
|
||||
out_dir = Path(output_dir)
|
||||
df = pd.DataFrame(curated_tracks)
|
||||
base_path = out_dir / f"detections_{date}_{camera_id}"
|
||||
return save_dataframe_parquet_and_csv(df, base_path)
|
||||
|
||||
|
||||
def save_curation_summary(
|
||||
curation_stats: dict[str, Any],
|
||||
output_dir: Path | str,
|
||||
date: str,
|
||||
camera_id: str,
|
||||
) -> Path:
|
||||
"""Save curation summary JSON to curation_{date}_{camera_id}.json."""
|
||||
out_dir = Path(output_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
json_path = out_dir / f"curation_{date}_{camera_id}.json"
|
||||
with open(json_path, "w", encoding="utf-8") as f:
|
||||
json.dump(curation_stats, f, indent=2)
|
||||
return json_path
|
||||
|
||||
|
||||
def save_cage_day_features(
|
||||
features_list: list[dict[str, Any]],
|
||||
output_dir: Path | str,
|
||||
) -> tuple[Path, Path]:
|
||||
"""Save aggregated cage day features to cage_day_features.parquet & .csv."""
|
||||
out_dir = Path(output_dir)
|
||||
df = pd.DataFrame(features_list)
|
||||
base_path = out_dir / "cage_day_features"
|
||||
return save_dataframe_parquet_and_csv(df, base_path)
|
||||
|
||||
|
||||
def save_weight_predictions(
|
||||
predictions_list: list[dict[str, Any]],
|
||||
output_dir: Path | str,
|
||||
date: str,
|
||||
) -> tuple[Path, Path]:
|
||||
"""Save weight predictions to predictions_{date}.parquet & .csv."""
|
||||
out_dir = Path(output_dir)
|
||||
df = pd.DataFrame(predictions_list)
|
||||
base_path = out_dir / f"predictions_{date}"
|
||||
return save_dataframe_parquet_and_csv(df, base_path)
|
||||
+130
-16
@@ -32,6 +32,15 @@ CREATE TABLE IF NOT EXISTS batch_runs (
|
||||
stopped_reason TEXT NOT NULL DEFAULT '',
|
||||
source_video TEXT NOT NULL DEFAULT '',
|
||||
generated_at TEXT NOT NULL DEFAULT '',
|
||||
cycle_day INTEGER NOT NULL DEFAULT 0,
|
||||
area_cm2_median REAL NOT NULL DEFAULT 0.0,
|
||||
minor_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
major_axis_cm_median REAL NOT NULL DEFAULT 0.0,
|
||||
predicted_weight_g REAL NOT NULL DEFAULT 0.0,
|
||||
gompertz_baseline_g REAL NOT NULL DEFAULT 0.0,
|
||||
vision_gain_g REAL NOT NULL DEFAULT 0.0,
|
||||
n_weight_samples INTEGER NOT NULL DEFAULT 0,
|
||||
rejection_rate REAL NOT NULL DEFAULT 0.0,
|
||||
UNIQUE(date, location, camera_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_batch_date ON batch_runs (date);
|
||||
@@ -42,15 +51,26 @@ CREATE INDEX IF NOT EXISTS idx_batch_location ON batch_runs (location);
|
||||
INSERT_SQL = """
|
||||
INSERT INTO batch_runs
|
||||
(date, location, camera_id, total_entered, frames_processed,
|
||||
elapsed_seconds, stopped_reason, source_video, generated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
elapsed_seconds, stopped_reason, source_video, generated_at,
|
||||
cycle_day, area_cm2_median, minor_axis_cm_median, major_axis_cm_median,
|
||||
predicted_weight_g, gompertz_baseline_g, vision_gain_g, n_weight_samples, rejection_rate)
|
||||
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
|
||||
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,
|
||||
cycle_day = excluded.cycle_day,
|
||||
area_cm2_median = excluded.area_cm2_median,
|
||||
minor_axis_cm_median = excluded.minor_axis_cm_median,
|
||||
major_axis_cm_median = excluded.major_axis_cm_median,
|
||||
predicted_weight_g = excluded.predicted_weight_g,
|
||||
gompertz_baseline_g = excluded.gompertz_baseline_g,
|
||||
vision_gain_g = excluded.vision_gain_g,
|
||||
n_weight_samples = excluded.n_weight_samples,
|
||||
rejection_rate = excluded.rejection_rate
|
||||
"""
|
||||
|
||||
SUMMARY_QUERY = """
|
||||
@@ -60,15 +80,98 @@ SELECT
|
||||
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
|
||||
ROUND(SUM(elapsed_seconds) / 60.0, 1) AS total_minutes,
|
||||
ROUND(AVG(predicted_weight_g), 1) AS avg_pred_weight
|
||||
FROM batch_runs
|
||||
WHERE date = ? AND location = ?
|
||||
GROUP BY date, location
|
||||
"""
|
||||
|
||||
|
||||
def migrate_db_schema(conn: sqlite3.Connection) -> None:
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.executescript(CREATE_TABLE)
|
||||
cursor = conn.execute("PRAGMA table_info(batch_runs)")
|
||||
existing_cols = {row[1] for row in cursor.fetchall()}
|
||||
new_cols = [
|
||||
("cycle_day", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("area_cm2_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("minor_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("major_axis_cm_median", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("predicted_weight_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("gompertz_baseline_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("vision_gain_g", "REAL NOT NULL DEFAULT 0.0"),
|
||||
("n_weight_samples", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("rejection_rate", "REAL NOT NULL DEFAULT 0.0"),
|
||||
]
|
||||
for col_name, col_type in new_cols:
|
||||
if col_name not in existing_cols:
|
||||
try:
|
||||
conn.execute(f"ALTER TABLE batch_runs ADD COLUMN {col_name} {col_type}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def load_companion_weight_data(report_dir: Path, date: str) -> dict[str, dict]:
|
||||
"""Load per-camera weight and dimensional metrics from companion prediction files."""
|
||||
weight_map: dict[str, dict] = {}
|
||||
|
||||
# 1. Try predictions_{date}.parquet or .csv
|
||||
for ext in (".parquet", ".csv"):
|
||||
pred_file = report_dir / f"predictions_{date}{ext}"
|
||||
if pred_file.is_file():
|
||||
try:
|
||||
import pandas as pd
|
||||
df = pd.read_parquet(pred_file) if ext == ".parquet" else pd.read_csv(pred_file)
|
||||
for _, row in df.iterrows():
|
||||
cid = str(row.get("camera_id", ""))
|
||||
if cid and cid != "FUSED":
|
||||
weight_map[cid] = {
|
||||
"cycle_day": int(row.get("cycle_day", 0)),
|
||||
"area_cm2_median": float(row.get("area_cm2_median", row.get("median_area_cm2", 0.0))),
|
||||
"minor_axis_cm_median": float(row.get("minor_axis_cm_median", 0.0)),
|
||||
"major_axis_cm_median": float(row.get("major_axis_cm_median", 0.0)),
|
||||
"predicted_weight_g": float(row.get("predicted_weight_g", 0.0)),
|
||||
"gompertz_baseline_g": float(row.get("gompertz_baseline_g", 0.0)),
|
||||
"vision_gain_g": float(row.get("vision_gain_g", 0.0)),
|
||||
"n_weight_samples": int(row.get("n_valid_samples", 0)),
|
||||
"rejection_rate": float(row.get("rejection_rate", 0.0)),
|
||||
}
|
||||
if weight_map:
|
||||
return weight_map
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. Try cage_day_features.parquet or .csv if predictions not directly mapped
|
||||
for ext in (".parquet", ".csv"):
|
||||
feat_file = report_dir / f"cage_day_features{ext}"
|
||||
if feat_file.is_file():
|
||||
try:
|
||||
import pandas as pd
|
||||
df = pd.read_parquet(feat_file) if ext == ".parquet" else pd.read_csv(feat_file)
|
||||
for _, row in df.iterrows():
|
||||
cid = str(row.get("camera_id", ""))
|
||||
if cid and cid != "FUSED" and cid not in weight_map:
|
||||
weight_map[cid] = {
|
||||
"cycle_day": int(row.get("cycle_day", 0)),
|
||||
"area_cm2_median": float(row.get("bbox_area_cm2_median", 0.0)),
|
||||
"minor_axis_cm_median": float(row.get("minor_axis_cm_median", 0.0)),
|
||||
"major_axis_cm_median": float(row.get("major_axis_cm_median", 0.0)),
|
||||
"predicted_weight_g": 0.0,
|
||||
"gompertz_baseline_g": 0.0,
|
||||
"vision_gain_g": 0.0,
|
||||
"n_weight_samples": int(row.get("n_valid_samples", 0)),
|
||||
"rejection_rate": float(row.get("rejection_rate", 0.0)),
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return weight_map
|
||||
|
||||
|
||||
def store_report(report_path: str, location: str, db_path: str) -> None:
|
||||
with open(report_path) as f:
|
||||
rep_p = Path(report_path)
|
||||
with open(rep_p) as f:
|
||||
report = json.load(f)
|
||||
|
||||
date = report["date"]
|
||||
@@ -77,13 +180,15 @@ def store_report(report_path: str, location: str, db_path: str) -> None:
|
||||
|
||||
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(db_path)
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.executescript(CREATE_TABLE)
|
||||
migrate_db_schema(conn)
|
||||
|
||||
weight_data = load_companion_weight_data(rep_p.parent, date)
|
||||
|
||||
rows = 0
|
||||
for camera_id, entry in cameras.items():
|
||||
if entry.get("skipped"):
|
||||
continue
|
||||
w_info = weight_data.get(camera_id, {})
|
||||
conn.execute(INSERT_SQL, (
|
||||
date, location, camera_id,
|
||||
entry.get("total_entered", 0),
|
||||
@@ -92,6 +197,15 @@ def store_report(report_path: str, location: str, db_path: str) -> None:
|
||||
entry.get("stopped_reason", ""),
|
||||
entry.get("source_video", ""),
|
||||
generated_at,
|
||||
w_info.get("cycle_day", 0),
|
||||
w_info.get("area_cm2_median", 0.0),
|
||||
w_info.get("minor_axis_cm_median", 0.0),
|
||||
w_info.get("major_axis_cm_median", 0.0),
|
||||
w_info.get("predicted_weight_g", 0.0),
|
||||
w_info.get("gompertz_baseline_g", 0.0),
|
||||
w_info.get("vision_gain_g", 0.0),
|
||||
w_info.get("n_weight_samples", 0),
|
||||
w_info.get("rejection_rate", 0.0),
|
||||
))
|
||||
rows += 1
|
||||
|
||||
@@ -101,15 +215,15 @@ def store_report(report_path: str, location: str, db_path: str) -> None:
|
||||
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)")
|
||||
f"{row[3]} chickens | {row[4]:.0f}s ({row[5]} min) | avg weight: {row[6]}g")
|
||||
|
||||
# also print per-camera breakdown
|
||||
cur = conn.execute(
|
||||
"SELECT camera_id, total_entered, elapsed_seconds "
|
||||
"SELECT camera_id, total_entered, elapsed_seconds, predicted_weight_g, area_cm2_median, minor_axis_cm_median, major_axis_cm_median "
|
||||
"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")
|
||||
for cam_id, count, secs, pw, area, minor_ax, major_ax in cur:
|
||||
print(f" {cam_id}: {count} chickens, {secs:.0f}s, weight: {pw:.1f}g (area: {area:.1f}cm², minor: {minor_ax:.1f}cm, major: {major_ax:.1f}cm)")
|
||||
|
||||
conn.close()
|
||||
print(f"\n[db] wrote {rows} rows to {db_path}")
|
||||
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/bin/bash
|
||||
# clear_db.sh - Clear SQLite chicken counts database records safely
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
if [ -d "$SCRIPT_DIR/../db" ]; then
|
||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
else
|
||||
PROJECT_ROOT="$SCRIPT_DIR"
|
||||
fi
|
||||
DB_PATH="$PROJECT_ROOT/db/chicken_counts.db"
|
||||
|
||||
echo "======================================================================"
|
||||
echo "🧹 Chicken Counting Database Reset Utility"
|
||||
echo " Target Database: $DB_PATH"
|
||||
echo "======================================================================"
|
||||
|
||||
if [ -f "$DB_PATH" ]; then
|
||||
# Create backup before clearing
|
||||
backup_file="$PROJECT_ROOT/db/chicken_counts_backup_$(date +%Y%m%d_%H%M%S).db"
|
||||
cp "$DB_PATH" "$backup_file"
|
||||
echo "📦 Backup saved to: $backup_file"
|
||||
|
||||
sqlite3 "$DB_PATH" "DELETE FROM batch_runs; VACUUM;" 2>/dev/null || rm -f "$DB_PATH"
|
||||
echo "✅ Successfully cleared batch_runs table from $DB_PATH."
|
||||
else
|
||||
echo "ℹ️ No database file found at $DB_PATH. Nothing to clear."
|
||||
fi
|
||||
@@ -3,21 +3,26 @@
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
export PYTHONPATH="$SCRIPT_DIR/src"
|
||||
if [ -d "$SCRIPT_DIR/../src" ]; then
|
||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
else
|
||||
PROJECT_ROOT="$SCRIPT_DIR"
|
||||
fi
|
||||
cd "$PROJECT_ROOT"
|
||||
export PYTHONPATH="$PROJECT_ROOT/src"
|
||||
|
||||
if [ -f "$SCRIPT_DIR/venv/bin/python" ]; then
|
||||
PYTHON="$SCRIPT_DIR/venv/bin/python"
|
||||
if [ -f "$PROJECT_ROOT/venv/bin/python" ]; then
|
||||
PYTHON="$PROJECT_ROOT/venv/bin/python"
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
|
||||
RAW_VIDEO_DIR="/media/asus/OneTouch/VIDEOS/cycle7/kandang-atas"
|
||||
RAW_VIDEO_DIR="/home/asus/.Codes/VIDEOS/cycle7/FULL_Cycle_Kandang_Atas_Test"
|
||||
BASE_OUTPUT_DIR="/home/asus/.Codes/VIDEOS/cycle7/FULL_Cycle_Kandang_Atas_Test"
|
||||
DB_PATH="$SCRIPT_DIR/db/chicken_counts.db"
|
||||
CONFIG_FILE="$SCRIPT_DIR/configs/cycle7_batch_optimized.yaml"
|
||||
DB_PATH="$PROJECT_ROOT/db/chicken_counts.db"
|
||||
CONFIG_FILE="$PROJECT_ROOT/configs/cycle7_batch_optimized.yaml"
|
||||
|
||||
# Maximum parallel video jobs (Default: 4 for optimal 16GB RAM & GPU utilization)
|
||||
# Maximum parallel video jobs (Default: 4 for optimal NVMe SSD, RAM & GPU utilization)
|
||||
MAX_JOBS="${1:-${MAX_JOBS:-4}}"
|
||||
|
||||
# 1. Validate raw video directory
|
||||
@@ -27,19 +32,7 @@ if [ ! -d "$RAW_VIDEO_DIR" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. Clear SQLite Database
|
||||
echo "======================================================================"
|
||||
echo "🧹 Initializing Clean Run Environment"
|
||||
echo " Database Path : $DB_PATH"
|
||||
if [ -f "$DB_PATH" ]; then
|
||||
echo " [db] Clearing previous chicken counts records..."
|
||||
sqlite3 "$DB_PATH" "DELETE FROM batch_runs; VACUUM;" 2>/dev/null || rm -f "$DB_PATH"
|
||||
echo " [db] ✅ Chicken counts database cleared."
|
||||
else
|
||||
echo " [db] No existing database found. Fresh DB will be created."
|
||||
fi
|
||||
|
||||
# 3. Discover dates up to 2026-07-09, ignoring folders with special notes
|
||||
# 2. Discover dates up to 2026-07-09, ignoring folders with special notes
|
||||
dates=()
|
||||
for d in "$RAW_VIDEO_DIR"/*; do
|
||||
[ -d "$d" ] || continue
|
||||
@@ -62,7 +55,8 @@ fi
|
||||
cameras=("CC1" "CC2" "CC3" "CC4")
|
||||
total_tasks=$((${#sorted_dates[@]} * ${#cameras[@]}))
|
||||
|
||||
# 4. Pre-create output date directories
|
||||
# 3. Pre-create output date directories
|
||||
echo " Database Path : $DB_PATH (Persistent storage)"
|
||||
echo " Output Root : $BASE_OUTPUT_DIR"
|
||||
mkdir -p "$BASE_OUTPUT_DIR"
|
||||
for d in "${sorted_dates[@]}"; do
|
||||
@@ -88,6 +82,7 @@ echo " Total Dates : ${#sorted_dates[@]} dates"
|
||||
echo " Cameras per Date : ${#cameras[@]} (CC1..CC4)"
|
||||
echo " Total Video Tasks : $total_tasks videos"
|
||||
echo " Max Parallel Jobs : $MAX_JOBS"
|
||||
echo " Worker Priority : nice -n 10 (Protected SSH / system responsiveness)"
|
||||
echo " Video Generation : DISABLED (--no-video)"
|
||||
echo "======================================================================"
|
||||
|
||||
@@ -107,9 +102,9 @@ for d in "${sorted_dates[@]}"; do
|
||||
active_count=$(jobs -p | wc -l)
|
||||
echo "[job $task_idx/$total_tasks] ⚙️ Launching $d ($cam) | Active workers: $((active_count + 1))/$MAX_JOBS"
|
||||
|
||||
# Launch individual camera task in background
|
||||
# Launch individual camera task in background with polite priority (nice -n 10)
|
||||
(
|
||||
$PYTHON -m chicken_counter.cli batch \
|
||||
nice -n 10 $PYTHON -m chicken_counter.cli batch \
|
||||
--config "$CONFIG_FILE" \
|
||||
--root-dir "$RAW_VIDEO_DIR" \
|
||||
--output-dir "$BASE_OUTPUT_DIR" \
|
||||
@@ -137,3 +132,11 @@ echo " Total Time Taken : ${hours}h ${mins}m ${secs}s (Total: ${elapsed}s)"
|
||||
echo " Results Stored In : $DB_PATH"
|
||||
echo " Output Reports : $BASE_OUTPUT_DIR"
|
||||
echo "======================================================================"
|
||||
|
||||
# Automatically generate Excel Analytics Summary
|
||||
if [ -f "$PROJECT_ROOT/export_excel_report.py" ]; then
|
||||
echo ""
|
||||
echo "[report] 📊 Generating Analytical Excel Workbook..."
|
||||
$PYTHON "$PROJECT_ROOT/export_excel_report.py"
|
||||
echo "[report] ✅ Report ready at: $PROJECT_ROOT/db/chicken_counts_report.xlsx"
|
||||
fi
|
||||
@@ -1,139 +0,0 @@
|
||||
#!/bin/bash
|
||||
# test_run_full_cycle7.sh - Run Full Cycle 7 Video Processing on Kandang Atas (2026-05-22 to 2026-07-09)
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
export PYTHONPATH="$SCRIPT_DIR/src"
|
||||
|
||||
if [ -f "$SCRIPT_DIR/venv/bin/python" ]; then
|
||||
PYTHON="$SCRIPT_DIR/venv/bin/python"
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
|
||||
RAW_VIDEO_DIR="/media/asus/OneTouch/VIDEOS/cycle7/kandang-atas"
|
||||
BASE_OUTPUT_DIR="/home/asus/.Codes/VIDEOS/cycle7/FULL_Cycle_Kandang_Atas_Test"
|
||||
DB_PATH="$SCRIPT_DIR/db/chicken_counts.db"
|
||||
CONFIG_FILE="$SCRIPT_DIR/configs/cycle7_batch_optimized.yaml"
|
||||
|
||||
# Maximum parallel video jobs (Default: 4 for optimal 16GB RAM & GPU utilization)
|
||||
MAX_JOBS="${1:-${MAX_JOBS:-4}}"
|
||||
|
||||
# 1. Validate raw video directory
|
||||
if [ ! -d "$RAW_VIDEO_DIR" ]; then
|
||||
echo "❌ Error: Raw video directory not found: $RAW_VIDEO_DIR"
|
||||
echo " Please check if the OneTouch drive is mounted."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. Clear SQLite Database
|
||||
echo "======================================================================"
|
||||
echo "🧹 Initializing Clean Run Environment"
|
||||
echo " Database Path : $DB_PATH"
|
||||
if [ -f "$DB_PATH" ]; then
|
||||
echo " [db] Clearing previous chicken counts records..."
|
||||
sqlite3 "$DB_PATH" "DELETE FROM batch_runs; VACUUM;" 2>/dev/null || rm -f "$DB_PATH"
|
||||
echo " [db] ✅ Chicken counts database cleared."
|
||||
else
|
||||
echo " [db] No existing database found. Fresh DB will be created."
|
||||
fi
|
||||
|
||||
# 3. Discover dates up to 2026-07-09, ignoring folders with special notes
|
||||
dates=()
|
||||
for d in "$RAW_VIDEO_DIR"/*; do
|
||||
[ -d "$d" ] || continue
|
||||
b=$(basename "$d")
|
||||
# Match strictly YYYY-MM-DD and only up to 2026-07-09
|
||||
if [[ "$b" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && [[ "$b" < "2026-07-10" ]]; then
|
||||
dates+=("$b")
|
||||
fi
|
||||
done
|
||||
|
||||
# Sort dates chronologically
|
||||
IFS=$'\n' sorted_dates=($(sort <<<"${dates[*]}"))
|
||||
unset IFS
|
||||
|
||||
if [ "${#sorted_dates[@]}" -eq 0 ]; then
|
||||
echo "❌ Error: No valid dates found in $RAW_VIDEO_DIR"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cameras=("CC1" "CC2" "CC3" "CC4")
|
||||
total_tasks=$((${#sorted_dates[@]} * ${#cameras[@]}))
|
||||
|
||||
# 4. Pre-create output date directories
|
||||
echo " Output Root : $BASE_OUTPUT_DIR"
|
||||
mkdir -p "$BASE_OUTPUT_DIR"
|
||||
for d in "${sorted_dates[@]}"; do
|
||||
mkdir -p "$BASE_OUTPUT_DIR/$d/output"
|
||||
done
|
||||
echo " [setup] ✅ Pre-created output folders for ${#sorted_dates[@]} dates."
|
||||
|
||||
# Trap SIGINT / SIGTERM to cleanly terminate all background workers on Ctrl+C
|
||||
cleanup() {
|
||||
echo -e "\n[runner] 🛑 Aborting: Terminating active background workers..."
|
||||
kill $(jobs -p) 2>/dev/null || true
|
||||
wait 2>/dev/null || true
|
||||
exit 1
|
||||
}
|
||||
trap cleanup SIGINT SIGTERM
|
||||
|
||||
echo "======================================================================"
|
||||
echo "🚀 Starting Full Cycle 7 Processing (Kandang Atas)"
|
||||
echo " Raw Video Source : $RAW_VIDEO_DIR"
|
||||
echo " Output Directory : $BASE_OUTPUT_DIR"
|
||||
echo " Date Range : ${sorted_dates[0]} to ${sorted_dates[${#sorted_dates[@]}-1]}"
|
||||
echo " Total Dates : ${#sorted_dates[@]} dates"
|
||||
echo " Cameras per Date : ${#cameras[@]} (CC1..CC4)"
|
||||
echo " Total Video Tasks : $total_tasks videos"
|
||||
echo " Max Parallel Jobs : $MAX_JOBS"
|
||||
echo " Video Generation : DISABLED (--no-video)"
|
||||
echo "======================================================================"
|
||||
|
||||
start_time=$(date +%s)
|
||||
task_idx=0
|
||||
|
||||
# Flatten tasks into dynamic worker pool (zero date-barrier delay)
|
||||
for d in "${sorted_dates[@]}"; do
|
||||
for cam in "${cameras[@]}"; do
|
||||
task_idx=$((task_idx + 1))
|
||||
|
||||
# Dynamic sliding window: Wait while active background jobs >= MAX_JOBS
|
||||
while [ "$(jobs -p | wc -l)" -ge "$MAX_JOBS" ]; do
|
||||
sleep 0.2
|
||||
done
|
||||
|
||||
active_count=$(jobs -p | wc -l)
|
||||
echo "[job $task_idx/$total_tasks] ⚙️ Launching $d ($cam) | Active workers: $((active_count + 1))/$MAX_JOBS"
|
||||
|
||||
# Launch individual camera task in background
|
||||
(
|
||||
$PYTHON -m chicken_counter.cli batch \
|
||||
--config "$CONFIG_FILE" \
|
||||
--root-dir "$RAW_VIDEO_DIR" \
|
||||
--output-dir "$BASE_OUTPUT_DIR" \
|
||||
--date "$d" \
|
||||
--camera "$cam" \
|
||||
--no-video
|
||||
) &
|
||||
done
|
||||
done
|
||||
|
||||
# Wait for all remaining background workers to finish
|
||||
echo "----------------------------------------------------------------------"
|
||||
echo "[runner] ⏳ All $total_tasks tasks dispatched. Waiting for active workers to complete..."
|
||||
wait
|
||||
|
||||
elapsed=$(( $(date +%s) - start_time ))
|
||||
hours=$(( elapsed / 3600 ))
|
||||
mins=$(( (elapsed % 3600) / 60 ))
|
||||
secs=$(( elapsed % 60 ))
|
||||
|
||||
echo "======================================================================"
|
||||
echo "✨ Full Cycle 7 Processing Completed!"
|
||||
echo " Total Tasks Run : $total_tasks videos across ${#sorted_dates[@]} dates"
|
||||
echo " Total Time Taken : ${hours}h ${mins}m ${secs}s (Total: ${elapsed}s)"
|
||||
echo " Results Stored In : $DB_PATH"
|
||||
echo " Output Reports : $BASE_OUTPUT_DIR"
|
||||
echo "======================================================================"
|
||||
@@ -0,0 +1,255 @@
|
||||
"""Unit tests for chicken weight estimation, metric calibration, curation, and storage."""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from chicken_counter.weight.calibration import CalibrationConfig, compute_metric_bbox
|
||||
from chicken_counter.weight.growth_model import (
|
||||
STANDARD_BROILER_WEIGHT_TABLE,
|
||||
gompertz_baseline_weight,
|
||||
predict_chicken_weight,
|
||||
)
|
||||
from chicken_counter.weight.curation import (
|
||||
curate_track_observations,
|
||||
get_mad_zscore_threshold,
|
||||
)
|
||||
from chicken_counter.weight.aggregation import (
|
||||
aggregate_camera_features,
|
||||
build_cage_day_features_and_predictions,
|
||||
)
|
||||
from chicken_counter.weight.storage import (
|
||||
save_camera_detections,
|
||||
save_curation_summary,
|
||||
save_cage_day_features,
|
||||
save_weight_predictions,
|
||||
)
|
||||
|
||||
|
||||
class TestWeightEstimation(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp_dir = Path(tempfile.mkdtemp())
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
||||
|
||||
def test_metric_bbox_conversion(self):
|
||||
"""Test conversion of pixel bounding box and centroid to centimeters."""
|
||||
bbox_xyxy = (100, 200, 300, 500) # width=200px, height=300px
|
||||
centroid = (200, 350)
|
||||
px_per_cm = 20.0 # 20 pixels = 1 cm
|
||||
|
||||
res = compute_metric_bbox(bbox_xyxy, centroid, px_per_cm=px_per_cm)
|
||||
self.assertEqual(res["px_per_cm"], 20.0)
|
||||
self.assertEqual(res["width_cm"], 10.0)
|
||||
self.assertEqual(res["height_cm"], 15.0)
|
||||
self.assertEqual(res["bbox_area_cm2"], 150.0)
|
||||
self.assertAlmostEqual(res["aspect_ratio_cm"], 10.0 / 15.0, places=3)
|
||||
self.assertEqual(res["centroid_x_cm"], 10.0)
|
||||
self.assertEqual(res["centroid_y_cm"], 17.5)
|
||||
self.assertEqual(res["perimeter_cm"], 50.0)
|
||||
|
||||
def test_fatchicken_curation_deduplication(self):
|
||||
"""Test track deduplication keeps highest confidence observation per track_id."""
|
||||
raw_tracks = [
|
||||
{"date": "2026-06-18", "camera_id": "CC1", "track_id": 1, "confidence": 0.50, "frame_index": 10, "bbox_area_cm2": 150.0},
|
||||
{"date": "2026-06-18", "camera_id": "CC1", "track_id": 1, "confidence": 0.85, "frame_index": 15, "bbox_area_cm2": 155.0},
|
||||
{"date": "2026-06-18", "camera_id": "CC1", "track_id": 2, "confidence": 0.60, "frame_index": 20, "bbox_area_cm2": 140.0},
|
||||
]
|
||||
curated, stats = curate_track_observations(raw_tracks, cycle_day=20)
|
||||
self.assertEqual(len(curated), 2)
|
||||
track_1 = next(r for r in curated if r["track_id"] == 1)
|
||||
self.assertEqual(track_1["confidence"], 0.85)
|
||||
self.assertEqual(track_1["bbox_area_cm2"], 155.0)
|
||||
self.assertEqual(stats["raw_tracks"], 3)
|
||||
self.assertEqual(stats["validated_tracks"], 2)
|
||||
self.assertEqual(stats["saved_rows"], 2)
|
||||
|
||||
def test_fatchicken_mad_zscore_outlier_elimination(self):
|
||||
"""Test MAD z-score outlier rejection when samples >= 30."""
|
||||
# 35 tight normal birds around 150 cm2 (spread +/- 1 cm2) + 2 extreme outliers (500 cm2 and 10 cm2)
|
||||
normal_areas = [150.0 + ((i % 5) - 2) * 0.5 for i in range(35)]
|
||||
raw_tracks = []
|
||||
for i, area in enumerate(normal_areas, start=1):
|
||||
raw_tracks.append({
|
||||
"date": "2026-06-18", "camera_id": "CC1", "track_id": i,
|
||||
"confidence": 0.80, "frame_index": i * 10, "bbox_area_cm2": float(area),
|
||||
})
|
||||
# Add extreme outliers
|
||||
raw_tracks.append({"date": "2026-06-18", "camera_id": "CC1", "track_id": 98, "confidence": 0.80, "frame_index": 500, "bbox_area_cm2": 500.0})
|
||||
raw_tracks.append({"date": "2026-06-18", "camera_id": "CC1", "track_id": 99, "confidence": 0.80, "frame_index": 510, "bbox_area_cm2": 10.0})
|
||||
|
||||
# Cycle day 27 -> threshold 2.0
|
||||
curated, stats = curate_track_observations(raw_tracks, cycle_day=27)
|
||||
self.assertEqual(stats["outliers_discarded"], 2)
|
||||
self.assertEqual(stats["saved_rows"], 35)
|
||||
self.assertTrue(stats["outlier_filter_active"])
|
||||
self.assertNotIn(98, [r["track_id"] for r in curated])
|
||||
self.assertNotIn(99, [r["track_id"] for r in curated])
|
||||
|
||||
def test_growth_model_and_predictions(self):
|
||||
"""Test Gompertz baseline curve lookup and vision weight prediction."""
|
||||
# Day 0 DOC
|
||||
doc_base = gompertz_baseline_weight(0)
|
||||
self.assertEqual(doc_base, 42.0)
|
||||
|
||||
# Day 27
|
||||
day27_base = gompertz_baseline_weight(27)
|
||||
self.assertEqual(day27_base, STANDARD_BROILER_WEIGHT_TABLE[27])
|
||||
|
||||
pred = predict_chicken_weight(cycle_day=27, median_bbox_area_cm2=340.0)
|
||||
self.assertIn("predicted_weight_g", pred)
|
||||
self.assertIn("gompertz_baseline_g", pred)
|
||||
self.assertIn("vision_gain_g", pred)
|
||||
self.assertGreater(pred["predicted_weight_g"], 1800.0)
|
||||
|
||||
def test_aggregation_and_multi_camera_fusion(self):
|
||||
"""Test camera feature distribution aggregation and multi-camera FUSED row generation."""
|
||||
cam1_tracks = [{"track_id": i, "confidence": 0.8, "bbox_area_cm2": 330.0, "width_cm": 17.5, "height_cm": 18.8, "aspect_ratio_cm": 0.93, "perimeter_cm": 72.6} for i in range(1, 40)]
|
||||
cam2_tracks = [{"track_id": i, "confidence": 0.85, "bbox_area_cm2": 345.0, "width_cm": 18.0, "height_cm": 19.1, "aspect_ratio_cm": 0.94, "perimeter_cm": 74.2} for i in range(1, 60)]
|
||||
|
||||
cam1_agg = aggregate_camera_features(cam1_tracks, "CC1", "2026-06-18", cycle_day=27)
|
||||
cam2_agg = aggregate_camera_features(cam2_tracks, "CC2", "2026-06-18", cycle_day=27)
|
||||
|
||||
features_list, predictions_list = build_cage_day_features_and_predictions(
|
||||
[cam1_agg, cam2_agg], date="2026-06-18", cycle_day=27
|
||||
)
|
||||
|
||||
# CC1, CC2, and FUSED
|
||||
self.assertEqual(len(features_list), 3)
|
||||
self.assertEqual(len(predictions_list), 3)
|
||||
|
||||
fused_feat = next(r for r in features_list if r["camera_id"] == "FUSED")
|
||||
self.assertEqual(fused_feat["n_valid_samples"], 39 + 59)
|
||||
self.assertGreater(fused_feat["bbox_area_cm2_mean"], 300.0)
|
||||
|
||||
fused_pred = next(r for r in predictions_list if r["camera_id"] == "FUSED")
|
||||
self.assertEqual(fused_pred["dominant_camera"], "CC2")
|
||||
self.assertGreater(fused_pred["predicted_weight_g"], 1800.0)
|
||||
|
||||
def test_storage_parquet_csv_and_json(self):
|
||||
"""Test persistence to parquet and csv fallbacks."""
|
||||
data = [
|
||||
{"date": "2026-06-18", "camera_id": "CC1", "track_id": 1, "confidence": 0.8, "bbox_area_cm2": 250.0}
|
||||
]
|
||||
# Detections
|
||||
pq_path, csv_path = save_camera_detections(data, self.temp_dir, date="2026-06-18", camera_id="CC1")
|
||||
self.assertTrue(pq_path.is_file())
|
||||
self.assertTrue(csv_path.is_file())
|
||||
|
||||
# Curation Summary
|
||||
curation_stats = {"date": "2026-06-18", "camera_id": "CC1", "saved_rows": 1, "rejection_rate": 0.0}
|
||||
json_path = save_curation_summary(curation_stats, self.temp_dir, date="2026-06-18", camera_id="CC1")
|
||||
self.assertTrue(json_path.is_file())
|
||||
with open(json_path) as f:
|
||||
loaded_json = json.load(f)
|
||||
self.assertEqual(loaded_json["camera_id"], "CC1")
|
||||
|
||||
# Features & Predictions
|
||||
feat_pq, feat_csv = save_cage_day_features(data, self.temp_dir)
|
||||
pred_pq, pred_csv = save_weight_predictions(data, self.temp_dir, date="2026-06-18")
|
||||
self.assertTrue(feat_pq.is_file())
|
||||
self.assertTrue(pred_pq.is_file())
|
||||
|
||||
def test_minor_and_major_axis_metrics(self):
|
||||
"""Test calculation of minor_axis_cm and major_axis_cm across orientations."""
|
||||
# Width > Height
|
||||
res1 = compute_metric_bbox((0, 0, 400, 200), px_per_cm=20.0)
|
||||
self.assertEqual(res1["width_cm"], 20.0)
|
||||
self.assertEqual(res1["height_cm"], 10.0)
|
||||
self.assertEqual(res1["minor_axis_cm"], 10.0)
|
||||
self.assertEqual(res1["major_axis_cm"], 20.0)
|
||||
|
||||
# Height > Width
|
||||
res2 = compute_metric_bbox((0, 0, 160, 320), px_per_cm=20.0)
|
||||
self.assertEqual(res2["width_cm"], 8.0)
|
||||
self.assertEqual(res2["height_cm"], 16.0)
|
||||
self.assertEqual(res2["minor_axis_cm"], 8.0)
|
||||
self.assertEqual(res2["major_axis_cm"], 16.0)
|
||||
|
||||
def test_db_migration_and_weight_storage(self):
|
||||
"""Test SQLite migration helper and storing weight/dimensional metrics in batch_runs."""
|
||||
import sqlite3
|
||||
from chicken_counter.batch_runner import migrate_db_schema
|
||||
|
||||
db_path = self.temp_dir / "test_weights.db"
|
||||
conn = sqlite3.connect(db_path)
|
||||
migrate_db_schema(conn)
|
||||
|
||||
# Insert a sample batch run with weight data
|
||||
conn.execute("""INSERT INTO batch_runs (
|
||||
date, location, camera_id, total_entered, frames_processed, elapsed_seconds,
|
||||
stopped_reason, source_video, generated_at, cycle_day, area_cm2_median,
|
||||
minor_axis_cm_median, major_axis_cm_median, predicted_weight_g,
|
||||
gompertz_baseline_g, vision_gain_g, n_weight_samples, rejection_rate
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (
|
||||
"2026-06-05", "K1-L1", "CC1", 1500, 3000, 120.0,
|
||||
"end_of_video", "vid.mp4", "2026-06-05T12:00:00",
|
||||
14, 120.5, 9.8, 14.2, 425.0, 608.0, -183.0, 1450, 0.02
|
||||
))
|
||||
conn.commit()
|
||||
|
||||
cursor = conn.execute("SELECT date, location, camera_id, cycle_day, area_cm2_median, minor_axis_cm_median, major_axis_cm_median, predicted_weight_g FROM batch_runs WHERE date='2026-06-05'")
|
||||
row = cursor.fetchone()
|
||||
self.assertIsNotNone(row)
|
||||
self.assertEqual(row[0], "2026-06-05")
|
||||
self.assertEqual(row[1], "K1-L1")
|
||||
self.assertEqual(row[2], "CC1")
|
||||
self.assertEqual(row[3], 14)
|
||||
self.assertEqual(row[4], 120.5)
|
||||
self.assertEqual(row[5], 9.8)
|
||||
self.assertEqual(row[6], 14.2)
|
||||
self.assertEqual(row[7], 425.0)
|
||||
conn.close()
|
||||
|
||||
def test_excel_report_generation_with_weight_sheets(self):
|
||||
"""Test generating Excel report containing Weight & Growth Analytics sheet."""
|
||||
import sqlite3
|
||||
import openpyxl
|
||||
from export_excel_report import generate_excel_report
|
||||
|
||||
db_path = self.temp_dir / "report_test.db"
|
||||
excel_path = self.temp_dir / "test_report.xlsx"
|
||||
|
||||
conn = sqlite3.connect(db_path)
|
||||
from chicken_counter.batch_runner import migrate_db_schema
|
||||
migrate_db_schema(conn)
|
||||
|
||||
conn.execute("""INSERT INTO batch_runs (
|
||||
date, location, camera_id, total_entered, frames_processed, elapsed_seconds,
|
||||
stopped_reason, source_video, generated_at, cycle_day, area_cm2_median,
|
||||
minor_axis_cm_median, major_axis_cm_median, predicted_weight_g,
|
||||
gompertz_baseline_g, vision_gain_g, n_weight_samples, rejection_rate
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (
|
||||
"2026-06-05", "K1-L1", "CC1", 1200, 2400, 100.0,
|
||||
"end_of_video", "vid.mp4", "2026-06-05T12:00:00",
|
||||
14, 115.0, 9.5, 13.8, 430.0, 608.0, -178.0, 1180, 0.015
|
||||
))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
generate_excel_report(str(db_path), str(excel_path))
|
||||
self.assertTrue(excel_path.is_file())
|
||||
|
||||
wb = openpyxl.load_workbook(excel_path)
|
||||
sheet_names = wb.sheetnames
|
||||
self.assertIn("Daily Summary", sheet_names)
|
||||
self.assertIn("Camera Summary", sheet_names)
|
||||
self.assertIn("Weight & Growth Analytics", sheet_names)
|
||||
self.assertIn("Raw Batch Runs", sheet_names)
|
||||
self.assertIn("Configurations", sheet_names)
|
||||
|
||||
ws_growth = wb["Weight & Growth Analytics"]
|
||||
self.assertEqual(ws_growth["A1"].value, "Flock Weight & Growth Trajectory Analytics (Cycle 7)")
|
||||
# Check Day 14 row
|
||||
self.assertEqual(ws_growth["A5"].value, "2026-06-05")
|
||||
self.assertEqual(ws_growth["B5"].value, 14)
|
||||
self.assertEqual(ws_growth["H5"].value, 430.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user