File size: 5,379 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
"""
Prepare training data for Florence-2 fine-tuning.

Extracts the 13 gold boxes from the PDF and creates:
- Cropped images (for visualization + reference)
- COCO format annotations (for training)
- Simple JSON with coordinates (for testing)

Usage:
    python prepare_finetune_data.py
"""
from pathlib import Path
import json
import fitz
from PIL import Image
import numpy as np

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"

# Verified gold boxes from cellar_refined.log
GOLD = [
    {"tag": "AC-P",  "x": 7050, "y": 1300, "w": 500, "h": 550, "id": 1},
    {"tag": "AC-S",  "x": 3970, "y": 2200, "w": 500, "h": 500, "id": 2},
    {"tag": "AC-Q",  "x": 2530, "y": 2800, "w": 500, "h": 500, "id": 3},
    {"tag": "AC-P",  "x": 2530, "y": 3650, "w": 900, "h": 650, "id": 4},
    {"tag": "AC-P",  "x": 2530, "y": 4600, "w": 900, "h": 650, "id": 5},
    {"tag": "AC-P",  "x": 5750, "y": 4450, "w": 700, "h": 500, "id": 6},
    {"tag": "AC-T",  "x": 1800, "y": 6050, "w": 500, "h": 500, "id": 7},
    {"tag": "AC-T",  "x": 3300, "y": 7220, "w": 500, "h": 500, "id": 8},
    {"tag": "AC-U",  "x": 6600, "y": 6950, "w": 500, "h": 500, "id": 9},
    {"tag": "AC-U",  "x": 9050, "y": 7310, "w": 500, "h": 500, "id": 10},
    {"tag": "AC-T",  "x": 8300, "y": 5700, "w": 500, "h": 500, "id": 11},
    {"tag": "AC-T",  "x": 9600, "y": 6200, "w": 500, "h": 500, "id": 12},
    {"tag": "unit",  "x": 8200, "y": 400, "w": 600, "h": 600, "id": 13},
]

# Expand boxes slightly to include context
EXPANSION = 100  # pixels to add on each side

def render_pdf_to_image(pdf_path: Path, page_num: int, dpi: int) -> Image.Image:
    """Render PDF page to image at specified DPI."""
    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 main():
    TRAIN_DIR.mkdir(parents=True, exist_ok=True)

    print("Rendering full PDF page at 300 DPI...")
    full_img = render_pdf_to_image(PDF_PATH, 2, 300)
    print(f"Full image: {full_img.width}x{full_img.height}")

    # Create subdirectories
    (TRAIN_DIR / "images").mkdir(exist_ok=True)
    (TRAIN_DIR / "crops").mkdir(exist_ok=True)

    # Save full image
    full_img.save(TRAIN_DIR / "images" / "full_page.png")

    # Extract crops and create annotations
    crops = []
    coco_images = []
    coco_annotations = []
    annotation_id = 1

    for box in GOLD:
        img_id = box["id"]
        tag = box["tag"]

        # Get expanded box (with context)
        x1 = max(0, box["x"] - EXPANSION)
        y1 = max(0, box["y"] - EXPANSION)
        x2 = min(full_img.width, box["x"] + box["w"] + EXPANSION)
        y2 = min(full_img.height, box["y"] + box["h"] + EXPANSION)

        # Extract crop
        crop_img = full_img.crop((x1, y1, x2, y2))
        crop_path = TRAIN_DIR / "crops" / f"unit_{img_id:02d}_{tag}.png"
        crop_img.save(crop_path)

        # Adjust box coordinates to crop-relative
        box_x1_in_crop = box["x"] - x1
        box_y1_in_crop = box["y"] - y1
        box_x2_in_crop = box_x1_in_crop + box["w"]
        box_y2_in_crop = box_y1_in_crop + box["h"]

        crops.append({
            "image_id": img_id,
            "image_path": str(crop_path.name),
            "crop_bounds": [x1, y1, x2, y2],
            "tag": tag,
            "box": {
                "x": box["x"],
                "y": box["y"],
                "w": box["w"],
                "h": box["h"],
                "x1_in_crop": box_x1_in_crop,
                "y1_in_crop": box_y1_in_crop,
                "x2_in_crop": box_x2_in_crop,
                "y2_in_crop": box_y2_in_crop,
            }
        })

        # COCO format
        coco_images.append({
            "id": img_id,
            "file_name": str(crop_path.name),
            "width": crop_img.width,
            "height": crop_img.height,
        })

        coco_annotations.append({
            "id": annotation_id,
            "image_id": img_id,
            "category_id": 1,  # All units in same category
            "bbox": [box_x1_in_crop, box_y1_in_crop, box["w"], box["h"]],
            "area": box["w"] * box["h"],
            "iscrowd": 0,
        })
        annotation_id += 1

    # Save crop annotations
    with open(TRAIN_DIR / "crops_annotation.json", "w") as f:
        json.dump(crops, f, indent=2)

    # Save COCO format
    coco = {
        "images": coco_images,
        "annotations": coco_annotations,
        "categories": [{"id": 1, "name": "hvac_unit"}],
    }
    with open(TRAIN_DIR / "coco_annotation.json", "w") as f:
        json.dump(coco, f, indent=2)

    print(f"\nCreated {len(crops)} training examples:")
    print(f"  Crops: {TRAIN_DIR / 'crops'}")
    print(f"  Annotations: {TRAIN_DIR / 'crops_annotation.json'}")
    print(f"  COCO format: {TRAIN_DIR / 'coco_annotation.json'}")
    print(f"  Full page: {TRAIN_DIR / 'images' / 'full_page.png'}")

    # Print summary
    print("\nTraining examples:")
    for crop in crops:
        print(f"  {crop['image_id']:2d}. {crop['tag']:5s} @ ({crop['box']['x']:5d}, {crop['box']['y']:5d}) {crop['box']['w']}x{crop['box']['h']}")


if __name__ == "__main__":
    main()