processing_owlvit.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 OWL-ViT
  17. """
  18. import warnings
  19. from typing import List
  20. import numpy as np
  21. from ...processing_utils import ProcessorMixin
  22. from ...tokenization_utils_base import BatchEncoding
  23. from ...utils import is_flax_available, is_tf_available, is_torch_available
  24. class OwlViTProcessor(ProcessorMixin):
  25. r"""
  26. Constructs an OWL-ViT processor which wraps [`OwlViTImageProcessor`] and [`CLIPTokenizer`]/[`CLIPTokenizerFast`]
  27. into a single processor that interits both the image processor and tokenizer functionalities. See the
  28. [`~OwlViTProcessor.__call__`] and [`~OwlViTProcessor.decode`] for more information.
  29. Args:
  30. image_processor ([`OwlViTImageProcessor`], *optional*):
  31. The image processor is a required input.
  32. tokenizer ([`CLIPTokenizer`, `CLIPTokenizerFast`], *optional*):
  33. The tokenizer is a required input.
  34. """
  35. attributes = ["image_processor", "tokenizer"]
  36. image_processor_class = "OwlViTImageProcessor"
  37. tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast")
  38. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  39. feature_extractor = None
  40. if "feature_extractor" in kwargs:
  41. warnings.warn(
  42. "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
  43. " instead.",
  44. FutureWarning,
  45. )
  46. feature_extractor = kwargs.pop("feature_extractor")
  47. image_processor = image_processor if image_processor is not None else feature_extractor
  48. if image_processor is None:
  49. raise ValueError("You need to specify an `image_processor`.")
  50. if tokenizer is None:
  51. raise ValueError("You need to specify a `tokenizer`.")
  52. super().__init__(image_processor, tokenizer)
  53. def __call__(self, text=None, images=None, query_images=None, padding="max_length", return_tensors="np", **kwargs):
  54. """
  55. Main method to prepare for the model one or several text(s) and image(s). This method forwards the `text` and
  56. `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode:
  57. the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
  58. CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
  59. of the above two methods for more information.
  60. Args:
  61. text (`str`, `List[str]`, `List[List[str]]`):
  62. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  63. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  64. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  65. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`,
  66. `List[torch.Tensor]`):
  67. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  68. tensor. Both channels-first and channels-last formats are supported.
  69. query_images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
  70. The query image to be prepared, one query image is expected per target image to be queried. Each image
  71. can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image
  72. should be of shape (C, H, W), where C is a number of channels, H and W are image height and width.
  73. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  74. If set, will return tensors of a particular framework. Acceptable values are:
  75. - `'tf'`: Return TensorFlow `tf.constant` objects.
  76. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  77. - `'np'`: Return NumPy `np.ndarray` objects.
  78. - `'jax'`: Return JAX `jnp.ndarray` objects.
  79. Returns:
  80. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  81. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  82. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  83. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  84. `None`).
  85. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  86. """
  87. if text is None and query_images is None and images is None:
  88. raise ValueError(
  89. "You have to specify at least one text or query image or image. All three cannot be none."
  90. )
  91. if text is not None:
  92. if isinstance(text, str) or (isinstance(text, List) and not isinstance(text[0], List)):
  93. encodings = [self.tokenizer(text, padding=padding, return_tensors=return_tensors, **kwargs)]
  94. elif isinstance(text, List) and isinstance(text[0], List):
  95. encodings = []
  96. # Maximum number of queries across batch
  97. max_num_queries = max([len(t) for t in text])
  98. # Pad all batch samples to max number of text queries
  99. for t in text:
  100. if len(t) != max_num_queries:
  101. t = t + [" "] * (max_num_queries - len(t))
  102. encoding = self.tokenizer(t, padding=padding, return_tensors=return_tensors, **kwargs)
  103. encodings.append(encoding)
  104. else:
  105. raise TypeError("Input text should be a string, a list of strings or a nested list of strings")
  106. if return_tensors == "np":
  107. input_ids = np.concatenate([encoding["input_ids"] for encoding in encodings], axis=0)
  108. attention_mask = np.concatenate([encoding["attention_mask"] for encoding in encodings], axis=0)
  109. elif return_tensors == "jax" and is_flax_available():
  110. import jax.numpy as jnp
  111. input_ids = jnp.concatenate([encoding["input_ids"] for encoding in encodings], axis=0)
  112. attention_mask = jnp.concatenate([encoding["attention_mask"] for encoding in encodings], axis=0)
  113. elif return_tensors == "pt" and is_torch_available():
  114. import torch
  115. input_ids = torch.cat([encoding["input_ids"] for encoding in encodings], dim=0)
  116. attention_mask = torch.cat([encoding["attention_mask"] for encoding in encodings], dim=0)
  117. elif return_tensors == "tf" and is_tf_available():
  118. import tensorflow as tf
  119. input_ids = tf.stack([encoding["input_ids"] for encoding in encodings], axis=0)
  120. attention_mask = tf.stack([encoding["attention_mask"] for encoding in encodings], axis=0)
  121. else:
  122. raise ValueError("Target return tensor type could not be returned")
  123. encoding = BatchEncoding()
  124. encoding["input_ids"] = input_ids
  125. encoding["attention_mask"] = attention_mask
  126. if query_images is not None:
  127. encoding = BatchEncoding()
  128. query_pixel_values = self.image_processor(
  129. query_images, return_tensors=return_tensors, **kwargs
  130. ).pixel_values
  131. encoding["query_pixel_values"] = query_pixel_values
  132. if images is not None:
  133. image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
  134. if text is not None and images is not None:
  135. encoding["pixel_values"] = image_features.pixel_values
  136. return encoding
  137. elif query_images is not None and images is not None:
  138. encoding["pixel_values"] = image_features.pixel_values
  139. return encoding
  140. elif text is not None or query_images is not None:
  141. return encoding
  142. else:
  143. return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
  144. def post_process(self, *args, **kwargs):
  145. """
  146. This method forwards all its arguments to [`OwlViTImageProcessor.post_process`]. Please refer to the docstring
  147. of this method for more information.
  148. """
  149. return self.image_processor.post_process(*args, **kwargs)
  150. def post_process_object_detection(self, *args, **kwargs):
  151. """
  152. This method forwards all its arguments to [`OwlViTImageProcessor.post_process_object_detection`]. Please refer
  153. to the docstring of this method for more information.
  154. """
  155. return self.image_processor.post_process_object_detection(*args, **kwargs)
  156. def post_process_image_guided_detection(self, *args, **kwargs):
  157. """
  158. This method forwards all its arguments to [`OwlViTImageProcessor.post_process_one_shot_object_detection`].
  159. Please refer to the docstring of this method for more information.
  160. """
  161. return self.image_processor.post_process_image_guided_detection(*args, **kwargs)
  162. def batch_decode(self, *args, **kwargs):
  163. """
  164. This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  165. refer to the docstring of this method for more information.
  166. """
  167. return self.tokenizer.batch_decode(*args, **kwargs)
  168. def decode(self, *args, **kwargs):
  169. """
  170. This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  171. the docstring of this method for more information.
  172. """
  173. return self.tokenizer.decode(*args, **kwargs)
  174. @property
  175. def feature_extractor_class(self):
  176. warnings.warn(
  177. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  178. FutureWarning,
  179. )
  180. return self.image_processor_class
  181. @property
  182. def feature_extractor(self):
  183. warnings.warn(
  184. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  185. FutureWarning,
  186. )
  187. return self.image_processor