Update handler.py
Browse files- handler.py +41 -47
handler.py
CHANGED
|
@@ -1,48 +1,42 @@
|
|
|
|
|
| 1 |
import torch
|
| 2 |
-
from
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
tokenizer
|
| 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 |
-
# Join tokens back into a string
|
| 44 |
-
reconstructed_text = " ".join(result).replace(" ##", "")
|
| 45 |
-
|
| 46 |
-
return {"result": reconstructed_text}
|
| 47 |
-
|
| 48 |
-
# Note: The actual function signatures for init() and process() might need to be adapted based on Hugging Face's requirements.
|
|
|
|
| 1 |
+
from transformers import AutoModelForTokenClassification, AutoTokenizer
|
| 2 |
import torch
|
| 3 |
+
from typing import Dict, List, Any
|
| 4 |
+
|
| 5 |
+
class EndpointHandler:
|
| 6 |
+
def __init__(self, path: str = "dejanseo/LinkBERT"):
|
| 7 |
+
# Initialize tokenizer and model with the specified path
|
| 8 |
+
self.tokenizer = AutoTokenizer.from_pretrained(path)
|
| 9 |
+
self.model = AutoModelForTokenClassification.from_pretrained(path)
|
| 10 |
+
self.model.eval() # Set model to evaluation mode
|
| 11 |
+
|
| 12 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 13 |
+
# Extract input text from the request
|
| 14 |
+
inputs = data.get("inputs", "")
|
| 15 |
+
|
| 16 |
+
# Tokenize the inputs
|
| 17 |
+
inputs_tensor = self.tokenizer(inputs, return_tensors="pt", add_special_tokens=True)
|
| 18 |
+
input_ids = inputs_tensor["input_ids"]
|
| 19 |
+
|
| 20 |
+
# Run the model
|
| 21 |
+
with torch.no_grad():
|
| 22 |
+
outputs = self.model(input_ids)
|
| 23 |
+
predictions = torch.argmax(outputs.logits, dim=-1)
|
| 24 |
+
|
| 25 |
+
# Process the predictions to generate readable output
|
| 26 |
+
tokens = self.tokenizer.convert_ids_to_tokens(input_ids[0])[1:-1] # Exclude CLS and SEP tokens
|
| 27 |
+
predictions = predictions[0][1:-1].tolist()
|
| 28 |
+
|
| 29 |
+
# Reconstruct the text with annotations for token classification
|
| 30 |
+
result = []
|
| 31 |
+
for token, pred in zip(tokens, predictions):
|
| 32 |
+
if pred == 1: # Assuming '1' is the label for the class of interest
|
| 33 |
+
result.append(f"<u>{token}</u>")
|
| 34 |
+
else:
|
| 35 |
+
result.append(token)
|
| 36 |
+
|
| 37 |
+
reconstructed_text = " ".join(result).replace(" ##", "")
|
| 38 |
+
|
| 39 |
+
# Return the processed text in a structured format
|
| 40 |
+
return [{"text": reconstructed_text}]
|
| 41 |
+
|
| 42 |
+
# Note: You'll need to replace 'path' with the actual path or identifier of your model when initializing the EndpointHandler.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|