pipeline.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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: Optional[str] = None,
  32. use_doc_orientation_classify: Optional[bool] = None,
  33. use_doc_unwarping: Optional[bool] = None,
  34. use_textline_orientation: Optional[bool] = None,
  35. limit_side_len: Optional[int] = None,
  36. limit_type: Optional[str] = None,
  37. thresh: Optional[float] = None,
  38. box_thresh: Optional[float] = None,
  39. max_candidates: Optional[int] = None,
  40. unclip_ratio: Optional[float] = None,
  41. use_dilation: Optional[bool] = None,
  42. pp_option: Optional[PaddlePredictorOption] = None,
  43. use_hpip: bool = False,
  44. hpi_params: Optional[Dict[str, Any]] = None,
  45. ) -> None:
  46. """
  47. Initializes the class with given configurations and options.
  48. Args:
  49. config (Dict): Configuration dictionary containing model and other parameters.
  50. device (Union[str, None]): The device to run the prediction on.
  51. use_textline_orientation (Union[bool, None]): Whether to use textline orientation.
  52. use_doc_orientation_classify (Union[bool, None]): Whether to use document orientation classification.
  53. use_doc_unwarping (Union[bool, None]): Whether to use document unwarping.
  54. limit_side_len (Union[int, None]): Limit of side length.
  55. limit_type (Union[str, None]): Type of limit.
  56. thresh (Union[float, None]): Threshold value.
  57. box_thresh (Union[float, None]): Box threshold value.
  58. max_candidates (Union[int, None]): Maximum number of candidates.
  59. unclip_ratio (Union[float, None]): Unclip ratio.
  60. use_dilation (Union[bool, None]): Whether to use dilation.
  61. pp_option (Union[PaddlePredictorOption, None]): Options for PaddlePaddle predictor.
  62. use_hpip (Union[bool, None]): Whether to use high-performance inference.
  63. hpi_params (Union[Dict[str, Any], None]): HPIP specific parameters.
  64. """
  65. super().__init__(
  66. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  67. )
  68. self.use_textline_orientation = (
  69. use_textline_orientation
  70. if use_textline_orientation is not None
  71. else config.get("use_textline_orientation", False)
  72. )
  73. self.use_doc_preprocessor = self.get_preprocessor_value(
  74. use_doc_orientation_classify, use_doc_unwarping, config, False
  75. )
  76. text_det_default_params = {
  77. "limit_side_len": 960,
  78. "limit_type": "max",
  79. "thresh": 0.3,
  80. "box_thresh": 0.6,
  81. "max_candidates": 1000,
  82. "unclip_ratio": 2.0,
  83. "use_dilation": False,
  84. }
  85. text_det_config = config["SubModules"]["TextDetection"]
  86. for key, default_params in text_det_default_params.items():
  87. text_det_config[key] = locals().get(
  88. key, text_det_config.get(key, default_params)
  89. )
  90. self.text_det_model = self.create_model(text_det_config)
  91. text_rec_config = config["SubModules"]["TextRecognition"]
  92. self.text_rec_model = self.create_model(text_rec_config)
  93. if self.use_textline_orientation:
  94. textline_orientation_config = config["SubModules"]["TextLineOrientation"]
  95. self.textline_orientation_model = self.create_model(
  96. textline_orientation_config
  97. )
  98. if self.use_doc_preprocessor:
  99. doc_preprocessor_config = config["SubPipelines"]["DocPreprocessor"]
  100. self.doc_preprocessor_pipeline = self.create_pipeline(
  101. doc_preprocessor_config
  102. )
  103. self.text_type = config["text_type"]
  104. if self.text_type == "general":
  105. self._sort_boxes = SortQuadBoxes()
  106. self._crop_by_polys = CropByPolys(det_box_type="quad")
  107. elif self.text_type == "seal":
  108. self._sort_boxes = SortPolyBoxes()
  109. self._crop_by_polys = CropByPolys(det_box_type="poly")
  110. else:
  111. raise ValueError("Unsupported text type {}".format(self.text_type))
  112. self.batch_sampler = ImageBatchSampler(batch_size=1)
  113. self.img_reader = ReadImage(format="BGR")
  114. @staticmethod
  115. def get_preprocessor_value(orientation, unwarping, config, default):
  116. if orientation is None and unwarping is None:
  117. return config.get("use_doc_preprocessor", default)
  118. else:
  119. if orientation is False and unwarping is False:
  120. return False
  121. else:
  122. return True
  123. def rotate_image(
  124. self, image_array_list: List[np.ndarray], rotate_angle_list: List[int]
  125. ) -> List[np.ndarray]:
  126. """
  127. Rotate the given image arrays by their corresponding angles.
  128. 0 corresponds to 0 degrees, 1 corresponds to 180 degrees.
  129. Args:
  130. image_array_list (List[np.ndarray]): A list of input image arrays to be rotated.
  131. rotate_angle_list (List[int]): A list of rotation indicators (0 or 1).
  132. 0 means rotate by 0 degrees
  133. 1 means rotate by 180 degrees
  134. Returns:
  135. List[np.ndarray]: A list of rotated image arrays.
  136. Raises:
  137. AssertionError: If any rotate_angle is not 0 or 1.
  138. AssertionError: If the lengths of input lists don't match.
  139. """
  140. assert len(image_array_list) == len(
  141. rotate_angle_list
  142. ), f"Length of image_array_list ({len(image_array_list)}) must match length of rotate_angle_list ({len(rotate_angle_list)})"
  143. for angle in rotate_angle_list:
  144. assert angle in [0, 1], f"rotate_angle must be 0 or 1, now it's {angle}"
  145. rotated_images = []
  146. for image_array, rotate_indicator in zip(image_array_list, rotate_angle_list):
  147. # Convert 0/1 indicator to actual rotation angle
  148. rotate_angle = rotate_indicator * 180
  149. rotated_image = rotate(image_array, rotate_angle, reshape=True)
  150. rotated_images.append(rotated_image)
  151. return rotated_images
  152. def check_model_settings_valid(self, model_settings: Dict) -> bool:
  153. """
  154. Check if the input parameters are valid based on the initialized models.
  155. Args:
  156. model_info_params(Dict): A dictionary containing input parameters.
  157. Returns:
  158. bool: True if all required models are initialized according to input parameters, False otherwise.
  159. """
  160. if model_settings["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  161. logging.error(
  162. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  163. )
  164. return False
  165. if (
  166. model_settings["use_textline_orientation"]
  167. and not self.use_textline_orientation
  168. ):
  169. logging.error(
  170. "Set use_textline_orientation, but the models for use_textline_orientation are not initialized."
  171. )
  172. return False
  173. return True
  174. def predict_doc_preprocessor_res(
  175. self, image_array: np.ndarray, input_params: dict
  176. ) -> tuple[DocPreprocessorResult, np.ndarray]:
  177. """
  178. Preprocess the document image based on input parameters.
  179. Args:
  180. image_array (np.ndarray): The input image array.
  181. input_params (dict): Dictionary containing preprocessing parameters.
  182. Returns:
  183. tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
  184. result dictionary and the processed image array.
  185. """
  186. if input_params["use_doc_preprocessor"]:
  187. use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
  188. use_doc_unwarping = input_params["use_doc_unwarping"]
  189. doc_preprocessor_res = next(
  190. self.doc_preprocessor_pipeline(
  191. image_array,
  192. use_doc_orientation_classify=use_doc_orientation_classify,
  193. use_doc_unwarping=use_doc_unwarping,
  194. )
  195. )
  196. else:
  197. doc_preprocessor_res = {"output_img": image_array}
  198. return doc_preprocessor_res
  199. def predict(
  200. self,
  201. input: str | list[str] | np.ndarray | list[np.ndarray],
  202. use_doc_orientation_classify: bool = False,
  203. use_doc_unwarping: bool = False,
  204. use_textline_orientation: bool = False,
  205. limit_side_len: int = 960,
  206. limit_type: str = "max",
  207. thresh: float = 0.3,
  208. box_thresh: float = 0.6,
  209. max_candidates: int = 1000,
  210. unclip_ratio: float = 2.0,
  211. use_dilation: bool = False,
  212. **kwargs,
  213. ) -> OCRResult:
  214. """Predicts OCR results for the given input.
  215. Args:
  216. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or path(s) to the images or pdf(s).
  217. **kwargs: Additional keyword arguments that can be passed to the function.
  218. Returns:
  219. OCRResult: An iterable of OCRResult objects, each containing the predicted text and other relevant information.
  220. """
  221. model_settings = {
  222. "use_doc_orientation_classify": use_doc_orientation_classify,
  223. "use_doc_unwarping": use_doc_unwarping,
  224. "use_textline_orientation": use_textline_orientation,
  225. }
  226. if use_doc_orientation_classify or use_doc_unwarping:
  227. model_settings["use_doc_preprocessor"] = True
  228. else:
  229. model_settings["use_doc_preprocessor"] = False
  230. if not self.check_model_settings_valid(model_settings):
  231. yield None
  232. text_det_params = {
  233. "limit_side_len": limit_side_len,
  234. "limit_type": limit_type,
  235. "thresh": thresh,
  236. "box_thresh": box_thresh,
  237. "max_candidates": max_candidates,
  238. "unclip_ratio": unclip_ratio,
  239. "use_dilation": use_dilation,
  240. }
  241. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  242. image_array = self.img_reader(batch_data)[0]
  243. img_id += 1
  244. doc_preprocessor_res = self.predict_doc_preprocessor_res(
  245. image_array, model_settings
  246. )
  247. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  248. det_res = next(
  249. self.text_det_model(doc_preprocessor_image, **text_det_params)
  250. )
  251. dt_polys = det_res["dt_polys"]
  252. dt_scores = det_res["dt_scores"]
  253. dt_polys = self._sort_boxes(dt_polys)
  254. single_img_res = {
  255. "input_path": input,
  256. # TODO: `doc_preprocessor_image` parameter does not need to be retained here, it requires further confirmation.
  257. "doc_preprocessor_image": doc_preprocessor_image,
  258. "doc_preprocessor_res": doc_preprocessor_res,
  259. "dt_polys": dt_polys,
  260. "img_id": img_id,
  261. "input_params": model_settings,
  262. "text_det_params": text_det_params,
  263. "text_type": self.text_type,
  264. }
  265. single_img_res["rec_text"] = []
  266. single_img_res["rec_score"] = []
  267. if len(dt_polys) > 0:
  268. all_subs_of_img = list(
  269. self._crop_by_polys(doc_preprocessor_image, dt_polys)
  270. )
  271. # use textline orientation model
  272. if model_settings["use_textline_orientation"]:
  273. angles = [
  274. textline_angle_info["class_ids"][0]
  275. for textline_angle_info in self.textline_orientation_model(
  276. all_subs_of_img
  277. )
  278. ]
  279. single_img_res["textline_orientation_angle"] = angles
  280. all_subs_of_img = self.rotate_image(all_subs_of_img, angles)
  281. for rec_res in self.text_rec_model(all_subs_of_img):
  282. single_img_res["rec_text"].append(rec_res["rec_text"])
  283. single_img_res["rec_score"].append(rec_res["rec_score"])
  284. yield OCRResult(single_img_res)