draw_bbox.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import fitz
  2. from magic_pdf.config.constants import CROSS_PAGE
  3. from magic_pdf.config.ocr_content_type import (BlockType, CategoryId,
  4. ContentType)
  5. from magic_pdf.data.dataset import Dataset
  6. from magic_pdf.libs.commons import fitz # PyMuPDF
  7. from magic_pdf.model.magic_model import MagicModel
  8. def draw_bbox_without_number(i, bbox_list, page, rgb_config, fill_config):
  9. new_rgb = []
  10. for item in rgb_config:
  11. item = float(item) / 255
  12. new_rgb.append(item)
  13. page_data = bbox_list[i]
  14. for bbox in page_data:
  15. x0, y0, x1, y1 = bbox
  16. rect_coords = fitz.Rect(x0, y0, x1, y1) # Define the rectangle
  17. if fill_config:
  18. page.draw_rect(
  19. rect_coords,
  20. color=None,
  21. fill=new_rgb,
  22. fill_opacity=0.3,
  23. width=0.5,
  24. overlay=True,
  25. ) # Draw the rectangle
  26. else:
  27. page.draw_rect(
  28. rect_coords,
  29. color=new_rgb,
  30. fill=None,
  31. fill_opacity=1,
  32. width=0.5,
  33. overlay=True,
  34. ) # Draw the rectangle
  35. def draw_bbox_with_number(i, bbox_list, page, rgb_config, fill_config, draw_bbox=True):
  36. new_rgb = []
  37. for item in rgb_config:
  38. item = float(item) / 255
  39. new_rgb.append(item)
  40. page_data = bbox_list[i]
  41. for j, bbox in enumerate(page_data):
  42. x0, y0, x1, y1 = bbox
  43. rect_coords = fitz.Rect(x0, y0, x1, y1) # Define the rectangle
  44. if draw_bbox:
  45. if fill_config:
  46. page.draw_rect(
  47. rect_coords,
  48. color=None,
  49. fill=new_rgb,
  50. fill_opacity=0.3,
  51. width=0.5,
  52. overlay=True,
  53. ) # Draw the rectangle
  54. else:
  55. page.draw_rect(
  56. rect_coords,
  57. color=new_rgb,
  58. fill=None,
  59. fill_opacity=1,
  60. width=0.5,
  61. overlay=True,
  62. ) # Draw the rectangle
  63. page.insert_text(
  64. (x1 + 2, y0 + 10), str(j + 1), fontsize=10, color=new_rgb
  65. ) # Insert the index in the top left corner of the rectangle
  66. def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):
  67. dropped_bbox_list = []
  68. tables_list, tables_body_list = [], []
  69. tables_caption_list, tables_footnote_list = [], []
  70. imgs_list, imgs_body_list, imgs_caption_list = [], [], []
  71. imgs_footnote_list = []
  72. titles_list = []
  73. texts_list = []
  74. interequations_list = []
  75. lists_list = []
  76. indexs_list = []
  77. for page in pdf_info:
  78. page_dropped_list = []
  79. tables, tables_body, tables_caption, tables_footnote = [], [], [], []
  80. imgs, imgs_body, imgs_caption, imgs_footnote = [], [], [], []
  81. titles = []
  82. texts = []
  83. interequations = []
  84. lists = []
  85. indices = []
  86. for dropped_bbox in page['discarded_blocks']:
  87. page_dropped_list.append(dropped_bbox['bbox'])
  88. dropped_bbox_list.append(page_dropped_list)
  89. for block in page['para_blocks']:
  90. bbox = block['bbox']
  91. if block['type'] == BlockType.Table:
  92. tables.append(bbox)
  93. for nested_block in block['blocks']:
  94. bbox = nested_block['bbox']
  95. if nested_block['type'] == BlockType.TableBody:
  96. tables_body.append(bbox)
  97. elif nested_block['type'] == BlockType.TableCaption:
  98. tables_caption.append(bbox)
  99. elif nested_block['type'] == BlockType.TableFootnote:
  100. tables_footnote.append(bbox)
  101. elif block['type'] == BlockType.Image:
  102. imgs.append(bbox)
  103. for nested_block in block['blocks']:
  104. bbox = nested_block['bbox']
  105. if nested_block['type'] == BlockType.ImageBody:
  106. imgs_body.append(bbox)
  107. elif nested_block['type'] == BlockType.ImageCaption:
  108. imgs_caption.append(bbox)
  109. elif nested_block['type'] == BlockType.ImageFootnote:
  110. imgs_footnote.append(bbox)
  111. elif block['type'] == BlockType.Title:
  112. titles.append(bbox)
  113. elif block['type'] == BlockType.Text:
  114. texts.append(bbox)
  115. elif block['type'] == BlockType.InterlineEquation:
  116. interequations.append(bbox)
  117. elif block['type'] == BlockType.List:
  118. lists.append(bbox)
  119. elif block['type'] == BlockType.Index:
  120. indices.append(bbox)
  121. tables_list.append(tables)
  122. tables_body_list.append(tables_body)
  123. tables_caption_list.append(tables_caption)
  124. tables_footnote_list.append(tables_footnote)
  125. imgs_list.append(imgs)
  126. imgs_body_list.append(imgs_body)
  127. imgs_caption_list.append(imgs_caption)
  128. imgs_footnote_list.append(imgs_footnote)
  129. titles_list.append(titles)
  130. texts_list.append(texts)
  131. interequations_list.append(interequations)
  132. lists_list.append(lists)
  133. indexs_list.append(indices)
  134. layout_bbox_list = []
  135. table_type_order = {
  136. 'table_caption': 1,
  137. 'table_body': 2,
  138. 'table_footnote': 3
  139. }
  140. for page in pdf_info:
  141. page_block_list = []
  142. for block in page['para_blocks']:
  143. if block['type'] in [
  144. BlockType.Text,
  145. BlockType.Title,
  146. BlockType.InterlineEquation,
  147. BlockType.List,
  148. BlockType.Index,
  149. ]:
  150. bbox = block['bbox']
  151. page_block_list.append(bbox)
  152. elif block['type'] in [BlockType.Image]:
  153. for sub_block in block['blocks']:
  154. bbox = sub_block['bbox']
  155. page_block_list.append(bbox)
  156. elif block['type'] in [BlockType.Table]:
  157. sorted_blocks = sorted(block['blocks'], key=lambda x: table_type_order[x['type']])
  158. for sub_block in sorted_blocks:
  159. bbox = sub_block['bbox']
  160. page_block_list.append(bbox)
  161. layout_bbox_list.append(page_block_list)
  162. pdf_docs = fitz.open('pdf', pdf_bytes)
  163. for i, page in enumerate(pdf_docs):
  164. draw_bbox_without_number(i, dropped_bbox_list, page, [158, 158, 158], True)
  165. # draw_bbox_without_number(i, tables_list, page, [153, 153, 0], True) # color !
  166. draw_bbox_without_number(i, tables_body_list, page, [204, 204, 0], True)
  167. draw_bbox_without_number(i, tables_caption_list, page, [255, 255, 102], True)
  168. draw_bbox_without_number(i, tables_footnote_list, page, [229, 255, 204], True)
  169. # draw_bbox_without_number(i, imgs_list, page, [51, 102, 0], True)
  170. draw_bbox_without_number(i, imgs_body_list, page, [153, 255, 51], True)
  171. draw_bbox_without_number(i, imgs_caption_list, page, [102, 178, 255], True)
  172. draw_bbox_without_number(i, imgs_footnote_list, page, [255, 178, 102], True),
  173. draw_bbox_without_number(i, titles_list, page, [102, 102, 255], True)
  174. draw_bbox_without_number(i, texts_list, page, [153, 0, 76], True)
  175. draw_bbox_without_number(i, interequations_list, page, [0, 255, 0], True)
  176. draw_bbox_without_number(i, lists_list, page, [40, 169, 92], True)
  177. draw_bbox_without_number(i, indexs_list, page, [40, 169, 92], True)
  178. draw_bbox_with_number(
  179. i, layout_bbox_list, page, [255, 0, 0], False, draw_bbox=False
  180. )
  181. # Save the PDF
  182. pdf_docs.save(f'{out_path}/{filename}')
  183. def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
  184. text_list = []
  185. inline_equation_list = []
  186. interline_equation_list = []
  187. image_list = []
  188. table_list = []
  189. dropped_list = []
  190. next_page_text_list = []
  191. next_page_inline_equation_list = []
  192. def get_span_info(span):
  193. if span['type'] == ContentType.Text:
  194. if span.get(CROSS_PAGE, False):
  195. next_page_text_list.append(span['bbox'])
  196. else:
  197. page_text_list.append(span['bbox'])
  198. elif span['type'] == ContentType.InlineEquation:
  199. if span.get(CROSS_PAGE, False):
  200. next_page_inline_equation_list.append(span['bbox'])
  201. else:
  202. page_inline_equation_list.append(span['bbox'])
  203. elif span['type'] == ContentType.InterlineEquation:
  204. page_interline_equation_list.append(span['bbox'])
  205. elif span['type'] == ContentType.Image:
  206. page_image_list.append(span['bbox'])
  207. elif span['type'] == ContentType.Table:
  208. page_table_list.append(span['bbox'])
  209. for page in pdf_info:
  210. page_text_list = []
  211. page_inline_equation_list = []
  212. page_interline_equation_list = []
  213. page_image_list = []
  214. page_table_list = []
  215. page_dropped_list = []
  216. # 将跨页的span放到移动到下一页的列表中
  217. if len(next_page_text_list) > 0:
  218. page_text_list.extend(next_page_text_list)
  219. next_page_text_list.clear()
  220. if len(next_page_inline_equation_list) > 0:
  221. page_inline_equation_list.extend(next_page_inline_equation_list)
  222. next_page_inline_equation_list.clear()
  223. # 构造dropped_list
  224. for block in page['discarded_blocks']:
  225. if block['type'] == BlockType.Discarded:
  226. for line in block['lines']:
  227. for span in line['spans']:
  228. page_dropped_list.append(span['bbox'])
  229. dropped_list.append(page_dropped_list)
  230. # 构造其余useful_list
  231. # for block in page['para_blocks']: # span直接用分段合并前的结果就可以
  232. for block in page['preproc_blocks']:
  233. if block['type'] in [
  234. BlockType.Text,
  235. BlockType.Title,
  236. BlockType.InterlineEquation,
  237. BlockType.List,
  238. BlockType.Index,
  239. ]:
  240. for line in block['lines']:
  241. for span in line['spans']:
  242. get_span_info(span)
  243. elif block['type'] in [BlockType.Image, BlockType.Table]:
  244. for sub_block in block['blocks']:
  245. for line in sub_block['lines']:
  246. for span in line['spans']:
  247. get_span_info(span)
  248. text_list.append(page_text_list)
  249. inline_equation_list.append(page_inline_equation_list)
  250. interline_equation_list.append(page_interline_equation_list)
  251. image_list.append(page_image_list)
  252. table_list.append(page_table_list)
  253. pdf_docs = fitz.open('pdf', pdf_bytes)
  254. for i, page in enumerate(pdf_docs):
  255. # 获取当前页面的数据
  256. draw_bbox_without_number(i, text_list, page, [255, 0, 0], False)
  257. draw_bbox_without_number(i, inline_equation_list, page, [0, 255, 0], False)
  258. draw_bbox_without_number(i, interline_equation_list, page, [0, 0, 255], False)
  259. draw_bbox_without_number(i, image_list, page, [255, 204, 0], False)
  260. draw_bbox_without_number(i, table_list, page, [204, 0, 255], False)
  261. draw_bbox_without_number(i, dropped_list, page, [158, 158, 158], False)
  262. # Save the PDF
  263. pdf_docs.save(f'{out_path}/{filename}')
  264. def draw_model_bbox(model_list, dataset: Dataset, out_path, filename):
  265. dropped_bbox_list = []
  266. tables_body_list, tables_caption_list, tables_footnote_list = [], [], []
  267. imgs_body_list, imgs_caption_list, imgs_footnote_list = [], [], []
  268. titles_list = []
  269. texts_list = []
  270. interequations_list = []
  271. magic_model = MagicModel(model_list, dataset)
  272. for i in range(len(model_list)):
  273. page_dropped_list = []
  274. tables_body, tables_caption, tables_footnote = [], [], []
  275. imgs_body, imgs_caption, imgs_footnote = [], [], []
  276. titles = []
  277. texts = []
  278. interequations = []
  279. page_info = magic_model.get_model_list(i)
  280. layout_dets = page_info['layout_dets']
  281. for layout_det in layout_dets:
  282. bbox = layout_det['bbox']
  283. if layout_det['category_id'] == CategoryId.Text:
  284. texts.append(bbox)
  285. elif layout_det['category_id'] == CategoryId.Title:
  286. titles.append(bbox)
  287. elif layout_det['category_id'] == CategoryId.TableBody:
  288. tables_body.append(bbox)
  289. elif layout_det['category_id'] == CategoryId.TableCaption:
  290. tables_caption.append(bbox)
  291. elif layout_det['category_id'] == CategoryId.TableFootnote:
  292. tables_footnote.append(bbox)
  293. elif layout_det['category_id'] == CategoryId.ImageBody:
  294. imgs_body.append(bbox)
  295. elif layout_det['category_id'] == CategoryId.ImageCaption:
  296. imgs_caption.append(bbox)
  297. elif layout_det['category_id'] == CategoryId.InterlineEquation_YOLO:
  298. interequations.append(bbox)
  299. elif layout_det['category_id'] == CategoryId.Abandon:
  300. page_dropped_list.append(bbox)
  301. elif layout_det['category_id'] == CategoryId.ImageFootnote:
  302. imgs_footnote.append(bbox)
  303. tables_body_list.append(tables_body)
  304. tables_caption_list.append(tables_caption)
  305. tables_footnote_list.append(tables_footnote)
  306. imgs_body_list.append(imgs_body)
  307. imgs_caption_list.append(imgs_caption)
  308. titles_list.append(titles)
  309. texts_list.append(texts)
  310. interequations_list.append(interequations)
  311. dropped_bbox_list.append(page_dropped_list)
  312. imgs_footnote_list.append(imgs_footnote)
  313. for i in range(len(dataset)):
  314. page = dataset.get_page(i)
  315. draw_bbox_with_number(
  316. i, dropped_bbox_list, page, [158, 158, 158], True
  317. ) # color !
  318. draw_bbox_with_number(i, tables_body_list, page, [204, 204, 0], True)
  319. draw_bbox_with_number(i, tables_caption_list, page, [255, 255, 102], True)
  320. draw_bbox_with_number(i, tables_footnote_list, page, [229, 255, 204], True)
  321. draw_bbox_with_number(i, imgs_body_list, page, [153, 255, 51], True)
  322. draw_bbox_with_number(i, imgs_caption_list, page, [102, 178, 255], True)
  323. draw_bbox_with_number(i, imgs_footnote_list, page, [255, 178, 102], True)
  324. draw_bbox_with_number(i, titles_list, page, [102, 102, 255], True)
  325. draw_bbox_with_number(i, texts_list, page, [153, 0, 76], True)
  326. draw_bbox_with_number(i, interequations_list, page, [0, 255, 0], True)
  327. # Save the PDF
  328. dataset.dump_to_file(f'{out_path}/{filename}')
  329. def draw_line_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
  330. layout_bbox_list = []
  331. for page in pdf_info:
  332. page_line_list = []
  333. for block in page['preproc_blocks']:
  334. if block['type'] in [BlockType.Text, BlockType.Title, BlockType.InterlineEquation]:
  335. for line in block['lines']:
  336. bbox = line['bbox']
  337. index = line['index']
  338. page_line_list.append({'index': index, 'bbox': bbox})
  339. if block['type'] in [BlockType.Image, BlockType.Table]:
  340. for sub_block in block['blocks']:
  341. if sub_block['type'] in [BlockType.ImageBody, BlockType.TableBody]:
  342. if len(sub_block['virtual_lines']) > 0 and sub_block['virtual_lines'][0].get('index', None) is not None:
  343. for line in sub_block['virtual_lines']:
  344. bbox = line['bbox']
  345. index = line['index']
  346. page_line_list.append({'index': index, 'bbox': bbox})
  347. else:
  348. for line in sub_block['lines']:
  349. bbox = line['bbox']
  350. index = line['index']
  351. page_line_list.append({'index': index, 'bbox': bbox})
  352. elif sub_block['type'] in [BlockType.ImageCaption, BlockType.TableCaption, BlockType.ImageFootnote, BlockType.TableFootnote]:
  353. for line in sub_block['lines']:
  354. bbox = line['bbox']
  355. index = line['index']
  356. page_line_list.append({'index': index, 'bbox': bbox})
  357. sorted_bboxes = sorted(page_line_list, key=lambda x: x['index'])
  358. layout_bbox_list.append(sorted_bbox['bbox'] for sorted_bbox in sorted_bboxes)
  359. pdf_docs = fitz.open('pdf', pdf_bytes)
  360. for i, page in enumerate(pdf_docs):
  361. draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
  362. pdf_docs.save(f'{out_path}/{filename}_line_sort.pdf')
  363. def draw_layout_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
  364. layout_bbox_list = []
  365. for page in pdf_info:
  366. page_block_list = []
  367. for block in page['para_blocks']:
  368. bbox = block['bbox']
  369. page_block_list.append(bbox)
  370. layout_bbox_list.append(page_block_list)
  371. pdf_docs = fitz.open('pdf', pdf_bytes)
  372. for i, page in enumerate(pdf_docs):
  373. draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
  374. pdf_docs.save(f'{out_path}/{filename}_layout_sort.pdf')