"""Side-by-side case study: run several PII models on hand-written sentences and print redactions. The cases are written by hand for this comparison (not produced by gen_zh_realistic.py and not from openpii), covering everyday genres. Each model uses the stock HF pipeline (aggregation_strategy="simple"). Usage: python case_study.py [--cases cases.json] model1 model2 ... """ import json, os, sys import torch from transformers import pipeline CASES = [ ("zh", "微信聊天", "老王,我新换的号码是 15921876543,以后打这个。我身份证是 320102198811052418,帮我订一下周六去杭州的高铁票。"), ("zh", "外卖备注", "放门口就行,电话尾号不用打了,有事打 186-2190-7735,地址:深圳市南山区科技园科苑路15号讯美科技广场3栋1201,找张晓雯。"), ("zh", "HR邮件", "陈总您好,新同事刘一鸣(男,29岁)将于2026年12月1日入职,工资卡为招商银行 6225 8812 3456 7890,邮箱 liuyiming@foxmail.com。"), ("zh", "医院", "患者赵淑芬,女,67岁,住北京市朝阳区望京西路48号,社保卡号 1234567890,家属联系电话 010-64723311。"), ("zh", "法律文书", "原告孙建国,男,1972年3月8日出生,汉族,住成都市武侯区人民南路四段27号,公民身份号码510107197203081234。"), ("zh", "电商客服", "亲,收货人欧阳娜娜的手机号是13700001111吗?您填写的地址是广州市天河区天河路385号太古汇,邮编510620。"), ("zh", "无个人信息", "本季度公司营收达到 3.2 亿元,同比增长 18%,北京和上海两地门店数量共计 126 家。"), ("ja", "予約確認", "佐藤花子様、12月24日19時のご予約を承りました。ご連絡は 080-3456-7890 までお願いいたします。"), ("ja", "住所変更", "鈴木一郎、〒150-0001 東京都渋谷区神宮前1-2-3、メール ichiro.suzuki@gmail.com に変更しました。"), ("ko", "배송", "박지훈 님, 부산광역시 해운대구 센텀중앙로 79 에 내일 도착 예정입니다. 문의: 010-9876-5432"), ("ko", "회원가입", "이름: 최수연, 생년월일: 1995년 7월 14일, 이메일: sooyeon.choi@naver.com"), ("en", "support", "Hi, this is Maria Gonzalez. My card 4532 0151 1283 0366 was charged twice; call me at (415) 555-0198."), ("en", "HR", "Employee: David Chen, DOB 04/17/1988, SSN 123-45-6789, lives at 742 Evergreen Terrace, Springfield."), ] def redact(text, ents): out, last = [], 0 for e in sorted(ents, key=lambda e: e["start"]): s, t = e["start"], e["end"] while s < t and text[s].isspace(): s += 1 if s < last: continue out += [text[last:s], f"[{e['entity_group']}]"]; last = t return "".join(out + [text[last:]]) def main(): global CASES args = sys.argv[1:] if args[0] == "--cases": CASES = [tuple(c) for c in json.load(open(args[1]))]; args = args[2:] out_path, models = args[0], args[1:] torch.set_num_threads(os.cpu_count()) res = {"cases": [{"lang": l, "genre": g, "text": t} for l, g, t in CASES], "models": {}} for m in models: nlp = pipeline("token-classification", model=m, aggregation_strategy="simple") res["models"][m] = [] for _, _, t in CASES: ents = [e for e in nlp(t) if e["score"] >= 0.5] res["models"][m].append({"redacted": redact(t, ents), "entities": [[t[e["start"]:e["end"]].strip(), e["entity_group"], round(float(e["score"]), 3)] for e in ents]}) print("done", m, flush=True) json.dump(res, open(out_path, "w"), ensure_ascii=False, indent=1) for i, (l, g, t) in enumerate(CASES): print(f"\n### {i+1}. [{l}] {g}\n原文: {t}") for m in models: print(f" {m.split('/')[-1][:28]:28s} {res['models'][m][i]['redacted']}") if __name__ == "__main__": main()