pipeline.py 13 KB

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