Datasets:
Download validate.py from josh-hud/code-pii: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/datasets/josh-hud/code-pii/resolve/main/validate.py
- Command line
-
hf download hf://datasets/josh-hud/code-pii/validate.py
-
curl -L -o validate.py https://huggingface.co/datasets/josh-hud/code-pii/resolve/main/validate.py
12.6 kB
| #!/usr/bin/env python3 | |
| """Validate a generated dataset directory: offsets, label counts, regex detectability, cluster / entity / replacement | |
| consistency (v3), random samples. | |
| Usage: python validate.py --data /path/to/dataset [--sample-files 2] [--n-eyeball 20] [--write-sample sample.jsonl --sample-n 500] | |
| Hard failures (assert): bad offsets, dangling or inconsistent entity ids, surface forms that do not resolve to the | |
| entity's form table, replacements with a different format/charset, replacement collisions inside a cluster, | |
| non-contiguous clusters, duplicate entity ids. The sample written with --write-sample consists of whole clusters. | |
| """ | |
| import argparse, collections, glob, json, os, random, re | |
| SCANNER = { # a deliberately simple regex scanner (gitleaks-like) used only as a sanity check | |
| "aws_access_key_id": re.compile(r"AKIA[0-9A-Z]{16}"), | |
| "github_pat": re.compile(r"gh[pos]_[A-Za-z0-9]{36}"), | |
| "github_fine_grained_pat": re.compile(r"github_pat_[A-Za-z0-9]{22}_[A-Za-z0-9]{59}"), | |
| "slack_token": re.compile(r"xox[abp]-[0-9A-Za-z-]{10,}"), | |
| "jwt": re.compile(r"eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"), | |
| "google_api_key": re.compile(r"AIza[0-9A-Za-z_-]{35}"), | |
| "stripe_secret_key": re.compile(r"(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{24}"), | |
| "pem_private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), | |
| "email": re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), | |
| "sendgrid_api_key": re.compile(r"SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}"), | |
| "openai_api_key": re.compile(r"sk-(?:proj-)?[A-Za-z0-9]{48}"), | |
| "hf_token": re.compile(r"hf_[A-Za-z0-9]{34}"), | |
| "gitlab_pat": re.compile(r"glpat-[A-Za-z0-9_-]{20}"), | |
| "npm_token": re.compile(r"npm_[A-Za-z0-9]{36}"), | |
| "generic_hex_key": re.compile(r"\b[0-9a-f]{32,64}\b"), | |
| } | |
| PEM_ESCAPE = ("\n", "\\n\" +\n \"") | |
| PERSON_LABEL = {"full_name": "person_name", "first_name": "person_name", "last_name": "person_name", "username": "username", "handle": "username", "email": "email"} | |
| def charset(v): | |
| return "+".join(k for k, rx in (("digit", "[0-9]"), ("lower", "[a-z]"), ("symbol", "[^A-Za-z0-9]"), ("upper", "[A-Z]")) if re.search(rx, v)) | |
| def check_cluster(recs, st, problems): | |
| """All invariants that need the whole cluster: entity table on doc 0, ids, forms, replacements, uniqueness.""" | |
| cid = recs[0]["cluster_id"] | |
| if [r["doc_index"] for r in recs] != list(range(len(recs))) or any(r["cluster_size"] != len(recs) or r["cluster_kind"] != recs[0]["cluster_kind"] for r in recs): | |
| problems["cluster_shape"] += 1 | |
| if recs[0]["entities"] is None or any(r["entities"] is not None for r in recs[1:]): | |
| problems["entities_placement"] += 1 | |
| ents = {e["entity_id"]: e for e in (recs[0]["entities"] or [])} | |
| if len(ents) != len(recs[0]["entities"] or []): | |
| problems["duplicate_entity_id"] += 1 | |
| seen = collections.Counter(); docs = collections.defaultdict(set) | |
| originals = set(); replacements = set() | |
| for e in ents.values(): | |
| if not e["entity_id"].startswith(cid + "/"): problems["entity_id_prefix"] += 1 | |
| if e["owner_entity_id"] is not None and ents.get(e["owner_entity_id"], {}).get("entity_type") != "person": problems["owner_unresolved"] += 1 | |
| if e["entity_type"] == "person" and set(e["forms"]) != {"full_name", "first_name", "last_name", "username", "handle", "email"}: problems["person_forms"] += 1 | |
| if e["entity_type"] != "person" and (e["forms"].get("literal") != e["canonical"] or e["replacement_forms"].get("literal") != e["replacement_canonical"]): problems["canonical_form"] += 1 | |
| for k, v in e["forms"].items(): | |
| originals.add(v) | |
| rv = e["replacement_forms"].get(k) | |
| if rv is None or rv == v: problems["replacement_missing_or_same"] += 1 | |
| else: replacements.add(rv) | |
| if e["entity_type"] != "person": | |
| v, rv = e["canonical"], e["replacement_canonical"] | |
| rx = SCANNER.get(e["value_type"]) | |
| if rx and bool(rx.search(v)) != bool(rx.search(rv)): problems["replacement_format"] += 1 | |
| if e["value_type"] not in ("jwt", "basic_auth_b64") and charset(v) != charset(rv): problems["replacement_charset"] += 1 | |
| if e["value_type"] not in ("password", "email", "jwt", "basic_auth_b64") and len(v) != len(rv): problems["replacement_length"] += 1 | |
| if e["value_type"] == "pem_private_key" and v.split("\n")[0] != rv.split("\n")[0]: problems["replacement_pem_kind"] += 1 | |
| if originals & replacements: problems["replacement_equals_original"] += 1 | |
| for r in recs: | |
| t = r["text"] | |
| for s in r["spans"]: | |
| e = ents.get(s["entity_id"]) | |
| if e is None: problems["span_entity_missing"] += 1; continue | |
| seen[e["entity_id"]] += 1; docs[e["entity_id"]].add(r["doc_index"]) | |
| k = s["surface_form_type"]; fk = "literal" if k == "escaped_literal" else k | |
| form, repl = e["forms"].get(fk), e["replacement_forms"].get(fk) | |
| if k == "escaped_literal": form = form and form.replace(*PEM_ESCAPE); repl = repl and repl.replace(*PEM_ESCAPE) | |
| if form != s["value"]: problems["span_form_mismatch"] += 1 | |
| if repl != s["replacement"]: problems["span_replacement_mismatch"] += 1 | |
| exp_label = PERSON_LABEL.get(fk, e["entity_type"]) if e["entity_type"] == "person" else e["entity_type"] | |
| if s["label"] != exp_label: problems["span_label_vs_entity"] += 1 | |
| st["surface_form"][k] += 1 | |
| for s in r["hard_negatives"]: | |
| if s.get("entity_id") is not None or s.get("replacement") is not None: problems["negative_with_entity"] += 1 | |
| for eid, e in ents.items(): | |
| if seen[eid] == 0: problems["entity_without_span"] += 1 | |
| if seen[eid] != e["n_mentions"] or len(docs[eid]) != e["n_docs"]: problems["entity_counts"] += 1 | |
| st["entity_type"][e["entity_type"]] += 1 | |
| st["docs_per_entity"][min(e["n_docs"], 6)] += 1; st["mentions_per_entity"][min(e["n_mentions"], 8)] += 1 | |
| if e["owner_entity_id"]: st["owned_entities"] += 1 | |
| if len(recs) > 1: | |
| st["multi_entities"] += 1; st["recurring_entities"] += e["n_docs"] > 1 | |
| # gold anonymized text must keep the same scanner hits at the same spans (replacements are format-preserving) | |
| r = recs[0]; t = r["text"]; out = []; pos = 0; ok = True | |
| for s in sorted(r["spans"], key=lambda s: s["start"]): | |
| out.append(t[pos:s["start"]]); out.append(s["replacement"]); pos = s["end"] | |
| rx = SCANNER.get(s["value_type"]) | |
| if rx and bool(rx.search(s["value"])) and not rx.search(s["replacement"]): ok = False | |
| out.append(t[pos:]); anon = "".join(out) | |
| if any(s["value"] in anon for s in r["spans"] if len(s["value"]) >= 8): problems["original_survives_in_gold_anonymized"] += 1 | |
| if not ok: problems["gold_anonymized_scanner"] += 1 | |
| st["clusters"] += 1; st["cluster_kind"][r["cluster_kind"]] += 1; st["cluster_size"][min(len(recs), 8)] += 1 | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--data", required=True) | |
| ap.add_argument("--sample-files", type=int, default=2) | |
| ap.add_argument("--n-eyeball", type=int, default=20) | |
| ap.add_argument("--write-sample") | |
| ap.add_argument("--sample-n", type=int, default=500, help="approximate number of records (whole clusters are kept)") | |
| ap.add_argument("--seed", type=int, default=0) | |
| a = ap.parse_args() | |
| random.seed(a.seed) | |
| parts = sorted(glob.glob(os.path.join(a.data, "part-?????.jsonl"))) | |
| use = parts[:a.sample_files] | |
| C = collections.Counter | |
| st = dict(files=0, injected=0, clean=0, spans=0, negs=0, bad_offsets=0, label=C(), vtype=C(), ctx=C(), lang=C(), negtype=C(), | |
| size_hist=C(), spans_per_file=C(), bytes=0, clusters=0, cluster_kind=C(), cluster_size=C(), entity_type=C(), | |
| docs_per_entity=C(), mentions_per_entity=C(), surface_form=C(), owned_entities=0, multi_entities=0, recurring_entities=0, cross_cluster_value_reuse_dictionary=0) | |
| problems = C(); det = C(); det_tot = C() | |
| all_entity_ids = set(); all_canonicals = C() | |
| reservoir = []; n_seen = 0 # reservoir over clusters | |
| for p in use: | |
| cur = [] | |
| def finish(): | |
| nonlocal n_seen | |
| if not cur: return | |
| check_cluster(cur, st, problems) | |
| for e in (cur[0]["entities"] or []): | |
| if e["entity_id"] in all_entity_ids: problems["global_duplicate_entity_id"] += 1 | |
| all_entity_ids.add(e["entity_id"]) | |
| if e["entity_type"] != "person": all_canonicals[(e["value_type"], e["canonical"])] += 1 | |
| n_seen += 1 | |
| if len(reservoir) < a.sample_n: | |
| reservoir.append(list(cur)) | |
| else: | |
| j = random.randrange(n_seen) | |
| if j < a.sample_n: reservoir[j] = list(cur) | |
| cur.clear() | |
| with open(p, encoding="utf-8") as fh: | |
| for line in fh: | |
| r = json.loads(line); t = r["text"] | |
| if cur and r["cluster_id"] != cur[0]["cluster_id"]: | |
| finish() | |
| cur.append(r) | |
| st["files"] += 1; st["bytes"] += len(line) | |
| st["lang"][r["language"]] += 1 | |
| st["size_hist"][("<1KB" if len(t) < 1024 else "<10KB" if len(t) < 10240 else "<100KB" if len(t) < 102400 else ">=100KB")] += 1 | |
| st["spans_per_file"][min(len(r["spans"]), 6)] += 1 | |
| st["injected" if r["spans"] else "clean"] += 1 | |
| for s in r["spans"] + r["hard_negatives"]: | |
| if t[s["start"]:s["end"]] != s["value"]: | |
| st["bad_offsets"] += 1 | |
| prev_end = -1 | |
| for s in sorted(r["spans"] + r["hard_negatives"], key=lambda s: s["start"]): | |
| if s["start"] < prev_end: problems["overlap"] += 1 | |
| prev_end = s["end"] | |
| for s in r["spans"]: | |
| st["spans"] += 1; st["label"][s["label"]] += 1; st["vtype"][s["value_type"]] += 1; st["ctx"][s["context"]] += 1 | |
| rx = SCANNER.get(s["value_type"]) | |
| if rx: | |
| det_tot[s["value_type"]] += 1 | |
| if rx.search(s["value"]) and any(m.start() <= s["start"] < m.end() for m in rx.finditer(t)): | |
| det[s["value_type"]] += 1 | |
| for s in r["hard_negatives"]: | |
| st["negs"] += 1; st["negtype"][s["value_type"]] += 1 | |
| finish() | |
| # short dictionary passwords / emails legitimately recur across clusters (reported); long random values must not | |
| st["cross_cluster_value_reuse_dictionary"] = sum(1 for (vt, v), n in all_canonicals.items() if n > 1 and vt in ("password", "email")) | |
| problems["cross_cluster_value_reuse_random"] = sum(1 for (vt, v), n in all_canonicals.items() if n > 1 and vt not in ("password", "email")) | |
| out = {k: (dict(v.most_common()) if isinstance(v, C) else v) for k, v in st.items()} | |
| out["regex_detectability"] = {k: f"{det[k]}/{det_tot[k]} ({100*det[k]/det_tot[k]:.1f}%)" for k in sorted(det_tot)} | |
| out["problems"] = dict(problems) | |
| print(json.dumps(out, indent=1)) | |
| assert st["bad_offsets"] == 0, st["bad_offsets"] | |
| assert not any(problems.values()), problems | |
| if a.write_sample: | |
| with open(a.write_sample, "w", encoding="utf-8") as fh: | |
| for cl in reservoir: | |
| for r in cl: | |
| fh.write(json.dumps(r, ensure_ascii=False) + "\n") | |
| print("\n===== EYEBALL SAMPLES (clusters) =====") | |
| eye = [cl for cl in reservoir if any(r["spans"] or r["hard_negatives"] for r in cl)] | |
| for cl in random.sample(eye, min(a.n_eyeball, len(eye))): | |
| print(f"\n=== {cl[0]['cluster_id']} {cl[0]['cluster_kind']} size={len(cl)}") | |
| for e in cl[0]["entities"] or []: | |
| print(f" ENT {e['entity_id'][-4:]} {e['entity_type']}/{e['value_type']} {e['canonical'][:40]!r} -> {e['replacement_canonical'][:40]!r} owner={e['owner_entity_id'] and e['owner_entity_id'][-4:]} docs={e['n_docs']} mentions={e['n_mentions']}") | |
| for r in cl: | |
| t = r["text"] | |
| print(f"--- doc {r['doc_index']} {r['id']} {r['language']} {r['path']}") | |
| for s in r["spans"] + r["hard_negatives"]: | |
| ls = t.rfind("\n", 0, s["start"]) + 1; le = t.find("\n", s["end"]); le = len(t) if le < 0 else le | |
| eid = s.get("entity_id"); eid = eid[-4:] if eid else "-" | |
| print(f" [{s['label']}/{s['value_type']} {eid}] {t[ls:le][:140]!r}") | |
| if __name__ == "__main__": | |
| main() | |