File size: 3,868 Bytes
693bf28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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 directory symlinks/copies under `splits/` for YOLOv8 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)
    
    # Load all valid/kept images
    rows = manifest.images(statuses=["deduped", "kept", "validated", "normalized"])
    if not rows:
        log.warning("splitter: no valid images found to split")
        return {"train": [], "val": [], "test": []}

    # Group image records by cluster_id
    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 + mem_len <= target_train or not splits["val"]:
            splits["train"].extend(members)
            current_train += mem_len
        elif current_val + mem_len <= target_val or not splits["test"]:
            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 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

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

    # Export split files to disk
    if copy_files:
        for split_name, members in splits.items():
            dst_img_dir = splits_dir / split_name / "images"
            dst_img_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)

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