File size: 13,111 Bytes
5c531db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env python3

from __future__ import annotations

import argparse
import json
import re
import sys
from collections import Counter
from pathlib import Path
from typing import Any, Dict, List, Set

from eval import CHECK_CATALOG, evaluate_record

REQUIRED_FIELDS: Dict[str, type] = {
    "id": str,
    "lang": str,
    "category": str,
    "subtopic": str,
    "domain": str,
    "difficulty": str,
    "eval_mode": str,
    "prompt": str,
    "instruction": str,
    "input": str,
    "expected": str,
    "checks": str,
}

VALID_CATEGORIES: Set[str] = {
    "formatting",
    "length",
    "lexical",
    "structure",
    "language_case_punct",
    "extraction",
    "classification",
    "multi_constraint",
    "edge_cases",
    "style_and_reasoning",
}

VALID_DOMAINS: Set[str] = {
    "business",
    "finance",
    "legal",
    "hr",
    "ecommerce",
    "logistics",
    "tech",
    "education",
    "science",
    "journalism",
    "everyday",
    "public_services",
}

VALID_DIFFICULTIES: Set[str] = {"easy", "medium", "hard"}
VALID_EVAL_MODES: Set[str] = {"deterministic", "llm_judge"}
VALID_OPS: Set[str] = {"==", ">=", "<=", ">", "<"}

def expected_to_response(expected_json_str: str) -> str:
    val = json.loads(expected_json_str)
    if isinstance(val, str):
        return val
    return json.dumps(val, ensure_ascii=False)

def validate_check_obj(chk: Any, eval_mode: str, idx: int) -> List[str]:
    errors: List[str] = []
    if not isinstance(chk, dict):
        return [f"check[{idx}] must be a JSON object"]
    ctype = chk.get("type")
    if not isinstance(ctype, str) or ctype not in CHECK_CATALOG:
        return [f"check[{idx}] unknown or missing check type: {ctype!r}"]

    if ctype == "llm_rubric" and eval_mode != "llm_judge":
        errors.append(f"check[{idx}] llm_rubric is only allowed when eval_mode=='llm_judge'")

    spec = CHECK_CATALOG[ctype]
    for req in spec["required"]:
        if req not in chk:
            errors.append(f"check[{idx}] ({ctype}) missing required param '{req}'")

    allowed_keys = {"type", "loose", *spec["required"], *spec["optional"]}
    extra = set(chk.keys()) - allowed_keys
    if extra:
        errors.append(f"check[{idx}] ({ctype}) unexpected params: {sorted(extra)}")

    if "loose" in chk and not isinstance(chk["loose"], bool):
        errors.append(f"check[{idx}] ({ctype}) 'loose' must be boolean")

    if ctype in ("word_count", "sentence_count", "line_count"):
        if chk.get("min") is None and chk.get("max") is None:
            errors.append(f"check[{idx}] ({ctype}) requires at least one of 'min' or 'max'")
        for k in ("min", "max"):
            if chk.get(k) is not None and (not isinstance(chk[k], int) or isinstance(chk[k], bool) or chk[k] < 0):
                errors.append(f"check[{idx}] ({ctype}) '{k}' must be non-negative int")

    if ctype in ("paragraph_count", "bullet_count", "section_count", "placeholder_count"):
        n = chk.get("n")
        min_n = 0 if ctype == "placeholder_count" else 1
        if not isinstance(n, int) or isinstance(n, bool) or n < min_n:
            errors.append(f"check[{idx}] ({ctype}) 'n' must be int >= {min_n}")

    if ctype in ("required_keys", "label_in_set", "contains_all", "contains_none"):
        key_name = "keys" if ctype == "required_keys" else ("labels" if ctype == "label_in_set" else "words")
        val = chk.get(key_name)
        if not isinstance(val, list) or not val or not all(isinstance(x, str) and x != "" for x in val):
            errors.append(f"check[{idx}] ({ctype}) '{key_name}' must be a non-empty list of non-empty strings")

    if ctype == "json_types":
        tmap = chk.get("types")
        valid_t = {"str", "string", "int", "integer", "float", "number", "bool", "boolean", "list", "array", "dict", "object", "null", "none"}
        if not isinstance(tmap, dict) or not tmap:
            errors.append(f"check[{idx}] (json_types) 'types' must be a non-empty dict")
        elif not all(isinstance(k, str) and isinstance(v, str) and v.lower() in valid_t for k, v in tmap.items()):
            errors.append(f"check[{idx}] (json_types) invalid type mapping in 'types'")

    if ctype == "keyword_frequency":
        if chk.get("op") not in VALID_OPS:
            errors.append(f"check[{idx}] (keyword_frequency) 'op' must be one of {sorted(VALID_OPS)}")
        if not isinstance(chk.get("n"), int) or isinstance(chk.get("n"), bool) or chk["n"] < 0:
            errors.append(f"check[{idx}] (keyword_frequency) 'n' must be non-negative int")

    if ctype in ("regex_match", "regex_absent"):
        pat = chk.get("pattern")
        if not isinstance(pat, str) or not pat:
            errors.append(f"check[{idx}] ({ctype}) 'pattern' must be non-empty string")
        else:
            try:
                re.compile(pat)
            except re.error as exc:
                errors.append(f"check[{idx}] ({ctype}) invalid regex: {exc}")

    if ctype == "language_ru" and "min_cyrillic_ratio" in chk:
        r = chk["min_cyrillic_ratio"]
        if not isinstance(r, (int, float)) or isinstance(r, bool) or not (0.0 < r <= 1.0):
            errors.append(f"check[{idx}] (language_ru) 'min_cyrillic_ratio' must be in (0, 1]")

    if ctype == "llm_rubric":
        crit = chk.get("criteria")
        if not isinstance(crit, list) or not (3 <= len(crit) <= 5) or not all(isinstance(c, str) and c.strip() for c in crit):
            errors.append(f"check[{idx}] (llm_rubric) 'criteria' must be a list of 3-5 non-empty strings")

    return errors

