gradio_app.py 9.7 KB

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