from typing import Dict, List, Any from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipeline import torch class EndpointHandler: def __init__(self, path=""): # load model and processor from path self.model = AutoModelForSeq2SeqLM.from_pretrained(path, device_map="auto") self.tokenizer = AutoTokenizer.from_pretrained(path) self.pipeline = pipeline(task="text-generation", tokenizer=self.tokenizer, device=0, device_map="auto", framework="pt", model=self.model, max_length=512) def __call__(self, data: Dict[str, Any]) -> Dict[str, str]: """ Args: data (:obj:): includes the deserialized image file as PIL.Image """ # process input inputs = data.pop("inputs", data) parameters = data.pop("parameters", None) # preprocess input_ids = self.tokenizer(inputs, return_tensors="pt").input_ids # postprocess the prediction prediction = self.tokenizer.decode(outputs[0], skip_special_tokens=True) # pass inputs with all kwargs in data if parameters is not None: outputs = self.model.generate(inputs, device=0, **parameters) else: outputs = self.model.generate(inputs, device=0) # postprocess the prediction prediction = self.tokenizer.decode(outputs[0], skip_special_tokens=True) return [{"generated_text": prediction}]