File size: 7,953 Bytes
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
35d4b41
 
4bc63c7
 
 
 
 
35d4b41
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
 
 
 
 
 
 
 
4bc63c7
 
 
 
 
 
 
 
35d4b41
 
 
4bc63c7
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
 
4bc63c7
 
 
 
 
 
 
35d4b41
 
 
4bc63c7
 
 
 
35d4b41
 
4bc63c7
 
 
 
 
 
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
"""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())