""" Test Claude Vision on the new cellar image annotated by user. Goal: Compare Claude Sonnet 4.5 zero-shot detection against the 12 gold boxes (6 ceiling_ducted + 6 wall_mounted) to see if VLM beats YOLO trained on 1 image. Tiles the image into 2700x2700 crops, sends each to Claude with a structured JSON prompt, aggregates detections, computes IoU vs gold. """ from __future__ import annotations import base64 import json import os import re import sys from io import BytesIO from pathlib import Path from dotenv import load_dotenv from openai import OpenAI from PIL import Image, ImageDraw, ImageFont load_dotenv(Path(__file__).resolve().parent.parent / ".env") ROOT = Path(__file__).resolve().parent V2_DIR = ROOT / "yolo_v2_data" RAW_DIR = V2_DIR / "raw" OUT_DIR = V2_DIR / "claude_output" OUT_DIR.mkdir(exist_ok=True) LOG_FILE = OUT_DIR / "log.txt" log_lines = [] def log(msg): s = str(msg) log_lines.append(s) print(s) def save_log(): LOG_FILE.write_text("\n".join(log_lines), encoding="utf-8") # Image is 14400x10800. Tile at 2700px with overlap to keep API calls down. TILE_SIZE = 2700 OVERLAP = 400 PROMPT = ( "You are analyzing a mechanical HVAC blueprint tile.\n\n" "Find every HVAC indoor unit visible in this tile. There are two types:\n" " - ceiling_ducted: rectangular boxes with internal mechanical detail (hatching, " "coil marks, fan cross, connected ductwork). Often labeled AC-P, AC-Q, AC-S, AC-T.\n" " - wall_mounted: smaller compact rectangular units mounted on walls. Usually labeled AC-U or similar.\n\n" "Each valid unit has:\n" " - A text label such as AC-P, AC-Q, AC-S, AC-T, AC-U, or similar 'AC-X' code\n" " - A rectangular body that you can see in the drawing\n\n" "Reject: duct size labels, diffuser circles, schedule tables, legends, bare pipes, dimensions.\n\n" "Return ONLY valid JSON, no markdown fences:\n" '{"detections":[{"label":"AC-P","class":"ceiling_ducted","xmin":N,"ymin":N,"xmax":N,"ymax":N},...]}\n\n' "Coordinates: integers 0-1000 normalized to the image you received.\n" "If no units visible: {\"detections\":[]}" ) def encode_b64(img: Image.Image, max_px: int = 1568) -> str: 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") return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii") def call_claude(client, prompt: str, img: Image.Image) -> str: data_url = encode_b64(img) resp = client.chat.completions.create( model="anthropic/claude-sonnet-4-5", messages=[{"role": "user", "content": [ {"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": data_url}}, ]}], temperature=0, max_tokens=600, ) return resp.choices[0].message.content or "" def parse_json(text: str): 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] try: return json.loads(text).get("detections", []) except Exception: return [] def iou_box(a, b): 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 try: if not os.environ.get("OPENROUTER_API_KEY"): log("ERROR: OPENROUTER_API_KEY not set in environment or .env") save_log() sys.exit(1) client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"]) # Load image image_files = list(RAW_DIR.glob("*.jpg")) + list(RAW_DIR.glob("*.png")) img_path = image_files[0] img = Image.open(img_path).convert("RGB") W, H = img.size log(f"Image: {img_path.name} ({W}x{H})") # Load gold boxes (convert from YOLO format to absolute pixels) label_files = list((V2_DIR / "extracted").rglob("*.txt")) label_files = [f for f in label_files if f.name != "classes.txt"] gold = [] with open(label_files[0]) as f: for line in f: parts = line.strip().split() if len(parts) != 5: continue cls, xc, yc, w, h = parts xc, yc, w, h = float(xc), float(yc), float(w), float(h) x1 = int((xc - w/2) * W) y1 = int((yc - h/2) * H) x2 = int((xc + w/2) * W) y2 = int((yc + h/2) * H) gold.append({ "class": "ceiling_ducted" if cls == "0" else "wall_mounted", "x1": x1, "y1": y1, "x2": x2, "y2": y2, }) log(f"Gold boxes: {len(gold)} " f"({sum(1 for g in gold if g['class']=='ceiling_ducted')} ceiling + " f"{sum(1 for g in gold if g['class']=='wall_mounted')} wall)") # Tile and call Claude log("\n=== Calling Claude on tiles ===") all_dets = [] tile_idx = 0 y = 0 while y < H: x = 0 while x < W: x2 = min(x + TILE_SIZE, W) y2 = min(y + TILE_SIZE, H) tile = img.crop((x, y, x2, y2)) tile_idx += 1 try: resp_text = call_claude(client, PROMPT, tile) dets = parse_json(resp_text) for d in dets: try: tx1 = int(d["xmin"] / 1000 * tile.width) + x ty1 = int(d["ymin"] / 1000 * tile.height) + y tx2 = int(d["xmax"] / 1000 * tile.width) + x ty2 = int(d["ymax"] / 1000 * tile.height) + y if tx2 > tx1 and ty2 > ty1: all_dets.append({ "label": d.get("label", "?"), "class": d.get("class", "?"), "x1": tx1, "y1": ty1, "x2": tx2, "y2": ty2, }) except Exception: continue if dets: log(f" Tile {tile_idx:2d} ({x:5d},{y:5d}): {len(dets)} det(s)") except Exception as e: log(f" Tile {tile_idx:2d} ERROR: {e}") x += TILE_SIZE - OVERLAP y += TILE_SIZE - OVERLAP log(f"\nTotal raw detections (with overlaps): {len(all_dets)}") # Deduplicate by center distance deduped = [] for d in all_dets: cx = (d["x1"] + d["x2"]) / 2 cy = (d["y1"] + d["y2"]) / 2 dup = False for kept in deduped: kcx = (kept["x1"] + kept["x2"]) / 2 kcy = (kept["y1"] + kept["y2"]) / 2 if abs(cx - kcx) < 100 and abs(cy - kcy) < 100: dup = True break if not dup: deduped.append(d) log(f"After dedup: {len(deduped)} detections") by_class = {} for d in deduped: by_class[d["class"]] = by_class.get(d["class"], 0) + 1 log(f" By class: {by_class}") # Score vs gold used = set() matches = [] for gi, g in enumerate(gold): best_i, best_s = None, 0.0 for di, d in enumerate(deduped): if di in used: continue s = iou_box(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_idx": gi, "gold_class": g["class"], "iou": round(best_s, 3), "matched_det_idx": best_i, "matched_label": deduped[best_i]["label"] if best_i is not None else None, "matched_class": deduped[best_i]["class"] if best_i is not None else None, }) 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) mean_iou = sum(m["iou"] for m in matches) / len(matches) class_correct = sum(1 for m in matches if m["matched_class"] == m["gold_class"]) log(f"\n=== RESULTS ===") log(f"Gold: {len(gold)} | Detected: {len(deduped)}") log(f"Mean IoU: {mean_iou:.3f}") log(f"Hits @ IoU 0.5: {hits_05}/{len(gold)}") log(f"Hits @ IoU 0.1: {hits_01}/{len(gold)}") log(f"Class correct (of matched): {class_correct}/{len(gold)}") log(f"\n--- Per-gold matches ---") for m in matches: log(f" gold {m['gold_idx']+1:2d} ({m['gold_class']:14s}) " f"-> IoU={m['iou']:.3f} | matched_label={m['matched_label']} class={m['matched_class']}") # Save JSON result = { "detections": deduped, "gold": gold, "matches": matches, "summary": { "gold_count": len(gold), "det_count": len(deduped), "mean_iou": round(mean_iou, 3), "hits_iou_05": hits_05, "hits_iou_01": hits_01, "class_correct": class_correct, } } (OUT_DIR / "results.json").write_text(json.dumps(result, indent=2)) log(f"\nResults JSON: {OUT_DIR / 'results.json'}") # Visualization overlay = img.copy() draw = ImageDraw.Draw(overlay) try: font = ImageFont.truetype("arial.ttf", 18) except: font = ImageFont.load_default() # Gold in green, detections in red for g in gold: draw.rectangle([g["x1"], g["y1"], g["x2"], g["y2"]], outline=(0, 255, 0), width=4) for idx, d in enumerate(deduped, 1): color = (255, 0, 0) if d["class"] == "ceiling_ducted" else (255, 100, 0) draw.rectangle([d["x1"], d["y1"], d["x2"], d["y2"]], outline=color, width=3) draw.text((d["x1"], d["y1"] - 20), f"{idx}.{d['label']}", fill=color, font=font) out_img = OUT_DIR / "claude_vs_gold.jpg" overlay.save(out_img, quality=70) log(f"Visualization: {out_img}") save_log() except Exception as e: import traceback log(f"ERROR: {e}") log(traceback.format_exc()) save_log() raise