draw_bbox.py 17 KB

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