pipeline_v2.py 58 KB

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