gradio_app.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 click
  9. import gradio as gr
  10. from gradio_pdf import PDF
  11. from loguru import logger
  12. from mineru.cli.common import prepare_env, read_fn, aio_do_parse, pdf_suffixes, image_suffixes
  13. from mineru.utils.hash_utils import str_sha256
  14. async def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, formula_enable, table_enable, language, backend, url):
  15. os.makedirs(output_dir, exist_ok=True)
  16. try:
  17. file_name = f'{safe_stem(Path(doc_path).stem)}_{time.strftime("%y%m%d_%H%M%S")}'
  18. pdf_data = read_fn(doc_path)
  19. if is_ocr:
  20. parse_method = 'ocr'
  21. else:
  22. parse_method = 'auto'
  23. if backend.startswith("vlm"):
  24. parse_method = "vlm"
  25. local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
  26. await aio_do_parse(
  27. output_dir=output_dir,
  28. pdf_file_names=[file_name],
  29. pdf_bytes_list=[pdf_data],
  30. p_lang_list=[language],
  31. parse_method=parse_method,
  32. end_page_id=end_page_id,
  33. formula_enable=formula_enable,
  34. table_enable=table_enable,
  35. backend=backend,
  36. server_url=url,
  37. )
  38. return local_md_dir, file_name
  39. except Exception as e:
  40. logger.exception(e)
  41. return None
  42. def compress_directory_to_zip(directory_path, output_zip_path):
  43. """压缩指定目录到一个 ZIP 文件。
  44. :param directory_path: 要压缩的目录路径
  45. :param output_zip_path: 输出的 ZIP 文件路径
  46. """
  47. try:
  48. with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
  49. # 遍历目录中的所有文件和子目录
  50. for root, dirs, files in os.walk(directory_path):
  51. for file in files:
  52. # 构建完整的文件路径
  53. file_path = os.path.join(root, file)
  54. # 计算相对路径
  55. arcname = os.path.relpath(file_path, directory_path)
  56. # 添加文件到 ZIP 文件
  57. zipf.write(file_path, arcname)
  58. return 0
  59. except Exception as e:
  60. logger.exception(e)
  61. return -1
  62. def image_to_base64(image_path):
  63. with open(image_path, 'rb') as image_file:
  64. return base64.b64encode(image_file.read()).decode('utf-8')
  65. def replace_image_with_base64(markdown_text, image_dir_path):
  66. # 匹配Markdown中的图片标签
  67. pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
  68. # 替换图片链接
  69. def replace(match):
  70. relative_path = match.group(1)
  71. full_path = os.path.join(image_dir_path, relative_path)
  72. base64_image = image_to_base64(full_path)
  73. return f'![{relative_path}](data:image/jpeg;base64,{base64_image})'
  74. # 应用替换
  75. return re.sub(pattern, replace, markdown_text)
  76. async def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=True, table_enable=True, language="ch", backend="pipeline", url=None):
  77. file_path = to_pdf(file_path)
  78. # 获取识别的md文件以及压缩包文件路径
  79. local_md_dir, file_name = await parse_pdf(file_path, './output', end_pages - 1, is_ocr, formula_enable, table_enable, language, backend, url)
  80. archive_zip_path = os.path.join('./output', str_sha256(local_md_dir) + '.zip')
  81. zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
  82. if zip_archive_success == 0:
  83. logger.info('Compression successful')
  84. else:
  85. logger.error('Compression failed')
  86. md_path = os.path.join(local_md_dir, file_name + '.md')
  87. with open(md_path, 'r', encoding='utf-8') as f:
  88. txt_content = f.read()
  89. md_content = replace_image_with_base64(txt_content, local_md_dir)
  90. # 返回转换后的PDF路径
  91. new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')
  92. return md_content, txt_content, archive_zip_path, new_pdf_path
  93. latex_delimiters = [
  94. {'left': '$$', 'right': '$$', 'display': True},
  95. {'left': '$', 'right': '$', 'display': False},
  96. {'left': '\\(', 'right': '\\)', 'display': False},
  97. {'left': '\\[', 'right': '\\]', 'display': True},
  98. ]
  99. header_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'resources', 'header.html')
  100. with open(header_path, 'r') as header_file:
  101. header = header_file.read()
  102. latin_lang = [
  103. 'af', 'az', 'bs', 'cs', 'cy', 'da', 'de', 'es', 'et', 'fr', 'ga', 'hr', # noqa: E126
  104. 'hu', 'id', 'is', 'it', 'ku', 'la', 'lt', 'lv', 'mi', 'ms', 'mt', 'nl',
  105. 'no', 'oc', 'pi', 'pl', 'pt', 'ro', 'rs_latin', 'sk', 'sl', 'sq', 'sv',
  106. 'sw', 'tl', 'tr', 'uz', 'vi', 'french', 'german'
  107. ]
  108. arabic_lang = ['ar', 'fa', 'ug', 'ur']
  109. cyrillic_lang = [
  110. 'rs_cyrillic', 'bg', 'mn', 'abq', 'ady', 'kbd', 'ava', # noqa: E126
  111. 'dar', 'inh', 'che', 'lbe', 'lez', 'tab'
  112. ]
  113. east_slavic_lang = ["ru", "be", "uk"]
  114. devanagari_lang = [
  115. 'hi', 'mr', 'ne', 'bh', 'mai', 'ang', 'bho', 'mah', 'sck', 'new', 'gom', # noqa: E126
  116. 'sa', 'bgc'
  117. ]
  118. other_lang = ['ch', 'ch_lite', 'ch_server', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka']
  119. add_lang = ['latin', 'arabic', 'east_slavic', 'cyrillic', 'devanagari']
  120. # all_lang = ['', 'auto']
  121. all_lang = []
  122. # all_lang.extend([*other_lang, *latin_lang, *arabic_lang, *cyrillic_lang, *devanagari_lang])
  123. all_lang.extend([*other_lang, *add_lang])
  124. def safe_stem(file_path):
  125. stem = Path(file_path).stem
  126. # 只保留字母、数字、下划线和点,其他字符替换为下划线
  127. return re.sub(r'[^\w.]', '_', stem)
  128. def to_pdf(file_path):
  129. if file_path is None:
  130. return None
  131. pdf_bytes = read_fn(file_path)
  132. # unique_filename = f'{uuid.uuid4()}.pdf'
  133. unique_filename = f'{safe_stem(file_path)}.pdf'
  134. # 构建完整的文件路径
  135. tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)
  136. # 将字节数据写入文件
  137. with open(tmp_file_path, 'wb') as tmp_pdf_file:
  138. tmp_pdf_file.write(pdf_bytes)
  139. return tmp_file_path
  140. # 更新界面函数
  141. def update_interface(backend_choice):
  142. if backend_choice in ["vlm-transformers", "vlm-sglang-engine"]:
  143. return gr.update(visible=False), gr.update(visible=False)
  144. elif backend_choice in ["vlm-sglang-client"]: # pipeline
  145. return gr.update(visible=True), gr.update(visible=False)
  146. elif backend_choice in ["pipeline"]:
  147. return gr.update(visible=False), gr.update(visible=True)
  148. else:
  149. pass
  150. @click.command()
  151. @click.option(
  152. '--enable-example',
  153. 'example_enable',
  154. type=bool,
  155. help="Enable example files for input."
  156. "The example files to be input need to be placed in the `example` folder within the directory where the command is currently executed.",
  157. default=True,
  158. )
  159. @click.option(
  160. '--enable-sglang-engine',
  161. 'sglang_engine_enable',
  162. type=bool,
  163. help="Enable SgLang engine backend for faster processing.",
  164. default=False,
  165. )
  166. @click.option(
  167. '--mem-fraction-static',
  168. 'mem_fraction_static',
  169. type=float,
  170. help="Set the static memory fraction for SgLang engine. ",
  171. default=None,
  172. )
  173. @click.option(
  174. '--enable-torch-compile',
  175. 'torch_compile_enable',
  176. type=bool,
  177. help="Enable torch compile for SgLang engine. ",
  178. default=False,
  179. )
  180. @click.option(
  181. '--enable-api',
  182. 'api_enable',
  183. type=bool,
  184. help="Enable gradio API for serving the application.",
  185. default=True,
  186. )
  187. def main(example_enable, sglang_engine_enable, mem_fraction_static, torch_compile_enable, api_enable):
  188. if sglang_engine_enable:
  189. try:
  190. print("Start init SgLang engine...")
  191. from mineru.backend.vlm.vlm_analyze import ModelSingleton
  192. modelsingleton = ModelSingleton()
  193. model_params = {
  194. "enable_torch_compile": torch_compile_enable
  195. }
  196. # 只有当mem_fraction_static不为None时才添加该参数
  197. if mem_fraction_static is not None:
  198. model_params["mem_fraction_static"] = mem_fraction_static
  199. predictor = modelsingleton.get_model(
  200. "sglang-engine",
  201. None,
  202. None,
  203. **model_params
  204. )
  205. print("SgLang engine init successfully.")
  206. except Exception as e:
  207. logger.exception(e)
  208. suffixes = pdf_suffixes + image_suffixes
  209. with gr.Blocks() as demo:
  210. gr.HTML(header)
  211. with gr.Row():
  212. with gr.Column(variant='panel', scale=5):
  213. with gr.Row():
  214. input_file = gr.File(label='Please upload a PDF or image', file_types=suffixes)
  215. with gr.Row():
  216. max_pages = gr.Slider(1, 20, 10, step=1, label='Max convert pages')
  217. with gr.Row():
  218. if sglang_engine_enable:
  219. drop_list = ["pipeline", "vlm-sglang-engine"]
  220. preferred_option = "vlm-sglang-engine"
  221. else:
  222. drop_list = ["pipeline", "vlm-transformers", "vlm-sglang-client"]
  223. preferred_option = "pipeline"
  224. backend = gr.Dropdown(drop_list, label="Backend", value=preferred_option)
  225. # with gr.Row(visible=False) as lang_options:
  226. with gr.Row(visible=False) as client_options:
  227. url = gr.Textbox(label='Server URL', value='http://localhost:30000', placeholder='http://localhost:30000')
  228. with gr.Row(equal_height=True):
  229. with gr.Column():
  230. gr.Markdown("**Recognition Options:**")
  231. formula_enable = gr.Checkbox(label='Enable formula recognition', value=True)
  232. table_enable = gr.Checkbox(label='Enable table recognition', value=True)
  233. with gr.Column(visible=False) as ocr_options:
  234. language = gr.Dropdown(all_lang, label='Language', value='ch')
  235. is_ocr = gr.Checkbox(label='Force enable OCR', value=False)
  236. with gr.Row():
  237. change_bu = gr.Button('Convert')
  238. clear_bu = gr.ClearButton(value='Clear')
  239. pdf_show = PDF(label='PDF preview', interactive=False, visible=True, height=800)
  240. if example_enable:
  241. example_root = os.path.join(os.getcwd(), 'examples')
  242. if os.path.exists(example_root):
  243. with gr.Accordion('Examples:'):
  244. gr.Examples(
  245. examples=[os.path.join(example_root, _) for _ in os.listdir(example_root) if
  246. _.endswith(tuple(suffixes))],
  247. inputs=input_file
  248. )
  249. with gr.Column(variant='panel', scale=5):
  250. output_file = gr.File(label='convert result', interactive=False)
  251. with gr.Tabs():
  252. with gr.Tab('Markdown rendering'):
  253. md = gr.Markdown(label='Markdown rendering', height=1100, show_copy_button=True,
  254. latex_delimiters=latex_delimiters,
  255. line_breaks=True)
  256. with gr.Tab('Markdown text'):
  257. md_text = gr.TextArea(lines=45, show_copy_button=True)
  258. # 添加事件处理
  259. backend.change(
  260. fn=update_interface,
  261. inputs=[backend],
  262. outputs=[client_options, ocr_options],
  263. api_name=False
  264. )
  265. # 添加demo.load事件,在页面加载时触发一次界面更新
  266. demo.load(
  267. fn=update_interface,
  268. inputs=[backend],
  269. outputs=[client_options, ocr_options],
  270. api_name=False
  271. )
  272. clear_bu.add([input_file, md, pdf_show, md_text, output_file, is_ocr])
  273. if api_enable:
  274. api_name = None
  275. else:
  276. api_name = False
  277. input_file.change(fn=to_pdf, inputs=input_file, outputs=pdf_show, api_name=api_name)
  278. change_bu.click(
  279. fn=to_markdown,
  280. inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, language, backend, url],
  281. outputs=[md, md_text, output_file, pdf_show],
  282. api_name=api_name
  283. )
  284. demo.launch()
  285. if __name__ == '__main__':
  286. main()