""" Test the refined detection prompt with Gemini 2.5 Flash on the full cellar. Compares refined prompt (symbol-first, tight boxes, detail requirement) vs original. Usage: python test_refined_prompt.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" # Tiles (tx, ty) in full-image pixels at 300 DPI. 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 (for comparison) 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\":[]}" ) # Refined prompt with all improvements REFINED_PROMPT = ( "You are analyzing a TILE (cropped section) of a mechanical HVAC floor plan PDF.\n\n" "TASK: Detect ONLY real HVAC indoor unit equipment symbols whose nearby label\n" "matches one of the schedule tags (AC-P, AC-Q, AC-S, AC-T, AC-U, AC-N).\n\n" "CRITICAL: Detection must be SYMBOL-FIRST, not text-first.\n" " 1. FIRST locate mechanically detailed rectangular equipment symbols\n" " 2. VERIFY dense internal mechanical detail exists\n" " 3. VERIFY duct/piping connectivity\n" " 4. THEN verify nearby label matches\n" " 5. Return detection ONLY if ALL conditions satisfied\n\n" "=== REQUIRED CHARACTERISTICS ===\n\n" "1. EQUIPMENT BODY\n" " - Rectangular or square mechanical equipment symbol\n" " - Medium-to-large size relative to nearby duct annotations\n" " - Visually darker/heavier weight than surrounding text\n\n" "2. INTERNAL MECHANICAL DETAIL (REQUIRED)\n" " Must contain DENSE internal detail such as:\n" " - Repeated parallel bars / grille lines\n" " - Coil fin patterns\n" " - Fan cross-hatching or circular fan symbol\n" " - Stacked dark parallel lines\n" " - Segmented internal compartments\n" " - Equipment coil structure\n\n" " Detail must occupy 30-60% of the equipment symbol's interior.\n" " Empty rectangles or sparse detail are NOT valid indoor units.\n\n" "3. HVAC CONNECTIVITY\n" " Equipment must be mechanically connected to HVAC infrastructure:\n" " - Attached inline to rectangular ductwork\n" " - Connected to duct branches or trunks\n" " - Connected to refrigerant piping\n" " - Integrated into duct network (not floating independently)\n\n" "4. MATCHING EQUIPMENT TAG\n" " Nearby label MUST exactly match (case-insensitive, whitespace trimmed):\n" " AC-P, AC-Q, AC-S, AC-T, AC-U, or AC-N\n\n" " Label position acceptable:\n" " - above, below, beside, or diagonally adjacent\n" " - rotated vertically or horizontally\n" " - within 15% of equipment symbol's dimensions from the edge\n" " - does NOT need to be inside the bounding box\n\n" "=== BOUNDING BOX RULES ===\n" " - Start box where equipment OUTLINE begins (exclude padding, don't over-expand)\n" " - Enclose ONLY the equipment symbol itself, NOT the label\n" " - Interior mechanical detail should occupy 30-60% of box area\n" " - Box coordinates: pixel positions within this tile (0,0=top-left)\n" " - If multiple units are adjacent, return separate non-overlapping boxes\n\n" "=== REJECT THESE ===\n" " - Isolated text labels or schedule tables\n" " - Simple empty duct boxes (no internal detail)\n" " - VAV boxes without dense grille/coil detail\n" " - Dampers, diffusers, thermostats, terminal boxes\n" " - Duct size labels (12x6, 16x8, etc.)\n" " - Symbols labeled: VD, FD, CD, RG, EG, SG, LD, PL, COD, CAR\n" " - Small annotation symbols attached to ducts\n" " - Rectangles lacking internal mechanical patterns\n" " - Text-only regions\n\n" "Return ONLY valid JSON, no markdown:\n" '{"detections":[{"tag":"AC-P","xmin":0,"ymin":0,"xmax":800,"ymax":600,"confidence":0.92}]}\n\n' "Tag: equipment label (case-insensitive)\n" "xmin, ymin, xmax, ymax: pixel coordinates within this tile image (0-based)\n" "confidence: optional float 0.0-1.0 expressing detection certainty\n\n" 'If no valid units: {"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 caller ──────────────────────────────────────────────────────────────── 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 "" # ── 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 tile-pixel detections to full-page pixel coords.""" out = [] for d in dets: try: x1 = int(d["xmin"]) + tx y1 = int(d["ymin"]) + ty x2 = int(d["xmax"]) + tx y2 = int(d["ymax"]) + 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, "confidence": d.get("confidence", 1.0) }) 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), "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_at_iou01": hits, "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) # ── main ────────────────────────────────────────────────────────────────────── 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) parser.add_argument("--tile", action="append", default=[]) args = parser.parse_args() args.out_dir.mkdir(parents=True, exist_ok=True) # 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"Testing refined prompt on {len(tiles)} tile(s)\n") # Run refined prompt print("=== REFINED PROMPT ===") all_dets: list[dict] = [] tile_log: list[dict] = [] for tx, ty in 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", REFINED_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) tile_log.append({"tile": [tx, ty], "count": len(page_dets)}) print(f" tile ({tx:5},{ty:5}): {len(page_dets):2d} det(s)") except Exception as exc: tile_log.append({"tile": [tx, ty], "error": str(exc)}) print(f" tile ({tx:5},{ty:5}): ERROR - {exc}") # Score refined score_refined = score_vs_gold(all_dets, gold) print(f"\n Total detections: {len(all_dets)}") print(f" Mean IoU vs gold: {score_refined.get('mean_iou')}") print(f" Hits (IoU ≥ 0.1): {score_refined.get('hits_at_iou01')}/{len(gold)}") # Save refined detections det_path = args.out_dir / "gemini_2.5-flash_refined_detections.json" det_path.write_text( json.dumps({ "prompt_version": "refined", "model": "gemini-2.5-flash", "detections": all_dets }, indent=2), encoding="utf-8" ) # Overlay visualization overlay_path = args.out_dir / "gemini_2.5-flash_refined_overlay.png" draw_overlay(full_img, all_dets, gold, overlay_path) # Save comparison report report = { "refined": { "total_dets": len(all_dets), "mean_iou": score_refined.get("mean_iou"), "hits_at_iou01": score_refined.get("hits_at_iou01"), "gold_count": len(gold), "matches": score_refined.get("matches"), } } (args.out_dir / "prompt_comparison.json").write_text(json.dumps(report, indent=2), encoding="utf-8") print(f"\nRefined detections saved: {det_path}") print(f"Overlay saved: {overlay_path}") print(f"Report saved: {args.out_dir / 'prompt_comparison.json'}") if __name__ == "__main__": main()