| """Split Dataset Script |
| |
| Split dataset into train/validation/test sets. |
| """ |
|
|
| import json |
| import random |
| import hashlib |
| from pathlib import Path |
| from typing import Dict, List, Tuple |
| from dataclasses import dataclass |
| from enum import Enum |
|
|
|
|
| class SplitType(Enum): |
| """Dataset split types.""" |
| TRAIN = "train" |
| VALIDATION = "validation" |
| TEST = "test" |
|
|
|
|
| @dataclass |
| class SplitConfig: |
| """Split configuration.""" |
| train_ratio: float = 0.7 |
| val_ratio: float = 0.15 |
| test_ratio: float = 0.15 |
| seed: int = 42 |
| stratify: bool = True |
| hash_split: bool = False |
|
|
|
|
| def load_jsonl(file_path: str) -> List[Dict]: |
| """Load JSONL file.""" |
| items = [] |
| with open(file_path, "r", encoding="utf-8") as f: |
| for line in f: |
| if line.strip(): |
| items.append(json.loads(line)) |
| return items |
|
|
|
|
| def save_jsonl(file_path: str, items: List[Dict]): |
| """Save to JSONL file.""" |
| Path(file_path).parent.mkdir(parents=True, exist_ok=True) |
| with open(file_path, "w", encoding="utf-8") as f: |
| for item in items: |
| f.write(json.dumps(item, ensure_ascii=False) + "\n") |
|
|
|
|
| def split_dataset( |
| items: List[Dict], |
| config: SplitConfig |
| ) -> Dict[SplitType, List[Dict]]: |
| """Split dataset according to config.""" |
| random.seed(config.seed) |
|
|
| if config.hash_split: |
| return _hash_split(items, config) |
| elif config.stratify: |
| return _stratified_split(items, config) |
| else: |
| return _random_split(items, config) |
|
|
|
|
| def _random_split( |
| items: List[Dict], |
| config: SplitConfig |
| ) -> Dict[SplitType, List[Dict]]: |
| """Random split.""" |
| shuffled = items.copy() |
| random.shuffle(shuffled) |
|
|
| total = len(shuffled) |
| train_size = int(total * config.train_ratio) |
| val_size = int(total * config.val_ratio) |
|
|
| return { |
| SplitType.TRAIN: shuffled[:train_size], |
| SplitType.VALIDATION: shuffled[train_size:train_size + val_size], |
| SplitType.TEST: shuffled[train_size + val_size:] |
| } |
|
|
|
|
| def _stratified_split( |
| items: List[Dict], |
| config: SplitConfig |
| ) -> Dict[SplitType, List[Dict]]: |
| """Stratified split by language.""" |
| |
| buckets: Dict[str, List] = {} |
|
|
| for item in items: |
| |
| code_match = item["response"].split("```")[1:2] |
| if code_match: |
| lang = code_match[0].split("\n")[0].strip() |
| else: |
| lang = "unknown" |
|
|
| if lang not in buckets: |
| buckets[lang] = [] |
| buckets[lang].append(item) |
|
|
| |
| train, val, test = [], [], [] |
|
|
| for lang, lang_items in buckets.items(): |
| random.shuffle(lang_items) |
| total = len(lang_items) |
| train_size = int(total * config.train_ratio) |
| val_size = int(total * config.val_ratio) |
|
|
| train.extend(lang_items[:train_size]) |
| val.extend(lang_items[train_size:train_size + val_size]) |
| test.extend(lang_items[train_size + val_size:]) |
|
|
| return { |
| SplitType.TRAIN: train, |
| SplitType.VALIDATION: val, |
| SplitType.TEST: test |
| } |
|
|
|
|
| def _hash_split( |
| items: List[Dict], |
| config: SplitConfig |
| ) -> Dict[SplitType, List[Dict]]: |
| """Deterministic hash-based split.""" |
| result = {SplitType.TRAIN: [], SplitType.VALIDATION: [], SplitType.TEST: []} |
|
|
| for item in items: |
| hash_val = hashlib.md5( |
| f"{json.dumps(item, sort_keys=True)}.burme".encode() |
| ).hexdigest() |
| hash_num = int(hash_val[:8], 16) |
| normalized = hash_num / 0xFFFFFFFF |
|
|
| if normalized < config.train_ratio: |
| result[SplitType.TRAIN].append(item) |
| elif normalized < config.train_ratio + config.val_ratio: |
| result[SplitType.VALIDATION].append(item) |
| else: |
| result[SplitType.TEST].append(item) |
|
|
| return result |
|
|
|
|
| def main(): |
| """Split dataset.""" |
| import argparse |
|
|
| parser = argparse.ArgumentParser(description="Split Burme-Coder-Max Dataset") |
| parser.add_argument("input", help="Input JSONL file") |
| parser.add_argument("-o", "--output-dir", default="data/split", help="Output directory") |
| parser.add_argument("--train-ratio", type=float, default=0.7, help="Train ratio") |
| parser.add_argument("--val-ratio", type=float, default=0.15, help="Validation ratio") |
| parser.add_argument("--test-ratio", type=float, default=0.15, help="Test ratio") |
| parser.add_argument("--seed", type=int, default=42, help="Random seed") |
| parser.add_argument("--hash", action="store_true", help="Use hash-based split") |
|
|
| args = parser.parse_args() |
|
|
| print("=" * 60) |
| print("✂️ Dataset Splitter") |
| print("=" * 60) |
|
|
| |
| print(f"\n📥 Loading: {args.input}") |
| items = load_jsonl(args.input) |
| print(f" Loaded {len(items)} items") |
|
|
| |
| config = SplitConfig( |
| train_ratio=args.train_ratio, |
| val_ratio=args.val_ratio, |
| test_ratio=args.test_ratio, |
| seed=args.seed, |
| hash_split=args.hash |
| ) |
|
|
| |
| print("\n✂️ Splitting dataset...") |
| splits = split_dataset(items, config) |
|
|
| for split_type, split_items in splits.items(): |
| print(f" {split_type.value}: {len(split_items)} items") |
|
|
| |
| output_dir = Path(args.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print(f"\n💾 Saving to: {output_dir}") |
| for split_type, split_items in splits.items(): |
| output_file = output_dir / f"{split_type.value}.jsonl" |
| save_jsonl(str(output_file), split_items) |
| print(f" ✅ {output_file.name}: {len(split_items)} items") |
|
|
| print("\n" + "=" * 60) |
| print("✅ Split complete!") |
| print("=" * 60) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|