File size: 4,733 Bytes
e39cfed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parent
REQUIRED_ROW_FIELDS = {
    "id",
    "taxonomy_version",
    "text",
    "language",
    "country",
    "domain",
    "entities",
    "source",
    "synthetic",
    "review_status",
    "split",
}
ALLOWED_SPLITS = {"train", "validation", "test"}


def _read_json(path: Path) -> Any:
    with path.open(encoding="utf-8") as stream:
        return json.load(stream)


def validate() -> list[str]:
    errors: list[str] = []
    manifest = _read_json(ROOT / "manifest.json")
    taxonomy_version = manifest["taxonomy_version"]
    files: dict[str, str] = manifest["files"]
    expected_paths = {ROOT / name for name in files}
    actual_paths = set(ROOT.glob("*.jsonl"))

    for path in sorted(expected_paths - actual_paths):
        errors.append(f"missing manifest file: {path.name}")
    for path in sorted(actual_paths - expected_paths):
        errors.append(f"unlisted JSONL file: {path.name}")

    seen_ids: set[str] = set()
    for filename, primary_type in sorted(files.items()):
        path = ROOT / filename
        if not path.exists():
            continue
        primary_found = False
        with path.open(encoding="utf-8") as stream:
            for line_number, raw_line in enumerate(stream, start=1):
                if not raw_line.strip():
                    continue
                location = f"{filename}:{line_number}"
                try:
                    row = json.loads(raw_line)
                except json.JSONDecodeError as error:
                    errors.append(f"{location}: invalid JSON: {error.msg}")
                    continue

                missing = REQUIRED_ROW_FIELDS - set(row)
                if missing:
                    errors.append(f"{location}: missing fields: {', '.join(sorted(missing))}")
                    continue
                if row["id"] in seen_ids:
                    errors.append(f"{location}: duplicate id: {row['id']}")
                seen_ids.add(row["id"])
                if row["taxonomy_version"] != taxonomy_version:
                    errors.append(f"{location}: taxonomy_version must be {taxonomy_version}")
                if not isinstance(row["text"], str) or not row["text"]:
                    errors.append(f"{location}: text must be a non-empty string")
                    continue
                if row["split"] not in ALLOWED_SPLITS:
                    errors.append(f"{location}: invalid split: {row['split']}")
                if not isinstance(row["entities"], list):
                    errors.append(f"{location}: entities must be an array")
                    continue

                for entity_index, entity in enumerate(row["entities"]):
                    entity_location = f"{location}:entity[{entity_index}]"
                    if not isinstance(entity, dict):
                        errors.append(f"{entity_location}: entity must be an object")
                        continue
                    missing_entity = {"start", "end", "type", "subtype"} - set(entity)
                    if missing_entity:
                        errors.append(
                            f"{entity_location}: missing fields: {', '.join(sorted(missing_entity))}"
                        )
                        continue
                    start, end = entity["start"], entity["end"]
                    if (
                        not isinstance(start, int)
                        or isinstance(start, bool)
                        or not isinstance(end, int)
                        or isinstance(end, bool)
                        or not 0 <= start < end <= len(row["text"])
                    ):
                        errors.append(
                            f"{entity_location}: invalid span [{start!r}, {end!r}) "
                            f"for text length {len(row['text'])}"
                        )
                        continue
                    if not row["text"][start:end].strip():
                        errors.append(f"{entity_location}: span contains only whitespace")
                    if entity["type"] == primary_type:
                        primary_found = True

        if not primary_found:
            errors.append(f"{filename}: no positive {primary_type} entity found")

    return errors


if __name__ == "__main__":
    validation_errors = validate()
    if validation_errors:
        print(f"Sample training data validation failed ({len(validation_errors)} errors):")
        for validation_error in validation_errors:
            print(f"- {validation_error}")
        raise SystemExit(1)
    print("Sample training data validation passed")