processing_clipseg.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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", "ViTImageProcessorFast")
  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. super().__init__(image_processor, tokenizer)
  46. def __call__(self, text=None, images=None, visual_prompt=None, return_tensors=None, **kwargs):
  47. """
  48. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  49. and `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode
  50. the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
  51. ViTImageProcessor's [`~ViTImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring of
  52. the above two methods for more information.
  53. Args:
  54. text (`str`, `list[str]`, `list[list[str]]`):
  55. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  56. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  57. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  58. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  59. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  60. tensor. Both channels-first and channels-last formats are supported.
  61. visual_prompt (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  62. The visual prompt image or batch of images to be prepared. Each visual prompt image can be a PIL image,
  63. NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape
  64. (C, H, W), where C is a number of channels, H and W are image height and width.
  65. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  66. If set, will return tensors of a particular framework. Acceptable values are:
  67. - `'tf'`: Return TensorFlow `tf.constant` objects.
  68. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  69. - `'np'`: Return NumPy `np.ndarray` objects.
  70. - `'jax'`: Return JAX `jnp.ndarray` objects.
  71. Returns:
  72. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  73. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  74. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  75. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  76. `None`).
  77. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  78. """
  79. if text is None and visual_prompt is None and images is None:
  80. raise ValueError("You have to specify either text, visual prompt or images.")
  81. if text is not None and visual_prompt is not None:
  82. raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt.")
  83. if text is not None:
  84. encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
  85. if visual_prompt is not None:
  86. prompt_features = self.image_processor(visual_prompt, return_tensors=return_tensors, **kwargs)
  87. if images is not None:
  88. image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
  89. if visual_prompt is not None and images is not None:
  90. encoding = {
  91. "pixel_values": image_features.pixel_values,
  92. "conditional_pixel_values": prompt_features.pixel_values,
  93. }
  94. return encoding
  95. elif text is not None and images is not None:
  96. encoding["pixel_values"] = image_features.pixel_values
  97. return encoding
  98. elif text is not None:
  99. return encoding
  100. elif visual_prompt is not None:
  101. encoding = {
  102. "conditional_pixel_values": prompt_features.pixel_values,
  103. }
  104. return encoding
  105. else:
  106. return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
  107. @property
  108. def feature_extractor_class(self):
  109. warnings.warn(
  110. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  111. FutureWarning,
  112. )
  113. return self.image_processor_class
  114. @property
  115. def feature_extractor(self):
  116. warnings.warn(
  117. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  118. FutureWarning,
  119. )
  120. return self.image_processor
  121. __all__ = ["CLIPSegProcessor"]