Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import ViltProcessor, ViltForNaturalLanguageVisualReasoning
|
3 |
+
import torch
|
4 |
+
|
5 |
+
torch.hub.download_url_to_file('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg', 'image1.jpg')
|
6 |
+
torch.hub.download_url_to_file('https://lil.nlp.cornell.edu/nlvr/exs/ex0_1.jpg', 'image2.jpg')
|
7 |
+
|
8 |
+
processor = ViltProcessor.from_pretrained("nielsr/vilt-b32-finetuned-nlvr2")
|
9 |
+
model = ViltForNaturalLanguageVisualReasoning.from_pretrained("nielsr/vilt-b32-finetuned-nlvr2")
|
10 |
+
|
11 |
+
def predict(image1, image2, text):
|
12 |
+
encoding_1 = processor(image1, text, return_tensors="pt")
|
13 |
+
encoding_2 = processor(image2, text, return_tensors="pt")
|
14 |
+
|
15 |
+
# forward pass
|
16 |
+
with torch.no_grad():
|
17 |
+
outputs = model(input_ids=encoding_1.input_ids, pixel_values=encoding_1.pixel_values, pixel_values_2=encoding_2.pixel_values)
|
18 |
+
|
19 |
+
logits = outputs.logits
|
20 |
+
idx = logits.argmax(-1).item()
|
21 |
+
predicted_answer = model.config.id2label[idx]
|
22 |
+
|
23 |
+
return predicted_answer
|
24 |
+
|
25 |
+
images = [gr.inputs.Image(type="pil"), gr.inputs.Image(type="pil")]
|
26 |
+
text = gr.inputs.Textbox(lines=2, label="Sentence")
|
27 |
+
answer = gr.outputs.Textbox(label="Predicted answer")
|
28 |
+
|
29 |
+
example_sentence = "The left image contains twice the number of dogs as the right image, and at least two dogs in total are standing."
|
30 |
+
examples = [["image1.jpg", "image2.jpg", example_sentence]]
|
31 |
+
|
32 |
+
title = "Interactive demo: natural language visual reasoning with ViLT"
|
33 |
+
description = "Gradio Demo for ViLT (Vision and Language Transformer), fine-tuned on NLVR2. To use it, simply upload a pair of images and type a sentence and click 'submit', or click one of the examples to load them. The model will predict whether the sentence is true or false, based on the 2 images. Read more at the links below."
|
34 |
+
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2102.03334' target='_blank'>ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision</a> | <a href='https://github.com/dandelin/ViLT' target='_blank'>Github Repo</a></p>"
|
35 |
+
|
36 |
+
interface = gr.Interface(fn=predict,
|
37 |
+
inputs=images + [text],
|
38 |
+
outputs=answer,
|
39 |
+
examples=examples,
|
40 |
+
title=title,
|
41 |
+
description=description,
|
42 |
+
article=article,
|
43 |
+
enable_queue=True)
|
44 |
+
interface.launch(debug=True)
|