File size: 4,251 Bytes
11a414e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Dataset Splitter Engine.

Stratified, cluster-aware train / val / test dataset partitioning:
- Prevents data leakage by ensuring all images in the same visual `cluster_id`
  are assigned to the SAME split (train, val, or test).
- Maintains balanced class distributions across splits according to target ratios (e.g. 70 / 15 / 15).
- Exports organized image & label directories under `data/splits/` for YOLOv8 model training.
"""
from __future__ import annotations

import logging
import random
import shutil
from collections import defaultdict
from pathlib import Path
from typing import Sequence

from .manifest import Manifest

log = logging.getLogger(__name__)


def create_cluster_splits(
    manifest: Manifest,
    train_ratio: float = 0.70,
    val_ratio: float = 0.15,
    test_ratio: float = 0.15,
    seed: int = 42,
) -> dict[str, list[dict]]:
    """Partition valid images into cluster-isolated train/val/test splits."""
    random.seed(seed)

    rows = manifest.images(statuses=["deduped", "kept", "validated", "normalized"])
    if not rows:
        log.warning("splitter: no valid images found to split")
        return {"train": [], "val": [], "test": []}

    clusters: dict[str, list[dict]] = defaultdict(list)
    for r in rows:
        cid = r["cluster_id"] or r["image_id"]
        clusters[cid].append(r)

    cluster_items = list(clusters.items())
    random.shuffle(cluster_items)

    total_count = len(rows)
    target_train = int(total_count * train_ratio)
    target_val = int(total_count * val_ratio)

    splits: dict[str, list[dict]] = {"train": [], "val": [], "test": []}

    current_train = 0
    current_val = 0

    for cid, members in cluster_items:
        mem_len = len(members)
        if current_train < target_train:
            splits["train"].extend(members)
            current_train += mem_len
        elif current_val < target_val:
            splits["val"].extend(members)
            current_val += mem_len
        else:
            splits["test"].extend(members)

    return splits


def run(
    manifest: Manifest,
    cfg: dict,
    data_dir: Path,
    splits_dir: Path,
    train_ratio: float = 0.70,
    val_ratio: float = 0.15,
    test_ratio: float = 0.15,
    copy_files: bool = True,
    seed: int = 42,
) -> dict[str, int]:
    """Execute cluster-isolated dataset split and write image & label files to splits directory."""
    splits = create_cluster_splits(
        manifest, train_ratio=train_ratio, val_ratio=val_ratio, test_ratio=test_ratio, seed=seed
    )

    stats = {
        "train": len(splits["train"]),
        "val": len(splits["val"]),
        "test": len(splits["test"]),
        "total_split": sum(len(s) for s in splits.values()),
    }

    if not stats["total_split"]:
        log.warning("splitter: 0 images split")
        return stats

    with manifest.transaction():
        for split_name, members in splits.items():
            for m in members:
                manifest.update_image(m["image_id"], split=split_name)

    auto_labels_dir = data_dir / "annotated_auto" / "labels"

    if copy_files:
        for split_name, members in splits.items():
            dst_img_dir = splits_dir / split_name / "images"
            dst_lbl_dir = splits_dir / split_name / "labels"
            dst_img_dir.mkdir(parents=True, exist_ok=True)
            dst_lbl_dir.mkdir(parents=True, exist_ok=True)

            for m in members:
                src_rel = m.get("norm_path") or m.get("orig_path")
                if not src_rel:
                    continue
                src_path = data_dir / src_rel
                if src_path.exists():
                    dst_path = dst_img_dir / src_path.name
                    if not dst_path.exists():
                        shutil.copy2(src_path, dst_path)

                    # Copy matching label file if available
                    label_name = f"{src_path.stem}.txt"
                    src_label = auto_labels_dir / label_name
                    if src_label.exists():
                        dst_label = dst_lbl_dir / label_name
                        if not dst_label.exists():
                            shutil.copy2(src_label, dst_label)

    log.info("splitter split summary: %s", stats)
    return stats