|
from typing import Dict, List, Any |
|
import torch |
|
from transformers import AutoTokenizer, AutoModelForSequenceClassification |
|
import torch.nn.functional as F |
|
|
|
class EndpointHandler: |
|
def __init__(self, path: str = "netandreus/bge-reranker-v2-m3"): |
|
|
|
self.tokenizer = AutoTokenizer.from_pretrained(path) |
|
self.model = AutoModelForSequenceClassification.from_pretrained(path) |
|
self.model.eval() |
|
|
|
|
|
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
self.model.to(self.device) |
|
|
|
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]: |
|
""" |
|
Expected input format: |
|
{ |
|
"inputs": { |
|
"source_sentence": "Your query here", |
|
"sentences": ["Document 1", "Document 2", ...] |
|
}, |
|
"normalize": true # Optional; defaults to False |
|
} |
|
""" |
|
inputs = data.get("inputs", {}) |
|
source_sentence = inputs.get("source_sentence") |
|
sentences = inputs.get("sentences", []) |
|
normalize = data.get("normalize", False) |
|
|
|
if not source_sentence or not sentences: |
|
return [{"error": "Both 'source_sentence' and 'sentences' fields are required inside 'inputs'."}] |
|
|
|
|
|
pairs = [[source_sentence, text] for text in sentences] |
|
|
|
|
|
tokenizer_inputs = self.tokenizer( |
|
pairs, |
|
padding=True, |
|
truncation=True, |
|
return_tensors="pt", |
|
max_length=512 |
|
).to(self.device) |
|
|
|
with torch.no_grad(): |
|
|
|
outputs = self.model(**tokenizer_inputs) |
|
scores = outputs.logits.view(-1) |
|
|
|
|
|
if normalize: |
|
scores = torch.sigmoid(scores) |
|
|
|
|
|
results = [ |
|
{"index": idx, "score": score.item()} |
|
for idx, score in enumerate(scores) |
|
] |
|
|
|
|
|
results.sort(key=lambda x: x["score"], reverse=True) |
|
return results |
|
|