image_captioning.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. from typing import Any, Dict
  3. import torch
  4. from torchvision import transforms
  5. from modelscope.utils.constant import ModeKeys
  6. from .base import OfaBasePreprocessor
  7. class OfaImageCaptioningPreprocessor(OfaBasePreprocessor):
  8. r"""
  9. OFA preprocessor for image captioning task.
  10. """
  11. def __init__(self,
  12. cfg,
  13. model_dir,
  14. mode=ModeKeys.INFERENCE,
  15. *args,
  16. **kwargs):
  17. """preprocess the data
  18. Args:
  19. cfg(modelscope.utils.config.ConfigDict) : model config
  20. model_dir (str): model path,
  21. mode: preprocessor mode (model mode)
  22. """
  23. super(OfaImageCaptioningPreprocessor,
  24. self).__init__(cfg, model_dir, mode, *args, **kwargs)
  25. # Initialize transform
  26. self.patch_resize_transform = transforms.Compose([
  27. lambda image: image.convert('RGB'),
  28. transforms.Resize(
  29. (self.patch_image_size, self.patch_image_size),
  30. interpolation=transforms.InterpolationMode.BICUBIC),
  31. transforms.ToTensor(),
  32. transforms.Normalize(mean=self.mean, std=self.std),
  33. ])
  34. def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
  35. if self.mode == ModeKeys.TRAIN:
  36. return self._build_train_sample(data)
  37. else:
  38. return self._build_infer_sample(data)
  39. def _build_train_sample(self, data: Dict[str, Any]) -> Dict[str, Any]:
  40. r"""
  41. Building training samples.
  42. step 1. Preprocess the data using the logic of `_build_infer_sample`
  43. and make sure the label data in the result.
  44. step 2. Preprocess the label data. Contains:
  45. - remove tokens within `!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~` and tripe
  46. - tokenize the label as `target` value without `bos` token.
  47. - add `bos` token and remove `eos` token of `target` as `prev_output_tokens`.
  48. Args:
  49. data (`Dict[str, Any]`): Input data, should contains the key of `image`, `prompt`
  50. and `label`, `image` refers the image input data, `prompt` refers the text
  51. input data the `label` is the supervised data for training.
  52. Return:
  53. A dict object, contains source, image, mask, label, target tokens,
  54. and previous output tokens data.
  55. """
  56. sample = self._build_infer_sample(data)
  57. target = sample['label']
  58. target = target.translate(self.transtab).strip()
  59. target_token_list = target.strip().split()
  60. target = ' '.join(target_token_list[:self.max_tgt_length])
  61. sample['target'] = self.tokenize_text(target, add_bos=False)
  62. sample['prev_output_tokens'] = torch.cat(
  63. [self.bos_item, sample['target'][:-1]])
  64. return sample
  65. def _build_infer_sample(self, data: Dict[str, Any]) -> Dict[str, Any]:
  66. r"""
  67. Building inference samples.
  68. step 1. Get the pillow image.
  69. step 2. Do some transforms for the pillow image as the image input,
  70. such as resize, normalize, to tensor etc.
  71. step 3. Tokenize the prompt as text input.
  72. step 4. Determine Whether or not to add labels to the sample.
  73. Args:
  74. data (`Dict[str, Any]`): Input data, should contains the key of `image` and `prompt`,
  75. the former refers the image input data, and the later refers the text input data.
  76. Return:
  77. A dict object, contains source, image, mask and label data.
  78. """
  79. image = self.get_img_pil(data[self.column_map['image']])
  80. patch_image = self.patch_resize_transform(image)
  81. prompt = self.cfg.model.get('prompt', ' what does the image describe?')
  82. inputs = self.tokenize_text(prompt)
  83. sample = {
  84. 'source': inputs,
  85. 'patch_image': patch_image,
  86. 'patch_mask': torch.tensor([True])
  87. }
  88. if 'text' in self.column_map and self.column_map['text'] in data:
  89. sample['label'] = data[self.column_map['text']]
  90. return sample