File size: 4,652 Bytes
2b3f8d7 | 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 | #!/usr/bin/env python3
from pathlib import Path
import argparse
import json
import shutil
def fail(msg):
raise SystemExit(msg)
def import_arrow():
try:
import pyarrow as pa
import pyarrow.parquet as pq
import pyarrow.compute as pc
return pa, pq, pc
except Exception as e:
fail(f"pyarrow is required for safe subset creation: {e}")
def auto_col(cols, candidates):
lower = {c.lower(): c for c in cols}
for cand in candidates:
if cand.lower() in lower:
return lower[cand.lower()]
return None
def is_lfs_pointer(path):
try:
return path.read_bytes()[:120].startswith(b"version https://git-lfs.github.com/spec/v1")
except OSError:
return False
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--root", default=".")
parser.add_argument("--out", default="safe_public_subset")
parser.add_argument("--risk-column", default=None)
parser.add_argument("--id-column", default=None)
parser.add_argument("--exclude-risk-values", default="high", help="Comma-separated risk values to exclude")
parser.add_argument("--overwrite", action="store_true")
args = parser.parse_args()
pa, pq, pc = import_arrow()
root = Path(args.root)
out = Path(args.out)
persona_path = root / "persona_core.parquet"
if not persona_path.exists():
fail("persona_core.parquet not found")
if is_lfs_pointer(persona_path):
fail("persona_core.parquet is a Git LFS pointer. Pull the real Parquet payload before creating a safe subset.")
table = pq.read_table(persona_path)
cols = table.column_names
if out.exists():
if not args.overwrite:
fail(f"Output directory exists: {out}. Use --overwrite to replace it.")
shutil.rmtree(out)
out.mkdir(parents=True)
risk_col = args.risk_column or auto_col(cols, [
"disclosure_risk_level",
"disclosure_risk",
"privacy_risk_level",
"risk_level",
])
if not risk_col:
fail(f"Could not auto-detect disclosure risk column. Columns: {cols}")
id_col = args.id_column or auto_col(cols, [
"synthetic_person_id",
"persona_id",
"person_id",
"synthetic_person_id",
"id",
])
if not id_col:
fail(f"Could not auto-detect persona id column. Columns: {cols}")
exclude_values = [x.strip().lower() for x in args.exclude_risk_values.split(",") if x.strip()]
risk_lower = pc.utf8_lower(table[risk_col].cast(pa.string()))
excluded_mask = pc.is_in(risk_lower, value_set=pa.array(exclude_values))
keep_mask = pc.invert(excluded_mask)
safe_persona = table.filter(keep_mask)
high_persona = table.filter(excluded_mask)
removed_ids = set(high_persona[id_col].to_pylist())
pq.write_table(safe_persona, out / "persona_core_safe.parquet")
report = {
"risk_column": risk_col,
"id_column": id_col,
"exclude_risk_values": exclude_values,
"persona_core_rows_before": table.num_rows,
"persona_core_rows_after": safe_persona.num_rows,
"removed_persona_rows": len(removed_ids),
"artifacts": {
"persona_core": {
"input": "persona_core.parquet",
"output": "persona_core_safe.parquet",
"rows_before": table.num_rows,
"rows_after": safe_persona.num_rows,
}
},
}
for name in ["persona_views", "actor_state_init"]:
p = root / f"{name}.parquet"
if not p.exists():
continue
if is_lfs_pointer(p):
report["artifacts"][name] = {"input": p.name, "skipped": "Git LFS pointer; real Parquet payload not present"}
continue
t = pq.read_table(p)
if id_col not in t.column_names:
report["artifacts"][name] = {"input": p.name, "skipped": f"missing id column {id_col}"}
continue
remove_mask = pc.is_in(t[id_col], value_set=pa.array(list(removed_ids), type=t[id_col].type))
keep = pc.invert(remove_mask)
safe_t = t.filter(keep)
out_name = f"{name}_safe.parquet"
pq.write_table(safe_t, out / out_name)
report["artifacts"][name] = {
"input": p.name,
"output": out_name,
"rows_before": t.num_rows,
"rows_after": safe_t.num_rows,
}
(out / "safe_subset_report.json").write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
print(json.dumps(report, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()
|