Spaces:
Paused
Paused
Download python_files/finetune_detr.py from Rachel7/hvac_fable: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/python_files/finetune_detr.py
- Command line
-
hf download hf://spaces/Rachel7/hvac_fable/python_files/finetune_detr.py
-
curl -L -o finetune_detr.py https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/python_files/finetune_detr.py
10.6 kB
| """ | |
| Fine-tune DETR (Detection Transformer) on HVAC unit detection. | |
| DETR is simpler than Florence-2 for object detection and works well with small datasets. | |
| We train on the 13 gold examples and test on the full cellar. | |
| Usage: | |
| pip install transformers torch pillow datasets torchvision -q | |
| python finetune_detr.py [--epochs 50] | |
| """ | |
| from pathlib import Path | |
| import json | |
| import torch | |
| from PIL import Image | |
| import fitz | |
| from transformers import AutoImageProcessor, AutoModelForObjectDetection | |
| from torch.utils.data import Dataset, DataLoader | |
| from torch.optim import AdamW | |
| import argparse | |
| 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 | |
| NUM_CLASSES = 1 # Only one class: "hvac_unit" | |
| # 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), | |
| ] | |
| class HVACUnitDataset(Dataset): | |
| """Dataset for HVAC unit detection.""" | |
| def __init__(self, image_processor): | |
| self.image_processor = image_processor | |
| self.crops_annotation = self._load_crops_annotation() | |
| def _load_crops_annotation(self): | |
| with open(TRAIN_DIR / "crops_annotation.json") as f: | |
| return json.load(f) | |
| def __len__(self): | |
| return len(self.crops_annotation) | |
| def __getitem__(self, idx): | |
| crop_info = self.crops_annotation[idx] | |
| crop_path = TRAIN_DIR / "crops" / crop_info["image_path"] | |
| # Load image | |
| image = Image.open(crop_path).convert("RGB") | |
| w, h = image.size | |
| # Get box in crop coordinates (normalized to 0-1) | |
| box = crop_info["box"] | |
| x1_norm = box["x1_in_crop"] / w | |
| y1_norm = box["y1_in_crop"] / h | |
| x2_norm = box["x2_in_crop"] / w | |
| y2_norm = box["y2_in_crop"] / h | |
| # Prepare image and annotations for DETR | |
| encoding = self.image_processor(images=image, return_tensors="pt") | |
| # Remove batch dimension | |
| for k, v in encoding.items(): | |
| encoding[k] = v.squeeze() | |
| # DETR expects: | |
| # - boxes: list of [x_center, y_center, width, height] in [0, 1] | |
| # - class_labels: list of class indices | |
| x_center = (x1_norm + x2_norm) / 2 | |
| y_center = (y1_norm + y2_norm) / 2 | |
| box_width = x2_norm - x1_norm | |
| box_height = y2_norm - y1_norm | |
| encoding["class_labels"] = torch.tensor([0]) # Class 0 for all units | |
| encoding["boxes"] = torch.tensor([[x_center, y_center, box_width, box_height]]) | |
| return encoding | |
| def collate_fn(batch): | |
| """Collate function for DataLoader.""" | |
| pixel_values = torch.stack([item["pixel_values"] for item in batch]) | |
| pixel_mask = torch.stack([item["pixel_mask"] for item in batch]) | |
| class_labels = [item["class_labels"] for item in batch] | |
| boxes = [item["boxes"] for item in batch] | |
| batch_dict = { | |
| "pixel_values": pixel_values, | |
| "pixel_mask": pixel_mask, | |
| "class_labels": class_labels, | |
| "boxes": boxes, | |
| } | |
| return batch_dict | |
| 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: | |
| """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(epochs: int = 30): | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| print(f"Using device: {device}") | |
| # Load model and processor | |
| print("Loading DETR model...") | |
| model_id = "facebook/detr-resnet50" | |
| image_processor = AutoImageProcessor.from_pretrained(model_id) | |
| model = AutoModelForObjectDetection.from_pretrained( | |
| model_id, num_labels=NUM_CLASSES, ignore_mismatched_sizes=True | |
| ).to(device) | |
| # Create dataset and dataloader | |
| print("Preparing dataset...") | |
| train_dataset = HVACUnitDataset(image_processor) | |
| train_dataloader = DataLoader(train_dataset, batch_size=1, shuffle=True, collate_fn=collate_fn) | |
| # Optimizer | |
| optimizer = AdamW(model.parameters(), lr=1e-4) | |
| # Training loop | |
| print(f"\nTraining for {epochs} epochs...") | |
| model.train() | |
| for epoch in range(epochs): | |
| total_loss = 0 | |
| for batch_idx, batch in enumerate(train_dataloader): | |
| # Forward pass | |
| pixel_values = batch["pixel_values"].to(device) | |
| pixel_mask = batch["pixel_mask"].to(device) | |
| # Prepare targets | |
| targets = [] | |
| for i in range(len(batch["class_labels"])): | |
| target = { | |
| "class_labels": batch["class_labels"][i].to(device), | |
| "boxes": batch["boxes"][i].to(device), | |
| } | |
| targets.append(target) | |
| # Forward | |
| outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=targets) | |
| loss = outputs.loss | |
| # Backward | |
| optimizer.zero_grad() | |
| loss.backward() | |
| optimizer.step() | |
| total_loss += loss.item() | |
| avg_loss = total_loss / len(train_dataloader) | |
| if (epoch + 1) % 10 == 0: | |
| print(f" Epoch {epoch + 1}/{epochs}: loss={avg_loss:.4f}") | |
| # Save model | |
| model_path = Path(__file__).resolve().parent / "detr_finetuned" | |
| model_path.mkdir(exist_ok=True) | |
| model.save_pretrained(model_path) | |
| image_processor.save_pretrained(model_path) | |
| print(f"\nModel saved to: {model_path}") | |
| # Evaluate on full cellar | |
| print("\n=== EVALUATING ON FULL CELLAR ===") | |
| model.eval() | |
| 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: | |
| # Prepare input | |
| inputs = image_processor(images=tile_img, return_tensors="pt").to(device) | |
| # Inference | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| # Post-process | |
| results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=[(tile_img.height, tile_img.width)]) | |
| for result in results: | |
| boxes = result["boxes"] | |
| scores = result["scores"] | |
| for box, score in zip(boxes, scores): | |
| if score < 0.3: # Low confidence threshold | |
| continue | |
| x1, y1, x2, y2 = box.cpu().numpy() | |
| # Convert to page coordinates | |
| x1_page = int(x1) + tx | |
| y1_page = int(y1) + ty | |
| x2_page = int(x2) + tx | |
| y2_page = int(y2) + ty | |
| all_dets.append({ | |
| "tag": "unit", | |
| "x": x1_page, | |
| "y": y1_page, | |
| "w": x2_page - x1_page, | |
| "h": y2_page - y1_page, | |
| "confidence": float(score), | |
| }) | |
| if len(all_dets) > 0: | |
| print(f" tile ({tx:5},{ty:5}): {len(results[0]['boxes']):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 / "detr_finetuned_detections.json", "w") as f: | |
| json.dump({"model": "DETR (fine-tuned on 13 examples)", "detections": all_dets}, f, indent=2) | |
| print(f"\nResults saved: {out_dir / 'detr_finetuned_detections.json'}") | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--epochs", type=int, default=30, help="Number of training epochs") | |
| args = parser.parse_args() | |
| main(epochs=args.epochs) | |