Andrew Luo commited on
Commit
865f97a
1 Parent(s): a31db03
Files changed (2) hide show
  1. handler.py +52 -0
  2. requirements.txt +3 -0
handler.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
2
+ import torch
3
+ from PIL import Image
4
+ from typing import Dict, List, Any
5
+
6
+ class EndpointHandler():
7
+ def __init__(self, path=""):
8
+ model = VisionEncoderDecoderModel.from_pretrained(
9
+ "nlpconnect/vit-gpt2-image-captioning")
10
+ feature_extractor = ViTImageProcessor.from_pretrained(
11
+ "nlpconnect/vit-gpt2-image-captioning")
12
+ tokenizer = AutoTokenizer.from_pretrained(
13
+ "nlpconnect/vit-gpt2-image-captioning")
14
+
15
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
+ model.to(device)
17
+ self.model = model
18
+ self.feature_extractor = feature_extractor
19
+ self.tokenizer = tokenizer
20
+
21
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
22
+ """
23
+ data args:
24
+ inputs (:obj: `str`)
25
+ date (:obj: `str`)
26
+ Return:
27
+ A :obj:`list` | `dict`: will be serialized and returned
28
+ """
29
+ # get inputs
30
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
31
+ max_length = 128
32
+ num_beams = 4
33
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams}
34
+ image_paths = data.pop("image_paths", data)
35
+ images = []
36
+ for image_path in image_paths:
37
+ i_image = Image.open(image_path)
38
+ if i_image.mode != "RGB":
39
+ i_image = i_image.convert(mode="RGB")
40
+
41
+ images.append(i_image)
42
+
43
+ pixel_values = self.feature_extractor(
44
+ images=images, return_tensors="pt").pixel_values
45
+ pixel_values = pixel_values.to(device)
46
+
47
+ output_ids = self.model.generate(pixel_values, **gen_kwargs)
48
+
49
+ preds = self.tokenizer.batch_decode(
50
+ output_ids, skip_special_tokens=True)
51
+ preds = [pred.strip() for pred in preds]
52
+ return preds
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch
2
+ transformers
3
+ Pillow