File size: 10,004 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
"""
Test Gemini Vision (2.5 Pro) on the new cellar image annotated by user.

Tiles the image, sends each to Gemini, aggregates detections, compares to 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 google import genai
from google.genai import types as genai_types
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 / "gemini_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.
TILE_SIZE = 2700
OVERLAP = 400
MODEL_ID = "gemini-2.5-pro"

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 visible 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_png(img: Image.Image, max_px: int = 1568) -> bytes:
    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 buf.getvalue()


def call_gemini(client, prompt: str, img: Image.Image) -> str:
    img_bytes = encode_png(img)
    response = client.models.generate_content(
        model=MODEL_ID,
        contents=[prompt, genai_types.Part.from_bytes(data=img_bytes, mime_type="image/png")],
        config=genai_types.GenerateContentConfig(max_output_tokens=2048, 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: 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("GEMINI_API_KEY"):
        log("ERROR: GEMINI_API_KEY not set")
        save_log()
        sys.exit(1)

    client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
    log(f"Using model: {MODEL_ID}")

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

    # Tile and call Gemini
    log("\n=== Calling Gemini 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_gemini(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: {str(e)[:200]}")
            x += TILE_SIZE - OVERLAP
        y += TILE_SIZE - OVERLAP

    log(f"\nTotal raw detections: {len(all_dets)}")

    # Dedup 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)}")
    by_class = {}
    for d in deduped:
        by_class[d["class"]] = by_class.get(d["class"], 0) + 1
    log(f"  By class: {by_class}")

    # Score
    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: {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
    (OUT_DIR / "results.json").write_text(json.dumps({
        "model": MODEL_ID,
        "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,
        }
    }, indent=2))

    # Visualize
    overlay = img.copy()
    draw = ImageDraw.Draw(overlay)
    try:
        font = ImageFont.truetype("arial.ttf", 18)
    except:
        font = ImageFont.load_default()
    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)
    overlay.save(OUT_DIR / "gemini_vs_gold.jpg", quality=70)
    log(f"\nVisualization: {OUT_DIR / 'gemini_vs_gold.jpg'}")

    save_log()
except Exception as e:
    import traceback
    log(f"ERROR: {e}")
    log(traceback.format_exc())
    save_log()
    raise