draw_bbox.py 15 KB

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