File size: 7,355 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
"""
Rescore all model detections using ground-truth positions from the verified
tiling pipeline (cellar_verify.log / cellar_refined.log), which are already
in full-image PDF pixel space at 300 DPI.

Also regenerates clean overlays without the broken screenshot-mapped gold boxes.
"""
import json
from pathlib import Path
import fitz
from PIL import Image, ImageDraw, ImageFont

DET_DIR  = Path(__file__).parent / "output_floor_iter" / "cellar_allunits_compare"
PDF_PATH = Path(__file__).parent.parent / "raw_pdfs" / "355 E 86th St Mechanical 100% CD Set_flattened.pdf"

# ── Gold boxes from the verified tiling pipeline (cellar_refined.log)
# Positions are FULL-IMAGE pixels at 300 DPI (14400Γ—10800).
# Box sizes estimated from GOLD_ACP dimensions for AC-P; similar size for others.
GOLD = [
    # AC-P  (log: (7170,1470);  GOLD_ACP #1 was (7440,1650,320,430))
    {"tag": "AC-P",  "x": 7050, "y": 1300, "w": 500, "h": 550},
    # AC-S  (log: (4170,2400))
    {"tag": "AC-S",  "x": 3970, "y": 2200, "w": 500, "h": 500},
    # AC-Q  (log: (2730,3000))
    {"tag": "AC-Q",  "x": 2530, "y": 2800, "w": 500, "h": 500},
    # AC-P  (log: (2730,3900);  GOLD_ACP #2 was (2730,3810,839,570))
    {"tag": "AC-P",  "x": 2530, "y": 3650, "w": 900, "h": 650},
    # AC-P  (log: (2730,4800);  GOLD_ACP #3 was (2730,4770,869,570))
    {"tag": "AC-P",  "x": 2530, "y": 4600, "w": 900, "h": 650},
    # AC-P  (log: (6000,4650);  GOLD_ACP #4 was (5220,4680,570,300))
    {"tag": "AC-P",  "x": 5750, "y": 4450, "w": 700, "h": 500},
    # AC-T  (log: (2034,6294))
    {"tag": "AC-T",  "x": 1800, "y": 6050, "w": 500, "h": 500},
    # AC-T  (log: (3540,7470))
    {"tag": "AC-T",  "x": 3300, "y": 7220, "w": 500, "h": 500},
    # AC-U  (log: (6840,7200))
    {"tag": "AC-U",  "x": 6600, "y": 6950, "w": 500, "h": 500},
    # AC-U  (log: (9270,7560))
    {"tag": "AC-U",  "x": 9050, "y": 7310, "w": 500, "h": 500},
    # AC-T  tile (8100,5400) had 3 hits β€” estimate positions
    {"tag": "AC-T",  "x": 8300, "y": 5700, "w": 500, "h": 500},
    {"tag": "AC-T",  "x": 9600, "y": 6200, "w": 500, "h": 500},
    # Extra unit seen in current run at tile (8100,0) by Gemini Pro
    {"tag": "unit",  "x": 8200, "y":  400, "w": 600, "h": 600},
]

print(f"Gold boxes: {len(GOLD)}")

# ── scoring ──────────────────────────────────────────────────────────────────
def iou(a, b):
    ax2, ay2 = a["x"] + a["w"], a["y"] + a["h"]
    bx2, by2 = b["x"] + b["w"], b["y"] + b["h"]
    ix1, iy1 = max(a["x"], b["x"]), max(a["y"], b["y"])
    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(dets, gold_boxes, threshold=0.1):
    used = set()
    matches = []
    for gi, g in enumerate(gold_boxes, 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, "tag": g["tag"], "iou": round(best_s, 3), "hit": best_s >= threshold})
    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 hits, mean_iou, matches

# ── render thumbnail ─────────────────────────────────────────────────────────
print("Rendering thumbnail …")
doc = fitz.open(PDF_PATH)
pix = doc.load_page(1).get_pixmap(matrix=fitz.Matrix(72/72, 72/72), alpha=False)
thumb_base = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
S = pix.width / 14400          # thumbnail scale
print(f"Thumb {thumb_base.width}x{thumb_base.height}  scale={S:.4f}\n")

