processing_layoutlmv3.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 List, 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. if image_processor is None:
  53. raise ValueError("You need to specify an `image_processor`.")
  54. if tokenizer is None:
  55. raise ValueError("You need to specify a `tokenizer`.")
  56. super().__init__(image_processor, tokenizer)
  57. def __call__(
  58. self,
  59. images,
  60. text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
  61. text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
  62. boxes: Union[List[List[int]], List[List[List[int]]]] = None,
  63. word_labels: Optional[Union[List[int], List[List[int]]]] = None,
  64. add_special_tokens: bool = True,
  65. padding: Union[bool, str, PaddingStrategy] = False,
  66. truncation: Union[bool, str, TruncationStrategy] = None,
  67. max_length: Optional[int] = None,
  68. stride: int = 0,
  69. pad_to_multiple_of: Optional[int] = None,
  70. return_token_type_ids: Optional[bool] = None,
  71. return_attention_mask: Optional[bool] = None,
  72. return_overflowing_tokens: bool = False,
  73. return_special_tokens_mask: bool = False,
  74. return_offsets_mapping: bool = False,
  75. return_length: bool = False,
  76. verbose: bool = True,
  77. return_tensors: Optional[Union[str, TensorType]] = None,
  78. **kwargs,
  79. ) -> BatchEncoding:
  80. """
  81. This method first forwards the `images` argument to [`~LayoutLMv3ImageProcessor.__call__`]. In case
  82. [`LayoutLMv3ImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and
  83. bounding boxes along with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output,
  84. together with resized and normalized `pixel_values`. In case [`LayoutLMv3ImageProcessor`] was initialized with
  85. `apply_ocr` set to `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along
  86. with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output, together with
  87. resized and normalized `pixel_values`.
  88. Please refer to the docstring of the above two methods for more information.
  89. """
  90. # verify input
  91. if self.image_processor.apply_ocr and (boxes is not None):
  92. raise ValueError(
  93. "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
  94. )
  95. if self.image_processor.apply_ocr and (word_labels is not None):
  96. raise ValueError(
  97. "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
  98. )
  99. # first, apply the image processor
  100. features = self.image_processor(images=images, return_tensors=return_tensors)
  101. # second, apply the tokenizer
  102. if text is not None and self.image_processor.apply_ocr and text_pair is None:
  103. if isinstance(text, str):
  104. text = [text] # add batch dimension (as the image processor always adds a batch dimension)
  105. text_pair = features["words"]
  106. encoded_inputs = self.tokenizer(
  107. text=text if text is not None else features["words"],
  108. text_pair=text_pair if text_pair is not None else None,
  109. boxes=boxes if boxes is not None else features["boxes"],
  110. word_labels=word_labels,
  111. add_special_tokens=add_special_tokens,
  112. padding=padding,
  113. truncation=truncation,
  114. max_length=max_length,
  115. stride=stride,
  116. pad_to_multiple_of=pad_to_multiple_of,
  117. return_token_type_ids=return_token_type_ids,
  118. return_attention_mask=return_attention_mask,
  119. return_overflowing_tokens=return_overflowing_tokens,
  120. return_special_tokens_mask=return_special_tokens_mask,
  121. return_offsets_mapping=return_offsets_mapping,
  122. return_length=return_length,
  123. verbose=verbose,
  124. return_tensors=return_tensors,
  125. **kwargs,
  126. )
  127. # add pixel values
  128. images = features.pop("pixel_values")
  129. if return_overflowing_tokens is True:
  130. images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
  131. encoded_inputs["pixel_values"] = images
  132. return encoded_inputs
  133. def get_overflowing_images(self, images, overflow_to_sample_mapping):
  134. # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
  135. images_with_overflow = []
  136. for sample_idx in overflow_to_sample_mapping:
  137. images_with_overflow.append(images[sample_idx])
  138. if len(images_with_overflow) != len(overflow_to_sample_mapping):
  139. raise ValueError(
  140. "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
  141. f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
  142. )
  143. return images_with_overflow
  144. def batch_decode(self, *args, **kwargs):
  145. """
  146. This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
  147. refer to the docstring of this method for more information.
  148. """
  149. return self.tokenizer.batch_decode(*args, **kwargs)
  150. def decode(self, *args, **kwargs):
  151. """
  152. This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer
  153. to the docstring of this method for more information.
  154. """
  155. return self.tokenizer.decode(*args, **kwargs)
  156. @property
  157. def model_input_names(self):
  158. return ["input_ids", "bbox", "attention_mask", "pixel_values"]
  159. @property
  160. def feature_extractor_class(self):
  161. warnings.warn(
  162. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  163. FutureWarning,
  164. )
  165. return self.image_processor_class
  166. @property
  167. def feature_extractor(self):
  168. warnings.warn(
  169. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  170. FutureWarning,
  171. )
  172. return self.image_processor