Download google_drive_export/pipeline/splitter.py from FaustDerLegende/Micro_component_dataset: direct link, hf CLI and curl.
- Browser
- Download file 3.87 kB
-
https://huggingface.co/datasets/FaustDerLegende/Micro_component_dataset/resolve/main/google_drive_export/pipeline/splitter.py
- Command line
-
hf download hf://datasets/FaustDerLegende/Micro_component_dataset/google_drive_export/pipeline/splitter.py
-
curl -L -o splitter.py https://huggingface.co/datasets/FaustDerLegende/Micro_component_dataset/resolve/main/google_drive_export/pipeline/splitter.py
3.87 kB
| """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 | |