File size: 3,482 Bytes
d2efaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import math
import random
import shutil
from pathlib import Path
from typing import List


IMG_EXTS = {".jpg", ".jpeg", ".JPG", ".JPEG"}


def list_images(root: Path) -> List[Path]:
    files: List[Path] = []
    for p in root.rglob("*"):
        if p.is_file() and p.suffix in IMG_EXTS:
            files.append(p)
    return files


def clean_dir(p: Path) -> None:
    if p.exists():
        for child in p.iterdir():
            if child.is_file():
                child.unlink()
            else:
                shutil.rmtree(child)


def copy_files(files: List[Path], dst_dir: Path) -> None:
    dst_dir.mkdir(parents=True, exist_ok=True)
    for f in files:
        shutil.copy2(f, dst_dir / f.name)


def main():
    ap = argparse.ArgumentParser(description="Prepare train/val/test splits from a raw images folder (Route B).")
    ap.add_argument("--src", type=Path, required=True, help="Root folder containing raw images (recursively)")
    ap.add_argument("--dst", type=Path, default=Path("data"), help="Destination data folder containing splits")
    ap.add_argument("--train", type=float, default=1.0, help="Train ratio (0..1)")
    ap.add_argument("--val", type=float, default=0.0, help="Validation ratio (0..1)")
    ap.add_argument("--test", type=float, default=0.0, help="Test ratio (0..1)")
    ap.add_argument("--seed", type=int, default=42, help="Random seed")
    ap.add_argument("--clean", action="store_true", help="Clean split folders before copying")
    args = ap.parse_args()

    total_ratio = args.train + args.val + args.test
    if not (0.999 <= total_ratio <= 1.001):
        raise SystemExit(f"Ratios must sum to 1.0; got {total_ratio}")

    imgs = list_images(args.src)
    if not imgs:
        raise SystemExit(f"No JPEG images found under {args.src}")

    random.seed(args.seed)
    random.shuffle(imgs)

    n = len(imgs)
    n_train = int(math.floor(n * args.train))
    n_val = int(math.floor(n * args.val))
    n_test = n - n_train - n_val

    train_files = imgs[:n_train]
    val_files = imgs[n_train:n_train + n_val]
    test_files = imgs[n_train + n_val:]

    print(f"Total images: {n} -> train {len(train_files)}, val {len(val_files)}, test {len(test_files)}")

    for split, files in (("train", train_files), ("validation", val_files), ("test", test_files)):
        split_dir = args.dst / split
        if args.clean:
            clean_dir(split_dir)
        if files:
            copy_files(files, split_dir)
            print(f"Copied {len(files)} files to {split_dir}")

    # Generate metadata.csv for each existing split using existing extractor
    try:
        from scripts.extract_split_metadata import extract_split  # type: ignore
    except Exception:
        # Fallback: import relative to this file
        import sys
        here = Path(__file__).resolve().parent
        if str(here) not in sys.path:
            sys.path.insert(0, str(here))
        try:
            from extract_split_metadata import extract_split  # type: ignore
        except Exception as e:
            raise SystemExit(f"Failed to import extractor: {e}")

    written = []
    for split in ("train", "validation", "test"):
        split_dir = args.dst / split
        if split_dir.exists():
            csv_path = extract_split(split_dir)
            written.append(csv_path)

    print("Done. Metadata files:")
    for p in written:
        print(p)


if __name__ == "__main__":
    main()