"""K_train of clarification G3 and the P2 / P2b / P2_literal slice flags. K_train is built ONCE from the train manifests that the frozen mix_v1.yaml names (the leaves and their filters, same reading as CODE/scripts/r5_vlma/build_sequence.py), after the freeze, and hashed. It reads training text only, never a validation or test manifest. Three key sets (keys by textnorm.n1_key: NFC, lower case with the Turkic fold for tr and az, letters and decimal digits only, folded with the language of the row): hand_keys keys of every hand_real and hand_synth training label AND of every whitespace token of those labels (P2, G3) hand_literal keys of the whole labels of hand_real and hand_synth training rows only (literal variant) all_keys hand_keys plus the labels and tokens of every other non-clutter training row (typed_synth, typed_real, typed_real_ocr) plus the tokens of the generator's train text and of the character-LM training text (P2b, G3) A test crop with a non-empty key is in P2 when its key is not in hand_keys, in P2b when its key is not in all_keys, and in P2_literal when its key is not in hand_literal. The slice membership is computed inside the gated test pass (it needs the test labels) as a deterministic function of these three sets. """ import csv import gzip import hashlib import json import os import time from .textnorm import n1_key csv.field_size_limit(10 ** 9) HAND_KINDS = ("hand_real", "hand_synth") SHARE_KEYS = ("share", "weight", "fraction", "percent", "pct", "proportion") CHILD_KEYS = ("members", "sources", "manifests", "items", "children", "parts", "components", "strata", "groups") PATH_KEYS = ("manifest", "path", "file", "tsv") FILES = {"hand_keys": "ktrain_hand_keys.txt.gz", "hand_literal": "ktrain_hand_literal_keys.txt.gz", "all_keys": "ktrain_all_keys.txt.gz"} DEFINITION = ("K_train (clarification G3 of amendment 3.2): N1 keys (NFC, lower case with the Turkic fold for tr and az, letters and " "decimal digits only) of every hand_real and hand_synth training label of the leaves of mix_v1.yaml and of every " "whitespace token of those labels. P2b adds the typed_synth labels and tokens, the tokens of the generator's train " "text and of the character-LM training text. P2_literal uses the whole labels of hand_real and hand_synth only.") def sha256_bytes(b): return hashlib.sha256(b).hexdigest() 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 set_hash(keys): h = hashlib.sha256() for k in sorted(keys): h.update(k.encode("utf-8")) h.update(b"\n") return h.hexdigest() def read_mix_leaves(mix_yaml): """Leaves of mix_v1.yaml: list of {'name','manifest','filter','sha256'} (same walk as build_sequence.py).""" import yaml doc = yaml.safe_load(open(mix_yaml, encoding="utf-8")) root = doc.get("mix", doc) if isinstance(doc, dict) else doc leaves = [] def children_of(node): if isinstance(node, list): return node if isinstance(node, dict): for k in CHILD_KEYS: v = node.get(k) if isinstance(v, list): return v if isinstance(v, dict): return [dict(c, name=c.get("name", n)) if isinstance(c, dict) else {"name": n, "manifest": c} for n, c in v.items()] return None def path_of(node): if isinstance(node, str): return node if isinstance(node, dict): for k in PATH_KEYS: if isinstance(node.get(k), str): return node[k] return None def walk(node, name, flt): p = path_of(node) f2 = dict(flt) if isinstance(node, dict) and isinstance(node.get("filter"), dict): f2.update(node["filter"]) if p is not None and children_of(node) is None: leaves.append({"name": name, "manifest": p, "filter": f2, "sha256": node.get("sha256") if isinstance(node, dict) else None}) return ch = children_of(node) if ch is None: raise SystemExit("cannot read mix node %r" % name) for i, c in enumerate(ch): nm = (c.get("name") if isinstance(c, dict) else None) or os.path.splitext(os.path.basename(path_of(c) or str(i)))[0] walk(c, (name + "/" + nm) if name else nm, f2) walk(root, "", {}) return leaves def _match(row, flt): for col, want in flt.items(): v = row.get(col) if isinstance(want, (list, tuple, set)): if v not in [str(x) for x in want]: return False elif v != str(want): return False return True def read_manifest_rows(path): with open(path, encoding="utf-8", newline="") as f: rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE) return list(rd) def _read_text_file(path, lang_hint): """Yields (lang, text) from sentences.tsv (id text) or a plain text file (one line per text).""" with open(path, encoding="utf-8", newline="") as f: for line in f: line = line.rstrip("\n") if "\t" in line: line = line.split("\t", 1)[1] if line: yield lang_hint, line.replace("▁", " ") def build(mix_yaml, out_dir, extra_text_files=(), manifest_root=None): """Builds and writes K_train. Returns the manifest dict. manifest_root: optional folder that replaces the folder of every leaf manifest (tests only).""" os.makedirs(out_dir, exist_ok=True) leaves = read_mix_leaves(mix_yaml) hand_keys, hand_lit, all_keys = set(), set(), set() used = [] seen_paths = set() for lf in leaves: p = lf["manifest"] if manifest_root: p = os.path.join(manifest_root, os.path.basename(p)) rows = read_manifest_rows(p) sha = sha256_file(p) if lf.get("sha256") is not None and str(lf["sha256"]) != sha: raise SystemExit("manifest %s sha256 %s differs from mix_v1.yaml %s" % (p, sha, lf["sha256"])) n_used = 0 for r in rows: if r.get("split") != "train" or not _match(r, lf["filter"]): continue kind = r.get("kind") lang = r.get("lang") text = r.get("text", "") whole = n1_key(text, lang) toks = [n1_key(t, lang) for t in text.split()] toks = [t for t in toks if t] if kind in HAND_KINDS: if whole: hand_keys.add(whole) hand_lit.add(whole) hand_keys.update(toks) all_keys.add(whole) if whole else None all_keys.update(toks) n_used += 1 elif kind != "clutter" and text: # every other training row with text (typed_synth, typed_real, typed_real_ocr, ...) is training text: it is inside the # character-LM training text that clarification G3 names, so it goes into the P2b set if whole: all_keys.add(whole) all_keys.update(toks) n_used += 1 used.append({"name": lf["name"], "manifest": p, "sha256": sha, "filter": lf["filter"], "rows_used": n_used}) seen_paths.add(p) extra_info = [] for ep in extra_text_files: lang = os.path.basename(os.path.dirname(ep)) n = 0 for lg, line in _read_text_file(ep, lang): for t in line.split(): k = n1_key(t, lg) if k: all_keys.add(k) n += 1 extra_info.append({"path": ep, "lines": n, "sha256": sha256_file(ep), "lang_hint": lang}) all_keys |= hand_keys sets = {"hand_keys": hand_keys, "hand_literal": hand_lit, "all_keys": all_keys} man = {"schema": "r5eval-ktrain-1", "built_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "definition": DEFINITION, "mix_yaml": mix_yaml, "mix_yaml_sha256": sha256_file(mix_yaml), "leaves": used, "extra_text": extra_info, "files": {}, "counts": {}, "set_sha256": {}, "frozen": True} for name, keys in sets.items(): fn = FILES[name] with gzip.open(os.path.join(out_dir, fn), "wt", encoding="utf-8", newline="\n") as f: for k in sorted(keys): f.write(k + "\n") man["files"][name] = fn man["counts"][name] = len(keys) man["set_sha256"][name] = set_hash(keys) man["ktrain_sha256"] = sha256_bytes(("|".join(man["set_sha256"][k] for k in sorted(man["set_sha256"]))).encode("ascii")) with open(os.path.join(out_dir, "ktrain_manifest.json"), "w", encoding="utf-8") as f: json.dump(man, f, ensure_ascii=False, indent=1) return man class KTrain: def __init__(self, hand_keys, hand_literal, all_keys, ktrain_sha256, info=None): self.hand_keys, self.hand_literal, self.all_keys = hand_keys, hand_literal, all_keys self.sha256 = ktrain_sha256 self.info = info or {} def flags(self, label, lang): """Slice membership of a crop with this label: dict P2, P2b, P2_literal (all False for an empty key).""" k = n1_key(label, lang) if not k: return {"P2": False, "P2b": False, "P2_literal": False} return {"P2": k not in self.hand_keys, "P2b": k not in self.all_keys, "P2_literal": k not in self.hand_literal} def load(manifest_json, verify=True): d = os.path.dirname(os.path.abspath(manifest_json)) man = json.load(open(manifest_json, encoding="utf-8")) sets = {} for name, fn in man["files"].items(): with gzip.open(os.path.join(d, fn), "rt", encoding="utf-8") as f: sets[name] = set(line.rstrip("\n") for line in f) if verify and set_hash(sets[name]) != man["set_sha256"][name]: raise SystemExit("K_train file %s does not match its recorded sha256" % fn) return KTrain(sets["hand_keys"], sets["hand_literal"], sets["all_keys"], man["ktrain_sha256"], man)