processing_altclip.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # coding=utf-8
  2. # Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang The HuggingFace Inc. 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 AltCLIP
  17. """
  18. from typing import List, 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. from ...utils.deprecation import deprecate_kwarg
  23. class AltClipProcessorKwargs(ProcessingKwargs, total=False):
  24. _defaults = {}
  25. class AltCLIPProcessor(ProcessorMixin):
  26. r"""
  27. Constructs a AltCLIP processor which wraps a CLIP image processor and a XLM-Roberta tokenizer into a single
  28. processor.
  29. [`AltCLIPProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`XLMRobertaTokenizerFast`]. See
  30. the [`~AltCLIPProcessor.__call__`] and [`~AltCLIPProcessor.decode`] for more information.
  31. Args:
  32. image_processor ([`CLIPImageProcessor`], *optional*):
  33. The image processor is a required input.
  34. tokenizer ([`XLMRobertaTokenizerFast`], *optional*):
  35. The tokenizer is a required input.
  36. """
  37. attributes = ["image_processor", "tokenizer"]
  38. image_processor_class = "CLIPImageProcessor"
  39. tokenizer_class = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
  40. @deprecate_kwarg(old_name="feature_extractor", version="5.0.0", new_name="image_processor")
  41. def __init__(self, image_processor=None, tokenizer=None):
  42. if image_processor is None:
  43. raise ValueError("You need to specify an `image_processor`.")
  44. if tokenizer is None:
  45. raise ValueError("You need to specify a `tokenizer`.")
  46. super().__init__(image_processor, tokenizer)
  47. def __call__(
  48. self,
  49. images: ImageInput = None,
  50. text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
  51. audio=None,
  52. videos=None,
  53. **kwargs: Unpack[AltClipProcessorKwargs],
  54. ) -> BatchEncoding:
  55. """
  56. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  57. and `kwargs` arguments to XLMRobertaTokenizerFast's [`~XLMRobertaTokenizerFast.__call__`] if `text` is not
  58. `None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
  59. CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
  60. of the above two methods for more information.
  61. Args:
  62. images (`ImageInput`):
  63. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  64. tensor. Both channels-first and channels-last formats are supported.
  65. text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
  66. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  67. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  68. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  69. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  70. If set, will return tensors of a particular framework. Acceptable values are:
  71. - `'tf'`: Return TensorFlow `tf.constant` objects.
  72. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  73. - `'np'`: Return NumPy `np.ndarray` objects.
  74. - `'jax'`: Return JAX `jnp.ndarray` objects.
  75. Returns:
  76. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  77. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  78. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  79. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  80. `None`).
  81. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  82. """
  83. if text is None and images is None:
  84. raise ValueError("You must specify either text or images.")
  85. if text is None and images is None:
  86. raise ValueError("You must specify either text or images.")
  87. output_kwargs = self._merge_kwargs(
  88. AltClipProcessorKwargs,
  89. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  90. **kwargs,
  91. )
  92. if text is not None:
  93. encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
  94. if images is not None:
  95. image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
  96. # BC for explicit return_tensors
  97. if "return_tensors" in output_kwargs["common_kwargs"]:
  98. return_tensors = output_kwargs["common_kwargs"].pop("return_tensors", None)
  99. if text is not None and images is not None:
  100. encoding["pixel_values"] = image_features.pixel_values
  101. return encoding
  102. elif text is not None:
  103. return encoding
  104. else:
  105. return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
  106. def batch_decode(self, *args, **kwargs):
  107. """
  108. This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`].
  109. Please refer to the docstring of this method for more information.
  110. """
  111. return self.tokenizer.batch_decode(*args, **kwargs)
  112. def decode(self, *args, **kwargs):
  113. """
  114. This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please
  115. refer to the docstring of this method for more information.
  116. """
  117. return self.tokenizer.decode(*args, **kwargs)
  118. @property
  119. def model_input_names(self):
  120. tokenizer_input_names = self.tokenizer.model_input_names
  121. image_processor_input_names = self.image_processor.model_input_names
  122. return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
  123. __all__ = ["AltCLIPProcessor"]