app.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import base64
  3. import os
  4. import time
  5. import zipfile
  6. from pathlib import Path
  7. import re
  8. import gradio as gr
  9. from loguru import logger
  10. from magic_pdf.libs.hash_utils import compute_sha256
  11. from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter
  12. from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter
  13. from magic_pdf.tools.common import do_parse, prepare_env
  14. def read_fn(path):
  15. disk_rw = DiskReaderWriter(os.path.dirname(path))
  16. return disk_rw.read(os.path.basename(path), AbsReaderWriter.MODE_BIN)
  17. def parse_pdf(doc_path, output_dir, end_page_id):
  18. os.makedirs(output_dir, exist_ok=True)
  19. try:
  20. file_name = f"{str(Path(doc_path).stem)}_{time.time()}"
  21. pdf_data = read_fn(doc_path)
  22. parse_method = "auto"
  23. local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
  24. do_parse(
  25. output_dir,
  26. file_name,
  27. pdf_data,
  28. [],
  29. parse_method,
  30. False,
  31. end_page_id=end_page_id,
  32. )
  33. return local_md_dir, file_name
  34. except Exception as e:
  35. logger.exception(e)
  36. def compress_directory_to_zip(directory_path, output_zip_path):
  37. """
  38. 压缩指定目录到一个 ZIP 文件。
  39. :param directory_path: 要压缩的目录路径
  40. :param output_zip_path: 输出的 ZIP 文件路径
  41. """
  42. try:
  43. with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
  44. # 遍历目录中的所有文件和子目录
  45. for root, dirs, files in os.walk(directory_path):
  46. for file in files:
  47. # 构建完整的文件路径
  48. file_path = os.path.join(root, file)
  49. # 计算相对路径
  50. arcname = os.path.relpath(file_path, directory_path)
  51. # 添加文件到 ZIP 文件
  52. zipf.write(file_path, arcname)
  53. return 0
  54. except Exception as e:
  55. logger.exception(e)
  56. return -1
  57. def image_to_base64(image_path):
  58. with open(image_path, "rb") as image_file:
  59. return base64.b64encode(image_file.read()).decode('utf-8')
  60. def replace_image_with_base64(markdown_text, image_dir_path):
  61. # 匹配Markdown中的图片标签
  62. pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
  63. # 替换图片链接
  64. def replace(match):
  65. relative_path = match.group(1)
  66. full_path = os.path.join(image_dir_path, relative_path)
  67. base64_image = image_to_base64(full_path)
  68. return f"![{relative_path}](data:image/jpeg;base64,{base64_image})"
  69. # 应用替换
  70. return re.sub(pattern, replace, markdown_text)
  71. def to_markdown(file_path, end_pages):
  72. # 获取识别的md文件以及压缩包文件路径
  73. local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1)
  74. archive_zip_path = os.path.join("./output", compute_sha256(local_md_dir) + ".zip")
  75. zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
  76. if zip_archive_success == 0:
  77. logger.info("压缩成功")
  78. else:
  79. logger.error("压缩失败")
  80. md_path = os.path.join(local_md_dir, file_name + ".md")
  81. with open(md_path, 'r', encoding='utf-8') as f:
  82. txt_content = f.read()
  83. md_content = replace_image_with_base64(txt_content, local_md_dir)
  84. # 返回转换后的PDF路径
  85. new_pdf_path = os.path.join(local_md_dir, file_name + "_layout.pdf")
  86. return md_content, txt_content, archive_zip_path, show_pdf(new_pdf_path)
  87. def show_pdf(file_path):
  88. with open(file_path, "rb") as f:
  89. base64_pdf = base64.b64encode(f.read()).decode('utf-8')
  90. pdf_display = f'<embed src="data:application/pdf;base64,{base64_pdf}" ' \
  91. f'width="100%" height="1000" type="application/pdf">'
  92. return pdf_display
  93. latex_delimiters = [{"left": "$$", "right": "$$", "display": True},
  94. {"left": '$', "right": '$', "display": False}]
  95. if __name__ == "__main__":
  96. with gr.Blocks() as demo:
  97. with gr.Row():
  98. with gr.Column(variant='panel', scale=5):
  99. file = gr.File(label="请上传pdf", file_types=[".pdf"])
  100. max_pages = gr.Slider(1, 10, 5, step=1, label="最大转换页数")
  101. with gr.Row() as bu_flow:
  102. change_bu = gr.Button("转换")
  103. clear_bu = gr.ClearButton([file, max_pages], value="清除")
  104. gr.Markdown(value="### PDF预览")
  105. pdf_show = gr.HTML(label="PDF预览")
  106. with gr.Column(variant='panel', scale=5):
  107. output_file = gr.File(label="Markdown识别结果文件", interactive=False)
  108. with gr.Tabs():
  109. with gr.Tab("Markdown渲染"):
  110. md = gr.Markdown(label="Markdown渲染", height=1100, show_copy_button=True,
  111. latex_delimiters=latex_delimiters, line_breaks=True)
  112. with gr.Tab("Markdown文本"):
  113. md_text = gr.TextArea(lines=55, show_copy_button=True)
  114. file.upload(fn=show_pdf, inputs=file, outputs=pdf_show)
  115. change_bu.click(fn=to_markdown, inputs=[file, max_pages], outputs=[md, md_text, output_file, pdf_show])
  116. clear_bu.add([md, pdf_show, md_text, output_file])
  117. demo.launch()