processing_layoutlmv2.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. # Copyright 2021 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 LayoutLMv2.
  16. """
  17. from ...processing_utils import ProcessorMixin
  18. from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
  19. from ...utils import TensorType, auto_docstring
  20. @auto_docstring
  21. class LayoutLMv2Processor(ProcessorMixin):
  22. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  23. super().__init__(image_processor, tokenizer)
  24. @auto_docstring
  25. def __call__(
  26. self,
  27. images,
  28. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  29. text_pair: PreTokenizedInput | list[PreTokenizedInput] | None = None,
  30. boxes: list[list[int]] | list[list[list[int]]] | None = None,
  31. word_labels: list[int] | list[list[int]] | None = None,
  32. add_special_tokens: bool = True,
  33. padding: bool | str | PaddingStrategy = False,
  34. truncation: bool | str | TruncationStrategy = False,
  35. max_length: int | None = None,
  36. stride: int = 0,
  37. pad_to_multiple_of: int | None = None,
  38. return_token_type_ids: bool | None = None,
  39. return_attention_mask: bool | None = None,
  40. return_overflowing_tokens: bool = False,
  41. return_special_tokens_mask: bool = False,
  42. return_offsets_mapping: bool = False,
  43. return_length: bool = False,
  44. verbose: bool = True,
  45. return_tensors: str | TensorType | None = None,
  46. **kwargs,
  47. ) -> BatchEncoding:
  48. # verify input
  49. if self.image_processor.apply_ocr and (boxes is not None):
  50. raise ValueError(
  51. "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
  52. )
  53. if self.image_processor.apply_ocr and (word_labels is not None):
  54. raise ValueError(
  55. "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
  56. )
  57. if return_overflowing_tokens is True and return_offsets_mapping is False:
  58. raise ValueError("You cannot return overflowing tokens without returning the offsets mapping.")
  59. # first, apply the image processor
  60. features = self.image_processor(images=images, return_tensors=return_tensors)
  61. # second, apply the tokenizer
  62. if text is not None and self.image_processor.apply_ocr and text_pair is None:
  63. if isinstance(text, str):
  64. text = [text] # add batch dimension (as the image processor always adds a batch dimension)
  65. text_pair = features["words"]
  66. encoded_inputs = self.tokenizer(
  67. text=text if text is not None else features["words"],
  68. text_pair=text_pair if text_pair is not None else None,
  69. boxes=boxes if boxes is not None else features["boxes"],
  70. word_labels=word_labels,
  71. add_special_tokens=add_special_tokens,
  72. padding=padding,
  73. truncation=truncation,
  74. max_length=max_length,
  75. stride=stride,
  76. pad_to_multiple_of=pad_to_multiple_of,
  77. return_token_type_ids=return_token_type_ids,
  78. return_attention_mask=return_attention_mask,
  79. return_overflowing_tokens=return_overflowing_tokens,
  80. return_special_tokens_mask=return_special_tokens_mask,
  81. return_offsets_mapping=return_offsets_mapping,
  82. return_length=return_length,
  83. verbose=verbose,
  84. return_tensors=return_tensors,
  85. **kwargs,
  86. )
  87. # add pixel values
  88. images = features.pop("pixel_values")
  89. if return_overflowing_tokens is True:
  90. images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
  91. encoded_inputs["image"] = images
  92. return encoded_inputs
  93. def get_overflowing_images(self, images, overflow_to_sample_mapping):
  94. # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
  95. images_with_overflow = []
  96. for sample_idx in overflow_to_sample_mapping:
  97. images_with_overflow.append(images[sample_idx])
  98. if len(images_with_overflow) != len(overflow_to_sample_mapping):
  99. raise ValueError(
  100. "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
  101. f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
  102. )
  103. return images_with_overflow
  104. @property
  105. def model_input_names(self):
  106. return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]
  107. __all__ = ["LayoutLMv2Processor"]