File size: 10,627 Bytes
dac3297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""
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)