Spaces:
Paused
Paused
Download python_files/compare_cellar_acp_models.py from Rachel7/hvac_fable: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/python_files/compare_cellar_acp_models.py
- Command line
-
hf download hf://spaces/Rachel7/hvac_fable/python_files/compare_cellar_acp_models.py
-
curl -L -o compare_cellar_acp_models.py https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/python_files/compare_cellar_acp_models.py
12.2 kB
| 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() | |