fast_api.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import uuid
  2. import os
  3. import re
  4. import tempfile
  5. import asyncio
  6. import uvicorn
  7. import click
  8. import zipfile
  9. from pathlib import Path
  10. import glob
  11. from fastapi import FastAPI, UploadFile, File, Form
  12. from fastapi.middleware.gzip import GZipMiddleware
  13. from fastapi.responses import JSONResponse, FileResponse
  14. from starlette.background import BackgroundTask
  15. from typing import List, Optional
  16. from loguru import logger
  17. from base64 import b64encode
  18. from mineru.cli.common import aio_do_parse, read_fn, pdf_suffixes, image_suffixes
  19. from mineru.utils.cli_parser import arg_parse
  20. from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
  21. from mineru.version import __version__
  22. app = FastAPI()
  23. app.add_middleware(GZipMiddleware, minimum_size=1000)
  24. def sanitize_filename(filename: str) -> str:
  25. """
  26. 格式化压缩文件的文件名
  27. 移除路径遍历字符, 保留 Unicode 字母、数字、._-
  28. 禁止隐藏文件
  29. """
  30. sanitized = re.sub(r'[/\\\.]{2,}|[/\\]', '', filename)
  31. sanitized = re.sub(r'[^\w.-]', '_', sanitized, flags=re.UNICODE)
  32. if sanitized.startswith('.'):
  33. sanitized = '_' + sanitized[1:]
  34. return sanitized or 'unnamed'
  35. def cleanup_file(file_path: str) -> None:
  36. """清理临时 zip 文件"""
  37. try:
  38. if os.path.exists(file_path):
  39. os.remove(file_path)
  40. except Exception as e:
  41. logger.warning(f"fail clean file {file_path}: {e}")
  42. def encode_image(image_path: str) -> str:
  43. """Encode image using base64"""
  44. with open(image_path, "rb") as f:
  45. return b64encode(f.read()).decode()
  46. def get_infer_result(file_suffix_identifier: str, pdf_name: str, parse_dir: str) -> Optional[str]:
  47. """从结果文件中读取推理结果"""
  48. result_file_path = os.path.join(parse_dir, f"{pdf_name}{file_suffix_identifier}")
  49. if os.path.exists(result_file_path):
  50. with open(result_file_path, "r", encoding="utf-8") as fp:
  51. return fp.read()
  52. return None
  53. @app.post(path="/file_parse",)
  54. async def parse_pdf(
  55. files: List[UploadFile] = File(...),
  56. output_dir: str = Form("./output"),
  57. lang_list: List[str] = Form(["ch"]),
  58. backend: str = Form("pipeline"),
  59. parse_method: str = Form("auto"),
  60. formula_enable: bool = Form(True),
  61. table_enable: bool = Form(True),
  62. server_url: Optional[str] = Form(None),
  63. return_md: bool = Form(True),
  64. return_middle_json: bool = Form(False),
  65. return_model_output: bool = Form(False),
  66. return_content_list: bool = Form(False),
  67. return_images: bool = Form(False),
  68. response_format_zip: bool = Form(False),
  69. start_page_id: int = Form(0),
  70. end_page_id: int = Form(99999),
  71. ):
  72. # 获取命令行配置参数
  73. config = getattr(app.state, "config", {})
  74. try:
  75. # 创建唯一的输出目录
  76. unique_dir = os.path.join(output_dir, str(uuid.uuid4()))
  77. os.makedirs(unique_dir, exist_ok=True)
  78. # 处理上传的PDF文件
  79. pdf_file_names = []
  80. pdf_bytes_list = []
  81. for file in files:
  82. content = await file.read()
  83. file_path = Path(file.filename)
  84. # 创建临时文件
  85. temp_path = Path(unique_dir) / file_path.name
  86. with open(temp_path, "wb") as f:
  87. f.write(content)
  88. # 如果是图像文件或PDF,使用read_fn处理
  89. file_suffix = guess_suffix_by_path(temp_path)
  90. if file_suffix in pdf_suffixes + image_suffixes:
  91. try:
  92. pdf_bytes = read_fn(temp_path)
  93. pdf_bytes_list.append(pdf_bytes)
  94. pdf_file_names.append(file_path.stem)
  95. os.remove(temp_path) # 删除临时文件
  96. except Exception as e:
  97. return JSONResponse(
  98. status_code=400,
  99. content={"error": f"Failed to load file: {str(e)}"}
  100. )
  101. else:
  102. return JSONResponse(
  103. status_code=400,
  104. content={"error": f"Unsupported file type: {file_suffix}"}
  105. )
  106. # 设置语言列表,确保与文件数量一致
  107. actual_lang_list = lang_list
  108. if len(actual_lang_list) != len(pdf_file_names):
  109. # 如果语言列表长度不匹配,使用第一个语言或默认"ch"
  110. actual_lang_list = [actual_lang_list[0] if actual_lang_list else "ch"] * len(pdf_file_names)
  111. # 调用异步处理函数
  112. await aio_do_parse(
  113. output_dir=unique_dir,
  114. pdf_file_names=pdf_file_names,
  115. pdf_bytes_list=pdf_bytes_list,
  116. p_lang_list=actual_lang_list,
  117. backend=backend,
  118. parse_method=parse_method,
  119. formula_enable=formula_enable,
  120. table_enable=table_enable,
  121. server_url=server_url,
  122. f_draw_layout_bbox=False,
  123. f_draw_span_bbox=False,
  124. f_dump_md=return_md,
  125. f_dump_middle_json=return_middle_json,
  126. f_dump_model_output=return_model_output,
  127. f_dump_orig_pdf=False,
  128. f_dump_content_list=return_content_list,
  129. start_page_id=start_page_id,
  130. end_page_id=end_page_id,
  131. **config
  132. )
  133. # 根据 response_format_zip 决定返回类型
  134. if response_format_zip:
  135. zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_results_")
  136. os.close(zip_fd)
  137. with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
  138. for pdf_name in pdf_file_names:
  139. safe_pdf_name = sanitize_filename(pdf_name)
  140. if backend.startswith("pipeline"):
  141. parse_dir = os.path.join(unique_dir, pdf_name, parse_method)
  142. else:
  143. parse_dir = os.path.join(unique_dir, pdf_name, "vlm")
  144. if not os.path.exists(parse_dir):
  145. continue
  146. # 写入文本类结果
  147. if return_md:
  148. path = os.path.join(parse_dir, f"{pdf_name}.md")
  149. if os.path.exists(path):
  150. zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}.md"))
  151. if return_middle_json:
  152. path = os.path.join(parse_dir, f"{pdf_name}_middle.json")
  153. if os.path.exists(path):
  154. zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}_middle.json"))
  155. if return_model_output:
  156. path = os.path.join(parse_dir, f"{pdf_name}_model.json")
  157. if os.path.exists(path):
  158. zf.write(path, arcname=os.path.join(safe_pdf_name, os.path.basename(path)))
  159. if return_content_list:
  160. path = os.path.join(parse_dir, f"{pdf_name}_content_list.json")
  161. if os.path.exists(path):
  162. zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}_content_list.json"))
  163. # 写入图片
  164. if return_images:
  165. images_dir = os.path.join(parse_dir, "images")
  166. image_paths = glob.glob(os.path.join(glob.escape(images_dir), "*.jpg"))
  167. for image_path in image_paths:
  168. zf.write(image_path, arcname=os.path.join(safe_pdf_name, "images", os.path.basename(image_path)))
  169. return FileResponse(
  170. path=zip_path,
  171. media_type="application/zip",
  172. filename="results.zip",
  173. background=BackgroundTask(cleanup_file, zip_path)
  174. )
  175. else:
  176. # 构建 JSON 结果
  177. result_dict = {}
  178. for pdf_name in pdf_file_names:
  179. result_dict[pdf_name] = {}
  180. data = result_dict[pdf_name]
  181. if backend.startswith("pipeline"):
  182. parse_dir = os.path.join(unique_dir, pdf_name, parse_method)
  183. else:
  184. parse_dir = os.path.join(unique_dir, pdf_name, "vlm")
  185. if os.path.exists(parse_dir):
  186. if return_md:
  187. data["md_content"] = get_infer_result(".md", pdf_name, parse_dir)
  188. if return_middle_json:
  189. data["middle_json"] = get_infer_result("_middle.json", pdf_name, parse_dir)
  190. if return_model_output:
  191. data["model_output"] = get_infer_result("_model.json", pdf_name, parse_dir)
  192. if return_content_list:
  193. data["content_list"] = get_infer_result("_content_list.json", pdf_name, parse_dir)
  194. if return_images:
  195. images_dir = os.path.join(parse_dir, "images")
  196. safe_pattern = os.path.join(glob.escape(images_dir), "*.jpg")
  197. image_paths = glob.glob(safe_pattern)
  198. data["images"] = {
  199. os.path.basename(
  200. image_path
  201. ): f"data:image/jpeg;base64,{encode_image(image_path)}"
  202. for image_path in image_paths
  203. }
  204. return JSONResponse(
  205. status_code=200,
  206. content={
  207. "backend": backend,
  208. "version": __version__,
  209. "results": result_dict
  210. }
  211. )
  212. except Exception as e:
  213. logger.exception(e)
  214. return JSONResponse(
  215. status_code=500,
  216. content={"error": f"Failed to process file: {str(e)}"}
  217. )
  218. @click.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
  219. @click.pass_context
  220. @click.option('--host', default='127.0.0.1', help='Server host (default: 127.0.0.1)')
  221. @click.option('--port', default=8000, type=int, help='Server port (default: 8000)')
  222. @click.option('--reload', is_flag=True, help='Enable auto-reload (development mode)')
  223. def main(ctx, host, port, reload, **kwargs):
  224. kwargs.update(arg_parse(ctx))
  225. # 将配置参数存储到应用状态中
  226. app.state.config = kwargs
  227. """启动MinerU FastAPI服务器的命令行入口"""
  228. print(f"Start MinerU FastAPI Service: http://{host}:{port}")
  229. print("The API documentation can be accessed at the following address:")
  230. print(f"- Swagger UI: http://{host}:{port}/docs")
  231. print(f"- ReDoc: http://{host}:{port}/redoc")
  232. uvicorn.run(
  233. "mineru.cli.fast_api:app",
  234. host=host,
  235. port=port,
  236. reload=reload
  237. )
  238. if __name__ == "__main__":
  239. main()