""" Test minimal refinement: tweak original prompt slightly for tighter boxes, but keep the generous sizing that worked. The issue with v1 and v2 was over-emphasizing internal detail and symbol-only detection. This version keeps the original generous box approach but adds precision guidance. Usage: python test_minimal_refinement.py --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 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" 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 # Original prompt (baseline) ORIGINAL_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\":[]}" ) # Minimal refinement: just add a bit more precision guidance MINIMAL_REFINEMENT = ( "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 rectangular equipment body with internal detail: hatching, coil marks, fan cross, or connected ductwork\n" " - A nearby text label that matches AC-P, AC-Q, AC-S, AC-T, AC-U, AC-N, or other AC-X codes\n" " - The label and body clearly belong together (even if label is rotated or offset slightly)\n\n" "Quality improvements:\n" " - IMPORTANT: Look for units that have internal mechanical structure (coils, grilles, fans)\n" " - Reject empty rectangles, duct size labels, diffusers, VAV boxes without detail\n" " - Reject: thermostats, dampers, tables, legends, and bare ductwork\n\n" "Bounding box: Return a box covering the complete unit body + label.\n" " - Include the full mechanical equipment symbol\n" " - Include the nearby label\n" " - Avoid excessive padding, but be generous rather than cutting off any part\n\n" "Return ONLY valid JSON, no markdown:\n" '{"detections":[{"tag":"AC-P","xmin":0,"ymin":0,"xmax":600,"ymax":500},...]} \n\n' "Coordinates: integers 0-1000 normalized to this tile image.\n" "If no units: {\"detections\":[]}" ) 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 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 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]: 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").upper(), "x": x1, "y": y1, "w": x2 - x1, "h": y2 - y1, }) return out 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} 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: used.add(best_i) matches.append({"gold": gi, "iou": round(best_s, 3), "hit": best_s >= 0.1}) n = len(matches) hits = sum(1 for m in matches if m["hit"]) mean_iou = round(sum(m["iou"] for m in matches) / n, 3) if n else 0.0 return { "gold_count": len(gold), "det_count": len(dets), "mean_iou": mean_iou, "hits": hits, "matches": matches, } 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 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=4096) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--gold", type=Path, default=None) args = parser.parse_args() args.out_dir.mkdir(parents=True, exist_ok=True) # Verified gold boxes from cellar_refined.log gold: list[dict] = [ {"tag": "AC-P", "x": 7050, "y": 1300, "w": 500, "h": 550}, {"tag": "AC-S", "x": 3970, "y": 2200, "w": 500, "h": 500}, {"tag": "AC-Q", "x": 2530, "y": 2800, "w": 500, "h": 500}, {"tag": "AC-P", "x": 2530, "y": 3650, "w": 900, "h": 650}, {"tag": "AC-P", "x": 2530, "y": 4600, "w": 900, "h": 650}, {"tag": "AC-P", "x": 5750, "y": 4450, "w": 700, "h": 500}, {"tag": "AC-T", "x": 1800, "y": 6050, "w": 500, "h": 500}, {"tag": "AC-T", "x": 3300, "y": 7220, "w": 500, "h": 500}, {"tag": "AC-U", "x": 6600, "y": 6950, "w": 500, "h": 500}, {"tag": "AC-U", "x": 9050, "y": 7310, "w": 500, "h": 500}, {"tag": "AC-T", "x": 8300, "y": 5700, "w": 500, "h": 500}, {"tag": "AC-T", "x": 9600, "y": 6200, "w": 500, "h": 500}, {"tag": "unit", "x": 8200, "y": 400, "w": 600, "h": 600}, ] print(f"Using verified gold boxes: {len(gold)} boxes from cellar_refined.log") 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}\n") results = [] # Test both prompts for comparison for name, prompt in [("ORIGINAL", ORIGINAL_PROMPT), ("MINIMAL_REFINEMENT", MINIMAL_REFINEMENT)]: print(f"=== {name} ===") all_dets: list[dict] = [] for tx, ty in DEFAULT_TILES: 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 = call_gemini("gemini-2.5-flash", prompt, tile_img, args.max_px, args.max_tokens) parsed = parse_json_text(raw) page_dets = dets_to_page_coords(parsed, tile_img, tx, ty) all_dets.extend(page_dets) if len(page_dets) > 0: print(f" tile ({tx:5},{ty:5}): {len(page_dets):2d} det(s)") except Exception as exc: print(f" tile ({tx:5},{ty:5}): ERROR - {exc}") score = score_vs_gold(all_dets, gold) print(f" Total: {len(all_dets)} dets Mean IoU: {score.get('mean_iou')} Hits: {score.get('hits')}/{len(gold)}\n") results.append((name, all_dets, score)) # Save det_path = args.out_dir / f"gemini_2.5-flash_{name.lower()}_detections.json" det_path.write_text(json.dumps({"prompt": name, "detections": all_dets}, indent=2), encoding="utf-8") overlay_path = args.out_dir / f"gemini_2.5-flash_{name.lower()}_overlay.png" draw_overlay(full_img, all_dets, gold, overlay_path) # Summary print("=== COMPARISON ===") for name, dets, score in results: print(f" {name:25s} dets={len(dets):3d} mean_iou={score.get('mean_iou', 'n/a')} hits={score.get('hits', 0)}/{len(gold)}") if __name__ == "__main__": main()