""" Fine-tune YOLOv8 on HVAC unit detection. YOLOv8 is simpler to set up and fine-tune than DETR. We create YOLO format annotations from our crops and fine-tune the model. Usage: pip install ultralytics -q python finetune_yolov8.py [--epochs 50] """ from pathlib import Path import json import yaml from PIL import Image import fitz from ultralytics import YOLO import torch 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" YOLO_DIR = Path(__file__).resolve().parent / "yolo_dataset" 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 prepare_yolo_dataset(): """Convert crops to YOLO format.""" print("Preparing YOLO dataset...") YOLO_DIR.mkdir(exist_ok=True) (YOLO_DIR / "images" / "train").mkdir(parents=True, exist_ok=True) (YOLO_DIR / "labels" / "train").mkdir(parents=True, exist_ok=True) crops_annotation = json.loads((TRAIN_DIR / "crops_annotation.json").read_text()) for crop_info in crops_annotation: crop_path = TRAIN_DIR / "crops" / crop_info["image_path"] img = Image.open(crop_path) w, h = img.size # Copy image img.save(YOLO_DIR / "images" / "train" / crop_path.name) # Create YOLO label file (class x_center y_center width height in normalized coords) box = crop_info["box"] x_center = (box["x1_in_crop"] + box["x2_in_crop"]) / 2 / w y_center = (box["y1_in_crop"] + box["y2_in_crop"]) / 2 / h box_w = (box["x2_in_crop"] - box["x1_in_crop"]) / w box_h = (box["y2_in_crop"] - box["y1_in_crop"]) / h label_path = YOLO_DIR / "labels" / "train" / crop_path.stem + ".txt" with open(label_path, "w") as f: f.write(f"0 {x_center} {y_center} {box_w} {box_h}\n") # Create dataset.yaml dataset_yaml = { "path": str(YOLO_DIR), "train": "images/train", "val": None, "test": None, "nc": 1, "names": {0: "hvac_unit"} } with open(YOLO_DIR / "data.yaml", "w") as f: yaml.dump(dataset_yaml, f) print(f"Dataset ready: {YOLO_DIR}") return str(YOLO_DIR / "data.yaml") 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 iou(a: dict, b: dict) -> float: 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: 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, } def main(epochs: int = 50): device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Using device: {device}\n") # Prepare dataset dataset_yaml = prepare_yolo_dataset() # Load model print("Loading YOLOv8 nano model...") model = YOLO("yolov8n.pt") # Fine-tune print(f"Fine-tuning for {epochs} epochs...") model.train( data=dataset_yaml, epochs=epochs, imgsz=640, batch=1, device=0 if torch.cuda.is_available() else "cpu", verbose=False, patience=50, ) # Evaluate on full cellar print("\n=== EVALUATING ON FULL CELLAR ===") 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: # Infer results = model(tile_img, conf=0.3, verbose=False) for result in results: boxes = result.boxes for box in boxes: x1, y1, x2_box, y2_box = box.xyxy[0].cpu().numpy() conf = box.conf[0].cpu().numpy() # Convert to page coordinates x1_page = int(x1) + tx y1_page = int(y1) + ty x2_page = int(x2_box) + tx y2_page = int(y2_box) + ty all_dets.append({ "tag": "unit", "x": x1_page, "y": y1_page, "w": x2_page - x1_page, "h": y2_page - y1_page, "confidence": float(conf), }) if len(all_dets) > sum(1 for d in all_dets if d["x"] < tx + 1 and d["y"] < ty + 1): n_new = len([d for d in all_dets if d["x"] >= tx and d["x"] < x2 and d["y"] >= ty and d["y"] < y2]) if n_new > 0: print(f" tile ({tx:5},{ty:5}): {n_new:2d} detection(s)") 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 / "yolov8_finetuned_detections.json", "w") as f: json.dump({"model": "YOLOv8 (fine-tuned on 13 examples)", "detections": all_dets}, f, indent=2) print(f"\nResults saved: {out_dir / 'yolov8_finetuned_detections.json'}") print(f"Model saved: {Path('runs/detect/train/weights/best.pt')}") if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--epochs", type=int, default=50, help="Number of training epochs") args = parser.parse_args() main(epochs=args.epochs)