Text Classification
Transformers
ONNX
Safetensors
English
bert
political-discourse
media-bias
wording
contextual-review
text-embeddings-inference
Instructions to use Giuliocc/doxa-wording-encoder with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Giuliocc/doxa-wording-encoder with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="Giuliocc/doxa-wording-encoder")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("Giuliocc/doxa-wording-encoder") model = AutoModelForSequenceClassification.from_pretrained("Giuliocc/doxa-wording-encoder", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 2,877 Bytes
b6e07f2 | 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 | """Run the checked wording model locally with ONNX Runtime."""
import hashlib
import json
from pathlib import Path
import numpy as np
import onnxruntime as ort
from tokenizers import Tokenizer
class WordingModel:
def __init__(self, folder, threads=1):
folder = Path(folder)
self.manifest = json.loads((folder / "runtime_manifest.json").read_text())
for asset in self.manifest["files"].values():
if hashlib.sha256((folder / asset["path"]).read_bytes()).hexdigest() != asset["sha256"]:
raise ValueError("A model asset does not match the published manifest")
self.tokenizer = Tokenizer.from_file(str(folder / "tokenizer.json"))
if json.loads((folder / "tokenizer.json").read_text()).get("truncation"):
raise ValueError("The tokenizer must preserve full input length")
options = ort.SessionOptions()
options.intra_op_num_threads = threads
options.inter_op_num_threads = 1
self.session = ort.InferenceSession(str(folder / "onnx/model_quantized.onnx"),
sess_options=options, providers=["CPUExecutionProvider"])
def check(self, text):
if not isinstance(text, str) or not text.strip():
raise ValueError("Choose a non-empty passage")
manifest = self.manifest
encoded = self.tokenizer.encode(text)
length = len(encoded.ids)
result = {
"method": manifest["method"], "task": manifest["task"], "decision": "unresolved",
"model_score": None, "class_scores": None, "score_calibration": manifest["score_calibration"],
"decision_threshold": manifest["threshold"], "token_count": length,
"maximum_tokens": manifest["maximum_tokens"], "model_id": manifest["model_id"],
"model_revision": manifest["revision"], "context_used": False, "reason": None,
"scope": manifest["scope"],
}
if length > manifest["maximum_tokens"]:
return result | {"reason": "input_too_long"}
values = {"input_ids": encoded.ids, "attention_mask": encoded.attention_mask, "token_type_ids": encoded.type_ids}
inputs = {item.name: np.array([values[item.name]], dtype=np.int64) for item in self.session.get_inputs()}
logits = self.session.run(None, inputs)[0][0] / manifest["temperature"]
probabilities = np.exp(logits - logits.max())
probabilities /= probabilities.sum()
positive = float(probabilities[1])
result["model_score"] = positive
result["class_scores"] = {"no_biased_wording": 1 - positive, "biased_wording": positive}
if max(positive, 1 - positive) < manifest["threshold"]:
result["reason"] = "below_resolution_threshold"
else:
result["decision"] = "wording_flag" if positive >= .5 else "no_wording_flag"
return result
|