pipeline.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. from ..base import BasePipeline
  15. from typing import Any, Dict, Optional
  16. import numpy as np
  17. import cv2
  18. from ..components import CropByBoxes
  19. from .utils import convert_points_to_boxes, get_sub_regions_ocr_res
  20. from .table_recognition_post_processing import get_table_recognition_res
  21. from .result import LayoutParsingResult
  22. ########## [TODO]后续需要更新路径
  23. from ...components.transforms import ReadImage
  24. class LayoutParsingPipeline(BasePipeline):
  25. """Layout Parsing Pipeline"""
  26. entities = "layout_parsing"
  27. def __init__(self,
  28. config,
  29. device=None,
  30. pp_option=None,
  31. use_hpip: bool = False,
  32. hpi_params: Optional[Dict[str, Any]] = None):
  33. super().__init__(device=device, pp_option=pp_option,
  34. use_hpip=use_hpip, hpi_params=hpi_params)
  35. self.inintial_predictor(config)
  36. self.img_reader = ReadImage(format="BGR")
  37. self._crop_by_boxes = CropByBoxes()
  38. def inintial_predictor(self, config):
  39. layout_det_config = config['SubModules']["LayoutDetection"]
  40. self.layout_det_model = self.create_model(layout_det_config)
  41. self.use_doc_preprocessor = False
  42. if 'use_doc_preprocessor' in config:
  43. self.use_doc_preprocessor = config['use_doc_preprocessor']
  44. if self.use_doc_preprocessor:
  45. doc_preprocessor_config = config['SubPipelines']['DocPreprocessor']
  46. self.doc_preprocessor_pipeline = self.create_pipeline(doc_preprocessor_config)
  47. self.use_common_ocr = False
  48. if "use_common_ocr" in config:
  49. self.use_common_ocr = config['use_common_ocr']
  50. if self.use_common_ocr:
  51. common_ocr_config = config['SubPipelines']['CommonOCR']
  52. self.common_ocr_pipeline = self.create_pipeline(common_ocr_config)
  53. self.use_seal_recognition = False
  54. if "use_seal_recognition" in config:
  55. self.use_seal_recognition = config['use_seal_recognition']
  56. if self.use_seal_recognition:
  57. seal_ocr_config = config['SubPipelines']['SealOCR']
  58. self.seal_ocr_pipeline = self.create_pipeline(seal_ocr_config)
  59. self.use_table_recognition = False
  60. if "use_table_recognition" in config:
  61. self.use_table_recognition = config['use_table_recognition']
  62. if self.use_table_recognition:
  63. table_structure_config = config['SubModules']['TableStructurePredictor']
  64. self.table_structure_model = self.create_model(table_structure_config)
  65. if not self.use_common_ocr:
  66. common_ocr_config = config['SubPipelines']['OCR']
  67. self.common_ocr_pipeline = self.create_pipeline(common_ocr_config)
  68. return
  69. def get_text_paragraphs_ocr_res(self, overall_ocr_res, layout_det_res):
  70. '''get ocr res of the text paragraphs'''
  71. object_boxes = []
  72. for box_info in layout_det_res['boxes']:
  73. if box_info['label'].lower() in ['image', 'formula', 'table', 'seal']:
  74. object_boxes.append(box_info['coordinate'])
  75. object_boxes = np.array(object_boxes)
  76. return get_sub_regions_ocr_res(overall_ocr_res, object_boxes, flag_within=False)
  77. def check_input_params(self, input_params):
  78. if input_params['use_doc_preprocessor'] and not self.use_doc_preprocessor:
  79. raise ValueError("The models for doc preprocessor are not initialized.")
  80. if input_params['use_common_ocr'] and not self.use_common_ocr:
  81. raise ValueError("The models for common OCR are not initialized.")
  82. if input_params['use_seal_recognition'] and not self.use_seal_recognition:
  83. raise ValueError("The models for seal recognition are not initialized.")
  84. if input_params['use_table_recognition'] and not self.use_table_recognition:
  85. raise ValueError("The models for table recognition are not initialized.")
  86. return
  87. def predict(self, input,
  88. use_doc_orientation_classify=True,
  89. use_doc_unwarping=True,
  90. use_common_ocr=True,
  91. use_seal_recognition=True,
  92. use_table_recognition=True,
  93. **kwargs):
  94. if not isinstance(input, list):
  95. input_list = [input]
  96. else:
  97. input_list = input
  98. input_params = {"use_doc_preprocessor":self.use_doc_preprocessor,
  99. "use_doc_orientation_classify":use_doc_orientation_classify,
  100. "use_doc_unwarping":use_doc_unwarping,
  101. "use_common_ocr":use_common_ocr,
  102. "use_seal_recognition":use_seal_recognition,
  103. "use_table_recognition":use_table_recognition}
  104. if use_doc_orientation_classify or use_doc_unwarping:
  105. input_params['use_doc_preprocessor'] = True
  106. self.check_input_params(input_params)
  107. img_id = 1
  108. for input in input_list:
  109. if isinstance(input, str):
  110. image_array = next(self.img_reader(input))[0]['img']
  111. else:
  112. image_array = input
  113. assert len(image_array.shape) == 3
  114. if input_params['use_doc_preprocessor']:
  115. doc_preprocessor_res = next(self.doc_preprocessor_pipeline(
  116. image_array,
  117. use_doc_orientation_classify=use_doc_orientation_classify,
  118. use_doc_unwarping=use_doc_unwarping))
  119. doc_preprocessor_image = doc_preprocessor_res['output_img']
  120. doc_preprocessor_res['img_id'] = img_id
  121. else:
  122. doc_preprocessor_res = {}
  123. doc_preprocessor_image = image_array
  124. ########## [TODO]RT-DETR 检测结果有重复
  125. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  126. if input_params['use_common_ocr'] or input_params['use_table_recognition']:
  127. overall_ocr_res = next(self.common_ocr_pipeline(doc_preprocessor_image))
  128. overall_ocr_res['img_id'] = img_id
  129. dt_boxes = convert_points_to_boxes(overall_ocr_res['dt_polys'])
  130. overall_ocr_res['dt_boxes'] = dt_boxes
  131. else:
  132. overall_ocr_res = {}
  133. text_paragraphs_ocr_res = {}
  134. if input_params['use_common_ocr']:
  135. text_paragraphs_ocr_res = self.get_text_paragraphs_ocr_res(
  136. overall_ocr_res, layout_det_res)
  137. text_paragraphs_ocr_res['img_id'] = img_id
  138. table_res_list = []
  139. if input_params['use_table_recognition']:
  140. table_region_id = 1
  141. for box_info in layout_det_res['boxes']:
  142. if box_info['label'].lower() in ['table']:
  143. crop_img_info = self._crop_by_boxes(doc_preprocessor_image, [box_info])
  144. crop_img_info = crop_img_info[0]
  145. table_structure_pred = next(self.table_structure_model(
  146. crop_img_info['img']))
  147. table_recognition_res = get_table_recognition_res(
  148. crop_img_info, table_structure_pred, overall_ocr_res)
  149. table_recognition_res['table_region_id'] = table_region_id
  150. table_region_id += 1
  151. table_res_list.append(table_recognition_res)
  152. seal_res_list = []
  153. if input_params['use_seal_recognition']:
  154. seal_region_id = 1
  155. for box_info in layout_det_res['boxes']:
  156. if box_info['label'].lower() in ['seal']:
  157. crop_img_info = self._crop_by_boxes(doc_preprocessor_image, [box_info])
  158. crop_img_info = crop_img_info[0]
  159. seal_ocr_res = next(self.seal_ocr_pipeline(crop_img_info['img']))
  160. seal_ocr_res['seal_region_id'] = seal_region_id
  161. seal_region_id += 1
  162. seal_res_list.append(seal_ocr_res)
  163. single_img_res = {"layout_det_res":layout_det_res,
  164. "doc_preprocessor_res":doc_preprocessor_res,
  165. "text_paragraphs_ocr_res":text_paragraphs_ocr_res,
  166. "table_res_list":table_res_list,
  167. "seal_res_list":seal_res_list,
  168. "input_params":input_params}
  169. yield LayoutParsingResult(single_img_res)