Publish verified dalil-span-ner-onnx BIO dalil span extractor (INT8 ONNX + FP16 Safetensors)
5b6e93d verified Download inference_example.py from ridloabelian/dalil-span-ner-onnx: direct link, hf CLI and curl.
- Browser
- Download file 6.22 kB
-
https://huggingface.co/ridloabelian/dalil-span-ner-onnx/resolve/main/inference_example.py
- Command line
-
hf download hf://ridloabelian/dalil-span-ner-onnx/inference_example.py
-
curl -L -o inference_example.py https://huggingface.co/ridloabelian/dalil-span-ner-onnx/resolve/main/inference_example.py
6.22 kB
| #!/usr/bin/env python3 | |
| """Minimal zero-PyTorch ONNX Runtime inference example for | |
| `ridloabelian/dalil-span-ner-onnx` (`dalil-span-ner-v1`). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import onnxruntime as ort | |
| import sentencepiece as spm | |
| BIO_LABELS = ( | |
| "O", | |
| "B-QURAN_REF", | |
| "I-QURAN_REF", | |
| "B-QURAN_QUOTE", | |
| "I-QURAN_QUOTE", | |
| "B-HADITH_REF", | |
| "I-HADITH_REF", | |
| "B-HADITH_QUOTE", | |
| "I-HADITH_QUOTE", | |
| "B-FIQH_REF", | |
| "I-FIQH_REF", | |
| ) | |
| _AR_STRIP = frozenset( | |
| [chr(cp) for cp in range(0x0610, 0x061B)] | |
| + [chr(cp) for cp in range(0x064B, 0x0660)] | |
| + [chr(cp) for cp in range(0x06D6, 0x06EE)] | |
| + ["\u0640", "\u0670", "\u06E5", "\u06E6"] | |
| ) | |
| def encode_with_offsets(sp: spm.SentencePieceProcessor, raw_text: str, max_length: int = 256): | |
| norm_chars, orig_spans = [], [] | |
| for idx, ch in enumerate(raw_text): | |
| if ch in _AR_STRIP: | |
| if orig_spans: | |
| orig_spans[-1] = (orig_spans[-1][0], idx + 1) | |
| continue | |
| norm_chars.append("ا" if ch == "ٱ" else ch) | |
| orig_spans.append((idx, idx + 1)) | |
| norm_text = "".join(norm_chars) | |
| byte_to_char = {} | |
| bpos = 0 | |
| for ci, ch in enumerate(norm_text): | |
| byte_to_char[bpos] = ci | |
| bpos += len(ch.encode("utf-8")) | |
| byte_to_char[bpos] = len(norm_text) | |
| proto = sp.encode(norm_text, return_type="proto") | |
| ids, offsets = [0], [(0, 0)] | |
| for piece in proto.pieces[: max_length - 2]: | |
| sp_id = int(piece.id) | |
| ids.append(3 if sp_id == 0 else (0 if sp_id == 1 else (2 if sp_id == 2 else sp_id + 1))) | |
| c0 = byte_to_char.get(int(piece.begin), -1) | |
| c1 = byte_to_char.get(int(piece.end), -1) | |
| if c0 < 0 or c1 <= c0 or c1 > len(orig_spans): | |
| offsets.append((0, 0)) | |
| continue | |
| c0_orig = c0 | |
| while c0 < c1 and norm_text[c0].isspace(): | |
| c0 += 1 | |
| use_c0 = c0 if c0 < c1 else c0_orig | |
| offsets.append((orig_spans[use_c0][0], orig_spans[c1 - 1][1])) | |
| ids.append(2) | |
| offsets.append((0, 0)) | |
| return ids, offsets | |
| def decode_spans(raw_text: str, offsets: list[tuple[int, int]], logits: np.ndarray): | |
| arr = logits - np.max(logits, axis=-1, keepdims=True) | |
| probs = np.exp(arr) / np.sum(np.exp(arr), axis=-1, keepdims=True) | |
| preds = np.argmax(probs, axis=-1) | |
| confs = np.max(probs, axis=-1) | |
| spans, cur, s0, s1, scores = [], None, 0, 0, [] | |
| def flush(): | |
| nonlocal cur, s0, s1, scores | |
| if cur is None: | |
| return | |
| base = " \t\r\n\u200e\u200f\ufeff" | |
| lead = base + ("«»﴿﴾\"'“”\u06d6\u06d7\u06d8\u06d9\u06da\u06db\u06dc\u06dd\u06de" if cur.endswith("_QUOTE") else ",;:") | |
| trail = base + ("«»﴿﴾\"'“”\u06d6\u06d7\u06d8\u06d9\u06da\u06db\u06dc\u06dd\u06de" if cur.endswith("_QUOTE") else ".,;:") | |
| while s0 < s1 and raw_text[s0] in lead: | |
| s0 += 1 | |
| while s1 > s0 and raw_text[s1 - 1] in trail: | |
| s1 -= 1 | |
| if cur.endswith("_REF"): | |
| while s1 > s0 and raw_text[s1 - 1] == ")" and raw_text[s0:s1].count(")") > raw_text[s0:s1].count("("): | |
| s1 -= 1 | |
| while s0 < s1 and raw_text[s0] == "(" and raw_text[s0:s1].count("(") > raw_text[s0:s1].count(")"): | |
| s0 += 1 | |
| if s1 > s0: | |
| spans.append({"label": cur, "start": s0, "end": s1, "text": raw_text[s0:s1], "score": round(float(sum(scores) / len(scores)), 4)}) | |
| cur, scores = None, [] | |
| for i, (t0, t1) in enumerate(offsets): | |
| if t1 <= t0: | |
| flush() | |
| continue | |
| lbl = BIO_LABELS[int(preds[i])] | |
| if lbl == "O": | |
| flush() | |
| continue | |
| prefix, ent = lbl.split("-", 1) | |
| if prefix == "B" or cur != ent: | |
| flush() | |
| cur, s0, s1, scores = ent, t0, t1, [float(confs[i])] | |
| else: | |
| s1 = max(s1, t1) | |
| scores.append(float(confs[i])) | |
| flush() | |
| return spans | |
| def extract_spans(model_path: Path, texts: list[str], *, synthetic_smoke: bool = False): | |
| model_dir = model_path.parent.parent if model_path.parent.name == "onnx" else model_path.parent | |
| sess = ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"]) | |
| if synthetic_smoke: | |
| ids = np.array([[0, 10, 20, 30, 2], [0, 40, 50, 1, 1]], dtype=np.int64) | |
| mask = np.array([[1, 1, 1, 1, 1], [1, 1, 1, 0, 0]], dtype=np.int64) | |
| (logits,) = sess.run(["logits"], {"input_ids": ids, "attention_mask": mask}) | |
| return {"synthetic_shape": list(logits.shape)} | |
| sp = spm.SentencePieceProcessor(model_file=str(model_dir / "sentencepiece.bpe.model")) | |
| out = [] | |
| for raw_text in texts: | |
| ids, offsets = encode_with_offsets(sp, raw_text) | |
| ids_np = np.asarray([ids], dtype=np.int64) | |
| mask_np = np.ones_like(ids_np, dtype=np.int64) | |
| (logits,) = sess.run(["logits"], {"input_ids": ids_np, "attention_mask": mask_np}) | |
| out.append({"text": raw_text, "spans": decode_spans(raw_text, offsets, logits[0])}) | |
| return {"results": out} | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="Run zero-PyTorch dalil-span-ner-onnx inference.") | |
| root = Path(__file__).resolve().parent | |
| parser.add_argument("--model", type=Path, default=root / "onnx" / "dalil-span-ner-v1-int8.onnx") | |
| parser.add_argument("--synthetic-smoke", action="store_true") | |
| parser.add_argument( | |
| "--text", | |
| action="append", | |
| default=None, | |
| help="Input text to extract dalil spans from (repeatable).", | |
| ) | |
| args = parser.parse_args() | |
| samples = args.text or [ | |
| "Sebagaimana Allah berfirman dalam Al Baqarah 275 وَأَحَلَّ اللَّهُ الْبَيْعَ وَحَرَّمَ الرِّبَا serta Fatwa DSN-MUI No. 04/DSN-MUI/IV/2000.", | |
| "HR Bukhari menyebutkan انما الاعمال بالنيات dalam kitab awal.", | |
| "Update Server Linux di AWS S3 dengan Latency 12ms via Pasal 5 UU ITE.", | |
| ] | |
| print(json.dumps(extract_spans(args.model, samples, synthetic_smoke=args.synthetic_smoke), ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |