pii-detector-cjk-small / scripts /prep_openpii.py
CheezOne's picture
Release
858ec3b verified
Raw History Blame Contribute Delete
2.54 kB
"""Extract zh/ja/ko/en examples from ai4privacy/pii-masking-openpii-1.5m (CC-BY-4.0)
into a compact span format: {"text", "spans": [[start, end, label], ...], "lang", "src"}.
Usage: python prep_openpii.py <openpii_dir> <out_dir> [--en-train N] [--seed S]
"""
import argparse, json, os, random
LABELS = ["GIVENNAME", "SURNAME", "TITLE", "DATE", "TIME", "AGE", "SEX", "GENDER",
"EMAIL", "TELEPHONENUM", "CITY", "STREET", "BUILDINGNUM", "ZIPCODE",
"IDCARDNUM", "PASSPORTNUM", "DRIVERLICENSENUM", "TAXNUM", "SOCIALNUM",
"CREDITCARDNUMBER"]
KEEP = {"zh", "ja", "ko", "en"}
def convert(d):
text = d["source_text"]
spans = []
for m in d["privacy_mask"]:
if m["label"] not in LABELS: # drop the long tail of rare labels (<0.1%)
continue
s, e = m["start"], m["end"]
if text[s:e] != m["value"]: # skip misaligned annotations
return None
spans.append([s, e, m["label"]])
return {"text": text, "spans": sorted(spans), "lang": d["language"], "src": "openpii"}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("openpii_dir"); ap.add_argument("out_dir")
ap.add_argument("--en-train", type=int, default=40000)
ap.add_argument("--test-per-lang", type=int, default=1000)
ap.add_argument("--seed", type=int, default=13)
a = ap.parse_args()
rng = random.Random(a.seed)
os.makedirs(a.out_dir, exist_ok=True)
for split, fname in [("train", "train.jsonl"), ("test", "validation.jsonl")]:
by_lang = {l: [] for l in KEEP}
bad = 0
with open(os.path.join(a.openpii_dir, "data", fname)) as f:
for line in f:
d = json.loads(line)
if d["language"] not in KEEP:
continue
r = convert(d)
if r is None:
bad += 1; continue
by_lang[d["language"]].append(r)
out = []
for l, rows in by_lang.items():
rng.shuffle(rows)
if split == "train" and l == "en":
rows = rows[: a.en_train]
if split == "test":
rows = rows[: a.test_per_lang]
out += rows
print(split, l, len(rows))
rng.shuffle(out)
print(split, "misaligned skipped:", bad)
with open(os.path.join(a.out_dir, f"openpii_{split}.jsonl"), "w") as f:
for r in out:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
if __name__ == "__main__":
main()