processing_layoutxlm.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # coding=utf-8
  2. # Copyright 2021 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 LayoutXLM.
  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 LayoutXLMProcessor(ProcessorMixin):
  24. r"""
  25. Constructs a LayoutXLM processor which combines a LayoutXLM image processor and a LayoutXLM tokenizer into a single
  26. processor.
  27. [`LayoutXLMProcessor`] offers all the functionalities you need to prepare data for the model.
  28. It first uses [`LayoutLMv2ImageProcessor`] to resize document images to a fixed size, and optionally applies OCR to
  29. get words and normalized bounding boxes. These are then provided to [`LayoutXLMTokenizer`] or
  30. [`LayoutXLMTokenizerFast`], 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 (`LayoutLMv2ImageProcessor`, *optional*):
  35. An instance of [`LayoutLMv2ImageProcessor`]. The image processor is a required input.
  36. tokenizer (`LayoutXLMTokenizer` or `LayoutXLMTokenizerFast`, *optional*):
  37. An instance of [`LayoutXLMTokenizer`] or [`LayoutXLMTokenizerFast`]. The tokenizer is a required input.
  38. """
  39. attributes = ["image_processor", "tokenizer"]
  40. image_processor_class = "LayoutLMv2ImageProcessor"
  41. tokenizer_class = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast")
  42. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  43. if "feature_extractor" in kwargs:
  44. warnings.warn(
  45. "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
  46. " instead.",
  47. FutureWarning,
  48. )
  49. feature_extractor = kwargs.pop("feature_extractor")
  50. image_processor = image_processor if image_processor is not None else feature_extractor
  51. if image_processor is None:
  52. raise ValueError("You need to specify an `image_processor`.")
  53. if tokenizer is None:
  54. raise ValueError("You need to specify a `tokenizer`.")
  55. super().__init__(image_processor, tokenizer)
  56. def __call__(
  57. self,
  58. images,
  59. text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
  60. text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
  61. boxes: Union[List[List[int]], List[List[List[int]]]] = None,
  62. word_labels: Optional[Union[List[int], List[List[int]]]] = None,
  63. add_special_tokens: bool = True,
  64. padding: Union[bool, str, PaddingStrategy] = False,
  65. truncation: Union[bool, str, TruncationStrategy] = None,
  66. max_length: Optional[int] = None,
  67. stride: int = 0,
  68. pad_to_multiple_of: Optional[int] = None,
  69. return_token_type_ids: Optional[bool] = None,
  70. return_attention_mask: Optional[bool] = None,
  71. return_overflowing_tokens: bool = False,
  72. return_special_tokens_mask: bool = False,
  73. return_offsets_mapping: bool = False,
  74. return_length: bool = False,
  75. verbose: bool = True,
  76. return_tensors: Optional[Union[str, TensorType]] = None,
  77. **kwargs,
  78. ) -> BatchEncoding:
  79. """
  80. This method first forwards the `images` argument to [`~LayoutLMv2ImagePrpcessor.__call__`]. In case
  81. [`LayoutLMv2ImagePrpcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and
  82. bounding boxes along with the additional arguments to [`~LayoutXLMTokenizer.__call__`] and returns the output,
  83. together with resized `images`. In case [`LayoutLMv2ImagePrpcessor`] was initialized with `apply_ocr` set to
  84. `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along with the additional
  85. arguments to [`~LayoutXLMTokenizer.__call__`] and returns the output, together with resized `images``.
  86. Please refer to the docstring of the above two methods for more information.
  87. """
  88. # verify input
  89. if self.image_processor.apply_ocr and (boxes is not None):
  90. raise ValueError(
  91. "You cannot provide bounding boxes "
  92. "if you initialized the image processor with apply_ocr set to True."
  93. )
  94. if self.image_processor.apply_ocr and (word_labels is not None):
  95. raise ValueError(
  96. "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
  97. )
  98. if return_overflowing_tokens is True and return_offsets_mapping is False:
  99. raise ValueError("You cannot return overflowing tokens without returning the offsets mapping.")
  100. # first, apply the image processor
  101. features = self.image_processor(images=images, return_tensors=return_tensors)
  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. text_pair = features["words"]
  107. encoded_inputs = self.tokenizer(
  108. text=text if text is not None else features["words"],
  109. text_pair=text_pair if text_pair is not None else None,
  110. boxes=boxes if boxes is not None else features["boxes"],
  111. word_labels=word_labels,
  112. add_special_tokens=add_special_tokens,
  113. padding=padding,
  114. truncation=truncation,
  115. max_length=max_length,
  116. stride=stride,
  117. pad_to_multiple_of=pad_to_multiple_of,
  118. return_token_type_ids=return_token_type_ids,
  119. return_attention_mask=return_attention_mask,
  120. return_overflowing_tokens=return_overflowing_tokens,
  121. return_special_tokens_mask=return_special_tokens_mask,
  122. return_offsets_mapping=return_offsets_mapping,
  123. return_length=return_length,
  124. verbose=verbose,
  125. return_tensors=return_tensors,
  126. **kwargs,
  127. )
  128. # add pixel values
  129. images = features.pop("pixel_values")
  130. if return_overflowing_tokens is True:
  131. images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
  132. encoded_inputs["image"] = images
  133. return encoded_inputs
  134. def get_overflowing_images(self, images, overflow_to_sample_mapping):
  135. # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
  136. images_with_overflow = []
  137. for sample_idx in overflow_to_sample_mapping:
  138. images_with_overflow.append(images[sample_idx])
  139. if len(images_with_overflow) != len(overflow_to_sample_mapping):
  140. raise ValueError(
  141. "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
  142. f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
  143. )
  144. return images_with_overflow
  145. def batch_decode(self, *args, **kwargs):
  146. """
  147. This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
  148. refer to the docstring of this method for more information.
  149. """
  150. return self.tokenizer.batch_decode(*args, **kwargs)
  151. def decode(self, *args, **kwargs):
  152. """
  153. This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer
  154. to the docstring of this method for more information.
  155. """
  156. return self.tokenizer.decode(*args, **kwargs)
  157. @property
  158. def model_input_names(self):
  159. return ["input_ids", "bbox", "attention_mask", "image"]
  160. @property
  161. def feature_extractor_class(self):
  162. warnings.warn(
  163. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  164. FutureWarning,
  165. )
  166. return self.image_processor_class
  167. @property
  168. def feature_extractor(self):
  169. warnings.warn(
  170. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  171. FutureWarning,
  172. )
  173. return self.image_processor