hvac_fable / python_files /finetune_florence2.py
Rachel7's picture
Deploy Fable B-test analyzer
dac3297 verified
Raw History Blame Contribute Delete
7.79 kB
"""
Fine-tune Florence-2 on HVAC unit detection.
Florence-2 is designed for vision tasks and performs region/box detection well.
We fine-tune on the 13 gold box examples and test on the full cellar.
Usage:
pip install transformers torch pillow datasets peft -q
python finetune_florence2.py
Note: Florence-2 fine-tuning is done via prompt-based learning.
We create instruction-tuning examples: "Detect <tag> units" -> returns bounding boxes.
"""
from pathlib import Path
import json
import torch
from PIL import Image
import numpy as np
from transformers import AutoProcessor, AutoModelForCausalLM
import fitz
ROOT = Path(__file__).resolve().parent.parent
PDF_PATH = ROOT / "raw_pdfs" / "355 E 86th St Mechanical 100% CD Set_flattened.pdf"
TRAIN_DIR = Path(__file__).resolve().parent / "finetune_data"
TILE_SIZE = 2700
# Verified gold boxes
GOLD = [
{"tag": "AC-P", "x": 7050, "y": 1300, "w": 500, "h": 550},
{"tag": "AC-S", "x": 3970, "y": 2200, "w": 500, "h": 500},
{"tag": "AC-Q", "x": 2530, "y": 2800, "w": 500, "h": 500},
{"tag": "AC-P", "x": 2530, "y": 3650, "w": 900, "h": 650},
{"tag": "AC-P", "x": 2530, "y": 4600, "w": 900, "h": 650},
{"tag": "AC-P", "x": 5750, "y": 4450, "w": 700, "h": 500},
{"tag": "AC-T", "x": 1800, "y": 6050, "w": 500, "h": 500},
{"tag": "AC-T", "x": 3300, "y": 7220, "w": 500, "h": 500},
{"tag": "AC-U", "x": 6600, "y": 6950, "w": 500, "h": 500},
{"tag": "AC-U", "x": 9050, "y": 7310, "w": 500, "h": 500},
{"tag": "AC-T", "x": 8300, "y": 5700, "w": 500, "h": 500},
{"tag": "AC-T", "x": 9600, "y": 6200, "w": 500, "h": 500},
{"tag": "unit", "x": 8200, "y": 400, "w": 600, "h": 600},
]
DEFAULT_TILES = [
(0, 0), (2700, 0), (5400, 0), (8100, 0),
(0, 2700), (2700, 2700), (5400, 2700), (8100, 2700),
(0, 5400), (2700, 5400), (5400, 5400), (8100, 5400),
(0, 8100), (2700, 8100),
]
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 load_model_and_processor():
"""Load Florence-2 model and processor."""
print("Loading Florence-2 model...")
model_id = "microsoft/Florence-2-large"
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
trust_remote_code=True
).to(device)
return model, processor, device
def detect_boxes_with_florence2(model, processor, image: Image.Image, device: str, prompt: str = None) -> list[dict]:
"""
Use Florence-2 to detect bounding boxes in an image.
Florence-2 can run object detection with the <OD> (open-vocabulary detection) task.
"""
if prompt is None:
prompt = "<OD>Detect HVAC units with internal mechanical detail"
# Prepare input
inputs = processor(text=prompt, images=image, return_tensors="pt").to(device)
# Generate
with torch.no_grad():
generated_ids = model.generate(
input_ids=inputs["input_ids"],
pixel_values=inputs["pixel_values"],
max_new_tokens=1024,
do_sample=False,
num_beams=3,
)
# Decode output
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
# Parse bounding boxes from output
# Florence-2 returns boxes in format like: <bbox>x1,y1,x2,y2</bbox>
boxes = []
import re
bbox_pattern = r'<bbox>(\d+),(\d+),(\d+),(\d+)</bbox>'
for match in re.finditer(bbox_pattern, generated_text):
x1, y1, x2, y2 = map(int, match.groups())
# Normalize to 0-1000
w, h = image.width, image.height
x1_norm = int(x1 / w * 1000)
y1_norm = int(y1 / h * 1000)
x2_norm = int(x2 / w * 1000)
y2_norm = int(y2 / h * 1000)
boxes.append({
"xmin": x1_norm, "ymin": y1_norm, "xmax": x2_norm, "ymax": y2_norm,
"tag": "unit"
})
return boxes
def iou(a: dict, b: dict) -> float:
"""Compute IoU between two boxes."""
ax1, ay1 = a["x"], a["y"]
ax2, ay2 = ax1 + a["w"], ay1 + a["h"]
bx1, by1 = b["x"], b["y"]
bx2, by2 = bx1 + b["w"], by1 + 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_vs_gold(dets: list[dict], gold: list[dict]) -> dict:
"""Score detections against gold boxes."""
if not gold:
return {"gold_count": 0, "det_count": len(dets), "mean_iou": None}
used = set()
matches = []
for gi, g in enumerate(gold):
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 >= 0.1})
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 {
"gold_count": len(gold),
"det_count": len(dets),
"mean_iou": mean_iou,
"hits": hits,
"matches": matches,
}
def main():
# Load model
model, processor, device = load_model_and_processor()
print("\n=== TESTING FLORENCE-2 (ZERO-SHOT) ===")
print("Testing on full cellar tiles (no fine-tuning yet)...")
# Render full page
print("Rendering page...")
full_img = render_page(PDF_PATH, 2, 300)
all_dets: list[dict] = []
for tx, ty in DEFAULT_TILES:
x2 = min(tx + TILE_SIZE, full_img.width)
y2 = min(ty + TILE_SIZE, full_img.height)
tile_img = full_img.crop((tx, ty, x2, y2))
try:
# Detect with Florence-2
boxes = detect_boxes_with_florence2(model, processor, tile_img, device)
# Convert to page coordinates
for box in boxes:
x1 = int(box["xmin"] / 1000 * tile_img.width) + tx
y1 = int(box["ymin"] / 1000 * tile_img.height) + ty
x2_page = int(box["xmax"] / 1000 * tile_img.width) + tx
y2_page = int(box["ymax"] / 1000 * tile_img.height) + ty
all_dets.append({
"tag": box["tag"],
"x": x1, "y": y1, "w": x2_page - x1, "h": y2_page - y1
})
if len(boxes) > 0:
print(f" tile ({tx:5},{ty:5}): {len(boxes):2d} box(es)")
except Exception as exc:
print(f" tile ({tx:5},{ty:5}): ERROR - {exc}")
# Score
score = score_vs_gold(all_dets, GOLD)
print(f"\nTotal detections: {len(all_dets)}")
print(f"Mean IoU vs gold: {score.get('mean_iou')}")
print(f"Hits (IoU ≥ 0.1): {score.get('hits')}/{len(GOLD)}")
# Save results
out_dir = Path(__file__).resolve().parent / "output_floor_iter" / "cellar_allunits_compare"
out_dir.mkdir(parents=True, exist_ok=True)
with open(out_dir / "florence2_zeroshot_detections.json", "w") as f:
json.dump({"model": "Florence-2 (zero-shot)", "detections": all_dets}, f, indent=2)
print(f"\nResults saved: {out_dir / 'florence2_zeroshot_detections.json'}")
if __name__ == "__main__":
main()