File size: 1,521 Bytes
914a76b
 
 
 
 
 
 
 
 
 
f43b206
914a76b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f43b206
914a76b
 
 
f43b206
914a76b
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import AutoProcessor, AutoTokenizer, AutoImageProcessor, AutoModelForCausalLM, BlipForConditionalGeneration, VisionEncoderDecoderModel
import torch

git_processor_base = AutoProcessor.from_pretrained("microsoft/git-base-coco")
git_model_base = AutoModelForCausalLM.from_pretrained("microsoft/git-base-coco")

device = "cuda" if torch.cuda.is_available() else "cpu"

git_model_base.to(device)


def generate_caption(processor, model, image, tokenizer=None):
    inputs = processor(images=image, return_tensors="pt").to(device)
    
    generated_ids = model.generate(pixel_values=inputs.pixel_values, max_length=50)

    if tokenizer is not None:
        generated_caption = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
    else:
        generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
   
    return generated_caption


def generate_captions(image):
    caption_git_base = generate_caption(git_processor_base, git_model_base, image)

    return caption_git_base

   
examples = [["test-1.jpeg"], ["test-2.jpeg"], ["test-3.jpeg"], ["test-4.jpeg"], ["test-5.jpeg"], ["test-6.jpg"]]
outputs = [gr.outputs.Textbox(label="Caption generated by GIT-base")] 


interface = gr.Interface(fn=generate_captions, 
                         inputs=gr.inputs.Image(type="pil"),
                         outputs=outputs,
                         examples=examples,  
                         enable_queue=True)
interface.launch(debug=True)