TAG_COLORS = {
    "AC-P": (220, 0, 180), "AC-Q": (0, 160, 255), "AC-S": (0, 200, 0),
    "AC-T": (255, 130, 0),  "AC-U": (160, 0, 255), "AC-N": (0, 200, 200),
}
DEFAULT_COLOR = (255, 60, 60)
GOLD_COLOR    = (0, 255, 0)

MODEL_FILES = [
    ("Gemini 2.5 Pro",   "gemini_gemini-2.5-pro_detections.json"),
    ("Gemini 2.5 Flash", "gemini_gemini-2.5-flash_detections.json"),
    ("GPT-4o",           "openrouter_openai_gpt-4o_detections.json"),
    ("Claude S4.5",      "openrouter_anthropic_claude-sonnet-4-5_detections.json"),
    ("Featherless G3",   "featherless_DavidAU_Gemma3-27B-it-vl-GLM-4.7-Uncensored-Heretic-Deep-Reasoning_detections.json"),
]

rows = []
overlay_imgs = []
font = ImageFont.load_default()

for label, fname in MODEL_FILES:
    f = DET_DIR / fname
    if not f.exists():
        print(f"MISSING: {fname}")
        continue
    dets = json.loads(f.read_text(encoding="utf-8"))["detections"]
    hits, mean_iou, matches = score(dets, GOLD)

    print(f"{label}")
    print(f"  dets={len(dets)}  hits(iou>=0.1)={hits}/{len(GOLD)}  mean_iou={mean_iou}")
    for m in matches:
        flag = "HIT " if m["hit"] else "miss"
        print(f"    gold#{m['gold']:2d} {m['tag']:<6} iou={m['iou']:.3f}  [{flag}]")
    print()
    rows.append({"model": label, "dets": len(dets), "hits": hits, "mean_iou": mean_iou})

    # Draw overlay β€” model detections in color, gold in green
    thumb = thumb_base.copy()
    draw  = ImageDraw.Draw(thumb)
    for g in GOLD:
        x1, y1 = int(g["x"]*S), int(g["y"]*S)
        x2, y2 = int((g["x"]+g["w"])*S), int((g["y"]+g["h"])*S)
        draw.rectangle([x1,y1,x2,y2], outline=GOLD_COLOR, width=3)
    for det in dets:
        color = TAG_COLORS.get(det.get("tag",""), DEFAULT_COLOR)
        x1, y1 = int(det["x"]*S), int(det["y"]*S)
        x2, y2 = int((det["x"]+det["w"])*S), int((det["y"]+det["h"])*S)
        draw.rectangle([x1,y1,x2,y2], outline=color, width=4)
        draw.text((x1+2, max(0,y1-10)), det.get("tag","?"), fill=color, font=font)
    out = DET_DIR / f"v2_overlay_{label.replace(' ','_').replace('/','_')}.png"
    thumb.save(out)
    overlay_imgs.append((label, thumb))

# ── ranking ──────────────────────────────────────────────────────────────────
print("=== RANKING ===")
for r in sorted(rows, key=lambda x: (-x["hits"], -x["mean_iou"])):
    bar = "#" * int(r["mean_iou"] * 80)
    print(f"  {r['hits']:2d}/{len(GOLD)} hits  iou={r['mean_iou']:.3f} {bar:<12}  {r['dets']:3d} dets  {r['model']}")

# ── 3-column comparison grid (best 3) ───────────────────────────────────────
top3 = sorted(rows, key=lambda x: (-x["hits"], -x["mean_iou"]))[:3]
top3_imgs = [(lbl, img) for (lbl, img) in overlay_imgs
             if any(r["model"] == lbl for r in top3)]
if top3_imgs:
    w, h = top3_imgs[0][1].size
    lh = 20
    grid = Image.new("RGB", (w * 3, h + lh), (20, 20, 20))
    dg = ImageDraw.Draw(grid)
    for i, (lbl, img) in enumerate(top3_imgs):
        grid.paste(img, (i*w, lh))
        dg.text((i*w+4, 2), lbl, fill=(255,255,255), font=font)
    gp = DET_DIR / "v2_top3_comparison.png"
    grid.save(gp)
    print(f"\nTop-3 comparison grid: {gp}")