feat(weight, api): add camera location and coop identification to weight estimation

- Propagate parent coop (e.g. K1) and floor location (e.g. K1-L1) across feature aggregation, predictions, and curation storage
- Add REST API endpoints GET /api/weight/coops and GET /api/weight/coop/<coop_id>
- Support multi-coop non-colliding predictions and ?coop= / ?location= filtering
- Add dynamic farm root discovery and folder path fallback inference for legacy datasets
- Persist FUSED flock weight in SQLite batch_runs table with camera_id='FUSED'
- Update GET /api/db/date/<date> to return weight and coop metadata for all cameras
- Update ERD.md, CHANGELOG.md, API.md, and CENTRAL_DASHBOARD_INTEGRATION.md
- Add comprehensive unit tests in test_weight_estimation.py and test_dashboard_weight_api.py
This commit is contained in:
andrew committed 2026-09-03 14:12:35 +07:00
1 parent c738db6f92
commit e138360a13
11 files changed
+1044 -66

No files matched your search

+30 -2
View File
@@ -471,14 +471,38 @@ curl -X POST https://your-server.com/api/notify \
## Weight Estimation & Growth Analytics Endpoints
### `GET /api/weight/coops`
Returns summary list of all detected coops with available weight predictions.
```json
{
"coops": [
{
"coop": "K1",
"locations": ["K1-L1", "K1-L2"],
"days_count": 25,
"latest_date": "2026-06-18",
"latest_weight_g": 1424.2
}
],
"total_coops": 1
}
```
### `GET /api/weight/coop/<coop_id>`
Returns weight prediction history filtered for a specific coop (e.g. `K1` for Kandang 1).
### `GET /api/weight/predictions`
Returns all predicted body weights and growth milestones across all processed dates in the cycle.
Supports query parameter filtering: `?coop=K1` and `?location=K1-L1`.
```json
{
"predictions": [
{
"date": "2026-06-18",
"coop": "K1",
"location": "K1-L1",
"camera_id": "FUSED",
"cycle_day": 27,
"predicted_weight_g": 2147.2,
@@ -495,12 +519,14 @@ Returns all predicted body weights and growth milestones across all processed da
### `GET /api/weight/predictions/<date>`
Returns per-camera and `FUSED` weight prediction records for a specific date (e.g. `2026-06-18`).
Supports query parameter filtering: `?coop=K1` and `?location=K1-L1`.
### `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.
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. Supports `?coop=K1` and `?location=K1-L1`.
### `GET /api/weight/curation/<date>/<camera_id>`
Returns FatChicken curation and MAD outlier rejection audit statistics for a specific camera on a given date.
Supports `?coop=K1` or route format `GET /api/weight/curation/<date>/<coop>/<camera_id>`.
---
@@ -516,8 +542,10 @@ For model evaluation, feature engineering, and retraining, the pipeline saves st
| Column | Type | Description |
| :--- | :--- | :--- |
| `date` | `string` | Counting date in `YYYY-MM-DD` |
| `coop` | `string` | Parent coop / kandang (e.g. `K1` for Kandang 1) |
| `location` | `string` | Floor / location ID (e.g. `K1-L1`, `test-coop-1`) |
| `cycle_day` | `int64` | Day index in the rearing cycle (Day 0 = DOC Arrival) |
| `camera_id` | `string` | Camera identifier (e.g. `CC1`, `CC2`) |
| `camera_id` | `string` | Camera identifier (e.g. `CC1`, `CC2`, `FUSED`) |
| `frame_index` | `int64` | Frame index where observation was captured |
| `track_id` | `int64` | Consistent tracker ID assigned by BoT-SORT |
| `class_id` | `int64` | YOLO detection class (`0` = chicken) |
+330
View File
@@ -0,0 +1,330 @@
# 🐔 Central Dashboard API Integration & Data Mapping Guide
**Edge Device Host:** `http://192.168.192.106:8090`
**Protocol:** HTTP REST (JSON) + Multipart MJPEG Live Streams
**Repository:** `chicken-counting-sukawarna-det`
**Site:** Site A (Sukawarna Farm)
---
## 1. 🌐 System Overview & Base URL
The edge machine at **`192.168.192.106`** runs the Chicken Counting Vision Pipeline and hosts the local API server on port **`8090`**.
```text
Base API URL: http://192.168.192.106:8090
```
### Health Check / Heartbeat Endpoint
```http
GET http://192.168.192.106:8090/api/status
```
**Response Example:**
```json
{
"status": "running",
"is_counting_active": true,
"active_cameras": ["CC1", "CC2", "CC3", "CC4"],
"latest_counted_date": "2026-06-18",
"total_chickens_all_time": 146418,
"cycle_start_date": "2026-05-22",
"doc_weight_g": 42.0,
"timestamp": "2026-09-02T10:45:00.000000+00:00"
}
```
---
## 2. 🏛️ Farm Hierarchy & 2-Coop / 8-Camera Test Setup
The system organizes farm video and camera streams in a 4-tier hierarchy:
$$\text{Site} \longrightarrow \text{Coop (Kandang)} \longrightarrow \text{Floor / Location} \longrightarrow \text{Camera (CC1..CC4)}$$
| Level | Identifier | Test Values (2 Coops / 8 Cameras) |
| :--- | :--- | :--- |
| **Site** | `site` | `site_a` |
| **Coop 1** | `location` | `test-coop-1` *(Cameras: `CC1`, `CC2`, `CC3`, `CC4`)* |
| **Coop 2** | `location` | `test-coop-2` *(Cameras: `CC1`, `CC2`, `CC3`, `CC4`)* |
| **Total Test Scope** | — | **8 camera feeds total** |
---
## 3. 🗺️ Master Field Mappings (Edge API $\longrightarrow$ Central DB)
When the Central Dashboard pulls data from the edge device, map the edge fields to the Central Database tables as follows:
### A. Table `CHICKEN_COUNTING` (Headcount & Mortality)
| Edge API Field / Source | Central Table Field | Type | Description / Aggregation Logic |
| :--- | :--- | :--- | :--- |
| `date` | `date` | `DATE` | Batch run date (`YYYY-MM-DD`) |
| `location` | `floor_id` | `VARCHAR` | Floor/Coop ID (e.g., `test-coop-1`, `K1-L1`) |
| $\sum$ `total_entered` | `total_count` | `INTEGER` | Sum of `total_entered` across `CC1`..`CC4` for that floor |
| `total_mortality` | `mortality_count` | `INTEGER` | Carcass count from `/api/mortality/date/{date}` |
| Matched Date | `cycle_id` | `INTEGER` | References active commercial cycle in Central DB |
### B. Table `CHICKEN_WEIGHT` (Flock Growth & Morphometrics)
| Edge API Field / Source | Central Table Field | Type | Description / Units |
| :--- | :--- | :--- | :--- |
| `coop` | `coop` / `kandang_id` | `VARCHAR` | Parent coop / kandang (e.g., `K1` for Kandang 1) |
| `location` | `floor_id` | `VARCHAR` | Floor/location ID (e.g., `K1-L1`, `test-coop-1`) |
| `camera_id` | `camera_id` | `VARCHAR` | Camera ID (`CC1`..`CC4`) or `FUSED` for flock aggregate |
| `cycle_day` | `age` | `INTEGER` | Flock age in days ($0 = \text{DOC Arrival}$, $1+ = \text{Weight active}$) |
| `predicted_weight_g` / `fused_prediction_g` | `average_weight` | `FLOAT` | Predicted weight in **grams** ($g$) |
| `n_valid_samples` | `chicken_count` | `INTEGER` | Number of non-outlier validated chickens weighed |
| `area_cm2_median` | `area_cm2_median` | `FLOAT` | Calibrated median body projected area ($cm^2$) |
| `major_axis_cm_median` | `major_axis_cm_median` | `FLOAT` | Calibrated median body length ($cm$) |
| `minor_axis_cm_median` | `minor_axis_cm_median` | `FLOAT` | Calibrated median body width ($cm$) |
| `gompertz_baseline_g` | `gompertz_baseline_g` | `FLOAT` | Theoretical Gompertz growth curve baseline ($g$) |
| `vision_gain_g` | `vision_gain_g` | `FLOAT` | Vision-derived allometric gain residual ($g$) |
| `rejection_rate` | `rejection_rate` | `FLOAT` | Outlier filter rejection rate ($0.0 \text{ to } 1.0$) |
### C. Table `DETECTIONS` / `BATCH_RUNS` (Per-Camera Telemetry)
| Edge API Field | Central Table Field | Type | Description |
| :--- | :--- | :--- | :--- |
| `camera_id` | `camera_id` | `VARCHAR` | `CC1`, `CC2`, `CC3`, or `CC4` |
| `frames_processed` | `frames_processed` | `INTEGER` | Total video frames analyzed |
| `elapsed_seconds` | `elapsed_seconds` | `REAL` | Pipeline execution time in seconds |
| `stopped_reason` | `stopped_reason` | `VARCHAR` | Reason run ended (`completed` or `backward` optical flow) |
---
## 4. 📡 Primary REST API Endpoints
### 1. Overall Summary
```http
GET http://192.168.192.106:8090/api/db/summary
```
**Response:**
```json
{
"days": 1,
"locations": 2,
"total_runs": 8,
"total_chickens": 14280,
"total_hours": 0.45
}
```
---
### 2. Historical & 8-Camera Date Records
```http
GET http://192.168.192.106:8090/api/db/date/2026-06-18
```
**Response (8 Camera Runs across 2 Coops):**
```json
{
"date": "2026-06-18",
"total": {
"total": 14280,
"minutes": 27.2
},
"cameras": [
{
"camera_id": "CC1",
"location": "test-coop-1",
"total_entered": 1820,
"predicted_weight_g": 1430.5,
"frames_processed": 5120,
"elapsed_seconds": 184.2,
"stopped_reason": "completed"
},
{
"camera_id": "CC2",
"location": "test-coop-1",
"total_entered": 1750,
"predicted_weight_g": 1415.2,
"frames_processed": 5120,
"elapsed_seconds": 185.0,
"stopped_reason": "completed"
},
{
"camera_id": "CC3",
"location": "test-coop-1",
"total_entered": 1890,
"predicted_weight_g": 1442.0,
"frames_processed": 5120,
"elapsed_seconds": 183.8,
"stopped_reason": "completed"
},
{
"camera_id": "CC4",
"location": "test-coop-1",
"total_entered": 1710,
"predicted_weight_g": 1408.3,
"frames_processed": 5120,
"elapsed_seconds": 182.1,
"stopped_reason": "completed"
},
{
"camera_id": "CC1",
"location": "test-coop-2",
"total_entered": 1790,
"predicted_weight_g": 1425.0,
"frames_processed": 5120,
"elapsed_seconds": 186.4,
"stopped_reason": "completed"
},
{
"camera_id": "CC2",
"location": "test-coop-2",
"total_entered": 1810,
"predicted_weight_g": 1432.1,
"frames_processed": 5120,
"elapsed_seconds": 184.9,
"stopped_reason": "completed"
},
{
"camera_id": "CC3",
"location": "test-coop-2",
"total_entered": 1760,
"predicted_weight_g": 1410.8,
"frames_processed": 5120,
"elapsed_seconds": 185.7,
"stopped_reason": "completed"
},
{
"camera_id": "CC4",
"location": "test-coop-2",
"total_entered": 1750,
"predicted_weight_g": 1420.4,
"frames_processed": 5120,
"elapsed_seconds": 183.0,
"stopped_reason": "completed"
}
]
}
```
---
### 3. Filter by Individual Coop Location
```http
GET http://192.168.192.106:8090/api/db/location/test-coop-1
GET http://192.168.192.106:8090/api/db/location/test-coop-2
```
**Response:**
```json
{
"location": "test-coop-1",
"summary": {
"days": 1,
"total": 7170,
"hours": 0.22
},
"history": [
{
"date": "2026-06-18",
"cameras": "CC1, CC2, CC3, CC4",
"total": 7170,
"minutes": 13.5
}
]
}
```
---
### 4. Weight Predictions & Morphometrics
```http
GET http://192.168.192.106:8090/api/weight/coops
GET http://192.168.192.106:8090/api/weight/coop/K1
GET http://192.168.192.106:8090/api/weight/predictions?coop=K1
GET http://192.168.192.106:8090/api/weight/predictions/2026-06-18?coop=K1
GET http://192.168.192.106:8090/api/weight/features/2026-06-18?coop=K1
```
**Response (`GET /api/weight/predictions/2026-06-18?coop=K1`):**
```json
{
"date": "2026-06-18",
"records": [
{
"date": "2026-06-18",
"coop": "K1",
"location": "K1-L1",
"camera_id": "FUSED",
"cycle_day": 27,
"predicted_weight_g": 1424.2,
"doc_weight_g": 42.0,
"gompertz_baseline_g": 1390.0,
"vision_gain_g": 34.2,
"n_valid_samples": 6840,
"rejection_rate": 0.046,
"dominant_camera": "CC2",
"area_cm2_median": 245.3,
"major_axis_cm_median": 22.4,
"minor_axis_cm_median": 14.1
}
],
"total_records": 1
}
```
---
### 5. Mortality (Dead Bird) Reports
```http
GET http://192.168.192.106:8090/api/mortality/coops
GET http://192.168.192.106:8090/api/mortality/date/2026-06-18
```
**Response:**
```json
[
{
"coop": "K1",
"covered_floors": ["K1-L1", "K1-L2"],
"total_carcasses": 5,
"latest_date": "2026-06-18",
"latest_count": 5
},
{
"coop": "K2",
"covered_floors": ["K2-L1", "K2-L2"],
"total_carcasses": 3,
"latest_date": "2026-06-18",
"latest_count": 3
}
]
```
---
### 6. Live MJPEG Camera Streams & Real-Time Stats
* **Live Video Streams:**
* `http://192.168.192.106:8090/stream/CC1`
* `http://192.168.192.106:8090/stream/CC2`
* `http://192.168.192.106:8090/stream/CC3`
* `http://192.168.192.106:8090/stream/CC4`
* **Real-time Stats:**
* `GET http://192.168.192.106:8090/shm/CC1/stats.json`
---
## 5. 🧪 Testing Script for Central Dashboard Developers
```bash
#!/bin/bash
BASE="http://192.168.192.106:8090"
echo "=== 1. System Status ==="
curl -s "$BASE/api/status" | jq .
echo "=== 2. Overall Summary (All 8 Cameras) ==="
curl -s "$BASE/api/db/summary" | jq .
echo "=== 3. Coop 1 Data ==="
curl -s "$BASE/api/db/location/test-coop-1" | jq .
echo "=== 4. Coop 2 Data ==="
curl -s "$BASE/api/db/location/test-coop-2" | jq .
echo "=== 5. Weight Predictions ==="
curl -s "$BASE/api/weight/predictions" | jq .
echo "=== 6. Mortality Summary ==="
curl -s "$BASE/api/mortality/coops" | jq .
```
+26 -1
View File
@@ -2,7 +2,32 @@
All notable changes to the `chicken-counting-sukawarna-det` project are documented in this file.
## [Unreleased] - 2026-08-27
## [Unreleased] - 2026-09-03
### 📍 Camera Location & Coop Identification in Weight Estimation API
- **End-to-End Coop (`coop`) and Floor Location (`location`) Metadata Integration**:
- Enhanced weight pipeline (`src/chicken_counter/weight/aggregation.py`) to propagate parent coop (e.g. `K1` for Kandang 1) and floor location (e.g. `K1-L1` or `test-coop-1`) across `aggregate_camera_features` and `build_cage_day_features_and_predictions`.
- Added automatic coop derivation via `get_coop_for_location(location)` when only floor/location is provided.
- Included `coop` and `location` in all individual camera records, the `FUSED` flock record, and `cage_day_features`.
- Extended intermediate observation Parquet schema (`DETECTION_PARQUET_COLUMNS`) in `storage.py` with `coop` and `location`.
- Added `coop` and `location` tracking in `save_curation_summary` to `curation_{date}_{camera_id}.json`.
- **REST API Enhancements & Multi-Coop Disambiguation (`dashboard.py`)**:
- **New Endpoints**:
- `GET /api/weight/coops`: Summary list of all detected coops with available weight predictions, covered floors, and latest flock weight.
- `GET /api/weight/coop/<coop_id>`: Historical weight predictions filtered specifically for a coop (e.g. `K1`).
- **Deduplication Fix**: Fixed the date-collision bug in `GET /api/weight/predictions` where records were deduplicated by date alone. Keying on `(date, coop, location, camera_id)` now preserves multiple coops on the same date.
- **Query Parameter Filtering**: Added `?coop=` and `?location=` filtering to `/api/weight/predictions`, `/api/weight/predictions/<date>`, `/api/weight/features/<date>`, and `/api/weight/curation/...`.
- **Dynamic Farm Discovery**: Expanded root discovery using `discover_farm_structure()` and added automatic fallback inference (`_infer_coop_and_location`) to enrich legacy datasets from folder path hierarchy.
- **Telemetry & SQL Integration**: Updated `GET /api/db/date/<date>` to return `predicted_weight_g`, `area_cm2_median`, `cycle_day`, and `coop` for all cameras, matching Central Dashboard specifications.
- **FUSED Flock Weight Persistence**: Updated `batch_runner.py` and `store_results.py` to persist overall `FUSED` flock predictions into SQLite `batch_runs` table with `camera_id='FUSED'`.
- **Documentation & ERD Updates**:
- Updated `ERD.md`: Added `coop` and `location` to `DETECTIONS`, `CHICKEN_WEIGHT`, `CHICKEN_COUNTING`, and `BATCH_RUNS`.
- Updated `CENTRAL_DASHBOARD_INTEGRATION.md`: Added `coop` and `location` field mappings to Table `CHICKEN_WEIGHT` and updated Section 4.4 examples.
- Updated `API.md`: Documented new coop endpoints, query parameters, and updated Parquet intermediate schema table.
## [0.3.0] - 2026-08-27
### 🧹 Automated Storage Lifecycle & Validated Raw Video Purging
- **Strict Multi-Camera Artifact Validation & Purge (`src/chicken_counter/storage_lifecycle.py`)**:
+8 -1
View File
@@ -120,7 +120,7 @@ erDiagram
integer id PK "AUTOINCREMENT (SQLite edge runs)"
string date "YYYY-MM-DD"
string location FK "References FLOOR(floor_id)"
string camera_id FK "References CAMERA(camera_id)"
string camera_id FK "References CAMERA(camera_id) or 'FUSED'"
integer total_entered "Headcount count validated"
integer frames_processed
real elapsed_seconds
@@ -140,6 +140,8 @@ erDiagram
DETECTIONS {
string date "YYYY-MM-DD"
string coop "Parent Coop (e.g. K1)"
string location "Floor Location FK (e.g. K1-L1)"
integer cycle_day "Cycle Day (0 = DOC Arrival)"
string camera_id FK "CC1..CC4"
integer frame_index "Count trigger frame"
@@ -175,6 +177,8 @@ erDiagram
CHICKEN_COUNTING {
int cc_id PK "NOT NULL"
int cycle_id FK "References CYCLES"
string coop "Parent Coop (e.g. K1)"
string location "Floor ID (e.g. K1-L1)"
date date "NOT NULL"
int total_count "NOT NULL (Aggregated total from edge BATCH_RUNS)"
int mortality_count "NOT NULL (Carcasses from vision segmentation)"
@@ -185,6 +189,9 @@ erDiagram
CHICKEN_WEIGHT {
int cw_id PK "NOT NULL"
int cycle_id FK "References CYCLES"
string coop "Parent Coop (e.g. K1)"
string location "Floor ID (e.g. K1-L1)"
string camera_id "Camera ID (CC1..CC4 or FUSED)"
date date "NOT NULL"
int age "NOT NULL (Cycle Day: 1+)"
int doc_weight "NOT NULL (Cycle-specific initial DOC weight)"
+264 -57
View File
@@ -58,6 +58,7 @@ _mortality_reports_cache: list[Path] = []
_mortality_reports_mtime: float = 0.0
_mortality_image_cache: dict[str, Path] = {}
_MORTALITY_CACHE_TTL: float = 15.0 # seconds
_weight_candidate_roots: list[Path] = []
def _load_initial_cycle_start_date() -> str:
@@ -931,9 +932,19 @@ class DashboardHandler(SimpleHTTPRequestHandler):
prefix = "/api/db/date/"
if path.startswith(prefix):
date = path[len(prefix):]
cameras = conn.execute("SELECT camera_id, total_entered, frames_processed, ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason, source_video, location FROM batch_runs WHERE date=? ORDER BY camera_id", (date,)).fetchall()
total = conn.execute("SELECT SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs WHERE date=?", (date,)).fetchone()
res = {"date": date, "total": dict(total), "cameras": [dict(r) for r in cameras]}
cameras = conn.execute("""SELECT camera_id, total_entered, frames_processed,
ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason, source_video,
location, 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
FROM batch_runs WHERE date=? ORDER BY location, camera_id""", (date,)).fetchall()
cam_list = []
for r in cameras:
d = dict(r)
loc = d.get("location", "")
d["coop"] = get_coop_for_location(loc) if loc else ""
cam_list.append(d)
total = conn.execute("SELECT SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs WHERE date=? AND camera_id != 'FUSED'", (date,)).fetchone()
res = {"date": date, "total": dict(total) if total else {}, "cameras": cam_list}
res.update(_calc_cycle_info(date))
self._send_json(res)
return
@@ -942,17 +953,33 @@ class DashboardHandler(SimpleHTTPRequestHandler):
prefix = "/api/db/camera/"
if path.startswith(prefix):
cam_id = path[len(prefix):]
rows = conn.execute("SELECT date, location, total_entered, frames_processed, ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason FROM batch_runs WHERE camera_id=? ORDER BY date DESC LIMIT 50", (cam_id,)).fetchall()
self._send_json([dict(r) for r in rows])
rows = conn.execute("""SELECT date, location, total_entered, frames_processed,
ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason,
predicted_weight_g, area_cm2_median, cycle_day
FROM batch_runs WHERE camera_id=? ORDER BY date DESC LIMIT 50""", (cam_id,)).fetchall()
cam_rows = []
for r in rows:
d = dict(r)
loc = d.get("location", "")
d["coop"] = get_coop_for_location(loc) if loc else ""
cam_rows.append(d)
self._send_json(cam_rows)
return
# /api/db/location/<name>
prefix = "/api/db/location/"
if path.startswith(prefix):
loc = path[len(prefix):]
history = conn.execute("SELECT date, GROUP_CONCAT(camera_id,', ') AS cameras, SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes FROM batch_runs WHERE location=? GROUP BY date ORDER BY date DESC LIMIT 50", (loc,)).fetchall()
summary = conn.execute("SELECT COUNT(DISTINCT date) AS days, SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/3600.0,1) AS hours FROM batch_runs WHERE location=?", (loc,)).fetchone()
self._send_json({"location": loc, "summary": dict(summary), "history": [dict(r) for r in history]})
history = conn.execute("""SELECT date, GROUP_CONCAT(camera_id,', ') AS cameras,
SUM(total_entered) AS total, ROUND(SUM(elapsed_seconds)/60.0,1) AS minutes,
ROUND(AVG(CASE WHEN predicted_weight_g > 0 THEN predicted_weight_g END), 1) AS avg_weight_g
FROM batch_runs WHERE location=? AND camera_id != 'FUSED' GROUP BY date ORDER BY date DESC LIMIT 50""", (loc,)).fetchall()
summary = conn.execute("""SELECT COUNT(DISTINCT date) AS days, SUM(total_entered) AS total,
ROUND(SUM(elapsed_seconds)/3600.0,1) AS hours,
ROUND(AVG(CASE WHEN predicted_weight_g > 0 THEN predicted_weight_g END), 1) AS avg_weight_g
FROM batch_runs WHERE location=? AND camera_id != 'FUSED'""", (loc,)).fetchone()
coop = get_coop_for_location(loc)
self._send_json({"location": loc, "coop": coop, "summary": dict(summary) if summary else {}, "history": [dict(r) for r in history]})
return
self._send_json({})
@@ -1260,89 +1287,269 @@ class DashboardHandler(SimpleHTTPRequestHandler):
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/coops - Summary list of all detected coops with weight data
GET /api/weight/coop/<coop_id> - Weight predictions filtered for a specific coop (e.g. K1)
GET /api/weight/predictions - All predicted flock weights (supports ?coop=K1 and ?location=K1-L1)
GET /api/weight/predictions/<date> - Weight predictions for a date (supports ?coop=K1 and ?location=K1-L1)
GET /api/weight/features/<date> - Aggregated metric feature distributions for a specific date
GET /api/weight/curation/<date>/<camera_id> - FatChicken curation audit JSON
GET /api/weight/curation/<date>/<camera_id> - FatChicken curation audit JSON (supports ?coop=K1 or /<date>/<coop>/<cam>)
"""
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",
]
parsed = urlparse(self.path)
query = parse_qs(parsed.query)
coop_filter = (query.get("coop", [None])[0] or "").strip()
loc_filter = (query.get("location", [None])[0] or "").strip()
if path == "/api/weight/predictions":
all_predictions = []
seen_dates = set()
for root in candidate_roots:
if not root.is_dir():
if _weight_candidate_roots:
candidate_roots = list(_weight_candidate_roots)
else:
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",
base_dir / "VIDEOS",
base_dir.parent / "VIDEOS",
]
try:
farm_struct = discover_farm_structure()
if farm_struct.videos_root and farm_struct.videos_root.is_dir():
candidate_roots.append(farm_struct.videos_root)
for c_info in farm_struct.coops.values():
if c_info.coop_dir and c_info.coop_dir.is_dir():
candidate_roots.append(c_info.coop_dir)
for f_dir in c_info.floors.values():
if f_dir.is_dir():
candidate_roots.append(f_dir)
except Exception:
pass
unique_roots = []
for r in candidate_roots:
if r.is_dir() and r not in unique_roots:
unique_roots.append(r)
def _infer_coop_and_location(file_path: Path) -> tuple[str, str]:
parts = list(file_path.parts)
for i in range(len(parts) - 1, -1, -1):
p = parts[i]
if p in ("output", "weight_and_parquet_data") or re.match(r"^\d{4}-\d{2}-\d{2}$", p):
continue
if p.lower().startswith("predictions_") or p.lower().startswith("cage_day_") or p.lower().startswith("curation_"):
continue
if re.match(r"^[Ll]\d+$", p) and i > 0:
parent_part = parts[i - 1]
parent_coop = get_coop_for_location(parent_part)
return parent_coop, f"{parent_coop}-{p.upper()}"
loc = p
coop = get_coop_for_location(loc)
return coop, loc
return "kandang-atas", "kandang-atas"
def _enrich_records(records: list[dict], file_path: Path) -> list[dict]:
inferred_coop, inferred_loc = _infer_coop_and_location(file_path)
enriched = []
for r in records:
d = dict(r)
loc = str(d.get("location") or inferred_loc or "")
coop = str(d.get("coop") or inferred_coop or (get_coop_for_location(loc) if loc else ""))
d["coop"] = coop
d["location"] = loc
enriched.append(d)
return enriched
# GET /api/weight/coops
if path == "/api/weight/coops":
coops_map: dict[str, dict] = {}
for root in unique_roots:
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
if not date_match:
continue
d_str = date_match.group(1)
inferred_coop, inferred_loc = _infer_coop_and_location(pred_file)
if inferred_coop not in coops_map:
coops_map[inferred_coop] = {
"coop": inferred_coop,
"locations": set(),
"dates": set(),
"latest_date": d_str,
"latest_weight_g": 0.0,
}
coops_map[inferred_coop]["locations"].add(inferred_loc)
coops_map[inferred_coop]["dates"].add(d_str)
if d_str >= coops_map[inferred_coop]["latest_date"]:
coops_map[inferred_coop]["latest_date"] = d_str
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)
fused = df[df["camera_id"] == "FUSED"]
if not fused.empty:
coops_map[inferred_coop]["latest_weight_g"] = float(fused.iloc[0].get("predicted_weight_g", 0.0))
elif not df.empty:
coops_map[inferred_coop]["latest_weight_g"] = float(df.iloc[0].get("predicted_weight_g", 0.0))
except Exception:
pass
coop_list = []
for c_id in sorted(coops_map.keys()):
info = coops_map[c_id]
coop_list.append({
"coop": info["coop"],
"locations": sorted(list(info["locations"])),
"days_count": len(info["dates"]),
"latest_date": info["latest_date"],
"latest_weight_g": round(info["latest_weight_g"], 1),
})
self._send_json({"coops": coop_list, "total_coops": len(coop_list)})
return
# GET /api/weight/coop/<coop_id>
prefix_coop = "/api/weight/coop/"
if path.startswith(prefix_coop):
target_coop = path[len(prefix_coop):].strip().upper()
coop_predictions = []
seen_keys = set()
for root in unique_roots:
for pred_file in sorted(root.rglob("predictions_*.parquet")) + sorted(root.rglob("predictions_*.csv")):
inferred_coop, inferred_loc = _infer_coop_and_location(pred_file)
if inferred_coop.upper() != target_coop:
continue
try:
import pandas as pd
df = pd.read_parquet(pred_file) if pred_file.suffix == ".parquet" else pd.read_csv(pred_file)
records = _enrich_records(df.to_dict(orient="records"), pred_file)
for r in records:
if r.get("coop", "").upper() != target_coop:
continue
if loc_filter and r.get("location", "").upper() != loc_filter.upper():
continue
key = (r.get("date"), r.get("coop"), r.get("location"), r.get("camera_id"))
if key in seen_keys:
continue
seen_keys.add(key)
coop_predictions.append(r)
except Exception:
pass
self._send_json({"coop": target_coop, "predictions": coop_predictions, "total_records": len(coop_predictions)})
return
# GET /api/weight/predictions
if path == "/api/weight/predictions":
all_predictions = []
seen_keys = set()
for root in unique_roots:
for pred_file in sorted(root.rglob("predictions_*.parquet")) + sorted(root.rglob("predictions_*.csv")):
try:
import pandas as pd
df = pd.read_parquet(pred_file) if pred_file.suffix == ".parquet" else pd.read_csv(pred_file)
records = _enrich_records(df.to_dict(orient="records"), pred_file)
for r in records:
if coop_filter and r.get("coop", "").upper() != coop_filter.upper():
continue
if loc_filter and r.get("location", "").upper() != loc_filter.upper():
continue
key = (r.get("date"), r.get("coop"), r.get("location"), r.get("camera_id"))
if key in seen_keys:
continue
seen_keys.add(key)
all_predictions.append(r)
except Exception:
pass
self._send_json({"predictions": all_predictions, "total_records": len(all_predictions)})
return
# GET /api/weight/predictions/<date>
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():
date_predictions = []
seen_keys = set()
for root in unique_roots:
for pred_file in sorted(root.rglob(f"predictions_{target_date}.parquet")) + sorted(root.rglob(f"predictions_{target_date}.csv")):
try:
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
df = pd.read_parquet(pred_file) if pred_file.suffix == ".parquet" else pd.read_csv(pred_file)
records = _enrich_records(df.to_dict(orient="records"), pred_file)
for r in records:
if coop_filter and r.get("coop", "").upper() != coop_filter.upper():
continue
if loc_filter and r.get("location", "").upper() != loc_filter.upper():
continue
key = (r.get("date"), r.get("coop"), r.get("location"), r.get("camera_id"))
if key in seen_keys:
continue
seen_keys.add(key)
date_predictions.append(r)
except Exception:
pass
if date_predictions:
self._send_json({"date": target_date, "records": date_predictions, "total_records": len(date_predictions)})
return
self._send_json({"error": f"No predictions found for date {target_date}"}, status_code=404)
return
# GET /api/weight/features/<date>
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
date_features = []
seen_keys = set()
for root in unique_roots:
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
for feat_file in root.rglob(f"cage_day_features{ext}"):
if target_date not in str(feat_file):
continue
try:
import pandas as pd
df = pd.read_parquet(feat_file) if ext == ".parquet" else pd.read_csv(feat_file)
features = _enrich_records(df.to_dict(orient="records"), feat_file)
for f in features:
if coop_filter and f.get("coop", "").upper() != coop_filter.upper():
continue
if loc_filter and f.get("location", "").upper() != loc_filter.upper():
continue
key = (f.get("date"), f.get("coop"), f.get("location"), f.get("camera_id"))
if key in seen_keys:
continue
seen_keys.add(key)
date_features.append(f)
except Exception:
pass
if date_features:
self._send_json({"date": target_date, "features": date_features, "total_records": len(date_features)})
return
self._send_json({"error": f"No cage features found for date {target_date}"}, status_code=404)
return
# GET /api/weight/curation/<date>/<camera_id> or /<date>/<coop>/<camera_id>
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():
target_date = parts[0]
target_coop = parts[1] if len(parts) >= 3 else coop_filter
target_cam = parts[2] if len(parts) >= 3 else (parts[1] if len(parts) >= 2 else "")
for root in unique_roots:
for cur_file in root.rglob(f"curation_{target_date}_{target_cam}.json"):
inferred_coop, inferred_loc = _infer_coop_and_location(cur_file)
if target_coop and inferred_coop.upper() != target_coop.upper():
continue
cur_file = root / target_date / "output" / f"curation_{target_date}_{target_cam}.json"
if cur_file.is_file():
try:
with open(cur_file, "r", encoding="utf-8") as f:
self._send_json(json.load(f))
cur_data = json.load(f)
if "coop" not in cur_data:
cur_data["coop"] = inferred_coop
if "location" not in cur_data:
cur_data["location"] = inferred_loc
self._send_json(cur_data)
return
self._send_json({"error": f"Curation file not found for {target_date}/{target_cam}"}, status_code=404)
return
except Exception:
pass
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)
+49 -2
View File
@@ -10,7 +10,7 @@ from chicken_counter.batch_discovery import CameraDiscoveryResult, discover_came
from chicken_counter.compress import compress_video_to_target
from chicken_counter.config import BatchSettings, CameraConfig, CameraPreset, build_camera_config_from_batch
from chicken_counter.db_utils import checkpoint_sqlite_wal, get_sqlite_connection, install_shutdown_signal_handlers
from chicken_counter.discovery import resolve_floor_video_dir
from chicken_counter.discovery import get_coop_for_location, resolve_floor_video_dir
from chicken_counter.engine_utils import ensure_compatible_model
from chicken_counter.overlay import draw_overlay
from chicken_counter.pipeline import PipelineArtifacts, _consume_result, _write_stream_frame, build_pipeline, run_pipeline
@@ -727,11 +727,21 @@ def process_and_save_daily_weight_data(
all_cam_obs = curation_stats.get("all_observations") or getattr(p_res, "track_measurements", []) or curated_rows
# Save per-camera detection parquet (all observations with quality flags) & curation summary JSON
run_location = settings.batch.location or ""
run_coop = get_coop_for_location(run_location) if run_location else ""
if all_cam_obs:
save_camera_detections(all_cam_obs, output_dir, date=run_date, camera_id=cam_id)
all_day_observations.extend(all_cam_obs)
if curation_stats:
save_curation_summary(curation_stats, output_dir, date=run_date, camera_id=cam_id)
save_curation_summary(
curation_stats,
output_dir,
date=run_date,
camera_id=cam_id,
location=run_location,
coop=run_coop,
)
# Compute camera aggregate features on clean curated tracks
if curated_rows and cycle_day > 0:
@@ -741,6 +751,8 @@ def process_and_save_daily_weight_data(
date=run_date,
cycle_day=cycle_day,
curation_stats=curation_stats,
location=run_location,
coop=run_coop,
)
camera_aggregates.append(cam_agg)
@@ -755,11 +767,16 @@ def process_and_save_daily_weight_data(
if not camera_aggregates:
return
run_location = settings.batch.location or ""
run_coop = get_coop_for_location(run_location) if run_location else ""
features_list, predictions_list = build_cage_day_features_and_predictions(
camera_aggregates=camera_aggregates,
date=run_date,
cycle_day=cycle_day,
doc_weight_g=getattr(settings.batch, "doc_weight_g", 42.0),
location=run_location,
coop=run_coop,
)
if features_list:
@@ -779,7 +796,37 @@ def process_and_save_daily_weight_data(
for pred in predictions_list:
cid = pred["camera_id"]
if cid == "FUSED":
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 (?, ?, 'FUSED', 0, 0, 0.0, 'fused_flock_weight', '', datetime('now'), ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(date, location, camera_id) DO UPDATE SET
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""",
(
run_date,
settings.batch.location,
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),
))
continue
conn.execute("""UPDATE batch_runs SET
cycle_day = ?,
area_cm2_median = ?,
+31 -1
View File
@@ -6,6 +6,7 @@ from typing import Any
import numpy as np
from chicken_counter.weight.growth_model import predict_chicken_weight
from chicken_counter.discovery import get_coop_for_location
FEATURE_COLUMNS = ["bbox_area_cm2", "width_cm", "height_cm", "minor_axis_cm", "major_axis_cm", "aspect_ratio_cm", "perimeter_cm"]
@@ -50,6 +51,8 @@ def aggregate_camera_features(
date: str,
cycle_day: int,
curation_stats: dict[str, Any] | None = None,
location: str = "",
coop: str = "",
) -> dict[str, Any]:
"""Calculate aggregated distribution metrics for one camera on a given day."""
stats = curation_stats or {}
@@ -61,8 +64,13 @@ def aggregate_camera_features(
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))
if not coop and location:
coop = get_coop_for_location(location)
row: dict[str, Any] = {
"date": str(date),
"coop": str(coop),
"location": str(location),
"cycle_day": int(cycle_day),
"camera_id": str(camera_id),
"detection_count": raw_tracks_count,
@@ -86,6 +94,8 @@ def build_cage_day_features_and_predictions(
date: str,
cycle_day: int,
doc_weight_g: float = 42.0,
location: str = "",
coop: str = "",
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Build multi-camera feature rows (including FUSED row) and generate weight predictions.
@@ -95,7 +105,21 @@ def build_cage_day_features_and_predictions(
if not camera_aggregates:
return [], []
features_list = list(camera_aggregates)
if not location and camera_aggregates:
location = camera_aggregates[0].get("location", "")
if not coop:
coop = camera_aggregates[0].get("coop", "") if camera_aggregates else ""
if not coop and location:
coop = get_coop_for_location(location)
features_list = []
for r in camera_aggregates:
row_copy = dict(r)
if "location" not in row_copy or not row_copy["location"]:
row_copy["location"] = str(location)
if "coop" not in row_copy or not row_copy["coop"]:
row_copy["coop"] = str(coop)
features_list.append(row_copy)
# Multi-camera Fused Row (weighted by detection_count / n_valid_samples)
if len(camera_aggregates) > 1:
@@ -105,6 +129,8 @@ def build_cage_day_features_and_predictions(
fused_row: dict[str, Any] = {
"date": str(date),
"coop": str(coop),
"location": str(location),
"cycle_day": int(cycle_day),
"camera_id": "FUSED",
"detection_count": total_detections,
@@ -142,6 +168,8 @@ def build_cage_day_features_and_predictions(
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)
row_loc = feat_row.get("location", location)
row_coop = feat_row.get("coop", coop)
pred_res = predict_chicken_weight(
cycle_day=cycle_day,
@@ -152,6 +180,8 @@ def build_cage_day_features_and_predictions(
pred_record = {
"date": str(date),
"coop": str(row_coop),
"location": str(row_loc),
"camera_id": str(cam_id),
"cycle_day": int(cycle_day),
"area_cm2_median": float(median_area),
+10
View File
@@ -29,6 +29,8 @@ def save_dataframe_parquet_and_csv(df: pd.DataFrame, base_path: Path) -> tuple[P
DETECTION_PARQUET_COLUMNS = [
"date",
"coop",
"location",
"cycle_day",
"camera_id",
"frame_index",
@@ -94,6 +96,8 @@ def standardize_detection_dataframe(records: list[dict[str, Any]] | pd.DataFrame
# Cast to strict numeric, boolean, and nullable types
type_map = {
"date": "string",
"coop": "string",
"location": "string",
"cycle_day": "int64",
"camera_id": "string",
"frame_index": "int64",
@@ -169,12 +173,18 @@ def save_curation_summary(
output_dir: Path | str,
date: str,
camera_id: str,
location: str = "",
coop: 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"
clean_stats = {k: v for k, v in curation_stats.items() if k != "all_observations"}
if location and "location" not in clean_stats:
clean_stats["location"] = str(location)
if coop and "coop" not in clean_stats:
clean_stats["coop"] = str(coop)
with open(json_path, "w", encoding="utf-8") as f:
json.dump(clean_stats, f, indent=2)
return json_path
+18 -2
View File
@@ -128,7 +128,7 @@ def load_companion_weight_data(report_dir: Path, date: str) -> dict[str, dict]:
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":
if cid:
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))),
@@ -154,7 +154,7 @@ def load_companion_weight_data(report_dir: Path, date: str) -> dict[str, dict]:
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:
if cid 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)),
@@ -212,6 +212,22 @@ def store_report(report_path: str, location: str, db_path: str) -> None:
))
rows += 1
if "FUSED" in weight_data:
w_fused = weight_data["FUSED"]
conn.execute(INSERT_SQL, (
date, location, "FUSED",
0, 0, 0.0, "fused_flock_weight", "", generated_at,
w_fused.get("cycle_day", 0),
w_fused.get("area_cm2_median", 0.0),
w_fused.get("minor_axis_cm_median", 0.0),
w_fused.get("major_axis_cm_median", 0.0),
w_fused.get("predicted_weight_g", 0.0),
w_fused.get("gompertz_baseline_g", 0.0),
w_fused.get("vision_gain_g", 0.0),
w_fused.get("n_weight_samples", 0),
w_fused.get("rejection_rate", 0.0),
))
conn.commit()
# print summary
+187
View File
@@ -0,0 +1,187 @@
"""Unit tests for dashboard REST API weight endpoints, multi-coop handling, and location metadata."""
from __future__ import annotations
import json
import shutil
import tempfile
import threading
import unittest
import urllib.request
from pathlib import Path
import pandas as pd
import sqlite3
import dashboard
from dashboard import DashboardHandler, ThreadingHTTPServer
from chicken_counter.batch_runner import migrate_db_schema
class TestDashboardWeightAPI(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp_dir = Path(tempfile.mkdtemp())
# 1. Create mock multi-coop folder structure
# Coop K1, Floor L1
k1_dir = cls.temp_dir / "VIDEOS" / "cycle7" / "K1" / "L1" / "2026-06-18" / "output"
k1_dir.mkdir(parents=True, exist_ok=True)
k1_preds = [
{"date": "2026-06-18", "coop": "K1", "location": "K1-L1", "camera_id": "CC1", "cycle_day": 27, "predicted_weight_g": 1430.5},
{"date": "2026-06-18", "coop": "K1", "location": "K1-L1", "camera_id": "CC2", "cycle_day": 27, "predicted_weight_g": 1415.2},
{"date": "2026-06-18", "coop": "K1", "location": "K1-L1", "camera_id": "FUSED", "cycle_day": 27, "predicted_weight_g": 1424.2},
]
pd.DataFrame(k1_preds).to_parquet(k1_dir / "predictions_2026-06-18.parquet")
pd.DataFrame(k1_preds).to_parquet(k1_dir / "cage_day_features.parquet")
with open(k1_dir / "curation_2026-06-18_CC1.json", "w") as f:
json.dump({"date": "2026-06-18", "camera_id": "CC1", "raw_tracks": 50, "location": "K1-L1", "coop": "K1"}, f)
# Coop K2, Floor L1 (same date to test collision resolution)
k2_dir = cls.temp_dir / "VIDEOS" / "cycle7" / "K2" / "L1" / "2026-06-18" / "output"
k2_dir.mkdir(parents=True, exist_ok=True)
k2_preds = [
{"date": "2026-06-18", "coop": "K2", "location": "K2-L1", "camera_id": "CC1", "cycle_day": 27, "predicted_weight_g": 1425.0},
{"date": "2026-06-18", "coop": "K2", "location": "K2-L1", "camera_id": "FUSED", "cycle_day": 27, "predicted_weight_g": 1425.0},
]
pd.DataFrame(k2_preds).to_parquet(k2_dir / "predictions_2026-06-18.parquet")
# 2. Setup SQLite DB
db_path = cls.temp_dir / "test_api.db"
conn = sqlite3.connect(db_path)
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-18', 'K1-L1', 'CC1', 1820, 5000, 180.0, 'completed', 'v.mp4', '2026-06-18T12:00', 27, 245.0, 14.0, 22.0, 1430.5, 1390.0, 40.5, 900, 0.03)""")
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-18', 'K2-L1', 'CC1', 1790, 5000, 182.0, 'completed', 'v.mp4', '2026-06-18T12:00', 27, 240.0, 13.8, 21.8, 1425.0, 1390.0, 35.0, 880, 0.04)""")
conn.commit()
conn.close()
dashboard._db_path = str(db_path)
dashboard._weight_candidate_roots = [cls.temp_dir / "VIDEOS"]
# Start HTTP server on dynamic port
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), DashboardHandler)
cls.port = cls.server.server_address[1]
cls.base_url = f"http://127.0.0.1:{cls.port}"
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
cls.thread.start()
@classmethod
def tearDownClass(cls):
dashboard._weight_candidate_roots = []
cls.server.shutdown()
cls.server.server_close()
shutil.rmtree(cls.temp_dir, ignore_errors=True)
def _get(self, endpoint: str) -> dict | list:
url = f"{self.base_url}{endpoint}"
req = urllib.request.Request(url)
with urllib.request.urlopen(req, timeout=5) as resp:
return json.loads(resp.read().decode("utf-8"))
def test_weight_coops_endpoint(self):
"""Test GET /api/weight/coops returns both K1 and K2."""
res = self._get("/api/weight/coops")
self.assertIn("coops", res)
coop_names = [c["coop"] for c in res["coops"]]
self.assertIn("K1", coop_names)
self.assertIn("K2", coop_names)
k1_info = next(c for c in res["coops"] if c["coop"] == "K1")
self.assertIn("K1-L1", k1_info["locations"])
self.assertEqual(k1_info["latest_weight_g"], 1424.2)
def test_weight_coop_endpoint(self):
"""Test GET /api/weight/coop/K1 returns only K1 predictions."""
res = self._get("/api/weight/coop/K1")
self.assertEqual(res["coop"], "K1")
self.assertGreater(res["total_records"], 0)
for r in res["predictions"]:
self.assertEqual(r["coop"], "K1")
def test_weight_predictions_multi_coop_and_filtering(self):
"""Test GET /api/weight/predictions does not drop coops on same date, and supports ?coop= filtering."""
# 1. All predictions across coops
res_all = self._get("/api/weight/predictions")
coops_found = set(r["coop"] for r in res_all["predictions"])
self.assertIn("K1", coops_found)
self.assertIn("K2", coops_found)
# 2. Filter by coop=K1
res_k1 = self._get("/api/weight/predictions?coop=K1")
for r in res_k1["predictions"]:
self.assertEqual(r["coop"], "K1")
self.assertEqual(r["location"], "K1-L1")
# 3. Filter by coop=K2
res_k2 = self._get("/api/weight/predictions?coop=K2")
for r in res_k2["predictions"]:
self.assertEqual(r["coop"], "K2")
self.assertEqual(r["location"], "K2-L1")
def test_weight_predictions_by_date(self):
"""Test GET /api/weight/predictions/2026-06-18 returns records with coop/location and supports filtering."""
res = self._get("/api/weight/predictions/2026-06-18")
self.assertEqual(res["date"], "2026-06-18")
coops_found = set(r["coop"] for r in res["records"])
self.assertIn("K1", coops_found)
self.assertIn("K2", coops_found)
# Filter by coop
res_k1 = self._get("/api/weight/predictions/2026-06-18?coop=K1")
for r in res_k1["records"]:
self.assertEqual(r["coop"], "K1")
def test_weight_features_endpoint(self):
"""Test GET /api/weight/features/2026-06-18 returns features enriched with coop and location."""
res = self._get("/api/weight/features/2026-06-18")
self.assertEqual(res["date"], "2026-06-18")
self.assertGreater(res["total_records"], 0)
self.assertEqual(res["features"][0]["coop"], "K1")
self.assertEqual(res["features"][0]["location"], "K1-L1")
def test_weight_curation_endpoint(self):
"""Test GET /api/weight/curation/2026-06-18/CC1 returns curation JSON with coop and location."""
res = self._get("/api/weight/curation/2026-06-18/CC1?coop=K1")
self.assertEqual(res["camera_id"], "CC1")
self.assertEqual(res["coop"], "K1")
self.assertEqual(res["location"], "K1-L1")
def test_db_date_endpoint_contains_weight_and_coop(self):
"""Test GET /api/db/date/2026-06-18 returns predicted_weight_g and coop."""
res = self._get("/api/db/date/2026-06-18")
self.assertEqual(res["date"], "2026-06-18")
self.assertEqual(len(res["cameras"]), 2)
c1 = next(c for c in res["cameras"] if c["location"] == "K1-L1")
self.assertEqual(c1["coop"], "K1")
self.assertEqual(c1["camera_id"], "CC1")
self.assertEqual(c1["predicted_weight_g"], 1430.5)
c2 = next(c for c in res["cameras"] if c["location"] == "K2-L1")
self.assertEqual(c2["coop"], "K2")
self.assertEqual(c2["camera_id"], "CC1")
self.assertEqual(c2["predicted_weight_g"], 1425.0)
def test_db_location_endpoint_contains_coop(self):
"""Test GET /api/db/location/K1-L1 returns coop and avg_weight_g."""
res = self._get("/api/db/location/K1-L1")
self.assertEqual(res["location"], "K1-L1")
self.assertEqual(res["coop"], "K1")
self.assertIn("avg_weight_g", res["summary"])
self.assertEqual(res["summary"]["avg_weight_g"], 1430.5)
if __name__ == "__main__":
unittest.main()
+91
View File
@@ -552,6 +552,97 @@ class TestWeightEstimation(unittest.TestCase):
self.assertEqual(cell_d36.value, 36)
self.assertEqual(cell_d36.fill.start_color.rgb, "00FCE4D6")
def test_weight_prediction_location_and_coop_metadata(self):
"""Test build_cage_day_features_and_predictions preserves and infers coop and location."""
cam1_agg = aggregate_camera_features([], "CC1", "2026-06-18", cycle_day=27, location="K1-L1", coop="K1")
self.assertEqual(cam1_agg["location"], "K1-L1")
self.assertEqual(cam1_agg["coop"], "K1")
# Auto-infer coop from location K2-L2
cam2_agg = aggregate_camera_features([], "CC2", "2026-06-18", cycle_day=27, location="K2-L2")
self.assertEqual(cam2_agg["location"], "K2-L2")
self.assertEqual(cam2_agg["coop"], "K2")
features_list, predictions_list = build_cage_day_features_and_predictions(
[cam1_agg], date="2026-06-18", cycle_day=27, location="K1-L1"
)
self.assertGreater(len(predictions_list), 0)
self.assertEqual(predictions_list[0]["coop"], "K1")
self.assertEqual(predictions_list[0]["location"], "K1-L1")
self.assertEqual(predictions_list[0]["camera_id"], "CC1")
def test_curation_summary_with_location_and_coop(self):
"""Test save_curation_summary saves location and coop to curation JSON."""
stats = {"raw_tracks": 10, "rejection_rate": 0.05}
json_path = save_curation_summary(
stats, self.temp_dir, date="2026-06-18", camera_id="CC1", location="K1-L1", coop="K1"
)
self.assertTrue(json_path.is_file())
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
self.assertEqual(data["location"], "K1-L1")
self.assertEqual(data["coop"], "K1")
def test_db_weight_queries_with_coop_and_fused(self):
"""Test SQLite batch_runs stores FUSED and queries return coop and weight."""
import sqlite3
from chicken_counter.batch_runner import migrate_db_schema
from chicken_counter.discovery import get_coop_for_location
db_path = self.temp_dir / "db_weight_test.db"
conn = sqlite3.connect(db_path)
migrate_db_schema(conn)
# Insert CC1 for K1-L1
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-18", "K1-L1", "CC1", 1500, 3000, 120.0,
"completed", "vid.mp4", "2026-06-18T12:00:00",
27, 245.0, 14.0, 22.0, 1430.5, 1390.0, 40.5, 680, 0.04
))
# Insert FUSED for K1-L1
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 (?, ?, 'FUSED', 0, 0, 0.0, 'fused_flock_weight', '', datetime('now'), ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (
"2026-06-18", "K1-L1",
27, 245.0, 14.0, 22.0, 1424.2, 1390.0, 34.2, 2700, 0.04
))
conn.commit()
cursor = conn.execute("""SELECT camera_id, total_entered, frames_processed,
ROUND(elapsed_seconds,1) AS elapsed_seconds, stopped_reason, source_video,
location, 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
FROM batch_runs WHERE date='2026-06-18' ORDER BY location, camera_id""")
col_names = [col[0] for col in cursor.description]
rows = cursor.fetchall()
cameras = []
for r in rows:
d = dict(zip(col_names, r))
d["coop"] = get_coop_for_location(d["location"])
cameras.append(d)
self.assertEqual(len(cameras), 2)
cc1 = next(c for c in cameras if c["camera_id"] == "CC1")
self.assertEqual(cc1["coop"], "K1")
self.assertEqual(cc1["location"], "K1-L1")
self.assertEqual(cc1["predicted_weight_g"], 1430.5)
fused = next(c for c in cameras if c["camera_id"] == "FUSED")
self.assertEqual(fused["coop"], "K1")
self.assertEqual(fused["location"], "K1-L1")
self.assertEqual(fused["predicted_weight_g"], 1424.2)
conn.close()
if __name__ == "__main__":
unittest.main()