processing_markuplm.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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 MarkupLM.
  17. """
  18. from typing import Optional, Union
  19. from ...file_utils import TensorType
  20. from ...processing_utils import ProcessorMixin
  21. from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TruncationStrategy
  22. class MarkupLMProcessor(ProcessorMixin):
  23. r"""
  24. Constructs a MarkupLM processor which combines a MarkupLM feature extractor and a MarkupLM tokenizer into a single
  25. processor.
  26. [`MarkupLMProcessor`] offers all the functionalities you need to prepare data for the model.
  27. It first uses [`MarkupLMFeatureExtractor`] to extract nodes and corresponding xpaths from one or more HTML strings.
  28. Next, these are provided to [`MarkupLMTokenizer`] or [`MarkupLMTokenizerFast`], which turns them into token-level
  29. `input_ids`, `attention_mask`, `token_type_ids`, `xpath_tags_seq` and `xpath_subs_seq`.
  30. Args:
  31. feature_extractor (`MarkupLMFeatureExtractor`):
  32. An instance of [`MarkupLMFeatureExtractor`]. The feature extractor is a required input.
  33. tokenizer (`MarkupLMTokenizer` or `MarkupLMTokenizerFast`):
  34. An instance of [`MarkupLMTokenizer`] or [`MarkupLMTokenizerFast`]. The tokenizer is a required input.
  35. parse_html (`bool`, *optional*, defaults to `True`):
  36. Whether or not to use `MarkupLMFeatureExtractor` to parse HTML strings into nodes and corresponding xpaths.
  37. """
  38. feature_extractor_class = "MarkupLMFeatureExtractor"
  39. tokenizer_class = ("MarkupLMTokenizer", "MarkupLMTokenizerFast")
  40. parse_html = True
  41. def __call__(
  42. self,
  43. html_strings=None,
  44. nodes=None,
  45. xpaths=None,
  46. node_labels=None,
  47. questions=None,
  48. add_special_tokens: bool = True,
  49. padding: Union[bool, str, PaddingStrategy] = False,
  50. truncation: Union[bool, str, TruncationStrategy] = None,
  51. max_length: Optional[int] = None,
  52. stride: int = 0,
  53. pad_to_multiple_of: Optional[int] = None,
  54. return_token_type_ids: Optional[bool] = None,
  55. return_attention_mask: Optional[bool] = None,
  56. return_overflowing_tokens: bool = False,
  57. return_special_tokens_mask: bool = False,
  58. return_offsets_mapping: bool = False,
  59. return_length: bool = False,
  60. verbose: bool = True,
  61. return_tensors: Optional[Union[str, TensorType]] = None,
  62. **kwargs,
  63. ) -> BatchEncoding:
  64. """
  65. This method first forwards the `html_strings` argument to [`~MarkupLMFeatureExtractor.__call__`]. Next, it
  66. passes the `nodes` and `xpaths` along with the additional arguments to [`~MarkupLMTokenizer.__call__`] and
  67. returns the output.
  68. Optionally, one can also provide a `text` argument which is passed along as first sequence.
  69. Please refer to the docstring of the above two methods for more information.
  70. """
  71. # first, create nodes and xpaths
  72. if self.parse_html:
  73. if html_strings is None:
  74. raise ValueError("Make sure to pass HTML strings in case `parse_html` is set to `True`")
  75. if nodes is not None or xpaths is not None or node_labels is not None:
  76. raise ValueError(
  77. "Please don't pass nodes, xpaths nor node labels in case `parse_html` is set to `True`"
  78. )
  79. features = self.feature_extractor(html_strings)
  80. nodes = features["nodes"]
  81. xpaths = features["xpaths"]
  82. else:
  83. if html_strings is not None:
  84. raise ValueError("You have passed HTML strings but `parse_html` is set to `False`.")
  85. if nodes is None or xpaths is None:
  86. raise ValueError("Make sure to pass nodes and xpaths in case `parse_html` is set to `False`")
  87. # # second, apply the tokenizer
  88. if questions is not None and self.parse_html:
  89. if isinstance(questions, str):
  90. questions = [questions] # add batch dimension (as the feature extractor always adds a batch dimension)
  91. encoded_inputs = self.tokenizer(
  92. text=questions if questions is not None else nodes,
  93. text_pair=nodes if questions is not None else None,
  94. xpaths=xpaths,
  95. node_labels=node_labels,
  96. add_special_tokens=add_special_tokens,
  97. padding=padding,
  98. truncation=truncation,
  99. max_length=max_length,
  100. stride=stride,
  101. pad_to_multiple_of=pad_to_multiple_of,
  102. return_token_type_ids=return_token_type_ids,
  103. return_attention_mask=return_attention_mask,
  104. return_overflowing_tokens=return_overflowing_tokens,
  105. return_special_tokens_mask=return_special_tokens_mask,
  106. return_offsets_mapping=return_offsets_mapping,
  107. return_length=return_length,
  108. verbose=verbose,
  109. return_tensors=return_tensors,
  110. **kwargs,
  111. )
  112. return encoded_inputs
  113. def batch_decode(self, *args, **kwargs):
  114. """
  115. This method forwards all its arguments to TrOCRTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer
  116. to the docstring of this method for more information.
  117. """
  118. return self.tokenizer.batch_decode(*args, **kwargs)
  119. def decode(self, *args, **kwargs):
  120. """
  121. This method forwards all its arguments to TrOCRTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
  122. docstring of this method for more information.
  123. """
  124. return self.tokenizer.decode(*args, **kwargs)
  125. @property
  126. def model_input_names(self):
  127. tokenizer_input_names = self.tokenizer.model_input_names
  128. return tokenizer_input_names