processing_udop.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # Copyright 2024 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 UDOP.
  16. """
  17. from transformers import logging
  18. from ...image_processing_utils import BatchFeature
  19. from ...image_utils import ImageInput
  20. from ...processing_utils import ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
  21. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  22. from ...utils import auto_docstring
  23. logger = logging.get_logger(__name__)
  24. class UdopTextKwargs(TextKwargs, total=False):
  25. word_labels: list[int] | list[list[int]] | None
  26. boxes: list[list[int]] | list[list[list[int]]] | None
  27. class UdopProcessorKwargs(ProcessingKwargs, total=False):
  28. text_kwargs: UdopTextKwargs
  29. _defaults = {
  30. "text_kwargs": {
  31. "add_special_tokens": True,
  32. "padding": False,
  33. "truncation": False,
  34. "stride": 0,
  35. "return_overflowing_tokens": False,
  36. "return_special_tokens_mask": False,
  37. "return_offsets_mapping": False,
  38. "return_length": False,
  39. "verbose": True,
  40. },
  41. }
  42. @auto_docstring
  43. class UdopProcessor(ProcessorMixin):
  44. r"""
  45. Constructs a UDOP processor which combines a LayoutLMv3 image processor and a UDOP tokenizer into a single processor.
  46. [`UdopProcessor`] offers all the functionalities you need to prepare data for the model.
  47. It first uses [`LayoutLMv3ImageProcessor`] to resize, rescale and normalize document images, and optionally applies OCR
  48. to get words and normalized bounding boxes. These are then provided to [`UdopTokenizer`],
  49. which turns the words and bounding boxes into token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`.
  50. Optionally, one can provide integer `word_labels`, which are turned into token-level `labels` for token
  51. classification tasks (such as FUNSD, CORD).
  52. Additionally, it also supports passing `text_target` and `text_pair_target` to the tokenizer, which can be used to
  53. prepare labels for language modeling tasks.
  54. """
  55. def __init__(self, image_processor, tokenizer):
  56. super().__init__(image_processor, tokenizer)
  57. @auto_docstring
  58. def __call__(
  59. self,
  60. images: ImageInput | None = None,
  61. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  62. **kwargs: Unpack[UdopProcessorKwargs],
  63. ) -> BatchFeature:
  64. # verify input
  65. output_kwargs = self._merge_kwargs(
  66. UdopProcessorKwargs,
  67. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  68. **kwargs,
  69. )
  70. boxes = output_kwargs["text_kwargs"].pop("boxes", None)
  71. word_labels = output_kwargs["text_kwargs"].pop("word_labels", None)
  72. text_pair = output_kwargs["text_kwargs"].pop("text_pair", None)
  73. return_overflowing_tokens = output_kwargs["text_kwargs"].get("return_overflowing_tokens", False)
  74. return_offsets_mapping = output_kwargs["text_kwargs"].get("return_offsets_mapping", False)
  75. text_target = output_kwargs["text_kwargs"].get("text_target", None)
  76. if self.image_processor.apply_ocr and (boxes is not None):
  77. raise ValueError(
  78. "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
  79. )
  80. if self.image_processor.apply_ocr and (word_labels is not None):
  81. raise ValueError(
  82. "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
  83. )
  84. if return_overflowing_tokens and not return_offsets_mapping:
  85. raise ValueError("You cannot return overflowing tokens without returning the offsets mapping.")
  86. if text_target is not None:
  87. # use the processor to prepare the targets of UDOP
  88. return self.tokenizer(
  89. **output_kwargs["text_kwargs"],
  90. )
  91. else:
  92. # use the processor to prepare the inputs of UDOP
  93. # first, apply the image processor
  94. features = self.image_processor(images=images, **output_kwargs["images_kwargs"])
  95. features_words = features.pop("words", None)
  96. features_boxes = features.pop("boxes", None)
  97. output_kwargs["text_kwargs"].pop("text_target", None)
  98. output_kwargs["text_kwargs"].pop("text_pair_target", None)
  99. output_kwargs["text_kwargs"]["text_pair"] = text_pair
  100. output_kwargs["text_kwargs"]["boxes"] = boxes if boxes is not None else features_boxes
  101. output_kwargs["text_kwargs"]["word_labels"] = word_labels
  102. # second, apply the tokenizer
  103. if text is not None and self.image_processor.apply_ocr and text_pair is None:
  104. if isinstance(text, str):
  105. text = [text] # add batch dimension (as the image processor always adds a batch dimension)
  106. output_kwargs["text_kwargs"]["text_pair"] = features_words
  107. encoded_inputs = self.tokenizer(
  108. text=text if text is not None else features_words,
  109. **output_kwargs["text_kwargs"],
  110. )
  111. # add pixel values
  112. if return_overflowing_tokens is True:
  113. features["pixel_values"] = self.get_overflowing_images(
  114. features["pixel_values"], encoded_inputs["overflow_to_sample_mapping"]
  115. )
  116. features.update(encoded_inputs)
  117. return features
  118. # Copied from transformers.models.layoutlmv3.processing_layoutlmv3.LayoutLMv3Processor.get_overflowing_images
  119. def get_overflowing_images(self, images, overflow_to_sample_mapping):
  120. # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
  121. images_with_overflow = []
  122. for sample_idx in overflow_to_sample_mapping:
  123. images_with_overflow.append(images[sample_idx])
  124. if len(images_with_overflow) != len(overflow_to_sample_mapping):
  125. raise ValueError(
  126. "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
  127. f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
  128. )
  129. return images_with_overflow
  130. @property
  131. def model_input_names(self):
  132. tokenizer_input_names = self.tokenizer.model_input_names
  133. image_processor_input_names = self.image_processor.model_input_names
  134. return list(tokenizer_input_names + image_processor_input_names + ["bbox"])
  135. __all__ = ["UdopProcessor"]