from models.blip_vqa import blip_vqa
import requests
import torch
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
from PIL import Image
from IPython.display import display
import argparse
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def load_demo_image(image_size, device):
img_url = 'https://prod-ai-talk.oss-cn-beijing.aliyuncs.com/test/AI/yinxingshu.jpeg'
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert('RGB')
w, h = raw_image.size
display(raw_image.resize((w // 5, h // 5)))
transform = transforms.Compose([
transforms.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC),
transforms.ToTensor(),
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
])
image = transform(raw_image).unsqueeze(0).to(device)
return image
# 设置命令行参数
parser = argparse.ArgumentParser()
parser.add_argument('--model_url', type=str, default='https://prod-ai-talk.oss-cn-beijing.aliyuncs.com/test/AI/model_base_vqa_capfilt_large.pth')
parser.add_argument('--question', type=str, default='How many cats, what color are the cats?')
args = parser.parse_args()
image_size = 480
image = load_demo_image(image_size=image_size, device=device)
model_url = args.model_url
question = args.question
model = blip_vqa(pretrained=model_url, image_size=image_size, vit='base')
model.eval()
model = model.to(device)
with torch.no_grad():
answer = model(image, question, train=False, inference='generate')
print('answer: ' + answer[0])