File size: 11,244 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
296
297
298
"""
Test revised prompt v2 with corrected box sizing.

The first refined prompt was TOO TIGHT (boxes 5-10x too small).
This version balances: symbol-first detection + internal detail requirement,
but with proper box sizing (equipment symbol + label area, not just tiny detail).

Usage:
    python test_revised_prompt_v2.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

# Revised prompt v2: Symbol-first + internal detail requirement, but proper box sizing
REVISED_PROMPT_V2 = (
    "You are analyzing a TILE (cropped section) of a mechanical HVAC floor plan PDF.\n\n"

    "TASK: Detect ONLY real HVAC indoor unit equipment whose nearby label\n"
    "matches one of the schedule tags (AC-P, AC-Q, AC-S, AC-T, AC-U, AC-N).\n\n"

    "=== DETECTION APPROACH ===\n"
    "1. SYMBOL-FIRST: Locate mechanically detailed rectangular equipment symbols\n"
    "2. VERIFY detail: Symbol must contain dense internal mechanical patterns\n"
    "3. VERIFY connection: Equipment must connect to HVAC ductwork or piping\n"
    "4. VERIFY label: Nearby label must match schedule tag (case-insensitive)\n"
    "5. RETURN detection only if ALL conditions satisfied\n\n"

    "=== WHAT TO DETECT ===\n"
    "Valid indoor units have:\n"
    "  - Rectangular/square equipment body (medium-to-large size)\n"
    "  - DENSE internal mechanical detail:\n"
    "    * Repeated parallel bars or grille lines\n"
    "    * Coil fin patterns\n"
    "    * Fan cross-hatching or symbol\n"
    "    * Segmented internal compartments\n"
    "    * NOT just empty outline\n"
    "  - Mechanical connection to ducts or refrigerant piping\n"
    "  - Nearby label exactly matching: AC-P, AC-Q, AC-S, AC-T, AC-U, or AC-N\n\n"

    "=== BOUNDING BOX RULES ===\n"
    "Return a BOX that covers the complete equipment symbol + nearby label:\n"
    "  - Include the full equipment symbol (where the internal detail is)\n"
    "  - Include the associated label if it's close (within ~100-200 pixels)\n"
    "  - Box should be reasonably generous but not padding excessively\n"
    "  - If equipment and label are far apart, prioritize the equipment symbol\n"
    "  - Coordinates are pixel positions within this tile image (0,0=top-left)\n\n"

    "=== REJECT THESE ===\n"
    "  - Isolated text labels, tables, or legends\n"
    "  - Empty duct boxes or rectangles (no internal detail)\n"
    "  - VAV boxes, dampers, diffusers, terminal boxes\n"
    "  - Duct size labels (12x6, 16x8, etc.)\n"
    "  - Symbols: VD, FD, CD, RG, EG, SG, LD, PL, COD, CAR\n"
    "  - Small annotation symbols\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'
    'If no valid 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"]) + 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


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,
    }


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)

    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)")

    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 revised prompt v2 on {len(DEFAULT_TILES)} tile(s)\n")

    print("=== REVISED PROMPT V2 ===")
    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", REVISED_PROMPT_V2, 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)
            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 = score_vs_gold(all_dets, gold)
    print(f"\n  Total detections: {len(all_dets)}")
    print(f"  Mean IoU vs gold: {score.get('mean_iou')}")
    print(f"  Hits (IoU ≥ 0.1): {score.get('hits_at_iou01')}/{len(gold)}")

    # Save detections
    det_path = args.out_dir / "gemini_2.5-flash_revised_v2_detections.json"
    det_path.write_text(
        json.dumps({
            "prompt_version": "revised_v2",
            "model": "gemini-2.5-flash",
            "detections": all_dets
        }, indent=2),
        encoding="utf-8"
    )

    # Overlay
    overlay_path = args.out_dir / "gemini_2.5-flash_revised_v2_overlay.png"
    draw_overlay(full_img, all_dets, gold, overlay_path)

    print(f"\nDetections saved: {det_path}")
    print(f"Overlay saved: {overlay_path}")


if __name__ == "__main__":
    main()