gradio_app.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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"]:
  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. @click.option(
  188. '--max-convert-pages',
  189. 'max_convert_pages',
  190. type=int,
  191. help="Set the maximum number of pages to convert from PDF to Markdown.",
  192. default=1000,
  193. )
  194. @click.option(
  195. '--server-name',
  196. 'server_name',
  197. type=str,
  198. help="Set the server name for the Gradio app.",
  199. default=None,
  200. )
  201. @click.option(
  202. '--server-port',
  203. 'server_port',
  204. type=int,
  205. help="Set the server port for the Gradio app.",
  206. default=None,
  207. )
  208. def main(
  209. example_enable, sglang_engine_enable, mem_fraction_static, torch_compile_enable, api_enable, max_convert_pages,
  210. server_name, server_port
  211. ):
  212. if sglang_engine_enable:
  213. try:
  214. print("Start init SgLang engine...")
  215. from mineru.backend.vlm.vlm_analyze import ModelSingleton
  216. model_singleton = ModelSingleton()
  217. model_params = {
  218. "enable_torch_compile": torch_compile_enable
  219. }
  220. # 只有当mem_fraction_static不为None时才添加该参数
  221. if mem_fraction_static is not None:
  222. model_params["mem_fraction_static"] = mem_fraction_static
  223. predictor = model_singleton.get_model(
  224. "sglang-engine",
  225. None,
  226. None,
  227. **model_params
  228. )
  229. print("SgLang engine init successfully.")
  230. except Exception as e:
  231. logger.exception(e)
  232. suffixes = pdf_suffixes + image_suffixes
  233. with gr.Blocks() as demo:
  234. gr.HTML(header)
  235. with gr.Row():
  236. with gr.Column(variant='panel', scale=5):
  237. with gr.Row():
  238. input_file = gr.File(label='Please upload a PDF or image', file_types=suffixes)
  239. with gr.Row():
  240. max_pages = gr.Slider(1, max_convert_pages, int(max_convert_pages/2), step=1, label='Max convert pages')
  241. with gr.Row():
  242. if sglang_engine_enable:
  243. drop_list = ["pipeline", "vlm-sglang-engine"]
  244. preferred_option = "vlm-sglang-engine"
  245. else:
  246. drop_list = ["pipeline", "vlm-transformers", "vlm-sglang-client"]
  247. preferred_option = "pipeline"
  248. backend = gr.Dropdown(drop_list, label="Backend", value=preferred_option)
  249. with gr.Row(visible=False) as client_options:
  250. url = gr.Textbox(label='Server URL', value='http://localhost:30000', placeholder='http://localhost:30000')
  251. with gr.Row(equal_height=True):
  252. with gr.Column():
  253. gr.Markdown("**Recognition Options:**")
  254. formula_enable = gr.Checkbox(label='Enable formula recognition', value=True)
  255. table_enable = gr.Checkbox(label='Enable table recognition', value=True)
  256. with gr.Column(visible=False) as ocr_options:
  257. language = gr.Dropdown(all_lang, label='Language', value='ch')
  258. is_ocr = gr.Checkbox(label='Force enable OCR', value=False)
  259. with gr.Row():
  260. change_bu = gr.Button('Convert')
  261. clear_bu = gr.ClearButton(value='Clear')
  262. pdf_show = PDF(label='PDF preview', interactive=False, visible=True, height=800)
  263. if example_enable:
  264. example_root = os.path.join(os.getcwd(), 'examples')
  265. if os.path.exists(example_root):
  266. with gr.Accordion('Examples:'):
  267. gr.Examples(
  268. examples=[os.path.join(example_root, _) for _ in os.listdir(example_root) if
  269. _.endswith(tuple(suffixes))],
  270. inputs=input_file
  271. )
  272. with gr.Column(variant='panel', scale=5):
  273. output_file = gr.File(label='convert result', interactive=False)
  274. with gr.Tabs():
  275. with gr.Tab('Markdown rendering'):
  276. md = gr.Markdown(label='Markdown rendering', height=1100, show_copy_button=True,
  277. latex_delimiters=latex_delimiters,
  278. line_breaks=True)
  279. with gr.Tab('Markdown text'):
  280. md_text = gr.TextArea(lines=45, show_copy_button=True)
  281. # 添加事件处理
  282. backend.change(
  283. fn=update_interface,
  284. inputs=[backend],
  285. outputs=[client_options, ocr_options],
  286. api_name=False
  287. )
  288. # 添加demo.load事件,在页面加载时触发一次界面更新
  289. demo.load(
  290. fn=update_interface,
  291. inputs=[backend],
  292. outputs=[client_options, ocr_options],
  293. api_name=False
  294. )
  295. clear_bu.add([input_file, md, pdf_show, md_text, output_file, is_ocr])
  296. if api_enable:
  297. api_name = None
  298. else:
  299. api_name = False
  300. input_file.change(fn=to_pdf, inputs=input_file, outputs=pdf_show, api_name=api_name)
  301. change_bu.click(
  302. fn=to_markdown,
  303. inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, language, backend, url],
  304. outputs=[md, md_text, output_file, pdf_show],
  305. api_name=api_name
  306. )
  307. demo.launch(server_name=server_name, server_port=server_port, show_api=api_enable)
  308. if __name__ == '__main__':
  309. main()