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
Download scripts/common.py from CheezOne/pii-detector-cjk-small: direct link, hf CLI and curl.
- Browser
- Download file 5.79 kB
-
https://huggingface.co/CheezOne/pii-detector-cjk-small/resolve/main/scripts/common.py
- Command line
-
hf download hf://CheezOne/pii-detector-cjk-small/scripts/common.py
-
curl -L -o common.py https://huggingface.co/CheezOne/pii-detector-cjk-small/resolve/main/scripts/common.py
5.79 kB
| """Shared label schema, span<->token alignment and evaluation for the PII tagger.""" | |
| import json | |
| from collections import Counter, defaultdict | |
| ENTITY_LABELS = ["GIVENNAME", "SURNAME", "TITLE", "DATE", "TIME", "AGE", "SEX", "GENDER", | |
| "EMAIL", "TELEPHONENUM", "CITY", "STREET", "BUILDINGNUM", "ZIPCODE", | |
| "IDCARDNUM", "PASSPORTNUM", "DRIVERLICENSENUM", "TAXNUM", "SOCIALNUM", | |
| "CREDITCARDNUMBER"] | |
| BIO = ["O"] + [f"{p}-{l}" for l in ENTITY_LABELS for p in ("B", "I")] | |
| L2I = {l: i for i, l in enumerate(BIO)} | |
| def read_jsonl(path, limit=None): | |
| out = [] | |
| with open(path) as f: | |
| for i, line in enumerate(f): | |
| if limit and i >= limit: | |
| break | |
| out.append(json.loads(line)) | |
| return out | |
| def trim(text, s, e): | |
| """Trim whitespace from a char span (tokenizers often include a leading space).""" | |
| while s < e and text[s].isspace(): | |
| s += 1 | |
| while e > s and text[e - 1].isspace(): | |
| e -= 1 | |
| return s, e | |
| def clean_offsets(text, offsets, special_mask): | |
| """Per token: (raw_start, s, e) with whitespace trimmed and overlapping prefix tokens | |
| (e.g. a Metaspace '▁' at (0,1) followed by a token also starting at 0) made empty. | |
| Special tokens -> None.""" | |
| out = [] | |
| for i, ((s, e), sp) in enumerate(zip(offsets, special_mask)): | |
| if sp: | |
| out.append(None); continue | |
| raw = s | |
| nxt = next((offsets[j] for j in range(i + 1, len(offsets)) if not special_mask[j]), None) | |
| if nxt is not None and nxt[0] < e and nxt[0] <= s: | |
| e = s # overlapping prefix token -> empty | |
| s, e = trim(text, s, e) | |
| out.append((raw, s, e)) | |
| return out | |
| def token_labels(text, spans, offsets, special_mask): | |
| """Assign BIO ids to tokens from char spans. First content token of a span gets B-, | |
| later ones I-. Whitespace tokens strictly inside the current span get I- (so HF | |
| pipeline aggregation keeps '138 3648 5027' together); otherwise O.""" | |
| labels, prev = [], None | |
| spans = sorted(spans) | |
| for tokinfo in clean_offsets(text, offsets, special_mask): | |
| if tokinfo is None: | |
| labels.append(-100); continue | |
| raw, s, e = tokinfo | |
| if e <= s: # whitespace / empty token | |
| if prev is not None and prev[0] < raw < prev[1]: | |
| labels.append(L2I[f"I-{prev[2]}"]) | |
| else: | |
| labels.append(L2I["O"]); prev = None | |
| continue | |
| hit = next(((ss, se, lab) for ss, se, lab in spans if s < se and e > ss), None) | |
| if hit is None: | |
| labels.append(L2I["O"]); prev = None | |
| else: | |
| labels.append(L2I[("I-" if prev == hit else "B-") + hit[2]]); prev = hit | |
| return labels | |
| def decode_spans(text, offsets, pred_ids, special_mask): | |
| """BIO token predictions -> char spans [(s, e, label)]. An I- that does not continue | |
| the current entity starts a new one (lenient).""" | |
| spans, cur = [], None | |
| for tokinfo, p in zip(clean_offsets(text, offsets, special_mask), pred_ids): | |
| if tokinfo is None: | |
| continue | |
| raw, s, e = tokinfo | |
| tag = BIO[p] | |
| if e <= s: # whitespace: only an explicit O closes the entity | |
| if tag == "O" and cur: | |
| spans.append(cur); cur = None | |
| continue | |
| if tag == "O": | |
| if cur: spans.append(cur); cur = None | |
| continue | |
| bi, lab = tag.split("-", 1) | |
| if cur and lab == cur[2] and bi == "I": | |
| cur = (cur[0], e, lab) | |
| else: | |
| if cur: spans.append(cur) | |
| cur = (s, e, lab) | |
| if cur: | |
| spans.append(cur) | |
| return spans | |
| def evaluate(examples, preds): | |
| """examples: list of {text, spans, lang}; preds: list of predicted span lists. | |
| Returns exact-match entity P/R/F1 (overall, per lang, per label) and char-level redaction P/R.""" | |
| res = {"by_lang": {}, "by_label": {}} | |
| tp = Counter(); fp = Counter(); fn = Counter() | |
| ltp = Counter(); lfp = Counter(); lfn = Counter() | |
| ch = defaultdict(Counter) | |
| for ex, pr in zip(examples, preds): | |
| text, lang = ex["text"], ex.get("lang", "?") | |
| gold = {(*trim(text, s, e), l) for s, e, l in ex["spans"]} | |
| pred = {(*trim(text, s, e), l) for s, e, l in pr} | |
| for g in gold: | |
| (tp if g in pred else fn)[lang] += 1; (ltp if g in pred else lfn)[g[2]] += 1 | |
| for p in pred - gold: | |
| fp[lang] += 1; lfp[p[2]] += 1 | |
| gchars = {i for s, e, _ in gold for i in range(s, e) if not text[i].isspace()} | |
| pchars = {i for s, e, _ in pred for i in range(s, e) if not text[i].isspace()} | |
| ch[lang]["tp"] += len(gchars & pchars); ch[lang]["fp"] += len(pchars - gchars); ch[lang]["fn"] += len(gchars - pchars) | |
| def prf(t, p_, n): | |
| P = t / (t + p_) if t + p_ else 0.0; R = t / (t + n) if t + n else 0.0 | |
| return {"precision": round(P, 4), "recall": round(R, 4), "f1": round(2 * P * R / (P + R), 4) if P + R else 0.0, "support": t + n} | |
| for lang in sorted(set(tp) | set(fn) | set(fp)): | |
| r = prf(tp[lang], fp[lang], fn[lang]) | |
| c = ch[lang]; r["redact_precision"] = round(c["tp"] / max(1, c["tp"] + c["fp"]), 4); r["redact_recall"] = round(c["tp"] / max(1, c["tp"] + c["fn"]), 4) | |
| res["by_lang"][lang] = r | |
| for lab in ENTITY_LABELS: | |
| if ltp[lab] + lfn[lab] + lfp[lab]: | |
| res["by_label"][lab] = prf(ltp[lab], lfp[lab], lfn[lab]) | |
| res["overall"] = prf(sum(tp.values()), sum(fp.values()), sum(fn.values())) | |
| C = Counter() | |
| for c in ch.values(): C.update(c) | |
| res["overall"]["redact_precision"] = round(C["tp"] / max(1, C["tp"] + C["fp"]), 4) | |
| res["overall"]["redact_recall"] = round(C["tp"] / max(1, C["tp"] + C["fn"]), 4) | |
| return res | |