app.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import base64
  3. import os
  4. import re
  5. import time
  6. import uuid
  7. import zipfile
  8. from pathlib import Path
  9. import gradio as gr
  10. from gradio_pdf import PDF
  11. from loguru import logger
  12. from mineru.cli.common import prepare_env, do_parse
  13. from mineru.data.data_reader_writer import FileBasedDataReader
  14. from mineru.utils.hash_utils import str_sha256
  15. def read_fn(path):
  16. disk_rw = FileBasedDataReader(os.path.dirname(path))
  17. return disk_rw.read(os.path.basename(path))
  18. def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, formula_enable, table_enable, language):
  19. os.makedirs(output_dir, exist_ok=True)
  20. try:
  21. file_name = f'{str(Path(doc_path).stem)}_{time.time()}'
  22. pdf_data = read_fn(doc_path)
  23. if is_ocr:
  24. parse_method = 'ocr'
  25. else:
  26. parse_method = 'auto'
  27. local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
  28. do_parse(
  29. output_dir=output_dir,
  30. pdf_file_names=[file_name],
  31. pdf_bytes_list=[pdf_data],
  32. p_lang_list=[language],
  33. parse_method=parse_method,
  34. end_page_id=end_page_id,
  35. p_formula_enable=formula_enable,
  36. p_table_enable=table_enable,
  37. )
  38. return local_md_dir, file_name
  39. except Exception as e:
  40. logger.exception(e)
  41. def compress_directory_to_zip(directory_path, output_zip_path):
  42. """压缩指定目录到一个 ZIP 文件。
  43. :param directory_path: 要压缩的目录路径
  44. :param output_zip_path: 输出的 ZIP 文件路径
  45. """
  46. try:
  47. with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
  48. # 遍历目录中的所有文件和子目录
  49. for root, dirs, files in os.walk(directory_path):
  50. for file in files:
  51. # 构建完整的文件路径
  52. file_path = os.path.join(root, file)
  53. # 计算相对路径
  54. arcname = os.path.relpath(file_path, directory_path)
  55. # 添加文件到 ZIP 文件
  56. zipf.write(file_path, arcname)
  57. return 0
  58. except Exception as e:
  59. logger.exception(e)
  60. return -1
  61. def image_to_base64(image_path):
  62. with open(image_path, 'rb') as image_file:
  63. return base64.b64encode(image_file.read()).decode('utf-8')
  64. def replace_image_with_base64(markdown_text, image_dir_path):
  65. # 匹配Markdown中的图片标签
  66. pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
  67. # 替换图片链接
  68. def replace(match):
  69. relative_path = match.group(1)
  70. full_path = os.path.join(image_dir_path, relative_path)
  71. base64_image = image_to_base64(full_path)
  72. return f'![{relative_path}](data:image/jpeg;base64,{base64_image})'
  73. # 应用替换
  74. return re.sub(pattern, replace, markdown_text)
  75. def to_markdown(file_path, end_pages, is_ocr, formula_enable, table_enable, language):
  76. file_path = to_pdf(file_path)
  77. # 获取识别的md文件以及压缩包文件路径
  78. local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1, is_ocr, formula_enable, table_enable, language)
  79. archive_zip_path = os.path.join('./output', str_sha256(local_md_dir) + '.zip')
  80. zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
  81. if zip_archive_success == 0:
  82. logger.info('压缩成功')
  83. else:
  84. logger.error('压缩失败')
  85. md_path = os.path.join(local_md_dir, file_name + '.md')
  86. with open(md_path, 'r', encoding='utf-8') as f:
  87. txt_content = f.read()
  88. md_content = replace_image_with_base64(txt_content, local_md_dir)
  89. # 返回转换后的PDF路径
  90. new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')
  91. return md_content, txt_content, archive_zip_path, new_pdf_path
  92. latex_delimiters = [
  93. {'left': '$$', 'right': '$$', 'display': True},
  94. {'left': '$', 'right': '$', 'display': False},
  95. {'left': '\\(', 'right': '\\)', 'display': False},
  96. {'left': '\\[', 'right': '\\]', 'display': True},
  97. ]
  98. def init_model():
  99. try:
  100. pass
  101. return 0
  102. except Exception as e:
  103. logger.exception(e)
  104. return -1
  105. model_init = init_model()
  106. logger.info(f'model_init: {model_init}')
  107. with open('header.html', 'r') as file:
  108. header = file.read()
  109. latin_lang = [
  110. 'af', 'az', 'bs', 'cs', 'cy', 'da', 'de', 'es', 'et', 'fr', 'ga', 'hr', # noqa: E126
  111. 'hu', 'id', 'is', 'it', 'ku', 'la', 'lt', 'lv', 'mi', 'ms', 'mt', 'nl',
  112. 'no', 'oc', 'pi', 'pl', 'pt', 'ro', 'rs_latin', 'sk', 'sl', 'sq', 'sv',
  113. 'sw', 'tl', 'tr', 'uz', 'vi', 'french', 'german'
  114. ]
  115. arabic_lang = ['ar', 'fa', 'ug', 'ur']
  116. cyrillic_lang = [
  117. 'ru', 'rs_cyrillic', 'be', 'bg', 'uk', 'mn', 'abq', 'ady', 'kbd', 'ava', # noqa: E126
  118. 'dar', 'inh', 'che', 'lbe', 'lez', 'tab'
  119. ]
  120. devanagari_lang = [
  121. 'hi', 'mr', 'ne', 'bh', 'mai', 'ang', 'bho', 'mah', 'sck', 'new', 'gom', # noqa: E126
  122. 'sa', 'bgc'
  123. ]
  124. other_lang = ['ch', 'ch_lite', 'ch_server', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka']
  125. add_lang = ['latin', 'arabic', 'cyrillic', 'devanagari']
  126. # all_lang = ['', 'auto']
  127. all_lang = []
  128. # all_lang.extend([*other_lang, *latin_lang, *arabic_lang, *cyrillic_lang, *devanagari_lang])
  129. all_lang.extend([*other_lang, *add_lang])
  130. def to_pdf(file_path):
  131. pdf_bytes = read_fn(file_path)
  132. # 将pdfbytes 写入到uuid.pdf中
  133. # 生成唯一的文件名
  134. unique_filename = f'{uuid.uuid4()}.pdf'
  135. # 构建完整的文件路径
  136. tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)
  137. # 将字节数据写入文件
  138. with open(tmp_file_path, 'wb') as tmp_pdf_file:
  139. tmp_pdf_file.write(pdf_bytes)
  140. return tmp_file_path
  141. if __name__ == '__main__':
  142. with gr.Blocks() as demo:
  143. gr.HTML(header)
  144. with gr.Row():
  145. with gr.Column(variant='panel', scale=5):
  146. file = gr.File(label='Please upload a PDF or image', file_types=['.pdf', '.png', '.jpeg', '.jpg'])
  147. max_pages = gr.Slider(1, 20, 10, step=1, label='Max convert pages')
  148. with gr.Row():
  149. with gr.Column():
  150. is_ocr = gr.Checkbox(label='Force enable OCR', value=False)
  151. with gr.Column():
  152. language = gr.Dropdown(all_lang, label='Language', value='ch')
  153. with gr.Row():
  154. formula_enable = gr.Checkbox(label='Enable formula recognition', value=True)
  155. table_enable = gr.Checkbox(label='Enable table recognition(test)', value=True)
  156. with gr.Row():
  157. change_bu = gr.Button('Convert')
  158. clear_bu = gr.ClearButton(value='Clear')
  159. pdf_show = PDF(label='PDF preview', interactive=False, visible=True, height=800)
  160. with gr.Accordion('Examples:'):
  161. example_root = os.path.join(os.path.dirname(__file__), 'examples')
  162. gr.Examples(
  163. examples=[os.path.join(example_root, _) for _ in os.listdir(example_root) if
  164. _.endswith('pdf')],
  165. inputs=file
  166. )
  167. with gr.Column(variant='panel', scale=5):
  168. output_file = gr.File(label='convert result', interactive=False)
  169. with gr.Tabs():
  170. with gr.Tab('Markdown rendering'):
  171. md = gr.Markdown(label='Markdown rendering', height=1100, show_copy_button=True,
  172. latex_delimiters=latex_delimiters,
  173. line_breaks=True)
  174. with gr.Tab('Markdown text'):
  175. md_text = gr.TextArea(lines=45, show_copy_button=True)
  176. file.change(fn=to_pdf, inputs=file, outputs=pdf_show)
  177. change_bu.click(fn=to_markdown, inputs=[file, max_pages, is_ocr, formula_enable, table_enable, language],
  178. outputs=[md, md_text, output_file, pdf_show])
  179. clear_bu.add([file, md, pdf_show, md_text, output_file, is_ocr])
  180. demo.launch(server_name='0.0.0.0')