|
from transformers import BertForTokenClassification, BertTokenizer, AutoConfig |
|
import torch |
|
from typing import Dict, List, Any |
|
|
|
class EndpointHandler: |
|
def __init__(self, path: str = "dejanseo/LinkBERT"): |
|
|
|
self.config = AutoConfig.from_pretrained(path) |
|
|
|
|
|
|
|
self.model = BertForTokenClassification.from_pretrained( |
|
path, |
|
config=self.config |
|
) |
|
self.model.eval() |
|
|
|
|
|
self.tokenizer = BertTokenizer.from_pretrained("bert-large-cased") |
|
|
|
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}] |
|
|
|
|
|
|
|
|