pipeline.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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, Union
  15. import numpy as np
  16. from ....utils import logging
  17. from ....utils.deps import pipeline_requires_extra
  18. from ...common.batch_sampler import ImageBatchSampler
  19. from ...common.reader import ReadImage
  20. from ...utils.benchmark import benchmark
  21. from ...utils.hpi import HPIConfig
  22. from ...utils.pp_option import PaddlePredictorOption
  23. from .._parallel import AutoParallelImageSimpleInferencePipeline
  24. from ..base import BasePipeline
  25. from ..components import (
  26. CropByPolys,
  27. SortPolyBoxes,
  28. SortQuadBoxes,
  29. cal_ocr_word_box,
  30. convert_points_to_boxes,
  31. rotate_image,
  32. )
  33. from .result import OCRResult
  34. @benchmark.time_methods
  35. class _OCRPipeline(BasePipeline):
  36. """OCR Pipeline"""
  37. def __init__(
  38. self,
  39. config: Dict,
  40. device: Optional[str] = None,
  41. pp_option: Optional[PaddlePredictorOption] = None,
  42. use_hpip: bool = False,
  43. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  44. ) -> None:
  45. """
  46. Initializes the class with given configurations and options.
  47. Args:
  48. config (Dict): Configuration dictionary containing various settings.
  49. device (str, optional): Device to run the predictions on. Defaults to None.
  50. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  51. use_hpip (bool, optional): Whether to use the high-performance
  52. inference plugin (HPIP) by default. Defaults to False.
  53. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  54. The default high-performance inference configuration dictionary.
  55. Defaults to None.
  56. """
  57. super().__init__(
  58. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_config=hpi_config
  59. )
  60. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  61. if self.use_doc_preprocessor:
  62. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  63. "DocPreprocessor",
  64. {
  65. "pipeline_config_error": "config error for doc_preprocessor_pipeline!"
  66. },
  67. )
  68. self.doc_preprocessor_pipeline = self.create_pipeline(
  69. doc_preprocessor_config
  70. )
  71. self.use_textline_orientation = config.get("use_textline_orientation", True)
  72. if self.use_textline_orientation:
  73. textline_orientation_config = config.get("SubModules", {}).get(
  74. "TextLineOrientation",
  75. {"model_config_error": "config error for textline_orientation_model!"},
  76. )
  77. self.textline_orientation_model = self.create_model(
  78. textline_orientation_config
  79. )
  80. text_det_config = config.get("SubModules", {}).get(
  81. "TextDetection", {"model_config_error": "config error for text_det_model!"}
  82. )
  83. self.text_type = config["text_type"]
  84. if self.text_type == "general":
  85. self.text_det_limit_side_len = text_det_config.get("limit_side_len", 960)
  86. self.text_det_limit_type = text_det_config.get("limit_type", "max")
  87. self.text_det_max_side_limit = text_det_config.get("max_side_limit", 4000)
  88. self.text_det_thresh = text_det_config.get("thresh", 0.3)
  89. self.text_det_box_thresh = text_det_config.get("box_thresh", 0.6)
  90. self.input_shape = text_det_config.get("input_shape", None)
  91. self.text_det_unclip_ratio = text_det_config.get("unclip_ratio", 2.0)
  92. self._sort_boxes = SortQuadBoxes()
  93. self._crop_by_polys = CropByPolys(det_box_type="quad")
  94. elif self.text_type == "seal":
  95. self.text_det_limit_side_len = text_det_config.get("limit_side_len", 736)
  96. self.text_det_limit_type = text_det_config.get("limit_type", "min")
  97. self.text_det_max_side_limit = text_det_config.get("max_side_limit", 4000)
  98. self.text_det_thresh = text_det_config.get("thresh", 0.2)
  99. self.text_det_box_thresh = text_det_config.get("box_thresh", 0.6)
  100. self.text_det_unclip_ratio = text_det_config.get("unclip_ratio", 0.5)
  101. self.input_shape = text_det_config.get("input_shape", None)
  102. self._sort_boxes = SortPolyBoxes()
  103. self._crop_by_polys = CropByPolys(det_box_type="poly")
  104. else:
  105. raise ValueError("Unsupported text type {}".format(self.text_type))
  106. self.text_det_model = self.create_model(
  107. text_det_config,
  108. limit_side_len=self.text_det_limit_side_len,
  109. limit_type=self.text_det_limit_type,
  110. max_side_limit=self.text_det_max_side_limit,
  111. thresh=self.text_det_thresh,
  112. box_thresh=self.text_det_box_thresh,
  113. unclip_ratio=self.text_det_unclip_ratio,
  114. input_shape=self.input_shape,
  115. )
  116. text_rec_config = config.get("SubModules", {}).get(
  117. "TextRecognition",
  118. {"model_config_error": "config error for text_rec_model!"},
  119. )
  120. self.text_rec_score_thresh = text_rec_config.get("score_thresh", 0)
  121. self.return_word_box = text_rec_config.get("return_word_box", False)
  122. self.input_shape = text_rec_config.get("input_shape", None)
  123. self.text_rec_model = self.create_model(
  124. text_rec_config, input_shape=self.input_shape
  125. )
  126. self.batch_sampler = ImageBatchSampler(batch_size=config.get("batch_size", 1))
  127. self.img_reader = ReadImage(format="BGR")
  128. def rotate_image(
  129. self, image_array_list: List[np.ndarray], rotate_angle_list: List[int]
  130. ) -> List[np.ndarray]:
  131. """
  132. Rotate the given image arrays by their corresponding angles.
  133. 0 corresponds to 0 degrees, 1 corresponds to 180 degrees.
  134. Args:
  135. image_array_list (List[np.ndarray]): A list of input image arrays to be rotated.
  136. rotate_angle_list (List[int]): A list of rotation indicators (0 or 1).
  137. 0 means rotate by 0 degrees
  138. 1 means rotate by 180 degrees
  139. Returns:
  140. List[np.ndarray]: A list of rotated image arrays.
  141. Raises:
  142. AssertionError: If any rotate_angle is not 0 or 1.
  143. AssertionError: If the lengths of input lists don't match.
  144. """
  145. assert len(image_array_list) == len(
  146. rotate_angle_list
  147. ), f"Length of image_array_list ({len(image_array_list)}) must match length of rotate_angle_list ({len(rotate_angle_list)})"
  148. for angle in rotate_angle_list:
  149. assert angle in [0, 1], f"rotate_angle must be 0 or 1, now it's {angle}"
  150. rotated_images = []
  151. for image_array, rotate_indicator in zip(image_array_list, rotate_angle_list):
  152. # Convert 0/1 indicator to actual rotation angle
  153. rotate_angle = rotate_indicator * 180
  154. rotated_image = rotate_image(image_array, rotate_angle)
  155. rotated_images.append(rotated_image)
  156. return rotated_images
  157. def check_model_settings_valid(self, model_settings: Dict) -> bool:
  158. """
  159. Check if the input parameters are valid based on the initialized models.
  160. Args:
  161. model_info_params(Dict): A dictionary containing input parameters.
  162. Returns:
  163. bool: True if all required models are initialized according to input parameters, False otherwise.
  164. """
  165. if model_settings["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  166. logging.error(
  167. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  168. )
  169. return False
  170. if (
  171. model_settings["use_textline_orientation"]
  172. and not self.use_textline_orientation
  173. ):
  174. logging.error(
  175. "Set use_textline_orientation, but the models for use_textline_orientation are not initialized."
  176. )
  177. return False
  178. return True
  179. def get_model_settings(
  180. self,
  181. use_doc_orientation_classify: Optional[bool],
  182. use_doc_unwarping: Optional[bool],
  183. use_textline_orientation: Optional[bool],
  184. ) -> dict:
  185. """
  186. Get the model settings based on the provided parameters or default values.
  187. Args:
  188. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  189. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  190. use_textline_orientation (Optional[bool]): Whether to use textline orientation.
  191. Returns:
  192. dict: A dictionary containing the model settings.
  193. """
  194. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  195. use_doc_preprocessor = self.use_doc_preprocessor
  196. else:
  197. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  198. use_doc_preprocessor = True
  199. else:
  200. use_doc_preprocessor = False
  201. if use_textline_orientation is None:
  202. use_textline_orientation = self.use_textline_orientation
  203. return dict(
  204. use_doc_preprocessor=use_doc_preprocessor,
  205. use_textline_orientation=use_textline_orientation,
  206. )
  207. def get_text_det_params(
  208. self,
  209. text_det_limit_side_len: Optional[int] = None,
  210. text_det_limit_type: Optional[str] = None,
  211. text_det_max_side_limit: Optional[int] = None,
  212. text_det_thresh: Optional[float] = None,
  213. text_det_box_thresh: Optional[float] = None,
  214. text_det_unclip_ratio: Optional[float] = None,
  215. ) -> dict:
  216. """
  217. Get text detection parameters.
  218. If a parameter is None, its default value from the instance will be used.
  219. Args:
  220. text_det_limit_side_len (Optional[int]): The maximum side length of the text box.
  221. text_det_limit_type (Optional[str]): The type of limit to apply to the text box.
  222. text_det_max_side_limit (Optional[int]): The maximum side length of the text box.
  223. text_det_thresh (Optional[float]): The threshold for text detection.
  224. text_det_box_thresh (Optional[float]): The threshold for the bounding box.
  225. text_det_unclip_ratio (Optional[float]): The ratio for unclipping the text box.
  226. Returns:
  227. dict: A dictionary containing the text detection parameters.
  228. """
  229. if text_det_limit_side_len is None:
  230. text_det_limit_side_len = self.text_det_limit_side_len
  231. if text_det_limit_type is None:
  232. text_det_limit_type = self.text_det_limit_type
  233. if text_det_max_side_limit is None:
  234. text_det_max_side_limit = self.text_det_max_side_limit
  235. if text_det_thresh is None:
  236. text_det_thresh = self.text_det_thresh
  237. if text_det_box_thresh is None:
  238. text_det_box_thresh = self.text_det_box_thresh
  239. if text_det_unclip_ratio is None:
  240. text_det_unclip_ratio = self.text_det_unclip_ratio
  241. return dict(
  242. limit_side_len=text_det_limit_side_len,
  243. limit_type=text_det_limit_type,
  244. thresh=text_det_thresh,
  245. max_side_limit=text_det_max_side_limit,
  246. box_thresh=text_det_box_thresh,
  247. unclip_ratio=text_det_unclip_ratio,
  248. )
  249. def predict(
  250. self,
  251. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  252. use_doc_orientation_classify: Optional[bool] = None,
  253. use_doc_unwarping: Optional[bool] = None,
  254. use_textline_orientation: Optional[bool] = None,
  255. text_det_limit_side_len: Optional[int] = None,
  256. text_det_limit_type: Optional[str] = None,
  257. text_det_max_side_limit: Optional[int] = None,
  258. text_det_thresh: Optional[float] = None,
  259. text_det_box_thresh: Optional[float] = None,
  260. text_det_unclip_ratio: Optional[float] = None,
  261. text_rec_score_thresh: Optional[float] = None,
  262. return_word_box: Optional[bool] = None,
  263. ) -> OCRResult:
  264. """
  265. Predict OCR results based on input images or arrays with optional preprocessing steps.
  266. Args:
  267. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): Input image of pdf path(s) or numpy array(s).
  268. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  269. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  270. use_textline_orientation (Optional[bool]): Whether to use textline orientation prediction.
  271. text_det_limit_side_len (Optional[int]): Maximum side length for text detection.
  272. text_det_limit_type (Optional[str]): Type of limit to apply for text detection.
  273. text_det_max_side_limit (Optional[int]): Maximum side length for text detection.
  274. text_det_thresh (Optional[float]): Threshold for text detection.
  275. text_det_box_thresh (Optional[float]): Threshold for text detection boxes.
  276. text_det_unclip_ratio (Optional[float]): Ratio for unclipping text detection boxes.
  277. text_rec_score_thresh (Optional[float]): Score threshold for text recognition.
  278. return_word_box (Optional[bool]): Whether to return word boxes along with recognized texts.
  279. Returns:
  280. OCRResult: Generator yielding OCR results for each input image.
  281. """
  282. model_settings = self.get_model_settings(
  283. use_doc_orientation_classify, use_doc_unwarping, use_textline_orientation
  284. )
  285. if not self.check_model_settings_valid(model_settings):
  286. yield {"error": "the input params for model settings are invalid!"}
  287. text_det_params = self.get_text_det_params(
  288. text_det_limit_side_len,
  289. text_det_limit_type,
  290. text_det_max_side_limit,
  291. text_det_thresh,
  292. text_det_box_thresh,
  293. text_det_unclip_ratio,
  294. )
  295. if text_rec_score_thresh is None:
  296. text_rec_score_thresh = self.text_rec_score_thresh
  297. if return_word_box is None:
  298. return_word_box = self.return_word_box
  299. for _, batch_data in enumerate(self.batch_sampler(input)):
  300. image_arrays = self.img_reader(batch_data.instances)
  301. if model_settings["use_doc_preprocessor"]:
  302. doc_preprocessor_results = list(
  303. self.doc_preprocessor_pipeline(
  304. image_arrays,
  305. use_doc_orientation_classify=use_doc_orientation_classify,
  306. use_doc_unwarping=use_doc_unwarping,
  307. )
  308. )
  309. else:
  310. doc_preprocessor_results = [{"output_img": arr} for arr in image_arrays]
  311. doc_preprocessor_images = [
  312. item["output_img"] for item in doc_preprocessor_results
  313. ]
  314. det_results = list(
  315. self.text_det_model(doc_preprocessor_images, **text_det_params)
  316. )
  317. dt_polys_list = [item["dt_polys"] for item in det_results]
  318. dt_polys_list = [self._sort_boxes(item) for item in dt_polys_list]
  319. results = [
  320. {
  321. "input_path": input_path,
  322. "page_index": page_index,
  323. "doc_preprocessor_res": doc_preprocessor_res,
  324. "dt_polys": dt_polys,
  325. "model_settings": model_settings,
  326. "text_det_params": text_det_params,
  327. "text_type": self.text_type,
  328. "text_rec_score_thresh": text_rec_score_thresh,
  329. "return_word_box": return_word_box,
  330. "rec_texts": [],
  331. "rec_scores": [],
  332. "rec_polys": [],
  333. "vis_fonts": [],
  334. }
  335. for input_path, page_index, doc_preprocessor_res, dt_polys in zip(
  336. batch_data.input_paths,
  337. batch_data.page_indexes,
  338. doc_preprocessor_results,
  339. dt_polys_list,
  340. )
  341. ]
  342. indices = list(range(len(doc_preprocessor_images)))
  343. indices = [idx for idx in indices if len(dt_polys_list[idx]) > 0]
  344. if indices:
  345. all_subs_of_imgs = []
  346. chunk_indices = [0]
  347. for idx in indices:
  348. all_subs_of_img = list(
  349. self._crop_by_polys(
  350. doc_preprocessor_images[idx], dt_polys_list[idx]
  351. )
  352. )
  353. all_subs_of_imgs.extend(all_subs_of_img)
  354. chunk_indices.append(chunk_indices[-1] + len(all_subs_of_img))
  355. # use textline orientation model
  356. if model_settings["use_textline_orientation"]:
  357. angles = [
  358. int(textline_angle_info["class_ids"][0])
  359. for textline_angle_info in self.textline_orientation_model(
  360. all_subs_of_imgs
  361. )
  362. ]
  363. all_subs_of_imgs = self.rotate_image(all_subs_of_imgs, angles)
  364. else:
  365. angles = [-1] * len(all_subs_of_imgs)
  366. for i, idx in enumerate(indices):
  367. res = results[idx]
  368. res["textline_orientation_angles"] = angles[
  369. chunk_indices[i] : chunk_indices[i + 1]
  370. ]
  371. # TODO: Process all sub-images in the batch together
  372. for i, idx in enumerate(indices):
  373. all_subs_of_img = all_subs_of_imgs[
  374. chunk_indices[i] : chunk_indices[i + 1]
  375. ]
  376. res = results[idx]
  377. dt_polys = dt_polys_list[idx]
  378. sub_img_info_list = [
  379. {
  380. "sub_img_id": img_id,
  381. "sub_img_ratio": sub_img.shape[1] / float(sub_img.shape[0]),
  382. }
  383. for img_id, sub_img in enumerate(all_subs_of_img)
  384. ]
  385. sorted_subs_info = sorted(
  386. sub_img_info_list, key=lambda x: x["sub_img_ratio"]
  387. )
  388. sorted_subs_of_img = [
  389. all_subs_of_img[x["sub_img_id"]] for x in sorted_subs_info
  390. ]
  391. for i, rec_res in enumerate(
  392. self.text_rec_model(
  393. sorted_subs_of_img, return_word_box=return_word_box
  394. )
  395. ):
  396. sub_img_id = sorted_subs_info[i]["sub_img_id"]
  397. sub_img_info_list[sub_img_id]["rec_res"] = rec_res
  398. if return_word_box:
  399. res["text_word"] = []
  400. res["text_word_region"] = []
  401. for sno in range(len(sub_img_info_list)):
  402. rec_res = sub_img_info_list[sno]["rec_res"]
  403. if rec_res["rec_score"] >= text_rec_score_thresh:
  404. if return_word_box:
  405. word_box_content_list, word_box_list = cal_ocr_word_box(
  406. rec_res["rec_text"][0],
  407. dt_polys[sno],
  408. rec_res["rec_text"][1],
  409. )
  410. res["text_word"].append(word_box_content_list)
  411. res["text_word_region"].append(word_box_list)
  412. res["rec_texts"].append(rec_res["rec_text"][0])
  413. else:
  414. res["rec_texts"].append(rec_res["rec_text"])
  415. res["rec_scores"].append(rec_res["rec_score"])
  416. res["vis_fonts"].append(rec_res["vis_font"])
  417. res["rec_polys"].append(dt_polys[sno])
  418. for res in results:
  419. if self.text_type == "general":
  420. rec_boxes = convert_points_to_boxes(res["rec_polys"])
  421. res["rec_boxes"] = rec_boxes
  422. if return_word_box:
  423. res["text_word_boxes"] = [
  424. convert_points_to_boxes(line)
  425. for line in res["text_word_region"]
  426. ]
  427. else:
  428. res["rec_boxes"] = np.array([])
  429. yield OCRResult(res)
  430. @pipeline_requires_extra("ocr", alt="ocr-core")
  431. class OCRPipeline(AutoParallelImageSimpleInferencePipeline):
  432. entities = "OCR"
  433. @property
  434. def _pipeline_cls(self):
  435. return _OCRPipeline
  436. def _get_batch_size(self, config):
  437. return config.get("batch_size", 1)