TeamAlerito
commited on
Commit
·
bfe8399
1
Parent(s):
c9f5c38
Upload pipeline.py
Browse files- pipeline.py +62 -0
pipeline.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import Dict, List, Any
|
3 |
+
from PIL import Image
|
4 |
+
import jax
|
5 |
+
from transformers import ViTFeatureExtractor, AutoTokenizer, FlaxVisionEncoderDecoderModel, VisionEncoderDecoderModel
|
6 |
+
import torch
|
7 |
+
|
8 |
+
|
9 |
+
class PreTrainedPipeline():
|
10 |
+
|
11 |
+
def __init__(self, path=""):
|
12 |
+
|
13 |
+
model_dir = path
|
14 |
+
|
15 |
+
# self.model = FlaxVisionEncoderDecoderModel.from_pretrained(model_dir)
|
16 |
+
self.model = VisionEncoderDecoderModel.from_pretrained(model_dir)
|
17 |
+
self.feature_extractor = ViTFeatureExtractor.from_pretrained(model_dir)
|
18 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
19 |
+
|
20 |
+
max_length = 16
|
21 |
+
num_beams = 4
|
22 |
+
# self.gen_kwargs = {"max_length": max_length, "num_beams": num_beams}
|
23 |
+
self.gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "return_dict_in_generate": True, "output_scores": True}
|
24 |
+
|
25 |
+
self.model.to("cpu")
|
26 |
+
self.model.eval()
|
27 |
+
|
28 |
+
# @jax.jit
|
29 |
+
def _generate(pixel_values):
|
30 |
+
|
31 |
+
with torch.no_grad():
|
32 |
+
|
33 |
+
outputs = self.model.generate(pixel_values, **self.gen_kwargs)
|
34 |
+
output_ids = outputs.sequences
|
35 |
+
sequences_scores = outputs.sequences_scores
|
36 |
+
|
37 |
+
return output_ids, sequences_scores
|
38 |
+
|
39 |
+
self.generate = _generate
|
40 |
+
|
41 |
+
# compile the model
|
42 |
+
image_path = os.path.join(path, 'val_000000039769.jpg')
|
43 |
+
image = Image.open(image_path)
|
44 |
+
self(image)
|
45 |
+
image.close()
|
46 |
+
|
47 |
+
def __call__(self, inputs: "Image.Image") -> List[str]:
|
48 |
+
"""
|
49 |
+
Args:
|
50 |
+
Return:
|
51 |
+
"""
|
52 |
+
|
53 |
+
# pixel_values = self.feature_extractor(images=inputs, return_tensors="np").pixel_values
|
54 |
+
pixel_values = self.feature_extractor(images=inputs, return_tensors="pt").pixel_values
|
55 |
+
|
56 |
+
output_ids, sequences_scores = self.generate(pixel_values)
|
57 |
+
preds = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
58 |
+
preds = [pred.strip() for pred in preds]
|
59 |
+
|
60 |
+
preds = [{"label": preds[0], "score": float(sequences_scores[0])}]
|
61 |
+
|
62 |
+
return preds
|