File size: 2,537 Bytes
858ec3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()