pipeline.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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
  16. import numpy as np
  17. import cv2
  18. from ..base import BasePipeline
  19. from ..components import CropByBoxes
  20. # from ..layout_parsing.utils import convert_points_to_boxes
  21. from ..components import convert_points_to_boxes
  22. from .result import FormulaRecognitionResult
  23. from ...models_new.formula_recognition.result import (
  24. FormulaRecResult as SingleFormulaRecognitionResult,
  25. )
  26. from ....utils import logging
  27. from ...utils.pp_option import PaddlePredictorOption
  28. from ...common.reader import ReadImage
  29. from ...common.batch_sampler import ImageBatchSampler
  30. from ..ocr.result import OCRResult
  31. from ..doc_preprocessor.result import DocPreprocessorResult
  32. # [TODO] 待更新models_new到models
  33. from ...models_new.object_detection.result import DetResult
  34. class FormulaRecognitionPipeline(BasePipeline):
  35. """Formula Recognition Pipeline"""
  36. entities = ["formula_recognition"]
  37. def __init__(
  38. self,
  39. config: Dict,
  40. device: str = None,
  41. pp_option: PaddlePredictorOption = None,
  42. use_hpip: bool = False,
  43. hpi_params: Optional[Dict[str, Any]] = None,
  44. ) -> None:
  45. """Initializes the layout parsing pipeline.
  46. Args:
  47. config (Dict): Configuration dictionary containing various settings.
  48. device (str, optional): Device to run the predictions on. Defaults to None.
  49. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  50. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  51. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  52. """
  53. super().__init__(
  54. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  55. )
  56. self.use_doc_preprocessor = False
  57. if "use_doc_preprocessor" in config:
  58. self.use_doc_preprocessor = config["use_doc_preprocessor"]
  59. if self.use_doc_preprocessor:
  60. doc_preprocessor_config = config["SubPipelines"]["DocPreprocessor"]
  61. self.doc_preprocessor_pipeline = self.create_pipeline(
  62. doc_preprocessor_config
  63. )
  64. self.use_layout_detection = True
  65. if "use_layout_detection" in config:
  66. self.use_layout_detection = config["use_layout_detection"]
  67. if self.use_layout_detection:
  68. layout_det_config = config["SubModules"]["LayoutDetection"]
  69. self.layout_det_model = self.create_model(layout_det_config)
  70. formula_recognition_config = config["SubModules"]["FormulaRecognition"]
  71. self.formula_recognition_model = self.create_model(formula_recognition_config)
  72. self._crop_by_boxes = CropByBoxes()
  73. self.batch_sampler = ImageBatchSampler(batch_size=1)
  74. self.img_reader = ReadImage(format="BGR")
  75. def check_input_params_valid(
  76. self, input_params: Dict, layout_det_res: DetResult
  77. ) -> bool:
  78. """
  79. Check if the input parameters are valid based on the initialized models.
  80. Args:
  81. input_params (Dict): A dictionary containing input parameters.
  82. layout_det_res (DetResult): The layout detection result.
  83. Returns:
  84. bool: True if all required models are initialized according to input parameters, False otherwise.
  85. """
  86. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  87. logging.error(
  88. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  89. )
  90. return False
  91. if input_params["use_layout_detection"]:
  92. if layout_det_res is not None:
  93. logging.error(
  94. "The layout detection model has already been initialized, please set use_layout_detection=False"
  95. )
  96. return False
  97. if not self.use_layout_detection:
  98. logging.error(
  99. "Set use_layout_detection, but the models for layout detection are not initialized."
  100. )
  101. return False
  102. return True
  103. def predict_doc_preprocessor_res(
  104. self, image_array: np.ndarray, input_params: dict
  105. ) -> tuple[DocPreprocessorResult, np.ndarray]:
  106. """
  107. Preprocess the document image based on input parameters.
  108. Args:
  109. image_array (np.ndarray): The input image array.
  110. input_params (dict): Dictionary containing preprocessing parameters.
  111. Returns:
  112. tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
  113. result dictionary and the processed image array.
  114. """
  115. if input_params["use_doc_preprocessor"]:
  116. use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
  117. use_doc_unwarping = input_params["use_doc_unwarping"]
  118. doc_preprocessor_res = next(
  119. self.doc_preprocessor_pipeline(
  120. image_array,
  121. use_doc_orientation_classify=use_doc_orientation_classify,
  122. use_doc_unwarping=use_doc_unwarping,
  123. )
  124. )
  125. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  126. else:
  127. doc_preprocessor_res = {}
  128. doc_preprocessor_image = image_array
  129. return doc_preprocessor_res, doc_preprocessor_image
  130. def predict_single_formula_recognition_res(
  131. self,
  132. image_array: np.ndarray,
  133. ) -> SingleFormulaRecognitionResult:
  134. """
  135. Predict formula recognition results from an image array, layout detection results.
  136. Args:
  137. image_array (np.ndarray): The input image represented as a numpy array.
  138. formula_box (list): The formula box coordinates.
  139. flag_find_nei_text (bool): Whether to find neighboring text.
  140. Returns:
  141. SingleFormulaRecognitionResult: single formula recognition result.
  142. """
  143. formula_recognition_pred = next(self.formula_recognition_model(image_array))
  144. return formula_recognition_pred
  145. def predict(
  146. self,
  147. input: str | list[str] | np.ndarray | list[np.ndarray],
  148. use_layout_detection: bool = True,
  149. use_doc_orientation_classify: bool = False,
  150. use_doc_unwarping: bool = False,
  151. layout_det_res: DetResult = None,
  152. **kwargs
  153. ) -> FormulaRecognitionResult:
  154. """
  155. This function predicts the layout parsing result for the given input.
  156. Args:
  157. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) of pdf(s) to be processed.
  158. use_layout_detection (bool): Whether to use layout detection.
  159. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  160. use_doc_unwarping (bool): Whether to use document unwarping.
  161. layout_det_res (DetResult): The layout detection result.
  162. It will be used if it is not None and use_layout_detection is False.
  163. **kwargs: Additional keyword arguments.
  164. Returns:
  165. formulaRecognitionResult: The predicted formula recognition result.
  166. """
  167. input_params = {
  168. "use_layout_detection": use_layout_detection,
  169. "use_doc_preprocessor": self.use_doc_preprocessor,
  170. "use_doc_orientation_classify": use_doc_orientation_classify,
  171. "use_doc_unwarping": use_doc_unwarping,
  172. }
  173. if use_doc_orientation_classify or use_doc_unwarping:
  174. input_params["use_doc_preprocessor"] = True
  175. else:
  176. input_params["use_doc_preprocessor"] = False
  177. if not self.check_input_params_valid(input_params, layout_det_res):
  178. yield None
  179. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  180. image_array = self.img_reader(batch_data)[0]
  181. input_path = batch_data[0]
  182. img_id += 1
  183. doc_preprocessor_res, doc_preprocessor_image = (
  184. self.predict_doc_preprocessor_res(image_array, input_params)
  185. )
  186. formula_res_list = []
  187. formula_region_id = 1
  188. if not input_params["use_layout_detection"] and layout_det_res is None:
  189. layout_det_res = {}
  190. img_height, img_width = doc_preprocessor_image.shape[:2]
  191. single_formula_rec_res = self.predict_single_formula_recognition_res(
  192. doc_preprocessor_image,
  193. )
  194. single_formula_rec_res["formula_region_id"] = formula_region_id
  195. formula_res_list.append(single_formula_rec_res)
  196. formula_region_id += 1
  197. else:
  198. if input_params["use_layout_detection"]:
  199. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  200. for box_info in layout_det_res["boxes"]:
  201. if box_info["label"].lower() in ["formula"]:
  202. crop_img_info = self._crop_by_boxes(image_array, [box_info])
  203. crop_img_info = crop_img_info[0]
  204. single_formula_rec_res = (
  205. self.predict_single_formula_recognition_res(
  206. crop_img_info["img"]
  207. )
  208. )
  209. single_formula_rec_res["formula_region_id"] = formula_region_id
  210. single_formula_rec_res["dt_polys"] = box_info["coordinate"]
  211. formula_res_list.append(single_formula_rec_res)
  212. formula_region_id += 1
  213. single_img_res = {
  214. "layout_det_res": layout_det_res,
  215. "doc_preprocessor_res": doc_preprocessor_res,
  216. "formula_res_list": formula_res_list,
  217. "input_params": input_params,
  218. "img_id": img_id,
  219. "img_name": input_path,
  220. }
  221. yield FormulaRecognitionResult(single_img_res)