pii-secrets-guard-base / scripts /data_builder.py
greendesk1631's picture
Release Tamarillo/pii-secrets-guard-base
fd61893 verified
Raw History Blame Contribute Delete
19.9 kB
"""Build balanced, leak-free, commercially clean train/val/test JSONL corpora for pii-secrets-guard.
All external datasets used are strictly commercially permissive (CC-BY-4.0 / Apache-2.0 / MIT):
- nvidia/Nemotron-PII (CC-BY-4.0)
- nvidia/Nemotron-PII-Japan (CC-BY-4.0)
- gretelai/gretel-pii-masking-en-v1 (Apache-2.0)
- gretelai/synthetic_pii_finance_multilingual (Apache-2.0)
- Wismut/nym-pii-multilingual-data (MIT)
- Tamarillo deterministic synthetic Agent Secrets & Hard Negatives (Apache-2.0)
Explicitly excludes ALL ai4privacy datasets to guarantee clean Apache-2.0 redistribution.
"""
from __future__ import annotations
import argparse
import ast
import hashlib
import json
import os
import random
import re
from collections import Counter
from pathlib import Path
from typing import Any
from synth_secrets import build_long_context_needle_suite, generate_secrets_and_negatives
from taxonomy import CANONICAL_ENTITIES, SOURCE_ANNOTATED_ENTITIES, normalize_and_merge_spans
# Regex to catch accidental unannotated secret-like tokens in prose datasets
_UNANNOTATED_SECRET_RE = re.compile(
r"(?:sk-proj-|sk-ant-api|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{30,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)"
)
def _stable_hash_bucket(text: str, mod: int = 100) -> int:
return int(hashlib.md5(text.encode("utf-8", errors="ignore")).hexdigest()[:8], 16) % mod
def _parse_list_field(val: Any) -> list[Any]:
if isinstance(val, list):
return val
if isinstance(val, str):
s = val.strip()
if not s:
return []
try:
return json.loads(s)
except Exception:
try:
return ast.literal_eval(s)
except Exception:
return []
return []
def _find_entity_spans_in_text(text: str, entities: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Locate span offsets for datasets (like gretel-pii-masking-en-v1) that supply surface strings."""
spans: list[dict[str, Any]] = []
# Sort longer strings first to reduce partial substring collisions
items: list[tuple[str, str]] = []
for ent in entities:
surf = str(ent.get("entity", "")).strip()
types = ent.get("types", [])
if not surf or not types:
continue
lbl = str(types[0])
items.append((surf, lbl))
items.sort(key=lambda x: -len(x[0]))
used: list[tuple[int, int]] = []
for surf, lbl in items:
start_search = 0
while True:
idx = text.find(surf, start_search)
if idx == -1:
break
end = idx + len(surf)
# Require word-ish boundary for short alphanumeric strings to prevent substring matches
ok_boundary = True
if len(surf) <= 5 and surf.isalnum():
if idx > 0 and text[idx - 1].isalnum():
ok_boundary = False
if end < len(text) and text[end].isalnum():
ok_boundary = False
overlaps = any(not (end <= u0 or idx >= u1) for u0, u1 in used)
if ok_boundary and not overlaps:
spans.append({"start": idx, "end": end, "label": lbl})
used.append((idx, end))
start_search = idx + 1
return spans
def _extract_nemotron(row: dict[str, Any], source: str, lang: str) -> dict[str, Any] | None:
text = row.get("text")
if not isinstance(text, str) or not text.strip():
return None
raw_spans = _parse_list_field(row.get("spans"))
spans = normalize_and_merge_spans(text, raw_spans)
return {"text": text, "spans": spans, "source": source, "language": lang}
def _extract_gretel_en(row: dict[str, Any]) -> dict[str, Any] | None:
text = row.get("text")
if not isinstance(text, str) or not text.strip():
return None
ents = _parse_list_field(row.get("entities"))
raw_spans = _find_entity_spans_in_text(text, ents)
spans = normalize_and_merge_spans(text, raw_spans)
return {"text": text, "spans": spans, "source": "gretel_en", "language": "en"}
_GRETEL_LANG_MAP = {
"English": "en",
"Spanish": "es",
"Italian": "it",
"France": "fr",
"French": "fr",
"German": "de",
"Dutch": "nl",
"Swedish": "sv",
}
def _extract_gretel_multi(row: dict[str, Any]) -> dict[str, Any] | None:
text = row.get("generated_text")
if not isinstance(text, str) or not text.strip():
return None
raw_spans = _parse_list_field(row.get("pii_spans"))
spans = normalize_and_merge_spans(text, raw_spans)
lang = _GRETEL_LANG_MAP.get(str(row.get("language", "English")), "en")
return {"text": text, "spans": spans, "source": "gretel_multi", "language": lang}
def _extract_wismut(row: dict[str, Any]) -> dict[str, Any] | None:
text = row.get("text")
if not isinstance(text, str) or not text.strip():
return None
raw_spans = _parse_list_field(row.get("entities"))
spans = normalize_and_merge_spans(text, raw_spans)
return {"text": text, "spans": spans, "source": "wismut_multi", "language": "multi"}
def _sample_rows(rows: list[dict[str, Any]], max_n: int, rng: random.Random) -> list[dict[str, Any]]:
if max_n <= 0 or len(rows) <= max_n:
return rows
idx = rng.sample(range(len(rows)), max_n)
return [rows[i] for i in idx]
def _make_long_context_concat(
pool: list[dict[str, Any]],
n_long: int,
rng: random.Random,
target_min_chars: int = 3600,
target_max_chars: int = 12000,
) -> list[dict[str, Any]]:
"""Concatenate 4-12 documents with realistic separators while preserving exact span offsets
and computing the exact intersection of annotated entities for partial-label masking."""
if not pool or n_long <= 0:
return []
seps = ["\n\n---\n\n", "\n\n[NEXT_RECORD]\n", "\n\n"]
out: list[dict[str, Any]] = []
for _ in range(n_long):
target = rng.randint(target_min_chars, target_max_chars)
parts: list[str] = []
merged_spans: list[dict[str, Any]] = []
cur = 0
ann_inter: set[str] | None = None
while cur < target:
ex = rng.choice(pool)
src_ann = set(SOURCE_ANNOTATED_ENTITIES.get(ex.get("source", ""), CANONICAL_ENTITIES))
ann_inter = src_ann if ann_inter is None else (ann_inter & src_ann)
if parts:
sep = rng.choice(seps)
parts.append(sep)
cur += len(sep)
txt = ex["text"]
parts.append(txt)
for sp in ex["spans"]:
merged_spans.append({
"start": sp["start"] + cur,
"end": sp["end"] + cur,
"label": sp["label"],
})
cur += len(txt)
full_text = "".join(parts)
out.append({
"text": full_text,
"spans": merged_spans,
"source": "long_context_concat",
"language": "multi",
"annotated_entities": sorted(ann_inter or []),
})
return out
def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
def _summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:
src = Counter(r.get("source", "unknown") for r in rows)
ent = Counter(sp["label"] for r in rows for sp in r.get("spans", []))
neg = sum(1 for r in rows if not r.get("spans"))
avg_len = sum(len(r["text"]) for r in rows) / max(1, len(rows))
return {
"count": len(rows),
"zero_entity_rows": neg,
"avg_chars": round(avg_len, 1),
"sources": dict(src),
"entities": dict(ent.most_common()),
}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--out-dir", type=str, required=True)
parser.add_argument("--mode", choices=["en", "multilingual"], default="multilingual")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--max-nemotron-en", type=int, default=65000)
parser.add_argument("--max-nemotron-ja", type=int, default=15000)
parser.add_argument("--max-gretel-en", type=int, default=35000)
parser.add_argument("--max-gretel-multi", type=int, default=40000)
parser.add_argument("--max-wismut", type=int, default=95000)
parser.add_argument("--n-synth-secrets", type=int, default=25000)
parser.add_argument("--n-hard-negatives", type=int, default=15000)
parser.add_argument("--n-long-concat", type=int, default=15000)
parser.add_argument("--smoke", action="store_true", help="Tiny subset for fast pipeline smoke test")
args = parser.parse_args()
os.environ.setdefault("HF_HOME", "/tmp/hf")
from datasets import load_dataset # imported here so unit tests work without datasets installed
rng = random.Random(args.seed)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
if args.smoke:
args.max_nemotron_en = 2000
args.max_nemotron_ja = 500
args.max_gretel_en = 1500
args.max_gretel_multi = 1500
args.max_wismut = 2000
args.n_synth_secrets = 1200
args.n_hard_negatives = 600
args.n_long_concat = 400
train_rows: list[dict[str, Any]] = []
val_rows: list[dict[str, Any]] = []
test_suites: dict[str, list[dict[str, Any]]] = {}
# 1. nvidia/Nemotron-PII (CC-BY-4.0) — official train/test splits
print("[data] Loading nvidia/Nemotron-PII ...")
ds_nem = load_dataset("nvidia/Nemotron-PII")
nem_tr, nem_va = [], []
for row in ds_nem["train"]:
ex = _extract_nemotron(row, "nemotron_en", "en")
if not ex:
continue
if _stable_hash_bucket(ex["text"]) < 5:
nem_va.append(ex)
else:
nem_tr.append(ex)
nem_te = [ex for row in ds_nem["test"] if (ex := _extract_nemotron(row, "nemotron_en", "en"))]
train_rows.extend(_sample_rows(nem_tr, args.max_nemotron_en, rng))
val_rows.extend(_sample_rows(nem_va, 2500 if not args.smoke else 300, rng))
test_suites["nemotron_en"] = _sample_rows(nem_te, 5000 if not args.smoke else 400, rng)
# 2. gretelai/gretel-pii-masking-en-v1 (Apache-2.0) — official train/val/test
print("[data] Loading gretelai/gretel-pii-masking-en-v1 ...")
ds_gen = load_dataset("gretelai/gretel-pii-masking-en-v1")
gen_tr = [ex for row in ds_gen["train"] if (ex := _extract_gretel_en(row))]
gen_va = [ex for row in ds_gen["validation"] if (ex := _extract_gretel_en(row))]
gen_te = [ex for row in ds_gen["test"] if (ex := _extract_gretel_en(row))]
train_rows.extend(_sample_rows(gen_tr, args.max_gretel_en, rng))
val_rows.extend(_sample_rows(gen_va, 2000 if not args.smoke else 250, rng))
test_suites["gretel_en"] = _sample_rows(gen_te, 4000 if not args.smoke else 400, rng)
if args.mode == "multilingual":
# 3. gretelai/synthetic_pii_finance_multilingual (Apache-2.0) — official train/test
print("[data] Loading gretelai/synthetic_pii_finance_multilingual ...")
ds_gm = load_dataset("gretelai/synthetic_pii_finance_multilingual")
gm_tr, gm_va = [], []
for row in ds_gm["train"]:
ex = _extract_gretel_multi(row)
if not ex:
continue
if _stable_hash_bucket(ex["text"]) < 5:
gm_va.append(ex)
else:
gm_tr.append(ex)
gm_te = [ex for row in ds_gm["test"] if (ex := _extract_gretel_multi(row))]
train_rows.extend(_sample_rows(gm_tr, args.max_gretel_multi, rng))
val_rows.extend(_sample_rows(gm_va, 2000 if not args.smoke else 250, rng))
test_suites["gretel_multi"] = _sample_rows(gm_te, 5000 if not args.smoke else 400, rng)
# 4. Wismut/nym-pii-multilingual-data (MIT) — official train/val/test (streamed/sampled!)
print("[data] Loading Wismut/nym-pii-multilingual-data ...")
ds_wis = load_dataset("Wismut/nym-pii-multilingual-data", streaming=True)
wis_tr: list[dict[str, Any]] = []
# Strided sampling across streaming train to preserve full 23-language diversity
for idx, row in enumerate(ds_wis["train"]):
if idx % 7 != 0 and not args.smoke:
continue
ex = _extract_wismut(row)
if ex:
wis_tr.append(ex)
if len(wis_tr) >= args.max_wismut:
break
wis_va: list[dict[str, Any]] = []
for row in ds_wis["validation"]:
ex = _extract_wismut(row)
if ex:
wis_va.append(ex)
if len(wis_va) >= (3000 if not args.smoke else 300):
break
wis_te: list[dict[str, Any]] = []
for row in ds_wis["test"]:
ex = _extract_wismut(row)
if ex:
wis_te.append(ex)
if len(wis_te) >= (6000 if not args.smoke else 500):
break
train_rows.extend(wis_tr)
val_rows.extend(wis_va)
test_suites["wismut_multi"] = wis_te
# 5. nvidia/Nemotron-PII-Japan (CC-BY-4.0)
try:
print("[data] Loading nvidia/Nemotron-PII-Japan ...")
ds_ja = load_dataset("nvidia/Nemotron-PII-Japan", streaming=True)
ja_tr, ja_va = [], []
for row in ds_ja["train"]:
ex = _extract_nemotron(row, "nemotron_ja", "ja")
if not ex:
continue
if _stable_hash_bucket(ex["text"]) < 5 and len(ja_va) < (800 if not args.smoke else 100):
ja_va.append(ex)
elif len(ja_tr) < args.max_nemotron_ja:
ja_tr.append(ex)
if len(ja_tr) >= args.max_nemotron_ja and len(ja_va) >= (800 if not args.smoke else 100):
break
train_rows.extend(ja_tr)
val_rows.extend(ja_va)
if "test" in ds_ja:
ja_te = []
for row in ds_ja["test"]:
ex = _extract_nemotron(row, "nemotron_ja", "ja")
if ex:
ja_te.append(ex)
if len(ja_te) >= (2000 if not args.smoke else 200):
break
test_suites["nemotron_ja"] = ja_te
except Exception as e:
print(f"[warn] Skipping Nemotron-PII-Japan due to load error: {e}")
# Filter out any prose rows with unannotated secret-like tokens to avoid label conflicts
def _clean_prose(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
kept = []
for r in rows:
if not r["spans"] and _UNANNOTATED_SECRET_RE.search(r["text"]):
continue
kept.append(r)
return kept
train_rows = _clean_prose(train_rows)
# 6. Synthetic Agent Secrets & Hard Negatives (strictly split-isolated template families!)
print("[data] Generating Agent Secrets & Hard Negatives ...")
sec_tr = generate_secrets_and_negatives("train", args.n_synth_secrets, args.n_hard_negatives, seed=args.seed + 101)
sec_va = generate_secrets_and_negatives(
"validation",
1500 if not args.smoke else 200,
1000 if not args.smoke else 150,
seed=args.seed + 202,
)
sec_te = generate_secrets_and_negatives(
"test",
2000 if not args.smoke else 300,
0,
seed=args.seed + 303,
)
hardneg_te = generate_secrets_and_negatives(
"test",
0,
1500 if not args.smoke else 200,
seed=args.seed + 404,
)
train_rows.extend(sec_tr)
val_rows.extend(sec_va)
test_suites["agent_secrets"] = sec_te
test_suites["hard_negatives"] = hardneg_te
# 7. Span-preserving long-context concatenated training examples (1K-4K tokens)
print("[data] Building long-context concatenated training examples ...")
long_tr = _make_long_context_concat(train_rows, args.n_long_concat, rng)
train_rows.extend(long_tr)
# 8. Long-Context Needle-in-a-Haystack held-out eval suite (depths ~250..5000 tokens)
needle_base = (test_suites["agent_secrets"][:80] + test_suites["nemotron_en"][:80]) if not args.smoke else (
test_suites["agent_secrets"][:15] + test_suites["nemotron_en"][:15]
)
test_suites["long_context_needle"] = build_long_context_needle_suite(
needle_base,
target_char_depths=[1000, 3200, 6400, 12800, 20000],
seed=args.seed + 505,
)
# 9. Zero-shot OOD PII Benchmarks (NEVER included in train or val!)
try:
print("[data] Loading zero-shot OOD YalenLabs/yalen-pii-ner-bias-audit ...")
ds_yalen = load_dataset("YalenLabs/yalen-pii-ner-bias-audit", "benchmark", split="train")
yalen_rows = []
for row in ds_yalen:
txt = row.get("text")
if not isinstance(txt, str) or not txt.strip():
continue
raw_ents = _parse_list_field(row.get("entities"))
spans = normalize_and_merge_spans(txt, raw_ents)
yalen_rows.append({"text": txt, "spans": spans, "source": "ood_yalen_bias", "language": row.get("lang", "en")})
test_suites["ood_yalen_bias"] = _sample_rows(yalen_rows, 2000 if not args.smoke else 200, rng)
except Exception as e:
print(f"[warn] Skipping OOD YalenLabs: {e}")
try:
print("[data] Loading zero-shot OOD BTX24/turkish-privacy-pii-ner ...")
ds_tr = load_dataset("BTX24/turkish-privacy-pii-ner", split="test")
tr_rows = []
for row in ds_tr:
txt = row.get("text")
if not isinstance(txt, str) or not txt.strip():
continue
raw_lbls = _parse_list_field(row.get("label"))
remapped = [{"start": x["start"], "end": x["end"], "label": x.get("category", "")} for x in raw_lbls if isinstance(x, dict)]
spans = normalize_and_merge_spans(txt, remapped)
tr_rows.append({"text": txt, "spans": spans, "source": "ood_btx24_tr", "language": "tr"})
test_suites["ood_btx24_tr"] = _sample_rows(tr_rows, 1500 if not args.smoke else 200, rng)
except Exception as e:
print(f"[warn] Skipping OOD BTX24 Turkish: {e}")
# Attach explicit annotated_entities metadata for partial-label NER masking
for r in train_rows:
if "annotated_entities" not in r:
r["annotated_entities"] = SOURCE_ANNOTATED_ENTITIES.get(r.get("source", ""), list(CANONICAL_ENTITIES))
# Strict deduplication of train vs val/test by exact text hash
eval_hashes = {hashlib.md5(r["text"].encode("utf-8", errors="ignore")).hexdigest() for r in val_rows}
for suite in test_suites.values():
for r in suite:
eval_hashes.add(hashlib.md5(r["text"].encode("utf-8", errors="ignore")).hexdigest())
train_rows = [
r for r in train_rows
if hashlib.md5(r["text"].encode("utf-8", errors="ignore")).hexdigest() not in eval_hashes
]
rng.shuffle(train_rows)
_write_jsonl(out_dir / "train.jsonl", train_rows)
_write_jsonl(out_dir / "val.jsonl", val_rows)
for name, rows in test_suites.items():
_write_jsonl(out_dir / f"test_{name}.jsonl", rows)
stats = {
"mode": args.mode,
"entities": CANONICAL_ENTITIES,
"train": _summarize(train_rows),
"val": _summarize(val_rows),
"tests": {k: _summarize(v) for k, v in test_suites.items()},
}
(out_dir / "dataset_stats.json").write_text(json.dumps(stats, indent=2), encoding="utf-8")
print("[data] Done. Summary:")
print(json.dumps({k: v["count"] for k, v in stats["tests"].items()}, indent=2))
print(f"Train={stats['train']['count']:,} | Val={stats['val']['count']:,}")
if __name__ == "__main__":
main()