Spaces:
Runtime error
Runtime error
Upload Sample running code.py
Browse files- Sample running code.py +37 -0
Sample running code.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
7 |
+
feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
9 |
+
|
10 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
11 |
+
model.to(device)
|
12 |
+
|
13 |
+
|
14 |
+
|
15 |
+
max_length = 16
|
16 |
+
num_beams = 4
|
17 |
+
gen_kwargs = {"max_length": max_length, "num_beams": num_beams}
|
18 |
+
def predict_step(image_paths):
|
19 |
+
images = []
|
20 |
+
for image_path in image_paths:
|
21 |
+
i_image = Image.open(image_path)
|
22 |
+
if i_image.mode != "RGB":
|
23 |
+
i_image = i_image.convert(mode="RGB")
|
24 |
+
|
25 |
+
images.append(i_image)
|
26 |
+
|
27 |
+
pixel_values = feature_extractor(images=images, return_tensors="pt").pixel_values
|
28 |
+
pixel_values = pixel_values.to(device)
|
29 |
+
|
30 |
+
output_ids = model.generate(pixel_values, **gen_kwargs)
|
31 |
+
|
32 |
+
preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
33 |
+
preds = [pred.strip() for pred in preds]
|
34 |
+
return preds
|
35 |
+
|
36 |
+
|
37 |
+
predict_step(['i1.png'])
|