Download experiments/prepare_dataset.py from dormant78612/nextgenyeild-api: direct link, hf CLI and curl.
- Browser
- Download file 4.8 kB
-
https://huggingface.co/spaces/dormant78612/nextgenyeild-api/resolve/main/experiments/prepare_dataset.py
- Command line
-
hf download hf://spaces/dormant78612/nextgenyeild-api/experiments/prepare_dataset.py
-
curl -L -o prepare_dataset.py https://huggingface.co/spaces/dormant78612/nextgenyeild-api/resolve/main/experiments/prepare_dataset.py
4.8 kB
| import os | |
| import sys | |
| import shutil | |
| import random | |
| import json | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from pathlib import Path | |
| from tqdm import tqdm | |
| PROJECT_ROOT = Path(__file__).resolve().parent.parent | |
| # Source path on Windows / WSL | |
| DEFAULT_SOURCE = Path("/mnt/c/Users/Fahad/Downloads/WGSP_Extracted/WGSP-CN-Data") | |
| STAGE_MAPPING = { | |
| "1-Tillering": "0_tillering", | |
| "2-Jointing": "1_jointing", | |
| "3-BH": "2_booting", | |
| "4-Flowering": "3_anthesis", | |
| "5-Filling": "4_grain_filling", | |
| "6-Maturity": "5_maturity", | |
| } | |
| SPLIT_RATIOS = { | |
| "train": 0.70, | |
| "validation": 0.15, | |
| "test": 0.15, | |
| } | |
| SEED = 42 | |
| def prepare_dataset(source_dir: Path = DEFAULT_SOURCE, num_workers: int = 16): | |
| print("=" * 65) | |
| print("NextGenYeild: WGSP Dataset Preparation & Partitioning (Phase 5)") | |
| print("=" * 65) | |
| if not source_dir.exists(): | |
| raise FileNotFoundError(f"Source directory not found: {source_dir}") | |
| random.seed(SEED) | |
| copy_tasks = [] | |
| summary = { | |
| "source": str(source_dir), | |
| "seed": SEED, | |
| "splits": {"train": {}, "validation": {}, "test": {}}, | |
| "totals": {"train": 0, "validation": 0, "test": 0, "overall": 0}, | |
| } | |
| print("\n1. Scanning source folders and computing stratified splits (70/15/15)...") | |
| for src_folder_name, target_class_name in STAGE_MAPPING.items(): | |
| src_path = source_dir / src_folder_name | |
| if not src_path.exists(): | |
| raise FileNotFoundError(f"Missing expected stage folder: {src_path}") | |
| # List all image files | |
| valid_exts = {".png", ".jpg", ".jpeg", ".PNG", ".JPG", ".JPEG"} | |
| files = sorted([f for f in src_path.iterdir() if f.is_file() and f.suffix in valid_exts]) | |
| total_files = len(files) | |
| # Deterministic shuffle | |
| random.shuffle(files) | |
| n_train = int(total_files * SPLIT_RATIOS["train"]) | |
| n_val = int(total_files * SPLIT_RATIOS["validation"]) | |
| # Ensure remaining go to test so no off-by-one drops | |
| n_test = total_files - n_train - n_val | |
| train_files = files[:n_train] | |
| val_files = files[n_train : n_train + n_val] | |
| test_files = files[n_train + n_val :] | |
| summary["splits"]["train"][target_class_name] = len(train_files) | |
| summary["splits"]["validation"][target_class_name] = len(val_files) | |
| summary["splits"]["test"][target_class_name] = len(test_files) | |
| summary["totals"]["train"] += len(train_files) | |
| summary["totals"]["validation"] += len(val_files) | |
| summary["totals"]["test"] += len(test_files) | |
| summary["totals"]["overall"] += total_files | |
| print(f" • {src_folder_name:12s} -> {target_class_name:16s}: " | |
| f"Total={total_files:5d} (Train={len(train_files):5d}, Val={len(val_files):4d}, Test={len(test_files):4d})") | |
| # Prepare copy tasks | |
| for split_name, split_files in [("train", train_files), ("validation", val_files), ("test", test_files)]: | |
| dest_dir = PROJECT_ROOT / "data" / split_name / target_class_name | |
| dest_dir.mkdir(parents=True, exist_ok=True) | |
| for f in split_files: | |
| dest_file = dest_dir / f.name | |
| copy_tasks.append((f, dest_file)) | |
| print(f"\n2. Total dataset breakdown:") | |
| print(f" Train set : {summary['totals']['train']:,} images ({summary['totals']['train']/summary['totals']['overall']*100:.1f}%)") | |
| print(f" Validation set : {summary['totals']['validation']:,} images ({summary['totals']['validation']/summary['totals']['overall']*100:.1f}%)") | |
| print(f" Test set : {summary['totals']['test']:,} images ({summary['totals']['test']/summary['totals']['overall']*100:.1f}%)") | |
| print(f" Total images : {summary['totals']['overall']:,}") | |
| # Copy files in parallel | |
| print(f"\n3. Copying {len(copy_tasks):,} files using {num_workers} parallel workers...") | |
| def _copy(src_dst): | |
| src, dst = src_dst | |
| if not dst.exists() or dst.stat().st_size != src.stat().st_size: | |
| shutil.copy2(src, dst) | |
| return True | |
| with ThreadPoolExecutor(max_workers=num_workers) as executor: | |
| futures = [executor.submit(_copy, task) for task in copy_tasks] | |
| for _ in tqdm(as_completed(futures), total=len(copy_tasks), desc="Copying images"): | |
| pass | |
| # Save summary manifest | |
| manifest_path = PROJECT_ROOT / "data" / "dataset_summary.json" | |
| with open(manifest_path, "w") as f: | |
| json.dump(summary, f, indent=2) | |
| print(f"\n4. Dataset preparation complete!") | |
| print(f" Manifest saved to: {manifest_path}") | |
| print("=" * 65) | |
| if __name__ == "__main__": | |
| src = DEFAULT_SOURCE | |
| if len(sys.argv) > 1: | |
| src = Path(sys.argv[1]) | |
| prepare_dataset(source_dir=src) | |