pipeline_v2.py 60 KB

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