hvac_fable / python_files /gemini_vision_test.py
Rachel7's picture
Deploy Fable B-test analyzer
dac3297 verified
Raw History Blame Contribute Delete
10 kB
"""
Test Gemini Vision (2.5 Pro) on the new cellar image annotated by user.
Tiles the image, sends each to Gemini, aggregates detections, compares to gold.
"""
from __future__ import annotations
import base64
import json
import os
import re
import sys
from io import BytesIO
from pathlib import Path
from dotenv import load_dotenv
from google import genai
from google.genai import types as genai_types
from PIL import Image, ImageDraw, ImageFont
load_dotenv(Path(__file__).resolve().parent.parent / ".env")
ROOT = Path(__file__).resolve().parent
V2_DIR = ROOT / "yolo_v2_data"
RAW_DIR = V2_DIR / "raw"
OUT_DIR = V2_DIR / "gemini_output"
OUT_DIR.mkdir(exist_ok=True)
LOG_FILE = OUT_DIR / "log.txt"
log_lines = []
def log(msg):
s = str(msg)
log_lines.append(s)
print(s)
def save_log():
LOG_FILE.write_text("\n".join(log_lines), encoding="utf-8")
# Image is 14400x10800. Tile at 2700px with overlap.
TILE_SIZE = 2700
OVERLAP = 400
MODEL_ID = "gemini-2.5-pro"
PROMPT = (
"You are analyzing a mechanical HVAC blueprint tile.\n\n"
"Find every HVAC indoor unit visible in this tile. There are two types:\n"
" - ceiling_ducted: rectangular boxes with internal mechanical detail (hatching, "
"coil marks, fan cross, connected ductwork). Often labeled AC-P, AC-Q, AC-S, AC-T.\n"
" - wall_mounted: smaller compact rectangular units mounted on walls. Usually labeled AC-U or similar.\n\n"
"Each valid unit has:\n"
" - A text label such as AC-P, AC-Q, AC-S, AC-T, AC-U, or similar 'AC-X' code\n"
" - A rectangular body visible in the drawing\n\n"
"Reject: duct size labels, diffuser circles, schedule tables, legends, bare pipes, dimensions.\n\n"
"Return ONLY valid JSON, no markdown fences:\n"
'{"detections":[{"label":"AC-P","class":"ceiling_ducted","xmin":N,"ymin":N,"xmax":N,"ymax":N},...]}\n\n'
"Coordinates: integers 0-1000 normalized to the image you received.\n"
"If no units visible: {\"detections\":[]}"
)
def encode_png(img: Image.Image, max_px: int = 1568) -> bytes:
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")
return buf.getvalue()
def call_gemini(client, prompt: str, img: Image.Image) -> str:
img_bytes = encode_png(img)
response = client.models.generate_content(
model=MODEL_ID,
contents=[prompt, genai_types.Part.from_bytes(data=img_bytes, mime_type="image/png")],
config=genai_types.GenerateContentConfig(max_output_tokens=2048, temperature=0.0),
)
if response.text:
return response.text
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 parse_json(text: str):
text = text.strip()
text = re.sub(r"^```[a-zA-Z]*\n?", "", text)
text = re.sub(r"```$", "", text.strip())
start, end = text.find("{"), text.rfind("}")
if start >= 0 and end > start:
text = text[start:end + 1]
try:
return json.loads(text).get("detections", [])
except Exception:
return []
def iou_box(a, b):
ax1, ay1, ax2, ay2 = a["x1"], a["y1"], a["x2"], a["y2"]
bx1, by1, bx2, by2 = b["x1"], b["y1"], b["x2"], b["y2"]
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)
a_area = (ax2 - ax1) * (ay2 - ay1)
b_area = (bx2 - bx1) * (by2 - by1)
union = a_area + b_area - inter
return inter / union if union else 0.0
try:
if not os.environ.get("GEMINI_API_KEY"):
log("ERROR: GEMINI_API_KEY not set")
save_log()
sys.exit(1)
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
log(f"Using model: {MODEL_ID}")
# Load image
image_files = list(RAW_DIR.glob("*.jpg")) + list(RAW_DIR.glob("*.png"))
img_path = image_files[0]
img = Image.open(img_path).convert("RGB")
W, H = img.size
log(f"Image: {img_path.name} ({W}x{H})")
# Load gold boxes
label_files = list((V2_DIR / "extracted").rglob("*.txt"))
label_files = [f for f in label_files if f.name != "classes.txt"]
gold = []
with open(label_files[0]) as f:
for line in f:
parts = line.strip().split()
if len(parts) != 5:
continue
cls, xc, yc, w, h = parts
xc, yc, w, h = float(xc), float(yc), float(w), float(h)
x1 = int((xc - w/2) * W)
y1 = int((yc - h/2) * H)
x2 = int((xc + w/2) * W)
y2 = int((yc + h/2) * H)
gold.append({
"class": "ceiling_ducted" if cls == "0" else "wall_mounted",
"x1": x1, "y1": y1, "x2": x2, "y2": y2,
})
log(f"Gold boxes: {len(gold)}")
# Tile and call Gemini
log("\n=== Calling Gemini on tiles ===")
all_dets = []
tile_idx = 0
y = 0
while y < H:
x = 0
while x < W:
x2 = min(x + TILE_SIZE, W)
y2 = min(y + TILE_SIZE, H)
tile = img.crop((x, y, x2, y2))
tile_idx += 1
try:
resp_text = call_gemini(client, PROMPT, tile)
dets = parse_json(resp_text)
for d in dets:
try:
tx1 = int(d["xmin"] / 1000 * tile.width) + x
ty1 = int(d["ymin"] / 1000 * tile.height) + y
tx2 = int(d["xmax"] / 1000 * tile.width) + x
ty2 = int(d["ymax"] / 1000 * tile.height) + y
if tx2 > tx1 and ty2 > ty1:
all_dets.append({
"label": d.get("label", "?"),
"class": d.get("class", "?"),
"x1": tx1, "y1": ty1, "x2": tx2, "y2": ty2,
})
except Exception:
continue
if dets:
log(f" Tile {tile_idx:2d} ({x:5d},{y:5d}): {len(dets)} det(s)")
except Exception as e:
log(f" Tile {tile_idx:2d} ERROR: {str(e)[:200]}")
x += TILE_SIZE - OVERLAP
y += TILE_SIZE - OVERLAP
log(f"\nTotal raw detections: {len(all_dets)}")
# Dedup by center distance
deduped = []
for d in all_dets:
cx = (d["x1"] + d["x2"]) / 2
cy = (d["y1"] + d["y2"]) / 2
dup = False
for kept in deduped:
kcx = (kept["x1"] + kept["x2"]) / 2
kcy = (kept["y1"] + kept["y2"]) / 2
if abs(cx - kcx) < 100 and abs(cy - kcy) < 100:
dup = True
break
if not dup:
deduped.append(d)
log(f"After dedup: {len(deduped)}")
by_class = {}
for d in deduped:
by_class[d["class"]] = by_class.get(d["class"], 0) + 1
log(f" By class: {by_class}")
# Score
used = set()
matches = []
for gi, g in enumerate(gold):
best_i, best_s = None, 0.0
for di, d in enumerate(deduped):
if di in used:
continue
s = iou_box(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_idx": gi,
"gold_class": g["class"],
"iou": round(best_s, 3),
"matched_det_idx": best_i,
"matched_label": deduped[best_i]["label"] if best_i is not None else None,
"matched_class": deduped[best_i]["class"] if best_i is not None else None,
})
hits_05 = sum(1 for m in matches if m["iou"] >= 0.5)
hits_01 = sum(1 for m in matches if m["iou"] >= 0.1)
mean_iou = sum(m["iou"] for m in matches) / len(matches)
class_correct = sum(1 for m in matches if m["matched_class"] == m["gold_class"])
log(f"\n=== RESULTS ===")
log(f"Gold: {len(gold)} | Detected: {len(deduped)}")
log(f"Mean IoU: {mean_iou:.3f}")
log(f"Hits @ IoU 0.5: {hits_05}/{len(gold)}")
log(f"Hits @ IoU 0.1: {hits_01}/{len(gold)}")
log(f"Class correct: {class_correct}/{len(gold)}")
log(f"\n--- Per-gold matches ---")
for m in matches:
log(f" gold {m['gold_idx']+1:2d} ({m['gold_class']:14s}) "
f"-> IoU={m['iou']:.3f} | matched_label={m['matched_label']} class={m['matched_class']}")
# Save
(OUT_DIR / "results.json").write_text(json.dumps({
"model": MODEL_ID,
"detections": deduped,
"gold": gold,
"matches": matches,
"summary": {
"gold_count": len(gold),
"det_count": len(deduped),
"mean_iou": round(mean_iou, 3),
"hits_iou_05": hits_05,
"hits_iou_01": hits_01,
"class_correct": class_correct,
}
}, indent=2))
# Visualize
overlay = img.copy()
draw = ImageDraw.Draw(overlay)
try:
font = ImageFont.truetype("arial.ttf", 18)
except:
font = ImageFont.load_default()
for g in gold:
draw.rectangle([g["x1"], g["y1"], g["x2"], g["y2"]], outline=(0, 255, 0), width=4)
for idx, d in enumerate(deduped, 1):
color = (255, 0, 0) if d["class"] == "ceiling_ducted" else (255, 100, 0)
draw.rectangle([d["x1"], d["y1"], d["x2"], d["y2"]], outline=color, width=3)
draw.text((d["x1"], d["y1"] - 20), f"{idx}.{d['label']}", fill=color, font=font)
overlay.save(OUT_DIR / "gemini_vs_gold.jpg", quality=70)
log(f"\nVisualization: {OUT_DIR / 'gemini_vs_gold.jpg'}")
save_log()
except Exception as e:
import traceback
log(f"ERROR: {e}")
log(traceback.format_exc())
save_log()
raise