hvac_fable / python_files /_score_models.py
Rachel7's picture
Deploy Fable B-test analyzer
dac3297 verified
Raw History Blame Contribute Delete
5.32 kB
"""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}")