pipeline_v2.py 61 KB

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