""" Unified comparison script for HVAC unit detection models. INPUT: Each model writes a JSON file with this format: { "model": "model_name", "page_id": "cellar_p002", # or per-page key "detections": [ {"x1": int, "y1": int, "x2": int, "y2": int, "class": "ceiling_ducted" | "wall_mounted", "label": "AC-P" | "AC-T" | ... | null, "confidence": float} ] } GOLD format (one JSON per page): { "page_id": "cellar_p002", "image_width": int, "image_height": int, "gold": [ {"x1": int, "y1": int, "x2": int, "y2": int, "class": "ceiling_ducted" | "wall_mounted", "label": "AC-P" | null} ] } OUTPUT: comparison_report.md + comparison_report.json with: - Per-model summary (mean_iou, recall@0.5, recall@0.1, class_accuracy, etc.) - Per-page breakdown - Side-by-side table """ from __future__ import annotations import argparse import json from collections import defaultdict from pathlib import Path def iou(a: dict, b: dict) -> float: """IoU between two boxes in {x1,y1,x2,y2} format.""" ax1, ay1, ax2, ay2 = a["x1"], a["y1"], a["x2"], a["y2"] bx1, by1, bx2, by2 = b["x1"], b["y1"], b["x2"], b["y2"] ix1, iy1 = max(ax1, bx1), max(ay1, by1) ix2, iy2 = min(ax2, bx2), min(ay2, by2) inter = max(0, ix2 - ix1) * max(0, iy2 - iy1) a_area = (ax2 - ax1) * (ay2 - ay1) b_area = (bx2 - bx1) * (by2 - by1) union = a_area + b_area - inter return inter / union if union else 0.0 def match_gold_to_dets(gold: list[dict], dets: list[dict]) -> list[dict]: """Greedy match: each gold gets the best remaining detection by IoU.""" used = set() matches = [] for gi, g in enumerate(gold): best_i, best_s = None, 0.0 for di, d in enumerate(dets): if di in used: continue s = iou(g, d) if s > best_s: best_i, best_s = di, s if best_i is not None and best_s > 0: used.add(best_i) matches.append({ "gold_idx": gi, "gold_class": g.get("class"), "gold_label": g.get("label"), "iou": round(best_s, 3), "matched_det_idx": best_i, "matched_class": dets[best_i].get("class") if best_i is not None else None, "matched_label": dets[best_i].get("label") if best_i is not None else None, }) return matches def score_page(gold: list[dict], dets: list[dict]) -> dict: """Compute all metrics for one page.""" if not gold: return { "gold_count": 0, "det_count": len(dets), "mean_iou": 0, "recall_05": 0, "recall_01": 0, "class_correct": 0, "label_correct": 0, "false_positives": len(dets), "matches": [], } matches = match_gold_to_dets(gold, dets) n = len(matches) hits_05 = sum(1 for m in matches if m["iou"] >= 0.5) hits_01 = sum(1 for m in matches if m["iou"] >= 0.1) class_correct = sum(1 for m in matches if m["iou"] >= 0.1 and m["matched_class"] == m["gold_class"]) label_correct = sum(1 for m in matches if m["iou"] >= 0.1 and m["matched_label"] and m["matched_label"] == m["gold_label"]) matched_det_count = sum(1 for m in matches if m["matched_det_idx"] is not None) false_positives = max(0, len(dets) - matched_det_count) return { "gold_count": n, "det_count": len(dets), "mean_iou": round(sum(m["iou"] for m in matches) / n, 3), "recall_05": round(hits_05 / n, 3), "recall_01": round(hits_01 / n, 3), "class_accuracy": round(class_correct / n, 3), "label_accuracy": round(label_correct / n, 3) if any(m["gold_label"] for m in matches) else None, "false_positives": false_positives, "precision_01": round(hits_01 / max(1, len(dets)), 3), "matches": matches, } def aggregate_pages(per_page: dict[str, dict]) -> dict: """Average metrics across pages (weighted by gold_count).""" total_gold = sum(p["gold_count"] for p in per_page.values()) total_dets = sum(p["det_count"] for p in per_page.values()) if total_gold == 0: return {"pages": len(per_page), "gold_count": 0} weighted = lambda k: round( sum(p[k] * p["gold_count"] for p in per_page.values()) / total_gold, 3 ) return { "pages": len(per_page), "gold_count": total_gold, "det_count": total_dets, "mean_iou": weighted("mean_iou"), "recall_05": weighted("recall_05"), "recall_01": weighted("recall_01"), "class_accuracy": weighted("class_accuracy"), "false_positives_total": sum(p["false_positives"] for p in per_page.values()), } def load_jsonl_or_json(path: Path) -> list[dict]: """Load model outputs. Supports single JSON dict, list, or JSONL (one per page).""" text = path.read_text() text = text.strip() if text.startswith("["): return json.loads(text) if "\n" in text and text.lstrip().startswith("{"): # Try JSONL try: return [json.loads(line) for line in text.splitlines() if line.strip()] except json.JSONDecodeError: pass obj = json.loads(text) if isinstance(obj, dict) and "detections" in obj: return [obj] return obj if isinstance(obj, list) else [obj] def build_report(model_outputs: dict[str, list[dict]], gold_pages: dict[str, dict]) -> dict: """Build full comparison report. model_outputs: {model_name: [{page_id, detections}, ...]} gold_pages: {page_id: {gold: [...], image_width, image_height}} """ report = {"models": {}, "page_ids": sorted(gold_pages.keys())} for model_name, outputs in model_outputs.items(): # Index outputs by page_id by_page = {o["page_id"]: o["detections"] for o in outputs} per_page_scores = {} for page_id, page_gold in gold_pages.items(): dets = by_page.get(page_id, []) per_page_scores[page_id] = score_page(page_gold["gold"], dets) report["models"][model_name] = { "per_page": per_page_scores, "overall": aggregate_pages(per_page_scores), } return report def render_markdown(report: dict) -> str: """Render comparison report as markdown table.""" lines = ["# Model Comparison Report\n"] lines.append(f"Pages evaluated: {len(report['page_ids'])}") lines.append(f"Pages: {', '.join(report['page_ids'])}\n") # Overall summary table lines.append("## Overall (weighted by gold count)\n") cols = ["model", "gold", "dets", "mean_iou", "recall@0.5", "recall@0.1", "class_acc", "false_pos"] lines.append("| " + " | ".join(cols) + " |") lines.append("| " + " | ".join("---" for _ in cols) + " |") sortable = [] for name, data in report["models"].items(): o = data["overall"] sortable.append((o.get("mean_iou", 0), name, o)) for mean_iou, name, o in sorted(sortable, reverse=True): row = [name, str(o.get("gold_count", 0)), str(o.get("det_count", 0)), f"{o.get('mean_iou', 0):.3f}", f"{o.get('recall_05', 0):.3f}", f"{o.get('recall_01', 0):.3f}", f"{o.get('class_accuracy', 0):.3f}", str(o.get("false_positives_total", 0))] lines.append("| " + " | ".join(row) + " |") # Per-page breakdown lines.append("\n## Per-page breakdown\n") for page_id in report["page_ids"]: lines.append(f"\n### {page_id}\n") cols = ["model", "gold", "dets", "iou", "recall@0.5", "recall@0.1", "class_acc", "FP"] lines.append("| " + " | ".join(cols) + " |") lines.append("| " + " | ".join("---" for _ in cols) + " |") page_sortable = [] for name, data in report["models"].items(): p = data["per_page"].get(page_id, {}) page_sortable.append((p.get("mean_iou", 0), name, p)) for mean_iou, name, p in sorted(page_sortable, reverse=True): row = [name, str(p.get("gold_count", 0)), str(p.get("det_count", 0)), f"{p.get('mean_iou', 0):.3f}", f"{p.get('recall_05', 0):.3f}", f"{p.get('recall_01', 0):.3f}", f"{p.get('class_accuracy', 0):.3f}", str(p.get("false_positives", 0))] lines.append("| " + " | ".join(row) + " |") # Winner best = max(report["models"].items(), key=lambda kv: kv[1]["overall"].get("mean_iou", 0)) lines.append(f"\n## Winner: {best[0]} (mean IoU {best[1]['overall'].get('mean_iou', 0):.3f})") return "\n".join(lines) def main(): parser = argparse.ArgumentParser() parser.add_argument("--gold", required=True, help="Path to gold JSON (single file or directory of per-page files)") parser.add_argument("--predictions", nargs="+", required=True, help="Model name and path pairs, e.g. yolo=outputs/yolo.json florence=outputs/florence.json") parser.add_argument("--output", default="comparison_report", help="Output basename (no extension)") args = parser.parse_args() # Load gold gold_path = Path(args.gold) if gold_path.is_dir(): gold_pages = {} for gf in gold_path.glob("*.json"): obj = json.loads(gf.read_text()) gold_pages[obj["page_id"]] = obj else: obj = json.loads(gold_path.read_text()) if isinstance(obj, list): gold_pages = {p["page_id"]: p for p in obj} else: gold_pages = {obj["page_id"]: obj} # Load predictions model_outputs = {} for pred in args.predictions: if "=" not in pred: raise ValueError(f"Use model_name=path/to/file.json format. Got: {pred}") name, path = pred.split("=", 1) model_outputs[name] = load_jsonl_or_json(Path(path)) # Build report report = build_report(model_outputs, gold_pages) # Save out_json = Path(args.output + ".json") out_md = Path(args.output + ".md") out_json.write_text(json.dumps(report, indent=2)) out_md.write_text(render_markdown(report)) print(f"Report written: {out_md}") print(f"JSON written: {out_json}") print() print(render_markdown(report)) if __name__ == "__main__": main()