pipeline.py 11 KB

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