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