integrating chicken count, weighing, dashboard - fix

This commit is contained in:
andrew committed 2026-10-20 16:10:37 +07:00
1 parent 631b3ea1da
commit c58b74b387
4 files changed
+162 -2

No files matched your search

+9 -1
View File
@@ -225,7 +225,15 @@ output/
*.log
*.db-shm
*.db-wal
*backup*.db
*.db-journal
*.sqlite3-journal
*.sqlite-journal
*backup*.db*
*.bak
*.bak*
*.backup
*.db.bak*
*.db.backup*
*.2026*
.vscode/
configs/config_backup_folder/
+1 -1
View File
@@ -165,7 +165,7 @@ def _calc_cycle_info(target_date_str: str) -> dict:
start_d = date_type.fromisoformat(str(_cycle_start_date))
run_d = date_type.fromisoformat(str(target_date_str))
c_day = (run_d - start_d).days
stage = "early_cycle" if 0 <= c_day <= 15 else ("mid_cycle" if c_day >= 16 else "pre_cycle")
stage = "early_cycle" if 0 <= c_day <= 11 else ("mid_cycle" if 12 <= c_day <= 15 else ("late_cycle" if c_day >= 16 else "pre_cycle"))
return {"cycle_day": c_day, "stage": stage}
except Exception:
return {}
@@ -0,0 +1,45 @@
# Plan: counting deferral + dead-key removal + GBM enable + day-27 test run
Branch: `feat/weight-and-growth-analytics`. BASE: 2f77822.
## Global constraints
- Test command: `PYTHONPATH=src python3 -m unittest discover -s tests -p "test_*.py"` (from repo root). `python3 -m unittest tests.<mod>` does NOT work (no tests/__init__.py). No pytest.
- Baseline (pre-change): 83 tests, exactly 2 pre-existing problems — FAIL `test_aggregation_and_multi_camera_fusion` (line 174 `39+59` never updated for allowed_cameras default), ERROR `test_consolidate_full_cycle_datasets`. After changes the suite must have no NEW failures beyond what Task 2 intentionally fixes (174/179).
- Do not flip `predict_chicken_weight` default `use_gbm` (tests assert default-off). GBM enabled only at the aggregation call site.
- No comments in code unless the file already documents the same spot; preserve existing style.
- User already edited `stages.early_cycle.detection.iou: 0.85` in production YAML — do not revert.
## Task 1: config cleanup (YAML + config.py + config tests)
1. `configs/cycle7_batch_optimized.yaml`:
- Delete the ENTIRE `counting:` block (the `# Decoupled Counting Configuration` header comment through `track_buffer: 90`, currently lines 28-36). The section becomes a placeholder: its only remaining key duplicated `defaults.tracker.track_buffer: 90`; loader treats section as optional (`if "counting" in raw`).
- In `weighing:` remove line `min_track_observations: 5` and line `min_flock_uniformity_pct: 70.0` (under anomaly_curation). Keep every other weighing key.
2. `src/chicken_counter/config.py`:
- `CountingConfig`: `detection` default_factory → `{}`; `tracker` default_factory → `{}`; delete `roi_polygon` field.
- `WeighingConfig`: delete `min_track_observations` field; remove `"min_flock_uniformity_pct": 70.0` from `anomaly_curation` default_factory.
- Update the stale comment at the `_task_layer` counting branch (line ~423, mentions counting.roi_polygon declined) to reflect section now fully defers.
3. `tests/test_batch_task_config.py`:
- `test_production_yaml_sections_parsed` (lines 64-66): replace `counting.detection["iou"] == 0.55` / `min_box_area_px == 2500` asserts with `settings.batch.counting.detection == {}` and `settings.batch.counting.tracker == {}`.
- Add effective-value assertions proving deferral via `build_camera_config_from_batch(settings, "CC1", source=..., output_path=None, checkpoint_dir=..., date="2026-10-12")`-style calls (day 27 = mid stage): CC1 conf 0.35, min_box 2500; CC2 conf 0.50; and day-0 stage wins (conf 0.10, iou 0.85, min_box 50). Import exists or add it. Note per-camera keys: CC1 detection {min_box 2500, conf 0.35}, CC2 {conf 0.50}, CC3/CC4 none → defaults conf 0.40 min_box 3000.
- Custom minimal-YAML tests must keep passing untouched (they set counting keys explicitly — still valid because dataclass fields remain).
4. Run full suite. Must be baseline (83 tests, same 1 FAIL + 1 ERROR).
## Task 2: GBM enable + weight tests
1. `src/chicken_counter/weight/aggregation.py` (~line 208): add `use_gbm=True` to the `predict_chicken_weight(...)` call inside `build_cage_day_features_and_predictions`. Nothing else: no features_dict (measured identical output), no model_path threading (YAML == DEFAULT_GBM_MODEL_PATH).
2. `tests/test_weight_estimation.py`:
- line 174: `assertEqual(fused_feat["n_valid_samples"], 39 + 59)` → `59` (allowed_cameras default ["CC2","CC3"] filters CC1 out; CC2 has 59 tracks) — fixes pre-existing failure.
- line 179: `assertGreater(fused_pred["predicted_weight_g"], 1800.0)` → GBM day-27 = 1240.9; replace with `self.assertTrue(fused_pred["gbm_model_used"])` and `self.assertGreater(fused_pred["predicted_weight_g"], 1000.0)`.
3. Run full suite. Expected: 83 tests, only ERROR `test_consolidate_full_cycle_datasets` remains (the 174/179 fail becomes passing).
## Task 3: verification (controller-run)
- Full suite before/after diff vs baseline.
- Config smoke: load production YAML, print effective detection (conf/iou/min_box) for CC1-CC4 on day 0 and day 27.
- GBM smoke: `build_cage_day_features_and_predictions` returns `gbm_model_used=True`.
## Task 4: day-27 test run + report (subagent)
- Day 27 = 2026-06-18 under cycle_start 2026-05-22 (matches DB history: 2026-06-18|27).
- First backup DB: `cp db/chicken_counts.db db/chicken_counts_backup_<timestamp>.db` (existing pattern in db/).
- Run (videos ON, single pass, both tasks):
`PYTHONPATH=src python3 -m chicken_counter.cli batch --config configs/cycle7_batch_optimized.yaml --date 2026-06-18 --cycle-start-date 2026-05-22 --task all`
Long-running: use a generous timeout; poll if backgrounded.
- Ruling: `--task all` skips task-layer (counting section is empty now anyway; weight conf = per-camera instead of flat 0.50) — accepted for a test run; production scripts still use `--task count` / `--task weight`.
- Report: per-camera counts from output JSONs, predicted weights (gbm_model_used, vs prior DB values for 2026-06-18), vis video paths + sizes, suite re-run clean.
@@ -0,0 +1,107 @@
# Footage Source Absolute Path + Date Mapping + SIM Location Fix Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Production footage resolves from `FULL_Cycle_Kandang_Atas_Test` with a persisted date→date mapping so daily jobs run without new recordings; SIM writes stop colliding with production DB rows.
**Architecture:** `root_dir` set to absolute path (no-op today, explicit); new resolver in `discovery.py` picks identity folder if it has videos, else mapped source folder from `configs/date_mappings.yaml` — **outputs always land in processing-date folder, source folder never receives symlinks/outputs** (preserves prior no-leak guard). SIM location isolated via one config line.
**Tech Stack:** Python 3, PyYAML, sqlite3, unittest (`PYTHONPATH=src python3 -m unittest discover -s tests -p "test_*.py"`).
**Spec:** user decisions 2026-10-09 (mapped footage resolution; `configs/date_mappings.yaml` storage; video deletion + DB relabel in scope).
## Global Constraints
- Test command: `PYTHONPATH=src python3 -m unittest discover -s tests -p "test_*.py"` — baseline 83 tests, 0 FAIL, 1 pre-existing ERROR `test_consolidate_full_cycle_datasets`.
- No new dependencies.
- Footage root: `/home/asus/Project_FOLDER/.Codes/VIDEOS/cycle7/FULL_Cycle_Kandang_Atas_Test`.
- Mapping math must match `sim_map.sh:19-21`: epoch 2026-10-01, source start 2026-05-22, cycle 49 days. Spot-check: `2026-10-10 → 2026-05-31`, `2026-10-09 → 2026-05-30`.
- SIM location must become `K1-L1-SIM`; production stays `K1-L1`.
- Resolver interface: `resolve_mapped_video_dir(floor_root: Path, run_date: str, mappings_path: Path | None = None) -> Path`.
- Outputs (report/parquet) always under `floor_root / run_date / output`; source folder never modified.
- Destructive ops (Task 2 SQL, Task 3 rm) explicitly pre-approved by user.
- No pushes; end with commit + push command for user.
## Review Focus
1. Identity beats mapping when real footage exists — test: `tests/test_mapped_footage.py::test_identity_wins_over_mapping`.
2. Broken/missing mappings file never crashes job (skip-as-today) — tests: `test_missing_mappings_file_falls_back`, `test_missing_entry_falls_back`.
3. SIM can never write `location='K1-L1'` again — test: `tests/test_configs.py::test_sim_location_isolated`.
4. Outputs only in processing-date folder; source folder untouched — Task 7 smoke checks (unit cannot pin wiring).
5. YAML unquoted date keys normalize — test: `test_unquoted_date_key_resolves`.
---
### Task 1: Config fixes + invariant pin
**Files:**
- Modify: `configs/cycle7_batch_optimized.yaml:5`
- Modify: `configs/floor_config/K1-L1.yaml:6`
- Create: `tests/test_configs.py`
**Interfaces:**
- Produces: `location: "K1-L1-SIM"` in floor config; absolute `root_dir` in production config. Later tasks rely on these values.
- [ ] Step 1: Write failing test `tests/test_configs.py` (invariant: floor location `== "K1-L1-SIM"` and `!=` production location; production root_dir `== /home/asus/Project_FOLDER/.Codes/VIDEOS/cycle7/FULL_Cycle_Kandang_Atas_Test`).
- [ ] Step 2: Run test, expect FAIL.
- [ ] Step 3: Edit both yaml lines.
- [ ] Step 4: Run test, expect PASS; run full suite (83+new, 0 FAIL, 1 pre-existing ERROR).
- [ ] Step 5: Commit `fix: isolate SIM location and pin absolute footage root`.
### Task 2: One-time DB relabel (ops, no commit)
- [ ] SELECT rows for 2026-10-08/09, confirm SIM values (6662/4593/4904/6622 pattern).
- [ ] `UPDATE batch_runs SET location='K1-L1-SIM' WHERE date IN ('2026-10-08','2026-10-09');`
- [ ] Verify zero `K1-L1` rows remain for those dates; extend date list only if other dates hold SIM values.
### Task 3: Delete generated videos (ops, no commit, pre-approved)
- [ ] `rm ../VIDEOS/cycle7/K1-L1/2026-06-18/output/CC{1..4}_vis.mp4 ../VIDEOS/cycle7/K1-L1/2026-06-18/output/CC{1..4}_compressed.mp4`
- [ ] `rm ../VIDEOS/cycle7/kandang-atas/2026-06-18/output/CC1_vis.mp4`
- [ ] Verify output dirs empty, raw mp4s intact, ~9.7GB reclaimed.
### Task 4: Mapping generator + generated file
**Files:**
- Create: `scripts/generate_date_mappings.py`
- Create: `configs/date_mappings.yaml` (generated)
**Interfaces:**
- Consumes: mapping math from `sim_map.sh:19-21`.
- Produces: `configs/date_mappings.yaml` flat map `'<processing_date>': '<source_date>'` (quoted keys/values), range 2026-10-01…2026-11-18.
- [ ] Step 1: Write generator (epoch 2026-10-01, src 2026-05-22, cycle 49, quoted string keys).
- [ ] Step 2: Run it; spot-check `2026-10-10: '2026-05-31'`, `2026-10-09: '2026-05-30'`, 49 entries.
- [ ] Step 3: Commit both files `feat: add date mapping generator and mappings`.
### Task 5: Resolver + unit tests
**Files:**
- Modify: `src/chicken_counter/discovery.py`
- Create: `tests/test_mapped_footage.py`
**Interfaces:**
- Produces: `resolve_mapped_video_dir(floor_root: Path, run_date: str, mappings_path: Path | None = None) -> Path`. Default mappings path `PROJECT_ROOT / "configs/date_mappings.yaml"`.
Algorithm: (1) `day_dir = floor_root / run_date`; any `.mp4` in it → return `day_dir`. (2) load mappings via `yaml.safe_load`; missing/None → `day_dir`; normalize non-str keys via `.isoformat()`. (3) entry hit and `floor_root / mapped` `.is_dir()` → return it. (4) else `day_dir`.
- [ ] Step 1: Write failing tests: identity wins; mapping resolves; no entry → day; no file → day; missing source dir → day; unquoted date key resolves.
- [ ] Step 2: Run, expect FAIL.
- [ ] Step 3: Implement resolver in `discovery.py`.
- [ ] Step 4: Tests PASS; full suite green.
- [ ] Step 5: Commit `feat: resolve footage via persisted date mapping`.
### Task 6: Wire 3 batch_runner sites
**Files:**
- Modify: `src/chicken_counter/batch_runner.py:256-277`, `:498-519`, `:993-1017`
- [ ] Step 1: At each site after `day_dir = floor_root / run_date`: `video_dir = resolve_mapped_video_dir(floor_root, run_date)`; `discover_camera_videos(video_dir, settings, allow_empty=True)`; print `video_dir`; `output_dir` stays on `day_dir`.
- [ ] Step 2: Grep verify: no remaining `discover_camera_videos(day_dir`.
- [ ] Step 3: Full suite green (83+new, 0 FAIL, 1 pre-existing ERROR).
- [ ] Step 4: Commit `feat: wire mapped footage resolution into batch runs`.
### Task 7: End-to-end smoke (ops)
- [ ] `PYTHONPATH=src python3 -m chicken_counter batch --config configs/cycle7_batch_optimized.yaml --date 2026-10-10 --task count --no-video`
- [ ] Verify: input shows `.../2026-05-31`; reports under `FULL_Cycle_Kandang_Atas_Test/2026-10-10/output/`; no files created inside `2026-05-31/` (mtime); `batch_runs` row `2026-10-10/K1-L1` exists; no SIM-location rows for 2026-10-10.