processing_blip.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # coding=utf-8
  2. # Copyright 2022 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """
  16. Processor class for Blip.
  17. """
  18. from typing import Optional, Union
  19. from ...image_utils import ImageInput
  20. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  21. from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
  22. class BlipProcessorKwargs(ProcessingKwargs, total=False):
  23. _defaults = {
  24. "text_kwargs": {
  25. "add_special_tokens": True,
  26. "padding": False,
  27. "stride": 0,
  28. "return_overflowing_tokens": False,
  29. "return_special_tokens_mask": False,
  30. "return_offsets_mapping": False,
  31. "return_token_type_ids": False,
  32. "return_length": False,
  33. "verbose": True,
  34. },
  35. "images_kwargs": {},
  36. }
  37. class BlipProcessor(ProcessorMixin):
  38. r"""
  39. Constructs a BLIP processor which wraps a BERT tokenizer and BLIP image processor into a single processor.
  40. [`BlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`BertTokenizerFast`]. See the
  41. docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
  42. Args:
  43. image_processor (`BlipImageProcessor`):
  44. An instance of [`BlipImageProcessor`]. The image processor is a required input.
  45. tokenizer (`BertTokenizerFast`):
  46. An instance of ['BertTokenizerFast`]. The tokenizer is a required input.
  47. """
  48. attributes = ["image_processor", "tokenizer"]
  49. image_processor_class = ("BlipImageProcessor", "BlipImageProcessorFast")
  50. tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
  51. def __init__(self, image_processor, tokenizer, **kwargs):
  52. tokenizer.return_token_type_ids = False
  53. super().__init__(image_processor, tokenizer)
  54. self.current_processor = self.image_processor
  55. def __call__(
  56. self,
  57. images: Optional[ImageInput] = None,
  58. text: Optional[Union[str, list[str], TextInput, PreTokenizedInput]] = None,
  59. audio=None,
  60. videos=None,
  61. **kwargs: Unpack[BlipProcessorKwargs],
  62. ) -> BatchEncoding:
  63. """
  64. This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
  65. [`BertTokenizerFast.__call__`] to prepare text for the model.
  66. Please refer to the docstring of the above two methods for more information.
  67. Args:
  68. images (`ImageInput`):
  69. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  70. tensor. Both channels-first and channels-last formats are supported.
  71. text (`TextInput`, `PreTokenizedInput`, `list[TextInput]`, `list[PreTokenizedInput]`):
  72. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  73. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  74. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  75. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  76. If set, will return tensors of a particular framework. Acceptable values are:
  77. - `'tf'`: Return TensorFlow `tf.constant` objects.
  78. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  79. - `'np'`: Return NumPy `np.ndarray` objects.
  80. - `'jax'`: Return JAX `jnp.ndarray` objects.
  81. """
  82. if images is None and text is None:
  83. raise ValueError("You have to specify either images or text.")
  84. text_encoding = None
  85. # add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
  86. # else, return the text encoding.
  87. output_kwargs = self._merge_kwargs(
  88. BlipProcessorKwargs,
  89. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  90. **kwargs,
  91. )
  92. if text is not None:
  93. text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
  94. if images is not None:
  95. encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
  96. if text_encoding is not None:
  97. encoding_image_processor.update(text_encoding)
  98. return encoding_image_processor
  99. return text_encoding
  100. @property
  101. def model_input_names(self):
  102. tokenizer_input_names = self.tokenizer.model_input_names
  103. image_processor_input_names = self.image_processor.model_input_names
  104. tokenizer_input_names = [name for name in tokenizer_input_names if name != "token_type_ids"]
  105. return tokenizer_input_names + image_processor_input_names
  106. __all__ = ["BlipProcessor"]