processing_layoutlmv3.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. Processor class for LayoutLMv3.
  17. """
  18. import warnings
  19. from typing import Optional, Union
  20. from ...processing_utils import ProcessorMixin
  21. from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
  22. from ...utils import TensorType
  23. class LayoutLMv3Processor(ProcessorMixin):
  24. r"""
  25. Constructs a LayoutLMv3 processor which combines a LayoutLMv3 image processor and a LayoutLMv3 tokenizer into a
  26. single processor.
  27. [`LayoutLMv3Processor`] offers all the functionalities you need to prepare data for the model.
  28. It first uses [`LayoutLMv3ImageProcessor`] to resize and normalize document images, and optionally applies OCR to
  29. get words and normalized bounding boxes. These are then provided to [`LayoutLMv3Tokenizer`] or
  30. [`LayoutLMv3TokenizerFast`], which turns the words and bounding boxes into token-level `input_ids`,
  31. `attention_mask`, `token_type_ids`, `bbox`. Optionally, one can provide integer `word_labels`, which are turned
  32. into token-level `labels` for token classification tasks (such as FUNSD, CORD).
  33. Args:
  34. image_processor (`LayoutLMv3ImageProcessor`, *optional*):
  35. An instance of [`LayoutLMv3ImageProcessor`]. The image processor is a required input.
  36. tokenizer (`LayoutLMv3Tokenizer` or `LayoutLMv3TokenizerFast`, *optional*):
  37. An instance of [`LayoutLMv3Tokenizer`] or [`LayoutLMv3TokenizerFast`]. The tokenizer is a required input.
  38. """
  39. attributes = ["image_processor", "tokenizer"]
  40. image_processor_class = "LayoutLMv3ImageProcessor"
  41. tokenizer_class = ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast")
  42. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  43. feature_extractor = None
  44. if "feature_extractor" in kwargs:
  45. warnings.warn(
  46. "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
  47. " instead.",
  48. FutureWarning,
  49. )
  50. feature_extractor = kwargs.pop("feature_extractor")
  51. image_processor = image_processor if image_processor is not None else feature_extractor
  52. super().__init__(image_processor, tokenizer)
  53. def __call__(
  54. self,
  55. images,
  56. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  57. text_pair: Optional[Union[PreTokenizedInput, list[PreTokenizedInput]]] = None,
  58. boxes: Optional[Union[list[list[int]], list[list[list[int]]]]] = None,
  59. word_labels: Optional[Union[list[int], list[list[int]]]] = None,
  60. add_special_tokens: bool = True,
  61. padding: Union[bool, str, PaddingStrategy] = False,
  62. truncation: Union[bool, str, TruncationStrategy] = None,
  63. max_length: Optional[int] = None,
  64. stride: int = 0,
  65. pad_to_multiple_of: Optional[int] = None,
  66. return_token_type_ids: Optional[bool] = None,
  67. return_attention_mask: Optional[bool] = None,
  68. return_overflowing_tokens: bool = False,
  69. return_special_tokens_mask: bool = False,
  70. return_offsets_mapping: bool = False,
  71. return_length: bool = False,
  72. verbose: bool = True,
  73. return_tensors: Optional[Union[str, TensorType]] = None,
  74. **kwargs,
  75. ) -> BatchEncoding:
  76. """
  77. This method first forwards the `images` argument to [`~LayoutLMv3ImageProcessor.__call__`]. In case
  78. [`LayoutLMv3ImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and
  79. bounding boxes along with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output,
  80. together with resized and normalized `pixel_values`. In case [`LayoutLMv3ImageProcessor`] was initialized with
  81. `apply_ocr` set to `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along
  82. with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output, together with
  83. resized and normalized `pixel_values`.
  84. Please refer to the docstring of the above two methods for more information.
  85. """
  86. # verify input
  87. if self.image_processor.apply_ocr and (boxes is not None):
  88. raise ValueError(
  89. "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
  90. )
  91. if self.image_processor.apply_ocr and (word_labels is not None):
  92. raise ValueError(
  93. "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
  94. )
  95. # first, apply the image processor
  96. features = self.image_processor(images=images, return_tensors=return_tensors)
  97. # second, apply the tokenizer
  98. if text is not None and self.image_processor.apply_ocr and text_pair is None:
  99. if isinstance(text, str):
  100. text = [text] # add batch dimension (as the image processor always adds a batch dimension)
  101. text_pair = features["words"]
  102. encoded_inputs = self.tokenizer(
  103. text=text if text is not None else features["words"],
  104. text_pair=text_pair if text_pair is not None else None,
  105. boxes=boxes if boxes is not None else features["boxes"],
  106. word_labels=word_labels,
  107. add_special_tokens=add_special_tokens,
  108. padding=padding,
  109. truncation=truncation,
  110. max_length=max_length,
  111. stride=stride,
  112. pad_to_multiple_of=pad_to_multiple_of,
  113. return_token_type_ids=return_token_type_ids,
  114. return_attention_mask=return_attention_mask,
  115. return_overflowing_tokens=return_overflowing_tokens,
  116. return_special_tokens_mask=return_special_tokens_mask,
  117. return_offsets_mapping=return_offsets_mapping,
  118. return_length=return_length,
  119. verbose=verbose,
  120. return_tensors=return_tensors,
  121. **kwargs,
  122. )
  123. # add pixel values
  124. images = features.pop("pixel_values")
  125. if return_overflowing_tokens is True:
  126. images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
  127. encoded_inputs["pixel_values"] = images
  128. return encoded_inputs
  129. def get_overflowing_images(self, images, overflow_to_sample_mapping):
  130. # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
  131. images_with_overflow = []
  132. for sample_idx in overflow_to_sample_mapping:
  133. images_with_overflow.append(images[sample_idx])
  134. if len(images_with_overflow) != len(overflow_to_sample_mapping):
  135. raise ValueError(
  136. "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
  137. f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
  138. )
  139. return images_with_overflow
  140. @property
  141. def model_input_names(self):
  142. return ["input_ids", "bbox", "attention_mask", "pixel_values"]
  143. @property
  144. def feature_extractor_class(self):
  145. warnings.warn(
  146. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  147. FutureWarning,
  148. )
  149. return self.image_processor_class
  150. @property
  151. def feature_extractor(self):
  152. warnings.warn(
  153. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  154. FutureWarning,
  155. )
  156. return self.image_processor
  157. __all__ = ["LayoutLMv3Processor"]