File size: 1,243 Bytes
ccc2704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Dict, Any, List
import torch
from transformers import T5ForConditionalGeneration, T5Tokenizer

class EndpointHandler():
    def __init__(self, path=""):
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        try:
            self.model = T5ForConditionalGeneration.from_pretrained(path).to(self.device)
            self.tokenizer = T5Tokenizer.from_pretrained(path)
        except Exception as e:
            print(f"Error loading model or tokenizer from path {path}: {e}")
            # Handle error (e.g., exit or set model/tokenizer to None)

    def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
        inputs = data.get("inputs", "")
        if not inputs:
            return [{"error": "No inputs provided"}]

        tokenized_input = self.tokenizer(inputs, return_tensors="pt", truncation=True, max_length=512, padding="max_length")
        tokenized_input = tokenized_input.to(self.device)  # Move input tensors to the same device as model

        summary_ids = self.model.generate(**tokenized_input, max_length=400, do_sample=True, top_p=0.8)

        summary_text = self.tokenizer.decode(summary_ids[0], skip_special_tokens=True)

        return [{"summary": summary_text}]