|
from transformers import AutoModelForTokenClassification, AutoTokenizer |
|
import torch |
|
from typing import Dict, List, Any |
|
|
|
class EndpointHandler: |
|
def __init__(self, path: str = "dejanseo/LinkBERT"): |
|
|
|
self.tokenizer = AutoTokenizer.from_pretrained(path) |
|
self.model = AutoModelForTokenClassification.from_pretrained(path) |
|
self.model.eval() |
|
|
|
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]: |
|
|
|
inputs = data.get("inputs", "") |
|
|
|
|
|
inputs_tensor = self.tokenizer(inputs, return_tensors="pt", add_special_tokens=True) |
|
input_ids = inputs_tensor["input_ids"] |
|
|
|
|
|
with torch.no_grad(): |
|
outputs = self.model(input_ids) |
|
predictions = torch.argmax(outputs.logits, dim=-1) |
|
|
|
|
|
tokens = self.tokenizer.convert_ids_to_tokens(input_ids[0])[1:-1] |
|
predictions = predictions[0][1:-1].tolist() |
|
|
|
|
|
result = [] |
|
for token, pred in zip(tokens, predictions): |
|
if pred == 1: |
|
result.append(f"<u>{token}</u>") |
|
else: |
|
result.append(token) |
|
|
|
reconstructed_text = " ".join(result).replace(" ##", "") |
|
|
|
|
|
return [{"text": reconstructed_text}] |
|
|
|
|
|
|