pipeline_v2.py 59 KB

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