Download veil_ner.py from dekka-cloud/veil-ner-deep: direct link, hf CLI and curl.
- Browser
- Download file 5.41 kB
-
https://huggingface.co/dekka-cloud/veil-ner-deep/resolve/main/veil_ner.py
- Command line
-
hf download hf://dekka-cloud/veil-ner-deep/veil_ner.py
-
curl -L -o veil_ner.py https://huggingface.co/dekka-cloud/veil-ner-deep/resolve/main/veil_ner.py
5.41 kB
| """Find Ghanaian personal information in text with a Veil model, on the CPU, with nothing else running. | |
| pip install onnxruntime tokenizers numpy pyyaml huggingface_hub | |
| python veil_ner.py "Me din de Akosua Mensah, patient PT-204118" | |
| Works for veil-ner-nano and veil-ner-deep alike. It reads the model's manifest.yaml for the labels, | |
| the tokenizer window and the confidence threshold, and decodes the model's output the way Dekka | |
| Veil does: text longer than one window is read in overlapping windows, each token keeps the label | |
| from the window where it sits furthest from an edge, BIO tags become spans, and a span whose mean | |
| confidence is below the threshold is dropped. Offsets are character offsets into the text. | |
| """ | |
| from __future__ import annotations | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import onnxruntime as ort | |
| import yaml | |
| from tokenizers import Tokenizer | |
| TRAIL = ".,;:!?\"'" | |
| class VeilNER: | |
| def __init__(self, model_dir: str | Path, threads: int = 1) -> None: | |
| d = Path(model_dir) | |
| manifest = yaml.safe_load((d / "manifest.yaml").read_text()) | |
| self.labels: list[str] = manifest["labels"] | |
| self.threshold = float(manifest["threshold"]) | |
| tok = manifest["tokenizer"] | |
| self.tokenizer = Tokenizer.from_file(str(d / tok["file"])) | |
| self.tokenizer.enable_truncation(max_length=int(tok["max_length"]), stride=int(tok["stride"])) | |
| self.tokenizer.no_padding() | |
| opts = ort.SessionOptions() | |
| opts.intra_op_num_threads = threads | |
| opts.inter_op_num_threads = 1 | |
| self.session = ort.InferenceSession(str(d / manifest["model"]["file"]), sess_options=opts, providers=["CPUExecutionProvider"]) | |
| self.inputs = {i.name for i in self.session.get_inputs()} | |
| def __call__(self, text: str) -> list[dict]: | |
| first = self.tokenizer.encode(text) | |
| best: dict[int, tuple[int, float, int, tuple[int, int]]] = {} | |
| for window in [first, *first.overflowing]: | |
| ids = np.array([window.ids], dtype=np.int64) | |
| mask = np.array([window.attention_mask], dtype=np.int64) | |
| feed = {k: v for k, v in {"input_ids": ids, "attention_mask": mask}.items() if k in self.inputs} | |
| logits = self.session.run(["logits"], feed)[0][0] | |
| z = logits - logits.max(axis=-1, keepdims=True) | |
| probs = np.exp(z) / np.exp(z).sum(axis=-1, keepdims=True) | |
| tags, conf = probs.argmax(-1), probs.max(-1) | |
| n = len(window.ids) | |
| for t, (start, end) in enumerate(window.offsets): | |
| if start == end: | |
| continue | |
| margin = min(t, n - 1 - t) | |
| prev = best.get(start) | |
| if prev is None or margin > prev[2]: | |
| best[start] = (int(tags[t]), float(conf[t]), margin, (start, end)) | |
| tokens = [best[k] for k in sorted(best)] | |
| spans = _decode(text, [t[3] for t in tokens], [t[0] for t in tokens], [t[1] for t in tokens], self.labels) | |
| return [ | |
| {"label": label, "start": s, "end": e, "text": text[s:e], "score": round(p, 4)} | |
| for label, s, e, p in spans | |
| if p >= self.threshold | |
| ] | |
| def _core(text: str, start: int, end: int) -> tuple[int, int]: | |
| while start < end and text[start].isspace(): | |
| start += 1 | |
| while end > start and text[end - 1].isspace(): | |
| end -= 1 | |
| return start, end | |
| def _trim(text: str, start: int, end: int) -> tuple[int, int]: | |
| while end > start: | |
| span = text[start:end] | |
| c = text[end - 1] | |
| if c in TRAIL or (c == ")" and span.count(")") > span.count("(")): | |
| end -= 1 | |
| continue | |
| c = text[start] | |
| if c in "\"'" or (c == "(" and span.count("(") > span.count(")")): | |
| start += 1 | |
| continue | |
| break | |
| return start, end | |
| def _decode(text: str, offsets: list[tuple[int, int]], tag_ids: list[int], probs: list[float], labels: list[str]) -> list[tuple[str, int, int, float]]: | |
| raw: list[tuple[str, int, int, float]] = [] | |
| cur: list | None = None | |
| for (start, end), t, p in zip(offsets, tag_ids, probs): | |
| tag = labels[t] | |
| s, e = _core(text, start, end) | |
| if s >= e: | |
| continue | |
| if tag == "O": | |
| if cur: | |
| raw.append((cur[0], cur[1], cur[2], float(np.mean(cur[3])))) | |
| cur = None | |
| continue | |
| prefix, label = tag.split("-", 1) | |
| if cur and label == cur[0] and prefix == "I": | |
| cur[2] = e | |
| cur[3].append(p) | |
| else: | |
| if cur: | |
| raw.append((cur[0], cur[1], cur[2], float(np.mean(cur[3])))) | |
| cur = [label, s, e, [p]] | |
| if cur: | |
| raw.append((cur[0], cur[1], cur[2], float(np.mean(cur[3])))) | |
| out = [] | |
| for label, s, e, p in raw: | |
| s, e = _trim(text, s, e) | |
| if s < e: | |
| out.append((label, s, e, p)) | |
| return out | |
| if __name__ == "__main__": | |
| from huggingface_hub import snapshot_download | |
| repo = "dekka-cloud/veil-ner-nano" | |
| args = sys.argv[1:] | |
| if args[:1] == ["--model"]: | |
| repo, args = args[1], args[2:] | |
| model = VeilNER(repo if Path(repo).is_dir() else snapshot_download(repo)) | |
| for span in model(" ".join(args) or "Me din de Akosua Mensah, patient PT-204118"): | |
| print(f"{span['label']:<22} {span['text']!r} {span['score']}") | |