maximuspowers
commited on
Commit
•
8e93305
1
Parent(s):
0fbe754
Create handler.py
Browse files- handler.py +60 -0
handler.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Any
|
2 |
+
import json
|
3 |
+
import torch
|
4 |
+
from transformers import BertTokenizerFast, BertForTokenClassification
|
5 |
+
|
6 |
+
class EndpointHandler():
|
7 |
+
def __init__(self, path=""):
|
8 |
+
# Load the tokenizer and model
|
9 |
+
self.tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')
|
10 |
+
self.model = BertForTokenClassification.from_pretrained(path)
|
11 |
+
self.model.eval()
|
12 |
+
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
13 |
+
self.model.to(self.device)
|
14 |
+
|
15 |
+
# ID to label mapping
|
16 |
+
self.id2label = {
|
17 |
+
0: 'O',
|
18 |
+
1: 'B-STEREO',
|
19 |
+
2: 'I-STEREO',
|
20 |
+
3: 'B-GEN',
|
21 |
+
4: 'I-GEN',
|
22 |
+
5: 'B-UNFAIR',
|
23 |
+
6: 'I-UNFAIR'
|
24 |
+
}
|
25 |
+
|
26 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
27 |
+
"""
|
28 |
+
Args:
|
29 |
+
data (Dict[str, Any]): A dictionary containing the input text under 'inputs'.
|
30 |
+
|
31 |
+
Returns:
|
32 |
+
List[Dict[str, Any]]: A list of dictionaries with token labels.
|
33 |
+
"""
|
34 |
+
# Extract the input sentence
|
35 |
+
sentence = data.get("inputs", "")
|
36 |
+
if not sentence:
|
37 |
+
return [{"error": "Input 'inputs' is required."}]
|
38 |
+
|
39 |
+
# Tokenize the input sentence
|
40 |
+
inputs = self.tokenizer(sentence, return_tensors="pt", padding=True, truncation=True, max_length=128)
|
41 |
+
input_ids = inputs['input_ids'].to(self.device)
|
42 |
+
attention_mask = inputs['attention_mask'].to(self.device)
|
43 |
+
|
44 |
+
# Run inference
|
45 |
+
with torch.no_grad():
|
46 |
+
outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
|
47 |
+
logits = outputs.logits
|
48 |
+
probabilities = torch.sigmoid(logits)
|
49 |
+
predicted_labels = (probabilities > 0.5).int()
|
50 |
+
|
51 |
+
# Prepare the result
|
52 |
+
result = []
|
53 |
+
tokens = self.tokenizer.convert_ids_to_tokens(input_ids[0])
|
54 |
+
for i, token in enumerate(tokens):
|
55 |
+
if token not in self.tokenizer.all_special_tokens:
|
56 |
+
label_indices = (predicted_labels[0][i] == 1).nonzero(as_tuple=False).squeeze(-1)
|
57 |
+
labels = [self.id2label[idx.item()] for idx in label_indices] if label_indices.numel() > 0 else ['O']
|
58 |
+
result.append({"token": token, "labels": labels})
|
59 |
+
|
60 |
+
return result
|