processing_clipseg.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. Image/Text processor class for CLIPSeg
  17. """
  18. import warnings
  19. from ...processing_utils import ProcessorMixin
  20. from ...tokenization_utils_base import BatchEncoding
  21. class CLIPSegProcessor(ProcessorMixin):
  22. r"""
  23. Constructs a CLIPSeg processor which wraps a CLIPSeg image processor and a CLIP tokenizer into a single processor.
  24. [`CLIPSegProcessor`] offers all the functionalities of [`ViTImageProcessor`] and [`CLIPTokenizerFast`]. See the
  25. [`~CLIPSegProcessor.__call__`] and [`~CLIPSegProcessor.decode`] for more information.
  26. Args:
  27. image_processor ([`ViTImageProcessor`], *optional*):
  28. The image processor is a required input.
  29. tokenizer ([`CLIPTokenizerFast`], *optional*):
  30. The tokenizer is a required input.
  31. """
  32. attributes = ["image_processor", "tokenizer"]
  33. image_processor_class = "ViTImageProcessor"
  34. tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast")
  35. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  36. feature_extractor = None
  37. if "feature_extractor" in kwargs:
  38. warnings.warn(
  39. "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
  40. " instead.",
  41. FutureWarning,
  42. )
  43. feature_extractor = kwargs.pop("feature_extractor")
  44. image_processor = image_processor if image_processor is not None else feature_extractor
  45. if image_processor is None:
  46. raise ValueError("You need to specify an `image_processor`.")
  47. if tokenizer is None:
  48. raise ValueError("You need to specify a `tokenizer`.")
  49. super().__init__(image_processor, tokenizer)
  50. def __call__(self, text=None, images=None, visual_prompt=None, return_tensors=None, **kwargs):
  51. """
  52. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  53. and `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode
  54. the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
  55. ViTImageProcessor's [`~ViTImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring of
  56. the above two methods for more information.
  57. Args:
  58. text (`str`, `List[str]`, `List[List[str]]`):
  59. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  60. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  61. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  62. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
  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. visual_prompt (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
  66. The visual prompt image or batch of images to be prepared. Each visual prompt image can be a PIL image,
  67. NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape
  68. (C, H, W), where C is a number of channels, H and W are image height and width.
  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 visual_prompt is None and images is None:
  84. raise ValueError("You have to specify either text, visual prompt or images.")
  85. if text is not None and visual_prompt is not None:
  86. raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt.")
  87. if text is not None:
  88. encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
  89. if visual_prompt is not None:
  90. prompt_features = self.image_processor(visual_prompt, return_tensors=return_tensors, **kwargs)
  91. if images is not None:
  92. image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
  93. if visual_prompt is not None and images is not None:
  94. encoding = {
  95. "pixel_values": image_features.pixel_values,
  96. "conditional_pixel_values": prompt_features.pixel_values,
  97. }
  98. return encoding
  99. elif 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. elif visual_prompt is not None:
  105. encoding = {
  106. "conditional_pixel_values": prompt_features.pixel_values,
  107. }
  108. return encoding
  109. else:
  110. return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
  111. def batch_decode(self, *args, **kwargs):
  112. """
  113. This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  114. refer to the docstring of this method for more information.
  115. """
  116. return self.tokenizer.batch_decode(*args, **kwargs)
  117. def decode(self, *args, **kwargs):
  118. """
  119. This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  120. the docstring of this method for more information.
  121. """
  122. return self.tokenizer.decode(*args, **kwargs)
  123. @property
  124. def feature_extractor_class(self):
  125. warnings.warn(
  126. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  127. FutureWarning,
  128. )
  129. return self.image_processor_class
  130. @property
  131. def feature_extractor(self):
  132. warnings.warn(
  133. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  134. FutureWarning,
  135. )
  136. return self.image_processor