Add role-aware multi-message inference helper
Browse files
inference_mask_messages_onnx.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from common import decode_span_matrix, load_onnx_session, run_onnx_span, sigmoid_np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def replacement(label: str) -> str:
|
| 12 |
+
return f"[PII:{label}]"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def mask_text(text: str, spans: list[dict]) -> str:
|
| 16 |
+
out = text
|
| 17 |
+
for span in sorted(spans, key=lambda item: (item["start"], item["end"]), reverse=True):
|
| 18 |
+
out = out[: span["start"]] + replacement(span["label"]) + out[span["end"] :]
|
| 19 |
+
return out
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def infer_profile(role: str | None) -> str:
|
| 23 |
+
role_key = (role or "").strip().lower()
|
| 24 |
+
if role_key == "assistant":
|
| 25 |
+
return "assistant_public"
|
| 26 |
+
return "default"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def predict(text: str, role: str | None, session, tokenizer, config, min_score: float):
|
| 30 |
+
encoded = tokenizer(text, return_offsets_mapping=True, return_tensors="np", truncation=True)
|
| 31 |
+
offsets = [tuple(item) for item in encoded["offset_mapping"][0].tolist()]
|
| 32 |
+
span_logits = run_onnx_span(session, encoded)
|
| 33 |
+
span_scores = sigmoid_np(span_logits[0])
|
| 34 |
+
profile = infer_profile(role)
|
| 35 |
+
spans = decode_span_matrix(text, offsets, span_scores, config, min_score, profile=profile)
|
| 36 |
+
for span in spans:
|
| 37 |
+
span["replacement"] = replacement(span["label"])
|
| 38 |
+
return profile, spans
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def load_messages(path: Path) -> list[dict]:
|
| 42 |
+
raw = path.read_text(encoding="utf-8")
|
| 43 |
+
if path.suffix.lower() == ".jsonl":
|
| 44 |
+
return [json.loads(line) for line in raw.splitlines() if line.strip()]
|
| 45 |
+
data = json.loads(raw)
|
| 46 |
+
if isinstance(data, dict):
|
| 47 |
+
messages = data.get("messages")
|
| 48 |
+
if isinstance(messages, list):
|
| 49 |
+
return messages
|
| 50 |
+
if isinstance(data, list):
|
| 51 |
+
return data
|
| 52 |
+
raise ValueError("Expected a JSON array, a JSON object with a `messages` array, or JSONL")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def main() -> None:
|
| 56 |
+
parser = argparse.ArgumentParser()
|
| 57 |
+
parser.add_argument("--model", required=True)
|
| 58 |
+
parser.add_argument("--input-file", required=True)
|
| 59 |
+
parser.add_argument("--min-score", type=float, default=0.5)
|
| 60 |
+
parser.add_argument("--json", action="store_true")
|
| 61 |
+
args = parser.parse_args()
|
| 62 |
+
|
| 63 |
+
session, tokenizer, config = load_onnx_session(args.model, onnx_file="model_quantized.onnx", onnx_subfolder="onnx")
|
| 64 |
+
messages = load_messages(Path(args.input_file))
|
| 65 |
+
output_messages = []
|
| 66 |
+
for message in messages:
|
| 67 |
+
role = message.get("role")
|
| 68 |
+
text = message.get("text", "")
|
| 69 |
+
profile, spans = predict(text, role, session, tokenizer, config, args.min_score)
|
| 70 |
+
output_messages.append(
|
| 71 |
+
{
|
| 72 |
+
**message,
|
| 73 |
+
"profile": profile,
|
| 74 |
+
"spans": spans,
|
| 75 |
+
"masked_text": mask_text(text, spans),
|
| 76 |
+
}
|
| 77 |
+
)
|
| 78 |
+
result = {
|
| 79 |
+
"model": args.model,
|
| 80 |
+
"backend": "onnx_global_pointer_q8",
|
| 81 |
+
"messages": output_messages,
|
| 82 |
+
}
|
| 83 |
+
if args.json:
|
| 84 |
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
| 85 |
+
else:
|
| 86 |
+
for message in output_messages:
|
| 87 |
+
print(f"[{message.get('role', 'unknown')}] {message['masked_text']}")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
main()
|