predict.py 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """
  2. Download the weights in ./checkpoints beforehand for fast inference
  3. wget https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model*_base_caption.pth
  4. wget https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model*_vqa.pth
  5. wget https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth
  6. """
  7. from pathlib import Path
  8. from PIL import Image
  9. import torch
  10. from torchvision import transforms
  11. from torchvision.transforms.functional import InterpolationMode
  12. import cog
  13. from models.blip import blip_decoder
  14. from models.blip_vqa import blip_vqa
  15. from models.blip_itm import blip_itm
  16. class Predictor(cog.Predictor):
  17. def setup(self):
  18. self.device = "cuda:0"
  19. self.models = {
  20. 'image_captioning': blip_decoder(pretrained='checkpoints/model*_base_caption.pth',
  21. image_size=384, vit='base'),
  22. 'visual_question_answering': blip_vqa(pretrained='checkpoints/model*_vqa.pth',
  23. image_size=480, vit='base'),
  24. 'image_text_matching': blip_itm(pretrained='checkpoints/model_base_retrieval_coco.pth',
  25. image_size=384, vit='base')
  26. }
  27. @cog.input(
  28. "image",
  29. type=Path,
  30. help="input image",
  31. )
  32. @cog.input(
  33. "task",
  34. type=str,
  35. default='image_captioning',
  36. options=['image_captioning', 'visual_question_answering', 'image_text_matching'],
  37. help="Choose a task.",
  38. )
  39. @cog.input(
  40. "question",
  41. type=str,
  42. default=None,
  43. help="Type question for the input image for visual question answering task.",
  44. )
  45. @cog.input(
  46. "caption",
  47. type=str,
  48. default=None,
  49. help="Type caption for the input image for image text matching task.",
  50. )
  51. def predict(self, image, task, question, caption):
  52. if task == 'visual_question_answering':
  53. assert question is not None, 'Please type a question for visual question answering task.'
  54. if task == 'image_text_matching':
  55. assert caption is not None, 'Please type a caption for mage text matching task.'
  56. im = load_image(image, image_size=480 if task == 'visual_question_answering' else 384, device=self.device)
  57. model = self.models[task]
  58. model.eval()
  59. model = model.to(self.device)
  60. if task == 'image_captioning':
  61. with torch.no_grad():
  62. caption = model.generate(im, sample=False, num_beams=3, max_length=20, min_length=5)
  63. return 'Caption: ' + caption[0]
  64. if task == 'visual_question_answering':
  65. with torch.no_grad():
  66. answer = model(im, question, train=False, inference='generate')
  67. return 'Answer: ' + answer[0]
  68. # image_text_matching
  69. itm_output = model(im, caption, match_head='itm')
  70. itm_score = torch.nn.functional.softmax(itm_output, dim=1)[:, 1]
  71. itc_score = model(im, caption, match_head='itc')
  72. return f'The image and text is matched with a probability of {itm_score.item():.4f}.\n' \
  73. f'The image feature and text feature has a cosine similarity of {itc_score.item():.4f}.'
  74. def load_image(image, image_size, device):
  75. raw_image = Image.open(str(image)).convert('RGB')
  76. w, h = raw_image.size
  77. transform = transforms.Compose([
  78. transforms.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC),
  79. transforms.ToTensor(),
  80. transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
  81. ])
  82. image = transform(raw_image).unsqueeze(0).to(device)
  83. return image