lingologos-thinkingpython / tools /build_corpus.py
tailot's picture
thinking-python: reference implementation, corpus and gates
35d4b41 verified
Raw History Blame Contribute Delete
7.95 kB
"""Generate the corpus: one row per request the system claims to understand.
The rows are composed, not invented at run time: the frames come from the lexicon of the
variety, the templates from catalog/request_templates.json, the symbols from the fixture.
Rebuilding the corpus re-derives every byte, which is what --check verifies.
"""
import argparse
import hashlib
import json
import os
import sys
from typing import Dict, List
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from lingologos_thinkingpython import catalog, lexicon # noqa: E402
CORPUS_DIR = os.path.join(ROOT, "corpus")
TEMPLATES_FILE = os.path.join(ROOT, "catalog", "request_templates.json")
#: Symbols that exist in fixtures/lab, plus names that do not exist anywhere.
REAL_SYMBOLS = ["collect", "label_for", "show", "parse", "os", "registry"]
FAKE_SYMBOLS = ["render_frame", "split_rows"]
def request_data() -> Dict[str, Dict[str, List[str]]]:
with open(TEMPLATES_FILE, "r", encoding="utf-8") as handle:
return json.load(handle)
def split_of(text: str) -> str:
"""Deterministic 80/20 train/eval split: the same text is always in the same part."""
return "eval" if int(hashlib.sha1(text.encode("utf-8")).hexdigest()[:6], 16) % 5 == 0 else "train"
def tag(row: Dict) -> Dict:
row["split"] = split_of(row["text"])
return row
def contrastive(entries: List[Dict], data: Dict) -> List[Dict]:
"""Minimal pairs: the phrase of one shape plus one stray word that is also a surface
form of another shape. The router has to keep the first one.
Chinese has no spaces, so the unit of contrast is a character: the stray there is the
first character of another shape's surface form, glued to the phrase. The router reads
Chinese as substrings, so the pair is a real pair, not a token trick.
"""
out: List[Dict] = []
pairs = sorted(json.load(open(os.path.join(ROOT, "catalog", "conflict_policy.json"),
encoding="utf-8"))["pairs"])
policies = {tuple(sorted(k.split("|"))) for k in pairs}
for lang in lexicon.LANGS:
frames = lexicon.load(lang)["frames"]
templates = data["templates"][lang]
for first in entries:
for second in entries:
if first["id"] == second["id"] or tuple(sorted([first["id"], second["id"]])) not in policies:
continue
for phrase in frames.get(first["id"], [])[:2]:
candidate = frames.get(second["id"], [""])[:1][0] or ""
stray = candidate[:1] if lang == "zh" else candidate.split(" ")[0]
if not stray or stray in phrase:
continue
for template in templates[:2]:
for symbol in REAL_SYMBOLS[:3]:
text = template.replace("{p}", phrase).replace("{s}", symbol)
text = text + (" " + stray if lang != "zh" else stray)
out.append(tag({"level": "L3", "lang": lang,
"frame": first["id"], "text": text,
"symbol": symbol, "distractor": second["id"],
"source": "composed:minimal-pair"}))
return out
def rows(entries: List[Dict]) -> List[Dict]:
out: List[Dict] = []
data = request_data()
for lang in lexicon.LANGS:
frames = lexicon.load(lang)["frames"]
for entry in entries:
frame = entry["id"]
phrases = frames.get(frame) or entry.get("frames") or []
for phrase in phrases:
for template in data["templates"][lang]:
for symbol in REAL_SYMBOLS:
text = template.replace("{p}", phrase).replace("{s}", symbol)
out.append(tag({"level": "L1", "lang": lang, "frame": frame,
"text": text, "symbol": symbol,
"source": "composed:catalog+lexicon+fixture"}))
out.append(tag({"level": "L2", "lang": lang, "frame": frame,
"text": text + " " + lang, "symbol": symbol,
"noise": "trailing token",
"source": "composed:catalog+lexicon+fixture"}))
for negative in data["negatives"][lang]:
for symbol in FAKE_SYMBOLS:
out.append(tag({"level": "L4", "lang": lang, "frame": "",
"text": negative + " " + symbol, "symbol": symbol,
"expected": "REFUSED",
"source": "composed:negative-set"}))
for negative in data["negatives"][lang]:
out.append(tag({"level": "L5", "lang": lang, "frame": "", "text": negative,
"expected": "REFUSED", "source": "composed:negative-set"}))
out.extend(contrastive(entries, data))
return out
def fingerprint(rows_: List[Dict]) -> str:
digest = hashlib.sha256()
for row in rows_:
digest.update(json.dumps(row, sort_keys=True, ensure_ascii=False).encode("utf-8"))
digest.update(b"\n")
return digest.hexdigest()
def slices(built: List[Dict]) -> Dict[str, List[Dict]]:
"""The two artifacts that are read apart from the corpus: the adversarial rows (the
minimal pairs and the near misses of the negative set) and the refusal trajectories.
"""
return {"adversarial": [row for row in built if row["level"] in ("L3", "L4")],
"trajectories": [row for row in built if row["level"] == "L5"]}
def encode(rows_: List[Dict]) -> str:
return "".join(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n"
for row in rows_)
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Build the composed corpus.")
parser.add_argument("--check", action="store_true", help="verify the corpus on disk")
parser.add_argument("--out", default=os.path.join(CORPUS_DIR, "corpus.jsonl"))
args = parser.parse_args(argv)
entries = catalog.load_entries()
built = rows(entries)
payload = encode(built)
parts = {os.path.join(CORPUS_DIR, name + ".jsonl"): encode(part)
for name, part in slices(built).items()}
if args.check:
if not os.path.isfile(args.out):
sys.stderr.write("no corpus on disk\n")
return 1
with open(args.out, "r", encoding="utf-8") as handle:
stored = handle.read()
ok = stored == payload
for path, part in sorted(parts.items()):
if not os.path.isfile(path):
sys.stderr.write("missing slice %s\n" % path)
ok = False
continue
with open(path, "r", encoding="utf-8") as handle:
ok = ok and handle.read() == part
print("rows=%d fingerprint=%s match=%s"
% (len(built), fingerprint(built)[:16], ok))
return 0 if ok else 1
os.makedirs(CORPUS_DIR, exist_ok=True)
with open(args.out, "w", encoding="utf-8", newline="\n") as handle:
handle.write(payload)
for path, part in sorted(parts.items()):
with open(path, "w", encoding="utf-8", newline="\n") as handle:
handle.write(part)
counts: Dict[str, int] = {}
for row in built:
counts[row["level"]] = counts.get(row["level"], 0) + 1
print("wrote %d rows: %s" % (len(built), json.dumps(counts)))
print("slices: %s" % ", ".join("%s=%d" % (os.path.basename(path), part.count("\n"))
for path, part in sorted(parts.items())))
print("fingerprint %s" % fingerprint(built)[:16])
return 0
if __name__ == "__main__":
raise SystemExit(main())