File size: 5,976 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""File readers and writers: manifests, evalsets registry, prediction TSVs, raw jsonl, side files, JSON output."""
import csv
import hashlib
import json
import math
import os
import re
import unicodedata

csv.field_size_limit(10 ** 9)
MANIFEST_COLS = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"]


def sha256_file(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for blk in iter(lambda: f.read(1 << 20), b""):
            h.update(blk)
    return h.hexdigest()


def read_tsv(path, required=()):
    """Returns (header, rows as dicts, number of ragged rows). Quotes are not special (labels may contain them)."""
    rows, ragged = [], 0
    with open(path, encoding="utf-8", newline="") as f:
        header = f.readline().rstrip("\n").rstrip("\r").split("\t")
        for col in required:
            if col not in header:
                raise ValueError("%s: column %r missing (header %s)" % (path, col, header))
        n = len(header)
        for line in f:
            line = line.rstrip("\n")
            if line.endswith("\r"):
                line = line[:-1]
            if line == "":
                continue
            p = line.split("\t")
            if len(p) != n:
                ragged += 1
                continue
            rows.append(dict(zip(header, p)))
    return header, rows, ragged


def read_manifest(path):
    header, rows, ragged = read_tsv(path, required=MANIFEST_COLS)
    if ragged:
        raise ValueError("manifest %s has %d ragged rows" % (path, ragged))
    for r in rows:
        r["text"] = unicodedata.normalize("NFC", r["text"])
    return rows


class Registry:
    def __init__(self, doc, path):
        self.path = path
        if isinstance(doc, dict) and isinstance(doc.get("sets"), list):
            self.sets = doc["sets"]
        elif isinstance(doc, list):
            self.sets = doc
        else:
            raise ValueError("registry %s has no 'sets' list" % path)
        self.by_name = {}
        for s in self.sets:
            nm = s.get("name", "")
            self.by_name[nm] = s
            short = re.sub(r"\s*\(.*\)\s*$", "", nm)
            self.by_name.setdefault(short, s)
            man = s.get("manifest")
            if man:
                self.by_name.setdefault(os.path.splitext(os.path.basename(man))[0], s)

    def find(self, stem):
        """The registry entry for a prediction file name: exact registry name (spaces and parentheses included), the name
        without a trailing '(...)', or the basename of the manifest."""
        return self.by_name.get(stem)

    def is_locked(self, entry):
        return bool(entry.get("locked")) or str(entry.get("split", "")).lower() == "test"


def load_registry(path):
    with open(path, encoding="utf-8") as f:
        return Registry(json.load(f), path)


def read_preds(path):
    """Prediction TSV (id, ref, hyp, optional conf, conf_min, hit_cap, n_tokens). Returns (rows by id, ragged, duplicates)."""
    header, rows, ragged = read_tsv(path, required=("id", "ref", "hyp"))
    by, dup = {}, 0
    for r in rows:
        if r["id"] in by:
            dup += 1
        by[r["id"]] = r
    return by, header, ragged, dup


def read_raw_jsonl(path):
    out = {}
    with open(path, encoding="utf-8") as f:
        for line in f:
            try:
                d = json.loads(line)
            except ValueError:
                continue
            if isinstance(d, dict) and "id" in d:
                out[d["id"]] = d
    return out


def read_meta_tsv(path):
    header, rows, ragged = read_tsv(path, required=("id",))
    return {r["id"]: r for r in rows}


_SC_CACHE = {}


def score_names(sc):
    """Names a score file answers to: the registry name (with and without a trailing '(...)'), the prediction file stem, and the basename of the
    manifest. A prediction file called 'kohtd_test (P1).tsv' therefore matches the endpoint name 'kohtd_test'."""
    names = set()
    for n in (sc.get("registry_name"), sc.get("evalset")):
        if n:
            names.add(n)
            names.add(re.sub(r"\s*\(.*\)\s*$", "", n))
    mp = (sc.get("inputs") or {}).get("manifest_path")
    if mp:
        names.add(os.path.splitext(os.path.basename(mp))[0])
    return names


def find_score(ck_dir, wanted):
    """The scored JSON in a checkpoint's score folder that answers to one of the names in `wanted` (first in file order), else None."""
    import glob
    if not os.path.isdir(ck_dir):
        return None
    for p in sorted(glob.glob(os.path.join(ck_dir, "*.json"))):
        if p not in _SC_CACHE:
            try:
                _SC_CACHE[p] = json.load(open(p, encoding="utf-8"))
            except ValueError:
                _SC_CACHE[p] = None
        sc = _SC_CACHE[p]
        if sc and sc.get("status") == "scored" and score_names(sc) & set(wanted):
            return sc
    return None


def clean(o):
    """JSON-safe copy: numpy scalars to Python, NaN and infinity to None, tuples to lists."""
    try:
        import numpy as np
    except ImportError:  # pragma: no cover
        np = None
    if isinstance(o, dict):
        return {str(k): clean(v) for k, v in o.items()}
    if isinstance(o, (list, tuple)):
        return [clean(v) for v in o]
    if np is not None:
        if isinstance(o, np.ndarray):
            return clean(o.tolist())
        if isinstance(o, np.integer):
            return int(o)
        if isinstance(o, np.floating):
            o = float(o)
        if isinstance(o, np.bool_):
            return bool(o)
    if isinstance(o, float) and (math.isnan(o) or math.isinf(o)):
        return None
    return o


def write_json_atomic(path, obj):
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    tmp = path + ".tmp%d" % os.getpid()
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(clean(obj), f, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
    os.replace(tmp, path)