processing_flava.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # coding=utf-8
  2. # Copyright 2022 Meta Platforms authors and The HuggingFace Team. All rights reserved.
  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. Image/Text processor class for FLAVA
  17. """
  18. import warnings
  19. from typing import List, Optional, Union
  20. from ...image_utils import ImageInput
  21. from ...processing_utils import ProcessorMixin
  22. from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
  23. from ...utils import TensorType
  24. class FlavaProcessor(ProcessorMixin):
  25. r"""
  26. Constructs a FLAVA processor which wraps a FLAVA image processor and a FLAVA tokenizer into a single processor.
  27. [`FlavaProcessor`] offers all the functionalities of [`FlavaImageProcessor`] and [`BertTokenizerFast`]. See the
  28. [`~FlavaProcessor.__call__`] and [`~FlavaProcessor.decode`] for more information.
  29. Args:
  30. image_processor ([`FlavaImageProcessor`], *optional*): The image processor is a required input.
  31. tokenizer ([`BertTokenizerFast`], *optional*): The tokenizer is a required input.
  32. """
  33. attributes = ["image_processor", "tokenizer"]
  34. image_processor_class = "FlavaImageProcessor"
  35. tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
  36. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  37. feature_extractor = None
  38. if "feature_extractor" in kwargs:
  39. warnings.warn(
  40. "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
  41. " instead.",
  42. FutureWarning,
  43. )
  44. feature_extractor = kwargs.pop("feature_extractor")
  45. image_processor = image_processor if image_processor is not None else feature_extractor
  46. if image_processor is None:
  47. raise ValueError("You need to specify an `image_processor`.")
  48. if tokenizer is None:
  49. raise ValueError("You need to specify a `tokenizer`.")
  50. super().__init__(image_processor, tokenizer)
  51. self.current_processor = self.image_processor
  52. def __call__(
  53. self,
  54. images: Optional[ImageInput] = None,
  55. text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
  56. add_special_tokens: bool = True,
  57. padding: Union[bool, str, PaddingStrategy] = False,
  58. truncation: Union[bool, str, TruncationStrategy] = False,
  59. max_length: Optional[int] = None,
  60. stride: int = 0,
  61. pad_to_multiple_of: Optional[int] = None,
  62. return_image_mask: Optional[bool] = None,
  63. return_codebook_pixels: Optional[bool] = None,
  64. return_token_type_ids: Optional[bool] = None,
  65. return_attention_mask: Optional[bool] = None,
  66. return_overflowing_tokens: bool = False,
  67. return_special_tokens_mask: bool = False,
  68. return_offsets_mapping: bool = False,
  69. return_length: bool = False,
  70. verbose: bool = True,
  71. return_tensors: Optional[Union[str, TensorType]] = None,
  72. **kwargs,
  73. ):
  74. """
  75. This method uses [`FlavaImageProcessor.__call__`] method to prepare image(s) for the model, and
  76. [`BertTokenizerFast.__call__`] to prepare text for the model.
  77. Please refer to the docstring of the above two methods for more information.
  78. """
  79. if text is None and images is None:
  80. raise ValueError("You have to specify either text or images. Both cannot be none.")
  81. if text is not None:
  82. encoding = self.tokenizer(
  83. text=text,
  84. add_special_tokens=add_special_tokens,
  85. padding=padding,
  86. truncation=truncation,
  87. max_length=max_length,
  88. stride=stride,
  89. pad_to_multiple_of=pad_to_multiple_of,
  90. return_token_type_ids=return_token_type_ids,
  91. return_attention_mask=return_attention_mask,
  92. return_overflowing_tokens=return_overflowing_tokens,
  93. return_special_tokens_mask=return_special_tokens_mask,
  94. return_offsets_mapping=return_offsets_mapping,
  95. return_length=return_length,
  96. verbose=verbose,
  97. return_tensors=return_tensors,
  98. **kwargs,
  99. )
  100. if images is not None:
  101. image_features = self.image_processor(
  102. images,
  103. return_image_mask=return_image_mask,
  104. return_codebook_pixels=return_codebook_pixels,
  105. return_tensors=return_tensors,
  106. **kwargs,
  107. )
  108. if text is not None and images is not None:
  109. encoding.update(image_features)
  110. return encoding
  111. elif text is not None:
  112. return encoding
  113. else:
  114. return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
  115. def batch_decode(self, *args, **kwargs):
  116. """
  117. This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  118. refer to the docstring of this method for more information.
  119. """
  120. return self.tokenizer.batch_decode(*args, **kwargs)
  121. def decode(self, *args, **kwargs):
  122. """
  123. This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  124. the docstring of this method for more information.
  125. """
  126. return self.tokenizer.decode(*args, **kwargs)
  127. @property
  128. def model_input_names(self):
  129. tokenizer_input_names = self.tokenizer.model_input_names
  130. image_processor_input_names = self.image_processor.model_input_names
  131. return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
  132. @property
  133. def feature_extractor_class(self):
  134. warnings.warn(
  135. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  136. FutureWarning,
  137. )
  138. return self.image_processor_class
  139. @property
  140. def feature_extractor(self):
  141. warnings.warn(
  142. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  143. FutureWarning,
  144. )
  145. return self.image_processor