processing_trocr.py 5.6 KB

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