""" Compare multiple vision models for detecting ALL HVAC indoor units in the cellar floor plan. Tiles the full PDF page into 2700×2700 crops, runs each model on every tile, aggregates detections back to full-page pixel coordinates, and generates: - per-model full-page overlay PNG - summary.json with detection counts and (optionally) IoU scores vs gold boxes - side-by-side comparison PNG Usage: python run_cellar_allunits_compare.py \\ --model gemini:gemini-2.5-pro:8192 \\ --model gemini:gemini-2.5-flash:8192 \\ --model openrouter:openai/gpt-4o:1024 \\ --model "openrouter:anthropic/claude-sonnet-4-5:1024" \\ --model "featherless:DavidAU/Gemma3-27B-it-vl-GLM-4.7-Uncensored-Heretic-Deep-Reasoning:4096" \\ [--gold output_floor_iter/model_compare_acp/gold_allunits.json] """ from __future__ import annotations import argparse import base64 import json import os import re from io import BytesIO from pathlib import Path from typing import Any import fitz from dotenv import load_dotenv from google import genai from google.genai import types as genai_types from openai import OpenAI from PIL import Image, ImageDraw, ImageFont ROOT = Path(__file__).resolve().parent.parent DEFAULT_PDF = ROOT / "raw_pdfs" / "355 E 86th St Mechanical 100% CD Set_flattened.pdf" DEFAULT_OUT = Path(__file__).resolve().parent / "output_floor_iter" / "cellar_allunits_compare" # Tiles (tx, ty) in full-image pixels at 300 DPI. # Covers the drawing area where units appear. DEFAULT_TILES = [ (0, 0), (2700, 0), (5400, 0), (8100, 0), (0, 2700), (2700, 2700), (5400, 2700), (8100, 2700), (0, 5400), (2700, 5400), (5400, 5400), (8100, 5400), (0, 8100), (2700, 8100), ] TILE_SIZE = 2700 ALL_UNIT_PROMPT = ( "You are analyzing a mechanical HVAC blueprint tile.\n\n" "Find every HVAC indoor unit visible in this tile. A valid unit has ALL of:\n" " - A text label such as AC-P, AC-Q, AC-S, AC-T, AC-U, AC-N, AHU-X, or any 'AC-X' code\n" " - A rectangular body with internal detail: hatching, coil marks, fan cross, or connected ductwork\n" " - The label and body clearly belong together (even if the label is rotated or offset slightly)\n\n" "Reject: duct size labels, diffuser circles, schedule tables, legends, and bare pipes.\n\n" "Return a generous box covering both the label AND the complete unit body.\n" "Prefer slightly larger boxes over cutting off any part of the unit.\n\n" "Return ONLY valid JSON, no markdown fences:\n" '{"detections":[{"tag":"AC-P","xmin":N,"ymin":N,"xmax":N,"ymax":N},...]} \n\n' "Coordinates are integers 0-1000 normalized to the image you received.\n" "If no units are visible, return: {\"detections\":[]}" ) # ── rendering ───────────────────────────────────────────────────────────────── def render_page(pdf_path: Path, page_num: int, dpi: int) -> Image.Image: doc = fitz.open(pdf_path) page = doc.load_page(page_num - 1) pix = page.get_pixmap(matrix=fitz.Matrix(dpi / 72, dpi / 72), alpha=False) return Image.frombytes("RGB", [pix.width, pix.height], pix.samples) def encode_png_b64(img: Image.Image, max_px: int) -> tuple[str, float]: w, h = img.size factor = min(1.0, max_px / max(w, h)) if factor < 1: img = img.resize((int(w * factor), int(h * factor)), Image.LANCZOS) buf = BytesIO() img.save(buf, format="PNG") data = base64.b64encode(buf.getvalue()).decode("ascii") return f"data:image/png;base64,{data}", factor # ── API callers ─────────────────────────────────────────────────────────────── def call_gemini(model: str, prompt: str, img: Image.Image, max_px: int, max_tokens: int) -> str: client = genai.Client(api_key=os.environ["GEMINI_API_KEY"]) data_url, _ = encode_png_b64(img, max_px) image_bytes = base64.b64decode(data_url.split(",", 1)[1]) response = client.models.generate_content( model=model, contents=[prompt, genai_types.Part.from_bytes(data=image_bytes, mime_type="image/png")], config=genai_types.GenerateContentConfig(max_output_tokens=max_tokens, temperature=0.0), ) if response.text: return response.text for candidate in response.candidates or []: parts_text = [ p.text for p in (candidate.content.parts or []) if getattr(p, "text", None) and not getattr(p, "thought", False) ] if parts_text: return "\n".join(parts_text) return "" def call_openai_compat(model, prompt, img, max_px, max_tokens, base_url, api_key_env) -> str: client = OpenAI(base_url=base_url, api_key=os.environ[api_key_env]) data_url, _ = encode_png_b64(img, max_px) response = client.chat.completions.create( model=model, messages=[{"role": "user", "content": [ {"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": data_url}}, ]}], temperature=0, max_tokens=max_tokens, ) return response.choices[0].message.content or "" # ── parsing ─────────────────────────────────────────────────────────────────── def parse_json_text(text: str) -> list[dict[str, Any]]: text = text.strip() text = re.sub(r"^```[a-zA-Z]*\n?", "", text) text = re.sub(r"```$", "", text.strip()) start, end = text.find("{"), text.rfind("}") if start >= 0 and end > start: text = text[start: end + 1] return json.loads(text).get("detections", []) def dets_to_page_coords( dets: list[dict], tile_img: Image.Image, tx: int, ty: int ) -> list[dict]: """Convert 0-1000 tile-normalized detections to full-page pixel coords.""" out = [] for d in dets: try: x1 = int(d["xmin"] / 1000 * tile_img.width) + tx y1 = int(d["ymin"] / 1000 * tile_img.height) + ty x2 = int(d["xmax"] / 1000 * tile_img.width) + tx y2 = int(d["ymax"] / 1000 * tile_img.height) + ty except (KeyError, TypeError, ValueError): continue if x2 <= x1 or y2 <= y1: continue out.append({"tag": d.get("tag", "unit"), "x": x1, "y": y1, "w": x2 - x1, "h": y2 - y1}) return out # ── scoring ─────────────────────────────────────────────────────────────────── def iou(a: dict, b: dict) -> float: ax1, ay1 = a["x"], a["y"] ax2, ay2 = ax1 + a["w"], ay1 + a["h"] bx1, by1 = b["x"], b["y"] bx2, by2 = bx1 + b["w"], by1 + b["h"] 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) union = a["w"] * a["h"] + b["w"] * b["h"] - inter return inter / union if union else 0.0 def score_vs_gold(dets: list[dict], gold: list[dict]) -> dict: if not gold: return {"gold_count": 0, "det_count": len(dets), "mean_iou": None, "matches": []} used = set() matches = [] for gi, g in enumerate(gold, 1): 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: used.add(best_i) matches.append({"gold": gi, "iou": round(best_s, 3), "det_index": best_i}) n = len(matches) return { "gold_count": len(gold), "det_count": len(dets), "mean_iou": round(sum(m["iou"] for m in matches) / n, 3), "matches": matches, } # ── visualization ───────────────────────────────────────────────────────────── TAG_COLORS = { "AC-P": (255, 0, 200), "AC-Q": (0, 180, 255), "AC-S": (0, 220, 0), "AC-T": (255, 140, 0), "AC-U": (180, 0, 255), "AC-N": (0, 200, 200), } DEFAULT_DET_COLOR = (255, 80, 80) GOLD_COLOR = (0, 255, 0) def draw_overlay( full_img: Image.Image, dets: list[dict], gold: list[dict], out_path: Path, scale: float = 0.15, ) -> None: thumb_w = int(full_img.width * scale) thumb_h = int(full_img.height * scale) thumb = full_img.resize((thumb_w, thumb_h), Image.LANCZOS) draw = ImageDraw.Draw(thumb) font = ImageFont.load_default() for g in gold: draw.rectangle([ int(g["x"] * scale), int(g["y"] * scale), int((g["x"] + g["w"]) * scale), int((g["y"] + g["h"]) * scale), ], outline=GOLD_COLOR, width=3) for det in dets: color = TAG_COLORS.get(det["tag"], DEFAULT_DET_COLOR) x1, y1 = int(det["x"] * scale), int(det["y"] * scale) x2, y2 = int((det["x"] + det["w"]) * scale), int((det["y"] + det["h"]) * scale) draw.rectangle([x1, y1, x2, y2], outline=color, width=4) draw.text((x1, max(0, y1 - 12)), det["tag"], fill=color, font=font) thumb.save(out_path) def make_comparison_grid(overlay_paths: list[tuple[str, Path]], out_path: Path) -> None: """Tile multiple overlay images side by side with labels.""" imgs = [(label, Image.open(p)) for label, p in overlay_paths if p.exists()] if not imgs: return w, h = imgs[0][1].size n = len(imgs) grid = Image.new("RGB", (w * n, h + 30), (30, 30, 30)) draw = ImageDraw.Draw(grid) font = ImageFont.load_default() for i, (label, img) in enumerate(imgs): grid.paste(img, (i * w, 30)) draw.text((i * w + 5, 5), label[:40], fill=(255, 255, 255), font=font) grid.save(out_path) print(f"Comparison grid saved: {out_path}") # ── model spec parsing ──────────────────────────────────────────────────────── def parse_model_specs(values: list[str]) -> list[tuple[str, str, int | None]]: specs = [] for value in values: parts = value.split(":", 2) if len(parts) < 2: raise ValueError(f"Bad model spec: {value!r} (expected provider:model[:max_tokens])") provider = parts[0].strip().lower() model = parts[1].strip() max_tok = int(parts[2]) if len(parts) == 3 and parts[2].strip().isdigit() else None specs.append((provider, model, max_tok)) return specs # ── main ────────────────────────────────────────────────────────────────────── def run_model_on_tile( provider: str, model: str, tile_img: Image.Image, max_px: int, max_tokens: int ) -> str: if provider == "gemini": return call_gemini(model, ALL_UNIT_PROMPT, tile_img, max_px, max_tokens) elif provider == "openrouter": return call_openai_compat(model, ALL_UNIT_PROMPT, tile_img, max_px, max_tokens, "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY") elif provider == "groq": return call_openai_compat(model, ALL_UNIT_PROMPT, tile_img, max_px, max_tokens, "https://api.groq.com/openai/v1", "GROQ_API_KEY") elif provider == "featherless": return call_openai_compat(model, ALL_UNIT_PROMPT, tile_img, max_px, max_tokens, "https://api.featherless.ai/v1", "FEATHERLESS_API_KEY") else: raise ValueError(f"Unknown provider: {provider}") def main() -> None: load_dotenv(ROOT / ".env") parser = argparse.ArgumentParser() parser.add_argument("--pdf", type=Path, default=DEFAULT_PDF) parser.add_argument("--page", type=int, default=2) parser.add_argument("--dpi", type=int, default=300) parser.add_argument("--max-px", type=int, default=2048) parser.add_argument("--max-tokens", type=int, default=2048) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--gold", type=Path, default=None, help="JSON file from extract_screenshot_gold.py") parser.add_argument("--tile", action="append", default=[], help="tx,ty to include (default: all DEFAULT_TILES). Repeat for multiple.") parser.add_argument("--model", action="append", default=[], help="provider:model[:max_tokens]") args = parser.parse_args() args.out_dir.mkdir(parents=True, exist_ok=True) models = parse_model_specs(args.model or ["gemini:gemini-2.5-flash:8192"]) # Determine tiles if args.tile: tiles = [tuple(int(v) for v in t.split(",")) for t in args.tile] else: tiles = DEFAULT_TILES # Load gold boxes gold: list[dict] = [] if args.gold and args.gold.exists(): gold = json.loads(args.gold.read_text(encoding="utf-8")) print(f"Loaded {len(gold)} gold box(es) from {args.gold}") print(f"Rendering page {args.page} at {args.dpi} DPI...") full_img = render_page(args.pdf, args.page, args.dpi) print(f"Full image: {full_img.width}x{full_img.height}") print(f"Running {len(models)} model(s) on {len(tiles)} tile(s) = {len(models)*len(tiles)} API calls\n") summary = [] overlay_paths: list[tuple[str, Path]] = [] for provider, model, model_max_tok in models: max_tok = model_max_tok if model_max_tok is not None else args.max_tokens safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", f"{provider}_{model}") print(f"=== {provider}:{model} (max_tokens={max_tok}) ===") all_dets: list[dict] = [] tile_log: list[dict] = [] for tx, ty in tiles: # Crop tile x2 = min(tx + TILE_SIZE, full_img.width) y2 = min(ty + TILE_SIZE, full_img.height) tile_img = full_img.crop((tx, ty, x2, y2)) try: raw = run_model_on_tile(provider, model, tile_img, args.max_px, max_tok) parsed = parse_json_text(raw) page_dets = dets_to_page_coords(parsed, tile_img, tx, ty) all_dets.extend(page_dets) tile_log.append({"tile": [tx, ty], "count": len(page_dets)}) print(f" tile ({tx:5},{ty:5}): {len(page_dets):2d} hit(s)") except Exception as exc: tile_log.append({"tile": [tx, ty], "error": str(exc)}) print(f" tile ({tx:5},{ty:5}): ERROR - {exc}") # Save per-model detections det_path = args.out_dir / f"{safe}_detections.json" det_path.write_text(json.dumps({"provider": provider, "model": model, "detections": all_dets}, indent=2), encoding="utf-8") # Score vs gold score = score_vs_gold(all_dets, gold) print(f" Total detections: {len(all_dets)} mean_iou vs gold: {score.get('mean_iou')}") # Overlay visualization overlay_path = args.out_dir / f"{safe}_overlay.png" draw_overlay(full_img, all_dets, gold, overlay_path) overlay_paths.append((f"{provider}:{model}", overlay_path)) summary.append({ "provider": provider, "model": model, "total_dets": len(all_dets), "score": score, "tiles": tile_log, }) print() # Save summary (args.out_dir / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") # Side-by-side comparison grid make_comparison_grid(overlay_paths, args.out_dir / "comparison_grid.png") print(f"\nAll results in: {args.out_dir}") print("\n--- SUMMARY ---") for s in summary: miou = s["score"].get("mean_iou", "n/a") print(f" {s['provider']}:{s['model']:<50} dets={s['total_dets']:3d} mean_iou={miou}") if __name__ == "__main__": main()