gradio_app.py 13 KB

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