def validate_record(
    rec: Any,
    line_num: int,
    seen_ids: Set[str],
    allow_working_fields: bool = False,
    check_expected: bool = False,
    check_negative: bool = False,
) -> List[str]:
    errors: List[str] = []
    if not isinstance(rec, dict):
        return [f"Line {line_num}: record must be a JSON object"]

    allowed_fields = set(REQUIRED_FIELDS.keys())
    if allow_working_fields:
        allowed_fields.add("_negative")

    extra = set(rec.keys()) - allowed_fields
    if extra:
        errors.append(f"Line {line_num}: unexpected fields: {sorted(extra)}")

    for field, ftype in REQUIRED_FIELDS.items():
        if field not in rec:
            errors.append(f"Line {line_num}: missing required field '{field}'")
        elif not isinstance(rec[field], ftype):
            errors.append(f"Line {line_num}: field '{field}' must be {ftype.__name__}, got {type(rec[field]).__name__}")

    if errors:
        return errors

    rid = rec["id"]
    if not rid.strip():
        errors.append(f"Line {line_num}: 'id' must be non-empty")
    elif rid in seen_ids:
        errors.append(f"Line {line_num}: duplicate id '{rid}'")
    else:
        seen_ids.add(rid)

    if rec["lang"] != "ru":
        errors.append(f"Line {line_num}: 'lang' must be 'ru'")
    if rec["category"] not in VALID_CATEGORIES:
        errors.append(f"Line {line_num}: invalid category '{rec['category']}'")
    if not rec["subtopic"].strip():
        errors.append(f"Line {line_num}: 'subtopic' must be non-empty")
    if rec["domain"] not in VALID_DOMAINS:
        errors.append(f"Line {line_num}: invalid domain '{rec['domain']}'")
    if rec["difficulty"] not in VALID_DIFFICULTIES:
        errors.append(f"Line {line_num}: invalid difficulty '{rec['difficulty']}'")
    if rec["eval_mode"] not in VALID_EVAL_MODES:
        errors.append(f"Line {line_num}: invalid eval_mode '{rec['eval_mode']}'")
    if not rec["prompt"].strip():
        errors.append(f"Line {line_num}: 'prompt' must be non-empty")
    if not rec["instruction"].strip():
        errors.append(f"Line {line_num}: 'instruction' must be non-empty")

    eval_mode = rec["eval_mode"]
    if eval_mode == "llm_judge":
        if rec["category"] != "style_and_reasoning":
            errors.append(f"Line {line_num}: llm_judge must have category=='style_and_reasoning'")
        if rec["expected"] != "":
            errors.append(f"Line {line_num}: llm_judge must have expected==''")
    else:
        if rec["category"] == "style_and_reasoning":
            errors.append(f"Line {line_num}: style_and_reasoning must have eval_mode=='llm_judge'")
        if not rec["expected"].strip():
            errors.append(f"Line {line_num}: deterministic record must have non-empty JSON string 'expected'")
        else:
            try:
                json.loads(rec["expected"])
            except Exception as exc:
                errors.append(f"Line {line_num}: 'expected' is not valid JSON: {exc}")

    try:
        checks = json.loads(rec["checks"])
    except Exception as exc:
        errors.append(f"Line {line_num}: 'checks' is not valid JSON: {exc}")
        return errors

    if not isinstance(checks, list) or not checks:
        errors.append(f"Line {line_num}: 'checks' must be a non-empty JSON list")
        return errors

    for i, chk in enumerate(checks):
        for err in validate_check_obj(chk, eval_mode, i):
            errors.append(f"Line {line_num} ({rid}): {err}")

    if eval_mode == "llm_judge":
        has_det = any(isinstance(c, dict) and c.get("type") != "llm_rubric" for c in checks)
        has_rubric = any(isinstance(c, dict) and c.get("type") == "llm_rubric" for c in checks)
        if not has_det:
            errors.append(f"Line {line_num} ({rid}): llm_judge must include at least one deterministic check")
        if not has_rubric:
            errors.append(f"Line {line_num} ({rid}): llm_judge must include an llm_rubric check")

    if errors:
        return errors

    if check_expected and eval_mode == "deterministic":
        exp_resp = expected_to_response(rec["expected"])
        res = evaluate_record(rec, exp_resp)
        if not res["prompt_strict"]:
            errors.append(f"Line {line_num} ({rid}): expected FAILED strict checks: {res['strict_checks']}")
        if not res["prompt_loose"]:
            errors.append(f"Line {line_num} ({rid}): expected FAILED loose checks: {res['loose_checks']}")

    if check_negative:
        if "_negative" not in rec or not isinstance(rec["_negative"], str) or not rec["_negative"].strip():
            errors.append(f"Line {line_num} ({rid}): missing or empty '_negative' string")
        else:
            res_neg = evaluate_record(rec, rec["_negative"])
            if res_neg["prompt_strict"]:
                errors.append(f"Line {line_num} ({rid}): _negative PASSED all strict checks (must fail at least one)")

    return errors

