"""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)