File size: 1,572 Bytes
2b89c36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
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
from typing import Dict, Any
from transformers import DistilBertForSequenceClassification, DistilBertTokenizer
import torch

class EndpointHandler:
    def __init__(self, path: str = ""):
        # Load the tokenizer and model from the specified path
        self.tokenizer = DistilBertTokenizer.from_pretrained(path)
        self.model = DistilBertForSequenceClassification.from_pretrained(path)
        self.model.eval()  # Set the model to evaluation mode to disable dropout

    def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
        """
        Process the incoming request and return the category as a string of a number.
        
        Args:
            data (Dict[str, Any]): Input data containing the query as a string under 'inputs'.
        
        Returns:
            Dict[str, str]: A dictionary containing the predicted category as a string of a number.
        """
        # Extract the input string from the request data
        query = data.get("inputs", "")
        
        if not query:
            return {"error": "No input query provided"}

        # Tokenize the input query
        inputs = self.tokenizer(query, return_tensors="pt")

        # Perform inference
        with torch.no_grad():
            outputs = self.model(**inputs)
            # Get the predicted category index (assuming outputs.logits is the output tensor)
            predicted_category = torch.argmax(outputs.logits, dim=1).item()

        # Convert the predicted category index to a string and return
        return {"category": str(predicted_category)}