pipeline.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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, Tuple, 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 ...models.formula_recognition.result import (
  21. FormulaRecResult as SingleFormulaRecognitionResult,
  22. )
  23. from ...models.object_detection.result import DetResult
  24. from ...utils.hpi import HPIConfig
  25. from ...utils.pp_option import PaddlePredictorOption
  26. from ..base import BasePipeline
  27. from ..components import CropByBoxes
  28. from .result import FormulaRecognitionResult
  29. @pipeline_requires_extra("ocr")
  30. class FormulaRecognitionPipeline(BasePipeline):
  31. """Formula Recognition Pipeline"""
  32. entities = ["formula_recognition"]
  33. def __init__(
  34. self,
  35. config: Dict,
  36. device: str = None,
  37. pp_option: PaddlePredictorOption = None,
  38. use_hpip: bool = False,
  39. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  40. ) -> None:
  41. """Initializes the formula recognition pipeline.
  42. Args:
  43. config (Dict): Configuration dictionary containing various settings.
  44. device (str, optional): Device to run the predictions on. Defaults to None.
  45. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  46. use_hpip (bool, optional): Whether to use the high-performance
  47. inference plugin (HPIP) by default. Defaults to False.
  48. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  49. The default high-performance inference configuration dictionary.
  50. Defaults to None.
  51. """
  52. super().__init__(
  53. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_config=hpi_config
  54. )
  55. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  56. if self.use_doc_preprocessor:
  57. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  58. "DocPreprocessor",
  59. {
  60. "pipeline_config_error": "config error for doc_preprocessor_pipeline!"
  61. },
  62. )
  63. self.doc_preprocessor_pipeline = self.create_pipeline(
  64. doc_preprocessor_config
  65. )
  66. self.use_layout_detection = config.get("use_layout_detection", True)
  67. if self.use_layout_detection:
  68. layout_det_config = config.get("SubModules", {}).get(
  69. "LayoutDetection",
  70. {"model_config_error": "config error for layout_det_model!"},
  71. )
  72. layout_kwargs = {}
  73. if (threshold := layout_det_config.get("threshold", None)) is not None:
  74. layout_kwargs["threshold"] = threshold
  75. if (layout_nms := layout_det_config.get("layout_nms", None)) is not None:
  76. layout_kwargs["layout_nms"] = layout_nms
  77. if (
  78. layout_unclip_ratio := layout_det_config.get(
  79. "layout_unclip_ratio", None
  80. )
  81. ) is not None:
  82. layout_kwargs["layout_unclip_ratio"] = layout_unclip_ratio
  83. if (
  84. layout_merge_bboxes_mode := layout_det_config.get(
  85. "layout_merge_bboxes_mode", None
  86. )
  87. ) is not None:
  88. layout_kwargs["layout_merge_bboxes_mode"] = layout_merge_bboxes_mode
  89. self.layout_det_model = self.create_model(
  90. layout_det_config, **layout_kwargs
  91. )
  92. formula_recognition_config = config.get("SubModules", {}).get(
  93. "FormulaRecognition",
  94. {"model_config_error": "config error for formula_rec_model!"},
  95. )
  96. self.formula_recognition_model = self.create_model(formula_recognition_config)
  97. self._crop_by_boxes = CropByBoxes()
  98. self.batch_sampler = ImageBatchSampler(batch_size=1)
  99. self.img_reader = ReadImage(format="BGR")
  100. def get_model_settings(
  101. self,
  102. use_doc_orientation_classify: Optional[bool],
  103. use_doc_unwarping: Optional[bool],
  104. use_layout_detection: Optional[bool],
  105. ) -> dict:
  106. """
  107. Get the model settings based on the provided parameters or default values.
  108. Args:
  109. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  110. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  111. use_layout_detection (Optional[bool]): Whether to use layout detection.
  112. Returns:
  113. dict: A dictionary containing the model settings.
  114. """
  115. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  116. use_doc_preprocessor = self.use_doc_preprocessor
  117. else:
  118. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  119. use_doc_preprocessor = True
  120. else:
  121. use_doc_preprocessor = False
  122. if use_layout_detection is None:
  123. use_layout_detection = self.use_layout_detection
  124. return dict(
  125. use_doc_preprocessor=use_doc_preprocessor,
  126. use_layout_detection=use_layout_detection,
  127. )
  128. def check_model_settings_valid(
  129. self, model_settings: Dict, layout_det_res: DetResult
  130. ) -> bool:
  131. """
  132. Check if the input parameters are valid based on the initialized models.
  133. Args:
  134. model_settings (Dict): A dictionary containing input parameters.
  135. layout_det_res (DetResult): The layout detection result.
  136. Returns:
  137. bool: True if all required models are initialized according to input parameters, False otherwise.
  138. """
  139. if model_settings["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  140. logging.error(
  141. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  142. )
  143. return False
  144. if model_settings["use_layout_detection"]:
  145. if layout_det_res is not None:
  146. logging.error(
  147. "The layout detection model has already been initialized, please set use_layout_detection=False"
  148. )
  149. return False
  150. if not self.use_layout_detection:
  151. logging.error(
  152. "Set use_layout_detection, but the models for layout detection are not initialized."
  153. )
  154. return False
  155. return True
  156. def predict_single_formula_recognition_res(
  157. self,
  158. image_array: np.ndarray,
  159. ) -> SingleFormulaRecognitionResult:
  160. """
  161. Predict formula recognition results from an image array, layout detection results.
  162. Args:
  163. image_array (np.ndarray): The input image represented as a numpy array.
  164. formula_box (list): The formula box coordinates.
  165. flag_find_nei_text (bool): Whether to find neighboring text.
  166. Returns:
  167. SingleFormulaRecognitionResult: single formula recognition result.
  168. """
  169. formula_recognition_pred = next(self.formula_recognition_model(image_array))
  170. return formula_recognition_pred
  171. def predict(
  172. self,
  173. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  174. use_layout_detection: Optional[bool] = None,
  175. use_doc_orientation_classify: Optional[bool] = None,
  176. use_doc_unwarping: Optional[bool] = None,
  177. layout_det_res: Optional[DetResult] = None,
  178. layout_threshold: Optional[Union[float, dict]] = None,
  179. layout_nms: Optional[bool] = None,
  180. layout_unclip_ratio: Optional[Union[float, Tuple[float, float]]] = None,
  181. layout_merge_bboxes_mode: Optional[str] = None,
  182. **kwargs,
  183. ) -> FormulaRecognitionResult:
  184. """
  185. This function predicts the layout parsing result for the given input.
  186. Args:
  187. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): The input image(s) of pdf(s) to be processed.
  188. use_layout_detection (Optional[bool]): Whether to use layout detection.
  189. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  190. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  191. layout_det_res (Optional[DetResult]): The layout detection result.
  192. It will be used if it is not None and use_layout_detection is False.
  193. **kwargs: Additional keyword arguments.
  194. Returns:
  195. formulaRecognitionResult: The predicted formula recognition result.
  196. """
  197. model_settings = self.get_model_settings(
  198. use_doc_orientation_classify,
  199. use_doc_unwarping,
  200. use_layout_detection,
  201. )
  202. if not self.check_model_settings_valid(model_settings, layout_det_res):
  203. yield {"error": "the input params for model settings are invalid!"}
  204. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  205. image_array = self.img_reader(batch_data.instances)[0]
  206. if model_settings["use_doc_preprocessor"]:
  207. doc_preprocessor_res = next(
  208. self.doc_preprocessor_pipeline(
  209. image_array,
  210. use_doc_orientation_classify=use_doc_orientation_classify,
  211. use_doc_unwarping=use_doc_unwarping,
  212. )
  213. )
  214. else:
  215. doc_preprocessor_res = {"output_img": image_array}
  216. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  217. formula_res_list = []
  218. formula_region_id = 1
  219. if not model_settings["use_layout_detection"] and layout_det_res is None:
  220. layout_det_res = {}
  221. img_height, img_width = doc_preprocessor_image.shape[:2]
  222. single_formula_rec_res = self.predict_single_formula_recognition_res(
  223. doc_preprocessor_image,
  224. )
  225. single_formula_rec_res["formula_region_id"] = formula_region_id
  226. formula_res_list.append(single_formula_rec_res)
  227. formula_region_id += 1
  228. else:
  229. if model_settings["use_layout_detection"]:
  230. layout_det_res = next(
  231. self.layout_det_model(
  232. doc_preprocessor_image,
  233. threshold=layout_threshold,
  234. layout_nms=layout_nms,
  235. layout_unclip_ratio=layout_unclip_ratio,
  236. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  237. )
  238. )
  239. formula_crop_img = []
  240. for box_info in layout_det_res["boxes"]:
  241. if box_info["label"].lower() in ["formula"]:
  242. crop_img_info = self._crop_by_boxes(
  243. doc_preprocessor_image, [box_info]
  244. )
  245. crop_img_info = crop_img_info[0]
  246. formula_crop_img.append(crop_img_info["img"])
  247. single_formula_rec_res = {}
  248. single_formula_rec_res["formula_region_id"] = formula_region_id
  249. single_formula_rec_res["dt_polys"] = box_info["coordinate"]
  250. formula_res_list.append(single_formula_rec_res)
  251. formula_region_id += 1
  252. for idx, formula_rec_res in enumerate(
  253. self.formula_recognition_model(formula_crop_img)
  254. ):
  255. formula_region_id = formula_res_list[idx]["formula_region_id"]
  256. dt_polys = formula_res_list[idx]["dt_polys"]
  257. formula_rec_res["formula_region_id"] = formula_region_id
  258. formula_rec_res["dt_polys"] = dt_polys
  259. formula_res_list[idx] = formula_rec_res
  260. single_img_res = {
  261. "input_path": batch_data.input_paths[0],
  262. "page_index": batch_data.page_indexes[0],
  263. "layout_det_res": layout_det_res,
  264. "doc_preprocessor_res": doc_preprocessor_res,
  265. "formula_res_list": formula_res_list,
  266. "model_settings": model_settings,
  267. }
  268. yield FormulaRecognitionResult(single_img_res)