File size: 14,342 Bytes
4022aae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
"""Build Privacy Context Pairs from authored cases; no model or network access."""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
from collections import Counter
from itertools import product
from pathlib import Path

SPLITS = ("train", "validation", "test")
ROLES = ("alternative", "attribute")
SIDES = ("left", "right")
ORDINARY = ("a", "b")


def _canonical(value: object) -> str:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))


def _sha(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


def _unique_object(pairs: list[tuple[str, object]]) -> dict:
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate JSON key: {key}")
        result[key] = value
    return result


def _entry(root: Path, relative: str) -> dict:
    path = root / relative
    if not path.resolve().is_relative_to(root) or path.is_symlink():
        raise ValueError(f"Input must be an ordinary file inside its root: {relative}")
    payload = path.read_bytes()
    return {"path": relative, "bytes": len(payload), "sha256": _sha(payload)}


def _load(root: Path, relative: str) -> tuple[object, dict]:
    path = root / relative
    if not path.resolve().is_relative_to(root) or path.is_symlink():
        raise ValueError(f"Input must be an ordinary file inside its root: {relative}")
    payload = path.read_bytes()
    value = json.loads(payload, object_pairs_hook=_unique_object)
    return value, {"path": relative, "bytes": len(payload), "sha256": _sha(payload)}


def _write_json(path: Path, value: object) -> None:
    payload = json.dumps(value, indent=2, ensure_ascii=False, sort_keys=True) + "\n"
    with path.open("x", encoding="utf-8", newline="\n") as handle:
        handle.write(payload)


def _write_rows(path: Path, rows: list[dict], key: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("x", encoding="utf-8", newline="\n") as handle:
        for row in sorted(rows, key=lambda item: item[key]):
            handle.write(_canonical(row) + "\n")


def _load_cases(root: Path, protocol: dict) -> tuple[list[dict], list[dict]]:
    cases = []
    inputs = []
    required = set(protocol["source_case_keys"])
    languages = set(protocol["languages"])
    per_type = protocol["case_inventory"]["families_per_type"]
    seen = set()
    for target_type in protocol["target_types"]:
        values, entry = _load(root, f"source/{target_type}.json")
        inputs.append(entry)
        if not isinstance(values, list) or len(values) != per_type * len(languages):
            raise ValueError(
                f"{entry['path']}: expected {per_type * len(languages)} cases"
            )
        expected = {
            f"{target_type}-{number:02d}-{language}"
            for number in range(1, per_type + 1)
            for language in languages
        }
        observed = set()
        for case in values:
            if not isinstance(case, dict) or set(case) != required:
                raise ValueError(f"{entry['path']}: source case has incorrect keys")
            if any(
                not isinstance(value, str) or not value.strip()
                for value in case.values()
            ):
                raise ValueError(
                    f"{entry['path']}: all case values must be nonempty strings"
                )
            case_id = case["case_id"]
            if case_id in seen:
                raise ValueError(f"Duplicate case ID: {case_id}")
            seen.add(case_id)
            observed.add(case_id)
            if case["target_type"] != target_type or case["language"] not in languages:
                raise ValueError(f"{case_id}: source type or language mismatch")
            if case_id != f"{case['family_id']}-{case['language']}":
                raise ValueError(f"{case_id}: family/language identifier mismatch")
            cases.append(case)
        if observed != expected:
            raise ValueError(f"{entry['path']}: incomplete family/language inventory")
    return sorted(cases, key=lambda case: case["case_id"]), inputs


def _family_splits(cases: list[dict], protocol: dict) -> dict[str, str]:
    seed = protocol["split_recipe"]["seed"]
    sizes = protocol["split_recipe"]["family_counts_per_type"]
    assignments = {}
    for target_type in protocol["target_types"]:
        families = {
            case["family_id"] for case in cases if case["target_type"] == target_type
        }
        ordered = sorted(families, key=lambda family: _sha(f"{seed}|{family}".encode()))
        offset = 0
        for split in SPLITS:
            for family in ordered[offset : offset + sizes[split]]:
                assignments[family] = split
            offset += sizes[split]
        if offset != len(ordered):
            raise ValueError(f"{target_type}: split sizes do not cover all families")
    return assignments


def _record_id(case_id: str, role: str, side: str, ordinary: str) -> str:
    return f"pcp-v1-{case_id}-{role}-{side}-{ordinary}"


def _text_row(
    case: dict, split: str, case_sha: str, role: str, side: str, ordinary: str
) -> dict:
    cue = case[f"{role}_cue"]
    left, right = (cue, case["control"]) if side == "left" else (case["control"], cue)
    scene = case[f"ordinary_{ordinary}"]
    target = case["target"]
    text = f"{left}\n\n{target}.\n\n{right}\n\n{scene}"
    start = len(left) + 2
    end = start + len(target)
    right_start = end + 3
    right_end = right_start + len(right)
    ordinary_start = right_end + 2
    return {
        "id": _record_id(case["case_id"], role, side, ordinary),
        "case_id": case["case_id"],
        "family_id": case["family_id"],
        "language": case["language"],
        "target_type": case["target_type"],
        "split": split,
        "scenario_domain": case["scenario_domain"],
        "text": text,
        "target": {"text": target, "start": start, "end": end},
        "construction": {
            "role": role,
            "cue_side": side,
            "ordinary": ordinary,
            "intended_reference": case[f"{role}_reference"],
        },
        "slots": {
            "left": {"start": 0, "end": len(left)},
            "right": {"start": right_start, "end": right_end},
            "ordinary": {"start": ordinary_start, "end": len(text)},
        },
        "provenance": {
            "source_type": "synthetic",
            "authoring": "ai_assisted",
            "privacy_annotation_status": "not_human_adjudicated",
            "classifier_screening": "none",
        },
        "case_sha256": case_sha,
        "text_sha256": _sha(text.encode("utf-8")),
        "version": "1.0.0",
    }


def _pairs(case: dict, split: str) -> list[dict]:
    case_id = case["case_id"]
    common = {
        "case_id": case_id,
        "family_id": case["family_id"],
        "language": case["language"],
        "target_type": case["target_type"],
        "split": split,
    }
    result = []
    for side, ordinary in product(SIDES, ORDINARY):
        result.append(
            {
                **common,
                "id": f"{case_id}:role:{side}:{ordinary}",
                "kind": "role",
                "base_id": _record_id(case_id, "alternative", side, ordinary),
                "changed_id": _record_id(case_id, "attribute", side, ordinary),
                "direction": "attribute - alternative",
            }
        )
    for role, side in product(ROLES, SIDES):
        result.append(
            {
                **common,
                "id": f"{case_id}:ordinary:{role}:{side}",
                "kind": "ordinary",
                "base_id": _record_id(case_id, role, side, "a"),
                "changed_id": _record_id(case_id, role, side, "b"),
                "direction": "b - a",
            }
        )
    for role, ordinary in product(ROLES, ORDINARY):
        result.append(
            {
                **common,
                "id": f"{case_id}:cue_side:{role}:{ordinary}",
                "kind": "cue_side",
                "base_id": _record_id(case_id, role, "left", ordinary),
                "changed_id": _record_id(case_id, role, "right", ordinary),
                "direction": "right - left",
            }
        )
    return result


def _stats(
    cases: dict[str, list[dict]],
    texts: dict[str, list[dict]],
    pairs: dict[str, list[dict]],
    protocol: dict,
) -> dict:
    by_split = {}
    by_type = {
        name: {"records": 0, "cases": 0, "families": 0, "contrasts": 0}
        for name in protocol["target_types"]
    }
    by_language = {
        name: {"records": 0, "cases": 0, "contrasts": 0}
        for name in protocol["languages"]
    }
    seen_families = set()
    by_kind = Counter()
    shortest = None
    longest = 0
    for split in SPLITS:
        split_families = set()
        for case in cases[split]:
            target_type = case["target_type"]
            by_type[target_type]["cases"] += 1
            by_language[case["language"]]["cases"] += 1
            family = case["family_id"]
            split_families.add(family)
            if family not in seen_families:
                by_type[target_type]["families"] += 1
                seen_families.add(family)
        for row in texts[split]:
            by_type[row["target_type"]]["records"] += 1
            by_language[row["language"]]["records"] += 1
            length = len(row["text"])
            shortest = length if shortest is None else min(shortest, length)
            longest = max(longest, length)
        for row in pairs[split]:
            by_type[row["target_type"]]["contrasts"] += 1
            by_language[row["language"]]["contrasts"] += 1
            by_kind[row["kind"]] += 1
        by_split[split] = {
            "records": len(texts[split]),
            "cases": len(cases[split]),
            "families": len(split_families),
            "contrasts": len(pairs[split]),
        }
    return {
        "schema_version": 1,
        "name": protocol["name"],
        "version": protocol["version"],
        "records": sum(len(rows) for rows in texts.values()),
        "cases": sum(len(rows) for rows in cases.values()),
        "families": len(seen_families),
        "contrasts": sum(len(rows) for rows in pairs.values()),
        "gold_privacy_labels": 0,
        "by_split": by_split,
        "by_target_type": by_type,
        "by_language": by_language,
        "by_contrast_kind": dict(by_kind),
        "text_codepoint_length": {"min": shortest, "max": longest},
    }


def build(root: Path, out: Path) -> dict:
    root = root.resolve()
    out = out.resolve()
    if out.exists():
        raise ValueError(f"Output already exists; choose a new directory: {out}")
    protocol, protocol_entry = _load(root, ".construction/protocol.json")
    if (
        protocol["version"] != "1.0.0"
        or protocol["classifier_evaluation_allowed"] is not False
    ):
        raise ValueError("Expected the frozen, construction-only v1.0.0 protocol")
    source_cases, source_entries = _load_cases(root, protocol)
    inputs = sorted(
        [
            protocol_entry,
            *source_entries,
            _entry(root, "scripts/build.py"),
            _entry(root, "scripts/validate.py"),
        ],
        key=lambda entry: entry["path"],
    )
    assignments = _family_splits(source_cases, protocol)
    cases = {split: [] for split in SPLITS}
    texts = {split: [] for split in SPLITS}
    pairs = {split: [] for split in SPLITS}
    for source_case in source_cases:
        split = assignments[source_case["family_id"]]
        case_sha = _sha(_canonical(source_case).encode("utf-8"))
        cases[split].append({**source_case, "split": split, "case_sha256": case_sha})
        for role, side, ordinary in product(ROLES, SIDES, ORDINARY):
            texts[split].append(
                _text_row(source_case, split, case_sha, role, side, ordinary)
            )
        pairs[split].extend(_pairs(source_case, split))
    stats = _stats(cases, texts, pairs, protocol)
    counts = {key: stats[key] for key in ("records", "cases", "families", "contrasts")}
    expected = {"records": 2048, "cases": 256, "families": 128, "contrasts": 3072}
    if counts != expected:
        raise ValueError(f"Unexpected construction counts: {counts}")
    for entry in inputs:
        if _entry(root, entry["path"]) != entry:
            raise ValueError(f"Input changed during construction: {entry['path']}")
    out.mkdir(parents=True)
    generated = []
    for split in SPLITS:
        for directory, grouped, key in (
            ("data", texts, "id"),
            ("cases", cases, "case_id"),
            ("pairs", pairs, "id"),
        ):
            relative = f"{directory}/{split}.jsonl"
            _write_rows(out / relative, grouped[split], key)
            generated.append(relative)
    _write_json(out / "stats.json", stats)
    generated.append("stats.json")
    files = [_entry(out, relative) for relative in sorted(generated)]
    manifest = {
        "schema_version": 1,
        "name": protocol["name"],
        "version": protocol["version"],
        "protocol_sha256": protocol_entry["sha256"],
        "inputs": inputs,
        "files": files,
        "counts": counts,
    }
    _write_json(out / "manifest.json", manifest)
    with (out / "manifest.sha256").open("x", encoding="utf-8", newline="\n") as handle:
        handle.write(f"{_sha((out / 'manifest.json').read_bytes())}  manifest.json\n")
    return counts


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--root", type=Path, default=Path(__file__).resolve().parents[1]
    )
    parser.add_argument(
        "--out",
        type=Path,
        required=True,
        help="New output directory; never overwritten",
    )
    args = parser.parse_args()
    try:
        counts = build(args.root, args.out)
    except (ValueError, OSError, KeyError, TypeError) as error:
        print(f"Build failed: {error}", file=sys.stderr)
        return 1
    print(
        json.dumps(
            {"status": "built", "output": str(args.out.resolve()), **counts},
            sort_keys=True,
        )
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())