processing_layoutlmv3.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # Copyright 2022 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 LayoutLMv3.
  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 LayoutLMv3Processor(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 = None,
  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. if self.image_processor.apply_ocr and (boxes is not None):
  49. raise ValueError(
  50. "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
  51. )
  52. if self.image_processor.apply_ocr and (word_labels is not None):
  53. raise ValueError(
  54. "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
  55. )
  56. # first, apply the image processor
  57. features = self.image_processor(images=images, return_tensors=return_tensors)
  58. # second, apply the tokenizer
  59. if text is not None and self.image_processor.apply_ocr and text_pair is None:
  60. if isinstance(text, str):
  61. text = [text] # add batch dimension (as the image processor always adds a batch dimension)
  62. text_pair = features["words"]
  63. encoded_inputs = self.tokenizer(
  64. text=text if text is not None else features["words"],
  65. text_pair=text_pair if text_pair is not None else None,
  66. boxes=boxes if boxes is not None else features["boxes"],
  67. word_labels=word_labels,
  68. add_special_tokens=add_special_tokens,
  69. padding=padding,
  70. truncation=truncation,
  71. max_length=max_length,
  72. stride=stride,
  73. pad_to_multiple_of=pad_to_multiple_of,
  74. return_token_type_ids=return_token_type_ids,
  75. return_attention_mask=return_attention_mask,
  76. return_overflowing_tokens=return_overflowing_tokens,
  77. return_special_tokens_mask=return_special_tokens_mask,
  78. return_offsets_mapping=return_offsets_mapping,
  79. return_length=return_length,
  80. verbose=verbose,
  81. return_tensors=return_tensors,
  82. **kwargs,
  83. )
  84. # add pixel values
  85. images = features.pop("pixel_values")
  86. if return_overflowing_tokens is True:
  87. images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
  88. encoded_inputs["pixel_values"] = images
  89. return encoded_inputs
  90. def get_overflowing_images(self, images, overflow_to_sample_mapping):
  91. # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
  92. images_with_overflow = []
  93. for sample_idx in overflow_to_sample_mapping:
  94. images_with_overflow.append(images[sample_idx])
  95. if len(images_with_overflow) != len(overflow_to_sample_mapping):
  96. raise ValueError(
  97. "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
  98. f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
  99. )
  100. return images_with_overflow
  101. @property
  102. def model_input_names(self):
  103. return ["input_ids", "bbox", "attention_mask", "pixel_values"]
  104. __all__ = ["LayoutLMv3Processor"]