Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import torch
|
3 |
+
from PIL import Image
|
4 |
+
from ruamel import yaml
|
5 |
+
from albef.model import albef_model_for_vqa
|
6 |
+
from albef.data.transforms import ALBEFTextTransform, testing_image_transform
|
7 |
+
import gradio as gr
|
8 |
+
|
9 |
+
data_dir = "./vqa_data/"
|
10 |
+
|
11 |
+
config = yaml.load(open("./configs/vqa.yaml", "r"), Loader=yaml.Loader)
|
12 |
+
model = albef_model_for_vqa(config)
|
13 |
+
|
14 |
+
checkpoint_url = "https://download.pytorch.org/models/multimodal/albef/finetuned_vqa_checkpoint.pt"
|
15 |
+
checkpoint = torch.hub.load_state_dict_from_url(checkpoint_url, map_location='cpu')
|
16 |
+
model.load_state_dict(checkpoint)
|
17 |
+
|
18 |
+
image_transform = testing_image_transform()
|
19 |
+
question_transform = ALBEFTextTransform(add_end_token=False)
|
20 |
+
answer_transform = ALBEFTextTransform(do_pre_process=False)
|
21 |
+
|
22 |
+
answer_list = json.load(open(data_dir + "answer_list.json", "r"))
|
23 |
+
|
24 |
+
def infer(image, question):
|
25 |
+
images = [image]
|
26 |
+
image_input = [image_transform(image) for image in images]
|
27 |
+
image_input = torch.stack(image_input, dim=0)
|
28 |
+
question_input = question_transform([question])
|
29 |
+
question_atts = (question_input != 0).type(torch.long)
|
30 |
+
answer_input = answer_transform(answer_list)
|
31 |
+
answer_atts = (answer_input != 0).type(torch.long)
|
32 |
+
|
33 |
+
answer_ids, _ = model(
|
34 |
+
image_input,
|
35 |
+
question_input,
|
36 |
+
question_atts,
|
37 |
+
answer_input,
|
38 |
+
answer_atts,
|
39 |
+
k=1,
|
40 |
+
is_train=False,
|
41 |
+
)
|
42 |
+
|
43 |
+
predicted_answer_id = answer_ids[0]
|
44 |
+
predicted_answer = answer_list[predicted_answer_id]
|
45 |
+
|
46 |
+
return predicted_answer
|
47 |
+
|
48 |
+
demo = gr.Interface(
|
49 |
+
fn=infer,
|
50 |
+
inputs=[gr.Image(label='image', type='pil', image_mode='RGB'), gr.Text(label='question')],
|
51 |
+
outputs=gr.Text(label='answer'),
|
52 |
+
# examples=[
|
53 |
+
# ['vqav2.png', 'What sport is this?'],
|
54 |
+
# ['vizwiz.jpeg', 'What piece of meat have I taken out of the freezer?'],
|
55 |
+
# ['aqua.png', 'what does bol lean nonchalantly on'],
|
56 |
+
# ['robotvqa.png', 'How many silver spoons are there?'],
|
57 |
+
# ]
|
58 |
+
)
|
59 |
+
|
60 |
+
demo.launch()
|