Download scripts/build.py from TeskesLab/privacy-context-pairs: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/datasets/TeskesLab/privacy-context-pairs/resolve/main/scripts/build.py
- Command line
-
hf download hf://datasets/TeskesLab/privacy-context-pairs/scripts/build.py
-
curl -L -o build.py https://huggingface.co/datasets/TeskesLab/privacy-context-pairs/resolve/main/scripts/build.py
14.3 kB
| """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()) | |