pipeline.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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. from typing import Any, Dict, Optional
  15. from scipy.ndimage import rotate
  16. import numpy as np
  17. from ..base import BasePipeline
  18. from .result import DocPreprocessorResult
  19. from ....utils import logging
  20. from ...common.reader import ReadImage
  21. from ...common.batch_sampler import ImageBatchSampler
  22. from ...utils.pp_option import PaddlePredictorOption
  23. class DocPreprocessorPipeline(BasePipeline):
  24. """Doc Preprocessor Pipeline"""
  25. entities = "doc_preprocessor"
  26. def __init__(
  27. self,
  28. config: Dict,
  29. device: str = None,
  30. pp_option: PaddlePredictorOption = None,
  31. use_hpip: bool = False,
  32. hpi_params: Optional[Dict[str, Any]] = None,
  33. ) -> None:
  34. """Initializes the doc preprocessor pipeline.
  35. Args:
  36. config (Dict): Configuration dictionary containing various settings.
  37. device (str, optional): Device to run the predictions on. Defaults to None.
  38. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  39. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  40. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  41. """
  42. super().__init__(
  43. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  44. )
  45. self.use_doc_orientation_classify = True
  46. if "use_doc_orientation_classify" in config:
  47. self.use_doc_orientation_classify = config["use_doc_orientation_classify"]
  48. self.use_doc_unwarping = True
  49. if "use_doc_unwarping" in config:
  50. self.use_doc_unwarping = config["use_doc_unwarping"]
  51. if self.use_doc_orientation_classify:
  52. doc_ori_classify_config = config["SubModules"]["DocOrientationClassify"]
  53. self.doc_ori_classify_model = self.create_model(doc_ori_classify_config)
  54. if self.use_doc_unwarping:
  55. doc_unwarping_config = config["SubModules"]["DocUnwarping"]
  56. self.doc_unwarping_model = self.create_model(doc_unwarping_config)
  57. self.batch_sampler = ImageBatchSampler(batch_size=1)
  58. self.img_reader = ReadImage(format="BGR")
  59. def rotate_image(self, image_array: np.ndarray, rotate_angle: float) -> np.ndarray:
  60. """
  61. Rotate the given image array by the specified angle.
  62. Args:
  63. image_array (np.ndarray): The input image array to be rotated.
  64. rotate_angle (float): The angle in degrees by which to rotate the image.
  65. Returns:
  66. np.ndarray: The rotated image array.
  67. Raises:
  68. AssertionError: If rotate_angle is not in the range [0, 360).
  69. """
  70. assert (
  71. rotate_angle >= 0 and rotate_angle < 360
  72. ), "rotate_angle must in [0-360), but get {rotate_angle}."
  73. return rotate(image_array, rotate_angle, reshape=True)
  74. def check_input_params_valid(self, input_params: Dict) -> bool:
  75. """
  76. Check if the input parameters are valid based on the initialized models.
  77. Args:
  78. input_params (Dict): A dictionary containing input parameters.
  79. Returns:
  80. bool: True if all required models are initialized according to input parameters, False otherwise.
  81. """
  82. if (
  83. input_params["use_doc_orientation_classify"]
  84. and not self.use_doc_orientation_classify
  85. ):
  86. logging.error(
  87. "Set use_doc_orientation_classify, but the model for doc orientation classify is not initialized."
  88. )
  89. return False
  90. if input_params["use_doc_unwarping"] and not self.use_doc_unwarping:
  91. logging.error(
  92. "Set use_doc_unwarping, but the model for doc unwarping is not initialized."
  93. )
  94. return False
  95. return True
  96. def predict(
  97. self,
  98. input: str | list[str] | np.ndarray | list[np.ndarray],
  99. use_doc_orientation_classify: bool = True,
  100. use_doc_unwarping: bool = False,
  101. **kwargs
  102. ) -> DocPreprocessorResult:
  103. """
  104. Predict the preprocessing result for the input image or images.
  105. Args:
  106. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or path(s) to the images or pdfs.
  107. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  108. use_doc_unwarping (bool): Whether to use document unwarping.
  109. **kwargs: Additional keyword arguments.
  110. Returns:
  111. DocPreprocessorResult: A generator yielding preprocessing results.
  112. """
  113. input_params = {
  114. "use_doc_orientation_classify": use_doc_orientation_classify,
  115. "use_doc_unwarping": use_doc_unwarping,
  116. }
  117. if not self.check_input_params_valid(input_params):
  118. yield {"error": "input params invalid"}
  119. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  120. image_array = self.img_reader(batch_data)[0]
  121. if input_params["use_doc_orientation_classify"]:
  122. pred = next(self.doc_ori_classify_model(image_array))
  123. angle = int(pred["label_names"][0])
  124. rot_img = self.rotate_image(image_array, angle)
  125. else:
  126. angle = -1
  127. rot_img = image_array
  128. if input_params["use_doc_unwarping"]:
  129. output_img = next(self.doc_unwarping_model(rot_img))["doctr_img"]
  130. else:
  131. output_img = rot_img
  132. img_id += 1
  133. single_img_res = {
  134. "input_image": image_array,
  135. "input_params": input_params,
  136. "angle": angle,
  137. "rot_img": rot_img,
  138. "output_img": output_img,
  139. "img_id": img_id,
  140. }
  141. yield DocPreprocessorResult(single_img_res)