processing_trocr.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright 2021 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 TrOCR.
  16. """
  17. from ...image_processing_utils import BatchFeature
  18. from ...image_utils import ImageInput
  19. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  20. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  21. from ...utils import auto_docstring
  22. class TrOCRProcessorKwargs(ProcessingKwargs, total=False):
  23. _defaults = {}
  24. @auto_docstring
  25. class TrOCRProcessor(ProcessorMixin):
  26. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  27. super().__init__(image_processor, tokenizer)
  28. @auto_docstring
  29. def __call__(
  30. self,
  31. images: ImageInput | None = None,
  32. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
  33. **kwargs: Unpack[TrOCRProcessorKwargs],
  34. ) -> BatchFeature:
  35. if images is None and text is None:
  36. raise ValueError("You need to specify either an `images` or `text` input to process.")
  37. output_kwargs = self._merge_kwargs(
  38. TrOCRProcessorKwargs,
  39. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  40. **kwargs,
  41. )
  42. if images is not None:
  43. inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  44. if text is not None:
  45. encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
  46. if text is None:
  47. return inputs
  48. elif images is None:
  49. return encodings
  50. else:
  51. inputs["labels"] = encodings["input_ids"]
  52. return inputs
  53. @property
  54. def model_input_names(self):
  55. image_processor_input_names = self.image_processor.model_input_names
  56. return image_processor_input_names + ["labels"]
  57. __all__ = ["TrOCRProcessor"]