- 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
515 lines
25 KiB
Python
515 lines
25 KiB
Python
#!/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()
|