pipeline.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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, List, Optional
  15. import numpy as np
  16. from scipy.ndimage import rotate
  17. from ...common.reader import ReadImage
  18. from ...common.batch_sampler import ImageBatchSampler
  19. from ...utils.pp_option import PaddlePredictorOption
  20. from ..base import BasePipeline
  21. from ..components import CropByPolys, SortQuadBoxes, SortPolyBoxes
  22. from .result import OCRResult
  23. from ..doc_preprocessor.result import DocPreprocessorResult
  24. from ....utils import logging
  25. class OCRPipeline(BasePipeline):
  26. """OCR Pipeline"""
  27. entities = "OCR"
  28. def __init__(
  29. self,
  30. config: Dict,
  31. device: str = None,
  32. pp_option: PaddlePredictorOption = None,
  33. use_hpip: bool = False,
  34. hpi_params: Optional[Dict[str, Any]] = None,
  35. ) -> None:
  36. """
  37. Initializes the class with given configurations and options.
  38. Args:
  39. config (Dict): Configuration dictionary containing model and other parameters.
  40. device (str): The device to run the prediction on. Default is None.
  41. pp_option (PaddlePredictorOption): Options for PaddlePaddle predictor. Default is None.
  42. use_hpip (bool): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  43. hpi_params (Optional[Dict[str, Any]]): HPIP specific parameters. Default is None.
  44. """
  45. super().__init__(
  46. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  47. )
  48. self.inintial_predictor(config)
  49. self.text_type = config["text_type"]
  50. if self.text_type == "general":
  51. self._sort_boxes = SortQuadBoxes()
  52. self._crop_by_polys = CropByPolys(det_box_type="quad")
  53. elif self.text_type == "seal":
  54. self._sort_boxes = SortPolyBoxes()
  55. self._crop_by_polys = CropByPolys(det_box_type="poly")
  56. else:
  57. raise ValueError("Unsupported text type {}".format(self.text_type))
  58. self.batch_sampler = ImageBatchSampler(batch_size=1)
  59. self.img_reader = ReadImage(format="BGR")
  60. def set_used_models_flag(self, config: Dict) -> None:
  61. """
  62. Set the flags for which models to use based on the configuration.
  63. Args:
  64. config (Dict): A dictionary containing configuration settings.
  65. Returns:
  66. None
  67. """
  68. pipeline_name = config["pipeline_name"]
  69. self.pipeline_name = pipeline_name
  70. self.use_doc_preprocessor = False
  71. if "use_doc_preprocessor" in config:
  72. self.use_doc_preprocessor = config["use_doc_preprocessor"]
  73. self.use_textline_orientation = False
  74. if "use_textline_orientation" in config:
  75. self.use_textline_orientation = config["use_textline_orientation"]
  76. def inintial_predictor(self, config: Dict) -> None:
  77. """Initializes the predictor based on the provided configuration.
  78. Args:
  79. config (Dict): A dictionary containing the configuration for the predictor.
  80. Returns:
  81. None
  82. """
  83. self.set_used_models_flag(config)
  84. text_det_model_config = config["SubModules"]["TextDetection"]
  85. self.text_det_model = self.create_model(text_det_model_config)
  86. text_rec_model_config = config["SubModules"]["TextRecognition"]
  87. self.text_rec_model = self.create_model(text_rec_model_config)
  88. if self.use_doc_preprocessor:
  89. doc_preprocessor_config = config["SubPipelines"]["DocPreprocessor"]
  90. self.doc_preprocessor_pipeline = self.create_pipeline(
  91. doc_preprocessor_config
  92. )
  93. # Just for initialize the predictor
  94. if self.use_textline_orientation:
  95. textline_orientation_config = config["SubModules"]["TextLineOrientation"]
  96. self.textline_orientation_model = self.create_model(
  97. textline_orientation_config
  98. )
  99. return
  100. def rotate_image(
  101. self, image_array_list: List[np.ndarray], rotate_angle_list: List[int]
  102. ) -> List[np.ndarray]:
  103. """
  104. Rotate the given image arrays by their corresponding angles.
  105. 0 corresponds to 0 degrees, 1 corresponds to 180 degrees.
  106. Args:
  107. image_array_list (List[np.ndarray]): A list of input image arrays to be rotated.
  108. rotate_angle_list (List[int]): A list of rotation indicators (0 or 1).
  109. 0 means rotate by 0 degrees
  110. 1 means rotate by 180 degrees
  111. Returns:
  112. List[np.ndarray]: A list of rotated image arrays.
  113. Raises:
  114. AssertionError: If any rotate_angle is not 0 or 1.
  115. AssertionError: If the lengths of input lists don't match.
  116. """
  117. assert len(image_array_list) == len(
  118. rotate_angle_list
  119. ), f"Length of image_array_list ({len(image_array_list)}) must match length of rotate_angle_list ({len(rotate_angle_list)})"
  120. for angle in rotate_angle_list:
  121. assert angle in [0, 1], f"rotate_angle must be 0 or 1, now it's {angle}"
  122. rotated_images = []
  123. for image_array, rotate_indicator in zip(image_array_list, rotate_angle_list):
  124. # Convert 0/1 indicator to actual rotation angle
  125. rotate_angle = rotate_indicator * 180
  126. rotated_image = rotate(image_array, rotate_angle, reshape=True)
  127. rotated_images.append(rotated_image)
  128. return rotated_images
  129. def check_input_params_valid(self, input_params: Dict) -> bool:
  130. """
  131. Check if the input parameters are valid based on the initialized models.
  132. Args:
  133. input_params (Dict): A dictionary containing input parameters.
  134. Returns:
  135. bool: True if all required models are initialized according to input parameters, False otherwise.
  136. """
  137. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  138. logging.error(
  139. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  140. )
  141. return False
  142. if (
  143. input_params["use_textline_orientation"]
  144. and not self.use_textline_orientation
  145. ):
  146. logging.error(
  147. "Set use_textline_orientation, but the models for use_textline_orientation are not initialized."
  148. )
  149. return False
  150. return True
  151. def predict_doc_preprocessor_res(
  152. self, image_array: np.ndarray, input_params: dict
  153. ) -> tuple[DocPreprocessorResult, np.ndarray]:
  154. """
  155. Preprocess the document image based on input parameters.
  156. Args:
  157. image_array (np.ndarray): The input image array.
  158. input_params (dict): Dictionary containing preprocessing parameters.
  159. Returns:
  160. tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
  161. result dictionary and the processed image array.
  162. """
  163. if input_params["use_doc_preprocessor"]:
  164. use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
  165. use_doc_unwarping = input_params["use_doc_unwarping"]
  166. doc_preprocessor_res = next(
  167. self.doc_preprocessor_pipeline(
  168. image_array,
  169. use_doc_orientation_classify=use_doc_orientation_classify,
  170. use_doc_unwarping=use_doc_unwarping,
  171. )
  172. )
  173. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  174. else:
  175. doc_preprocessor_res = {}
  176. doc_preprocessor_image = image_array
  177. return doc_preprocessor_res, doc_preprocessor_image
  178. def predict(
  179. self,
  180. input: str | list[str] | np.ndarray | list[np.ndarray],
  181. use_doc_orientation_classify: bool = False,
  182. use_doc_unwarping: bool = False,
  183. use_textline_orientation: bool = False,
  184. **kwargs,
  185. ) -> OCRResult:
  186. """Predicts OCR results for the given input.
  187. Args:
  188. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or path(s) to the images or pdf(s).
  189. **kwargs: Additional keyword arguments that can be passed to the function.
  190. Returns:
  191. OCRResult: An iterable of OCRResult objects, each containing the predicted text and other relevant information.
  192. """
  193. input_params = {
  194. "use_doc_preprocessor": self.use_doc_preprocessor,
  195. "use_doc_orientation_classify": use_doc_orientation_classify,
  196. "use_doc_unwarping": use_doc_unwarping,
  197. "use_textline_orientation": self.use_textline_orientation,
  198. }
  199. if use_doc_orientation_classify or use_doc_unwarping:
  200. input_params["use_doc_preprocessor"] = True
  201. else:
  202. input_params["use_doc_preprocessor"] = False
  203. if not self.check_input_params_valid(input_params):
  204. yield None
  205. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  206. image_array = self.img_reader(batch_data)[0]
  207. img_id += 1
  208. doc_preprocessor_res, doc_preprocessor_image = (
  209. self.predict_doc_preprocessor_res(image_array, input_params)
  210. )
  211. det_res = next(self.text_det_model(doc_preprocessor_image))
  212. dt_polys = det_res["dt_polys"]
  213. dt_scores = det_res["dt_scores"]
  214. ########## [TODO] Need to confirm filtering thresholds for detection and recognition modules
  215. dt_polys = self._sort_boxes(dt_polys)
  216. single_img_res = {
  217. "doc_preprocessor_image": doc_preprocessor_image,
  218. "doc_preprocessor_res": doc_preprocessor_res,
  219. "dt_polys": dt_polys,
  220. "img_id": img_id,
  221. "input_params": input_params,
  222. "text_type": self.text_type,
  223. }
  224. single_img_res["rec_text"] = []
  225. single_img_res["rec_score"] = []
  226. if len(dt_polys) > 0:
  227. all_subs_of_img = list(
  228. self._crop_by_polys(doc_preprocessor_image, dt_polys)
  229. )
  230. # use textline orientation model
  231. if input_params["use_textline_orientation"]:
  232. angles = [
  233. textline_angle_info["class_ids"][0]
  234. for textline_angle_info in self.textline_orientation_model(
  235. all_subs_of_img
  236. )
  237. ]
  238. all_subs_of_img = self.rotate_image(all_subs_of_img, angles)
  239. for rec_res in self.text_rec_model(all_subs_of_img):
  240. single_img_res["rec_text"].append(rec_res["rec_text"])
  241. single_img_res["rec_score"].append(rec_res["rec_score"])
  242. yield OCRResult(single_img_res)