philschmid HF staff commited on
Commit
002f70f
1 Parent(s): d46a61d

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +33 -0
handler.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
3
+ import torch
4
+
5
+ class EndpointHandler:
6
+ def __init__(self, path=""):
7
+ # load model and processor from path
8
+ self.model = AutoModelForSeq2SeqLM.from_pretrained(path, device_map="auto", load_in_8bit=True)
9
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
10
+
11
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
12
+ """
13
+ Args:
14
+ data (:obj:):
15
+ includes the deserialized image file as PIL.Image
16
+ """
17
+ # process input
18
+ inputs = data.pop("inputs", data)
19
+ parameters = data.pop("parameters", None)
20
+
21
+ # preprocess
22
+ input_ids = self.tokenizer(inputs, return_tensors="pt").input_ids
23
+
24
+ # pass inputs with all kwargs in data
25
+ if parameters is not None:
26
+ outputs = self.model.generate(input_ids, **parameters)
27
+ else:
28
+ outputs = self.model.generate(input_ids)
29
+
30
+ # postprocess the prediction
31
+ prediction = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
32
+
33
+ return [{"generated_text": prediction}]