|
from PIL import Image |
|
import os |
|
import requests |
|
import torch |
|
from torchvision import transforms |
|
from torchvision.transforms.functional import InterpolationMode |
|
|
|
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
|
|
|
|
|
import gradio as gr |
|
|
|
from models.blip_vqa import blip_vqa |
|
|
|
image_size_vq = 480 |
|
transform_vq = transforms.Compose([ |
|
transforms.Resize((image_size_vq,image_size_vq),interpolation=InterpolationMode.BICUBIC), |
|
transforms.ToTensor(), |
|
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) |
|
]) |
|
|
|
model_url_vq = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model*_vqa.pth' |
|
|
|
model_vq = blip_vqa(pretrained=model_url_vq, image_size=480, vit='base') |
|
model_vq.eval() |
|
model_vq = model_vq.to(device) |
|
|
|
|
|
|
|
def inference(raw_image, question, mnlen, mxlen, token): |
|
if token != os.environ["TOKEN"]: |
|
return "Rong token" |
|
image_vq = transform_vq(raw_image).unsqueeze(0).to(device) |
|
with torch.no_grad(): |
|
answer = model_vq(image_vq, question, train=False, inference='generate', mina_len=mnlen, maxa_len=mxlen) |
|
return 'answer: '+answer[0] |
|
|
|
inputs = [gr.Image(type='pil'), |
|
gr.Textbox(lines=2, label="Question"), |
|
gr.Number(value=1, label="Min length", precision=0), |
|
gr.Number(value=10, label="Max length", precision=0), |
|
gr.Textbox(lines=1, label="Auth token")] |
|
|
|
outputs = gr.outputs.Textbox(label="Output") |
|
|
|
title = "BLIP" |
|
|
|
description = "Gradio endpoint for spuun's BLIP (Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation (Salesforce Research)). To use it you need to obtain a token from me :) Read more at the links below." |
|
|
|
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2201.12086' target='_blank'>BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation</a> | <a href='https://github.com/salesforce/BLIP' target='_blank'>Github Repo</a></p>" |
|
|
|
gr.Interface(inference, inputs, outputs, title=title, description=description, article=article).launch() |