Upload inference.py
Browse files- inference.py +114 -0
inference.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# inference.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import torch
|
| 5 |
+
import joblib
|
| 6 |
+
import numpy as np
|
| 7 |
+
from transformers import BertTokenizer, BertModel
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class EndpointHandler:
|
| 11 |
+
"""
|
| 12 |
+
Custom handler for Hugging Face Inference Endpoints.
|
| 13 |
+
|
| 14 |
+
Expected input JSON:
|
| 15 |
+
{"inputs": "some text"}
|
| 16 |
+
or {"inputs": ["text 1", "text 2", ...]}
|
| 17 |
+
|
| 18 |
+
Output:
|
| 19 |
+
For single input:
|
| 20 |
+
{"label": "...", "confidence": 0.95}
|
| 21 |
+
For multiple:
|
| 22 |
+
[
|
| 23 |
+
{"label": "...", "confidence": 0.95},
|
| 24 |
+
{"label": "...", "confidence": 0.80},
|
| 25 |
+
...
|
| 26 |
+
]
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, path: str = "."):
|
| 30 |
+
# 1. Device setup
|
| 31 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 32 |
+
print(f"[handler] Using device: {self.device}")
|
| 33 |
+
|
| 34 |
+
# 2. Load BERT
|
| 35 |
+
print("[handler] Loading BERT tokenizer and model...")
|
| 36 |
+
self.tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
|
| 37 |
+
self.bert_model = BertModel.from_pretrained("bert-base-uncased")
|
| 38 |
+
self.bert_model.to(self.device)
|
| 39 |
+
self.bert_model.eval()
|
| 40 |
+
|
| 41 |
+
# 3. Load MLP, scaler, label encoder
|
| 42 |
+
print("[handler] Loading classification components...")
|
| 43 |
+
mlp_path = os.path.join(path, "mlp_query_classifier.joblib")
|
| 44 |
+
scaler_path = os.path.join(path, "scaler_query_classifier.joblib")
|
| 45 |
+
le_path = os.path.join(path, "label_encoder_query_classifier.joblib")
|
| 46 |
+
|
| 47 |
+
self.mlp = joblib.load(mlp_path)
|
| 48 |
+
self.scaler = joblib.load(scaler_path)
|
| 49 |
+
self.le = joblib.load(le_path)
|
| 50 |
+
|
| 51 |
+
print("[handler] Loaded MLP, scaler, and label encoder.")
|
| 52 |
+
|
| 53 |
+
# ------------ Helper: BERT embeddings ------------
|
| 54 |
+
def get_bert_embeddings(self, text_list):
|
| 55 |
+
inputs = self.tokenizer(
|
| 56 |
+
text_list,
|
| 57 |
+
padding=True,
|
| 58 |
+
truncation=True,
|
| 59 |
+
max_length=128,
|
| 60 |
+
return_tensors="pt"
|
| 61 |
+
).to(self.device)
|
| 62 |
+
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
outputs = self.bert_model(**inputs)
|
| 65 |
+
|
| 66 |
+
# CLS token embedding
|
| 67 |
+
cls_embeddings = outputs.last_hidden_state[:, 0, :]
|
| 68 |
+
return cls_embeddings.cpu().numpy()
|
| 69 |
+
|
| 70 |
+
# ------------ Main entry point ------------
|
| 71 |
+
def __call__(self, data):
|
| 72 |
+
"""
|
| 73 |
+
data: dict with key "inputs"
|
| 74 |
+
"""
|
| 75 |
+
if "inputs" not in data:
|
| 76 |
+
raise ValueError("Input JSON must have an 'inputs' field.")
|
| 77 |
+
|
| 78 |
+
texts = data["inputs"]
|
| 79 |
+
|
| 80 |
+
# Normalize to list
|
| 81 |
+
is_single = False
|
| 82 |
+
if isinstance(texts, str):
|
| 83 |
+
texts = [texts]
|
| 84 |
+
is_single = True
|
| 85 |
+
|
| 86 |
+
# 1) BERT embedding
|
| 87 |
+
embeddings = self.get_bert_embeddings(texts)
|
| 88 |
+
|
| 89 |
+
# 2) Scale with same scaler as training
|
| 90 |
+
embeddings_scaled = self.scaler.transform(embeddings)
|
| 91 |
+
|
| 92 |
+
# 3) Predict class indices
|
| 93 |
+
pred_indices = self.mlp.predict(embeddings_scaled)
|
| 94 |
+
|
| 95 |
+
# 4) Map indices to labels
|
| 96 |
+
labels = self.le.inverse_transform(pred_indices)
|
| 97 |
+
|
| 98 |
+
# 5) Optionally, get probabilities
|
| 99 |
+
results = []
|
| 100 |
+
for i, idx in enumerate(pred_indices):
|
| 101 |
+
label = labels[i]
|
| 102 |
+
try:
|
| 103 |
+
probs = self.mlp.predict_proba(embeddings_scaled[i : i + 1])[0]
|
| 104 |
+
confidence = float(np.max(probs))
|
| 105 |
+
except Exception:
|
| 106 |
+
confidence = None
|
| 107 |
+
|
| 108 |
+
result = {"label": label}
|
| 109 |
+
results.append(result)
|
| 110 |
+
|
| 111 |
+
# If the user sent a single string, return a single dict
|
| 112 |
+
if is_single:
|
| 113 |
+
return results[0]
|
| 114 |
+
return results
|