iris-names / examples /extract.py
aneesahammed's picture
Rewrite the model card, correct the notices, add an example and a rebuild script
c1ca102 verified
Raw History Blame Contribute Delete
10.8 kB
# /// script
# requires-python = ">=3.11,<3.14"
# dependencies = [
# "onnxruntime==1.23.2",
# "tokenizers==0.22.2",
# "huggingface_hub>=1.0",
# "numpy>=2.0",
# ]
# ///
# SPDX-License-Identifier: Apache-2.0
"""Find names in text with the iris-names ONNX files, on the CPU, offline after download.
python extract.py "Ada Lovelace worked with Charles Babbage in London."
python extract.py --labels person,city --check "..."
python extract.py --self-test
This is a plain reference for the two models. It is not Iris's extraction pipeline,
which adds its own filtering, so results differ from Iris.
The word splitter and the overlap rule follow gliner2 2.1.0 (by Fastino AI,
Apache-2.0, https://github.com/fastino-ai/GLiNER2).
"""
import argparse
import bisect
import json
import re
import sys
import unicodedata
from pathlib import Path
import numpy as np
import onnxruntime as ort
from tokenizers import Tokenizer
REPO = "iris-hq/iris-names"
REVISION = "d179d4a5a599fa8541dd0da17d0aea89096039fc"
MODEL_FILES = ["gliner25/*", "gliner25/encoder/*", "deberta-nli/*"]
LIMIT = 512 # tokens per model call
LABELS = ["person", "organization", "location", "product", "event"]
MARKS = "".join(chr(c) for c in range(sys.maxunicode + 1) if unicodedata.category(chr(c)).startswith("M"))
WORD = rf"[\w{MARKS}‌‍]"
SPLITTER = re.compile(
rf"""(?:https?://[^\s]+|www\.[^\s]+)
|[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{{2,}}
|@[a-z0-9_]+
|{WORD}+(?:[-_]{WORD}+)*
|\S""",
re.VERBOSE | re.IGNORECASE,
)
def split_words(text):
"""Lowercased words with character offsets into the original text."""
return [(m.group().lower(), m.start(), m.end()) for m in SPLITTER.finditer(text)]
def session(path):
options = ort.SessionOptions()
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
options.enable_cpu_mem_arena = False
options.enable_mem_pattern = False
options.add_session_config_entry("session.disable_prepacking", "1")
options.intra_op_num_threads = 4
options.log_severity_level = 3
return ort.InferenceSession(str(path), options, providers=["CPUExecutionProvider"])
def sigmoid(x):
return 1 / (1 + np.exp(-np.clip(x, -60, 60)))
def best_non_overlapping(spans):
"""The set of (start, end, score) spans with the highest total score and no overlap."""
spans = sorted({(s, e): p for s, e, p in sorted(spans, key=lambda x: x[2])}.items(), key=lambda x: (x[0][1], x[0][0]))
ends = [e for (_, e), _ in spans]
best = [(0.0, [])]
for i, ((s, e), p) in enumerate(spans):
total, chosen = best[bisect.bisect_right(ends, s, 0, i)]
take = (total + p, chosen + [(s, e, p)])
best.append(max(take, best[i], key=lambda b: (b[0], len(b[1]))))
return best[-1][1]
class NameFinder:
"""GLiNER 2.5: text and labels in, scored spans out."""
def __init__(self, root):
root = Path(root) / "gliner25"
self.tokenizer = Tokenizer.from_file(str(root / "tokenizer.json"))
self.encoder = session(root / "encoder" / "model.onnx")
self.head = session(root / "boundary_head.onnx")
def ids(self, text):
return self.tokenizer.encode(text, add_special_tokens=False).ids
def find_words(self, words, labels, threshold=0.5):
"""Spans as (first word, end word, label index, score) for lowercased words."""
prefix = [i for t in ("(", "[P]", "entities", "(") for i in self.ids(t)]
queries = []
for label in labels:
queries.append(len(prefix)) # the [E] marker stands for the label
prefix += self.ids("[E]") + self.ids(label)
prefix += [i for t in (")", ")", "[SEP_TEXT]") for i in self.ids(t)]
budget = LIMIT - len(prefix)
if not labels or budget <= 0:
raise ValueError("give at least one label, and few enough to fit in 512 tokens")
spans, ids, routes, first = [], list(prefix), [], 0
for index, word in enumerate(words):
tokens = self.ids(word)
too_long = len(tokens) > budget # no span can include this word
if routes and (too_long or len(ids) + len(tokens) > LIMIT):
spans += self._window(ids, routes, queries, first, threshold)
ids, routes = list(prefix), []
if too_long:
continue
if not routes:
first = index
routes.append(len(ids)) # a word is represented by its first token
ids += tokens
if routes:
spans += self._window(ids, routes, queries, first, threshold)
return spans
def _window(self, ids, routes, queries, first, threshold):
states = self.encoder.run(None, {
"input_ids": np.array([ids], np.int64),
"attention_mask": np.ones((1, len(ids)), np.int64),
})[0][0]
last = len(ids) - 1
indices, pair_logits, valid, null_logits = self.head.run(None, {
"token_states": states[np.minimum(routes, last)][None],
"text_mask": np.ones((1, len(routes)), bool),
"query_states": states[queries][None],
"query_mask": np.ones((1, len(queries)), bool),
})
scores, null = sigmoid(pair_logits[0]), sigmoid(null_logits[0])
out = []
for label in range(len(queries)):
if null[label] > 0.5: # the model says this label is absent
continue
keep = np.flatnonzero(valid[0, label] & (scores[label] >= threshold))
spans = [(int(indices[0, label, c, 0]), int(indices[0, label, c, 1]), float(scores[label, c])) for c in keep]
out += [(first + s, first + e, label, p) for s, e, p in best_non_overlapping(spans)]
return out
def find(self, text, labels=LABELS, threshold=0.5):
"""Names in one short text, such as a sentence or paragraph."""
words = split_words(text)
found = []
for s, e, label, score in self.find_words([w for w, _, _ in words], labels, threshold):
start, end = words[s][1], words[e - 1][2]
found.append({"text": text[start:end], "label": labels[label], "start": start, "end": end,
"score": round(score, 4)})
return sorted(found, key=lambda f: (f["start"], f["end"]))
def find_lines(self, text, labels=LABELS, threshold=0.5):
"""Names in longer text, read a line at a time: the head proposes about 32 names per call."""
found, offset = [], 0
for line in text.splitlines(keepends=True):
for f in self.find(line, labels, threshold):
found.append({**f, "start": f["start"] + offset, "end": f["end"] + offset})
offset += len(line)
return found
class Checker:
"""DeBERTa-v3 NLI: the probability that a premise entails a hypothesis."""
def __init__(self, root):
root = Path(root) / "deberta-nli"
self.tokenizer = Tokenizer.from_file(str(root / "tokenizer.json"))
self.model = session(root / "model.onnx")
id2label = json.loads((root / "config.json").read_text())["id2label"]
self.entailment = next(int(k) for k, v in id2label.items() if v.lower() == "entailment")
def entails(self, premise, hypothesis):
def ids(text):
return self.tokenizer.encode(text, add_special_tokens=False).ids
pair = ids("[CLS]") + ids(premise) + ids("[SEP]") + ids(hypothesis) + ids("[SEP]")
if len(pair) > LIMIT:
return None # too long to check
logits = self.model.run(None, {
"input_ids": np.array([pair], np.int64),
"attention_mask": np.ones((1, len(pair)), np.int64),
})[0][0].astype(np.float64)
weights = np.exp(logits - logits.max())
return float(weights[self.entailment] / weights.sum())
def sentence_around(text, start, end):
breaks = [0] + [m.end() for m in re.finditer(r"[.!?]\s+|\n+", text)] + [len(text)]
left = max(b for b in breaks if b <= start)
right = min(b for b in breaks if b >= end)
return text[left:right].strip()
def self_test(root):
assert best_non_overlapping([(0, 2, 0.9), (1, 3, 0.8), (2, 4, 0.7)]) == [(0, 2, 0.9), (2, 4, 0.7)]
assert best_non_overlapping([(0, 4, 0.9), (0, 2, 0.6), (2, 4, 0.6)]) == [(0, 2, 0.6), (2, 4, 0.6)]
finder = NameFinder(root)
found = {(f["text"], f["label"]) for f in finder.find("Ada Lovelace worked with Charles Babbage in London.")}
assert found == {("Ada Lovelace", "person"), ("Charles Babbage", "person"), ("London", "location")}, found
assert finder.find("") == [] == finder.find_lines("")
lines = "Alice left.\r\n\nShe met Bob.\n"
in_lines = finder.find_lines(lines)
assert all(lines[f["start"]:f["end"]] == f["text"] for f in in_lines), in_lines
assert {"Alice", "Bob"} <= {f["text"] for f in in_lines}, in_lines
checker = Checker(root)
yes = checker.entails("Kyoto is a city in Japan.", "Kyoto is a city.")
no = checker.entails("Kyoto is a city in Japan.", "Kyoto is a person.")
assert yes > 0.9 and no < 0.1, (yes, no)
assert checker.entails("word " * 600, "Kyoto is a city.") is None
print("self-test passed")
def main():
parser = argparse.ArgumentParser(description="Find names in text with the iris-names ONNX files.")
parser.add_argument("text", nargs="?", help="text to read; leave out to read standard input")
parser.add_argument("--labels", default=",".join(LABELS), help="comma-separated, lowercase")
parser.add_argument("--threshold", type=float, default=0.5)
parser.add_argument("--check", action="store_true", help="also score each type with the NLI model")
parser.add_argument("--model-dir", help="a downloaded copy; default: download the pinned revision")
parser.add_argument("--self-test", action="store_true")
args = parser.parse_args()
root = args.model_dir
if not root:
from huggingface_hub import snapshot_download
root = snapshot_download(REPO, revision=REVISION, allow_patterns=MODEL_FILES)
if args.self_test:
return self_test(root)
text = args.text if args.text is not None else sys.stdin.read()
labels = [label.strip() for label in args.labels.split(",") if label.strip()]
found = NameFinder(root).find_lines(text, labels, args.threshold)
if args.check:
checker = Checker(root)
for f in found:
# Illustrative wording: choose and test your own for your labels.
score = checker.entails(sentence_around(text, f["start"], f["end"]), f"{f['text']} is a {f['label']}.")
f["check"] = None if score is None else round(score, 4)
print(json.dumps(found, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()