processing_nougat.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # coding=utf-8
  2. # Copyright 2023 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 Nougat.
  17. """
  18. from typing import Optional, Union
  19. from transformers.tokenization_utils_base import PreTokenizedInput, TextInput, TruncationStrategy
  20. from ...processing_utils import ProcessorMixin
  21. from ...utils import PaddingStrategy, TensorType
  22. class NougatProcessor(ProcessorMixin):
  23. r"""
  24. Constructs a Nougat processor which wraps a Nougat image processor and a Nougat tokenizer into a single processor.
  25. [`NougatProcessor`] offers all the functionalities of [`NougatImageProcessor`] and [`NougatTokenizerFast`]. See the
  26. [`~NougatProcessor.__call__`] and [`~NougatProcessor.decode`] for more information.
  27. Args:
  28. image_processor ([`NougatImageProcessor`]):
  29. An instance of [`NougatImageProcessor`]. The image processor is a required input.
  30. tokenizer ([`NougatTokenizerFast`]):
  31. An instance of [`NougatTokenizerFast`]. The tokenizer is a required input.
  32. """
  33. attributes = ["image_processor", "tokenizer"]
  34. image_processor_class = "AutoImageProcessor"
  35. tokenizer_class = "AutoTokenizer"
  36. def __init__(self, image_processor, tokenizer):
  37. super().__init__(image_processor, tokenizer)
  38. self.current_processor = self.image_processor
  39. def __call__(
  40. self,
  41. images=None,
  42. text=None,
  43. do_crop_margin: Optional[bool] = None,
  44. do_resize: Optional[bool] = None,
  45. size: Optional[dict[str, int]] = None,
  46. resample: "PILImageResampling" = None, # noqa: F821
  47. do_thumbnail: Optional[bool] = None,
  48. do_align_long_axis: Optional[bool] = None,
  49. do_pad: Optional[bool] = None,
  50. do_rescale: Optional[bool] = None,
  51. rescale_factor: Optional[Union[int, float]] = None,
  52. do_normalize: Optional[bool] = None,
  53. image_mean: Optional[Union[float, list[float]]] = None,
  54. image_std: Optional[Union[float, list[float]]] = None,
  55. data_format: Optional["ChannelDimension"] = "channels_first", # noqa: F821
  56. input_data_format: Optional[Union[str, "ChannelDimension"]] = None, # noqa: F821
  57. text_pair: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None,
  58. text_target: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None,
  59. text_pair_target: Optional[
  60. Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]
  61. ] = None,
  62. add_special_tokens: bool = True,
  63. padding: Union[bool, str, PaddingStrategy] = False,
  64. truncation: Optional[Union[bool, str, TruncationStrategy]] = None,
  65. max_length: Optional[int] = None,
  66. stride: int = 0,
  67. is_split_into_words: bool = False,
  68. pad_to_multiple_of: Optional[int] = None,
  69. return_tensors: Optional[Union[str, TensorType]] = 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. ):
  78. if images is None and text is None:
  79. raise ValueError("You need to specify either an `images` or `text` input to process.")
  80. if images is not None:
  81. inputs = self.image_processor(
  82. images,
  83. do_crop_margin=do_crop_margin,
  84. do_resize=do_resize,
  85. size=size,
  86. resample=resample,
  87. do_thumbnail=do_thumbnail,
  88. do_align_long_axis=do_align_long_axis,
  89. do_pad=do_pad,
  90. do_rescale=do_rescale,
  91. rescale_factor=rescale_factor,
  92. do_normalize=do_normalize,
  93. image_mean=image_mean,
  94. image_std=image_std,
  95. return_tensors=return_tensors,
  96. data_format=data_format,
  97. input_data_format=input_data_format,
  98. )
  99. if text is not None:
  100. encodings = self.tokenizer(
  101. text,
  102. text_pair=text_pair,
  103. text_target=text_target,
  104. text_pair_target=text_pair_target,
  105. add_special_tokens=add_special_tokens,
  106. padding=padding,
  107. truncation=truncation,
  108. max_length=max_length,
  109. stride=stride,
  110. is_split_into_words=is_split_into_words,
  111. pad_to_multiple_of=pad_to_multiple_of,
  112. return_tensors=return_tensors,
  113. return_token_type_ids=return_token_type_ids,
  114. return_attention_mask=return_attention_mask,
  115. return_overflowing_tokens=return_overflowing_tokens,
  116. return_special_tokens_mask=return_special_tokens_mask,
  117. return_offsets_mapping=return_offsets_mapping,
  118. return_length=return_length,
  119. verbose=verbose,
  120. )
  121. if text is None:
  122. return inputs
  123. elif images is None:
  124. return encodings
  125. else:
  126. inputs["labels"] = encodings["input_ids"]
  127. return inputs
  128. def post_process_generation(self, *args, **kwargs):
  129. """
  130. This method forwards all its arguments to NougatTokenizer's [`~PreTrainedTokenizer.post_process_generation`].
  131. Please refer to the docstring of this method for more information.
  132. """
  133. return self.tokenizer.post_process_generation(*args, **kwargs)
  134. __all__ = ["NougatProcessor"]