File size: 8,067 Bytes
40fd3fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"""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()