File size: 6,354 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
"""
Prepare unified dataset from your annotated pages.

INPUT directory layout:
    yolo_v2_data/pages/
      page_001/
        image.jpg                       <-- the page image
        labels.txt                      <-- YOLO format (one per box, normalized)
      page_002/
        image.jpg
        labels.txt
      ...

OUTPUT:
    yolo_v2_data/dataset_unified/
      train/
        images/   <- copied train images
        labels/   <- YOLO labels for train
      val/
        images/
        labels/
      test/
        images/
        labels/
      gold_train.json    <- absolute-pixel gold for compare_models.py
      gold_val.json
      gold_test.json
      data.yaml          <- YOLO dataset config
      split_info.json    <- which pages went where

Splits whole pages (not boxes) so test set is truly unseen.
"""
from __future__ import annotations
import argparse
import json
import random
import shutil
from pathlib import Path
from PIL import Image

CLASS_NAMES = {0: "ceiling_ducted", 1: "wall_mounted"}


def parse_yolo_label(label_path: Path, img_w: int, img_h: int) -> list[dict]:
    """Convert YOLO normalized labels to absolute-pixel boxes."""
    boxes = []
    if not label_path.exists():
        return boxes
    for line in label_path.read_text().strip().splitlines():
        parts = line.strip().split()
        if len(parts) != 5:
            continue
        cls, xc, yc, w, h = parts
        cls_id = int(cls)
        xc, yc, w, h = float(xc), float(yc), float(w), float(h)
        boxes.append({
            "class": CLASS_NAMES.get(cls_id, f"class_{cls_id}"),
            "class_id": cls_id,
            "x1": int((xc - w/2) * img_w),
            "y1": int((yc - h/2) * img_h),
            "x2": int((xc + w/2) * img_w),
            "y2": int((yc + h/2) * img_h),
            "label": None,  # text label not in YOLO format; can be added manually
        })
    return boxes


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--source", default="yolo_v2_data/pages",
                        help="Directory containing one folder per page")
    parser.add_argument("--output", default="yolo_v2_data/dataset_unified",
                        help="Output directory")
    parser.add_argument("--train_ratio", type=float, default=0.6)
    parser.add_argument("--val_ratio", type=float, default=0.2)
    parser.add_argument("--seed", type=int, default=42)
    args = parser.parse_args()

    source = Path(args.source).resolve()
    output = Path(args.output).resolve()

    if not source.exists():
        print(f"Source directory not found: {source}")
        print(f"\nExpected layout:")
        print(f"  {source}/page_001/image.jpg + labels.txt")
        print(f"  {source}/page_002/image.jpg + labels.txt")
        print(f"  ...")
        return

    # Find pages
    pages = []
    for page_dir in sorted(source.iterdir()):
        if not page_dir.is_dir():
            continue
        img_candidates = list(page_dir.glob("*.jpg")) + list(page_dir.glob("*.png"))
        label_candidates = list(page_dir.glob("*.txt"))
        if not img_candidates or not label_candidates:
            print(f"Skipping {page_dir.name}: missing image or label")
            continue
        pages.append({
            "page_id": page_dir.name,
            "image": img_candidates[0],
            "label": label_candidates[0],
        })

    if not pages:
        print(f"No valid pages in {source}")
        return

    print(f"Found {len(pages)} pages")

    # Shuffle and split BY PAGE (so test set is truly unseen)
    random.seed(args.seed)
    random.shuffle(pages)
    n = len(pages)
    n_train = max(1, int(n * args.train_ratio))
    n_val = max(1, int(n * args.val_ratio))
    train_pages = pages[:n_train]
    val_pages = pages[n_train:n_train + n_val]
    test_pages = pages[n_train + n_val:]

    if not test_pages:
        # Move one from val to test if test is empty
        if len(val_pages) > 1:
            test_pages.append(val_pages.pop())
        else:
            test_pages.append(train_pages.pop())

    print(f"Split: {len(train_pages)} train / {len(val_pages)} val / {len(test_pages)} test")

    # Create output structure
    if output.exists():
        shutil.rmtree(output)
    for split in ["train", "val", "test"]:
        (output / split / "images").mkdir(parents=True, exist_ok=True)
        (output / split / "labels").mkdir(parents=True, exist_ok=True)

    # Copy files + build gold JSON
    split_info = {}
    for split_name, split_pages in [("train", train_pages), ("val", val_pages), ("test", test_pages)]:
        gold_pages_list = []
        page_ids = []
        for p in split_pages:
            page_ids.append(p["page_id"])
            # Copy image and label
            target_img = output / split_name / "images" / f"{p['page_id']}{p['image'].suffix}"
            target_lbl = output / split_name / "labels" / f"{p['page_id']}.txt"
            shutil.copy(p["image"], target_img)
            shutil.copy(p["label"], target_lbl)
            # Build gold entry
            img = Image.open(p["image"])
            w, h = img.size
            gold_boxes = parse_yolo_label(p["label"], w, h)
            gold_pages_list.append({
                "page_id": p["page_id"],
                "image_width": w,
                "image_height": h,
                "gold": gold_boxes,
            })
        # Write gold JSON for this split
        (output / f"gold_{split_name}.json").write_text(
            json.dumps(gold_pages_list, indent=2)
        )
        split_info[split_name] = page_ids
        print(f"  {split_name}: {len(split_pages)} pages, "
              f"{sum(len(g['gold']) for g in gold_pages_list)} boxes")

    # data.yaml for YOLO
    data_yaml = {
        "path": str(output).replace("\\", "/"),
        "train": "train/images",
        "val": "val/images",
        "test": "test/images",
        "nc": 2,
        "names": list(CLASS_NAMES.values()),
    }
    import yaml
    (output / "data.yaml").write_text(yaml.dump(data_yaml, sort_keys=False))

    # Split info
    (output / "split_info.json").write_text(json.dumps(split_info, indent=2))

    print(f"\nDataset ready at: {output}")
    print(f"  YOLO config:  {output}/data.yaml")
    print(f"  Gold (eval):  {output}/gold_{{train,val,test}}.json")


if __name__ == "__main__":
    main()