processing_trocr.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 TrOCR.
  17. """
  18. import warnings
  19. from contextlib import contextmanager
  20. from typing import Optional, Union
  21. from ...image_processing_utils import BatchFeature
  22. from ...image_utils import ImageInput
  23. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  24. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  25. class TrOCRProcessorKwargs(ProcessingKwargs, total=False):
  26. _defaults = {}
  27. class TrOCRProcessor(ProcessorMixin):
  28. r"""
  29. Constructs a TrOCR processor which wraps a vision image processor and a TrOCR tokenizer into a single processor.
  30. [`TrOCRProcessor`] offers all the functionalities of [`ViTImageProcessor`/`DeiTImageProcessor`] and
  31. [`RobertaTokenizer`/`XLMRobertaTokenizer`]. See the [`~TrOCRProcessor.__call__`] and [`~TrOCRProcessor.decode`] for
  32. more information.
  33. Args:
  34. image_processor ([`ViTImageProcessor`/`DeiTImageProcessor`], *optional*):
  35. An instance of [`ViTImageProcessor`/`DeiTImageProcessor`]. The image processor is a required input.
  36. tokenizer ([`RobertaTokenizer`/`XLMRobertaTokenizer`], *optional*):
  37. An instance of [`RobertaTokenizer`/`XLMRobertaTokenizer`]. The tokenizer is a required input.
  38. """
  39. attributes = ["image_processor", "tokenizer"]
  40. image_processor_class = "AutoImageProcessor"
  41. tokenizer_class = "AutoTokenizer"
  42. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  43. feature_extractor = None
  44. if "feature_extractor" in kwargs:
  45. warnings.warn(
  46. "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
  47. " instead.",
  48. FutureWarning,
  49. )
  50. feature_extractor = kwargs.pop("feature_extractor")
  51. image_processor = image_processor if image_processor is not None else feature_extractor
  52. super().__init__(image_processor, tokenizer)
  53. self.current_processor = self.image_processor
  54. self._in_target_context_manager = False
  55. def __call__(
  56. self,
  57. images: Optional[ImageInput] = None,
  58. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  59. audio=None,
  60. videos=None,
  61. **kwargs: Unpack[TrOCRProcessorKwargs],
  62. ) -> BatchFeature:
  63. """
  64. When used in normal mode, this method forwards all its arguments to AutoImageProcessor's
  65. [`~AutoImageProcessor.__call__`] and returns its output. If used in the context
  66. [`~TrOCRProcessor.as_target_processor`] this method forwards all its arguments to TrOCRTokenizer's
  67. [`~TrOCRTokenizer.__call__`]. Please refer to the docstring of the above two methods for more information.
  68. """
  69. # For backward compatibility
  70. if self._in_target_context_manager:
  71. return self.current_processor(images, **kwargs)
  72. if images is None and text is None:
  73. raise ValueError("You need to specify either an `images` or `text` input to process.")
  74. output_kwargs = self._merge_kwargs(
  75. TrOCRProcessorKwargs,
  76. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  77. **kwargs,
  78. )
  79. if images is not None:
  80. inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  81. if text is not None:
  82. encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
  83. if text is None:
  84. return inputs
  85. elif images is None:
  86. return encodings
  87. else:
  88. inputs["labels"] = encodings["input_ids"]
  89. return inputs
  90. @property
  91. def model_input_names(self):
  92. image_processor_input_names = self.image_processor.model_input_names
  93. return image_processor_input_names + ["labels"]
  94. @contextmanager
  95. def as_target_processor(self):
  96. """
  97. Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning TrOCR.
  98. """
  99. warnings.warn(
  100. "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
  101. "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
  102. "your images inputs, or in a separate call."
  103. )
  104. self._in_target_context_manager = True
  105. self.current_processor = self.tokenizer
  106. yield
  107. self.current_processor = self.image_processor
  108. self._in_target_context_manager = False
  109. @property
  110. def feature_extractor_class(self):
  111. warnings.warn(
  112. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  113. FutureWarning,
  114. )
  115. return self.image_processor_class
  116. @property
  117. def feature_extractor(self):
  118. warnings.warn(
  119. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  120. FutureWarning,
  121. )
  122. return self.image_processor
  123. __all__ = ["TrOCRProcessor"]