Download src/data_processing.py from amkyawdev/burme-coder-max: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/datasets/amkyawdev/burme-coder-max/resolve/d9243d8a153e4179fa2bf1c993522c79cd37faaf/src/data_processing.py
- Command line
-
hf download hf://datasets/amkyawdev/burme-coder-max@d9243d8a153e4179fa2bf1c993522c79cd37faaf/src/data_processing.py
-
curl -L -o data_processing.py https://huggingface.co/datasets/amkyawdev/burme-coder-max/resolve/d9243d8a153e4179fa2bf1c993522c79cd37faaf/src/data_processing.py
10.7 kB
| """Data Validation and Split Module | |
| Validates and splits datasets for training/validation/testing. | |
| """ | |
| import json | |
| import random | |
| import hashlib | |
| from pathlib import Path | |
| from typing import List, Dict, Tuple, Optional, Callable | |
| from dataclasses import dataclass | |
| from enum import Enum | |
| import re | |
| class SplitType(Enum): | |
| """Dataset split types.""" | |
| TRAIN = "train" | |
| VALIDATION = "validation" | |
| TEST = "test" | |
| class DatasetItem: | |
| """Single dataset item.""" | |
| system: str | |
| instruction: str | |
| response: str | |
| metadata: Dict | |
| class ValidationResult: | |
| """Validation result.""" | |
| valid: bool | |
| errors: List[str] | |
| warnings: List[str] | |
| class DataValidator: | |
| """Validate dataset items.""" | |
| MIN_RESPONSE_LENGTH = 10 | |
| MAX_RESPONSE_LENGTH = 10000 | |
| MIN_INSTRUCTION_LENGTH = 3 | |
| def validate_item(cls, item: Dict) -> ValidationResult: | |
| """Validate a single dataset item.""" | |
| errors = [] | |
| warnings = [] | |
| # Check required fields | |
| required_fields = ["system", "instruction", "response"] | |
| for field in required_fields: | |
| if field not in item: | |
| errors.append(f"Missing required field: {field}") | |
| elif not isinstance(item[field], str): | |
| errors.append(f"Field '{field}' must be a string") | |
| if errors: | |
| return ValidationResult(valid=False, errors=errors, warnings=warnings) | |
| # Validate lengths | |
| if len(item["response"]) < cls.MIN_RESPONSE_LENGTH: | |
| errors.append(f"Response too short: {len(item['response'])} chars") | |
| if len(item["response"]) > cls.MAX_RESPONSE_LENGTH: | |
| warnings.append(f"Response very long: {len(item['response'])} chars") | |
| if len(item["instruction"]) < cls.MIN_INSTRUCTION_LENGTH: | |
| errors.append(f"Instruction too short: {len(item['instruction'])} chars") | |
| # Check for code blocks | |
| if "```" not in item["response"]: | |
| warnings.append("Response contains no code blocks") | |
| # Check for Myanmar content | |
| myanmar_pattern = re.compile(r"[\u1000-\u109f]+") | |
| has_myanmar = bool(myanmar_pattern.search(item["instruction"])) | |
| if not has_myanmar and not has_myanmar: | |
| warnings.append("No Myanmar text found") | |
| return ValidationResult( | |
| valid=len(errors) == 0, | |
| errors=errors, | |
| warnings=warnings | |
| ) | |
| def validate_dataset(cls, items: List[Dict]) -> Tuple[List[Dict], List[Dict]]: | |
| """Validate entire dataset, return valid and invalid items.""" | |
| valid = [] | |
| invalid = [] | |
| for item in items: | |
| result = cls.validate_item(item) | |
| if result.valid: | |
| valid.append(item) | |
| else: | |
| invalid.append({**item, "validation_errors": result.errors}) | |
| return valid, invalid | |
| class DataSplitter: | |
| """Split dataset into train/validation/test sets.""" | |
| def __init__(self, train_ratio: float = 0.7, val_ratio: float = 0.15, test_ratio: float = 0.15): | |
| self.train_ratio = train_ratio | |
| self.val_ratio = val_ratio | |
| self.test_ratio = test_ratio | |
| assert abs(train_ratio + val_ratio + test_ratio - 1.0) < 0.001, "Ratios must sum to 1.0" | |
| def split( | |
| self, | |
| items: List[Dict], | |
| stratify_by: Optional[Callable] = None | |
| ) -> Dict[SplitType, List[Dict]]: | |
| """Split dataset with optional stratification.""" | |
| if stratify_by: | |
| return self._stratified_split(items, stratify_by) | |
| else: | |
| return self._random_split(items) | |
| def _random_split(self, items: List[Dict]) -> Dict[SplitType, List[Dict]]: | |
| """Randomly split dataset.""" | |
| shuffled = items.copy() | |
| random.shuffle(shuffled) | |
| total = len(shuffled) | |
| train_size = int(total * self.train_ratio) | |
| val_size = int(total * self.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( | |
| self, | |
| items: List[Dict], | |
| stratify_by: Callable | |
| ) -> Dict[SplitType, List[Dict]]: | |
| """Split with stratification by a key function.""" | |
| buckets: Dict[str, List[Dict]] = {} | |
| for item in items: | |
| key = stratify_by(item) | |
| if key not in buckets: | |
| buckets[key] = [] | |
| buckets[key].append(item) | |
| train_buckets = {k: [] for k in buckets} | |
| val_buckets = {k: [] for k in buckets} | |
| test_buckets = {k: [] for k in buckets} | |
| for key, bucket_items in buckets.items(): | |
| random.shuffle(bucket_items) | |
| total = len(bucket_items) | |
| train_size = int(total * self.train_ratio) | |
| val_size = int(total * self.val_ratio) | |
| train_buckets[key] = bucket_items[:train_size] | |
| val_buckets[key] = bucket_items[train_size:train_size + val_size] | |
| test_buckets[key] = bucket_items[train_size + val_size:] | |
| return { | |
| SplitType.TRAIN: [item for bucket in train_buckets.values() for item in bucket], | |
| SplitType.VALIDATION: [item for bucket in val_buckets.values() for item in bucket], | |
| SplitType.TEST: [item for bucket in test_buckets.values() for item in bucket], | |
| } | |
| def hash_split(self, items: List[Dict], salt: str = "") -> Dict[SplitType, List[Dict]]: | |
| """Split based on hash for reproducibility.""" | |
| result = {SplitType.TRAIN: [], SplitType.VALIDATION: [], SplitType.TEST: []} | |
| for item in items: | |
| hash_val = hashlib.md5( | |
| f"{json.dumps(item, sort_keys=True)}{salt}".encode() | |
| ).hexdigest() | |
| hash_num = int(hash_val[:8], 16) | |
| normalized = hash_num / 0xFFFFFFFF | |
| if normalized < self.train_ratio: | |
| result[SplitType.TRAIN].append(item) | |
| elif normalized < self.train_ratio + self.val_ratio: | |
| result[SplitType.VALIDATION].append(item) | |
| else: | |
| result[SplitType.TEST].append(item) | |
| return result | |
| class DatasetManager: | |
| """Manage dataset operations.""" | |
| def load_jsonl(file_path: str) -> List[Dict]: | |
| """Load data from 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 data 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 load_json(file_path: str) -> List[Dict]: | |
| """Load data from JSON file.""" | |
| with open(file_path, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| return data if isinstance(data, list) else data.get("data", data.get("items", [data])) | |
| def save_json(file_path: str, items: List[Dict]): | |
| """Save data to JSON file.""" | |
| Path(file_path).parent.mkdir(parents=True, exist_ok=True) | |
| with open(file_path, "w", encoding="utf-8") as f: | |
| json.dump(items, f, indent=2, ensure_ascii=False) | |
| def save_split( | |
| output_dir: str, | |
| splits: Dict[SplitType, List[Dict]], | |
| format: str = "jsonl" | |
| ): | |
| """Save split datasets to files.""" | |
| output_path = Path(output_dir) | |
| output_path.mkdir(parents=True, exist_ok=True) | |
| for split_type, items in splits.items(): | |
| file_path = output_path / f"{split_type.value}.jsonl" | |
| DatasetManager.save_jsonl(str(file_path), items) | |
| def get_dataset_stats(items: List[Dict]) -> Dict: | |
| """Get statistics about a dataset.""" | |
| if not items: | |
| return {"count": 0} | |
| response_lengths = [len(item.get("response", "")) for item in items] | |
| instruction_lengths = [len(item.get("instruction", "")) for item in items] | |
| systems = [item.get("system", "") for item in items] | |
| unique_systems = len(set(systems)) | |
| return { | |
| "count": len(items), | |
| "avg_response_length": sum(response_lengths) / len(response_lengths), | |
| "min_response_length": min(response_lengths), | |
| "max_response_length": max(response_lengths), | |
| "avg_instruction_length": sum(instruction_lengths) / len(instruction_lengths), | |
| "unique_systems": unique_systems, | |
| } | |
| def main(): | |
| """Demo the data validation and split module.""" | |
| print("=" * 50) | |
| print("📊 Data Validation and Split Demo") | |
| print("=" * 50) | |
| # Sample data | |
| sample_data = [ | |
| { | |
| "system": "Expert Python programmer", | |
| "instruction": "Python decorator hta ya py", | |
| "response": "# Python Decorator\n```python\ndef decorator(func):\n return func\n```" | |
| }, | |
| { | |
| "system": "Expert JavaScript developer", | |
| "instruction": "JavaScript async/await hta ya", | |
| "response": "// Async/Await\nasync function fetch() {\n const data = await fetch('/api');\n}" | |
| }, | |
| { | |
| "system": "Database expert", | |
| "instruction": "SQL JOIN operations", | |
| "response": "-- SQL JOIN\nSELECT * FROM a INNER JOIN b ON a.id = b.id;" | |
| }, | |
| ] * 10 # Multiply for demo | |
| print(f"\n📁 Sample data: {len(sample_data)} items") | |
| # Validate | |
| print("\n🔍 Validating data...") | |
| validator = DataValidator() | |
| valid, invalid = validator.validate_dataset(sample_data) | |
| print(f" ✓ Valid: {len(valid)}") | |
| print(f" ✗ Invalid: {len(invalid)}") | |
| # Split | |
| print("\n✂️ Splitting data (70/15/15)...") | |
| splitter = DataSplitter() | |
| splits = splitter.hash_split(sample_data, salt="burme-coder-v1") | |
| for split_type, items in splits.items(): | |
| print(f" {split_type.value}: {len(items)} items") | |
| # Stats | |
| print("\n📈 Dataset statistics:") | |
| stats = DatasetManager.get_dataset_stats(valid) | |
| for key, value in stats.items(): | |
| print(f" {key}: {value:.2f}" if isinstance(value, float) else f" {key}: {value}") | |
| if __name__ == "__main__": | |
| main() | |