processing_pix2struct.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # Copyright 2023 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Processor class for Pix2Struct.
  16. """
  17. from ...feature_extraction_utils import BatchFeature
  18. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  19. from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
  20. from ...utils import auto_docstring, logging
  21. class Pix2StructProcessorKwargs(ProcessingKwargs, total=False):
  22. _defaults = {
  23. "text_kwargs": {
  24. "add_special_tokens": True,
  25. "padding": False,
  26. "stride": 0,
  27. "return_overflowing_tokens": False,
  28. "return_special_tokens_mask": False,
  29. "return_offsets_mapping": False,
  30. "return_token_type_ids": False,
  31. "return_length": False,
  32. "verbose": True,
  33. },
  34. "images_kwargs": {
  35. "max_patches": 2048,
  36. },
  37. }
  38. logger = logging.get_logger(__name__)
  39. @auto_docstring
  40. class Pix2StructProcessor(ProcessorMixin):
  41. def __init__(self, image_processor, tokenizer):
  42. tokenizer.return_token_type_ids = False
  43. super().__init__(image_processor, tokenizer)
  44. @auto_docstring
  45. def __call__(
  46. self,
  47. images=None,
  48. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  49. **kwargs: Unpack[Pix2StructProcessorKwargs],
  50. ) -> BatchEncoding | BatchFeature:
  51. if images is None and text is None:
  52. raise ValueError("You have to specify either images or text.")
  53. output_kwargs = self._merge_kwargs(
  54. Pix2StructProcessorKwargs,
  55. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  56. **kwargs,
  57. )
  58. add_special_tokens = output_kwargs["text_kwargs"].pop("add_special_tokens", None)
  59. # Get only text
  60. if images is None and not self.image_processor.is_vqa:
  61. output_kwargs["text_kwargs"]["add_special_tokens"] = (
  62. add_special_tokens if add_special_tokens is not None else True
  63. )
  64. text_encoding = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
  65. return text_encoding
  66. if not self.image_processor.is_vqa:
  67. # add pixel_values
  68. encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
  69. else:
  70. # add pixel_values and bbox
  71. output_kwargs["images_kwargs"].setdefault("header_text", text)
  72. encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
  73. if text is not None and not self.image_processor.is_vqa:
  74. output_kwargs["text_kwargs"]["add_special_tokens"] = (
  75. add_special_tokens if add_special_tokens is not None else False
  76. )
  77. text_encoding = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
  78. if "attention_mask" in text_encoding:
  79. text_encoding["decoder_attention_mask"] = text_encoding.pop("attention_mask")
  80. if "input_ids" in text_encoding:
  81. text_encoding["decoder_input_ids"] = text_encoding.pop("input_ids")
  82. else:
  83. text_encoding = None
  84. if text_encoding is not None:
  85. encoding_image_processor.update(text_encoding)
  86. return encoding_image_processor
  87. @property
  88. def model_input_names(self):
  89. image_processor_input_names = self.image_processor.model_input_names
  90. decoder_ids = ["decoder_attention_mask", "decoder_input_ids"]
  91. return image_processor_input_names + decoder_ids
  92. __all__ = ["Pix2StructProcessor"]