pipeline.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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: Optional[str] = None,
  30. pp_option: Optional[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 = config.get(
  46. "use_doc_orientation_classify", True
  47. )
  48. if self.use_doc_orientation_classify:
  49. doc_ori_classify_config = config.get("SubModules", {}).get(
  50. "DocOrientationClassify",
  51. {"model_config_error": "config error for doc_ori_classify_model!"},
  52. )
  53. self.doc_ori_classify_model = self.create_model(doc_ori_classify_config)
  54. self.use_doc_unwarping = config.get("use_doc_unwarping", True)
  55. if self.use_doc_unwarping:
  56. doc_unwarping_config = config.get("SubModules", {}).get(
  57. "DocUnwarping",
  58. {"model_config_error": "config error for doc_unwarping_model!"},
  59. )
  60. self.doc_unwarping_model = self.create_model(doc_unwarping_config)
  61. self.batch_sampler = ImageBatchSampler(batch_size=1)
  62. self.img_reader = ReadImage(format="BGR")
  63. def rotate_image(self, image_array: np.ndarray, rotate_angle: float) -> np.ndarray:
  64. """
  65. Rotate the given image array by the specified angle.
  66. Args:
  67. image_array (np.ndarray): The input image array to be rotated.
  68. rotate_angle (float): The angle in degrees by which to rotate the image.
  69. Returns:
  70. np.ndarray: The rotated image array.
  71. Raises:
  72. AssertionError: If rotate_angle is not in the range [0, 360).
  73. """
  74. assert (
  75. rotate_angle >= 0 and rotate_angle < 360
  76. ), "rotate_angle must in [0-360), but get {rotate_angle}."
  77. return rotate(image_array, rotate_angle, reshape=True)
  78. def check_model_settings_valid(self, model_settings: Dict) -> bool:
  79. """
  80. Check if the the input params for model settings are valid based on the initialized models.
  81. Args:
  82. model_settings (Dict): A dictionary containing model settings.
  83. Returns:
  84. bool: True if all required models are initialized according to the model settings, False otherwise.
  85. """
  86. if (
  87. model_settings["use_doc_orientation_classify"]
  88. and not self.use_doc_orientation_classify
  89. ):
  90. logging.error(
  91. "Set use_doc_orientation_classify, but the model for doc orientation classify is not initialized."
  92. )
  93. return False
  94. if model_settings["use_doc_unwarping"] and not self.use_doc_unwarping:
  95. logging.error(
  96. "Set use_doc_unwarping, but the model for doc unwarping is not initialized."
  97. )
  98. return False
  99. return True
  100. def get_model_settings(
  101. self, use_doc_orientation_classify, use_doc_unwarping
  102. ) -> dict:
  103. """
  104. Retrieve the model settings dictionary based on input parameters.
  105. Args:
  106. use_doc_orientation_classify (bool, optional): Whether to use document orientation classification.
  107. use_doc_unwarping (bool, optional): Whether to use document unwarping.
  108. Returns:
  109. dict: A dictionary containing the model settings.
  110. """
  111. if use_doc_orientation_classify is None:
  112. use_doc_orientation_classify = self.use_doc_orientation_classify
  113. if use_doc_unwarping is None:
  114. use_doc_unwarping = self.use_doc_unwarping
  115. model_settings = {
  116. "use_doc_orientation_classify": use_doc_orientation_classify,
  117. "use_doc_unwarping": use_doc_unwarping,
  118. }
  119. return model_settings
  120. def predict(
  121. self,
  122. input: str | list[str] | np.ndarray | list[np.ndarray],
  123. use_doc_orientation_classify: Optional[bool] = None,
  124. use_doc_unwarping: Optional[bool] = None,
  125. ) -> DocPreprocessorResult:
  126. """
  127. Predict the preprocessing result for the input image or images.
  128. Args:
  129. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or path(s) to the images or pdfs.
  130. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  131. use_doc_unwarping (bool): Whether to use document unwarping.
  132. **kwargs: Additional keyword arguments.
  133. Returns:
  134. DocPreprocessorResult: A generator yielding preprocessing results.
  135. """
  136. model_settings = self.get_model_settings(
  137. use_doc_orientation_classify, use_doc_unwarping
  138. )
  139. if not self.check_model_settings_valid(model_settings):
  140. yield {"error": "the input params for model settings are invalid!"}
  141. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  142. if not isinstance(batch_data[0], str):
  143. # TODO: add support input_pth for ndarray and pdf
  144. input_path = f"{img_id}"
  145. else:
  146. input_path = batch_data[0]
  147. image_array = self.img_reader(batch_data)[0]
  148. if model_settings["use_doc_orientation_classify"]:
  149. pred = next(self.doc_ori_classify_model(image_array))
  150. angle = int(pred["label_names"][0])
  151. rot_img = self.rotate_image(image_array, angle)
  152. else:
  153. angle = -1
  154. rot_img = image_array
  155. if model_settings["use_doc_unwarping"]:
  156. output_img = next(self.doc_unwarping_model(rot_img))["doctr_img"]
  157. else:
  158. output_img = rot_img
  159. single_img_res = {
  160. "input_path": input_path,
  161. "input_img": image_array,
  162. "model_settings": model_settings,
  163. "angle": angle,
  164. "rot_img": rot_img,
  165. "output_img": output_img,
  166. }
  167. yield DocPreprocessorResult(single_img_res)