pipeline_v2.py 61 KB

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