Token Classification
Transformers
ONNX
Safetensors
Transformers.js
modernbert
pii
pii-detection
ner
privacy
anonymization
redaction
de-identification
chinese
japanese
korean
cjk
mmbert
个人信息
脱敏
Eval Results (legacy)
Instructions to use CheezOne/pii-detector-cjk-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use CheezOne/pii-detector-cjk-small with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="CheezOne/pii-detector-cjk-small")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("CheezOne/pii-detector-cjk-small") model = AutoModelForTokenClassification.from_pretrained("CheezOne/pii-detector-cjk-small", device_map="auto") - Transformers.js
How to use CheezOne/pii-detector-cjk-small with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('token-classification', 'CheezOne/pii-detector-cjk-small'); - Notebooks
- Google Colab
- Kaggle
File size: 14,005 Bytes
858ec3b f9e841d 858ec3b f9e841d 858ec3b f9e841d 858ec3b f9e841d 858ec3b 3ad0089 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 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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | """Render the Hugging Face model card (README.md) from evaluation artifacts.
Usage: python make_card.py <model_dir> <repo_id> [--baselines eval/baseline_*.json]
Reads <model_dir>/eval_full.json, <model_dir>/onnx_report.json and baseline JSONs.
"""
import argparse, glob, json, os
LANG_NAMES = {"zh": "Chinese 中文", "ja": "Japanese 日本語", "ko": "Korean 한국어", "en": "English"}
LABEL_DESC = {
"GIVENNAME": "given name / 名", "SURNAME": "surname / 姓", "TITLE": "title, honorific (先生, 様, Mr.)",
"DATE": "date", "TIME": "time", "AGE": "age", "SEX": "sex", "GENDER": "gender identity",
"EMAIL": "email", "TELEPHONENUM": "phone number", "CITY": "city / district", "STREET": "street",
"BUILDINGNUM": "building / house / room number", "ZIPCODE": "postal code",
"IDCARDNUM": "national ID (e.g. 身份证)", "PASSPORTNUM": "passport no.", "DRIVERLICENSENUM": "driver licence no.",
"TAXNUM": "tax ID / 统一社会信用代码", "SOCIALNUM": "social security no.", "CREDITCARDNUMBER": "bank / credit card no.",
}
def pct(x):
return f"{100 * x:.1f}"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("model_dir"); ap.add_argument("repo_id")
ap.add_argument("--baselines", nargs="*", default=[])
a = ap.parse_args()
ev = json.load(open(os.path.join(a.model_dir, "eval_full.json")))
onnx = json.load(open(os.path.join(a.model_dir, "onnx_report.json"))) if os.path.exists(os.path.join(a.model_dir, "onnx_report.json")) else None
op, zr = ev["openpii_test.jsonl"], ev["zh_real_test.jsonl"]
lang_rows = "\n".join(
f"| {LANG_NAMES.get(l, l)} | openpii (synthetic, mixed formats) | {pct(r['precision'])} | {pct(r['recall'])} | **{pct(r['f1'])}** | {pct(r['redact_recall'])} | {r['support']} |"
for l, r in op["by_lang"].items())
z = zr["overall"]
lang_rows += f"\n| Chinese 中文 | **realistic mainland formats, held-out templates** | {pct(z['precision'])} | {pct(z['recall'])} | **{pct(z['f1'])}** | {pct(z['redact_recall'])} | {z['support']} |"
label_rows = "\n".join(
f"| `{lab}` | {LABEL_DESC.get(lab, '')} | {pct(r['f1'])} | {pct(zr['by_label'][lab]['f1']) if lab in zr['by_label'] else '–'} |"
for lab, r in op["by_label"].items())
base_rows = ""
for path in a.baselines:
b = json.load(open(path)); name = b["model"]
if name.startswith("runs/"):
continue
zz, oo = b.get("zh_real_test.jsonl", {}), b.get("openpii_test.jsonl", {})
cell = lambda d, k: pct(d[k]) if d and k in d else "–"
base_rows += (f"| [{name}](https://huggingface.co/{name}) | {cell(zz.get('all'), 'redact_recall')} | {cell(zz.get('all'), 'redact_precision')} | "
f"{cell(oo.get('zh'), 'redact_recall')} | {cell(oo.get('ja'), 'redact_recall')} | {cell(oo.get('ko'), 'redact_recall')} | {cell(oo.get('en'), 'redact_recall')} |\n")
ours = next((json.load(open(p)) for p in a.baselines if json.load(open(p))["model"].startswith("runs/")), None)
if ours:
zz, oo = ours["zh_real_test.jsonl"], ours["openpii_test.jsonl"]
base_rows = (f"| **{a.repo_id} (this model, ~140M)** | **{pct(zz['all']['redact_recall'])}** | **{pct(zz['all']['redact_precision'])}** | "
f"**{pct(oo['zh']['redact_recall'])}** | **{pct(oo['ja']['redact_recall'])}** | **{pct(oo['ko']['redact_recall'])}** | **{pct(oo['en']['redact_recall'])}** |\n") + base_rows
onnx_txt = ""
if onnx:
k32 = next((k for k in onnx if k.startswith("fp32:")), None); k8 = next((k for k in onnx if k.startswith("int8:")), None)
onnx_txt = f"""
| File | Size | F1 (zh-realistic subset) | Redaction recall | CPU latency (bs=1, 4 vCPU) |
|---|---|---|---|---|
| `onnx/model.onnx` (fp32) | {onnx['size_mb']['fp32']:.0f} MB | {pct(onnx[k32]['f1'])} | {pct(onnx[k32]['redact_recall'])} | {onnx[k32]['ms_per_example_bs1']:.0f} ms |
| `onnx/model_quantized.onnx` (int8 emb+attention) | {onnx['size_mb']['int8']:.0f} MB | {pct(onnx[k8]['f1'])} | {pct(onnx[k8]['redact_recall'])} | {onnx[k8]['ms_per_example_bs1']:.0f} ms |
"""
card = f"""---
license: apache-2.0
language: [zh, ja, ko, en]
library_name: transformers
pipeline_tag: token-classification
base_model: jhu-clsp/mmBERT-small
datasets: [ai4privacy/pii-masking-openpii-1.5m]
tags: [pii, pii-detection, ner, privacy, anonymization, redaction, de-identification, chinese, japanese, korean, cjk, onnx, transformers.js, modernbert, mmbert, 个人信息, 脱敏]
metrics: [f1, precision, recall]
model-index:
- name: {a.repo_id.split('/')[-1]}
results:
- task: {{type: token-classification, name: PII detection}}
dataset: {{name: openpii-1.5m validation (zh/ja/ko/en, 4k ex), type: ai4privacy/pii-masking-openpii-1.5m}}
metrics:
- {{type: f1, value: {op['overall']['f1']:.4f}, name: entity F1 (exact span)}}
- task: {{type: token-classification, name: PII detection}}
dataset: {{name: realistic Chinese PII (held-out templates), type: custom}}
metrics:
- {{type: f1, value: {z['f1']:.4f}, name: entity F1 (exact span)}}
---
# PII detector for Chinese, Japanese, Korean & English (small)
**A small (≈140M params), Apache-2.0 model that finds and labels personal data in 中文 / 日本語 / 한국어 / English text** —
names, phone numbers, national ID numbers (身份证), bank cards, emails, addresses, dates and 20 entity types in total.
Fast enough for CPU, ships ONNX (fp32 + int8) for Optimum / ONNX Runtime / **transformers.js** (browser, Node).
**开源小模型:检测并脱敏中、日、韩、英文本中的个人信息**(姓名、手机号、身份证号、银行卡号、邮箱、地址、日期等 20 类)。
约 1.4 亿参数,CPU 即可运行,提供 ONNX(可在浏览器中运行)。适用于大模型数据清洗、日志脱敏、客服对话脱敏、《个人信息保护法》(PIPL) 合规等场景。
👉 **Try it (runs 100% in your browser, text never leaves the page):** [live demo](https://huggingface.co/spaces/{a.repo_id.split('/')[0]}/pii-detector-demo)
## Why this model
- **CJK-first.** Most open PII models are English/European. Existing Chinese PII models are 278M–600M params; this one is ~140M with a tokenizer that splits Chinese finely, so `张伟` → `张` SURNAME + `伟` GIVENNAME works.
- **Real Chinese formats.** Public multilingual PII data uses foreign-style identifiers even in Chinese text. We add a [reproducible generator](scripts/gen_zh_realistic.py) of mainland-format PII (18-digit 身份证 with valid checksum, `1[3-9]` mobiles, landlines, UnionPay cards with Luhn checksum, 统一社会信用代码, 省/市/区/路/号 addresses, 护照号) and evaluate on **held-out sentence templates**.
- **Permissive.** Apache-2.0 weights; trained only on CC-BY-4.0 and self-generated synthetic data (no real personal data).
## Quick start
```python
from transformers import pipeline
pii = pipeline("token-classification", model="{a.repo_id}", aggregation_strategy="simple")
text = "收件人:王小明,手机:13812345678,地址:上海市浦东新区世纪大道100号,身份证号110101199003071234。"
for e in pii(text):
print(e["entity_group"], text[e["start"]:e["end"]], round(e["score"], 3))
```
Redact:
```python
def redact(text, min_score=0.5):
out, last = [], 0
for e in sorted(pii(text), key=lambda e: e["start"]):
if e["score"] < min_score: continue
out += [text[last:e["start"]], f"[{{e['entity_group']}}]"]; last = e["end"]
return "".join(out + [text[last:]])
print(redact("您好,李女士,您的银行卡6222021234567890128已绑定。"))
# 您好,[SURNAME][TITLE],您的银行卡[CREDITCARDNUMBER]已绑定。
```
ONNX Runtime via Optimum:
```python
from optimum.onnxruntime import ORTModelForTokenClassification
from transformers import AutoTokenizer, pipeline
model = ORTModelForTokenClassification.from_pretrained("{a.repo_id}", subfolder="onnx", file_name="model_quantized.onnx")
pii = pipeline("token-classification", model=model, tokenizer=AutoTokenizer.from_pretrained("{a.repo_id}"), aggregation_strategy="simple")
```
transformers.js (browser / Node, int8 ONNX, ~230 MB download, cached):
```js
import {{ pipeline }} from "@huggingface/transformers";
const pii = await pipeline("token-classification", "{a.repo_id}", {{ dtype: "q8" }});
console.log(await pii("山田太郎様の電話番号は090-1234-5678です。")); // per-token BIO labels
```
transformers.js' pipeline returns per-token labels without character offsets. For entity spans and redaction, use
[`pii.js`](https://huggingface.co/spaces/{a.repo_id.split('/')[0]}/pii-detector-demo/blob/main/pii.js) from the demo Space
(~70 lines: token→char alignment, BIO grouping, email regex backstop, `redact()`).
## Labels (BIO, 20 entity types)
| Label | Meaning | F1 openpii | F1 zh-realistic |
|---|---|---|---|
{label_rows}
## Evaluation
**Entity F1** = exact character-span + label match. **Redaction recall** = share of PII characters that get masked by *any* label (what matters when you just want PII removed).
| Language | Test set | Precision | Recall | F1 | Redaction recall | Entities |
|---|---|---|---|---|---|---|
{lang_rows}
### Comparison with other open PII models (label-agnostic)
Same test sets, each model run through the stock `pipeline(..., aggregation_strategy="simple")`; character-level redaction recall/precision so different label sets are comparable ([script](scripts/bench_redaction.py)). Numbers are % (higher is better).
| Model | zh-realistic recall | zh-realistic precision | openpii zh recall | ja recall | ko recall | en recall |
|---|---|---|---|---|---|---|
{base_rows}
Caveat: the openpii test split comes from the same distribution as our training data, which favours this model; the zh-realistic set uses templates never seen in training but was written by us. Please evaluate on your own data.
### ONNX
{onnx_txt}
int8 recipe: per-channel dynamic quantization of embeddings + attention only; MLPs and head stay fp32 (full int8 cost ~8 F1 points on this architecture — see `scripts/quant_sweep.py`).
## Training
- Base: [`jhu-clsp/mmBERT-small`](https://huggingface.co/jhu-clsp/mmBERT-small) (ModernBERT architecture, 1800+ languages). Chosen because its tokenizer splits Chinese finely: only 0.01% of entity boundaries fall inside a token on realistic Chinese text, vs 6.2% for multilingual-e5-small.
- Data (142,941 examples): [ai4privacy/pii-masking-openpii-1.5m](https://huggingface.co/datasets/ai4privacy/pii-masking-openpii-1.5m) zh 20,962 / ja 20,754 / ko 21,225 / en 40,000 (subsample), plus 40,000 generated realistic-Chinese examples (`gen_zh_realistic.py --seed 2 --templates train_v11`).
- 1 epoch, batch 32, lr 8e-5 linear decay (6% warmup), max length 256, embeddings frozen, bf16 autocast, on a 64-core CPU runner (~1 h). No GPU was used.
### What mattered: context diversity in the Chinese data (v1 → v1.1)
| Version | Chinese synthetic data | openpii F1 | zh-realistic (held-out templates) F1 | zh redaction recall |
|---|---|---|---|---|
| v1 | 20k, 11 fixed templates | 0.963 | 0.747 | 94.9% |
| **v1.1 (this release)** | 40k, + randomized key-value forms (varied field names/order/separators) and mixed-ID narratives | 0.961 | **0.978** | **99.6%** |
With few templates the model overfit openpii's foreign-style identifier conventions and fragmented 18-digit 身份证 numbers (mmBERT tokenizes digits one by one) into ID/tax/card pieces. Varying the contexts fixed this.
Full reproduction:
```bash
python scripts/prep_openpii.py <openpii_dir> data/prepared
python scripts/gen_zh_realistic.py data/prepared/zh_real_train_v11.jsonl --n 40000 --seed 2 --templates train_v11
python scripts/gen_zh_realistic.py data/prepared/zh_real_test.jsonl --n 1000 --seed 999 --templates heldout
python scripts/train.py --base jhu-clsp/mmBERT-small --train data/prepared/openpii_train.jsonl data/prepared/zh_real_train_v11.jsonl \
--eval data/prepared/openpii_test.jsonl data/prepared/zh_real_test.jsonl --out runs/v11 --epochs 1 --bs 32 --lr 8e-5 --freeze-emb
python scripts/export_onnx.py runs/v11 --test data/prepared/zh_real_test.jsonl
python scripts/bench_redaction.py runs/v11 data/prepared/zh_real_test.jsonl data/prepared/openpii_test.jsonl
```
## Limitations
- Trained on **synthetic** text. Real documents (OCR output, chat slang, mixed scripts) will be harder; always measure on your own data and keep a human in the loop for compliance-critical use.
- Not covered: organisation names, IP/URLs, usernames/passwords, bank account names, medical data. Combine with regexes for strictly formatted IDs if you need guaranteed recall.
- `SEX` vs `GENDER` and `SOCIALNUM` vs `IDCARDNUM` are often confused (they look alike); merge them if your use case allows.
- Japanese and Korean identifiers follow openpii's synthetic formats; realistic-format generators for ja/ko are planned.
- Max 512 tokens per call (split long documents).
- With `aggregation_strategy="simple"`, English/Korean entities may include a leading space (strip `text[start:end]`); emails with unusual TLDs are occasionally cut short.
## License & attribution
Model: Apache-2.0. Training data includes **OpenPII 1.5M by Ai4Privacy / Ai Suisse SA (CC-BY-4.0)** — https://huggingface.co/datasets/ai4privacy/pii-masking-openpii-1.5m. Base model mmBERT-small (MIT).
## Citation
```bibtex
@misc{{cheezone_pii_cjk_2026,
title = {{PII detector for Chinese, Japanese, Korean and English (small)}},
author = {{CheezOne}},
year = {{2026}},
url = {{https://huggingface.co/{a.repo_id}}}
}}
```
"""
extra = "eval/card_extra.md" # 30-language benchmark + examples (scripts/card_extra.py)
if os.path.exists(extra):
card = card.replace("## Training\n", open(extra).read() + "\n## Training\n", 1)
open(os.path.join(a.model_dir, "README.md"), "w").write(card)
print("wrote", os.path.join(a.model_dir, "README.md"))
if __name__ == "__main__":
main()
|