pipeline_v2.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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 ..base import BasePipeline
  28. from ..ocr.result import OCRResult
  29. from .result_v2 import LayoutParsingBlock, LayoutParsingResultV2
  30. from .utils import (
  31. caculate_bbox_area,
  32. calculate_text_orientation,
  33. convert_formula_res_to_ocr_format,
  34. format_line,
  35. gather_imgs,
  36. get_bbox_intersection,
  37. get_sub_regions_ocr_res,
  38. group_boxes_into_lines,
  39. remove_overlap_blocks,
  40. split_boxes_if_x_contained,
  41. update_layout_order_config_block_index,
  42. update_region_box,
  43. )
  44. from .xycut_enhanced import xycut_enhanced
  45. @pipeline_requires_extra("ocr")
  46. class LayoutParsingPipelineV2(BasePipeline):
  47. """Layout Parsing Pipeline V2"""
  48. entities = ["PP-StructureV3"]
  49. def __init__(
  50. self,
  51. config: dict,
  52. device: str = None,
  53. pp_option: PaddlePredictorOption = None,
  54. use_hpip: bool = False,
  55. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  56. ) -> None:
  57. """Initializes the layout parsing pipeline.
  58. Args:
  59. config (Dict): Configuration dictionary containing various settings.
  60. device (str, optional): Device to run the predictions on. Defaults to None.
  61. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  62. use_hpip (bool, optional): Whether to use the high-performance
  63. inference plugin (HPIP). Defaults to False.
  64. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  65. The high-performance inference configuration dictionary.
  66. Defaults to None.
  67. """
  68. super().__init__(
  69. device=device,
  70. pp_option=pp_option,
  71. use_hpip=use_hpip,
  72. hpi_config=hpi_config,
  73. )
  74. self.inintial_predictor(config)
  75. self.batch_sampler = ImageBatchSampler(batch_size=1)
  76. self.img_reader = ReadImage(format="BGR")
  77. def inintial_predictor(self, config: dict) -> None:
  78. """Initializes the predictor based on the provided configuration.
  79. Args:
  80. config (Dict): A dictionary containing the configuration for the predictor.
  81. Returns:
  82. None
  83. """
  84. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  85. self.use_general_ocr = config.get("use_general_ocr", True)
  86. self.use_table_recognition = config.get("use_table_recognition", True)
  87. self.use_seal_recognition = config.get("use_seal_recognition", True)
  88. self.use_formula_recognition = config.get(
  89. "use_formula_recognition",
  90. True,
  91. )
  92. if self.use_doc_preprocessor:
  93. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  94. "DocPreprocessor",
  95. {
  96. "pipeline_config_error": "config error for doc_preprocessor_pipeline!",
  97. },
  98. )
  99. self.doc_preprocessor_pipeline = self.create_pipeline(
  100. doc_preprocessor_config,
  101. )
  102. layout_det_config = config.get("SubModules", {}).get(
  103. "LayoutDetection",
  104. {"model_config_error": "config error for layout_det_model!"},
  105. )
  106. layout_kwargs = {}
  107. if (threshold := layout_det_config.get("threshold", None)) is not None:
  108. layout_kwargs["threshold"] = threshold
  109. if (layout_nms := layout_det_config.get("layout_nms", None)) is not None:
  110. layout_kwargs["layout_nms"] = layout_nms
  111. if (
  112. layout_unclip_ratio := layout_det_config.get("layout_unclip_ratio", None)
  113. ) is not None:
  114. layout_kwargs["layout_unclip_ratio"] = layout_unclip_ratio
  115. if (
  116. layout_merge_bboxes_mode := layout_det_config.get(
  117. "layout_merge_bboxes_mode", None
  118. )
  119. ) is not None:
  120. layout_kwargs["layout_merge_bboxes_mode"] = layout_merge_bboxes_mode
  121. self.layout_det_model = self.create_model(layout_det_config, **layout_kwargs)
  122. if self.use_general_ocr or self.use_table_recognition:
  123. general_ocr_config = config.get("SubPipelines", {}).get(
  124. "GeneralOCR",
  125. {"pipeline_config_error": "config error for general_ocr_pipeline!"},
  126. )
  127. self.general_ocr_pipeline = self.create_pipeline(
  128. general_ocr_config,
  129. )
  130. if self.use_seal_recognition:
  131. seal_recognition_config = config.get("SubPipelines", {}).get(
  132. "SealRecognition",
  133. {
  134. "pipeline_config_error": "config error for seal_recognition_pipeline!",
  135. },
  136. )
  137. self.seal_recognition_pipeline = self.create_pipeline(
  138. seal_recognition_config,
  139. )
  140. if self.use_table_recognition:
  141. table_recognition_config = config.get("SubPipelines", {}).get(
  142. "TableRecognition",
  143. {
  144. "pipeline_config_error": "config error for table_recognition_pipeline!",
  145. },
  146. )
  147. self.table_recognition_pipeline = self.create_pipeline(
  148. table_recognition_config,
  149. )
  150. if self.use_formula_recognition:
  151. formula_recognition_config = config.get("SubPipelines", {}).get(
  152. "FormulaRecognition",
  153. {
  154. "pipeline_config_error": "config error for formula_recognition_pipeline!",
  155. },
  156. )
  157. self.formula_recognition_pipeline = self.create_pipeline(
  158. formula_recognition_config,
  159. )
  160. return
  161. def get_text_paragraphs_ocr_res(
  162. self,
  163. overall_ocr_res: OCRResult,
  164. layout_det_res: DetResult,
  165. ) -> OCRResult:
  166. """
  167. Retrieves the OCR results for text paragraphs, excluding those of formulas, tables, and seals.
  168. Args:
  169. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  170. layout_det_res (DetResult): The detection result containing the layout information of the document.
  171. Returns:
  172. OCRResult: The OCR result for text paragraphs after excluding formulas, tables, and seals.
  173. """
  174. object_boxes = []
  175. for box_info in layout_det_res["boxes"]:
  176. if box_info["label"].lower() in ["formula", "table", "seal"]:
  177. object_boxes.append(box_info["coordinate"])
  178. object_boxes = np.array(object_boxes)
  179. sub_regions_ocr_res = get_sub_regions_ocr_res(
  180. overall_ocr_res, object_boxes, flag_within=False
  181. )
  182. return sub_regions_ocr_res
  183. def check_model_settings_valid(self, input_params: dict) -> bool:
  184. """
  185. Check if the input parameters are valid based on the initialized models.
  186. Args:
  187. input_params (Dict): A dictionary containing input parameters.
  188. Returns:
  189. bool: True if all required models are initialized according to input parameters, False otherwise.
  190. """
  191. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  192. logging.error(
  193. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized.",
  194. )
  195. return False
  196. if input_params["use_general_ocr"] and not self.use_general_ocr:
  197. logging.error(
  198. "Set use_general_ocr, but the models for general OCR are not initialized.",
  199. )
  200. return False
  201. if input_params["use_seal_recognition"] and not self.use_seal_recognition:
  202. logging.error(
  203. "Set use_seal_recognition, but the models for seal recognition are not initialized.",
  204. )
  205. return False
  206. if input_params["use_table_recognition"] and not self.use_table_recognition:
  207. logging.error(
  208. "Set use_table_recognition, but the models for table recognition are not initialized.",
  209. )
  210. return False
  211. return True
  212. def standardized_data(
  213. self,
  214. image: list,
  215. layout_order_config: dict,
  216. layout_det_res: DetResult,
  217. overall_ocr_res: OCRResult,
  218. formula_res_list: list,
  219. text_rec_model: Any,
  220. text_rec_score_thresh: Union[float, None] = None,
  221. ) -> list:
  222. """
  223. Retrieves the layout parsing result based on the layout detection result, OCR result, and other recognition results.
  224. Args:
  225. image (list): The input image.
  226. overall_ocr_res (OCRResult): An object containing the overall OCR results, including detected text boxes and recognized text. The structure is expected to have:
  227. - "input_img": The image on which OCR was performed.
  228. - "dt_boxes": A list of detected text box coordinates.
  229. - "rec_texts": A list of recognized text corresponding to the detected boxes.
  230. layout_det_res (DetResult): An object containing the layout detection results, including detected layout boxes and their labels. The structure is expected to have:
  231. - "boxes": A list of dictionaries with keys "coordinate" for box coordinates and "block_label" for the type of content.
  232. table_res_list (list): A list of table detection results, where each item is a dictionary containing:
  233. - "block_bbox": The bounding box of the table layout.
  234. - "pred_html": The predicted HTML representation of the table.
  235. formula_res_list (list): A list of formula recognition results.
  236. text_rec_model (Any): The text recognition model.
  237. text_rec_score_thresh (Optional[float], optional): The score threshold for text recognition. Defaults to None.
  238. Returns:
  239. list: A list of dictionaries representing the layout parsing result.
  240. """
  241. matched_ocr_dict = {}
  242. layout_to_ocr_mapping = {}
  243. object_boxes = []
  244. footnote_list = []
  245. bottom_text_y_max = 0
  246. max_block_area = 0.0
  247. region_box = [65535, 65535, 0, 0]
  248. layout_det_res = remove_overlap_blocks(
  249. layout_det_res,
  250. threshold=0.5,
  251. smaller=True,
  252. )
  253. # convert formula_res_list to OCRResult format
  254. convert_formula_res_to_ocr_format(formula_res_list, overall_ocr_res)
  255. # match layout boxes and ocr boxes and get some information for layout_order_config
  256. for box_idx, box_info in enumerate(layout_det_res["boxes"]):
  257. box = box_info["coordinate"]
  258. label = box_info["label"].lower()
  259. object_boxes.append(box)
  260. _, _, _, y2 = box
  261. # update the region box and max_block_area according to the layout boxes
  262. region_box = update_region_box(box, region_box)
  263. max_block_area = max(max_block_area, caculate_bbox_area(box))
  264. update_layout_order_config_block_index(layout_order_config, label, box_idx)
  265. # set the label of footnote to text, when it is above the text boxes
  266. if label == "footnote":
  267. footnote_list.append(box_idx)
  268. if label == "text":
  269. bottom_text_y_max = max(y2, bottom_text_y_max)
  270. if label not in ["formula", "table", "seal"]:
  271. _, matched_idxes = get_sub_regions_ocr_res(
  272. overall_ocr_res, [box], return_match_idx=True
  273. )
  274. layout_to_ocr_mapping[box_idx] = matched_idxes
  275. for matched_idx in matched_idxes:
  276. if matched_ocr_dict.get(matched_idx, None) is None:
  277. matched_ocr_dict[matched_idx] = [box_idx]
  278. else:
  279. matched_ocr_dict[matched_idx].append(box_idx)
  280. # fix the footnote label
  281. for footnote_idx in footnote_list:
  282. if (
  283. layout_det_res["boxes"][footnote_idx]["coordinate"][3]
  284. < bottom_text_y_max
  285. ):
  286. layout_det_res["boxes"][footnote_idx]["label"] = "text"
  287. layout_order_config["text_block_idxes"].append(footnote_idx)
  288. layout_order_config["footer_block_idxes"].remove(footnote_idx)
  289. # fix the doc_title label
  290. doc_title_idxes = layout_order_config.get("doc_title_block_idxes", [])
  291. paragraph_title_idxes = layout_order_config.get(
  292. "paragraph_title_block_idxes", []
  293. )
  294. # check if there is only one paragraph title and without doc_title
  295. only_one_paragraph_title = (
  296. len(paragraph_title_idxes) == 1 and len(doc_title_idxes) == 0
  297. )
  298. if only_one_paragraph_title:
  299. paragraph_title_block_area = caculate_bbox_area(
  300. layout_det_res["boxes"][paragraph_title_idxes[0]]["coordinate"]
  301. )
  302. title_area_max_block_threshold = layout_order_config.get(
  303. "title_area_max_block_threshold", 0.3
  304. )
  305. if (
  306. paragraph_title_block_area
  307. > max_block_area * title_area_max_block_threshold
  308. ):
  309. layout_det_res["boxes"][paragraph_title_idxes[0]]["label"] = "doc_title"
  310. layout_order_config["doc_title_block_idxes"].append(
  311. paragraph_title_idxes[0]
  312. )
  313. layout_order_config["paragraph_title_block_idxes"].remove(
  314. paragraph_title_idxes[0]
  315. )
  316. # Replace the OCR information of the hurdles.
  317. for overall_ocr_idx, layout_box_ids in matched_ocr_dict.items():
  318. if len(layout_box_ids) > 1:
  319. matched_no = 0
  320. overall_ocr_box = copy.deepcopy(
  321. overall_ocr_res["rec_boxes"][overall_ocr_idx]
  322. )
  323. overall_ocr_dt_poly = copy.deepcopy(
  324. overall_ocr_res["dt_polys"][overall_ocr_idx]
  325. )
  326. for box_idx in layout_box_ids:
  327. layout_box = layout_det_res["boxes"][box_idx]["coordinate"]
  328. crop_box = get_bbox_intersection(overall_ocr_box, layout_box)
  329. x1, y1, x2, y2 = [int(i) for i in crop_box]
  330. crop_img = np.array(image)[y1:y2, x1:x2]
  331. crop_img_rec_res = next(text_rec_model([crop_img]))
  332. crop_img_dt_poly = get_bbox_intersection(
  333. overall_ocr_dt_poly, layout_box, return_format="poly"
  334. )
  335. crop_img_rec_score = crop_img_rec_res["rec_score"]
  336. crop_img_rec_text = crop_img_rec_res["rec_text"]
  337. text_rec_score_thresh = (
  338. text_rec_score_thresh
  339. if text_rec_score_thresh is not None
  340. else (self.general_ocr_pipeline.text_rec_score_thresh)
  341. )
  342. if crop_img_rec_score >= text_rec_score_thresh:
  343. matched_no += 1
  344. if matched_no == 1:
  345. # the first matched ocr be replaced by the first matched layout box
  346. overall_ocr_res["dt_polys"][
  347. overall_ocr_idx
  348. ] = crop_img_dt_poly
  349. overall_ocr_res["rec_boxes"][overall_ocr_idx] = crop_box
  350. overall_ocr_res["rec_polys"][
  351. overall_ocr_idx
  352. ] = crop_img_dt_poly
  353. overall_ocr_res["rec_scores"][
  354. overall_ocr_idx
  355. ] = crop_img_rec_score
  356. overall_ocr_res["rec_texts"][
  357. overall_ocr_idx
  358. ] = crop_img_rec_text
  359. else:
  360. # the other matched ocr be appended to the overall ocr result
  361. overall_ocr_res["dt_polys"].append(crop_img_dt_poly)
  362. overall_ocr_res["rec_boxes"] = np.vstack(
  363. (overall_ocr_res["rec_boxes"], crop_box)
  364. )
  365. overall_ocr_res["rec_polys"].append(crop_img_dt_poly)
  366. overall_ocr_res["rec_scores"].append(crop_img_rec_score)
  367. overall_ocr_res["rec_texts"].append(crop_img_rec_text)
  368. overall_ocr_res["rec_labels"].append("text")
  369. layout_to_ocr_mapping[box_idx].remove(overall_ocr_idx)
  370. layout_to_ocr_mapping[box_idx].append(
  371. len(overall_ocr_res["rec_texts"]) - 1
  372. )
  373. layout_order_config["all_layout_region_box"] = region_box
  374. layout_order_config["layout_to_ocr_mapping"] = layout_to_ocr_mapping
  375. layout_order_config["matched_ocr_dict"] = matched_ocr_dict
  376. return layout_order_config, layout_det_res
  377. def sort_line_by_x_projection(
  378. self,
  379. line: List[List[Union[List[int], str]]],
  380. input_img: np.ndarray,
  381. text_rec_model: Any,
  382. text_rec_score_thresh: Union[float, None] = None,
  383. ) -> None:
  384. """
  385. Sort a line of text spans based on their vertical position within the layout bounding box.
  386. Args:
  387. line (list): A list of spans, where each span is a list containing a bounding box and text.
  388. input_img (ndarray): The input image used for OCR.
  389. general_ocr_pipeline (Any): The general OCR pipeline used for text recognition.
  390. Returns:
  391. list: The sorted line of text spans.
  392. """
  393. splited_boxes = split_boxes_if_x_contained(line)
  394. splited_lines = []
  395. if len(line) != len(splited_boxes):
  396. splited_boxes.sort(key=lambda span: span[0][0])
  397. for span in splited_boxes:
  398. if span[2] == "text":
  399. crop_img = input_img[
  400. int(span[0][1]) : int(span[0][3]),
  401. int(span[0][0]) : int(span[0][2]),
  402. ]
  403. crop_img_rec_res = next(text_rec_model([crop_img]))
  404. crop_img_rec_score = crop_img_rec_res["rec_score"]
  405. crop_img_rec_text = crop_img_rec_res["rec_text"]
  406. span[1] = (
  407. crop_img_rec_text
  408. if crop_img_rec_score >= text_rec_score_thresh
  409. else ""
  410. )
  411. splited_lines.append(span)
  412. else:
  413. splited_lines = line
  414. return splited_lines
  415. def get_block_rec_content(
  416. self,
  417. image: list,
  418. layout_order_config: dict,
  419. ocr_rec_res: dict,
  420. block: LayoutParsingBlock,
  421. text_rec_model: Any,
  422. text_rec_score_thresh: Union[float, None] = None,
  423. ) -> str:
  424. text_delimiter_map = {
  425. "content": "\n",
  426. }
  427. line_delimiter_map = {
  428. "doc_title": " ",
  429. "content": "\n",
  430. }
  431. if len(ocr_rec_res["rec_texts"]) == 0:
  432. block.content = ""
  433. return block
  434. label = block.label
  435. if label == "reference":
  436. rec_boxes = ocr_rec_res["boxes"]
  437. block_left_coordinate = min([box[0] for box in rec_boxes])
  438. block_right_coordinate = max([box[2] for box in rec_boxes])
  439. first_line_span_limit = (5,)
  440. last_line_span_limit = (20,)
  441. else:
  442. block_left_coordinate, _, block_right_coordinate, _ = block.bbox
  443. first_line_span_limit = (10,)
  444. last_line_span_limit = (10,)
  445. if label == "formula":
  446. ocr_rec_res["rec_texts"] = [
  447. rec_res_text.replace("$", "")
  448. for rec_res_text in ocr_rec_res["rec_texts"]
  449. ]
  450. lines = group_boxes_into_lines(
  451. ocr_rec_res,
  452. block,
  453. layout_order_config.get("line_height_iou_threshold", 0.4),
  454. )
  455. block.num_of_lines = len(lines)
  456. # format line
  457. new_lines = []
  458. horizontal_text_line_num = 0
  459. for line in lines:
  460. line.sort(key=lambda span: span[0][0])
  461. # merge formula and text
  462. ocr_labels = [span[2] for span in line]
  463. if "formula" in ocr_labels:
  464. line = self.sort_line_by_x_projection(
  465. line, image, text_rec_model, text_rec_score_thresh
  466. )
  467. text_orientation = calculate_text_orientation([span[0] for span in line])
  468. horizontal_text_line_num += 1 if text_orientation == "horizontal" else 0
  469. line_text = format_line(
  470. line,
  471. block_left_coordinate,
  472. block_right_coordinate,
  473. first_line_span_limit=first_line_span_limit,
  474. last_line_span_limit=last_line_span_limit,
  475. block_label=block.label,
  476. delimiter_map=text_delimiter_map,
  477. )
  478. new_lines.append(line_text)
  479. delim = line_delimiter_map.get(label, "")
  480. content = delim.join(new_lines)
  481. block.content = content
  482. block.direction = (
  483. "horizontal"
  484. if horizontal_text_line_num > len(new_lines) * 0.5
  485. else "vertical"
  486. )
  487. return block
  488. def get_layout_parsing_blocks(
  489. self,
  490. image: list,
  491. layout_order_config: dict,
  492. overall_ocr_res: OCRResult,
  493. layout_det_res: DetResult,
  494. table_res_list: list,
  495. seal_res_list: list,
  496. text_rec_model: Any,
  497. text_rec_score_thresh: Union[float, None] = None,
  498. ) -> list:
  499. """
  500. Extract structured information from OCR and layout detection results.
  501. Args:
  502. image (list): The input image.
  503. overall_ocr_res (OCRResult): An object containing the overall OCR results, including detected text boxes and recognized text. The structure is expected to have:
  504. - "input_img": The image on which OCR was performed.
  505. - "dt_boxes": A list of detected text box coordinates.
  506. - "rec_texts": A list of recognized text corresponding to the detected boxes.
  507. layout_det_res (DetResult): An object containing the layout detection results, including detected layout boxes and their labels. The structure is expected to have:
  508. - "boxes": A list of dictionaries with keys "coordinate" for box coordinates and "block_label" for the type of content.
  509. table_res_list (list): A list of table detection results, where each item is a dictionary containing:
  510. - "block_bbox": The bounding box of the table layout.
  511. - "pred_html": The predicted HTML representation of the table.
  512. seal_res_list (List): A list of seal detection results. The details of each item depend on the specific application context.
  513. text_rec_model (Any): A model for text recognition.
  514. 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.
  515. Returns:
  516. list: A list of structured boxes where each item is a dictionary containing:
  517. - "block_label": The label of the content (e.g., 'table', 'chart', 'image').
  518. - The label as a key with either table HTML or image data and text.
  519. - "block_bbox": The coordinates of the layout box.
  520. """
  521. table_index = 0
  522. seal_index = 0
  523. layout_parsing_blocks: List[LayoutParsingBlock] = []
  524. for box_idx, box_info in enumerate(layout_det_res["boxes"]):
  525. label = box_info["label"]
  526. block_bbox = box_info["coordinate"]
  527. rec_res = {"boxes": [], "rec_texts": [], "rec_labels": []}
  528. block = LayoutParsingBlock(label=label, bbox=block_bbox)
  529. if label == "table" and len(table_res_list) > 0:
  530. block.content = table_res_list[table_index]["pred_html"]
  531. table_index += 1
  532. elif label == "seal" and len(seal_res_list) > 0:
  533. block.content = seal_res_list[seal_index]["rec_texts"]
  534. seal_index += 1
  535. else:
  536. if label == "formula":
  537. _, ocr_idx_list = get_sub_regions_ocr_res(
  538. overall_ocr_res, [block_bbox], return_match_idx=True
  539. )
  540. layout_order_config["layout_to_ocr_mapping"][box_idx] = ocr_idx_list
  541. else:
  542. ocr_idx_list = layout_order_config["layout_to_ocr_mapping"].get(
  543. box_idx, []
  544. )
  545. for box_no in ocr_idx_list:
  546. rec_res["boxes"].append(overall_ocr_res["rec_boxes"][box_no])
  547. rec_res["rec_texts"].append(
  548. overall_ocr_res["rec_texts"][box_no],
  549. )
  550. rec_res["rec_labels"].append(
  551. overall_ocr_res["rec_labels"][box_no],
  552. )
  553. block = self.get_block_rec_content(
  554. image=image,
  555. block=block,
  556. layout_order_config=layout_order_config,
  557. ocr_rec_res=rec_res,
  558. text_rec_model=text_rec_model,
  559. text_rec_score_thresh=text_rec_score_thresh,
  560. )
  561. if label in ["chart", "image"]:
  562. x_min, y_min, x_max, y_max = list(map(int, block_bbox))
  563. img_path = f"imgs/img_in_table_box_{x_min}_{y_min}_{x_max}_{y_max}.jpg"
  564. img = Image.fromarray(image[y_min:y_max, x_min:x_max, ::-1])
  565. block.image = {img_path: img}
  566. layout_parsing_blocks.append(block)
  567. # when there is no layout detection result but there is ocr result, use ocr result
  568. if len(layout_det_res["boxes"]) == 0:
  569. region_box = [65535, 65535, 0, 0]
  570. for ocr_idx, (ocr_rec_box, ocr_rec_text) in enumerate(
  571. zip(overall_ocr_res["rec_boxes"], overall_ocr_res["rec_texts"])
  572. ):
  573. update_layout_order_config_block_index(
  574. layout_order_config, "text", ocr_idx
  575. )
  576. region_box = update_region_box(ocr_rec_box, region_box)
  577. layout_parsing_blocks.append(
  578. LayoutParsingBlock(
  579. label="text", bbox=ocr_rec_box, content=ocr_rec_text
  580. )
  581. )
  582. layout_order_config["all_layout_region_box"] = region_box
  583. return layout_parsing_blocks, layout_order_config
  584. def get_layout_parsing_res(
  585. self,
  586. image: list,
  587. layout_det_res: DetResult,
  588. overall_ocr_res: OCRResult,
  589. table_res_list: list,
  590. seal_res_list: list,
  591. formula_res_list: list,
  592. text_rec_score_thresh: Union[float, None] = None,
  593. ) -> list:
  594. """
  595. Retrieves the layout parsing result based on the layout detection result, OCR result, and other recognition results.
  596. Args:
  597. image (list): The input image.
  598. layout_det_res (DetResult): The detection result containing the layout information of the document.
  599. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  600. table_res_list (list): A list of table recognition results.
  601. seal_res_list (list): A list of seal recognition results.
  602. formula_res_list (list): A list of formula recognition results.
  603. text_rec_score_thresh (Optional[float], optional): The score threshold for text recognition. Defaults to None.
  604. Returns:
  605. list: A list of dictionaries representing the layout parsing result.
  606. """
  607. from .setting import layout_order_config
  608. # Standardize data
  609. layout_order_config, layout_det_res = self.standardized_data(
  610. image=image,
  611. layout_order_config=copy.deepcopy(layout_order_config),
  612. layout_det_res=layout_det_res,
  613. overall_ocr_res=overall_ocr_res,
  614. formula_res_list=formula_res_list,
  615. text_rec_model=self.general_ocr_pipeline.text_rec_model,
  616. text_rec_score_thresh=text_rec_score_thresh,
  617. )
  618. # Format layout parsing block
  619. parsing_res_list, layout_order_config = self.get_layout_parsing_blocks(
  620. image=image,
  621. layout_order_config=layout_order_config,
  622. overall_ocr_res=overall_ocr_res,
  623. layout_det_res=layout_det_res,
  624. table_res_list=table_res_list,
  625. seal_res_list=seal_res_list,
  626. text_rec_model=self.general_ocr_pipeline.text_rec_model,
  627. text_rec_score_thresh=self.general_ocr_pipeline.text_rec_score_thresh,
  628. )
  629. parsing_res_list = xycut_enhanced(
  630. parsing_res_list,
  631. layout_order_config,
  632. )
  633. return parsing_res_list
  634. def get_model_settings(
  635. self,
  636. use_doc_orientation_classify: Union[bool, None],
  637. use_doc_unwarping: Union[bool, None],
  638. use_general_ocr: Union[bool, None],
  639. use_seal_recognition: Union[bool, None],
  640. use_table_recognition: Union[bool, None],
  641. use_formula_recognition: Union[bool, None],
  642. ) -> dict:
  643. """
  644. Get the model settings based on the provided parameters or default values.
  645. Args:
  646. use_doc_orientation_classify (Union[bool, None]): Enables document orientation classification if True. Defaults to system setting if None.
  647. use_doc_unwarping (Union[bool, None]): Enables document unwarping if True. Defaults to system setting if None.
  648. use_general_ocr (Union[bool, None]): Enables general OCR if True. Defaults to system setting if None.
  649. use_seal_recognition (Union[bool, None]): Enables seal recognition if True. Defaults to system setting if None.
  650. use_table_recognition (Union[bool, None]): Enables table recognition if True. Defaults to system setting if None.
  651. use_formula_recognition (Union[bool, None]): Enables formula recognition if True. Defaults to system setting if None.
  652. Returns:
  653. dict: A dictionary containing the model settings.
  654. """
  655. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  656. use_doc_preprocessor = self.use_doc_preprocessor
  657. else:
  658. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  659. use_doc_preprocessor = True
  660. else:
  661. use_doc_preprocessor = False
  662. if use_general_ocr is None:
  663. use_general_ocr = self.use_general_ocr
  664. if use_seal_recognition is None:
  665. use_seal_recognition = self.use_seal_recognition
  666. if use_table_recognition is None:
  667. use_table_recognition = self.use_table_recognition
  668. if use_formula_recognition is None:
  669. use_formula_recognition = self.use_formula_recognition
  670. return dict(
  671. use_doc_preprocessor=use_doc_preprocessor,
  672. use_general_ocr=use_general_ocr,
  673. use_seal_recognition=use_seal_recognition,
  674. use_table_recognition=use_table_recognition,
  675. use_formula_recognition=use_formula_recognition,
  676. )
  677. def predict(
  678. self,
  679. input: Union[str, list[str], np.ndarray, list[np.ndarray]],
  680. use_doc_orientation_classify: Union[bool, None] = None,
  681. use_doc_unwarping: Union[bool, None] = None,
  682. use_textline_orientation: Optional[bool] = None,
  683. use_general_ocr: Union[bool, None] = None,
  684. use_seal_recognition: Union[bool, None] = None,
  685. use_table_recognition: Union[bool, None] = None,
  686. use_formula_recognition: Union[bool, None] = None,
  687. layout_threshold: Optional[Union[float, dict]] = None,
  688. layout_nms: Optional[bool] = None,
  689. layout_unclip_ratio: Optional[Union[float, Tuple[float, float], dict]] = None,
  690. layout_merge_bboxes_mode: Optional[str] = None,
  691. text_det_limit_side_len: Union[int, None] = None,
  692. text_det_limit_type: Union[str, None] = None,
  693. text_det_thresh: Union[float, None] = None,
  694. text_det_box_thresh: Union[float, None] = None,
  695. text_det_unclip_ratio: Union[float, None] = None,
  696. text_rec_score_thresh: Union[float, None] = None,
  697. seal_det_limit_side_len: Union[int, None] = None,
  698. seal_det_limit_type: Union[str, None] = None,
  699. seal_det_thresh: Union[float, None] = None,
  700. seal_det_box_thresh: Union[float, None] = None,
  701. seal_det_unclip_ratio: Union[float, None] = None,
  702. seal_rec_score_thresh: Union[float, None] = None,
  703. use_table_cells_ocr_results: bool = False,
  704. use_e2e_wired_table_rec_model: bool = False,
  705. use_e2e_wireless_table_rec_model: bool = True,
  706. **kwargs,
  707. ) -> LayoutParsingResultV2:
  708. """
  709. Predicts the layout parsing result for the given input.
  710. Args:
  711. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  712. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  713. use_textline_orientation (Optional[bool]): Whether to use textline orientation prediction.
  714. use_general_ocr (Optional[bool]): Whether to use general OCR.
  715. use_seal_recognition (Optional[bool]): Whether to use seal recognition.
  716. use_table_recognition (Optional[bool]): Whether to use table recognition.
  717. use_formula_recognition (Optional[bool]): Whether to use formula recognition.
  718. layout_threshold (Optional[float]): The threshold value to filter out low-confidence predictions. Default is None.
  719. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to False.
  720. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  721. Defaults to None.
  722. If it's a single number, then both width and height are used.
  723. If it's a tuple of two numbers, then they are used separately for width and height respectively.
  724. If it's None, then no unclipping will be performed.
  725. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  726. text_det_limit_side_len (Optional[int]): Maximum side length for text detection.
  727. text_det_limit_type (Optional[str]): Type of limit to apply for text detection.
  728. text_det_thresh (Optional[float]): Threshold for text detection.
  729. text_det_box_thresh (Optional[float]): Threshold for text detection boxes.
  730. text_det_unclip_ratio (Optional[float]): Ratio for unclipping text detection boxes.
  731. text_rec_score_thresh (Optional[float]): Score threshold for text recognition.
  732. seal_det_limit_side_len (Optional[int]): Maximum side length for seal detection.
  733. seal_det_limit_type (Optional[str]): Type of limit to apply for seal detection.
  734. seal_det_thresh (Optional[float]): Threshold for seal detection.
  735. seal_det_box_thresh (Optional[float]): Threshold for seal detection boxes.
  736. seal_det_unclip_ratio (Optional[float]): Ratio for unclipping seal detection boxes.
  737. seal_rec_score_thresh (Optional[float]): Score threshold for seal recognition.
  738. use_table_cells_ocr_results (bool): whether to use OCR results with cells.
  739. use_e2e_wired_table_rec_model (bool): Whether to use end-to-end wired table recognition model.
  740. use_e2e_wireless_table_rec_model (bool): Whether to use end-to-end wireless table recognition model.
  741. **kwargs (Any): Additional settings to extend functionality.
  742. Returns:
  743. LayoutParsingResultV2: The predicted layout parsing result.
  744. """
  745. model_settings = self.get_model_settings(
  746. use_doc_orientation_classify,
  747. use_doc_unwarping,
  748. use_general_ocr,
  749. use_seal_recognition,
  750. use_table_recognition,
  751. use_formula_recognition,
  752. )
  753. if not self.check_model_settings_valid(model_settings):
  754. yield {"error": "the input params for model settings are invalid!"}
  755. for batch_data in self.batch_sampler(input):
  756. image_array = self.img_reader(batch_data.instances)[0]
  757. if model_settings["use_doc_preprocessor"]:
  758. doc_preprocessor_res = next(
  759. self.doc_preprocessor_pipeline(
  760. image_array,
  761. use_doc_orientation_classify=use_doc_orientation_classify,
  762. use_doc_unwarping=use_doc_unwarping,
  763. ),
  764. )
  765. else:
  766. doc_preprocessor_res = {"output_img": image_array}
  767. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  768. layout_det_res = next(
  769. self.layout_det_model(
  770. doc_preprocessor_image,
  771. threshold=layout_threshold,
  772. layout_nms=layout_nms,
  773. layout_unclip_ratio=layout_unclip_ratio,
  774. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  775. )
  776. )
  777. imgs_in_doc = gather_imgs(doc_preprocessor_image, layout_det_res["boxes"])
  778. if model_settings["use_formula_recognition"]:
  779. formula_res_all = next(
  780. self.formula_recognition_pipeline(
  781. doc_preprocessor_image,
  782. use_layout_detection=False,
  783. use_doc_orientation_classify=False,
  784. use_doc_unwarping=False,
  785. layout_det_res=layout_det_res,
  786. ),
  787. )
  788. formula_res_list = formula_res_all["formula_res_list"]
  789. else:
  790. formula_res_list = []
  791. for formula_res in formula_res_list:
  792. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  793. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = 255.0
  794. if (
  795. model_settings["use_general_ocr"]
  796. or model_settings["use_table_recognition"]
  797. ):
  798. overall_ocr_res = next(
  799. self.general_ocr_pipeline(
  800. doc_preprocessor_image,
  801. use_textline_orientation=use_textline_orientation,
  802. text_det_limit_side_len=text_det_limit_side_len,
  803. text_det_limit_type=text_det_limit_type,
  804. text_det_thresh=text_det_thresh,
  805. text_det_box_thresh=text_det_box_thresh,
  806. text_det_unclip_ratio=text_det_unclip_ratio,
  807. text_rec_score_thresh=text_rec_score_thresh,
  808. ),
  809. )
  810. else:
  811. overall_ocr_res = {}
  812. overall_ocr_res["rec_labels"] = ["text"] * len(overall_ocr_res["rec_texts"])
  813. if model_settings["use_table_recognition"]:
  814. table_contents = copy.deepcopy(overall_ocr_res)
  815. for formula_res in formula_res_list:
  816. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  817. poly_points = [
  818. (x_min, y_min),
  819. (x_max, y_min),
  820. (x_max, y_max),
  821. (x_min, y_max),
  822. ]
  823. table_contents["dt_polys"].append(poly_points)
  824. table_contents["rec_texts"].append(
  825. f"${formula_res['rec_formula']}$"
  826. )
  827. table_contents["rec_boxes"] = np.vstack(
  828. (table_contents["rec_boxes"], [formula_res["dt_polys"]])
  829. )
  830. table_contents["rec_polys"].append(poly_points)
  831. table_contents["rec_scores"].append(1)
  832. for img in imgs_in_doc:
  833. img_path = img["path"]
  834. x_min, y_min, x_max, y_max = img["coordinate"]
  835. poly_points = [
  836. (x_min, y_min),
  837. (x_max, y_min),
  838. (x_max, y_max),
  839. (x_min, y_max),
  840. ]
  841. table_contents["dt_polys"].append(poly_points)
  842. table_contents["rec_texts"].append(
  843. f'<div style="text-align: center;"><img src="{img_path}" alt="Image" /></div>'
  844. )
  845. if table_contents["rec_boxes"].size == 0:
  846. table_contents["rec_boxes"] = np.array([img["coordinate"]])
  847. else:
  848. table_contents["rec_boxes"] = np.vstack(
  849. (table_contents["rec_boxes"], img["coordinate"])
  850. )
  851. table_contents["rec_polys"].append(poly_points)
  852. table_contents["rec_scores"].append(img["score"])
  853. table_res_all = next(
  854. self.table_recognition_pipeline(
  855. doc_preprocessor_image,
  856. use_doc_orientation_classify=False,
  857. use_doc_unwarping=False,
  858. use_layout_detection=False,
  859. use_ocr_model=False,
  860. overall_ocr_res=table_contents,
  861. layout_det_res=layout_det_res,
  862. cell_sort_by_y_projection=True,
  863. use_table_cells_ocr_results=use_table_cells_ocr_results,
  864. use_e2e_wired_table_rec_model=use_e2e_wired_table_rec_model,
  865. use_e2e_wireless_table_rec_model=use_e2e_wireless_table_rec_model,
  866. ),
  867. )
  868. table_res_list = table_res_all["table_res_list"]
  869. else:
  870. table_res_list = []
  871. if model_settings["use_seal_recognition"]:
  872. seal_res_all = next(
  873. self.seal_recognition_pipeline(
  874. doc_preprocessor_image,
  875. use_doc_orientation_classify=False,
  876. use_doc_unwarping=False,
  877. use_layout_detection=False,
  878. layout_det_res=layout_det_res,
  879. seal_det_limit_side_len=seal_det_limit_side_len,
  880. seal_det_limit_type=seal_det_limit_type,
  881. seal_det_thresh=seal_det_thresh,
  882. seal_det_box_thresh=seal_det_box_thresh,
  883. seal_det_unclip_ratio=seal_det_unclip_ratio,
  884. seal_rec_score_thresh=seal_rec_score_thresh,
  885. ),
  886. )
  887. seal_res_list = seal_res_all["seal_res_list"]
  888. else:
  889. seal_res_list = []
  890. parsing_res_list = self.get_layout_parsing_res(
  891. doc_preprocessor_image,
  892. layout_det_res=layout_det_res,
  893. overall_ocr_res=overall_ocr_res,
  894. table_res_list=table_res_list,
  895. seal_res_list=seal_res_list,
  896. formula_res_list=formula_res_list,
  897. text_rec_score_thresh=text_rec_score_thresh,
  898. )
  899. for formula_res in formula_res_list:
  900. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  901. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = formula_res[
  902. "input_img"
  903. ]
  904. single_img_res = {
  905. "input_path": batch_data.input_paths[0],
  906. "page_index": batch_data.page_indexes[0],
  907. "doc_preprocessor_res": doc_preprocessor_res,
  908. "layout_det_res": layout_det_res,
  909. "overall_ocr_res": overall_ocr_res,
  910. "table_res_list": table_res_list,
  911. "seal_res_list": seal_res_list,
  912. "formula_res_list": formula_res_list,
  913. "parsing_res_list": parsing_res_list,
  914. "imgs_in_doc": imgs_in_doc,
  915. "model_settings": model_settings,
  916. }
  917. yield LayoutParsingResultV2(single_img_res)
  918. def concatenate_markdown_pages(self, markdown_list: list) -> tuple:
  919. """
  920. Concatenate Markdown content from multiple pages into a single document.
  921. Args:
  922. markdown_list (list): A list containing Markdown data for each page.
  923. Returns:
  924. tuple: A tuple containing the processed Markdown text.
  925. """
  926. markdown_texts = ""
  927. previous_page_last_element_paragraph_end_flag = True
  928. for res in markdown_list:
  929. # Get the paragraph flags for the current page
  930. page_first_element_paragraph_start_flag: bool = res[
  931. "page_continuation_flags"
  932. ][0]
  933. page_last_element_paragraph_end_flag: bool = res["page_continuation_flags"][
  934. 1
  935. ]
  936. # Determine whether to add a space or a newline
  937. if (
  938. not page_first_element_paragraph_start_flag
  939. and not previous_page_last_element_paragraph_end_flag
  940. ):
  941. last_char_of_markdown = markdown_texts[-1] if markdown_texts else ""
  942. first_char_of_handler = (
  943. res["markdown_texts"][0] if res["markdown_texts"] else ""
  944. )
  945. # Check if the last character and the first character are Chinese characters
  946. last_is_chinese_char = (
  947. re.match(r"[\u4e00-\u9fff]", last_char_of_markdown)
  948. if last_char_of_markdown
  949. else False
  950. )
  951. first_is_chinese_char = (
  952. re.match(r"[\u4e00-\u9fff]", first_char_of_handler)
  953. if first_char_of_handler
  954. else False
  955. )
  956. if not (last_is_chinese_char or first_is_chinese_char):
  957. markdown_texts += " " + res["markdown_texts"]
  958. else:
  959. markdown_texts += res["markdown_texts"]
  960. else:
  961. markdown_texts += "\n\n" + res["markdown_texts"]
  962. previous_page_last_element_paragraph_end_flag = (
  963. page_last_element_paragraph_end_flag
  964. )
  965. return markdown_texts