processing_git.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 GIT
  17. """
  18. from typing import List, Optional, Union
  19. from ...feature_extraction_utils import BatchFeature
  20. from ...image_utils import ImageInput
  21. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, _validate_images_text_input_order
  22. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  23. class GitProcessorKwargs(ProcessingKwargs, total=False):
  24. _defaults = {}
  25. class GitProcessor(ProcessorMixin):
  26. r"""
  27. Constructs a GIT processor which wraps a CLIP image processor and a BERT tokenizer into a single processor.
  28. [`GitProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`BertTokenizerFast`]. See the
  29. [`~GitProcessor.__call__`] and [`~GitProcessor.decode`] for more information.
  30. Args:
  31. image_processor ([`AutoImageProcessor`]):
  32. The image processor is a required input.
  33. tokenizer ([`AutoTokenizer`]):
  34. The tokenizer is a required input.
  35. """
  36. attributes = ["image_processor", "tokenizer"]
  37. image_processor_class = "AutoImageProcessor"
  38. tokenizer_class = "AutoTokenizer"
  39. def __init__(self, image_processor, tokenizer):
  40. super().__init__(image_processor, tokenizer)
  41. self.current_processor = self.image_processor
  42. def __call__(
  43. self,
  44. images: Optional[ImageInput] = None,
  45. text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
  46. audio=None,
  47. videos=None,
  48. **kwargs: Unpack[GitProcessorKwargs],
  49. ) -> BatchFeature:
  50. """
  51. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  52. and `kwargs` arguments to BertTokenizerFast's [`~BertTokenizerFast.__call__`] if `text` is not `None` to encode
  53. the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
  54. CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
  55. of the above two methods for more information.
  56. Args:
  57. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
  58. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  59. tensor. Both channels-first and channels-last formats are supported.
  60. text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`, *optional*):
  61. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  62. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  63. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  64. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  65. If set, will return tensors of a particular framework. Acceptable values are:
  66. - `'tf'`: Return TensorFlow `tf.constant` objects.
  67. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  68. - `'np'`: Return NumPy `np.ndarray` objects.
  69. - `'jax'`: Return JAX `jnp.ndarray` objects.
  70. Returns:
  71. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  72. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  73. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  74. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  75. `None`).
  76. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  77. """
  78. if text is None and images is None:
  79. raise ValueError("You have to specify either text or images. Both cannot be none.")
  80. # check if images and text inputs are reversed for BC
  81. images, text = _validate_images_text_input_order(images, text)
  82. output_kwargs = self._merge_kwargs(
  83. GitProcessorKwargs,
  84. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  85. **kwargs,
  86. )
  87. data = {}
  88. if text is not None:
  89. text_features = self.tokenizer(text, **output_kwargs["text_kwargs"])
  90. data.update(text_features)
  91. if images is not None:
  92. image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
  93. data.update(image_features)
  94. return BatchFeature(data=data, tensor_type=output_kwargs["common_kwargs"].get("return_tensors"))
  95. def batch_decode(self, *args, **kwargs):
  96. """
  97. This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  98. refer to the docstring of this method for more information.
  99. """
  100. return self.tokenizer.batch_decode(*args, **kwargs)
  101. def decode(self, *args, **kwargs):
  102. """
  103. This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  104. the docstring of this method for more information.
  105. """
  106. return self.tokenizer.decode(*args, **kwargs)
  107. @property
  108. def model_input_names(self):
  109. return ["input_ids", "attention_mask", "pixel_values"]