processing_blip.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 List, 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. valid_kwargs = []
  50. image_processor_class = "BlipImageProcessor"
  51. tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
  52. def __init__(self, image_processor, tokenizer, **kwargs):
  53. tokenizer.return_token_type_ids = False
  54. super().__init__(image_processor, tokenizer)
  55. self.current_processor = self.image_processor
  56. def __call__(
  57. self,
  58. images: ImageInput = None,
  59. text: Optional[Union[str, List[str], TextInput, PreTokenizedInput]] = None,
  60. audio=None,
  61. videos=None,
  62. **kwargs: Unpack[BlipProcessorKwargs],
  63. ) -> BatchEncoding:
  64. """
  65. This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
  66. [`BertTokenizerFast.__call__`] to prepare text for the model.
  67. Please refer to the docstring of the above two methods for more information.
  68. Args:
  69. images (`ImageInput`):
  70. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  71. tensor. Both channels-first and channels-last formats are supported.
  72. text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
  73. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  74. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  75. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  76. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  77. If set, will return tensors of a particular framework. Acceptable values are:
  78. - `'tf'`: Return TensorFlow `tf.constant` objects.
  79. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  80. - `'np'`: Return NumPy `np.ndarray` objects.
  81. - `'jax'`: Return JAX `jnp.ndarray` objects.
  82. """
  83. if images is None and text is None:
  84. raise ValueError("You have to specify either images or text.")
  85. text_encoding = None
  86. # add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
  87. # else, return the text encoding.
  88. output_kwargs = self._merge_kwargs(
  89. BlipProcessorKwargs,
  90. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  91. **kwargs,
  92. )
  93. if text is not None:
  94. text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
  95. if images is not None:
  96. encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
  97. if text_encoding is not None:
  98. encoding_image_processor.update(text_encoding)
  99. return encoding_image_processor
  100. return text_encoding
  101. def batch_decode(self, *args, **kwargs):
  102. """
  103. This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  104. refer to the docstring of this method for more information.
  105. """
  106. return self.tokenizer.batch_decode(*args, **kwargs)
  107. def decode(self, *args, **kwargs):
  108. """
  109. This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  110. the docstring of this method for more information.
  111. """
  112. return self.tokenizer.decode(*args, **kwargs)
  113. @property
  114. def model_input_names(self):
  115. tokenizer_input_names = self.tokenizer.model_input_names
  116. image_processor_input_names = self.image_processor.model_input_names
  117. return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))