File size: 2,210 Bytes
2773523
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import gradio as gr
from transformers import AutoProcessor, AutoModelForCausalLM, BlipForConditionalGeneration
import torch

torch.hub.download_url_to_file('http://images.cocodataset.org/val2017/000000039769.jpg', 'cats.jpg')

git_processor = AutoProcessor.from_pretrained("microsoft/git-base-coco")
git_model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-coco")

blip_processor = AutoProcessor.from_pretrained("Salesfoce/blip-image-captioning-base")
blip_model = BlipForConditionalGeneration.from_pretrained("Salesfoce/blip-image-captioning-base")

def generate_caption(processor, model, image):
    inputs = processor(image=image, return_tensors="pt")
    
    generated_ids = model.generate(pixel_values=pixel_values, max_length=50)
     
    generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
   
    return generated_caption


def generate_captions(image):
    caption_git = generate_caption(git_processor, git_model, image)

    caption_blip = generate_caption(blip_processor, blip_model, image)

    return caption_git, caption_blip

   
examples = [["cats.jpg"]]

title = "Interactive demo: ViLT"
description = "Gradio Demo for ViLT (Vision and Language Transformer), fine-tuned on VQAv2, a model that can answer questions from images. To use it, simply upload your image and type a question and click 'submit', or click one of the examples to load them. Read more at the links below."
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>"

interface = gr.Interface(fn=answer_question, 
                         inputs=gr.inputs.Image(type="pil"),
                         outputs=[gr.outputs.Textbox(label="Generated caption by GIT"), gr.outputs.Textbox(label="Generated caption by BLIP")], 
                         examples=examples, 
                         title=title,
                         description=description,
                         article=article, 
                         enable_queue=True)
interface.launch(debug=True)