Spaces:
Paused
Paused
File size: 12,170 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 299 300 301 302 303 304 | 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 openai import OpenAI
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" / "model_compare_acp"
GOLD_ACP = [
{"tag": "AC-P", "x": 7440, "y": 1650, "w": 320, "h": 430},
{"tag": "AC-P", "x": 2730, "y": 3810, "w": 839, "h": 570},
{"tag": "AC-P", "x": 2730, "y": 4770, "w": 869, "h": 570},
{"tag": "AC-P", "x": 5220, "y": 4680, "w": 570, "h": 300},
]
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_data_url(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 build_prompt() -> str:
return (
"You are analyzing a mechanical HVAC blueprint page.\n\n"
"Find every HVAC indoor unit labeled exactly AC-P. A valid AC-P match has:\n"
"- the exact text label AC-P printed next to the unit, possibly rotated\n"
"- a rectangular HVAC indoor unit body with internal detail such as hatching,\n"
" coil/fan marks, or connected duct/piping\n"
"- the label and unit body belong together, even if separated by nearby lines\n\n"
"Reject duct size labels, diffuser circles, notes, legends, schedules, and bare ducts.\n\n"
"Return generous review boxes. Each box must cover both the AC-P text label and the\n"
"complete unit rectangle. Prefer a slightly larger box over cutting off the unit or label.\n\n"
"Return ONLY valid JSON, no markdown:\n"
'{"detections":[{"tag":"AC-P","xmin":N,"ymin":N,"xmax":N,"ymax":N}, ...]}\n\n'
"Coordinates must be integers from 0 to 1000 normalized to the full image you received."
)
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 = text.find("{")
end = text.rfind("}")
if start >= 0 and end > start:
text = text[start : end + 1]
data = json.loads(text)
return data.get("detections", [])
def normalize_detections(dets: list[dict[str, Any]], img_w: int, img_h: int) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for det in dets:
try:
xmin = int(det["xmin"])
ymin = int(det["ymin"])
xmax = int(det["xmax"])
ymax = int(det["ymax"])
except (KeyError, TypeError, ValueError):
continue
if xmax <= xmin or ymax <= ymin:
continue
out.append({
"tag": "AC-P",
"x": int(xmin / 1000 * img_w),
"y": int(ymin / 1000 * img_h),
"w": int((xmax - xmin) / 1000 * img_w),
"h": int((ymax - ymin) / 1000 * img_h),
})
return out
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_data_url(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
# Thinking models (2.5 Pro) return thought parts + answer parts separately
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 call_openai_compatible(
model: str,
prompt: str,
img: Image.Image,
max_px: int,
max_tokens: int,
base_url: str,
api_key_env: str,
) -> str:
client = OpenAI(base_url=base_url, api_key=os.environ[api_key_env])
data_url, _ = encode_png_data_url(img, max_px)
response = client.chat.completions.create(
model=model,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": data_url}},
],
}],
temperature=0,
max_tokens=max_tokens,
)
return response.choices[0].message.content or ""
def iou(a: dict[str, Any], b: dict[str, Any]) -> float:
ax1, ay1, ax2, ay2 = a["x"], a["y"], a["x"] + a["w"], a["y"] + a["h"]
bx1, by1, bx2, by2 = b["x"], b["y"], b["x"] + b["w"], b["y"] + 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_detections(dets: list[dict[str, Any]], gold_boxes: list[dict[str, Any]]) -> dict[str, Any]:
matches = []
used = set()
for gi, gold in enumerate(gold_boxes, 1):
best_i = None
best_score = 0.0
for di, det in enumerate(dets):
if di in used:
continue
s = iou(gold, det)
if s > best_score:
best_i = di
best_score = s
if best_i is not None:
used.add(best_i)
matches.append({"gold": gi, "iou": round(best_score, 3), "det_index": best_i})
n = len(matches) or 1
return {
"count": len(dets),
"mean_iou": round(sum(m["iou"] for m in matches) / n, 3),
"matches": matches,
}
def draw_preview(img: Image.Image, dets: list[dict[str, Any]], gold_boxes: list[dict[str, Any]], out_path: Path) -> None:
preview = img.copy()
draw = ImageDraw.Draw(preview)
font = ImageFont.load_default()
for gold in gold_boxes:
draw.rectangle([gold["x"], gold["y"], gold["x"] + gold["w"], gold["y"] + gold["h"]], outline=(0, 220, 0), width=5)
for idx, det in enumerate(dets, 1):
draw.rectangle([det["x"], det["y"], det["x"] + det["w"], det["y"] + det["h"]], outline=(255, 0, 255), width=6)
draw.text((det["x"], max(0, det["y"] - 20)), f"{idx}", fill=(255, 0, 255), font=font)
preview.save(out_path)
def parse_model_specs(values: list[str]) -> list[tuple[str, str, int | None]]:
"""Parse provider:model or provider:model:max_tokens specs."""
specs = []
for value in values:
parts = value.split(":", 2)
if len(parts) < 2:
raise ValueError(f"Model spec must look like provider:model, got {value!r}")
provider = parts[0].strip().lower()
model = parts[1].strip()
max_tok = int(parts[2]) if len(parts) == 3 and parts[2].strip().isdigit() else None
specs.append((provider, model, max_tok))
return specs
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=1024)
parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT)
parser.add_argument(
"--tile",
default=None,
help="Crop to a tile before sending: tx,ty[,size] in full-image pixels "
"(e.g. --tile 2700,2700 or --tile 2700,2700,3000). "
"Gold boxes are adjusted to tile-relative coords; only boxes inside the tile are kept.",
)
parser.add_argument(
"--model",
action="append",
default=[],
help="provider:model[:max_tokens], e.g. gemini:gemini-2.5-flash:8192",
)
args = parser.parse_args()
args.out_dir.mkdir(parents=True, exist_ok=True)
models = parse_model_specs(args.model or ["gemini:gemini-2.5-flash"])
full_img = render_page(args.pdf, args.page, args.dpi)
# Apply tile crop
tile_origin = (0, 0)
if args.tile:
parts = [int(p) for p in args.tile.split(",")]
tx, ty = parts[0], parts[1]
tile_size = parts[2] if len(parts) >= 3 else 2700
img = full_img.crop((tx, ty, min(tx + tile_size, full_img.width), min(ty + tile_size, full_img.height)))
tile_origin = (tx, ty)
print(f"Tile crop ({tx},{ty}) size={tile_size} -> img {img.width}x{img.height}")
else:
img = full_img
# Offset gold boxes into tile-local coords and drop boxes outside the tile
gold_boxes: list[dict[str, Any]] = []
for g in GOLD_ACP:
gx = g["x"] - tile_origin[0]
gy = g["y"] - tile_origin[1]
if 0 <= gx < img.width and 0 <= gy < img.height:
gold_boxes.append({**g, "x": gx, "y": gy})
if tile_origin != (0, 0):
print(f"Gold boxes in tile: {len(gold_boxes)}/{len(GOLD_ACP)}")
prompt = build_prompt()
summary = []
for provider, model, model_max_tok in models:
max_tok = model_max_tok if model_max_tok is not None else args.max_tokens
safe_name = re.sub(r"[^A-Za-z0-9_.-]+", "_", f"{provider}_{model}")
print(f"Running {provider}:{model} (max_tokens={max_tok})...")
try:
if provider == "gemini":
raw = call_gemini(model, prompt, img, args.max_px, max_tok)
elif provider == "openrouter":
raw = call_openai_compatible(
model, prompt, img, args.max_px, max_tok,
"https://openrouter.ai/api/v1", "OPENROUTER_API_KEY",
)
elif provider == "groq":
raw = call_openai_compatible(
model, prompt, img, args.max_px, max_tok,
"https://api.groq.com/openai/v1", "GROQ_API_KEY",
)
elif provider == "featherless":
raw = call_openai_compatible(
model, prompt, img, args.max_px, max_tok,
"https://api.featherless.ai/v1", "FEATHERLESS_API_KEY",
)
else:
raise ValueError(f"Unsupported provider: {provider}")
raw_path = args.out_dir / f"{safe_name}_raw.txt"
raw_path.write_text(raw, encoding="utf-8")
dets = normalize_detections(parse_json_text(raw), img.width, img.height)
score = score_detections(dets, gold_boxes)
result = {"provider": provider, "model": model, "detections": dets, "score": score}
(args.out_dir / f"{safe_name}_detections.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
draw_preview(img, dets, gold_boxes, args.out_dir / f"{safe_name}_preview.png")
summary.append({**score, "provider": provider, "model": model})
print(f" count={score['count']} mean_iou={score['mean_iou']}")
except Exception as exc:
summary.append({"provider": provider, "model": model, "error": str(exc)})
print(f" ERROR: {exc}")
(args.out_dir / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
print(f"\nWrote results to: {args.out_dir}")
if __name__ == "__main__":
main()
|