burme-coder-max / scripts /validate_dataset.py
amkyawdev's picture
Upload folder using huggingface_hub
40fd3fa verified
"""Dataset Validation Script
Validates burme-coder-max dataset quality and format.
"""
import json
import re
from pathlib import Path
from typing import Dict, List, Tuple
from dataclasses import dataclass
from datetime import datetime
@dataclass
class ValidationError:
"""Validation error."""
line: int
field: str
message: str
severity: str = "error"
class DatasetValidator:
"""Validate the burme-coder-max dataset."""
# Validation rules
REQUIRED_FIELDS = ["system", "instruction", "response"]
MIN_RESPONSE_LENGTH = 20
MAX_RESPONSE_LENGTH = 10000
MIN_INSTRUCTION_LENGTH = 3
# Myanmar text pattern
MYANMAR_PATTERN = re.compile(r"[\u1000-\u109f\uAA60-\uAA7f]+")
def __init__(self, data_dir: str):
self.data_dir = Path(data_dir)
self.errors: List[ValidationError] = []
self.warnings: List[ValidationError] = []
def validate_file(self, file_path: str) -> Tuple[bool, List[Dict]]:
"""Validate a single data file."""
items = []
self.errors = []
self.warnings = []
with open(file_path, "r", encoding="utf-8") as f:
for line_num, line in enumerate(f, 1):
if not line.strip():
continue
try:
item = json.loads(line)
items.append(item)
self._validate_item(item, line_num)
except json.JSONDecodeError as e:
self.errors.append(ValidationError(
line=line_num,
field="json",
message=f"Invalid JSON: {e}",
severity="error"
))
return len(self errors) == 0, items
def _validate_item(self, item: Dict, line_num: int):
"""Validate a single item."""
# Check required fields
for field in self.REQUIRED_FIELDS:
if field not in item:
self.errors.append(ValidationError(
line=line_num,
field=field,
message=f"Missing required field: {field}",
severity="error"
))
return
elif not isinstance(item[field], str):
self.errors.append(ValidationError(
line=line_num,
field=field,
message=f"Field {field} must be string",
severity="error"
))
# Check field lengths
response_len = len(item["response"])
if response_len < self.MIN_RESPONSE_LENGTH:
self.warnings.append(ValidationError(
line=line_num,
field="response",
message=f"Response too short ({response_len} chars)",
severity="warning"
))
if response_len > self.MAX_RESPONSE_LENGTH:
self.warnings.append(ValidationError(
line=line_num,
field="response",
message=f"Response too long ({response_len} chars)"
))
instruction_len = len(item["instruction"])
if instruction_len < self.MIN_INSTRUCTION_LENGTH:
self.errors.append(ValidationError(
line=line_num,
field="instruction",
message=f"Instruction too short ({instruction_len} chars)"
))
# Check for code blocks
if "```" not in item["response"]:
self.warnings.append(ValidationError(
line=line_num,
field="response",
message="Response missing code block"
))
# Check for language consistency
instruction_text = item["instruction"].lower()
response_text = item["response"]
# Count code blocks by language
code_blocks = re.findall(r"```(\w*)", response_text)
languages = set(code_blocks)
# Suggestion: if instruction mentions a language, include it in response
for lang in ["python", "javascript", "typescript", "java", "sql", "go", "rust"]:
if lang in instruction_text and lang.lower() not in languages:
self.warnings.append(ValidationError(
line=line_num,
field="response",
message=f"Instruction mentions '{lang}' but no code block found"
))
def get_stats(self, items: List[Dict]) -> Dict:
"""Get dataset statistics."""
stats = {
"total_items": len(items),
"timestamp": datetime.now().isoformat(),
}
if not items:
return stats
# Length statistics
response_lengths = [len(item["response"]) for item in items]
instruction_lengths = [len(item["instruction"]) for item in items]
stats["response"] = {
"avg_length": sum(response_lengths) / len(response_lengths),
"min_length": min(response_lengths),
"max_length": max(response_lengths),
}
stats["instruction"] = {
"avg_length": sum(instruction_lengths) / len(instruction_lengths),
"min_length": min(instruction_lengths),
"max_length": max(instruction_lengths),
}
# Language distribution
all_languages = []
for item in items:
code_blocks = re.findall(r"```(\w*)", item["response"])
all_languages.extend([lang for lang in code_blocks if lang])
from collections import Counter
lang_counts = Counter(all_languages)
stats["languages"] = dict(lang_counts)
# Myanmar content
myanmar_count = sum(
1 for item in items
if self.MYANMAR_PATTERN.search(item["instruction"])
)
stats["myanmar_items"] = myanmar_count
stats["myanmar_percentage"] = (myanmar_count / len(items)) * 100 if items else 0
# System prompts
systems = set(item["system"] for item in items)
stats["unique_systems"] = len(systems)
return stats
def main():
"""Run validation."""
import sys
print("=" * 60)
print("📊 Burme-Coder-Max Dataset Validator")
print("=" * 60)
data_dir = Path(__file__).parent.parent / "data" / "knowledge"
validator = DatasetValidator(str(data_dir))
# Find JSONL files
jsonl_files = list(Path(".").rglob("*.jsonl"))
if not jsonl_files:
print("⚠️ No JSONL files found")
sys.exit(1)
total_errors = 0
total_warnings = 0
total_items = 0
for jsonl_file in jsonl_files:
print(f"\n📁 Validating: {jsonl_file.name}")
valid, items = validator.validate_file(str(jsonl_file))
total_items += len(items)
if validator.errors:
print(f" ❌ {len(validator.errors)} errors:")
for err in validator.errors[:10]:
print(f" Line {err.line}: {err.field} - {err.message}")
if validator.warnings:
print(f" ⚠️ {len(validator.warnings)} warnings:")
for warn in validator.warnings[:5]:
print(f" Line {warn.line}: {warn.field} - {warn.message}")
if valid and not validator.errors:
print(" ✅ Valid")
total_errors += len(validator.errors)
total_warnings += len(validator.warnings)
# Get overall stats
if jsonl_files:
validator.validate_file(str(jsonl_files[0]))
stats = validator.get_stats([])
stats["total_items"] = total_items
print("\n📈 Overall Statistics:")
print(f" Total items: {stats['total_items']}")
print(f" Total errors: {total_errors}")
print(f" Total warnings: {total_warnings}")
print("\n" + "=" * 60)
if total_errors == 0:
print("✅ Validation passed!")
else:
print(f"❌ {total_errors} errors found, {total_warnings} warnings")
print("=" * 60)
if __name__ == "__main__":
main()