Spaces:
Paused
Paused
File size: 5,320 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 | """Score all model detection files against extracted gold boxes."""
import json
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
import fitz
GOLD_PATH = Path(__file__).parent / "output_floor_iter" / "model_compare_acp" / "gold_allunits.json"
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 = json.loads(GOLD_PATH.read_text(encoding="utf-8"))
print(f"Gold boxes: {len(gold)}\n")
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, "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 full page thumbnail for overlays
print("Rendering page thumbnail...")
doc = fitz.open(PDF_PATH)
page = doc.load_page(1)
scale = 72 / 72 # 72 DPI for thumbnail
pix = page.get_pixmap(matrix=fitz.Matrix(scale, scale), alpha=False)
thumb_base = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
SCALE = pix.width / 14400 # ratio thumb pixels / full-res pixels
print(f"Thumbnail: {thumb_base.width}x{thumb_base.height} scale={SCALE:.4f}\n")
GOLD_COLOR = (0, 255, 0)
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_COLOR = (255, 60, 60)
MODEL_FILES = [
("gemini", "gemini-2.5-pro",
"gemini_gemini-2.5-pro_detections.json"),
("gemini", "gemini-2.5-flash",
"gemini_gemini-2.5-flash_detections.json"),
("openrouter", "openai/gpt-4o",
"openrouter_openai_gpt-4o_detections.json"),
("openrouter", "anthropic/claude-sonnet-4-5",
"openrouter_anthropic_claude-sonnet-4-5_detections.json"),
("featherless", "Gemma3-27B-vl",
"featherless_DavidAU_Gemma3-27B-it-vl-GLM-4.7-Uncensored-Heretic-Deep-Reasoning_detections.json"),
]
rows = []
overlay_imgs = []
for prov, mod_label, fname in MODEL_FILES:
f = DET_DIR / fname
if not f.exists():
print(f"MISSING: {fname}")
continue
data = json.loads(f.read_text(encoding="utf-8"))
dets = data["detections"]
hits, mean_iou, matches = score(dets, gold)
label = f"{prov}:{mod_label}"
print(f"{label}")
print(f" dets={len(dets)} hits(iou>=0.1)={hits}/{len(gold)} mean_iou={mean_iou}")
for m in matches:
status = "HIT " if m["hit"] else "miss"
print(f" gold#{m['gold']:2d} iou={m['iou']:.3f} [{status}]")
print()
rows.append({"model": label, "dets": len(dets), "hits": hits, "mean_iou": mean_iou})
# Draw overlay
thumb = thumb_base.copy()
draw = ImageDraw.Draw(thumb)
font = ImageFont.load_default()
for g in gold:
x1, y1 = int(g["x"] * SCALE), int(g["y"] * SCALE)
x2, y2 = int((g["x"] + g["w"]) * SCALE), int((g["y"] + g["h"]) * SCALE)
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"] * 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 + 2, max(0, y1 - 10)), det.get("tag", "?"), fill=color, font=font)
out_path = DET_DIR / f"overlay_{prov}_{mod_label.replace('/', '_')}.png"
thumb.save(out_path)
overlay_imgs.append((label, thumb))
# Ranking
print("=== RANKING (mean_iou, iou threshold 0.1) ===")
for r in sorted(rows, key=lambda x: -x["mean_iou"]):
bar = "#" * int(r["mean_iou"] * 60)
print(f" {r['mean_iou']:.3f} {bar:<20} {r['hits']}/{len(gold)} hits {r['dets']:3d} dets {r['model']}")
# Side-by-side grid (2 rows)
if overlay_imgs:
cols = 3
rows_n = (len(overlay_imgs) + cols - 1) // cols
w, h = overlay_imgs[0][1].size
label_h = 18
grid = Image.new("RGB", (w * cols, (h + label_h) * rows_n), (20, 20, 20))
dfont = ImageFont.load_default()
dgrid = ImageDraw.Draw(grid)
for idx, (lbl, img) in enumerate(overlay_imgs):
col, row = idx % cols, idx // cols
gx, gy = col * w, row * (h + label_h)
grid.paste(img, (gx, gy + label_h))
dgrid.text((gx + 4, gy + 2), lbl[:50], fill=(255, 255, 255), font=dfont)
grid_path = DET_DIR / "scored_comparison_grid.png"
grid.save(grid_path)
print(f"\nGrid saved: {grid_path}")
|