def main() -> int:
    parser = argparse.ArgumentParser(description="Validate ru_if JSONL dataset.")
    parser.add_argument("--file", required=True, type=Path, help="Path to JSONL file")
    parser.add_argument("--working", action="store_true", help="Allow _negative field and verify expected & _negative")
    parser.add_argument("--check-expected", action="store_true", help="Verify expected passes strict and loose checks")
    parser.add_argument("--check-negative", action="store_true", help="Verify _negative fails at least one strict check")
    parser.add_argument("--stats", action="store_true", help="Print distribution statistics")
    args = parser.parse_args()

    if not args.file.exists():
        print(f"ERROR: File not found: {args.file}", file=sys.stderr)
        return 1

    check_exp = args.check_expected or args.working
    check_neg = args.check_negative or args.working
    allow_work = args.working or args.check_negative

    seen_ids: Set[str] = set()
    all_errors: List[str] = []
    records: List[Dict[str, Any]] = []

    with args.file.open("r", encoding="utf-8") as f:
        for line_num, line in enumerate(f, start=1):
            stripped = line.strip()
            if not stripped:
                continue
            try:
                rec = json.loads(stripped)
            except Exception as exc:
                all_errors.append(f"Line {line_num}: invalid JSON: {exc}")
                continue
            records.append(rec)
            all_errors.extend(
                validate_record(
                    rec,
                    line_num=line_num,
                    seen_ids=seen_ids,
                    allow_working_fields=allow_work,
                    check_expected=check_exp,
                    check_negative=check_neg,
                )
            )

    if args.stats and records:
        total = len(records)
        print(f"Total records: {total}")
        for field in ("category", "difficulty", "domain", "eval_mode"):
            counts = Counter(r.get(field) for r in records)
            print(f"\n{field}:")
            for k, v in sorted(counts.items()):
                print(f"  {k}: {v} ({v / total * 100:.1f}%)")

    if all_errors:
        print(f"\nVALIDATION FAILED: {len(all_errors)} error(s) in {args.file}", file=sys.stderr)
        for err in all_errors[:50]:
            print(f"  - {err}", file=sys.stderr)
        if len(all_errors) > 50:
            print(f"  ... and {len(all_errors) - 50} more", file=sys.stderr)
        return 1

    print(f"OK: {len(records)} records validated in {args.file}")
    return 0

if __name__ == "__main__":
    sys.exit(main())