Download handler.py from kellyhong/finetuned-DistilBERT-queryClassification: direct link, hf CLI and curl.
- Browser
- Download file 1.57 kB
-
https://huggingface.co/kellyhong/finetuned-DistilBERT-queryClassification/resolve/main/handler.py
- Command line
-
hf download hf://kellyhong/finetuned-DistilBERT-queryClassification/handler.py
-
curl -L -o handler.py https://huggingface.co/kellyhong/finetuned-DistilBERT-queryClassification/resolve/main/handler.py
1.57 kB
| 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)} | |