From 26347a8157f9bd6de2ba21ce4f5752bc80461349 Mon Sep 17 00:00:00 2001 From: panyy Date: Fri, 6 Nov 2026 16:52:28 +0800 Subject: [PATCH] refactor(parser): restore pristine MinerU 2.7.1 and original GPU build recipes --- .dockerignore | 10 + .gitattributes | 1 + README.md | 18 +- README.mineru-upstream.md | 16 -- docker/china/Dockerfile | 75 +++++- docker/china/Dockerfile.corex | 75 +++++- docker/compose.yaml | 10 +- docker/entrypoint.mineru-api.sh | 7 + docker/global/Dockerfile | 77 +++++- docker/global/Dockerfile.cuda | 79 +++++- docs/mineru-migration/2.7.1-baseline.json | 197 +++++++++++++++ docs/mineru-migration/README.md | 2 +- .../release-baseline-20261106.md | 4 +- mineru/backend/hybrid/hybrid_magic_model.py | 3 +- mineru/backend/pipeline/model_init.py | 9 +- mineru/backend/pipeline/pipeline_analyze.py | 7 +- .../pipeline_middle_json_mkcontent.py | 6 +- mineru/backend/vlm/utils.py | 6 - mineru/backend/vlm/vlm_analyze.py | 70 ------ mineru/backend/vlm/vlm_magic_model.py | 3 +- .../backend/vlm/vlm_middle_json_mkcontent.py | 4 +- mineru/cli/fast_api.py | 238 ++++++------------ mineru/model/mfd/yolo_v8.py | 6 +- mineru/model/mfr/unimernet/Unimernet.py | 6 +- .../rec/unet_table/utils_table_line_rec.py | 8 +- mineru/model/vlm/vllm_server.py | 23 -- mineru/utils/block_sort.py | 16 -- mineru/utils/config_reader.py | 14 +- mineru/utils/llm_aided.py | 2 +- mineru/utils/magic_model_utils.py | 74 +----- mineru/utils/model_utils.py | 20 +- mineru/utils/table_merge.py | 238 +++--------------- mineru/version.py | 2 +- scripts/build-images.sh | 5 +- scripts/check_parser_baseline.py | 46 ++++ scripts/run_parser.py | 44 +++- tests/unittest/test_heading_levels.py | 18 +- tests/unittest/test_parser_baseline.py | 92 +++++++ tests/unittest/test_parser_protocol.py | 49 ++++ 39 files changed, 879 insertions(+), 701 deletions(-) create mode 100644 docs/mineru-migration/2.7.1-baseline.json create mode 100644 scripts/check_parser_baseline.py create mode 100644 tests/unittest/test_parser_baseline.py create mode 100644 tests/unittest/test_parser_protocol.py diff --git a/.dockerignore b/.dockerignore index e238c85..6162b2c 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,13 @@ web_ui/dist mineru/cli/static/web test_files tests +.venv +.venv-* +venv-* +*.egg-info +.env +.env.* +*.env +config +models +logs diff --git a/.gitattributes b/.gitattributes index 5d2d462..7af7fd0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,4 @@ *.css linguist-vendored *.scss linguist-vendored *.sh text eol=lf +mineru/** text eol=lf diff --git a/README.md b/README.md index 5191657..4dfb91a 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,15 @@ # Unis MinerU 解析服务 -本仓库维护官方 `mineru-2.7.4-released` 解析源码及部署配置;`mineru/` 与官方发布包一致。 +当前基线为官方 **MinerU 2.7.1**。`mineru/` 的全部 187 个文件与登记的官方 wheel 一致,没有项目内核定制;本轮暂不加入六级标题补丁,保持官方最多四级的标题输出。 -思维导图工作台、用户授权、模型整理、文件格式分流和版本适配已迁至 MaxKB。旧 web_ui 不再部署。官方说明见 [README.mineru-upstream.md](README.mineru-upstream.md),基线哈希见 [2.7.4-baseline.json](docs/mineru-migration/2.7.4-baseline.json)。旧业务实现可从 Git 提交 `8b50192` 回看。 +思维导图工作台、用户授权、模型整理、文件格式分流和版本适配已迁至 MaxKB。旧 web_ui 不再部署。官方说明见 [README.mineru-upstream.md](README.mineru-upstream.md),来源和逐文件哈希见 [2.7.1-baseline.json](docs/mineru-migration/2.7.1-baseline.json)。旧业务实现可从 Git 提交 `8b50192` 回看。 ## 启动 在经过验证的独立虚拟环境安装本项目,准备原版 pipeline / VLM 模型及 mineru.json,设置 `MINERU_TOOLS_CONFIG_JSON` 和 `MINERU_MODEL_SOURCE=local`,运行: ```bash +python scripts/check_parser_baseline.py --runtime python scripts/run_parser.py --host 127.0.0.1 --port 8100 ``` @@ -18,6 +19,15 @@ python scripts/run_parser.py --host 127.0.0.1 --port 8100 ## 镜像 -CoreX 使用 `docker/china/Dockerfile.corex`;CUDA 使用 `docker/global/Dockerfile.cuda`。构建只安装当前源码,先固定厂商 Torch/torchvision/vLLM 版本,再解析其他依赖;冲突时停止构建。不得在厂商镜像中全量升级。 +CoreX 使用 `docker/china/Dockerfile.corex`;CUDA 使用 `docker/global/Dockerfile.cuda`。两者恢复 `develop` 中原厂商基础镜像和依赖安装顺序,保留原字体和系统库。必要差异是将旧 `mineru[core]>=2.7.4` 改为 `mineru[core]==2.7.1`,并在构建结束检查全部官方源码及安装版本。CoreX 继续使用原 `--no-deps` 安装方式及 CoreX 4.4.0 / Torch 2.7.1 / vLLM 0.11.2 / Python 3.10 基础镜像。 -`scripts/build-images.sh` 只构建解析镜像;`scripts/start-mindmap.sh` 为兼容旧命令保留,实际仅增量启动 parser,不删除容器或修改业务目录权限。具体国产卡组合仍需在目标硬件验证。 +`scripts/build-images.sh` 只构建解析镜像,不恢复已退役的 web_ui 构建。它保留 `unis-mindmap-api:版本`、`:corex`/`:cuda`、`:latest` 旧标签,并生成新版升级包需要的 `unis-mineru:版本-卡型` 标签和发布标记。构建时 `latest` 会更新,需保留原交付包/镜像 ID 以便回退。 + +```bash +API_FLAVOR=corex VERSION=refact-271-20261106-1 bash scripts/build-images.sh +# NVIDIA:API_FLAVOR=cuda +``` + +模型配置 entrypoint 保持原命令入口;`mineru-api` 命令转交 `scripts/run_parser.py`,在内核之外保留显存/并发参数兼容。包装器配置官方 ASGI app,并将 API 服务参数与引擎参数分开,避免把并发数等字段交给 vLLM 的 `AsyncEngineArgs`;不恢复内核参数过滤补丁。`scripts/start-mindmap.sh` 仅启动 parser,不删除容器、不递归修改业务目录权限;独立 Compose 的 NVIDIA 环境需配置 `MINERU_DOCKER_RUNTIME=nvidia`。 + +**回到 2.7.1 不等于 MR100 已通过验收。** 原依赖列表仍有浮动版本,基础镜像标签也不等于不可变镜像 ID;移除旧 AsyncEngineArgs 签名过滤补丁后,官方内核与厂商 vLLM 的组合仍需实卡验证。旧 CoreX 离线镜像继续保留为回退材料,见 [基线核查](docs/mineru-migration/release-baseline-20261106.md)。 diff --git a/README.mineru-upstream.md b/README.mineru-upstream.md index a434a16..0007004 100644 --- a/README.mineru-upstream.md +++ b/README.mineru-upstream.md @@ -45,22 +45,6 @@ # Changelog -- 2026/01/30 2.7.4 Release - - Added support for domestic computing platforms IluvatarCorex and Cambricon. Currently, the officially supported domestic computing platforms include: - - [Ascend](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/Ascend/) - - [T-Head](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/THead/) - - [METAX](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/METAX/) - - [Hygon](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/Hygon/) - - [Enflame](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/Enflame/) - - [MooreThreads](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/MooreThreads/) - - [IluvatarCorex](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/IluvatarCorex/) - - [Cambricon](https://opendatalab.github.io/MinerU/zh/usage/acceleration_cards/Cambricon/) - - MinerU continues to ensure compatibility with domestic hardware platforms, supporting mainstream chip architectures. With secure and reliable technology, we empower researchers, government, and enterprises to reach new heights in document digitization! - -- 2026/01/23 2.7.2 Release - - Added support for domestic computing platforms Hygon, Enflame, and Moore Threads. - - Cross-page table merging optimization, improving merge success rate and merge quality. - - 2026/01/06 2.7.1 Release - fix bug: #4300 - Updated pdfminer.six dependency version to resolve [CVE-2025-64512](https://github.com/advisories/GHSA-wf5f-4jwr-ppcp) diff --git a/docker/china/Dockerfile b/docker/china/Dockerfile index 12c1aac..592dbd0 100644 --- a/docker/china/Dockerfile +++ b/docker/china/Dockerfile @@ -1,14 +1,65 @@ FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10 -ENV MINERU_MODEL_SOURCE=local MINERU_MODEL_DIR=/models PYTHONPATH=/app -RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \ - && rm -rf /var/lib/apt/lists/* + +ENV DEBIAN_FRONTEND=noninteractive +ENV MINERU_MODEL_SOURCE=local +ENV MINERU_MODEL_DIR=/models +ENV MINERU_TOOLS_CONFIG_JSON=/root/mineru.json + +RUN apt-get update && apt-get install -y \ + fonts-noto-core \ + fonts-noto-cjk \ + fontconfig \ + libgl1-mesa-glx \ + && fc-cache -fv \ + && apt-get clean && rm -rf /var/lib/apt/lists/* + +RUN python3 -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \ + python3 -m pip install 'mineru[core]==2.7.1' --no-deps -i https://mirrors.aliyun.com/pypi/simple && \ + python3 -m pip install \ + "numpy==1.26.4" \ + "opencv-python==4.11.0.86" \ + "pydantic>=2.12,<3" \ + "modelscope" \ + "magic-pdf" \ + boto3 \ + "pdfminer.six>=20251230" \ + pypdfium2 \ + pypdf \ + reportlab \ + pdftext \ + huggingface-hub \ + json-repair \ + fast-langdetect \ + scikit-image \ + openai \ + beautifulsoup4 \ + magika \ + mineru-vl-utils \ + qwen-vl-utils \ + matplotlib \ + ultralytics \ + doclayout_yolo==0.0.4 \ + dill \ + PyYAML \ + ftfy \ + shapely \ + pyclipper \ + omegaconf \ + onnxruntime \ + python-pptx \ + python-docx \ + openpyxl \ + xlrd \ + xlwt \ + pylatexenc \ + mammoth \ + -i https://mirrors.aliyun.com/pypi/simple && \ + python3 -m pip cache purge + WORKDIR /app -COPY pyproject.toml README.mineru-upstream.md LICENSE.md ./ -COPY mineru ./mineru -COPY scripts/run_parser.py ./scripts/run_parser.py -# Pin vendor binaries before resolving Python dependencies. Conflicts fail the build rather than replacing vendor Torch. -RUN python3 -c "import importlib.metadata as m; from pathlib import Path; Path('/tmp/vendor-constraints.txt').write_text(chr(10).join(n+'=='+m.version(n) for n in ('torch','torchvision','vllm')))" \ - && python3 -m pip install --no-cache-dir -c /tmp/vendor-constraints.txt '.[vlm,pipeline,api]' -COPY docker/entrypoint.mineru-api.sh /entrypoint.sh -ENTRYPOINT ["bash", "/entrypoint.sh"] -CMD ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"] +COPY . . +COPY docker/entrypoint.mineru-api.sh /usr/local/bin/entrypoint.mineru-api.sh +RUN chmod +x /usr/local/bin/entrypoint.mineru-api.sh && python3 scripts/check_parser_baseline.py --runtime + +ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"] +CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"] diff --git a/docker/china/Dockerfile.corex b/docker/china/Dockerfile.corex index 12c1aac..592dbd0 100644 --- a/docker/china/Dockerfile.corex +++ b/docker/china/Dockerfile.corex @@ -1,14 +1,65 @@ FROM crpi-vofi3w62lkohhxsp.cn-shanghai.personal.cr.aliyuncs.com/opendatalab-mineru/corex:4.4.0_torch2.7.1_vllm0.11.2_py3.10 -ENV MINERU_MODEL_SOURCE=local MINERU_MODEL_DIR=/models PYTHONPATH=/app -RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \ - && rm -rf /var/lib/apt/lists/* + +ENV DEBIAN_FRONTEND=noninteractive +ENV MINERU_MODEL_SOURCE=local +ENV MINERU_MODEL_DIR=/models +ENV MINERU_TOOLS_CONFIG_JSON=/root/mineru.json + +RUN apt-get update && apt-get install -y \ + fonts-noto-core \ + fonts-noto-cjk \ + fontconfig \ + libgl1-mesa-glx \ + && fc-cache -fv \ + && apt-get clean && rm -rf /var/lib/apt/lists/* + +RUN python3 -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \ + python3 -m pip install 'mineru[core]==2.7.1' --no-deps -i https://mirrors.aliyun.com/pypi/simple && \ + python3 -m pip install \ + "numpy==1.26.4" \ + "opencv-python==4.11.0.86" \ + "pydantic>=2.12,<3" \ + "modelscope" \ + "magic-pdf" \ + boto3 \ + "pdfminer.six>=20251230" \ + pypdfium2 \ + pypdf \ + reportlab \ + pdftext \ + huggingface-hub \ + json-repair \ + fast-langdetect \ + scikit-image \ + openai \ + beautifulsoup4 \ + magika \ + mineru-vl-utils \ + qwen-vl-utils \ + matplotlib \ + ultralytics \ + doclayout_yolo==0.0.4 \ + dill \ + PyYAML \ + ftfy \ + shapely \ + pyclipper \ + omegaconf \ + onnxruntime \ + python-pptx \ + python-docx \ + openpyxl \ + xlrd \ + xlwt \ + pylatexenc \ + mammoth \ + -i https://mirrors.aliyun.com/pypi/simple && \ + python3 -m pip cache purge + WORKDIR /app -COPY pyproject.toml README.mineru-upstream.md LICENSE.md ./ -COPY mineru ./mineru -COPY scripts/run_parser.py ./scripts/run_parser.py -# Pin vendor binaries before resolving Python dependencies. Conflicts fail the build rather than replacing vendor Torch. -RUN python3 -c "import importlib.metadata as m; from pathlib import Path; Path('/tmp/vendor-constraints.txt').write_text(chr(10).join(n+'=='+m.version(n) for n in ('torch','torchvision','vllm')))" \ - && python3 -m pip install --no-cache-dir -c /tmp/vendor-constraints.txt '.[vlm,pipeline,api]' -COPY docker/entrypoint.mineru-api.sh /entrypoint.sh -ENTRYPOINT ["bash", "/entrypoint.sh"] -CMD ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"] +COPY . . +COPY docker/entrypoint.mineru-api.sh /usr/local/bin/entrypoint.mineru-api.sh +RUN chmod +x /usr/local/bin/entrypoint.mineru-api.sh && python3 scripts/check_parser_baseline.py --runtime + +ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"] +CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"] diff --git a/docker/compose.yaml b/docker/compose.yaml index 7360490..f1a8ba0 100644 --- a/docker/compose.yaml +++ b/docker/compose.yaml @@ -1,13 +1,21 @@ services: mineru-api: - image: unis-mineru:2.7.4 + image: unis-mineru:2.7.1 restart: unless-stopped + runtime: ${MINERU_DOCKER_RUNTIME:-runc} + privileged: true + ipc: host + shm_size: 32g ports: - "127.0.0.1:${MINERU_PORT:-8100}:8000" environment: MINERU_MODEL_SOURCE: local MINERU_MODEL_DIR: /models MINERU_GPU_MEMORY_UTILIZATION: ${MINERU_GPU_MEMORY_UTILIZATION:-0.5} + PYTHONPATH: /app:/usr/local/corex-4.4.0/lib64/python3/dist-packages + CUDA_VISIBLE_DEVICES: ${MINERU_CUDA_VISIBLE_DEVICES:-0} + NVIDIA_VISIBLE_DEVICES: ${MINERU_NVIDIA_VISIBLE_DEVICES:-all} + NVIDIA_DRIVER_CAPABILITIES: compute,utility volumes: - "${MINERU_MODEL_DIR:?Set MINERU_MODEL_DIR}:/models:ro" - mineru-output:/app/output diff --git a/docker/entrypoint.mineru-api.sh b/docker/entrypoint.mineru-api.sh index 34858a5..319d85e 100644 --- a/docker/entrypoint.mineru-api.sh +++ b/docker/entrypoint.mineru-api.sh @@ -46,4 +46,11 @@ export MINERU_TOOLS_CONFIG_JSON="$CONFIG_PATH" export MINERU_MODEL_SOURCE=${MINERU_MODEL_SOURCE:-local} export PYTHONPATH=${PYTHONPATH:-/app} +# Keep the historical Docker command while passing deployment-only settings +# through the wrapper instead of patching the official MinerU kernel. +if [ "${1:-}" = "mineru-api" ]; then + shift + set -- python3 /app/scripts/run_parser.py "$@" +fi + exec "$@" diff --git a/docker/global/Dockerfile b/docker/global/Dockerfile index 311cb53..d042b14 100644 --- a/docker/global/Dockerfile +++ b/docker/global/Dockerfile @@ -1,14 +1,67 @@ FROM pytorch/pytorch:2.7.1-cuda12.6-cudnn9-runtime -ENV MINERU_MODEL_SOURCE=local MINERU_MODEL_DIR=/models PYTHONPATH=/app -RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \ - && rm -rf /var/lib/apt/lists/* + +ENV DEBIAN_FRONTEND=noninteractive +ENV MINERU_MODEL_SOURCE=local +ENV MINERU_MODEL_DIR=/models +ENV MINERU_TOOLS_CONFIG_JSON=/root/mineru.json + +RUN apt-get update && apt-get install -y \ + fonts-noto-core \ + fonts-noto-cjk \ + fontconfig \ + libgl1 \ + libglib2.0-0 \ + git \ + && fc-cache -fv \ + && apt-get clean && rm -rf /var/lib/apt/lists/* + +RUN ln -sf "$(command -v python)" /usr/local/bin/python3 && \ + python -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \ + python -m pip install \ + 'mineru[core]==2.7.1' \ + 'vllm==0.11.2' \ + 'pydantic>=2.12,<3' \ + modelscope \ + magic-pdf \ + boto3 \ + 'pdfminer.six>=20251230' \ + pypdfium2 \ + pypdf \ + reportlab \ + pdftext \ + huggingface-hub \ + json-repair \ + fast-langdetect \ + scikit-image \ + openai \ + beautifulsoup4 \ + magika \ + mineru-vl-utils \ + qwen-vl-utils \ + matplotlib \ + ultralytics \ + doclayout_yolo==0.0.4 \ + dill \ + PyYAML \ + ftfy \ + shapely \ + pyclipper \ + omegaconf \ + onnxruntime-gpu \ + python-pptx \ + python-docx \ + openpyxl \ + xlrd \ + xlwt \ + pylatexenc \ + mammoth \ + -i https://mirrors.aliyun.com/pypi/simple && \ + python -m pip cache purge + WORKDIR /app -COPY pyproject.toml README.mineru-upstream.md LICENSE.md ./ -COPY mineru ./mineru -COPY scripts/run_parser.py ./scripts/run_parser.py -# Pin vendor binaries before resolving Python dependencies. Conflicts fail the build rather than replacing vendor Torch. -RUN python3 -c "import importlib.metadata as m; from pathlib import Path; Path('/tmp/vendor-constraints.txt').write_text(chr(10).join(n+'=='+m.version(n) for n in ('torch','torchvision')))" \ - && python3 -m pip install --no-cache-dir -c /tmp/vendor-constraints.txt '.[vlm,pipeline,api]' -COPY docker/entrypoint.mineru-api.sh /entrypoint.sh -ENTRYPOINT ["sh", "/entrypoint.sh"] -CMD ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"] +COPY . . +COPY docker/entrypoint.mineru-api.sh /usr/local/bin/entrypoint.mineru-api.sh +RUN chmod +x /usr/local/bin/entrypoint.mineru-api.sh && python3 scripts/check_parser_baseline.py --runtime + +ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"] +CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"] diff --git a/docker/global/Dockerfile.cuda b/docker/global/Dockerfile.cuda index 9ea5aaa..d042b14 100644 --- a/docker/global/Dockerfile.cuda +++ b/docker/global/Dockerfile.cuda @@ -1,14 +1,67 @@ -FROM vllm/vllm-openai:v0.11.2 -ENV MINERU_MODEL_SOURCE=local MINERU_MODEL_DIR=/models PYTHONPATH=/app -RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \ - && rm -rf /var/lib/apt/lists/* +FROM pytorch/pytorch:2.7.1-cuda12.6-cudnn9-runtime + +ENV DEBIAN_FRONTEND=noninteractive +ENV MINERU_MODEL_SOURCE=local +ENV MINERU_MODEL_DIR=/models +ENV MINERU_TOOLS_CONFIG_JSON=/root/mineru.json + +RUN apt-get update && apt-get install -y \ + fonts-noto-core \ + fonts-noto-cjk \ + fontconfig \ + libgl1 \ + libglib2.0-0 \ + git \ + && fc-cache -fv \ + && apt-get clean && rm -rf /var/lib/apt/lists/* + +RUN ln -sf "$(command -v python)" /usr/local/bin/python3 && \ + python -m pip install -U pip -i https://mirrors.aliyun.com/pypi/simple && \ + python -m pip install \ + 'mineru[core]==2.7.1' \ + 'vllm==0.11.2' \ + 'pydantic>=2.12,<3' \ + modelscope \ + magic-pdf \ + boto3 \ + 'pdfminer.six>=20251230' \ + pypdfium2 \ + pypdf \ + reportlab \ + pdftext \ + huggingface-hub \ + json-repair \ + fast-langdetect \ + scikit-image \ + openai \ + beautifulsoup4 \ + magika \ + mineru-vl-utils \ + qwen-vl-utils \ + matplotlib \ + ultralytics \ + doclayout_yolo==0.0.4 \ + dill \ + PyYAML \ + ftfy \ + shapely \ + pyclipper \ + omegaconf \ + onnxruntime-gpu \ + python-pptx \ + python-docx \ + openpyxl \ + xlrd \ + xlwt \ + pylatexenc \ + mammoth \ + -i https://mirrors.aliyun.com/pypi/simple && \ + python -m pip cache purge + WORKDIR /app -COPY pyproject.toml README.mineru-upstream.md LICENSE.md ./ -COPY mineru ./mineru -COPY scripts/run_parser.py ./scripts/run_parser.py -# Pin vendor binaries before resolving Python dependencies. Conflicts fail the build rather than replacing vendor Torch. -RUN python3 -c "import importlib.metadata as m; from pathlib import Path; Path('/tmp/vendor-constraints.txt').write_text(chr(10).join(n+'=='+m.version(n) for n in ('torch','torchvision','vllm')))" \ - && python3 -m pip install --no-cache-dir -c /tmp/vendor-constraints.txt '.[vlm,pipeline,api]' -COPY docker/entrypoint.mineru-api.sh /entrypoint.sh -ENTRYPOINT ["bash", "/entrypoint.sh"] -CMD ["python3", "scripts/run_parser.py", "--host", "0.0.0.0", "--port", "8000"] +COPY . . +COPY docker/entrypoint.mineru-api.sh /usr/local/bin/entrypoint.mineru-api.sh +RUN chmod +x /usr/local/bin/entrypoint.mineru-api.sh && python3 scripts/check_parser_baseline.py --runtime + +ENTRYPOINT ["/usr/local/bin/entrypoint.mineru-api.sh"] +CMD ["mineru-api", "--host", "0.0.0.0", "--port", "8000"] diff --git a/docs/mineru-migration/2.7.1-baseline.json b/docs/mineru-migration/2.7.1-baseline.json new file mode 100644 index 0000000..b34653f --- /dev/null +++ b/docs/mineru-migration/2.7.1-baseline.json @@ -0,0 +1,197 @@ +{ + "baseline": "PyPI mineru==2.7.1", + "url": "https://files.pythonhosted.org/packages/36/fd/d94ab07cbcfabae65a306a6d704214ec6024f443d8119e24234f1b3fa3ba/mineru-2.7.1-py3-none-any.whl", + "sha256": "3c144149f2749a79be240833c392216ddd69c1516de162b29dbaddbc0ce38f73", + "files": 187, + "kernel_modifications": [], + "hash_format": "sha256 after CRLF-to-LF normalization", + "source_hashes": { + "__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "backend/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "backend/hybrid/__init__.py": "20582bd82f0d7d2023f2aec917b40ea8cbc2889e8573c4c8b94dd48760da1595", + "backend/hybrid/hybrid_analyze.py": "49c930e93fa9bccbf757f9ea66405e5bc918e333480655b1a9e4b6bd7a8daad6", + "backend/hybrid/hybrid_magic_model.py": "dfd072799879e0a05b3deefb6f3182a99ad9e51370371198b6d7288ac8033ab7", + "backend/hybrid/hybrid_model_output_to_middle_json.py": "c84f9cd5e19ae4bccfa8b7ca7ef04e37f4894658eacb3d81ecb8a0945704ec54", + "backend/pipeline/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "backend/pipeline/batch_analyze.py": "dd406cd963b0708fa67c6025c59b78dfb3aa48e95e5cf2e7a586eb0fd8790f9e", + "backend/pipeline/model_init.py": "c33f157627945c2c734bd350aa499a897c1e7b2f31cfefc306f982d4eb8afc1e", + "backend/pipeline/model_json_to_middle_json.py": "ade5e4511ff02a6243eb877bbd135733116f8b09330e51a346c869770b15aae2", + "backend/pipeline/model_list.py": "edc5cc05f66b3f42baa96b9e8350fff96a1400d79220dce49ff89cf44ed840bb", + "backend/pipeline/para_split.py": "2aaf79326be43e6eeb2b1942486893bd52b217b084ac7236786180b39b0b9744", + "backend/pipeline/pipeline_analyze.py": "44f413b6efa6e1661543121128b8f7f553f268aaaba22e5373df85084b90857f", + "backend/pipeline/pipeline_magic_model.py": "c3c8c6c7c7fac9937459fdb23cfdcbf6b60a73dae8831ade642ad427326f3cef", + "backend/pipeline/pipeline_middle_json_mkcontent.py": "34908b18a13b06a336e1b45da5709f4da9728aaa33a301598e9773a48532e5a0", + "backend/utils.py": "18b254dc8ce70e6844d7fa8d9a453550eb6cbac9081c17b382c1153ba51aafe6", + "backend/vlm/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "backend/vlm/model_output_to_middle_json.py": "02a617e38812f5cad43bfb7b4ae51ab43ef51158e8c3aa48eb2036224de0434b", + "backend/vlm/utils.py": "b2a712e1654273154bd5a125288235ccd60cbb6c87e6d46956a45be255d59b7f", + "backend/vlm/vlm_analyze.py": "11d7c49a4ae803795a7d164ba8de2e39a2d6c7da3156752872a16c599c92f367", + "backend/vlm/vlm_magic_model.py": "983fa2af16e8a360e632ee10175c27bdbb62db174dc8198d7e56c1e1af939ac5", + "backend/vlm/vlm_middle_json_mkcontent.py": "c3e4b36e6e078ad47b318e298a7482659757b4f4aa9ad954f5c8cd87820e4328", + "cli/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "cli/client.py": "98f35f3044a1546fa2b619a5250e6719121a7768026605230461cdef30262e14", + "cli/common.py": "7cc3dcdb7e43b67ba942487db8520c1d4a71392bc2a79c9cdc0e7ab0069b0166", + "cli/fast_api.py": "4c6a59ab2504d64836797b0fefaa6bd29d72a8d38e53d8f28cbe4f734149c117", + "cli/gradio_app.py": "d882163a6d9b1071eae4164c95f98ddf2009c3535ff125002d343de68f9b632d", + "cli/models_download.py": "2cd7e822952524cee6eea6f64a20b1b63303c388c82c142d67034fd89a18f355", + "cli/vlm_server.py": "dbb1daa8edf0a4c5d203f9c0dc20ba24e0531cadeaeba48fd34703ea6f47b901", + "data/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "data/data_reader_writer/__init__.py": "f6a9c636bb2e181330c1fb10cbaa0285d933fbe6bf2cf758584d15659af4cabe", + "data/data_reader_writer/base.py": "9ea98071d1ce5cc3893ba4404f720b96280315ac3c3a9d124f20b0e723b301b2", + "data/data_reader_writer/dummy.py": "312c5069938af22fa59643d70e7d3c92fbee22d7b9a0907fe25463af59a75ed0", + "data/data_reader_writer/filebase.py": "8255d548927eb80fffa83d09feb7611d4d956043866a20b6824f52270ca73e3e", + "data/data_reader_writer/multi_bucket_s3.py": "6f05488a65556a3d0c35e549a4d000ad6e35746caaaaf0b3abd259e8e85db298", + "data/data_reader_writer/s3.py": "3707fc89c1d542a9bc448da7e00cf356ec0aef9775ab925956e0e97bbe028478", + "data/io/__init__.py": "9a343f2c049a5fee3fa60fb5bb368c272b0812582552cde8f9a92aac03fc3024", + "data/io/base.py": "4aa350a9edf466fa15be0ec656ffa12cc0a337ac81803c9041678b806b137e14", + "data/io/http.py": "776f826411a330f3af7409240bdcf150429862264f80befa66a706e21203793d", + "data/io/s3.py": "ddf0e2b4deeb1069f50ca0e48cab5fdb20baf260eb27eb55cb28bc55890d61e0", + "data/utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "data/utils/exceptions.py": "a3116951056e9bc2d1140820d5c66f328378c604947bde6b80d0d4da6cd39707", + "data/utils/path_utils.py": "ca47a8f965b5eb723618a016a34bc8a4fd4caedc08f7d3cfaad082d39ba1bd53", + "data/utils/schemas.py": "30afe99d690aebd3119d56b29278b6b42472eacc7b71d09e3ebcbf5bb5148217", + "model/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/layout/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/layout/doclayoutyolo.py": "0edb4835dba5cd38987150e5ffbd280ed51d7d598673daa429699b3ce180795d", + "model/mfd/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/mfd/yolo_v8.py": "b7ba6d992847a19096f5692a2cd08bd4a442871a5ad84ee3e60e5f89b5e552f6", + "model/mfr/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/mfr/pp_formulanet_plus_m/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/mfr/pp_formulanet_plus_m/predict_formula.py": "6a5197fec3c9c5987feefd6c38adc327c6a47e458efb673923f251eda5cc4cb5", + "model/mfr/pp_formulanet_plus_m/processors.py": "3122b26a7c620c38e00d01c1a2ff868cab4f9ccc7db529b1042f462243377edf", + "model/mfr/unimernet/Unimernet.py": "d5218b490dab73aa2c9671303f84e2ec9c5a365c8248681ed23b3e4ebd558a41", + "model/mfr/unimernet/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/mfr/unimernet/unimernet_hf/__init__.py": "907708486f064b84d6256df84822427a2d63c68e87c6f3b4d1a0b476ac8d1602", + "model/mfr/unimernet/unimernet_hf/modeling_unimernet.py": "fe5377cc32b17aab16fa1f6d5f1efd0d8893e6e4f83fd8b11b8f56ad260a1711", + "model/mfr/unimernet/unimernet_hf/unimer_mbart/__init__.py": "f53dab069c865f96054188fcf7e996ba346890ebb3e3180dade06e7a0720d7f7", + "model/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py": "87045aaf7a6a37f715b374d14cd4ae841e3069c06771f27eaaf6936a345bd317", + "model/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py": "5e49cbe940f6b217dc12b003f242e4e754f2dcbb5bbfbb838bf6379311b58def", + "model/mfr/unimernet/unimernet_hf/unimer_mbart/tokenization_unimer_mbart.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/mfr/unimernet/unimernet_hf/unimer_swin/__init__.py": "f3fd432b00c20d4064787622249e8c667a1d641b1ab476ea872821d75b3d7840", + "model/mfr/unimernet/unimernet_hf/unimer_swin/configuration_unimer_swin.py": "397dde4542819ca097b7124e1b7b1d368075215f99ede7e0594fa069c9583860", + "model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py": "6bd902bf0cc925246b29036d5b6a0ea53c2b6a9cdea7c06318558b84b1754f49", + "model/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py": "43f7dd9851d406d12801f5a9f5aa307704c213630814c38f6d88e84b25cada25", + "model/mfr/utils.py": "a408b51e7913b8ed11eb6e751dd97ea39d26d301f409ef3d3c07fbe160ac5cf5", + "model/ocr/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/ocr/pytorch_paddle.py": "707313979b0aca7e01636db4efeec643879997d05051cb39b9cc70fcd15ecc82", + "model/ori_cls/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/ori_cls/paddle_ori_cls.py": "5484b6d887ab1d24fb83ad000bdaf63c44081ba35059e41a1f53ab5c8c4d4ec8", + "model/reading_order/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/reading_order/layout_reader.py": "21550570d303177fa48a8f812318e9a479d64b77873eabef362848c367db2053", + "model/reading_order/xycut.py": "7b3352abf6385178b3b41e7c85b5c9b234c994e06a5888ee5b9036b8b49a652a", + "model/table/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/table/cls/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/table/cls/paddle_table_cls.py": "e4fb6278a42703380c3514d91609ea42c196293110df2c855909c14488df4380", + "model/table/rec/RapidTable.py": "d9d35d189b1576c19f466eabddd78445432cb79448c47d18ba21802e441b353c", + "model/table/rec/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/table/rec/slanet_plus/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/table/rec/slanet_plus/main.py": "bdfadcbd0f4905fdf661953d78da1eb68a9da5cac536c03558da9006c1bc8b6a", + "model/table/rec/slanet_plus/matcher.py": "bb017ec022da625690dc943ff98cb01959755d0627c7b1bf453b962d6f099419", + "model/table/rec/slanet_plus/matcher_utils.py": "f70b7fc9d79e5622dde7b6d4ea0de59d75e78b8f6a2d2adad82eb0485419922c", + "model/table/rec/slanet_plus/table_structure.py": "aadf873d8210ca9d1a586fcc9a733fb0c40257c64b6f8ac02d2b9ec82a213e03", + "model/table/rec/slanet_plus/table_structure_utils.py": "6184a4c0dd9674bc7baa458c48690f63bc97387e44355860e42b111a1b59e569", + "model/table/rec/unet_table/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/table/rec/unet_table/main.py": "275dd0effeacb58c9e76655e75ff42643ed1d2dba0b867d3837677a1be060ee3", + "model/table/rec/unet_table/table_recover.py": "ad2c9e5b2b8fd7433c74b280e5ed27e0fd835cc61b55b9a02f111c75903cff41", + "model/table/rec/unet_table/table_structure_unet.py": "8679982f36454652b463882bf3be06f4668b6a170a9cd65836e9fcebd15d987f", + "model/table/rec/unet_table/utils.py": "09802a256d3078f264e0d01e99bf16db4dcdec4df6bf4ba38966f16a70e177c2", + "model/table/rec/unet_table/utils_table_line_rec.py": "ceb09d3f023833c9eed0511f77b9512407b4cfc918ab72856f3c0494cf365121", + "model/table/rec/unet_table/utils_table_recover.py": "5e4b09b18f36652d24a949cd4fe8ef698cf1277577b2f312ce3d29bb021abb59", + "model/utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/utils/pytorchocr/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/utils/pytorchocr/base_ocr_v20.py": "e5b23b300bbae6bfaf9f6f24af0749ea98d932412f5a3b2913b110693b11111c", + "model/utils/pytorchocr/data/__init__.py": "618bb773e5b87e0104af1c4333df2e437a16c0f121fbac3be4b638cdc8f856d3", + "model/utils/pytorchocr/data/imaug/__init__.py": "7381f48173d1c1e434c0c16792b08b4d1e8caed1be7b89148a7c70ab61b557d5", + "model/utils/pytorchocr/data/imaug/operators.py": "79d05a0de7b39910241a476e3c5e8859c529136597461ee6011a929f0cb29c40", + "model/utils/pytorchocr/modeling/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/utils/pytorchocr/modeling/architectures/__init__.py": "0c203d152e26139a021c3941854ae460b77115e4086e13e3e0ff2827f811643f", + "model/utils/pytorchocr/modeling/architectures/base_model.py": "4615760e6fa8b34f24085ca54f9ef346eef61eafd125d172df141ed4c3da0ae5", + "model/utils/pytorchocr/modeling/backbones/__init__.py": "74e9aa86f2eb04cfb68a6730b7bde44ba00f98c6e1a15613a33966a8e9117ea0", + "model/utils/pytorchocr/modeling/backbones/det_mobilenet_v3.py": "af48169c0d579add19c381502f1ee47fe596c1977fdba3df37384cd3976b72e1", + "model/utils/pytorchocr/modeling/backbones/rec_donut_swin.py": "9530a37bb98fb84f9f1ded3901325ee42efbc319340914e8940b43fe07d04e68", + "model/utils/pytorchocr/modeling/backbones/rec_hgnet.py": "52c21bcea37f928c86a128754c0f6bdbb4a08291db78a4b71e6992f80d80c34e", + "model/utils/pytorchocr/modeling/backbones/rec_lcnetv3.py": "f954734cfb6becb4e6c09e1d0adb08fbe803f35600761de59556aef4ae159dcf", + "model/utils/pytorchocr/modeling/backbones/rec_mobilenet_v3.py": "989984eb11a98c7647d956b0d7a2e5225a911459bd47dc91b122446b7627de7c", + "model/utils/pytorchocr/modeling/backbones/rec_mv1_enhance.py": "2b8a7d28560d9a5b55df2dd0b311c8012371a2a946b71800a02c5e1687f20a6c", + "model/utils/pytorchocr/modeling/backbones/rec_pphgnetv2.py": "61fa75c51e5286ce5bd6ec468e1152ad880fabd065dcda20612a3e28e26ed3c9", + "model/utils/pytorchocr/modeling/backbones/rec_svtrnet.py": "008694677216064473da95a66a70634b441d25c6278a6312578316a1f36941c8", + "model/utils/pytorchocr/modeling/common.py": "debda34ef3d8412e08813bc8a91e25e9b055c11ee39fef3bad29a9bf7b65ab12", + "model/utils/pytorchocr/modeling/heads/__init__.py": "7650d6008083ff73eb622862a421c33f91822551fff9fc128fb59fa237c808ca", + "model/utils/pytorchocr/modeling/heads/cls_head.py": "a6e232e46954b4029eafa792e0758abb4ecfcd177e1e50c0a88cf95aa8c11da0", + "model/utils/pytorchocr/modeling/heads/det_db_head.py": "fa4f1ba6e190c3fc48543b2e9ab7e298ec60d0efa83f630e0320c94e353bd11a", + "model/utils/pytorchocr/modeling/heads/rec_ctc_head.py": "cb0ca4e512605084dd5efad4664db205258ab1a648aa74e87dd15bb9052dc235", + "model/utils/pytorchocr/modeling/heads/rec_multi_head.py": "2b8d12300f2d0155aefb77f081f8778c659e54501d5673321e3799788f4e3bb4", + "model/utils/pytorchocr/modeling/heads/rec_ppformulanet_head.py": "e5c2c951ab032ab6020b8ef34f1d83e4eb25e829cf87a24099dc1beac69e0d68", + "model/utils/pytorchocr/modeling/heads/rec_unimernet_head.py": "c2c1f16445f654eea43442d1e37794325796257ac352070fe672d67cd22b33e1", + "model/utils/pytorchocr/modeling/necks/__init__.py": "eb7e0bd72f905afe4ff28a4d89298abd0131dd4b24736d111bc0d888275b97c5", + "model/utils/pytorchocr/modeling/necks/db_fpn.py": "4cb176a52caf442d283f32f4795c8d960dd6e99bdfaf827c7c3d67ce2541eee2", + "model/utils/pytorchocr/modeling/necks/intracl.py": "c3641dc1d23d069896f76552e26a8bdf5b1511121b639dd37db0f943aa2489a6", + "model/utils/pytorchocr/modeling/necks/rnn.py": "4c052ae267b883fc97c5ab79c053a0193aa7a82d9450ad456762defb61162aa0", + "model/utils/pytorchocr/postprocess/__init__.py": "882d4e97a093c51599054c90ff9215311ea422eaeff5624f3965a8ecd02e6410", + "model/utils/pytorchocr/postprocess/cls_postprocess.py": "d555565d3fdbd6f8466fb3c6beac9f510dc8a7b2eea47eb6bcfbdaf7c1ad8d30", + "model/utils/pytorchocr/postprocess/db_postprocess.py": "01d64f17b7eb850dbb555769d0616631c5ed8afc036597d7621cc93a53f8cd4b", + "model/utils/pytorchocr/postprocess/rec_postprocess.py": "a86077a271441611e3aa4b0847520a3b1d8463df1ec1fb268c00e3ad15e0df46", + "model/utils/pytorchocr/utils/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/utils/pytorchocr/utils/resources/arch_config.yaml": "06f697b075d7572c5838562392dec7b72656884c8baef1ec1ec2587d06528436", + "model/utils/pytorchocr/utils/resources/dict/ka_dict.txt": "fad3f765943275eec2134a6fbc9b52785426641104d4e7db3a159dc73f341dde", + "model/utils/pytorchocr/utils/resources/dict/ppocrv4_doc_dict.txt": "a5bc3887c43c901e5a3f97b13ffadf1c5754ede7cc8c9f5abe22e875a7c48372", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_arabic_dict.txt": "7f92f7dbb9b75a4787a83bfb4f6d14a8ab515525130c9d40a9036f61cf6999e9", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_cyrillic_dict.txt": "db40aa52ceb112055be80c694afdf655d5d2c4f7873704524cc16a447ca913ba", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_devanagari_dict.txt": "09c7440bfc5477e5c41052304b6b185aff8c4a5e8b2b4c23c1c706f6fe1ee9fc", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_dict.txt": "d1979e9f794c464c0d2e0b70a7fe14dd978e9dc644c0e71f14158cdf8342af1b", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_el_dict.txt": "31defc62c0c3ad3674a82da6192226a2ba98ef4ff014a7045cb88d59f9c3de31", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_en_dict.txt": "e025a66d31f327ba0c232e03f407ae8d105e1e709e7ccb3f408aa778c24e70d6", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_eslav_dict.txt": "3e95f1581557162870cacdba5af91a4c6be2890710d395b0c3c7578e7ee5e6eb", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_korean_dict.txt": "a88071c68c01707489baa79ebe0405b7beb5cca229f4fc94cc3ef992328802d7", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_latin_dict.txt": "ccbcc45730b3fbbd9050c5bc74db6a99067141ef1035e3d14889a84a6b9b1aff", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_ta_dict.txt": "85b541352ae18dc6ba6d47152d8bf8adff6b0266e605d2eef2990c1bf466117b", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_te_dict.txt": "42f83f5d3fdb50778e4fa5b66c58d99a59ab7792151c5e74f34b8ffd7b61c9d6", + "model/utils/pytorchocr/utils/resources/dict/ppocrv5_th_dict.txt": "57f5406f94bb6688fb7077f7be65f08bbd71cecf48c01ea26c522cb5c4836b7a", + "model/utils/pytorchocr/utils/resources/models_config.yml": "408baa7aef75a5fbaac9ae096f199941290e6247be876073db53b6a4e2d03d87", + "model/utils/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml": "6bbcae78e4d4adfa59a3c0ac2babd0a246cb341d89f8fefb8a168287f2e8cef4", + "model/utils/tools/__init__.py": "c44a91eb967c60ecce2e8acb8cad0b087a2cdb35feb42bb14abc67763534d211", + "model/utils/tools/infer/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "model/utils/tools/infer/predict_cls.py": "f1198a975bde8e7665eb971a1d9355dad6ba84cb20e41fcb13e16ea823bc4fc0", + "model/utils/tools/infer/predict_det.py": "bd8411127eef10b5f106cafbd8208256f9b583057cd8e35a0b019fc542239def", + "model/utils/tools/infer/predict_rec.py": "f811fddc90e2b2ed244fa0b21c0e2995438a71bd8bf94bc393b4de8a7e6ec2de", + "model/utils/tools/infer/predict_system.py": "8647a0927ea1ab6bf6cea1d500feb5e7e93e7e44d2f2cc116126d97a8aa6488f", + "model/utils/tools/infer/pytorchocr_utility.py": "8b53c537efe479f254519e1593b8a0b354d4f207c4ad30e50d763afbc51ababc", + "model/vlm/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "model/vlm/lmdeploy_server.py": "3efc4935c508281f15cd63035de575b744874a0cff50b3b7e9903325ba69cfdd", + "model/vlm/vllm_server.py": "c3975dbac3db715684a16028fc14639b0bff630c6b73f6c23118718a1a32ca46", + "resources/fasttext-langdetect/lid.176.ftz": "e33db98de5d095f003b0645244841d33b0763864daf8d0516ae3cc1cfa759a56", + "resources/header.html": "ef1adfe9b1a5a11fb765e4c3c80f89bdabc4fcd791b940dede9d3b7042945d22", + "utils/__init__.py": "f0246b09056e1316b406db51161dd9e34945cb62b98cdd2ca7aeca5a33a58f97", + "utils/block_pre_proc.py": "b86066c5fd8c47d6e99539d023cc478c223e923de9951849af485c58a89d6ce4", + "utils/block_sort.py": "e5ed6638b0775bbc6ee58d619a1bc64873cbfda438d51ff855770fe2f8d800e5", + "utils/boxbase.py": "c67180d64ee156d4d0aeb7aa94998af92037cbd79d4c780b9868aa1ab4977241", + "utils/char_utils.py": "ef84f9625af99a2d6e75d008b8992ef59eac1fbbe147bb79f79fc7eea99bbb87", + "utils/check_sys_env.py": "4d18f3838c56ca8486ae0bf829a3f6db903ef7dc4180b01f67570f706aab0400", + "utils/cli_parser.py": "e2c78502ed64ba5b189f0e96336abf7318043addad12b655908f8b34417f906c", + "utils/config_reader.py": "2115564e90676e7469724e9e5d950ac3e7dc2edee1a27e52e2ea965be4416f5c", + "utils/cut_image.py": "8379b89df7093569718be3f49295d3b659aca5790c70b09f1b0998b90f99da11", + "utils/draw_bbox.py": "164829a6353346137ebb1bc285d9211d77036af244680a4c0faa82eaaa11c1f4", + "utils/engine_utils.py": "2666a8f7e3beb190f31fbbc034a103698e8d27cb6eb612ac4ebdb72c521e04b5", + "utils/enum_class.py": "59e8edef35fe11b9af40cfda8883c24b870537f2b4fbc398ce53b93f2cacba07", + "utils/format_utils.py": "dacf3dbc77122128eea2593c1ef8372bee7ead16e24f752cede14bcd42ab34ab", + "utils/guess_suffix_or_lang.py": "6940b6c002706b92c7d121f1c136ce109a95560be9754096145ea87fc7835647", + "utils/hash_utils.py": "50f4bff0d441995ba67723afd7a2e6bfa2f2db12bc3950c911ee601ba80a2059", + "utils/language.py": "ed14f79b149aee3769a02e7249ded975d1c0ed33bb52c9e60ce5a2619031bb28", + "utils/llm_aided.py": "f56532b6fc5e9d202e696478b1342154f43987ca58d3054e1f53b6b23ffa74bb", + "utils/magic_model_utils.py": "23abdd379e9aaa140118e6aca161e225b8e75ec0705288f0eb11636d66521da5", + "utils/model_utils.py": "ea6a0e42a1394a11da24a9043573fc057240ed1096b4e1a56076779e2770999b", + "utils/models_download_utils.py": "51f8efc21c4ee819091dae494a9115359ef51a82cc3cc989a729b74c7113d93e", + "utils/ocr_utils.py": "94f22bc0d5226f99abcd4929a274581ee502763576aaf11334b4b338bc9f96b5", + "utils/os_env_config.py": "64db644782ab256ef609e2284cdcc60cbead30abff84bf27cef588b2c1966ea6", + "utils/pdf_classify.py": "e83179a47ffd52af377ec16da7b9f88be39d6101b3a0d395f4bd1505486004c4", + "utils/pdf_image_tools.py": "2f69072a815a428e021a34b577af09002ae5072731ea0c829e71656c11512aec", + "utils/pdf_page_id.py": "7a6f7aea4d760915b8463e3d44688b07ff082f09173c19d645eb40a5ac77793b", + "utils/pdf_reader.py": "59e20d9b94b25815174f4c0ff65cc86de1ecf0fe9650890dea754be57e0bcc6e", + "utils/pdf_text_tool.py": "284ced8df76ab081c7ba24c400c00becbaf5392dd1ed4afeb93a8688246345e4", + "utils/run_async.py": "acf78fe010997ab47c541c910e1898cdf6626a12d5aa8644055012e787408cd8", + "utils/span_block_fix.py": "d1e5508c90ab4f4df0a11b7d86887a52ee364e9d5d69c7c64efdb1dc1f6aabde", + "utils/span_pre_proc.py": "9eee818794d63ca1731ee15f6c4b3402caf4e0ce3138be4838dcfff062479f8e", + "utils/table_merge.py": "5f6bd00822b1f211bd222a67e1410ff295c773d8de36660d62f979cf16934b61", + "version.py": "c91a521fa9816f804981b1654fbaedf0c4a30945b5ed8731d11ce22dffa540b0" + } +} diff --git a/docs/mineru-migration/README.md b/docs/mineru-migration/README.md index b72d635..52db75d 100644 --- a/docs/mineru-migration/README.md +++ b/docs/mineru-migration/README.md @@ -1,4 +1,4 @@ -> 状态更新:下文为历史差异盘点,4.0.12 合并方案已被替代。当前固定官方 2.7.4,业务功能迁入 MaxKB,参见仓库 README。 +> 状态更新(2026-11-06):下文仅保留历史盘点,4.0.12 及后续 2.7.4 方案已被替代。当前按用户要求恢复纯官方 2.7.1,暂不加六级标题补丁;业务功能继续位于 MaxKB。参见仓库 README 和 2.7.1-baseline.json。 # MinerU 2.7.1 定制盘点与 4.0.12 合并方案 diff --git a/docs/mineru-migration/release-baseline-20261106.md b/docs/mineru-migration/release-baseline-20261106.md index 6877bd5..73d3217 100644 --- a/docs/mineru-migration/release-baseline-20261106.md +++ b/docs/mineru-migration/release-baseline-20261106.md @@ -1,6 +1,6 @@ # MinerU 与天数发布基线核查 · 2026-11-06 -本记录是风险评估和发布建议,不代表已回退源码或通过 MR100 真机验收。 +更新:用户随后明确要求恢复 2.7.1。现已恢复官方 2.7.1 的全部 187 个文件,移除三处六级标题补丁及其它内核定制,CoreX/CUDA 构建恢复原厂商镜像和安装流程,仅固定 MinerU 为 `==2.7.1` 并增加完整性检查。以下表格是改动前的核查记录,保留用于追溯;恢复源码不代表 MR100 真机验收通过。 ## 当前事实 @@ -34,4 +34,4 @@ 旧镜像若接入新版还需要最小协议兼容验证:旧路径 `/api/file_parse`,新版 `/file_parse`;同步返回均有 `results` / `md_content`,但平台的版本目录、资源连通性检查及部署启动校验当前固定 2.7.4。现有升级脚本会拒绝直接替入未标记的旧镜像,不能把本记录当作可直接替换标签的操作手册。 -本轮未切换 MinerU 版本。采用旧栈前应核对上述镜像是否为原交付包,完成新平台与旧解析 API 的独立兼容演练;拿到 MR100 后再完成真实 PDF/图片、公式、表格、显存及连续任务验收。 +采用上述旧交付镜像时仍需核对是否为原交付包,并处理它的旧 API 路径。当前纯官方 2.7.1 自身提供 `/file_parse`,不带原项目的 `/api` 前缀;无需为新源码恢复旧业务接口。拿到 MR100 后仍需完成真实 PDF/图片、公式、表格、显存及连续任务验收。 diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py index fd27edb..2aab61b 100644 --- a/mineru/backend/hybrid/hybrid_magic_model.py +++ b/mineru/backend/hybrid/hybrid_magic_model.py @@ -424,8 +424,7 @@ def __tie_up_category_by_index(blocks, subject_block_type, object_block_type): # 调用通用方法 return tie_up_category_by_index( get_subjects, - get_objects, - object_block_type=object_block_type + get_objects ) diff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/pipeline/model_init.py index 65173e1..5ed2b8c 100644 --- a/mineru/backend/pipeline/model_init.py +++ b/mineru/backend/pipeline/model_init.py @@ -297,14 +297,7 @@ def ocr_det_batch_setting(device): # 检测torch的版本号 import torch from packaging import version - - device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "") - - if ( - version.parse(torch.__version__) >= version.parse("2.8.0") - or str(device).startswith('mps') - or device_type.lower() in ["corex"] - ): + if version.parse(torch.__version__) >= version.parse("2.8.0") or str(device).startswith('mps'): enable_ocr_det_batch = False else: enable_ocr_det_batch = True diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py index 4a6fdae..4383eec 100644 --- a/mineru/backend/pipeline/pipeline_analyze.py +++ b/mineru/backend/pipeline/pipeline_analyze.py @@ -193,12 +193,7 @@ def batch_image_analyze( # 检测torch的版本号 import torch from packaging import version - device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "") - if ( - version.parse(torch.__version__) >= version.parse("2.8.0") - or str(device).startswith('mps') - or device_type.lower() in ["corex"] - ): + if version.parse(torch.__version__) >= version.parse("2.8.0") or str(device).startswith('mps'): enable_ocr_det_batch = False else: enable_ocr_det_batch = True diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py index feb9613..8a80b0d 100644 --- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py +++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py @@ -296,8 +296,8 @@ def union_make(pdf_info_dict: list, def get_title_level(block): title_level = block.get('level', 1) - if title_level > 6: - title_level = 6 + if title_level > 4: + title_level = 4 elif title_level < 1: title_level = 0 return title_level @@ -311,4 +311,4 @@ def escape_special_markdown_char(content): for char in special_chars: content = content.replace(char, "\\" + char) - return content + return content \ No newline at end of file diff --git a/mineru/backend/vlm/utils.py b/mineru/backend/vlm/utils.py index 24b04b9..c64defa 100644 --- a/mineru/backend/vlm/utils.py +++ b/mineru/backend/vlm/utils.py @@ -18,12 +18,6 @@ def enable_custom_logits_processors() -> bool: compute_capability = f"{major}.{minor}" elif hasattr(torch, 'npu') and torch.npu.is_available(): compute_capability = "8.0" - elif hasattr(torch, 'gcu') and torch.gcu.is_available(): - compute_capability = "8.0" - elif hasattr(torch, 'musa') and torch.musa.is_available(): - compute_capability = "8.0" - elif hasattr(torch, 'mlu') and torch.mlu.is_available(): - compute_capability = "8.0" else: logger.info("CUDA not available, disabling custom_logits_processors") return False diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.py index 58884d3..ca7373d 100644 --- a/mineru/backend/vlm/vlm_analyze.py +++ b/mineru/backend/vlm/vlm_analyze.py @@ -1,7 +1,6 @@ # Copyright (c) Opendatalab. All rights reserved. import os import time -import json from loguru import logger @@ -100,37 +99,6 @@ class ModelSingleton: import vllm except ImportError: raise ImportError("Please install vllm to use the vllm-engine backend.") - - # musa vllm v1 引擎特殊配置 - # device = get_device() - # if device_type.startswith("musa"): - # import torch - # if torch.musa.is_available(): - # compilation_config = { - # "cudagraph_capture_sizes": [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 24, 28, 30], - # "simple_cuda_graph": True - # } - # block_size = 32 - # kwargs["compilation_config"] = compilation_config - # kwargs["block_size"] = block_size - - # corex vllm v1 引擎特殊配置 - device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "") - if device_type.lower() == "corex": - compilation_config = { - "cudagraph_mode": "FULL_DECODE_ONLY", - "level": 0 - } - kwargs["compilation_config"] = compilation_config - - if "compilation_config" in kwargs: - if isinstance(kwargs["compilation_config"], str): - try: - kwargs["compilation_config"] = json.loads(kwargs["compilation_config"]) - except json.JSONDecodeError: - logger.warning( - f"Failed to parse compilation_config as JSON: {kwargs['compilation_config']}") - del kwargs["compilation_config"] if "gpu_memory_utilization" not in kwargs: kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization() if "model" not in kwargs: @@ -144,46 +112,8 @@ class ModelSingleton: try: from vllm.engine.arg_utils import AsyncEngineArgs from vllm.v1.engine.async_llm import AsyncLLM - from vllm.config import CompilationConfig except ImportError: raise ImportError("Please install vllm to use the vllm-async-engine backend.") - - - # musa vllm v1 引擎特殊配置 - # device = get_device() - # if device.startswith("musa"): - # import torch - # if torch.musa.is_available(): - # compilation_config = CompilationConfig( - # cudagraph_capture_sizes=[1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 24, 28, 30], - # simple_cuda_graph=True - # ) - # block_size = 32 - # kwargs["compilation_config"] = compilation_config - # kwargs["block_size"] = block_size - - # corex vllm v1 引擎特殊配置 - device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "") - if device_type.lower() == "corex": - compilation_config = CompilationConfig( - cudagraph_mode="FULL_DECODE_ONLY", - level=0 - ) - kwargs["compilation_config"] = compilation_config - - if "compilation_config" in kwargs: - if isinstance(kwargs["compilation_config"], dict): - # 如果是字典,转换为 CompilationConfig 对象 - kwargs["compilation_config"] = CompilationConfig(**kwargs["compilation_config"]) - elif isinstance(kwargs["compilation_config"], str): - # 如果是 JSON 字符串,先解析再转换 - try: - config_dict = json.loads(kwargs["compilation_config"]) - kwargs["compilation_config"] = CompilationConfig(**config_dict) - except (json.JSONDecodeError, TypeError) as e: - logger.warning( - f"Failed to parse compilation_config: {kwargs['compilation_config']}, error: {e}") - del kwargs["compilation_config"] if "gpu_memory_utilization" not in kwargs: kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization() if "model" not in kwargs: diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.py index ee96f56..a4a17ad 100644 --- a/mineru/backend/vlm/vlm_magic_model.py +++ b/mineru/backend/vlm/vlm_magic_model.py @@ -349,8 +349,7 @@ def __tie_up_category_by_index(blocks, subject_block_type, object_block_type): # 调用通用方法 return tie_up_category_by_index( get_subjects, - get_objects, - object_block_type=object_block_type + get_objects ) diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py index 4c0ef9c..c081cd6 100644 --- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py +++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py @@ -651,8 +651,8 @@ def union_make(pdf_info_dict: list, def get_title_level(block): title_level = block.get('level', 1) - if title_level > 6: - title_level = 6 + if title_level > 4: + title_level = 4 elif title_level < 1: title_level = 0 return title_level diff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.py index aacbda1..06fd7ad 100644 --- a/mineru/cli/fast_api.py +++ b/mineru/cli/fast_api.py @@ -7,12 +7,12 @@ import asyncio import uvicorn import click import zipfile -import shutil from pathlib import Path import glob -from fastapi import Depends, FastAPI, HTTPException, UploadFile, File, Form, BackgroundTasks +from fastapi import Depends, FastAPI, HTTPException, UploadFile, File, Form from fastapi.middleware.gzip import GZipMiddleware from fastapi.responses import JSONResponse, FileResponse +from starlette.background import BackgroundTask from typing import List, Optional from loguru import logger @@ -30,30 +30,23 @@ from mineru.version import __version__ # 并发控制器 _request_semaphore: Optional[asyncio.Semaphore] = None - # 并发控制依赖函数 async def limit_concurrency(): if _request_semaphore is not None: - # 检查信号量是否已用尽,如果是则拒绝请求 - if _request_semaphore._value == 0: + if _request_semaphore.locked(): raise HTTPException( status_code=503, - detail=f"Server is at maximum capacity: {os.getenv('MINERU_API_MAX_CONCURRENT_REQUESTS', 'unset')}. Please try again later.", + detail=f"Server is at maximum capacity: {os.getenv('MINERU_API_MAX_CONCURRENT_REQUESTS', 'unset')}. Please try again later." ) async with _request_semaphore: yield else: yield - def create_app(): # By default, the OpenAPI documentation endpoints (openapi_url, docs_url, redoc_url) are enabled. # To disable the FastAPI docs and schema endpoints, set the environment variable MINERU_API_ENABLE_FASTAPI_DOCS=0. - enable_docs = str(os.getenv("MINERU_API_ENABLE_FASTAPI_DOCS", "1")).lower() in ( - "1", - "true", - "yes", - ) + enable_docs = str(os.getenv("MINERU_API_ENABLE_FASTAPI_DOCS", "1")).lower() in ("1", "true", "yes") app = FastAPI( openapi_url="/openapi.json" if enable_docs else None, docs_url="/docs" if enable_docs else None, @@ -63,9 +56,7 @@ def create_app(): # 初始化并发控制器:从环境变量MINERU_API_MAX_CONCURRENT_REQUESTS读取 global _request_semaphore try: - max_concurrent_requests = int( - os.getenv("MINERU_API_MAX_CONCURRENT_REQUESTS", "0") - ) + max_concurrent_requests = int(os.getenv("MINERU_API_MAX_CONCURRENT_REQUESTS", "0")) except ValueError: max_concurrent_requests = 0 @@ -76,7 +67,6 @@ def create_app(): app.add_middleware(GZipMiddleware, minimum_size=1000) return app - app = create_app() @@ -86,34 +76,27 @@ def sanitize_filename(filename: str) -> str: 移除路径遍历字符, 保留 Unicode 字母、数字、._- 禁止隐藏文件 """ - sanitized = re.sub(r"[/\\.]{2,}|[/\\]", "", filename) - sanitized = re.sub(r"[^\w.-]", "_", sanitized, flags=re.UNICODE) - if sanitized.startswith("."): - sanitized = "_" + sanitized[1:] - return sanitized or "unnamed" - + sanitized = re.sub(r'[/\\\.]{2,}|[/\\]', '', filename) + sanitized = re.sub(r'[^\w.-]', '_', sanitized, flags=re.UNICODE) + if sanitized.startswith('.'): + sanitized = '_' + sanitized[1:] + return sanitized or 'unnamed' def cleanup_file(file_path: str) -> None: - """清理临时文件或目录""" + """清理临时 zip 文件""" try: if os.path.exists(file_path): - if os.path.isfile(file_path): - os.remove(file_path) - elif os.path.isdir(file_path): - shutil.rmtree(file_path) + os.remove(file_path) except Exception as e: logger.warning(f"fail clean file {file_path}: {e}") - def encode_image(image_path: str) -> str: """Encode image using base64""" with open(image_path, "rb") as f: return b64encode(f.read()).decode() -def get_infer_result( - file_suffix_identifier: str, pdf_name: str, parse_dir: str -) -> Optional[str]: +def get_infer_result(file_suffix_identifier: str, pdf_name: str, parse_dir: str) -> Optional[str]: """从结果文件中读取推理结果""" result_file_path = os.path.join(parse_dir, f"{pdf_name}{file_suffix_identifier}") if os.path.exists(result_file_path): @@ -124,14 +107,11 @@ def get_infer_result( @app.post(path="/file_parse", dependencies=[Depends(limit_concurrency)]) async def parse_pdf( - background_tasks: BackgroundTasks, - files: List[UploadFile] = File( - ..., description="Upload pdf or image files for parsing" - ), - output_dir: str = Form("./output", description="Output local directory"), - lang_list: List[str] = Form( - ["ch"], - description="""(Adapted only for pipeline and hybrid backend)Input the languages in the pdf to improve OCR accuracy.Options: + files: List[UploadFile] = File(..., description="Upload pdf or image files for parsing"), + output_dir: str = Form("./output", description="Output local directory"), + lang_list: List[str] = Form( + ["ch"], + description="""(Adapted only for pipeline and hybrid backend)Input the languages in the pdf to improve OCR accuracy.Options: - ch: Chinese, English, Chinese Traditional. - ch_lite: Chinese, English, Chinese Traditional, Japanese. - ch_server: Chinese, English, Chinese Traditional, Japanese. @@ -149,54 +129,41 @@ async def parse_pdf( - east_slavic: Russian, Belarusian, Ukrainian, English. - cyrillic: Russian, Belarusian, Ukrainian, Serbian (Cyrillic), Bulgarian, Mongolian, Abkhazian, Adyghe, Kabardian, Avar, Dargin, Ingush, Chechen, Lak, Lezgin, Tabasaran, Kazakh, Kyrgyz, Tajik, Macedonian, Tatar, Chuvash, Bashkir, Malian, Moldovan, Udmurt, Komi, Ossetian, Buryat, Kalmyk, Tuvan, Sakha, Karakalpak, English. - devanagari: Hindi, Marathi, Nepali, Bihari, Maithili, Angika, Bhojpuri, Magahi, Santali, Newari, Konkani, Sanskrit, Haryanvi, English. -""", - ), - backend: str = Form( - "hybrid-auto-engine", - description="""The backend for parsing: +""" + ), + backend: str = Form( + "hybrid-auto-engine", + description="""The backend for parsing: - pipeline: More general, supports multiple languages, hallucination-free. - vlm-auto-engine: High accuracy via local computing power, supports Chinese and English documents only. - vlm-http-client: High accuracy via remote computing power(client suitable for openai-compatible servers), supports Chinese and English documents only. - hybrid-auto-engine: Next-generation high accuracy solution via local computing power, supports multiple languages. -- hybrid-http-client: High accuracy via remote computing power but requires a little local computing power(client suitable for openai-compatible servers), supports multiple languages.""", - ), - parse_method: str = Form( - "auto", - description="""(Adapted only for pipeline and hybrid backend)The method for parsing PDF: +- hybrid-http-client: High accuracy via remote computing power but requires a little local computing power(client suitable for openai-compatible servers), supports multiple languages.""" + ), + parse_method: str = Form( + "auto", + description="""(Adapted only for pipeline and hybrid backend)The method for parsing PDF: - auto: Automatically determine the method based on the file type - txt: Use text extraction method - ocr: Use OCR method for image-based PDFs -""", - ), - formula_enable: bool = Form(True, description="Enable formula parsing."), - table_enable: bool = Form(True, description="Enable table parsing."), - server_url: Optional[str] = Form( - None, - description="(Adapted only for -http-client backend)openai compatible server url, e.g., http://127.0.0.1:30000", - ), - return_md: bool = Form(True, description="Return markdown content in response"), - return_middle_json: bool = Form( - False, description="Return middle JSON in response" - ), - return_model_output: bool = Form( - False, description="Return model output JSON in response" - ), - return_content_list: bool = Form( - False, description="Return content list JSON in response" - ), - return_images: bool = Form( - False, description="Return extracted images in response" - ), - response_format_zip: bool = Form( - False, description="Return results as a ZIP file instead of JSON" - ), - start_page_id: int = Form( - 0, description="The starting page for PDF parsing, beginning from 0" - ), - end_page_id: int = Form( - 99999, description="The ending page for PDF parsing, beginning from 0" - ), +""" + ), + formula_enable: bool = Form(True, description="Enable formula parsing."), + table_enable: bool = Form(True, description="Enable table parsing."), + server_url: Optional[str] = Form( + None, + description="(Adapted only for -http-client backend)openai compatible server url, e.g., http://127.0.0.1:30000" + ), + return_md: bool = Form(True, description="Return markdown content in response"), + return_middle_json: bool = Form(False, description="Return middle JSON in response"), + return_model_output: bool = Form(False, description="Return model output JSON in response"), + return_content_list: bool = Form(False, description="Return content list JSON in response"), + return_images: bool = Form(False, description="Return extracted images in response"), + response_format_zip: bool = Form(False, description="Return results as a ZIP file instead of JSON"), + start_page_id: int = Form(0, description="The starting page for PDF parsing, beginning from 0"), + end_page_id: int = Form(99999, description="The ending page for PDF parsing, beginning from 0"), ): + # 获取命令行配置参数 config = getattr(app.state, "config", {}) @@ -204,7 +171,6 @@ async def parse_pdf( # 创建唯一的输出目录 unique_dir = os.path.join(output_dir, str(uuid.uuid4())) os.makedirs(unique_dir, exist_ok=True) - background_tasks.add_task(cleanup_file, unique_dir) # 处理上传的PDF文件 pdf_file_names = [] @@ -230,21 +196,20 @@ async def parse_pdf( except Exception as e: return JSONResponse( status_code=400, - content={"error": f"Failed to load file: {str(e)}"}, + content={"error": f"Failed to load file: {str(e)}"} ) else: return JSONResponse( status_code=400, - content={"error": f"Unsupported file type: {file_suffix}"}, + content={"error": f"Unsupported file type: {file_suffix}"} ) + # 设置语言列表,确保与文件数量一致 actual_lang_list = lang_list if len(actual_lang_list) != len(pdf_file_names): # 如果语言列表长度不匹配,使用第一个语言或默认"ch" - actual_lang_list = [ - actual_lang_list[0] if actual_lang_list else "ch" - ] * len(pdf_file_names) + actual_lang_list = [actual_lang_list[0] if actual_lang_list else "ch"] * len(pdf_file_names) # 调用异步处理函数 await aio_do_parse( @@ -266,15 +231,13 @@ async def parse_pdf( f_dump_content_list=return_content_list, start_page_id=start_page_id, end_page_id=end_page_id, - **config, + **config ) # 根据 response_format_zip 决定返回类型 if response_format_zip: zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_results_") os.close(zip_fd) - background_tasks.add_task(cleanup_file, zip_path) - with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf: for pdf_name in pdf_file_names: safe_pdf_name = sanitize_filename(pdf_name) @@ -284,13 +247,7 @@ async def parse_pdf( elif backend.startswith("vlm"): parse_dir = os.path.join(unique_dir, pdf_name, "vlm") elif backend.startswith("hybrid"): - parse_dir = os.path.join( - unique_dir, pdf_name, f"hybrid_{parse_method}" - ) - else: - # 未知 backend,跳过此文件 - logger.warning(f"Unknown backend type: {backend}, skipping {pdf_name}") - continue + parse_dir = os.path.join(unique_dir, pdf_name, f"hybrid_{parse_method}") if not os.path.exists(parse_dir): continue @@ -299,63 +256,35 @@ async def parse_pdf( if return_md: path = os.path.join(parse_dir, f"{pdf_name}.md") if os.path.exists(path): - zf.write( - path, - arcname=os.path.join( - safe_pdf_name, f"{safe_pdf_name}.md" - ), - ) + zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}.md")) if return_middle_json: path = os.path.join(parse_dir, f"{pdf_name}_middle.json") if os.path.exists(path): - zf.write( - path, - arcname=os.path.join( - safe_pdf_name, f"{safe_pdf_name}_middle.json" - ), - ) + zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}_middle.json")) if return_model_output: path = os.path.join(parse_dir, f"{pdf_name}_model.json") if os.path.exists(path): - zf.write( - path, - arcname=os.path.join( - safe_pdf_name, f"{safe_pdf_name}_model.json" - ), - ) + zf.write(path, arcname=os.path.join(safe_pdf_name, os.path.basename(path))) if return_content_list: path = os.path.join(parse_dir, f"{pdf_name}_content_list.json") if os.path.exists(path): - zf.write( - path, - arcname=os.path.join( - safe_pdf_name, f"{safe_pdf_name}_content_list.json" - ), - ) + zf.write(path, arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}_content_list.json")) # 写入图片 if return_images: images_dir = os.path.join(parse_dir, "images") - image_paths = glob.glob( - os.path.join(glob.escape(images_dir), "*.jpg") - ) + image_paths = glob.glob(os.path.join(glob.escape(images_dir), "*.jpg")) for image_path in image_paths: - zf.write( - image_path, - arcname=os.path.join( - safe_pdf_name, - "images", - os.path.basename(image_path), - ), - ) + zf.write(image_path, arcname=os.path.join(safe_pdf_name, "images", os.path.basename(image_path))) return FileResponse( path=zip_path, media_type="application/zip", filename="results.zip", + background=BackgroundTask(cleanup_file, zip_path) ) else: # 构建 JSON 结果 @@ -369,31 +298,17 @@ async def parse_pdf( elif backend.startswith("vlm"): parse_dir = os.path.join(unique_dir, pdf_name, "vlm") elif backend.startswith("hybrid"): - parse_dir = os.path.join( - unique_dir, pdf_name, f"hybrid_{parse_method}" - ) - else: - # 未知 backend,跳过此文件 - logger.warning(f"Unknown backend type: {backend}, skipping {pdf_name}") - continue + parse_dir = os.path.join(unique_dir, pdf_name, f"hybrid_{parse_method}") if os.path.exists(parse_dir): if return_md: - data["md_content"] = get_infer_result( - ".md", pdf_name, parse_dir - ) + data["md_content"] = get_infer_result(".md", pdf_name, parse_dir) if return_middle_json: - data["middle_json"] = get_infer_result( - "_middle.json", pdf_name, parse_dir - ) + data["middle_json"] = get_infer_result("_middle.json", pdf_name, parse_dir) if return_model_output: - data["model_output"] = get_infer_result( - "_model.json", pdf_name, parse_dir - ) + data["model_output"] = get_infer_result("_model.json", pdf_name, parse_dir) if return_content_list: - data["content_list"] = get_infer_result( - "_content_list.json", pdf_name, parse_dir - ) + data["content_list"] = get_infer_result("_content_list.json", pdf_name, parse_dir) if return_images: images_dir = os.path.join(parse_dir, "images") safe_pattern = os.path.join(glob.escape(images_dir), "*.jpg") @@ -410,24 +325,24 @@ async def parse_pdf( content={ "backend": backend, "version": __version__, - "results": result_dict, - }, + "results": result_dict + } ) except Exception as e: logger.exception(e) return JSONResponse( - status_code=500, content={"error": f"Failed to process file: {str(e)}"} + status_code=500, + content={"error": f"Failed to process file: {str(e)}"} ) -@click.command( - context_settings=dict(ignore_unknown_options=True, allow_extra_args=True) -) +@click.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True)) @click.pass_context -@click.option("--host", default="127.0.0.1", help="Server host (default: 127.0.0.1)") -@click.option("--port", default=8000, type=int, help="Server port (default: 8000)") -@click.option("--reload", is_flag=True, help="Enable auto-reload (development mode)") +@click.option('--host', default='127.0.0.1', help='Server host (default: 127.0.0.1)') +@click.option('--port', default=8000, type=int, help='Server port (default: 8000)') +@click.option('--reload', is_flag=True, help='Enable auto-reload (development mode)') def main(ctx, host, port, reload, **kwargs): + kwargs.update(arg_parse(ctx)) # 将配置参数存储到应用状态中 @@ -444,7 +359,12 @@ def main(ctx, host, port, reload, **kwargs): print(f"Start MinerU FastAPI Service: http://{host}:{port}") print(f"API documentation: http://{host}:{port}/docs") - uvicorn.run("mineru.cli.fast_api:app", host=host, port=port, reload=reload) + uvicorn.run( + "mineru.cli.fast_api:app", + host=host, + port=port, + reload=reload + ) if __name__ == "__main__": diff --git a/mineru/model/mfd/yolo_v8.py b/mineru/model/mfd/yolo_v8.py index d5c34b8..15ff7e8 100644 --- a/mineru/model/mfd/yolo_v8.py +++ b/mineru/model/mfd/yolo_v8.py @@ -1,7 +1,5 @@ import os from typing import List, Union - -import torch from tqdm import tqdm from ultralytics import YOLO import numpy as np @@ -20,8 +18,8 @@ class YOLOv8MFDModel: conf: float = 0.25, iou: float = 0.45, ): - self.device = torch.device(device) - self.model = YOLO(weight).to(self.device) + self.model = YOLO(weight).to(device) + self.device = device self.imgsz = imgsz self.conf = conf self.iou = iou diff --git a/mineru/model/mfr/unimernet/Unimernet.py b/mineru/model/mfr/unimernet/Unimernet.py index 5f8b951..5dc5fd5 100644 --- a/mineru/model/mfr/unimernet/Unimernet.py +++ b/mineru/model/mfr/unimernet/Unimernet.py @@ -23,12 +23,12 @@ class MathDataset(Dataset): class UnimernetModel(object): def __init__(self, weight_dir, _device_="cpu"): from .unimernet_hf import UnimernetModel - if _device_.startswith("mps") or _device_.startswith("npu") or _device_.startswith("musa"): + if _device_.startswith("mps") or _device_.startswith("npu"): self.model = UnimernetModel.from_pretrained(weight_dir, attn_implementation="eager") else: self.model = UnimernetModel.from_pretrained(weight_dir) - self.device = torch.device(_device_) - self.model.to(self.device) + self.device = _device_ + self.model.to(_device_) if not _device_.startswith("cpu"): self.model = self.model.to(dtype=torch.float16) self.model.eval() diff --git a/mineru/model/table/rec/unet_table/utils_table_line_rec.py b/mineru/model/table/rec/unet_table/utils_table_line_rec.py index fd2376e..b426dd9 100644 --- a/mineru/model/table/rec/unet_table/utils_table_line_rec.py +++ b/mineru/model/table/rec/unet_table/utils_table_line_rec.py @@ -4,8 +4,6 @@ import cv2 import numpy as np from scipy.spatial import distance as dist from skimage import measure -from skimage import __version__ as skimage_version -from packaging import version def transform_preds(coords, center, scale, output_size, rot=0): @@ -297,11 +295,7 @@ def min_area_rect_box( """ boxes = [] for region in regions: - if version.parse(skimage_version) >= version.parse("0.26.0"): - region_bbox_area = region.area_bbox - else: - region_bbox_area = region.bbox_area - if region_bbox_area > H * W * 3 / 4: # 过滤大的单元格 + if region.bbox_area > H * W * 3 / 4: # 过滤大的单元格 continue rect = cv2.minAreaRect(region.coords[:, ::-1]) diff --git a/mineru/model/vlm/vllm_server.py b/mineru/model/vlm/vllm_server.py index eb2c328..4ba8211 100644 --- a/mineru/model/vlm/vllm_server.py +++ b/mineru/model/vlm/vllm_server.py @@ -2,7 +2,6 @@ import os import sys from mineru.backend.vlm.utils import set_default_gpu_memory_utilization, enable_custom_logits_processors -from mineru.utils.config_reader import get_device from mineru.utils.models_download_utils import auto_download_and_get_model_root_path from vllm.entrypoints.cli.main import main as vllm_main @@ -14,8 +13,6 @@ def main(): has_port_arg = False has_gpu_memory_utilization_arg = False has_logits_processors_arg = False - has_block_size_arg = False - has_compilation_config = False model_path = None model_arg_indices = [] @@ -27,10 +24,6 @@ def main(): has_gpu_memory_utilization_arg = True if arg == "--logits-processors" or arg.startswith("--logits-processors="): has_logits_processors_arg = True - if arg == "--block-size" or arg.startswith("--block-size="): - has_block_size_arg = True - if arg == "--compilation-config" or arg.startswith("--compilation-config="): - has_compilation_config = True if arg == "--model": if i + 1 < len(args): model_path = args[i + 1] @@ -57,22 +50,6 @@ def main(): if (not has_logits_processors_arg) and custom_logits_processors: args.extend(["--logits-processors", "mineru_vl_utils:MinerULogitsProcessor"]) - # musa vllm v1 引擎特殊配置 - # device = get_device() - # if device.startswith("musa"): - # import torch - # if torch.musa.is_available(): - # if not has_block_size_arg: - # args.extend(["--block-size", "32"]) - # if not has_compilation_config: - # args.extend(["--compilation-config", '{"cudagraph_capture_sizes": [1,2,3,4,5,6,7,8,10,12,14,16,18,20,24,28,30], "simple_cuda_graph": true}']) - - # corex vllm v1 引擎特殊配置 - device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "") - if device_type.lower() == "corex": - if not has_compilation_config: - args.extend(["--compilation-config", '{"cudagraph_mode": "FULL_DECODE_ONLY", "level": 0}']) - # 重构参数,将模型路径作为位置参数 sys.argv = [sys.argv[0]] + ["serve", model_path] + args diff --git a/mineru/utils/block_sort.py b/mineru/utils/block_sort.py index b8857fc..23fafd2 100644 --- a/mineru/utils/block_sort.py +++ b/mineru/utils/block_sort.py @@ -186,22 +186,6 @@ def model_init(model_name: str): bf_16_support = True elif device_name.startswith("mps"): bf_16_support = True - elif device_name.startswith("gcu"): - if hasattr(torch, 'gcu') and torch.gcu.is_available(): - if torch.gcu.is_bf16_supported(): - bf_16_support = True - elif device_name.startswith("musa"): - if hasattr(torch, 'musa') and torch.musa.is_available(): - if torch.musa.is_bf16_supported(): - bf_16_support = True - elif device_name.startswith("npu"): - if hasattr(torch, 'npu') and torch.npu.is_available(): - if torch.npu.is_bf16_supported(): - bf_16_support = True - elif device_name.startswith("mlu"): - if hasattr(torch, 'mlu') and torch.mlu.is_available(): - if torch.mlu.is_bf16_supported(): - bf_16_support = True if model_name == 'layoutreader': # 检测modelscope的缓存目录是否存在 diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.py index 213db62..f6d013e 100644 --- a/mineru/utils/config_reader.py +++ b/mineru/utils/config_reader.py @@ -86,19 +86,7 @@ def get_device(): if torch_npu.npu.is_available(): return "npu" except Exception as e: - try: - if torch.gcu.is_available(): - return "gcu" - except Exception as e: - try: - if torch.musa.is_available(): - return "musa" - except Exception as e: - try: - if torch.mlu.is_available(): - return "mlu" - except Exception as e: - pass + pass return "cpu" diff --git a/mineru/utils/llm_aided.py b/mineru/utils/llm_aided.py index e8f7a53..03e669d 100644 --- a/mineru/utils/llm_aided.py +++ b/mineru/utils/llm_aided.py @@ -54,7 +54,7 @@ def llm_aided_title(page_info_list, title_aided_config): - 根据标题内容的语义为每个标题元素添加适当的层次结构 - 行高较大的标题一般是更高级别的标题 - 标题从前至后的层级必须是连续的,不能跳过层级 - - 标题层级最多为6级,不要添加过多的层级 + - 标题层级最多为4级,不要添加过多的层级 - 优化后的标题只保留代表该标题的层级的整数,不要保留其他信息 5. 合理性检查与微调: diff --git a/mineru/utils/magic_model_utils.py b/mineru/utils/magic_model_utils.py index f5e99bf..597d659 100644 --- a/mineru/utils/magic_model_utils.py +++ b/mineru/utils/magic_model_utils.py @@ -2,8 +2,6 @@ 包含两个MagicModel类中重复使用的方法和逻辑 """ from typing import List, Dict, Any, Callable - -from loguru import logger from mineru.utils.boxbase import bbox_distance, bbox_center_distance, is_in @@ -174,15 +172,11 @@ def tie_up_category_by_index( get_subjects_func: Callable, get_objects_func: Callable, extract_subject_func: Callable = None, - extract_object_func: Callable = None, - object_block_type: str = "object", + extract_object_func: Callable = None ): """ 基于index的类别关联方法,用于将主体对象与客体对象进行关联 - 客体优先匹配给index最接近的主体,匹配优先级为: - 1. index差值(最高优先级) - 2. bbox边缘距离(相邻边距离) - 3. bbox中心点距离(最低优先级,作为最终tiebreaker) + 客体优先匹配给index最接近的主体,index差值相同时使用bbox中心点距离作为tiebreaker 参数: get_subjects_func: 函数,提取主体对象 @@ -213,29 +207,6 @@ def tie_up_category_by_index( "sub_idx": i, } - # 提取所有客体的index集合,用于计算有效index差值 - object_indices = set(obj["index"] for obj in objects) - - def calc_effective_index_diff(obj_index: int, sub_index: int) -> int: - """ - 计算有效的index差值 - 有效差值 = 绝对差值 - 区间内其他客体的数量 - 即:如果obj_index和sub_index之间的差值是由其他客体造成的,则应该扣除这部分差值 - """ - if obj_index == sub_index: - return 0 - - start, end = min(obj_index, sub_index), max(obj_index, sub_index) - abs_diff = end - start - - # 计算区间(start, end)内有多少个其他客体的index - other_objects_count = 0 - for idx in range(start + 1, end): - if idx in object_indices: - other_objects_count += 1 - - return abs_diff - other_objects_count - # 为每个客体找到最匹配的主体 for obj in objects: if len(subjects) == 0: @@ -246,10 +217,10 @@ def tie_up_category_by_index( min_index_diff = float("inf") best_subject_indices = [] - # 找出有效index差值最小的所有主体 + # 找出index差值最小的所有主体 for i, subject in enumerate(subjects): sub_index = subject["index"] - index_diff = calc_effective_index_diff(obj_index, sub_index) + index_diff = abs(obj_index - sub_index) if index_diff < min_index_diff: min_index_diff = index_diff @@ -257,37 +228,18 @@ def tie_up_category_by_index( elif index_diff == min_index_diff: best_subject_indices.append(i) - if len(best_subject_indices) == 1: + # 如果有多个主体的index差值相同,使用中心点距离作为tiebreaker + if len(best_subject_indices) > 1: + min_center_dist = float("inf") best_subject_idx = best_subject_indices[0] - # 如果有多个主体的index差值相同(最多两个),根据边缘距离进行筛选 - elif len(best_subject_indices) == 2: - # 计算所有候选主体的边缘距离 - edge_distances = [(idx, bbox_distance(obj["bbox"], subjects[idx]["bbox"])) for idx in best_subject_indices] - edge_dist_diff = abs(edge_distances[0][1] - edge_distances[1][1]) - for idx, edge_dist in edge_distances: - logger.debug(f"Obj index: {obj_index}, Sub index: {subjects[idx]['index']}, Edge distance: {edge_dist}") - - if edge_dist_diff > 2: - # 边缘距离差值大于2,匹配边缘距离更小的主体 - best_subject_idx = min(edge_distances, key=lambda x: x[1])[0] - logger.debug(f"Obj index: {obj_index}, edge_dist_diff > 2, matching to subject with min edge distance, index: {subjects[best_subject_idx]['index']}") - elif object_block_type == "table_caption": - # 边缘距离差值<=2且为table_caption,匹配index更大的主体 - best_subject_idx = max(best_subject_indices, key=lambda idx: subjects[idx]["index"]) - logger.debug(f"Obj index: {obj_index}, edge_dist_diff <= 2 and table_caption, matching to later subject with index: {subjects[best_subject_idx]['index']}") - elif object_block_type.endswith("footnote"): - # 边缘距离差值<=2且为footnote,匹配index更小的主体 - best_subject_idx = min(best_subject_indices, key=lambda idx: subjects[idx]["index"]) - logger.debug(f"Obj index: {obj_index}, edge_dist_diff <= 2 and footnote, matching to earlier subject with index: {subjects[best_subject_idx]['index']}") - else: - # 边缘距离差值<=2 且不适用特殊匹配规则,使用中心点距离匹配 - center_distances = [(idx, bbox_center_distance(obj["bbox"], subjects[idx]["bbox"])) for idx in best_subject_indices] - for idx, center_dist in center_distances: - logger.debug(f"Obj index: {obj_index}, Sub index: {subjects[idx]['index']}, Center distance: {center_dist}") - best_subject_idx = min(center_distances, key=lambda x: x[1])[0] + for idx in best_subject_indices: + center_dist = bbox_center_distance(obj["bbox"], subjects[idx]["bbox"]) + if center_dist < min_center_dist: + min_center_dist = center_dist + best_subject_idx = idx else: - raise ValueError("More than two subjects have the same minimal index difference, which is unexpected.") + best_subject_idx = best_subject_indices[0] # 将客体添加到最佳主体的obj_bboxes中 result_dict[best_subject_idx]["obj_bboxes"].append(extract_object_func(obj)) diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.py index ccc01ec..5ce4be1 100644 --- a/mineru/utils/model_utils.py +++ b/mineru/utils/model_utils.py @@ -414,7 +414,7 @@ def get_res_list_from_layout_res(layout_res, iou_threshold=0.7, overlap_threshol def clean_memory(device='cuda'): - if str(device).startswith("cuda"): + if device == 'cuda': if torch.cuda.is_available(): torch.cuda.empty_cache() torch.cuda.ipc_collect() @@ -423,15 +423,6 @@ def clean_memory(device='cuda'): torch_npu.npu.empty_cache() elif str(device).startswith("mps"): torch.mps.empty_cache() - elif str(device).startswith("gcu"): - if torch.gcu.is_available(): - torch.gcu.empty_cache() - elif str(device).startswith("musa"): - if torch.musa.is_available(): - torch.musa.empty_cache() - elif str(device).startswith("mlu"): - if torch.mlu.is_available(): - torch.mlu.empty_cache() gc.collect() @@ -467,14 +458,5 @@ def get_vram(device) -> int: elif str(device).startswith("npu"): if torch_npu.npu.is_available(): total_memory = round(torch_npu.npu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB - elif str(device).startswith("gcu"): - if torch.gcu.is_available(): - total_memory = round(torch.gcu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB - elif str(device).startswith("musa"): - if torch.musa.is_available(): - total_memory = round(torch.musa.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB - elif str(device).startswith("mlu"): - if torch.mlu.is_available(): - total_memory = round(torch.mlu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB return total_memory diff --git a/mineru/utils/table_merge.py b/mineru/utils/table_merge.py index c445d03..b3c9e00 100644 --- a/mineru/utils/table_merge.py +++ b/mineru/utils/table_merge.py @@ -9,19 +9,13 @@ from mineru.utils.char_utils import full_to_half from mineru.utils.enum_class import BlockType, SplitFlag -CONTINUATION_END_MARKERS = [ +CONTINUATION_MARKERS = [ "(续)", "(续表)", "(续上表)", "(continued)", "(cont.)", "(cont’d)", - "(…continued)", - "续表", -] - -CONTINUATION_INLINE_MARKERS = [ - "(continued)", ] @@ -70,69 +64,6 @@ def calculate_table_total_columns(soup): return max_cols -def build_table_occupied_matrix(soup): - """构建表格的占用矩阵,返回每行的有效列数 - - Args: - soup: BeautifulSoup解析的表格 - - Returns: - dict: {row_idx: effective_columns} 每行的有效列数(考虑rowspan占用) - """ - rows = soup.find_all("tr") - if not rows: - return {} - - occupied = {} # {row_idx: {col_idx: True}} - row_effective_cols = {} # {row_idx: effective_columns} - - for row_idx, row in enumerate(rows): - col_idx = 0 - cells = row.find_all(["td", "th"]) - - if row_idx not in occupied: - occupied[row_idx] = {} - - for cell in cells: - # 找到下一个未被占用的列位置 - while col_idx in occupied[row_idx]: - col_idx += 1 - - colspan = int(cell.get("colspan", 1)) - rowspan = int(cell.get("rowspan", 1)) - - # 标记被这个单元格占用的所有位置 - for r in range(row_idx, row_idx + rowspan): - if r not in occupied: - occupied[r] = {} - for c in range(col_idx, col_idx + colspan): - occupied[r][c] = True - - col_idx += colspan - - # 该行的有效列数为已占用的最大列索引+1 - if occupied[row_idx]: - row_effective_cols[row_idx] = max(occupied[row_idx].keys()) + 1 - else: - row_effective_cols[row_idx] = 0 - - return row_effective_cols - - -def calculate_row_effective_columns(soup, row_idx): - """计算指定行的有效列数(考虑rowspan占用) - - Args: - soup: BeautifulSoup解析的表格 - row_idx: 行索引 - - Returns: - int: 该行的有效列数 - """ - row_effective_cols = build_table_occupied_matrix(soup) - return row_effective_cols.get(row_idx, 0) - - def calculate_row_columns(row): """ 计算表格行的实际列数,考虑colspan属性 @@ -182,10 +113,6 @@ def detect_table_headers(soup1, soup2, max_header_rows=5): rows1 = soup1.find_all("tr") rows2 = soup2.find_all("tr") - # 构建两个表格的有效列数矩阵 - effective_cols1 = build_table_occupied_matrix(soup1) - effective_cols2 = build_table_occupied_matrix(soup2) - min_rows = min(len(rows1), len(rows2), max_header_rows) header_rows = 0 headers_match = True @@ -203,24 +130,20 @@ def detect_table_headers(soup1, soup2, max_header_rows=5): if len(cells1) != len(cells2): structure_match = False else: - # 检查有效列数是否一致(考虑rowspan影响) - if effective_cols1.get(i, 0) != effective_cols2.get(i, 0): - structure_match = False - else: - # 然后检查单元格的属性和内容 - for cell1, cell2 in zip(cells1, cells2): - colspan1 = int(cell1.get("colspan", 1)) - rowspan1 = int(cell1.get("rowspan", 1)) - colspan2 = int(cell2.get("colspan", 1)) - rowspan2 = int(cell2.get("rowspan", 1)) + # 然后检查单元格的属性和内容 + for cell1, cell2 in zip(cells1, cells2): + colspan1 = int(cell1.get("colspan", 1)) + rowspan1 = int(cell1.get("rowspan", 1)) + colspan2 = int(cell2.get("colspan", 1)) + rowspan2 = int(cell2.get("rowspan", 1)) - # 去除所有空白字符(包括空格、换行、制表符等) - text1 = ''.join(full_to_half(cell1.get_text()).split()) - text2 = ''.join(full_to_half(cell2.get_text()).split()) + # 去除所有空白字符(包括空格、换行、制表符等) + text1 = ''.join(full_to_half(cell1.get_text()).split()) + text2 = ''.join(full_to_half(cell2.get_text()).split()) - if colspan1 != colspan2 or rowspan1 != rowspan2 or text1 != text2: - structure_match = False - break + if colspan1 != colspan2 or rowspan1 != rowspan2 or text1 != text2: + structure_match = False + break if structure_match: header_rows += 1 @@ -230,54 +153,7 @@ def detect_table_headers(soup1, soup2, max_header_rows=5): headers_match = header_rows > 0 # 只有当至少匹配了一行时,才认为表头匹配 break - # 如果严格匹配失败,尝试视觉一致性匹配(只比较文本内容) - if header_rows == 0: - header_rows, headers_match, header_texts = _detect_table_headers_visual(soup1, soup2, rows1, rows2, max_header_rows) - - return header_rows, headers_match, header_texts - - -def _detect_table_headers_visual(soup1, soup2, rows1, rows2, max_header_rows=5): - """ - 基于视觉一致性检测表头(只比较文本内容,忽略colspan/rowspan差异) - - Args: - soup1: 第一个表格的BeautifulSoup对象 - soup2: 第二个表格的BeautifulSoup对象 - rows1: 第一个表格的行列表 - rows2: 第二个表格的行列表 - max_header_rows: 最大可能的表头行数 - - Returns: - tuple: (表头行数, 表头是否一致, 表头文本列表) - """ - # 构建两个表格的有效列数矩阵 - effective_cols1 = build_table_occupied_matrix(soup1) - effective_cols2 = build_table_occupied_matrix(soup2) - - min_rows = min(len(rows1), len(rows2), max_header_rows) - header_rows = 0 - headers_match = True - header_texts = [] - - for i in range(min_rows): - cells1 = rows1[i].find_all(["td", "th"]) - cells2 = rows2[i].find_all(["td", "th"]) - - # 提取每行的文本内容列表(去除空白字符) - texts1 = [''.join(full_to_half(cell.get_text()).split()) for cell in cells1] - texts2 = [''.join(full_to_half(cell.get_text()).split()) for cell in cells2] - - # 检查视觉一致性:文本内容完全相同,且有效列数一致 - effective_cols_match = effective_cols1.get(i, 0) == effective_cols2.get(i, 0) - if texts1 == texts2 and effective_cols_match: - header_rows += 1 - row_texts = [full_to_half(cell.get_text().strip()) for cell in cells1] - header_texts.append(row_texts) - else: - headers_match = header_rows > 0 - break - + # 如果没有找到匹配的表头行,则返回失败 if header_rows == 0: headers_match = False @@ -287,32 +163,20 @@ def _detect_table_headers_visual(soup1, soup2, rows1, rows2, max_header_rows=5): def can_merge_tables(current_table_block, previous_table_block): """判断两个表格是否可以合并""" # 检查表格是否有caption和footnote - # 计算previous_table_block中的footnote数量 - footnote_count = sum(1 for block in previous_table_block["blocks"] if block["type"] == BlockType.TABLE_FOOTNOTE) # 如果有TABLE_CAPTION类型的块,检查是否至少有一个以"(续)"结尾 caption_blocks = [block for block in current_table_block["blocks"] if block["type"] == BlockType.TABLE_CAPTION] if caption_blocks: - # 检查是否至少有一个caption包含续表标识 - has_continuation_marker = False - for block in caption_blocks: - caption_text = full_to_half(merge_para_with_text(block).strip()).lower() - if ( - any(caption_text.endswith(marker.lower()) for marker in CONTINUATION_END_MARKERS) - or any(marker.lower() in caption_text for marker in CONTINUATION_INLINE_MARKERS) - ): - has_continuation_marker = True - break + # 如果所有caption都不以"(续)"、"(续表)"、"(continued)"或"(cont.)"结尾,则不合并 - # 如果所有caption都不包含续表标识,则不允许合并 - if not has_continuation_marker: + if not any( + any(full_to_half(merge_para_with_text(block).strip()).lower().endswith(marker.lower()) + for marker in CONTINUATION_MARKERS) + for block in caption_blocks + ): return False, None, None, None, None - # 如果current_table_block的caption存在续标识,放宽footnote的限制允许previous_table_block有最多一条footnote - if footnote_count > 1: - return False, None, None, None, None - else: - if footnote_count > 0: - return False, None, None, None, None + if any(block["type"] == BlockType.TABLE_FOOTNOTE for block in previous_table_block["blocks"]): + return False, None, None, None, None # 获取两个表格的HTML内容 current_html = "" @@ -362,44 +226,34 @@ def check_rows_match(soup1, soup2): if not (rows1 and rows2): return False - # 获取第一个表的最后一行数据行索引 - last_row_idx = None + # 获取第一个表的最后一行数据行 last_row = None - for idx in range(len(rows1) - 1, -1, -1): - if rows1[idx].find_all(["td", "th"]): - last_row_idx = idx - last_row = rows1[idx] + for row in reversed(rows1): + if row.find_all(["td", "th"]): + last_row = row break # 检测表头行数,以便获取第二个表的首个数据行 header_count, _, _ = detect_table_headers(soup1, soup2) # 获取第二个表的首个数据行 - first_data_row_idx = None first_data_row = None if len(rows2) > header_count: - first_data_row_idx = header_count first_data_row = rows2[header_count] # 第一个非表头行 if not (last_row and first_data_row): return False - # 计算有效列数(考虑rowspan和colspan) - last_row_effective_cols = calculate_row_effective_columns(soup1, last_row_idx) - first_row_effective_cols = calculate_row_effective_columns(soup2, first_data_row_idx) - - # 计算实际列数(仅考虑colspan)和视觉列数 + # 计算实际列数(考虑colspan)和视觉列数 last_row_cols = calculate_row_columns(last_row) first_row_cols = calculate_row_columns(first_data_row) last_row_visual_cols = calculate_visual_columns(last_row) first_row_visual_cols = calculate_visual_columns(first_data_row) - # logger.debug(f"行列数 - 前表最后一行: {last_row_cols}(有效列数:{last_row_effective_cols}, 视觉列数:{last_row_visual_cols}), 当前表首行: {first_row_cols}(有效列数:{first_row_effective_cols}, 视觉列数:{first_row_visual_cols})") + # logger.debug(f"行列数 - 前表最后一行: {last_row_cols}(视觉列数:{last_row_visual_cols}), 当前表首行: {first_row_cols}(视觉列数:{first_row_visual_cols})") - # 同时考虑有效列数匹配、实际列数匹配和视觉列数匹配 - return (last_row_effective_cols == first_row_effective_cols or - last_row_cols == first_row_cols or - last_row_visual_cols == first_row_visual_cols) + # 同时考虑实际列数匹配和视觉列数匹配 + return last_row_cols == first_row_cols or last_row_visual_cols == first_row_visual_cols def check_row_columns_match(row1, row2): @@ -416,13 +270,12 @@ def check_row_columns_match(row1, row2): return True -def adjust_table_rows_colspan(soup, rows, start_idx, end_idx, +def adjust_table_rows_colspan(rows, start_idx, end_idx, reference_structure, reference_visual_cols, target_cols, current_cols, reference_row): """调整表格行的colspan属性以匹配目标列数 Args: - soup: BeautifulSoup解析的表格对象(用于计算有效列数) rows: 表格行列表 start_idx: 起始行索引 end_idx: 结束行索引(不包含) @@ -434,21 +287,14 @@ def adjust_table_rows_colspan(soup, rows, start_idx, end_idx, """ reference_row_copy = deepcopy(reference_row) - # 构建有效列数矩阵 - effective_cols_matrix = build_table_occupied_matrix(soup) - for i in range(start_idx, end_idx): row = rows[i] cells = row.find_all(["td", "th"]) if not cells: continue - # 使用有效列数(考虑rowspan)判断是否需要调整 - current_row_effective_cols = effective_cols_matrix.get(i, 0) current_row_cols = calculate_row_columns(row) - - # 如果有效列数或实际列数已经达到目标,则跳过 - if current_row_effective_cols >= target_cols or current_row_cols >= target_cols: + if current_row_cols >= target_cols: continue # 检查是否与参考行结构匹配 @@ -460,12 +306,9 @@ def adjust_table_rows_colspan(soup, rows, start_idx, end_idx, cell["colspan"] = str(reference_structure[j]) else: # 扩展最后一个单元格以填补列数差异 - # 使用有效列数来计算差异 - cols_diff = target_cols - current_row_effective_cols - if cols_diff > 0: - last_cell = cells[-1] - current_last_span = int(last_cell.get("colspan", 1)) - last_cell["colspan"] = str(current_last_span + cols_diff) + last_cell = cells[-1] + current_last_span = int(last_cell.get("colspan", 1)) + last_cell["colspan"] = str(current_last_span + (target_cols - current_cols)) def perform_table_merge(soup1, soup2, previous_table_block, wait_merge_table_footnotes): @@ -496,7 +339,7 @@ def perform_table_merge(soup1, soup2, previous_table_block, wait_merge_table_foo reference_visual_cols = calculate_visual_columns(last_row1) # 以表1的最后一行为参考,调整表2的行 adjust_table_rows_colspan( - soup2, rows2, header_count, len(rows2), + rows2, header_count, len(rows2), reference_structure, reference_visual_cols, table_cols1, table_cols2, first_data_row2 ) @@ -506,7 +349,7 @@ def perform_table_merge(soup1, soup2, previous_table_block, wait_merge_table_foo reference_visual_cols = calculate_visual_columns(first_data_row2) # 以表2的第一个数据行为参考,调整表1的行 adjust_table_rows_colspan( - soup1, rows1, 0, len(rows1), + rows1, 0, len(rows1), reference_structure, reference_visual_cols, table_cols2, table_cols1, last_row1 ) @@ -520,11 +363,6 @@ def perform_table_merge(soup1, soup2, previous_table_block, wait_merge_table_foo row.extract() tbody1.append(row) - # 清空previous_table_block的footnote - previous_table_block["blocks"] = [ - block for block in previous_table_block["blocks"] - if block["type"] != BlockType.TABLE_FOOTNOTE - ] # 添加待合并表格的footnote到前一个表格中 for table_footnote in wait_merge_table_footnotes: temp_table_footnote = table_footnote.copy() @@ -585,4 +423,4 @@ def merge_table(page_info_list): # 删除当前页的table for block in current_table_block["blocks"]: block['lines'] = [] - block[SplitFlag.LINES_DELETED] = True + block[SplitFlag.LINES_DELETED] = True \ No newline at end of file diff --git a/mineru/version.py b/mineru/version.py index e617a4c..7a38ae0 100644 --- a/mineru/version.py +++ b/mineru/version.py @@ -1 +1 @@ -__version__ = "2.7.4" +__version__ = "2.7.1" diff --git a/scripts/build-images.sh b/scripts/build-images.sh index 7b2bde9..66f9660 100644 --- a/scripts/build-images.sh +++ b/scripts/build-images.sh @@ -2,7 +2,7 @@ set -euo pipefail ROOT_DIR=$(cd "$(dirname "$0")/.." && pwd) API_FLAVOR=${API_FLAVOR:-corex} -VERSION=${VERSION:-2.7.4} +VERSION=${VERSION:-2.7.1} [[ "$VERSION" =~ ^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$ ]] || exit 2 case "$API_FLAVOR" in corex) FILE=docker/china/Dockerfile.corex ;; @@ -12,4 +12,5 @@ esac exec docker build -f "$ROOT_DIR/$FILE" \ --label io.unis.component=parser --label io.unis.layout=refact --label "io.unis.gpu=$API_FLAVOR" \ --label "org.opencontainers.image.revision=$(git -C "$ROOT_DIR" rev-parse HEAD)" \ - -t "unis-mineru:$VERSION-$API_FLAVOR" -t "unis-mineru:$VERSION" "$ROOT_DIR" + -t "unis-mineru:$VERSION-$API_FLAVOR" -t "unis-mineru:$VERSION" \ + -t "unis-mindmap-api:$VERSION" -t "unis-mindmap-api:$API_FLAVOR" -t unis-mindmap-api:latest "$ROOT_DIR" diff --git a/scripts/check_parser_baseline.py b/scripts/check_parser_baseline.py new file mode 100644 index 0000000..095259e --- /dev/null +++ b/scripts/check_parser_baseline.py @@ -0,0 +1,46 @@ +"""Check the official parser tree; no model loading, DB, Redis or network.""" +import argparse +import ast +import hashlib +import json +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[1] + + +def check(root=ROOT, runtime=False): + manifest = json.loads((root / 'docs/mineru-migration/2.7.1-baseline.json').read_text(encoding='utf-8')) + package = root / 'mineru' + files = {p.relative_to(package).as_posix(): p for p in package.rglob('*') + if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc', '.pyo')} + if set(files) != set(manifest['source_hashes']): + raise ValueError('Parser file set differs from the official 2.7.1 baseline') + for name, path in files.items(): + if hashlib.sha256(path.read_bytes().replace(b'\r\n', b'\n')).hexdigest() != manifest['source_hashes'][name]: + raise ValueError('Parser source differs from official 2.7.1: ' + name) + module = ast.parse((package / 'version.py').read_text(encoding='utf-8')) + version = next(ast.literal_eval(n.value) for n in module.body if isinstance(n, ast.Assign) + and any(getattr(target, 'id', None) == '__version__' for target in n.targets)) + if version != '2.7.1' or len(files) != 187: + raise ValueError('Unexpected parser baseline version or file count') + result = {'version': version, 'official_files': len(files), 'kernel_modifications': 0} + if runtime: + import importlib.metadata as metadata + sys.path.insert(0, str(root)) + import mineru + from mineru.version import __version__ + if Path(mineru.__file__).resolve() != (package / '__init__.py').resolve() or __version__ != version: + raise ValueError('The imported parser does not match the local official baseline') + if metadata.version('mineru') != version: + raise ValueError('Installed MinerU metadata does not match the source version') + result['installed_version'] = version + result['source_path'] = str(package) + return result + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--runtime', action='store_true') + args = parser.parse_args() + print(json.dumps(check(runtime=args.runtime))) diff --git a/scripts/run_parser.py b/scripts/run_parser.py index f737af5..fa0eba4 100644 --- a/scripts/run_parser.py +++ b/scripts/run_parser.py @@ -1,7 +1,9 @@ """Start the pinned upstream parser; application features live in MaxKB.""" import os +import argparse from pathlib import Path import sys +from types import SimpleNamespace ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) @@ -12,18 +14,38 @@ def main(): os.environ.setdefault('MINERU_API_MAX_CONCURRENT_REQUESTS', '1') from mineru.version import __version__ from mineru import __file__ as module_path - if __version__ != '2.7.4' or not Path(module_path).resolve().is_relative_to(ROOT / 'mineru'): + if __version__ != '2.7.1' or not Path(module_path).resolve().is_relative_to(ROOT / 'mineru'): raise RuntimeError('解析服务版本或源码路径不匹配') - if not any(arg.startswith('--mineru-api-max-concurrent-requests') for arg in sys.argv): - sys.argv += ['--mineru-api-max-concurrent-requests', os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS']] - memory = os.getenv('MINERU_GPU_MEMORY_UTILIZATION') - if memory: - if not 0 < float(memory) < 1: - raise ValueError('MINERU_GPU_MEMORY_UTILIZATION must be between 0 and 1') - if not any(arg.startswith('--gpu-memory-utilization') for arg in sys.argv): - sys.argv += ['--gpu-memory-utilization', str(float(memory))] - from mineru.cli.fast_api import main as serve - serve() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--host', default='127.0.0.1') + parser.add_argument('--port', type=int, default=8000) + parser.add_argument('--mineru-api-max-concurrent-requests', type=int, + default=int(os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS'])) + parser.add_argument('--gpu-memory-utilization', type=float, + default=float(os.environ['MINERU_GPU_MEMORY_UTILIZATION']) + if os.getenv('MINERU_GPU_MEMORY_UTILIZATION') else None) + parser.add_argument('--reload', action='store_true') + args, engine_args = parser.parse_known_args() + if args.reload: + raise ValueError('解析服务使用单进程启动,请移除 --reload') + if args.mineru_api_max_concurrent_requests < 0: + raise ValueError('解析请求并发数不能小于 0') + if args.gpu_memory_utilization is not None and not 0 < args.gpu_memory_utilization < 1: + raise ValueError('MINERU_GPU_MEMORY_UTILIZATION must be between 0 and 1') + os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS'] = str(args.mineru_api_max_concurrent_requests) + # Official 2.7.1's CLI puts every extra flag in app.state.config. The API + # forwards that dict to vLLM, where API-only flags are invalid EngineArgs. + # Configure the unmodified upstream ASGI app and pass only engine options. + from mineru.utils.cli_parser import arg_parse + from mineru.cli.fast_api import app + normalized = [] + for value in engine_args: + normalized.extend(value.split('=', 1) if value.startswith('--') and '=' in value else [value]) + app.state.config = arg_parse(SimpleNamespace(args=normalized)) + if args.gpu_memory_utilization is not None: + app.state.config['gpu_memory_utilization'] = args.gpu_memory_utilization + import uvicorn + uvicorn.run(app, host=args.host, port=args.port) if __name__ == '__main__': diff --git a/tests/unittest/test_heading_levels.py b/tests/unittest/test_heading_levels.py index e84d4ae..6e1c2ae 100644 --- a/tests/unittest/test_heading_levels.py +++ b/tests/unittest/test_heading_levels.py @@ -1,4 +1,4 @@ -"""Heading post-processing checks; no OCR, model inference or external requests.""" +"""Official 2.7.1 heading behavior; the optional six-level patch is disabled.""" import copy import json from types import SimpleNamespace @@ -21,23 +21,23 @@ class HeadingLevelsTests(unittest.TestCase): def pages(self): return [{'page_idx': 0, 'page_size': [600, 800], 'para_blocks': self.blocks(), 'discarded_blocks': []}] - def test_both_output_backends_preserve_six_headings_in_markdown_and_metadata(self): + def test_both_output_backends_keep_the_official_four_level_limit(self): for converter in (pipeline, vlm): with self.subTest(converter=converter.__name__), patch.object(converter, 'detect_lang', return_value='en'): markdown = converter.union_make(copy.deepcopy(self.pages()), MakeMode.MM_MD) - self.assertEqual(markdown.split('\n\n'), [f'{"#" * i} Heading{i}' for i in range(1, 7)]) + self.assertEqual(markdown.split('\n\n'), [f'{"#" * min(i, 4)} Heading{i}' for i in range(1, 7)]) content = converter.union_make(copy.deepcopy(self.pages()), MakeMode.CONTENT_LIST) - self.assertEqual([item['text_level'] for item in content], list(range(1, 7))) + self.assertEqual([item['text_level'] for item in content], [1, 2, 3, 4, 4, 4]) content_v2 = vlm.union_make(self.pages(), MakeMode.CONTENT_LIST_V2) - self.assertEqual([item['content']['level'] for page in content_v2 for item in page], list(range(1, 7))) + self.assertEqual([item['content']['level'] for page in content_v2 for item in page], [1, 2, 3, 4, 4, 4]) def test_out_of_range_levels_still_produce_valid_markdown(self): for converter in (pipeline, vlm): self.assertEqual(converter.get_title_level({}), 1) - for value, expected in [(-1, 0), (0, 0), (5, 5), (6, 6), (7, 6), (99, 6)]: + for value, expected in [(-1, 0), (0, 0), (5, 4), (6, 4), (7, 4), (99, 4)]: self.assertEqual(converter.get_title_level({'level': value}), expected) - def test_assisted_title_prompt_allows_six_levels(self): + def test_assisted_title_prompt_keeps_the_official_four_level_limit(self): client = MagicMock() client.chat.completions.create.return_value = [SimpleNamespace(choices=[SimpleNamespace( delta=SimpleNamespace(content=json.dumps({str(i): i + 1 for i in range(6)})))])] @@ -45,8 +45,8 @@ class HeadingLevelsTests(unittest.TestCase): with patch.object(llm_aided, 'OpenAI', return_value=client), patch.object(pipeline, 'detect_lang', return_value='en'): llm_aided.llm_aided_title(pages, {'api_key': 'unused-test-value', 'base_url': 'https://example.invalid', 'model': 'test'}) instruction = client.chat.completions.create.call_args.kwargs['messages'][0]['content'] - self.assertIn('标题层级最多为6级', instruction) - self.assertNotIn('标题层级最多为4级', instruction) + self.assertIn('标题层级最多为4级', instruction) + self.assertNotIn('标题层级最多为6级', instruction) self.assertEqual([block['level'] for block in pages[0]['para_blocks']], list(range(1, 7))) diff --git a/tests/unittest/test_parser_baseline.py b/tests/unittest/test_parser_baseline.py new file mode 100644 index 0000000..156c52b --- /dev/null +++ b/tests/unittest/test_parser_baseline.py @@ -0,0 +1,92 @@ +"""Baseline and launcher checks requiring only Python's standard library.""" +import importlib.util +import json +import os +from pathlib import Path +import shutil +import sys +import tempfile +from types import ModuleType, SimpleNamespace +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] + + +def load(name, relative): + spec = importlib.util.spec_from_file_location(name, ROOT / relative) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +baseline = load('parser_baseline_check', 'scripts/check_parser_baseline.py') +launcher = load('parser_launch_check', 'scripts/run_parser.py') + + +class ParserBaselineTests(unittest.TestCase): + def test_entire_kernel_matches_the_official_271_package(self): + self.assertEqual(baseline.check(), {'version': '2.7.1', 'official_files': 187, 'kernel_modifications': 0}) + + def test_modified_or_extra_source_is_rejected(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + shutil.copytree(ROOT / 'mineru', root / 'mineru', ignore=shutil.ignore_patterns('__pycache__', '*.pyc')) + (root / 'docs/mineru-migration').mkdir(parents=True) + shutil.copyfile(ROOT / 'docs/mineru-migration/2.7.1-baseline.json', root / 'docs/mineru-migration/2.7.1-baseline.json') + source = root / 'mineru/version.py' + original = source.read_bytes() + source.write_bytes(original + b'\n# custom patch\n') + with self.assertRaisesRegex(ValueError, 'source differs'): + baseline.check(root) + source.write_bytes(original) + (root / 'mineru/retired_custom_api.py').write_text('') + with self.assertRaisesRegex(ValueError, 'file set differs'): + baseline.check(root) + + def launch(self, version='2.7.1', path=None, args=None, memory='0.5'): + package = ModuleType('mineru'); package.__file__ = str(path or ROOT / 'mineru/__init__.py') + release = ModuleType('mineru.version'); release.__version__ = version + api = ModuleType('mineru.cli.fast_api'); api.app = SimpleNamespace(state=SimpleNamespace()) + cli = ModuleType('mineru.utils.cli_parser') + cli.arg_parse = lambda ctx: {ctx.args[i][2:].replace('-', '_'): ctx.args[i + 1] for i in range(0, len(ctx.args), 2)} + server = ModuleType('uvicorn') + captured = {} + def run(app, **kwargs): + captured.update(config=app.state.config, server=kwargs, + concurrency=os.environ['MINERU_API_MAX_CONCURRENT_REQUESTS']) + server.run = run + with patch.dict(sys.modules, {'mineru': package, 'mineru.version': release, 'mineru.cli.fast_api': api, + 'mineru.utils.cli_parser': cli, 'uvicorn': server}), \ + patch.dict(os.environ, {'MINERU_GPU_MEMORY_UTILIZATION': memory, 'MINERU_API_MAX_CONCURRENT_REQUESTS': '1'}, clear=True), \ + patch.object(sys, 'argv', ['run_parser.py', *(args or [])]): + launcher.main() + return captured + + def test_deployment_options_are_forwarded_without_kernel_patches(self): + args = self.launch() + self.assertEqual(args['concurrency'], '1') + self.assertEqual(args['config'], {'gpu_memory_utilization': 0.5}) + explicit = self.launch(args=['--gpu-memory-utilization=0.4']) + self.assertEqual(explicit['config'], {'gpu_memory_utilization': 0.4}) + + def test_api_flags_never_leak_into_vllm_engine_arguments(self): + result = self.launch(args=['--host', '0.0.0.0', '--port', '8100', + '--mineru-api-max-concurrent-requests=2', '--tensor-parallel-size=2']) + self.assertEqual(result['server'], {'host': '0.0.0.0', 'port': 8100}) + self.assertEqual(result['concurrency'], '2') + self.assertEqual(result['config'], {'tensor_parallel_size': '2', 'gpu_memory_utilization': 0.5}) + + def test_wrong_version_or_import_path_is_rejected(self): + for kwargs in ({'version': '2.7.4'}, {'path': ROOT / 'other/mineru/__init__.py'}): + with self.subTest(kwargs=kwargs), self.assertRaises(RuntimeError): + self.launch(**kwargs) + + def test_invalid_memory_limit_is_rejected(self): + for value in ('0', '1', 'invalid'): + with self.subTest(value=value), self.assertRaises(ValueError): + self.launch(memory=value) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/tests/unittest/test_parser_protocol.py b/tests/unittest/test_parser_protocol.py new file mode 100644 index 0000000..fe1cfcb --- /dev/null +++ b/tests/unittest/test_parser_protocol.py @@ -0,0 +1,49 @@ +"""Real upstream FastAPI protocol with inference mocked; no GPU or model requests.""" +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from fastapi.testclient import TestClient +from mineru.cli import fast_api + + +class ParserProtocolTests(unittest.TestCase): + def test_official_routes_do_not_restore_retired_application_features(self): + with TestClient(fast_api.app) as client: + schema = client.get('/openapi.json').json() + self.assertIn('/file_parse', schema['paths']) + self.assertNotIn('/api/file_parse', schema['paths']) + self.assertFalse(any('organize' in path or 'mindmap' in path for path in schema['paths'])) + + def test_pipeline_response_matches_maxkb_markdown_middle_json_and_images_contract(self): + async def infer(**kwargs): + for name in kwargs['pdf_file_names']: + output = Path(kwargs['output_dir']) / name / kwargs['parse_method'] + (output / 'images').mkdir(parents=True) + (output / (name + '.md')).write_text('# CODEX 271 protocol\n\n![image](images/test.jpg)', encoding='utf-8') + (output / (name + '_middle.json')).write_text(json.dumps({'pdf_info': [{'page_idx': 0, 'para_blocks': []}]}), encoding='utf-8') + (output / 'images/test.jpg').write_bytes(b'isolated-test-image') + with tempfile.TemporaryDirectory() as folder, \ + patch.object(fast_api, 'aio_do_parse', side_effect=infer), \ + patch.object(fast_api, 'guess_suffix_by_path', return_value='pdf'), \ + patch.object(fast_api, 'read_fn', return_value=b'isolated-pdf'), \ + TestClient(fast_api.app) as client: + response = client.post('/file_parse', files={'files': ('CODEX_271_PROTOCOL.pdf', b'%PDF-test', 'application/pdf')}, + data={'backend': 'pipeline', 'parse_method': 'auto', 'output_dir': folder, + 'return_md': 'true', 'return_middle_json': 'true', 'return_images': 'true', + 'response_format_zip': 'false'}) + self.assertEqual(response.status_code, 200, response.text[:300]) + payload = response.json() + self.assertEqual(payload['version'], '2.7.1') + self.assertEqual(payload['backend'], 'pipeline') + self.assertEqual(len(payload['results']), 1) + result = next(iter(payload['results'].values())) + self.assertIn('# CODEX 271 protocol', result['md_content']) + self.assertEqual(json.loads(result['middle_json'])['pdf_info'][0]['page_idx'], 0) + self.assertTrue(result['images']['test.jpg'].startswith('data:image/jpeg;base64,')) + + +if __name__ == '__main__': + unittest.main(verbosity=2)