File size: 4,672 Bytes
abc625e
abb7917
abc625e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abb7917
 
abc625e
 
 
 
 
 
 
 
 
 
 
 
 
 
abb7917
 
 
 
 
 
abc625e
 
 
abb7917
 
abc625e
 
abb7917
 
 
 
 
abc625e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abb7917
 
abc625e
 
 
 
 
 
 
 
 
 
 
 
 
 
abb7917
 
abc625e
abb7917
 
 
 
abc625e
 
abb7917
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abc625e
 
 
 
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
import argparse
import collections
import hashlib
import json
from pathlib import Path

import pyarrow.parquet as pq
from datasets import ClassLabel, Features, Value


LABELS = ["anger", "fear", "joy", "love", "sadness", "surprise", "neutral"]
LANGUAGES = {"de", "en", "es", "fr", "it"}
FEATURES = Features(
    {
        "id": Value("string"),
        "source_id": Value("string"),
        "text": Value("string"),
        "label": ClassLabel(names=LABELS),
        "label_name": Value("string"),
        "dataset": Value("string"),
        "license": Value("string"),
        "language": Value("string"),
        "is_label_conflict": Value("bool"),
        "label_variants": Value("int8"),
    }
)


def file_sha256(path):
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--reports",
        type=Path,
        nargs="+",
        default=[Path("reports/all_validation.json"), Path("reports/sample_validation.json")],
    )
    return parser.parse_args()


def validate(report_path):
    report = json.loads(report_path.read_text(encoding="utf-8"))
    ids = set()
    source_ids = set()
    rows = 0
    label_counts = collections.Counter()
    language_counts = collections.Counter()
    stratum_counts = collections.Counter()
    conflict_rows = 0

    for shard in report["shards"]:
        path = Path(shard["path"])
        if file_sha256(path) != shard["sha256"]:
            raise ValueError(f"checksum mismatch: {path}")
        parquet = pq.ParquetFile(path)
        if parquet.schema_arrow != FEATURES.arrow_schema:
            raise ValueError(f"schema mismatch: {path}")
        if parquet.metadata.num_rows != shard["rows"]:
            raise ValueError(f"row count mismatch: {path}")
        for batch in parquet.iter_batches(batch_size=65_536):
            columns = batch.to_pydict()
            for index, row_id in enumerate(columns["id"]):
                language = columns["language"][index]
                source_id = columns["source_id"][index]
                label = columns["label"][index]
                is_conflict = columns["is_label_conflict"][index]
                variants = columns["label_variants"][index]
                if row_id in ids:
                    raise ValueError(f"duplicate id: {row_id}")
                ids.add(row_id)
                source_ids.add(source_id)
                if language not in LANGUAGES:
                    raise ValueError(f"invalid language: {language}")
                if row_id != f"{source_id}_{language}":
                    raise ValueError(f"id/source mismatch: {row_id}")
                if not columns["text"][index].strip():
                    raise ValueError(f"empty text: {row_id}")
                if not 0 <= label < len(LABELS):
                    raise ValueError(f"invalid label: {row_id}")
                if columns["label_name"][index] != LABELS[label]:
                    raise ValueError(f"label name mismatch: {row_id}")
                if is_conflict != (variants > 1) or not 1 <= variants <= len(LABELS):
                    raise ValueError(f"conflict metadata mismatch: {row_id}")
                rows += 1
                conflict_rows += is_conflict
                label_counts[LABELS[label]] += 1
                language_counts[language] += 1
                stratum_counts[f"{language}/{LABELS[label]}"] += 1

    expected = report["counts"]
    checks = {
        "output_rows": rows,
        "output_unique_ids": len(ids),
        "retained_source_ids": len(source_ids),
        "label_conflict_rows": conflict_rows,
        "labels": dict(sorted(label_counts.items())),
        "languages": dict(sorted(language_counts.items())),
    }
    for key, actual in checks.items():
        if actual != expected[key]:
            raise ValueError(f"{report['config']} {key} mismatch: {actual} != {expected[key]}")
    if "language_label_strata" in expected:
        actual = dict(sorted(stratum_counts.items()))
        if actual != expected["language_label_strata"]:
            raise ValueError(f"{report['config']} language/label balance mismatch")
    return {
        "config": report["config"],
        "status": "valid",
        "rows": rows,
        "unique_ids": len(ids),
        "source_ids": len(source_ids),
        "shards": len(report["shards"]),
    }


def main():
    args = parse_args()
    print(json.dumps([validate(path) for path in args.reports], indent=2))


if __name__ == "__main__":
    main()