processing_pix2struct.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # coding=utf-8
  2. # Copyright 2023 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. Processor class for Pix2Struct.
  17. """
  18. from typing import Optional, Union
  19. from ...feature_extraction_utils import BatchFeature
  20. from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
  21. from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
  22. from ...utils import logging
  23. class Pix2StructImagesKwargs(ImagesKwargs, total=False):
  24. max_patches: Optional[int]
  25. header_text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]]
  26. class Pix2StructProcessorKwargs(ProcessingKwargs, total=False):
  27. images_kwargs: Pix2StructImagesKwargs
  28. _defaults = {
  29. "text_kwargs": {
  30. "add_special_tokens": True,
  31. "padding": False,
  32. "stride": 0,
  33. "return_overflowing_tokens": False,
  34. "return_special_tokens_mask": False,
  35. "return_offsets_mapping": False,
  36. "return_token_type_ids": False,
  37. "return_length": False,
  38. "verbose": True,
  39. },
  40. "images_kwargs": {
  41. "max_patches": 2048,
  42. },
  43. }
  44. logger = logging.get_logger(__name__)
  45. class Pix2StructProcessor(ProcessorMixin):
  46. r"""
  47. Constructs a PIX2STRUCT processor which wraps a BERT tokenizer and PIX2STRUCT image processor into a single
  48. processor.
  49. [`Pix2StructProcessor`] offers all the functionalities of [`Pix2StructImageProcessor`] and [`T5TokenizerFast`]. See
  50. the docstring of [`~Pix2StructProcessor.__call__`] and [`~Pix2StructProcessor.decode`] for more information.
  51. Args:
  52. image_processor (`Pix2StructImageProcessor`):
  53. An instance of [`Pix2StructImageProcessor`]. The image processor is a required input.
  54. tokenizer (Union[`T5TokenizerFast`, `T5Tokenizer`]):
  55. An instance of ['T5TokenizerFast`] or ['T5Tokenizer`]. The tokenizer is a required input.
  56. """
  57. attributes = ["image_processor", "tokenizer"]
  58. image_processor_class = "Pix2StructImageProcessor"
  59. tokenizer_class = ("T5Tokenizer", "T5TokenizerFast")
  60. def __init__(self, image_processor, tokenizer):
  61. tokenizer.return_token_type_ids = False
  62. super().__init__(image_processor, tokenizer)
  63. def __call__(
  64. self,
  65. images=None,
  66. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  67. audio=None,
  68. videos=None,
  69. **kwargs: Unpack[Pix2StructProcessorKwargs],
  70. ) -> Union[BatchEncoding, BatchFeature]:
  71. """
  72. This method uses [`Pix2StructImageProcessor.preprocess`] method to prepare image(s) for the model, and
  73. [`T5TokenizerFast.__call__`] to prepare text for the model.
  74. Please refer to the docstring of the above two methods for more information.
  75. """
  76. if images is None and text is None:
  77. raise ValueError("You have to specify either images or text.")
  78. output_kwargs = self._merge_kwargs(
  79. Pix2StructProcessorKwargs,
  80. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  81. **kwargs,
  82. )
  83. add_special_tokens = output_kwargs["text_kwargs"].pop("add_special_tokens", None)
  84. # Get only text
  85. if images is None and not self.image_processor.is_vqa:
  86. output_kwargs["text_kwargs"]["add_special_tokens"] = (
  87. add_special_tokens if add_special_tokens is not None else True
  88. )
  89. self.current_processor = self.tokenizer
  90. text_encoding = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
  91. return text_encoding
  92. if not self.image_processor.is_vqa:
  93. # add pixel_values
  94. encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
  95. else:
  96. # add pixel_values and bbox
  97. output_kwargs["images_kwargs"].setdefault("header_text", text)
  98. encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
  99. if text is not None and not self.image_processor.is_vqa:
  100. output_kwargs["text_kwargs"]["add_special_tokens"] = (
  101. add_special_tokens if add_special_tokens is not None else False
  102. )
  103. text_encoding = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
  104. if "attention_mask" in text_encoding:
  105. text_encoding["decoder_attention_mask"] = text_encoding.pop("attention_mask")
  106. if "input_ids" in text_encoding:
  107. text_encoding["decoder_input_ids"] = text_encoding.pop("input_ids")
  108. else:
  109. text_encoding = None
  110. if text_encoding is not None:
  111. encoding_image_processor.update(text_encoding)
  112. return encoding_image_processor
  113. @property
  114. def model_input_names(self):
  115. image_processor_input_names = self.image_processor.model_input_names
  116. decoder_ids = ["decoder_attention_mask", "decoder_input_ids"]
  117. return image_processor_input_names + decoder_ids
  118. __all__ = ["Pix2StructProcessor"]