pipeline_v2.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  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 __future__ import annotations
  15. import copy
  16. import re
  17. from typing import Any, Dict, List, Optional, Tuple, Union
  18. import numpy as np
  19. from PIL import Image
  20. from ....utils import logging
  21. from ....utils.deps import pipeline_requires_extra
  22. from ...common.batch_sampler import ImageBatchSampler
  23. from ...common.reader import ReadImage
  24. from ...models.object_detection.result import DetResult
  25. from ...utils.benchmark import benchmark
  26. from ...utils.hpi import HPIConfig
  27. from ...utils.pp_option import PaddlePredictorOption
  28. from .._parallel import AutoParallelImageSimpleInferencePipeline
  29. from ..base import BasePipeline
  30. from ..ocr.result import OCRResult
  31. from .layout_objects import LayoutBlock, LayoutRegion
  32. from .result_v2 import LayoutParsingResultV2
  33. from .setting import BLOCK_LABEL_MAP, BLOCK_SETTINGS, REGION_SETTINGS
  34. from .utils import (
  35. caculate_bbox_area,
  36. calculate_minimum_enclosing_bbox,
  37. calculate_overlap_ratio,
  38. convert_formula_res_to_ocr_format,
  39. gather_imgs,
  40. get_bbox_intersection,
  41. get_sub_regions_ocr_res,
  42. remove_overlap_blocks,
  43. shrink_supplement_region_bbox,
  44. update_region_box,
  45. )
  46. from .xycut_enhanced import xycut_enhanced
  47. @benchmark.time_methods
  48. class _LayoutParsingPipelineV2(BasePipeline):
  49. """Layout Parsing Pipeline V2"""
  50. def __init__(
  51. self,
  52. config: dict,
  53. device: str = None,
  54. pp_option: PaddlePredictorOption = None,
  55. use_hpip: bool = False,
  56. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  57. ) -> None:
  58. """Initializes the layout parsing pipeline.
  59. Args:
  60. config (Dict): Configuration dictionary containing various settings.
  61. device (str, optional): Device to run the predictions on. Defaults to None.
  62. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  63. use_hpip (bool, optional): Whether to use the high-performance
  64. inference plugin (HPIP) by default. Defaults to False.
  65. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  66. The default high-performance inference configuration dictionary.
  67. Defaults to None.
  68. """
  69. super().__init__(
  70. device=device,
  71. pp_option=pp_option,
  72. use_hpip=use_hpip,
  73. hpi_config=hpi_config,
  74. )
  75. self.inintial_predictor(config)
  76. self.batch_sampler = ImageBatchSampler(batch_size=config.get("batch_size", 1))
  77. self.img_reader = ReadImage(format="BGR")
  78. def inintial_predictor(self, config: dict) -> None:
  79. """Initializes the predictor based on the provided configuration.
  80. Args:
  81. config (Dict): A dictionary containing the configuration for the predictor.
  82. Returns:
  83. None
  84. """
  85. if (
  86. config.get("use_doc_preprocessor", True)
  87. or config.get("use_doc_orientation_classify", True)
  88. or config.get("use_doc_unwarping", True)
  89. ):
  90. self.use_doc_preprocessor = True
  91. else:
  92. self.use_doc_preprocessor = False
  93. self.use_table_recognition = config.get("use_table_recognition", True)
  94. self.use_seal_recognition = config.get("use_seal_recognition", True)
  95. self.use_region_detection = config.get(
  96. "use_region_detection",
  97. True,
  98. )
  99. self.use_formula_recognition = config.get(
  100. "use_formula_recognition",
  101. True,
  102. )
  103. self.use_chart_recognition = config.get(
  104. "use_chart_recognition",
  105. False,
  106. )
  107. if self.use_doc_preprocessor:
  108. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  109. "DocPreprocessor",
  110. {
  111. "pipeline_config_error": "config error for doc_preprocessor_pipeline!",
  112. },
  113. )
  114. self.doc_preprocessor_pipeline = self.create_pipeline(
  115. doc_preprocessor_config,
  116. )
  117. if self.use_region_detection:
  118. region_detection_config = config.get("SubModules", {}).get(
  119. "RegionDetection",
  120. {
  121. "model_config_error": "config error for block_region_detection_model!"
  122. },
  123. )
  124. self.region_detection_model = self.create_model(
  125. region_detection_config,
  126. )
  127. layout_det_config = config.get("SubModules", {}).get(
  128. "LayoutDetection",
  129. {"model_config_error": "config error for layout_det_model!"},
  130. )
  131. layout_kwargs = {}
  132. if (threshold := layout_det_config.get("threshold", None)) is not None:
  133. layout_kwargs["threshold"] = threshold
  134. if (layout_nms := layout_det_config.get("layout_nms", None)) is not None:
  135. layout_kwargs["layout_nms"] = layout_nms
  136. if (
  137. layout_unclip_ratio := layout_det_config.get("layout_unclip_ratio", None)
  138. ) is not None:
  139. layout_kwargs["layout_unclip_ratio"] = layout_unclip_ratio
  140. if (
  141. layout_merge_bboxes_mode := layout_det_config.get(
  142. "layout_merge_bboxes_mode", None
  143. )
  144. ) is not None:
  145. layout_kwargs["layout_merge_bboxes_mode"] = layout_merge_bboxes_mode
  146. self.layout_det_model = self.create_model(layout_det_config, **layout_kwargs)
  147. general_ocr_config = config.get("SubPipelines", {}).get(
  148. "GeneralOCR",
  149. {"pipeline_config_error": "config error for general_ocr_pipeline!"},
  150. )
  151. self.general_ocr_pipeline = self.create_pipeline(
  152. general_ocr_config,
  153. )
  154. if self.use_seal_recognition:
  155. seal_recognition_config = config.get("SubPipelines", {}).get(
  156. "SealRecognition",
  157. {
  158. "pipeline_config_error": "config error for seal_recognition_pipeline!",
  159. },
  160. )
  161. self.seal_recognition_pipeline = self.create_pipeline(
  162. seal_recognition_config,
  163. )
  164. if self.use_table_recognition:
  165. table_recognition_config = config.get("SubPipelines", {}).get(
  166. "TableRecognition",
  167. {
  168. "pipeline_config_error": "config error for table_recognition_pipeline!",
  169. },
  170. )
  171. self.table_recognition_pipeline = self.create_pipeline(
  172. table_recognition_config,
  173. )
  174. if self.use_formula_recognition:
  175. formula_recognition_config = config.get("SubPipelines", {}).get(
  176. "FormulaRecognition",
  177. {
  178. "pipeline_config_error": "config error for formula_recognition_pipeline!",
  179. },
  180. )
  181. self.formula_recognition_pipeline = self.create_pipeline(
  182. formula_recognition_config,
  183. )
  184. # TODO(gaotingquan): init the model at any time
  185. chart_recognition_config = config.get("SubModules", {}).get(
  186. "ChartRecognition",
  187. {"model_config_error": "config error for block_region_detection_model!"},
  188. )
  189. self.chart_recognition_model = self.create_model(
  190. chart_recognition_config,
  191. )
  192. return
  193. def get_text_paragraphs_ocr_res(
  194. self,
  195. overall_ocr_res: OCRResult,
  196. layout_det_res: DetResult,
  197. ) -> OCRResult:
  198. """
  199. Retrieves the OCR results for text paragraphs, excluding those of formulas, tables, and seals.
  200. Args:
  201. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  202. layout_det_res (DetResult): The detection result containing the layout information of the document.
  203. Returns:
  204. OCRResult: The OCR result for text paragraphs after excluding formulas, tables, and seals.
  205. """
  206. object_boxes = []
  207. for box_info in layout_det_res["boxes"]:
  208. if box_info["label"].lower() in ["formula", "table", "seal"]:
  209. object_boxes.append(box_info["coordinate"])
  210. object_boxes = np.array(object_boxes)
  211. sub_regions_ocr_res = get_sub_regions_ocr_res(
  212. overall_ocr_res, object_boxes, flag_within=False
  213. )
  214. return sub_regions_ocr_res
  215. def check_model_settings_valid(self, input_params: dict) -> bool:
  216. """
  217. Check if the input parameters are valid based on the initialized models.
  218. Args:
  219. input_params (Dict): A dictionary containing input parameters.
  220. Returns:
  221. bool: True if all required models are initialized according to input parameters, False otherwise.
  222. """
  223. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  224. logging.error(
  225. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized.",
  226. )
  227. return False
  228. if input_params["use_seal_recognition"] and not self.use_seal_recognition:
  229. logging.error(
  230. "Set use_seal_recognition, but the models for seal recognition are not initialized.",
  231. )
  232. return False
  233. if input_params["use_table_recognition"] and not self.use_table_recognition:
  234. logging.error(
  235. "Set use_table_recognition, but the models for table recognition are not initialized.",
  236. )
  237. return False
  238. return True
  239. def standardized_data(
  240. self,
  241. image: list,
  242. region_det_res: DetResult,
  243. layout_det_res: DetResult,
  244. overall_ocr_res: OCRResult,
  245. formula_res_list: list,
  246. text_rec_model: Any,
  247. text_rec_score_thresh: Union[float, None] = None,
  248. ) -> list:
  249. """
  250. Retrieves the layout parsing result based on the layout detection result, OCR result, and other recognition results.
  251. Args:
  252. image (list): The input image.
  253. overall_ocr_res (OCRResult): An object containing the overall OCR results, including detected text boxes and recognized text. The structure is expected to have:
  254. - "input_img": The image on which OCR was performed.
  255. - "dt_boxes": A list of detected text box coordinates.
  256. - "rec_texts": A list of recognized text corresponding to the detected boxes.
  257. layout_det_res (DetResult): An object containing the layout detection results, including detected layout boxes and their labels. The structure is expected to have:
  258. - "boxes": A list of dictionaries with keys "coordinate" for box coordinates and "block_label" for the type of content.
  259. table_res_list (list): A list of table detection results, where each item is a dictionary containing:
  260. - "block_bbox": The bounding box of the table layout.
  261. - "pred_html": The predicted HTML representation of the table.
  262. formula_res_list (list): A list of formula recognition results.
  263. text_rec_model (Any): The text recognition model.
  264. text_rec_score_thresh (Optional[float], optional): The score threshold for text recognition. Defaults to None.
  265. Returns:
  266. list: A list of dictionaries representing the layout parsing result.
  267. """
  268. matched_ocr_dict = {}
  269. region_to_block_map = {}
  270. block_to_ocr_map = {}
  271. object_boxes = []
  272. footnote_list = []
  273. paragraph_title_list = []
  274. bottom_text_y_max = 0
  275. max_block_area = 0.0
  276. doc_title_num = 0
  277. base_region_bbox = [65535, 65535, 0, 0]
  278. layout_det_res = remove_overlap_blocks(
  279. layout_det_res,
  280. threshold=0.5,
  281. smaller=True,
  282. )
  283. # convert formula_res_list to OCRResult format
  284. convert_formula_res_to_ocr_format(formula_res_list, overall_ocr_res)
  285. # match layout boxes and ocr boxes and get some information for layout_order_config
  286. for box_idx, box_info in enumerate(layout_det_res["boxes"]):
  287. box = box_info["coordinate"]
  288. label = box_info["label"].lower()
  289. object_boxes.append(box)
  290. _, _, _, y2 = box
  291. # update the region box and max_block_area according to the layout boxes
  292. base_region_bbox = update_region_box(box, base_region_bbox)
  293. max_block_area = max(max_block_area, caculate_bbox_area(box))
  294. # update_layout_order_config_block_index(layout_order_config, label, box_idx)
  295. # set the label of footnote to text, when it is above the text boxes
  296. if label == "footnote":
  297. footnote_list.append(box_idx)
  298. elif label == "paragraph_title":
  299. paragraph_title_list.append(box_idx)
  300. if label == "text":
  301. bottom_text_y_max = max(y2, bottom_text_y_max)
  302. if label == "doc_title":
  303. doc_title_num += 1
  304. if label not in ["formula", "table", "seal"]:
  305. _, matched_idxes = get_sub_regions_ocr_res(
  306. overall_ocr_res, [box], return_match_idx=True
  307. )
  308. block_to_ocr_map[box_idx] = matched_idxes
  309. for matched_idx in matched_idxes:
  310. if matched_ocr_dict.get(matched_idx, None) is None:
  311. matched_ocr_dict[matched_idx] = [box_idx]
  312. else:
  313. matched_ocr_dict[matched_idx].append(box_idx)
  314. # fix the footnote label
  315. for footnote_idx in footnote_list:
  316. if (
  317. layout_det_res["boxes"][footnote_idx]["coordinate"][3]
  318. < bottom_text_y_max
  319. ):
  320. layout_det_res["boxes"][footnote_idx]["label"] = "text"
  321. # check if there is only one paragraph title and without doc_title
  322. only_one_paragraph_title = len(paragraph_title_list) == 1 and doc_title_num == 0
  323. if only_one_paragraph_title:
  324. paragraph_title_block_area = caculate_bbox_area(
  325. layout_det_res["boxes"][paragraph_title_list[0]]["coordinate"]
  326. )
  327. title_area_max_block_threshold = BLOCK_SETTINGS.get(
  328. "title_conversion_area_ratio_threshold", 0.3
  329. )
  330. if (
  331. paragraph_title_block_area
  332. > max_block_area * title_area_max_block_threshold
  333. ):
  334. layout_det_res["boxes"][paragraph_title_list[0]]["label"] = "doc_title"
  335. # Replace the OCR information of the hurdles.
  336. for overall_ocr_idx, layout_box_ids in matched_ocr_dict.items():
  337. if len(layout_box_ids) > 1:
  338. matched_no = 0
  339. overall_ocr_box = copy.deepcopy(
  340. overall_ocr_res["rec_boxes"][overall_ocr_idx]
  341. )
  342. overall_ocr_dt_poly = copy.deepcopy(
  343. overall_ocr_res["dt_polys"][overall_ocr_idx]
  344. )
  345. for box_idx in layout_box_ids:
  346. layout_box = layout_det_res["boxes"][box_idx]["coordinate"]
  347. crop_box = get_bbox_intersection(overall_ocr_box, layout_box)
  348. for ocr_idx in block_to_ocr_map[box_idx]:
  349. ocr_box = overall_ocr_res["rec_boxes"][ocr_idx]
  350. iou = calculate_overlap_ratio(ocr_box, crop_box, "small")
  351. if iou > 0.8:
  352. overall_ocr_res["rec_texts"][ocr_idx] = ""
  353. x1, y1, x2, y2 = [int(i) for i in crop_box]
  354. crop_img = np.array(image)[y1:y2, x1:x2]
  355. crop_img_rec_res = list(text_rec_model([crop_img]))[0]
  356. crop_img_dt_poly = get_bbox_intersection(
  357. overall_ocr_dt_poly, layout_box, return_format="poly"
  358. )
  359. crop_img_rec_score = crop_img_rec_res["rec_score"]
  360. crop_img_rec_text = crop_img_rec_res["rec_text"]
  361. text_rec_score_thresh = (
  362. text_rec_score_thresh
  363. if text_rec_score_thresh is not None
  364. else (self.general_ocr_pipeline.text_rec_score_thresh)
  365. )
  366. if crop_img_rec_score >= text_rec_score_thresh:
  367. matched_no += 1
  368. if matched_no == 1:
  369. # the first matched ocr be replaced by the first matched layout box
  370. overall_ocr_res["dt_polys"][
  371. overall_ocr_idx
  372. ] = crop_img_dt_poly
  373. overall_ocr_res["rec_boxes"][overall_ocr_idx] = crop_box
  374. overall_ocr_res["rec_polys"][
  375. overall_ocr_idx
  376. ] = crop_img_dt_poly
  377. overall_ocr_res["rec_scores"][
  378. overall_ocr_idx
  379. ] = crop_img_rec_score
  380. overall_ocr_res["rec_texts"][
  381. overall_ocr_idx
  382. ] = crop_img_rec_text
  383. else:
  384. # the other matched ocr be appended to the overall ocr result
  385. overall_ocr_res["dt_polys"].append(crop_img_dt_poly)
  386. if len(overall_ocr_res["rec_boxes"]) == 0:
  387. overall_ocr_res["rec_boxes"] = np.array([crop_box])
  388. else:
  389. overall_ocr_res["rec_boxes"] = np.vstack(
  390. (overall_ocr_res["rec_boxes"], crop_box)
  391. )
  392. overall_ocr_res["rec_polys"].append(crop_img_dt_poly)
  393. overall_ocr_res["rec_scores"].append(crop_img_rec_score)
  394. overall_ocr_res["rec_texts"].append(crop_img_rec_text)
  395. overall_ocr_res["rec_labels"].append("text")
  396. block_to_ocr_map[box_idx].remove(overall_ocr_idx)
  397. block_to_ocr_map[box_idx].append(
  398. len(overall_ocr_res["rec_texts"]) - 1
  399. )
  400. # use layout bbox to do ocr recognition when there is no matched ocr
  401. for layout_box_idx, overall_ocr_idxes in block_to_ocr_map.items():
  402. has_text = False
  403. for idx in overall_ocr_idxes:
  404. if overall_ocr_res["rec_texts"][idx] != "":
  405. has_text = True
  406. break
  407. if not has_text and layout_det_res["boxes"][layout_box_idx][
  408. "label"
  409. ] not in BLOCK_LABEL_MAP.get("vision_labels", []):
  410. crop_box = layout_det_res["boxes"][layout_box_idx]["coordinate"]
  411. x1, y1, x2, y2 = [int(i) for i in crop_box]
  412. crop_img = np.array(image)[y1:y2, x1:x2]
  413. crop_img_rec_res = list(text_rec_model([crop_img]))[0]
  414. crop_img_dt_poly = get_bbox_intersection(
  415. crop_box, crop_box, return_format="poly"
  416. )
  417. crop_img_rec_score = crop_img_rec_res["rec_score"]
  418. crop_img_rec_text = crop_img_rec_res["rec_text"]
  419. text_rec_score_thresh = (
  420. text_rec_score_thresh
  421. if text_rec_score_thresh is not None
  422. else (self.general_ocr_pipeline.text_rec_score_thresh)
  423. )
  424. if crop_img_rec_score >= text_rec_score_thresh:
  425. if len(overall_ocr_res["rec_boxes"]) == 0:
  426. overall_ocr_res["rec_boxes"] = np.array([crop_box])
  427. else:
  428. overall_ocr_res["rec_boxes"] = np.vstack(
  429. (overall_ocr_res["rec_boxes"], crop_box)
  430. )
  431. overall_ocr_res["rec_polys"].append(crop_img_dt_poly)
  432. overall_ocr_res["rec_scores"].append(crop_img_rec_score)
  433. overall_ocr_res["rec_texts"].append(crop_img_rec_text)
  434. overall_ocr_res["rec_labels"].append("text")
  435. block_to_ocr_map[layout_box_idx].append(
  436. len(overall_ocr_res["rec_texts"]) - 1
  437. )
  438. # when there is no layout detection result but there is ocr result, convert ocr detection result to layout detection result
  439. if len(layout_det_res["boxes"]) == 0 and len(overall_ocr_res["rec_boxes"]) > 0:
  440. for idx, ocr_rec_box in enumerate(overall_ocr_res["rec_boxes"]):
  441. base_region_bbox = update_region_box(ocr_rec_box, base_region_bbox)
  442. layout_det_res["boxes"].append(
  443. {
  444. "label": "text",
  445. "coordinate": ocr_rec_box,
  446. "score": overall_ocr_res["rec_scores"][idx],
  447. }
  448. )
  449. block_to_ocr_map[idx] = [idx]
  450. mask_labels = (
  451. BLOCK_LABEL_MAP.get("unordered_labels", [])
  452. + BLOCK_LABEL_MAP.get("header_labels", [])
  453. + BLOCK_LABEL_MAP.get("footer_labels", [])
  454. )
  455. block_bboxes = [box["coordinate"] for box in layout_det_res["boxes"]]
  456. region_det_res["boxes"] = sorted(
  457. region_det_res["boxes"],
  458. key=lambda item: caculate_bbox_area(item["coordinate"]),
  459. )
  460. if len(region_det_res["boxes"]) == 0:
  461. region_det_res["boxes"] = [
  462. {
  463. "coordinate": base_region_bbox,
  464. "label": "SupplementaryRegion",
  465. "score": 1,
  466. }
  467. ]
  468. region_to_block_map[0] = range(len(block_bboxes))
  469. else:
  470. block_idxes_set = set(range(len(block_bboxes)))
  471. # match block to region
  472. for region_idx, region_info in enumerate(region_det_res["boxes"]):
  473. matched_idxes = []
  474. region_to_block_map[region_idx] = []
  475. region_bbox = region_info["coordinate"]
  476. for block_idx in block_idxes_set:
  477. if layout_det_res["boxes"][block_idx]["label"] in mask_labels:
  478. continue
  479. overlap_ratio = calculate_overlap_ratio(
  480. region_bbox, block_bboxes[block_idx], mode="small"
  481. )
  482. if overlap_ratio > REGION_SETTINGS.get(
  483. "match_block_overlap_ratio_threshold", 0.8
  484. ):
  485. matched_idxes.append(block_idx)
  486. old_region_bbox_matched_idxes = []
  487. if len(matched_idxes) > 0:
  488. while len(old_region_bbox_matched_idxes) != len(matched_idxes):
  489. old_region_bbox_matched_idxes = copy.deepcopy(matched_idxes)
  490. matched_idxes = []
  491. matched_bboxes = [
  492. block_bboxes[idx] for idx in old_region_bbox_matched_idxes
  493. ]
  494. new_region_bbox = calculate_minimum_enclosing_bbox(
  495. matched_bboxes
  496. )
  497. for block_idx in block_idxes_set:
  498. if (
  499. layout_det_res["boxes"][block_idx]["label"]
  500. in mask_labels
  501. ):
  502. continue
  503. overlap_ratio = calculate_overlap_ratio(
  504. new_region_bbox, block_bboxes[block_idx], mode="small"
  505. )
  506. if overlap_ratio > REGION_SETTINGS.get(
  507. "match_block_overlap_ratio_threshold", 0.8
  508. ):
  509. matched_idxes.append(block_idx)
  510. for block_idx in matched_idxes:
  511. block_idxes_set.remove(block_idx)
  512. region_to_block_map[region_idx] = matched_idxes
  513. region_det_res["boxes"][region_idx]["coordinate"] = new_region_bbox
  514. # Supplement region when there is no matched block
  515. while len(block_idxes_set) > 0:
  516. unmatched_bboxes = [block_bboxes[idx] for idx in block_idxes_set]
  517. if len(unmatched_bboxes) == 0:
  518. break
  519. supplement_region_bbox = calculate_minimum_enclosing_bbox(
  520. unmatched_bboxes
  521. )
  522. matched_idxes = []
  523. # check if the new region bbox is overlapped with other region bbox, if have, then shrink the new region bbox
  524. for region_idx, region_info in enumerate(region_det_res["boxes"]):
  525. if len(region_to_block_map[region_idx]) == 0:
  526. continue
  527. region_bbox = region_info["coordinate"]
  528. overlap_ratio = calculate_overlap_ratio(
  529. supplement_region_bbox, region_bbox
  530. )
  531. if overlap_ratio > 0:
  532. supplement_region_bbox, matched_idxes = (
  533. shrink_supplement_region_bbox(
  534. supplement_region_bbox,
  535. region_bbox,
  536. image.shape[1],
  537. image.shape[0],
  538. block_idxes_set,
  539. block_bboxes,
  540. )
  541. )
  542. matched_idxes = [
  543. idx
  544. for idx in matched_idxes
  545. if layout_det_res["boxes"][idx]["label"] not in mask_labels
  546. ]
  547. if len(matched_idxes) == 0:
  548. matched_idxes = [
  549. idx
  550. for idx in block_idxes_set
  551. if layout_det_res["boxes"][idx]["label"] not in mask_labels
  552. ]
  553. if len(matched_idxes) == 0:
  554. break
  555. matched_bboxes = [block_bboxes[idx] for idx in matched_idxes]
  556. supplement_region_bbox = calculate_minimum_enclosing_bbox(
  557. matched_bboxes
  558. )
  559. region_idx = len(region_det_res["boxes"])
  560. region_to_block_map[region_idx] = list(matched_idxes)
  561. for block_idx in matched_idxes:
  562. block_idxes_set.remove(block_idx)
  563. region_det_res["boxes"].append(
  564. {
  565. "coordinate": supplement_region_bbox,
  566. "label": "SupplementaryRegion",
  567. "score": 1,
  568. }
  569. )
  570. mask_idxes = [
  571. idx
  572. for idx in range(len(layout_det_res["boxes"]))
  573. if layout_det_res["boxes"][idx]["label"] in mask_labels
  574. ]
  575. for idx in mask_idxes:
  576. bbox = layout_det_res["boxes"][idx]["coordinate"]
  577. region_idx = len(region_det_res["boxes"])
  578. region_to_block_map[region_idx] = [idx]
  579. region_det_res["boxes"].append(
  580. {
  581. "coordinate": bbox,
  582. "label": "SupplementaryRegion",
  583. "score": 1,
  584. }
  585. )
  586. region_block_ocr_idx_map = dict(
  587. region_to_block_map=region_to_block_map,
  588. block_to_ocr_map=block_to_ocr_map,
  589. )
  590. return region_block_ocr_idx_map, region_det_res, layout_det_res
  591. def get_layout_parsing_objects(
  592. self,
  593. image: list,
  594. region_block_ocr_idx_map: dict,
  595. region_det_res: DetResult,
  596. overall_ocr_res: OCRResult,
  597. layout_det_res: DetResult,
  598. table_res_list: list,
  599. seal_res_list: list,
  600. chart_res_list: list,
  601. text_rec_model: Any,
  602. text_rec_score_thresh: Union[float, None] = None,
  603. ) -> list:
  604. """
  605. Extract structured information from OCR and layout detection results.
  606. Args:
  607. image (list): The input image.
  608. overall_ocr_res (OCRResult): An object containing the overall OCR results, including detected text boxes and recognized text. The structure is expected to have:
  609. - "input_img": The image on which OCR was performed.
  610. - "dt_boxes": A list of detected text box coordinates.
  611. - "rec_texts": A list of recognized text corresponding to the detected boxes.
  612. layout_det_res (DetResult): An object containing the layout detection results, including detected layout boxes and their labels. The structure is expected to have:
  613. - "boxes": A list of dictionaries with keys "coordinate" for box coordinates and "block_label" for the type of content.
  614. table_res_list (list): A list of table detection results, where each item is a dictionary containing:
  615. - "block_bbox": The bounding box of the table layout.
  616. - "pred_html": The predicted HTML representation of the table.
  617. seal_res_list (List): A list of seal detection results. The details of each item depend on the specific application context.
  618. text_rec_model (Any): A model for text recognition.
  619. text_rec_score_thresh (Union[float, None]): The minimum score required for a recognized character to be considered valid. If None, use the default value specified during initialization. Default is None.
  620. Returns:
  621. list: A list of structured boxes where each item is a dictionary containing:
  622. - "block_label": The label of the content (e.g., 'table', 'chart', 'image').
  623. - The label as a key with either table HTML or image data and text.
  624. - "block_bbox": The coordinates of the layout box.
  625. """
  626. table_index = 0
  627. seal_index = 0
  628. chart_index = 0
  629. layout_parsing_blocks: List[LayoutBlock] = []
  630. for box_idx, box_info in enumerate(layout_det_res["boxes"]):
  631. label = box_info["label"]
  632. block_bbox = box_info["coordinate"]
  633. rec_res = {"boxes": [], "rec_texts": [], "rec_labels": []}
  634. block = LayoutBlock(label=label, bbox=block_bbox)
  635. if label == "table" and len(table_res_list) > 0:
  636. block.content = table_res_list[table_index]["pred_html"]
  637. table_index += 1
  638. elif label == "seal" and len(seal_res_list) > 0:
  639. block.content = "\n".join(seal_res_list[seal_index]["rec_texts"])
  640. seal_index += 1
  641. elif label == "chart" and len(chart_res_list) > 0:
  642. block.content = chart_res_list[chart_index]
  643. chart_index += 1
  644. else:
  645. if label == "formula":
  646. _, ocr_idx_list = get_sub_regions_ocr_res(
  647. overall_ocr_res, [block_bbox], return_match_idx=True
  648. )
  649. region_block_ocr_idx_map["block_to_ocr_map"][box_idx] = ocr_idx_list
  650. else:
  651. ocr_idx_list = region_block_ocr_idx_map["block_to_ocr_map"].get(
  652. box_idx, []
  653. )
  654. for box_no in ocr_idx_list:
  655. rec_res["boxes"].append(overall_ocr_res["rec_boxes"][box_no])
  656. rec_res["rec_texts"].append(
  657. overall_ocr_res["rec_texts"][box_no],
  658. )
  659. rec_res["rec_labels"].append(
  660. overall_ocr_res["rec_labels"][box_no],
  661. )
  662. block.update_text_content(
  663. image=image,
  664. ocr_rec_res=rec_res,
  665. text_rec_model=text_rec_model,
  666. text_rec_score_thresh=text_rec_score_thresh,
  667. )
  668. if (
  669. label
  670. in ["seal", "table", "formula", "chart"]
  671. + BLOCK_LABEL_MAP["image_labels"]
  672. ):
  673. x_min, y_min, x_max, y_max = list(map(int, block_bbox))
  674. img_path = (
  675. f"imgs/img_in_{block.label}_box_{x_min}_{y_min}_{x_max}_{y_max}.jpg"
  676. )
  677. img = Image.fromarray(image[y_min:y_max, x_min:x_max, ::-1])
  678. block.image = {"path": img_path, "img": img}
  679. layout_parsing_blocks.append(block)
  680. page_region_bbox = [65535, 65535, 0, 0]
  681. layout_parsing_regions: List[LayoutRegion] = []
  682. for region_idx, region_info in enumerate(region_det_res["boxes"]):
  683. region_bbox = np.array(region_info["coordinate"]).astype("int")
  684. region_blocks = [
  685. layout_parsing_blocks[idx]
  686. for idx in region_block_ocr_idx_map["region_to_block_map"][region_idx]
  687. ]
  688. if region_blocks:
  689. page_region_bbox = update_region_box(region_bbox, page_region_bbox)
  690. region = LayoutRegion(bbox=region_bbox, blocks=region_blocks)
  691. layout_parsing_regions.append(region)
  692. layout_parsing_page = LayoutRegion(
  693. bbox=np.array(page_region_bbox).astype("int"), blocks=layout_parsing_regions
  694. )
  695. return layout_parsing_page
  696. def sort_layout_parsing_blocks(
  697. self, layout_parsing_page: LayoutRegion
  698. ) -> List[LayoutBlock]:
  699. layout_parsing_regions = xycut_enhanced(layout_parsing_page)
  700. parsing_res_list = []
  701. for region in layout_parsing_regions:
  702. layout_parsing_blocks = xycut_enhanced(region)
  703. parsing_res_list.extend(layout_parsing_blocks)
  704. return parsing_res_list
  705. def get_layout_parsing_res(
  706. self,
  707. image: list,
  708. region_det_res: DetResult,
  709. layout_det_res: DetResult,
  710. overall_ocr_res: OCRResult,
  711. table_res_list: list,
  712. seal_res_list: list,
  713. chart_res_list: list,
  714. formula_res_list: list,
  715. text_rec_score_thresh: Union[float, None] = None,
  716. ) -> list:
  717. """
  718. Retrieves the layout parsing result based on the layout detection result, OCR result, and other recognition results.
  719. Args:
  720. image (list): The input image.
  721. layout_det_res (DetResult): The detection result containing the layout information of the document.
  722. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  723. table_res_list (list): A list of table recognition results.
  724. seal_res_list (list): A list of seal recognition results.
  725. formula_res_list (list): A list of formula recognition results.
  726. text_rec_score_thresh (Optional[float], optional): The score threshold for text recognition. Defaults to None.
  727. Returns:
  728. list: A list of dictionaries representing the layout parsing result.
  729. """
  730. # Standardize data
  731. region_block_ocr_idx_map, region_det_res, layout_det_res = (
  732. self.standardized_data(
  733. image=image,
  734. region_det_res=region_det_res,
  735. layout_det_res=layout_det_res,
  736. overall_ocr_res=overall_ocr_res,
  737. formula_res_list=formula_res_list,
  738. text_rec_model=self.general_ocr_pipeline.text_rec_model,
  739. text_rec_score_thresh=text_rec_score_thresh,
  740. )
  741. )
  742. # Format layout parsing block
  743. layout_parsing_page = self.get_layout_parsing_objects(
  744. image=image,
  745. region_block_ocr_idx_map=region_block_ocr_idx_map,
  746. region_det_res=region_det_res,
  747. overall_ocr_res=overall_ocr_res,
  748. layout_det_res=layout_det_res,
  749. table_res_list=table_res_list,
  750. seal_res_list=seal_res_list,
  751. chart_res_list=chart_res_list,
  752. text_rec_model=self.general_ocr_pipeline.text_rec_model,
  753. text_rec_score_thresh=self.general_ocr_pipeline.text_rec_score_thresh,
  754. )
  755. parsing_res_list = self.sort_layout_parsing_blocks(layout_parsing_page)
  756. order_index = 1
  757. for index, block in enumerate(parsing_res_list):
  758. block.index = index
  759. if block.label in BLOCK_LABEL_MAP["visualize_index_labels"]:
  760. block.order_index = order_index
  761. order_index += 1
  762. return parsing_res_list
  763. def get_model_settings(
  764. self,
  765. use_doc_orientation_classify: Union[bool, None],
  766. use_doc_unwarping: Union[bool, None],
  767. use_seal_recognition: Union[bool, None],
  768. use_table_recognition: Union[bool, None],
  769. use_formula_recognition: Union[bool, None],
  770. use_chart_recognition: Union[bool, None],
  771. use_region_detection: Union[bool, None],
  772. ) -> dict:
  773. """
  774. Get the model settings based on the provided parameters or default values.
  775. Args:
  776. use_doc_orientation_classify (Union[bool, None]): Enables document orientation classification if True. Defaults to system setting if None.
  777. use_doc_unwarping (Union[bool, None]): Enables document unwarping if True. Defaults to system setting if None.
  778. use_seal_recognition (Union[bool, None]): Enables seal recognition if True. Defaults to system setting if None.
  779. use_table_recognition (Union[bool, None]): Enables table recognition if True. Defaults to system setting if None.
  780. use_formula_recognition (Union[bool, None]): Enables formula recognition if True. Defaults to system setting if None.
  781. Returns:
  782. dict: A dictionary containing the model settings.
  783. """
  784. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  785. use_doc_preprocessor = self.use_doc_preprocessor
  786. else:
  787. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  788. use_doc_preprocessor = True
  789. else:
  790. use_doc_preprocessor = False
  791. if use_seal_recognition is None:
  792. use_seal_recognition = self.use_seal_recognition
  793. if use_table_recognition is None:
  794. use_table_recognition = self.use_table_recognition
  795. if use_formula_recognition is None:
  796. use_formula_recognition = self.use_formula_recognition
  797. if use_region_detection is None:
  798. use_region_detection = self.use_region_detection
  799. if use_chart_recognition is None:
  800. use_chart_recognition = self.use_chart_recognition
  801. return dict(
  802. use_doc_preprocessor=use_doc_preprocessor,
  803. use_seal_recognition=use_seal_recognition,
  804. use_table_recognition=use_table_recognition,
  805. use_formula_recognition=use_formula_recognition,
  806. use_chart_recognition=use_chart_recognition,
  807. use_region_detection=use_region_detection,
  808. )
  809. def predict(
  810. self,
  811. input: Union[str, list[str], np.ndarray, list[np.ndarray]],
  812. use_doc_orientation_classify: Union[bool, None] = None,
  813. use_doc_unwarping: Union[bool, None] = None,
  814. use_textline_orientation: Optional[bool] = None,
  815. use_seal_recognition: Union[bool, None] = None,
  816. use_table_recognition: Union[bool, None] = None,
  817. use_formula_recognition: Union[bool, None] = None,
  818. use_chart_recognition: Union[bool, None] = None,
  819. use_region_detection: Union[bool, None] = None,
  820. layout_threshold: Optional[Union[float, dict]] = None,
  821. layout_nms: Optional[bool] = None,
  822. layout_unclip_ratio: Optional[Union[float, Tuple[float, float], dict]] = None,
  823. layout_merge_bboxes_mode: Optional[str] = None,
  824. text_det_limit_side_len: Union[int, None] = None,
  825. text_det_limit_type: Union[str, None] = None,
  826. text_det_thresh: Union[float, None] = None,
  827. text_det_box_thresh: Union[float, None] = None,
  828. text_det_unclip_ratio: Union[float, None] = None,
  829. text_rec_score_thresh: Union[float, None] = None,
  830. seal_det_limit_side_len: Union[int, None] = None,
  831. seal_det_limit_type: Union[str, None] = None,
  832. seal_det_thresh: Union[float, None] = None,
  833. seal_det_box_thresh: Union[float, None] = None,
  834. seal_det_unclip_ratio: Union[float, None] = None,
  835. seal_rec_score_thresh: Union[float, None] = None,
  836. use_wired_table_cells_trans_to_html: bool = False,
  837. use_wireless_table_cells_trans_to_html: bool = False,
  838. use_table_orientation_classify: bool = True,
  839. use_ocr_results_with_table_cells: bool = True,
  840. use_e2e_wired_table_rec_model: bool = False,
  841. use_e2e_wireless_table_rec_model: bool = True,
  842. **kwargs,
  843. ) -> LayoutParsingResultV2:
  844. """
  845. Predicts the layout parsing result for the given input.
  846. Args:
  847. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): Input image path, list of image paths,
  848. numpy array of an image, or list of numpy arrays.
  849. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  850. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  851. use_textline_orientation (Optional[bool]): Whether to use textline orientation prediction.
  852. use_seal_recognition (Optional[bool]): Whether to use seal recognition.
  853. use_table_recognition (Optional[bool]): Whether to use table recognition.
  854. use_formula_recognition (Optional[bool]): Whether to use formula recognition.
  855. use_region_detection (Optional[bool]): Whether to use region detection.
  856. layout_threshold (Optional[float]): The threshold value to filter out low-confidence predictions. Default is None.
  857. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to False.
  858. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  859. Defaults to None.
  860. If it's a single number, then both width and height are used.
  861. If it's a tuple of two numbers, then they are used separately for width and height respectively.
  862. If it's None, then no unclipping will be performed.
  863. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  864. text_det_limit_side_len (Optional[int]): Maximum side length for text detection.
  865. text_det_limit_type (Optional[str]): Type of limit to apply for text detection.
  866. text_det_thresh (Optional[float]): Threshold for text detection.
  867. text_det_box_thresh (Optional[float]): Threshold for text detection boxes.
  868. text_det_unclip_ratio (Optional[float]): Ratio for unclipping text detection boxes.
  869. text_rec_score_thresh (Optional[float]): Score threshold for text recognition.
  870. seal_det_limit_side_len (Optional[int]): Maximum side length for seal detection.
  871. seal_det_limit_type (Optional[str]): Type of limit to apply for seal detection.
  872. seal_det_thresh (Optional[float]): Threshold for seal detection.
  873. seal_det_box_thresh (Optional[float]): Threshold for seal detection boxes.
  874. seal_det_unclip_ratio (Optional[float]): Ratio for unclipping seal detection boxes.
  875. seal_rec_score_thresh (Optional[float]): Score threshold for seal recognition.
  876. use_wired_table_cells_trans_to_html (bool): Whether to use wired table cells trans to HTML.
  877. use_wireless_table_cells_trans_to_html (bool): Whether to use wireless table cells trans to HTML.
  878. use_table_orientation_classify (bool): Whether to use table orientation classification.
  879. use_ocr_results_with_table_cells (bool): Whether to use OCR results processed by table cells.
  880. use_e2e_wired_table_rec_model (bool): Whether to use end-to-end wired table recognition model.
  881. use_e2e_wireless_table_rec_model (bool): Whether to use end-to-end wireless table recognition model.
  882. **kwargs (Any): Additional settings to extend functionality.
  883. Returns:
  884. LayoutParsingResultV2: The predicted layout parsing result.
  885. """
  886. model_settings = self.get_model_settings(
  887. use_doc_orientation_classify,
  888. use_doc_unwarping,
  889. use_seal_recognition,
  890. use_table_recognition,
  891. use_formula_recognition,
  892. use_chart_recognition,
  893. use_region_detection,
  894. )
  895. if not self.check_model_settings_valid(model_settings):
  896. yield {"error": "the input params for model settings are invalid!"}
  897. for batch_data in self.batch_sampler(input):
  898. image_arrays = self.img_reader(batch_data.instances)
  899. if model_settings["use_doc_preprocessor"]:
  900. doc_preprocessor_results = list(
  901. self.doc_preprocessor_pipeline(
  902. image_arrays,
  903. use_doc_orientation_classify=use_doc_orientation_classify,
  904. use_doc_unwarping=use_doc_unwarping,
  905. )
  906. )
  907. else:
  908. doc_preprocessor_results = [{"output_img": arr} for arr in image_arrays]
  909. doc_preprocessor_images = [
  910. item["output_img"] for item in doc_preprocessor_results
  911. ]
  912. layout_det_results = list(
  913. self.layout_det_model(
  914. doc_preprocessor_images,
  915. threshold=layout_threshold,
  916. layout_nms=layout_nms,
  917. layout_unclip_ratio=layout_unclip_ratio,
  918. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  919. )
  920. )
  921. imgs_in_doc = [
  922. gather_imgs(img, res["boxes"])
  923. for img, res in zip(doc_preprocessor_images, layout_det_results)
  924. ]
  925. if model_settings["use_region_detection"]:
  926. region_det_results = list(
  927. self.region_detection_model(
  928. doc_preprocessor_images,
  929. layout_nms=True,
  930. layout_merge_bboxes_mode="small",
  931. ),
  932. )
  933. else:
  934. region_det_results = [{"boxes": []} for _ in doc_preprocessor_images]
  935. if model_settings["use_formula_recognition"]:
  936. formula_res_all = list(
  937. self.formula_recognition_pipeline(
  938. doc_preprocessor_images,
  939. use_layout_detection=False,
  940. use_doc_orientation_classify=False,
  941. use_doc_unwarping=False,
  942. layout_det_res=layout_det_results,
  943. ),
  944. )
  945. formula_res_lists = [
  946. item["formula_res_list"] for item in formula_res_all
  947. ]
  948. else:
  949. formula_res_lists = [[] for _ in doc_preprocessor_images]
  950. for doc_preprocessor_image, formula_res_list in zip(
  951. doc_preprocessor_images, formula_res_lists
  952. ):
  953. for formula_res in formula_res_list:
  954. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  955. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = 255.0
  956. overall_ocr_results = list(
  957. self.general_ocr_pipeline(
  958. doc_preprocessor_images,
  959. use_textline_orientation=use_textline_orientation,
  960. text_det_limit_side_len=text_det_limit_side_len,
  961. text_det_limit_type=text_det_limit_type,
  962. text_det_thresh=text_det_thresh,
  963. text_det_box_thresh=text_det_box_thresh,
  964. text_det_unclip_ratio=text_det_unclip_ratio,
  965. text_rec_score_thresh=text_rec_score_thresh,
  966. ),
  967. )
  968. for overall_ocr_res in overall_ocr_results:
  969. overall_ocr_res["rec_labels"] = ["text"] * len(
  970. overall_ocr_res["rec_texts"]
  971. )
  972. if model_settings["use_table_recognition"]:
  973. table_res_lists = []
  974. for (
  975. layout_det_res,
  976. doc_preprocessor_image,
  977. overall_ocr_res,
  978. formula_res_list,
  979. imgs_in_doc_for_img,
  980. ) in zip(
  981. layout_det_results,
  982. doc_preprocessor_images,
  983. overall_ocr_results,
  984. formula_res_lists,
  985. imgs_in_doc,
  986. ):
  987. table_contents_for_img = copy.deepcopy(overall_ocr_res)
  988. for formula_res in formula_res_list:
  989. x_min, y_min, x_max, y_max = list(
  990. map(int, formula_res["dt_polys"])
  991. )
  992. poly_points = [
  993. (x_min, y_min),
  994. (x_max, y_min),
  995. (x_max, y_max),
  996. (x_min, y_max),
  997. ]
  998. table_contents_for_img["dt_polys"].append(poly_points)
  999. rec_formula = formula_res["rec_formula"]
  1000. if not rec_formula.startswith("$") or not rec_formula.endswith(
  1001. "$"
  1002. ):
  1003. rec_formula = f"${rec_formula}$"
  1004. table_contents_for_img["rec_texts"].append(f"{rec_formula}")
  1005. if table_contents_for_img["rec_boxes"].size == 0:
  1006. table_contents_for_img["rec_boxes"] = np.array(
  1007. [formula_res["dt_polys"]]
  1008. )
  1009. else:
  1010. table_contents_for_img["rec_boxes"] = np.vstack(
  1011. (
  1012. table_contents_for_img["rec_boxes"],
  1013. [formula_res["dt_polys"]],
  1014. )
  1015. )
  1016. table_contents_for_img["rec_polys"].append(poly_points)
  1017. table_contents_for_img["rec_scores"].append(1)
  1018. for img in imgs_in_doc_for_img:
  1019. img_path = img["path"]
  1020. x_min, y_min, x_max, y_max = img["coordinate"]
  1021. poly_points = [
  1022. (x_min, y_min),
  1023. (x_max, y_min),
  1024. (x_max, y_max),
  1025. (x_min, y_max),
  1026. ]
  1027. table_contents_for_img["dt_polys"].append(poly_points)
  1028. table_contents_for_img["rec_texts"].append(
  1029. f'<div style="text-align: center;"><img src="{img_path}" alt="Image" /></div>'
  1030. )
  1031. if table_contents_for_img["rec_boxes"].size == 0:
  1032. table_contents_for_img["rec_boxes"] = np.array(
  1033. [img["coordinate"]]
  1034. )
  1035. else:
  1036. table_contents_for_img["rec_boxes"] = np.vstack(
  1037. (table_contents_for_img["rec_boxes"], img["coordinate"])
  1038. )
  1039. table_contents_for_img["rec_polys"].append(poly_points)
  1040. table_contents_for_img["rec_scores"].append(img["score"])
  1041. table_res_all = list(
  1042. self.table_recognition_pipeline(
  1043. doc_preprocessor_image,
  1044. use_doc_orientation_classify=False,
  1045. use_doc_unwarping=False,
  1046. use_layout_detection=False,
  1047. use_ocr_model=False,
  1048. overall_ocr_res=table_contents_for_img,
  1049. layout_det_res=layout_det_res,
  1050. cell_sort_by_y_projection=True,
  1051. use_wired_table_cells_trans_to_html=use_wired_table_cells_trans_to_html,
  1052. use_wireless_table_cells_trans_to_html=use_wireless_table_cells_trans_to_html,
  1053. use_table_orientation_classify=use_table_orientation_classify,
  1054. use_ocr_results_with_table_cells=use_ocr_results_with_table_cells,
  1055. use_e2e_wired_table_rec_model=use_e2e_wired_table_rec_model,
  1056. use_e2e_wireless_table_rec_model=use_e2e_wireless_table_rec_model,
  1057. ),
  1058. )
  1059. single_table_res_lists = [
  1060. item["table_res_list"] for item in table_res_all
  1061. ]
  1062. table_res_lists.extend(single_table_res_lists)
  1063. else:
  1064. table_res_lists = [[] for _ in doc_preprocessor_images]
  1065. if model_settings["use_seal_recognition"]:
  1066. seal_res_all = list(
  1067. self.seal_recognition_pipeline(
  1068. doc_preprocessor_images,
  1069. use_doc_orientation_classify=False,
  1070. use_doc_unwarping=False,
  1071. use_layout_detection=False,
  1072. layout_det_res=layout_det_results,
  1073. seal_det_limit_side_len=seal_det_limit_side_len,
  1074. seal_det_limit_type=seal_det_limit_type,
  1075. seal_det_thresh=seal_det_thresh,
  1076. seal_det_box_thresh=seal_det_box_thresh,
  1077. seal_det_unclip_ratio=seal_det_unclip_ratio,
  1078. seal_rec_score_thresh=seal_rec_score_thresh,
  1079. ),
  1080. )
  1081. seal_res_lists = [item["seal_res_list"] for item in seal_res_all]
  1082. else:
  1083. seal_res_lists = [[] for _ in doc_preprocessor_images]
  1084. for (
  1085. input_path,
  1086. page_index,
  1087. doc_preprocessor_image,
  1088. doc_preprocessor_res,
  1089. layout_det_res,
  1090. region_det_res,
  1091. overall_ocr_res,
  1092. table_res_list,
  1093. seal_res_list,
  1094. formula_res_list,
  1095. imgs_in_doc_for_img,
  1096. ) in zip(
  1097. batch_data.input_paths,
  1098. batch_data.page_indexes,
  1099. doc_preprocessor_images,
  1100. doc_preprocessor_results,
  1101. layout_det_results,
  1102. region_det_results,
  1103. overall_ocr_results,
  1104. table_res_lists,
  1105. seal_res_lists,
  1106. formula_res_lists,
  1107. imgs_in_doc,
  1108. ):
  1109. chart_res_list = []
  1110. if model_settings["use_chart_recognition"]:
  1111. chart_imgs_list = []
  1112. for bbox in layout_det_res["boxes"]:
  1113. if bbox["label"] == "chart":
  1114. x_min, y_min, x_max, y_max = bbox["coordinate"]
  1115. chart_img = doc_preprocessor_image[
  1116. int(y_min) : int(y_max), int(x_min) : int(x_max), :
  1117. ]
  1118. chart_imgs_list.append({"image": chart_img})
  1119. for chart_res_batch in self.chart_recognition_model(
  1120. input=chart_imgs_list
  1121. ):
  1122. chart_res_list.append(chart_res_batch["result"])
  1123. parsing_res_list = self.get_layout_parsing_res(
  1124. doc_preprocessor_image,
  1125. region_det_res=region_det_res,
  1126. layout_det_res=layout_det_res,
  1127. overall_ocr_res=overall_ocr_res,
  1128. table_res_list=table_res_list,
  1129. seal_res_list=seal_res_list,
  1130. chart_res_list=chart_res_list,
  1131. formula_res_list=formula_res_list,
  1132. text_rec_score_thresh=text_rec_score_thresh,
  1133. )
  1134. for formula_res in formula_res_list:
  1135. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  1136. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = formula_res[
  1137. "input_img"
  1138. ]
  1139. single_img_res = {
  1140. "input_path": input_path,
  1141. "page_index": page_index,
  1142. "doc_preprocessor_res": doc_preprocessor_res,
  1143. "layout_det_res": layout_det_res,
  1144. "region_det_res": region_det_res,
  1145. "overall_ocr_res": overall_ocr_res,
  1146. "table_res_list": table_res_list,
  1147. "seal_res_list": seal_res_list,
  1148. "chart_res_list": chart_res_list,
  1149. "formula_res_list": formula_res_list,
  1150. "parsing_res_list": parsing_res_list,
  1151. "imgs_in_doc": imgs_in_doc_for_img,
  1152. "model_settings": model_settings,
  1153. }
  1154. yield LayoutParsingResultV2(single_img_res)
  1155. def concatenate_markdown_pages(self, markdown_list: list) -> tuple:
  1156. """
  1157. Concatenate Markdown content from multiple pages into a single document.
  1158. Args:
  1159. markdown_list (list): A list containing Markdown data for each page.
  1160. Returns:
  1161. tuple: A tuple containing the processed Markdown text.
  1162. """
  1163. markdown_texts = ""
  1164. previous_page_last_element_paragraph_end_flag = True
  1165. for res in markdown_list:
  1166. # Get the paragraph flags for the current page
  1167. page_first_element_paragraph_start_flag: bool = res[
  1168. "page_continuation_flags"
  1169. ][0]
  1170. page_last_element_paragraph_end_flag: bool = res["page_continuation_flags"][
  1171. 1
  1172. ]
  1173. # Determine whether to add a space or a newline
  1174. if (
  1175. not page_first_element_paragraph_start_flag
  1176. and not previous_page_last_element_paragraph_end_flag
  1177. ):
  1178. last_char_of_markdown = markdown_texts[-1] if markdown_texts else ""
  1179. first_char_of_handler = (
  1180. res["markdown_texts"][0] if res["markdown_texts"] else ""
  1181. )
  1182. # Check if the last character and the first character are Chinese characters
  1183. last_is_chinese_char = (
  1184. re.match(r"[\u4e00-\u9fff]", last_char_of_markdown)
  1185. if last_char_of_markdown
  1186. else False
  1187. )
  1188. first_is_chinese_char = (
  1189. re.match(r"[\u4e00-\u9fff]", first_char_of_handler)
  1190. if first_char_of_handler
  1191. else False
  1192. )
  1193. if not (last_is_chinese_char or first_is_chinese_char):
  1194. markdown_texts += " " + res["markdown_texts"]
  1195. else:
  1196. markdown_texts += res["markdown_texts"]
  1197. else:
  1198. markdown_texts += "\n\n" + res["markdown_texts"]
  1199. previous_page_last_element_paragraph_end_flag = (
  1200. page_last_element_paragraph_end_flag
  1201. )
  1202. return markdown_texts
  1203. @pipeline_requires_extra("ocr")
  1204. class LayoutParsingPipelineV2(AutoParallelImageSimpleInferencePipeline):
  1205. entities = ["PP-StructureV3"]
  1206. @property
  1207. def _pipeline_cls(self):
  1208. return _LayoutParsingPipelineV2
  1209. def _get_batch_size(self, config):
  1210. return config.get("batch_size", 1)