File size: 12,286 Bytes
dac3297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
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()