Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
ci: add PR gates and separate optional backend tests
myhloli235fb8e5eded
diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.ymlindex 8df06552..2bbe78cb 100644--- a/.github/workflows/cli.yml+++ b/.github/workflows/cli.yml@@ -1,20 +1,75 @@-# This workflow will install Python dependencies, run tests and lint with a variety of Python versions-# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python-name: mineru-cli-test+on:push:- branches:- - "master"- - "dev"- paths-ignore:- - "cmds/**"- - "**.md"+ branches: [master, dev]+ pull_request:+ branches: [master, dev]+ workflow_dispatch:+ workflow_call:++permissions:+ contents: read++concurrency:+ group: cli-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && startsWith(github.ref, 'refs/heads/')) }}++env:+ PYTHONUTF8: '1'+jobs:- cli-test:+ changes:+ # fork 保持跳过;来自 fork 的上游 PR 仍在上游仓库执行只读测试。if: github.repository == 'opendatalab/MinerU'+ runs-on: ubuntu-latest+ timeout-minutes: 5+ outputs:+ code: ${{ steps.changes.outputs.code }}+ steps:+ - uses: actions/checkout@v6+ with:+ ref: ${{ github.sha }}+ fetch-depth: 2+ persist-credentials: false+ - uses: actions/setup-python@v6+ with:+ python-version: '3.12'+ - id: changes+ run: python scripts/ci/changes.py++ lint:+ needs: changes+ if: needs.changes.outputs.code == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@v6+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-python@v6+ with:+ python-version: '3.11'+ - uses: astral-sh/setup-uv@v7+ - name: Install lightweight check tools+ run: |+ uv venv+ uv pip install ruff==0.14.2 pytest packaging+ - name: Check Python and CI helpers+ run: |+ uv run --no-project --no-sync python -m compileall -q mineru scripts tests+ # 存量注解问题分批治理;全仓先阻止语法错误及未定义名称。+ uv run --no-project --no-sync ruff check --select E9,F63,F7,F82 mineru scripts tests+ uv run --no-project --no-sync ruff check scripts/ci tests/ci+ uv run --no-project --no-sync ruff format --check scripts/ci tests/ci+ uv run --no-project --no-sync python -m pytest -o addopts='' --confcutdir=tests/ci tests/ci++ cli-test:+ needs: changes+ if: needs.changes.outputs.code == 'true'runs-on: ${{ matrix.os }}- timeout-minutes: 240+ timeout-minutes: 30strategy:fail-fast: falsematrix:@@ -23,60 +78,110 @@ jobs:defaults:run:shell: bash- env:- PYTHONUTF8: '1'-steps:- - name: PDF cli- uses: actions/checkout@v6+ - uses: actions/checkout@v6with:- fetch-depth: 2-- - name: Set up Python- uses: actions/setup-python@v6+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-python@v6with:python-version: ${{ matrix.python }}-- - name: install uv- uses: astral-sh/setup-uv@v7-+ - uses: astral-sh/setup-uv@v7+ - uses: actions/setup-node@v6+ if: runner.os == 'Linux'+ with:+ node-version: '22'- name: Install and check dependenciesrun: |- uv --versionuv venv --python "$(python -c 'import sys; print(sys.executable)')"- uv pip install '.[test]'+ uv pip install --only-binary=docvortex '.[test]'uv pip check-- - name: Check Python syntax- run: uv run --no-project --no-sync python -m compileall -q mineru scripts tests-- name: Run Linux unit tests- if: runner.os == 'Linux' && matrix.python != '3.12'- run: uv run --no-project --no-sync python -m pytest -o addopts='' tests/unittest-- - name: Run Linux unit tests with coverage- if: runner.os == 'Linux' && matrix.python == '3.12'+ if: runner.os == 'Linux'run: |- uv run --no-project --no-sync python tests/clean_coverage.py- # 统一使用 pytest-cov 采集覆盖率,避免叠加启动 coverage 采集器。- uv run --no-project --no-sync python -m pytest tests/unittest- uv run --no-project --no-sync python tests/get_coverage.py-+ command -v jq >/dev/null || { sudo apt-get update && sudo apt-get install -y --no-install-recommends jq; }+ coverage=()+ if [[ '${{ matrix.python }}' == '3.12' ]]; then+ coverage=(--cov=mineru --cov-report=term:skip-covered --cov-report=xml:build/ci/coverage.xml --cov-precision=2 --cov-fail-under=58)+ fi+ uv run --no-project --no-sync python -m pytest -o addopts='' --strict-markers \+ -m 'not torch' --durations=30 --junitxml=build/ci/tests.xml "${coverage[@]}" tests/unittest- name: Run Windows and macOS public contract testsif: runner.os != 'Linux'run: |- uv run --no-project --no-sync python -m pytest -o addopts='' \+ uv run --no-project --no-sync python -m pytest -o addopts='' --strict-markers \+ --durations=30 --junitxml=build/ci/tests.xml \tests/unittest/test_docvortex_import_boundary.py \tests/unittest/test_backend_architecture.py \tests/unittest/test_docvortex_protocol.py \tests/unittest/test_docvortex_routing.py \tests/unittest/test_parser_api_contract.py+ - name: Retain test reports+ if: ${{ always() }}+ uses: actions/upload-artifact@v6+ with:+ name: tests-${{ matrix.os }}-py${{ matrix.python }}+ path: build/ci/*.xml+ retention-days: 14+ if-no-files-found: warn++ torch-test:+ needs: changes+ if: needs.changes.outputs.code == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@v6+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-python@v6+ with:+ python-version: '3.12'+ - uses: astral-sh/setup-uv@v7+ with:+ cache-suffix: torch-cpu+ - name: Install CPU Torch test dependencies+ run: |+ uv venv+ # 先安装 CPU wheel,宿主求解复用已安装的兼容版本,避免下载 CUDA 运行时。+ uv pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu+ uv pip install --only-binary=docvortex '.[test,torch]'+ uv pip check+ uv run --no-project --no-sync python -c 'import torch, torchvision, transformers; assert torch.version.cuda is None'+ - name: Run Torch regressions+ run: |+ uv run --no-project --no-sync python -m pytest -o addopts='' --strict-markers \+ -m 'torch and not accelerator' --durations=30 --junitxml=build/ci/torch.xml tests/unittest+ - name: Retain Torch test report+ if: ${{ always() }}+ uses: actions/upload-artifact@v6+ with:+ name: tests-torch-cpu+ path: build/ci/torch.xml+ retention-days: 14+ if-no-files-found: warn-# notify_to_feishu:-# if: ${{ always() && !cancelled() && contains(needs.*.result, 'failure')}}-# needs: cli-test-# runs-on: ubuntu-latest-# steps:-# - name: notify-# run: |-# curl -X POST -H "Content-Type: application/json" -d '{"msg_type":"post","content":{"post":{"zh_cn":{"title":"'${{ github.repository }}' GitHubAction Failed","content":[[{"tag":"text","text":""},{"tag":"a","text":"Please click here for details ","href":"https://github.com/'${{ github.repository }}'/actions/runs/'${GITHUB_RUN_ID}'"}]]}}}}' ${{ secrets.FEISHU_WEBHOOK_URL }}+ ci-result:+ name: CI result+ needs: [changes, lint, cli-test, torch-test]+ if: ${{ always() && github.repository == 'opendatalab/MinerU' }}+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - name: Require all applicable checks+ env:+ CHANGES_RESULT: ${{ needs.changes.result }}+ CODE_CHANGED: ${{ needs.changes.outputs.code }}+ LINT_RESULT: ${{ needs.lint.result }}+ TEST_RESULT: ${{ needs.cli-test.result }}+ TORCH_RESULT: ${{ needs.torch-test.result }}+ run: |+ test "$CHANGES_RESULT" = success+ if [[ "$CODE_CHANGED" == true ]]; then+ test "$LINT_RESULT" = success+ test "$TEST_RESULT" = success+ test "$TORCH_RESULT" = success+ else+ test "$CODE_CHANGED" = false+ fidiff --git a/.github/workflows/docvortex-boundary.yml b/.github/workflows/docvortex-boundary.ymldeleted file mode 100644index dc17c3fc..00000000--- a/.github/workflows/docvortex-boundary.yml+++ /dev/null@@ -1,270 +0,0 @@-name: DocVortex boundary integration--on:- workflow_dispatch:- inputs:- docvortex-wheel-url:- description: Native ABI3 DocVortex wheel URL; mutually exclusive with docvortex-ref- required: false- type: string- docvortex-ref:- description: SHA or ref of myhloli/DocVortex to build; mutually exclusive with wheel URL- required: false- type: string- utils-wheel-url:- description: Optional mineru-vl-utils 2.0.1+ wheel URL for unpublished dependency validation- required: false- type: string--permissions:- contents: read--env:- PYTHONUTF8: '1'- DOCVORTEX_PDF_RENDER_BACKEND: legacy--jobs:- integration:- strategy:- fail-fast: false- matrix:- os: [ubuntu-latest, windows-latest, macos-latest]- python: ['3.11', '3.12', '3.13', '3.14']- runs-on: ${{ matrix.os }}- defaults:- run:- shell: bash- steps:- - uses: actions/checkout@v6- - uses: actions/setup-python@v6- with:- python-version: ${{ matrix.python }}- - uses: astral-sh/setup-uv@v7- - name: Validate mutually exclusive engine inputs- env:- DOCVORTEX_WHEEL_URL: ${{ inputs.docvortex-wheel-url }}- DOCVORTEX_REF: ${{ inputs.docvortex-ref }}- run: |- python - <<'PY'- import os- # 必须指定一种引擎来源,不能在输入缺失时回退到索引版本。- wheel = os.environ["DOCVORTEX_WHEEL_URL"].strip()- ref = os.environ["DOCVORTEX_REF"].strip()- if bool(wheel) == bool(ref):- raise SystemExit("Provide exactly one of docvortex-wheel-url or docvortex-ref")- if ref and (ref != os.environ["DOCVORTEX_REF"] or any(char.isspace() for char in ref)):- raise SystemExit("docvortex-ref must be a SHA or Git ref without whitespace")- PY- - name: Checkout selected engine revision- if: ${{ inputs.docvortex-ref != '' }}- uses: actions/checkout@v6- with:- repository: myhloli/DocVortex- ref: ${{ inputs.docvortex-ref }}- path: .boundary/docvortex-src- persist-credentials: false- - name: Read the selected revision's Rust toolchain- if: ${{ inputs.docvortex-ref != '' }}- id: rust-version- run: |- python - <<'PY'- import os- from pathlib import Path- import re- # 使用引擎所声明的工具链,只提取构建所需的 channel 字段。- text = Path(".boundary/docvortex-src/rust-toolchain.toml").read_text(encoding="utf-8")- match = re.search(r'^\s*channel\s*=\s*["\']([A-Za-z0-9][A-Za-z0-9.+-]*)["\']', text, re.MULTILINE)- if match is None:- raise SystemExit("Selected DocVortex revision must declare a Rust toolchain channel")- with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as output:- output.write(f"toolchain={match.group(1)}\n")- PY- - name: Install matching Rust toolchain- if: ${{ inputs.docvortex-ref != '' }}- uses: dtolnay/rust-toolchain@stable- with:- toolchain: ${{ steps.rust-version.outputs.toolchain }}- - name: Build the selected native wheel- if: ${{ inputs.docvortex-ref != '' }}- run: |- uv build --wheel --python "$(python -c 'import sys; print(sys.executable)')" \- --out-dir "$GITHUB_WORKSPACE/.boundary/wheelhouse" .boundary/docvortex-src- - name: Download the supplied engine wheel- if: ${{ inputs.docvortex-wheel-url != '' }}- env:- DOCVORTEX_WHEEL_URL: ${{ inputs.docvortex-wheel-url }}- run: |- python -m pip download --no-deps --only-binary=:all: \- --dest .boundary/wheelhouse "$DOCVORTEX_WHEEL_URL"- - name: Freeze the exact native artifact- env:- DOCVORTEX_REF: ${{ inputs.docvortex-ref }}- run: |- python - <<'PY'- import hashlib- import json- import os- from pathlib import Path- import subprocess- from zipfile import ZipFile- # URL 与源码构建统一为一个本地 wheel,安装前拒绝纯 Python 或非 ABI3 产物。- wheels = list(Path(".boundary/wheelhouse").glob("*.whl"))- assert len(wheels) == 1, wheels- wheel = wheels[0].resolve()- with ZipFile(wheel) as archive:- metadata = [name for name in archive.namelist() if name.endswith(".dist-info/WHEEL")]- assert len(metadata) == 1, metadata- tags = [line for line in archive.read(metadata[0]).decode().splitlines() if line.startswith("Tag:")]- assert tags and all("-abi3-" in tag for tag in tags), tags- assert any(name.startswith("docvortex/_native") and name.endswith((".so", ".pyd")) for name in archive.namelist())- ref = os.environ["DOCVORTEX_REF"]- record = {- "source": "ref" if ref else "wheel-url",- "requested_ref": ref or None,- "resolved_commit": subprocess.check_output(["git", "-C", ".boundary/docvortex-src", "rev-parse", "HEAD"], text=True).strip() if ref else None,- "host_commit": os.environ["GITHUB_SHA"],- "wheel": str(wheel),- "wheel_sha256": hashlib.sha256(wheel.read_bytes()).hexdigest(),- "wheel_tags": tags,- }- Path(".boundary/engine-artifact.json").write_text(json.dumps(record, indent=2), encoding="utf-8")- with Path(os.environ["GITHUB_ENV"]).open("a", encoding="utf-8") as output:- output.write(f"DOCVORTEX_WHEEL={wheel}\n")- PY- - name: Install matching engine wheel and host- env:- UTILS_WHEEL_URL: ${{ inputs.utils-wheel-url }}- run: |- uv venv --python "$(python -c 'import sys; print(sys.executable)')"- packages=("$DOCVORTEX_WHEEL" '.[test]' psutil)- if [[ -n "$UTILS_WHEEL_URL" ]]; then packages+=("$UTILS_WHEEL_URL"); fi- # 单次求解固定引擎产物,避免安装宿主时换成索引中的另一个 DocVortex。- uv pip install "${packages[@]}"- uv pip check- - name: Verify installed native ABI3 provenance and protocol- run: |- if [[ -f .venv/Scripts/activate ]]; then source .venv/Scripts/activate; else source .venv/bin/activate; fi- python -I - <<'PY'- import hashlib- import importlib.metadata- import json- from pathlib import Path- import sysconfig- from urllib.parse import urlsplit- from urllib.request import url2pathname- from zipfile import ZipFile- import docvortex- import docvortex._native as native- import mineru- from docvortex._compute_backend import backend_info- # 隔离导入必须来自已安装 wheel 的 site-packages,而非两个源码 checkout。- site_roots = {Path(sysconfig.get_paths()[name]).resolve() for name in ("purelib", "platlib")}- origins = {"docvortex": Path(docvortex.__file__).resolve(), "native": Path(native.__file__).resolve(), "mineru": Path(mineru.__file__).resolve()}- for name, path in origins.items():- assert any(path.is_relative_to(root) for root in site_roots), (name, path, site_roots)- info = backend_info()- assert info["backend"] == "rust", info- assert native.PROTOCOL_VERSION >= 15 and info["protocol"] == native.PROTOCOL_VERSION, info- assert info["extension_sha256"] == hashlib.sha256(origins["native"].read_bytes()).hexdigest(), info- artifact = json.loads(Path(".boundary/engine-artifact.json").read_text(encoding="utf-8"))- distribution = importlib.metadata.distribution("docvortex")- provenance = json.loads(distribution.read_text("direct_url.json") or "{}")- def stream_hash(stream, algorithm="sha256"):- """分块校验完整文件内容,避免原生扩展或字体资源引入大块临时分配。"""- fingerprint = hashlib.new(algorithm)- for chunk in iter(lambda: stream.read(1024 * 1024), b""):- fingerprint.update(chunk)- return fingerprint.hexdigest()-- wheel = Path(artifact["wheel"]).resolve(strict=True)- direct_url = urlsplit(provenance.get("url", ""))- assert direct_url.scheme == "file" and direct_url.netloc in ("", "localhost"), provenance- assert not direct_url.query and not direct_url.fragment, provenance- installed_from = Path(url2pathname(direct_url.path)).resolve(strict=True)- assert installed_from == wheel, (installed_from, wheel)- with wheel.open("rb") as stream:- assert stream_hash(stream) == artifact["wheel_sha256"], artifact- # uv 的本地 wheel direct_url 允许 archive_info 为空;有声明摘要仍逐一验证。- archive_info = provenance.get("archive_info", {})- declared_hashes = dict(archive_info.get("hashes", {}))- if archive_info.get("hash"):- algorithm, value = archive_info["hash"].split("=", 1)- assert algorithm not in declared_hashes or declared_hashes[algorithm] == value, archive_info- declared_hashes[algorithm] = value- for algorithm, expected in declared_hashes.items():- with wheel.open("rb") as stream:- assert stream_hash(stream, algorithm) == expected.lower(), (algorithm, archive_info)- # 独立比较归档与实际安装的每个包文件,覆盖代码、资源和原生扩展;不依赖 RECORD。- package_root = origins["docvortex"].parent- verified_paths = set()- payload_fingerprint = hashlib.sha256()- matched_package_files = matched_metadata_files = 0- with ZipFile(wheel) as archive:- package_entries = [entry for entry in archive.infolist() if not entry.is_dir() and entry.filename.startswith("docvortex/")]- metadata_entries = [entry for entry in archive.infolist() if entry.filename.endswith(".dist-info/METADATA")]- assert package_entries and len(metadata_entries) == 1, (len(package_entries), len(metadata_entries))- entries = sorted(package_entries + metadata_entries, key=lambda entry: entry.filename)- assert len({entry.filename for entry in entries}) == len(entries), "Duplicate wheel payload paths"- for entry in entries:- installed = Path(distribution.locate_file(entry.filename)).resolve(strict=True)- assert any(installed.is_relative_to(root) for root in site_roots), installed- if entry.filename.startswith("docvortex/"):- assert installed.is_relative_to(package_root), installed- matched_package_files += 1- else:- matched_metadata_files += 1- with archive.open(entry) as expected_stream, installed.open("rb") as installed_stream:- expected_hash = stream_hash(expected_stream)- assert stream_hash(installed_stream) == expected_hash, (entry.filename, installed)- verified_paths.add(installed)- payload_fingerprint.update(entry.filename.encode("utf-8") + b"\0" + expected_hash.encode("ascii") + b"\n")- assert origins["docvortex"] in verified_paths and origins["native"] in verified_paths, origins- with wheel.open("rb") as stream:- assert stream_hash(stream) == artifact["wheel_sha256"], "Wheel changed during payload verification"- payload_verification = {- "direct_url_matches_frozen_wheel": True,- "frozen_wheel_sha256_verified": artifact["wheel_sha256"],- "declared_archive_hashes_verified": declared_hashes,- "matched_package_files": matched_package_files,- "matched_metadata_files": matched_metadata_files,- "loaded_native_extension_verified": True,- "verified_payload_sha256": payload_fingerprint.hexdigest(),- "scope": "All wheel docvortex/ files plus METADATA; installer-rewritten RECORD and generated pyc excluded",- }- wheel_metadata = distribution.read_text("WHEEL") or ""- assert any(line.startswith("Tag:") and "-abi3-" in line for line in wheel_metadata.splitlines())- record = {"versions": {name: importlib.metadata.version(name) for name in ("docvortex", "mineru")}, "origins": {name: str(path) for name, path in origins.items()}, "compute": info, "artifact": artifact, "payload_verification": payload_verification}- Path(".boundary/installed-contract.json").write_text(json.dumps(record, indent=2), encoding="utf-8")- print(json.dumps(record, indent=2))- PY- - name: Verify public contracts and deterministic inference replay- run: |- if [[ -f .venv/Scripts/activate ]]; then source .venv/Scripts/activate; else source .venv/bin/activate; fi- python -I -m pytest -q -o addopts='' -o pythonpath=tests/unittest --import-mode=importlib \- tests/unittest/test_docvortex_import_boundary.py \- tests/unittest/test_backend_architecture.py \- tests/unittest/test_docvortex_protocol.py \- tests/unittest/test_docvortex_routing.py \- tests/unittest/test_pdf_text_styles.py \- tests/unittest/test_pdf_analyze_block_content.py \- tests/unittest/test_native_pdf_table_pipeline.py \- tests/unittest/test_pdf_analyze_visual_blocks.py \- tests/unittest/test_pdf_model_inputs.py \- tests/unittest/test_pdf_cpu_reuse.py \- tests/unittest/test_pdf_memory_lifecycle.py \- tests/unittest/test_pdf_render_session_integration.py \- tests/unittest/test_pdf_window_snapshots.py \- tests/unittest/test_native_span_assignment.py \- tests/unittest/test_flash_pdf_render_scheduling.py \- tests/unittest/test_opencv_boundaries.py \- tests/unittest/test_process_heap_memory.py- - name: Retain exact wheel and installation evidence- if: ${{ always() }}- uses: actions/upload-artifact@v6- with:- name: docvortex-boundary-${{ matrix.os }}-py${{ matrix.python }}- path: |- .boundary/wheelhouse/*.whl- .boundary/engine-artifact.json- .boundary/installed-contract.json- if-no-files-found: warndiff --git a/.github/workflows/mkdocs.yml b/.github/workflows/mkdocs.ymlindex eaff3e01..b7c052c2 100644--- a/.github/workflows/mkdocs.yml+++ b/.github/workflows/mkdocs.yml@@ -2,68 +2,91 @@ name: Docson:push:- branches:- - "master"- - "dev"- - "next"+ branches: [master, dev, next]pull_request:+permissions:+ contents: read++concurrency:+ group: docs-${{ github.event.pull_request.number || github.ref }}+ # 正式发布不在推送途中被取消;PR 和开发分支只保留最新检查。+ cancel-in-progress: ${{ github.ref != 'refs/heads/master' }}+jobs:docs-build-check:name: Docs build check (no deploy)runs-on: ubuntu-latest+ timeout-minutes: 10+ outputs:+ changed: ${{ steps.changes.outputs.docs }}steps:- - name: Checkout- uses: actions/checkout@v6- - name: Install script test tools- run: sudo apt-get update && sudo apt-get install -y --no-install-recommends jq- - name: Set up Python- uses: actions/setup-python@v6+ - uses: actions/checkout@v6+ with:+ ref: ${{ github.sha }}+ fetch-depth: 2+ persist-credentials: false+ - uses: actions/setup-python@v6+ with:+ python-version: '3.12'+ - name: Determine whether docs changed+ id: changes+ run: python scripts/ci/changes.py+ - uses: astral-sh/setup-uv@v7+ if: steps.changes.outputs.docs == 'true'with:- python-version: "3.12"- - name: Install project and docs dependencies+ cache-dependency-glob: docs/requirements.txt+ - name: Install docs dependencies+ if: steps.changes.outputs.docs == 'true'run: |- python -m pip install --upgrade pip- python -m pip install -e .- python -m pip install -r docs/requirements.txt pytest- - name: Run HTTP example script tests- run: python -m pytest -q -o addopts= tests/unittest/test_http_api_example_script.py+ uv venv+ uv pip install -r docs/requirements.txt- name: Build docs (strict)- run: python -m mkdocs build --strict+ if: steps.changes.outputs.docs == 'true'+ run: uv run --no-project --no-sync python -m mkdocs build --strict+ - name: Retain the verified site+ if: >-+ steps.changes.outputs.docs == 'true' && github.event_name == 'push' &&+ github.ref == 'refs/heads/master' && github.repository == 'opendatalab/MinerU'+ uses: actions/upload-artifact@v6+ with:+ name: docs-site+ path: site/+ include-hidden-files: true+ if-no-files-found: error+ retention-days: 7docs-publish:name: Publish docs to GitHub Pagesneeds: docs-build-checkif: >-- github.event_name == 'push' &&- github.ref == 'refs/heads/master' &&- github.repository == 'opendatalab/MinerU'+ needs.docs-build-check.outputs.changed == 'true' && github.event_name == 'push' &&+ github.ref == 'refs/heads/master' && github.repository == 'opendatalab/MinerU'runs-on: ubuntu-latest- permissions:- contents: write+ timeout-minutes: 10concurrency:group: docs-gh-pagescancel-in-progress: falsesteps:- - name: Checkout- uses: actions/checkout@v6- - name: Set up Python- uses: actions/setup-python@v6- with:- python-version: "3.12"- - name: Install docs dependencies- run: |- python -m pip install --upgrade pip- python -m pip install -r docs/requirements.txt- name: Require release tokenenv:RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}run: |if [ -z "$RELEASE_TOKEN" ]; then- echo "RELEASE_TOKEN is empty; refusing to degrade publishing into a build-only step." >&2+ echo "RELEASE_TOKEN is empty; refusing to skip publishing." >&2exit 1fi- - name: Publish to GitHub Pages- env:- GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}- run: python -m mkdocs gh-deploy --force+ - uses: actions/checkout@v6+ with:+ ref: ${{ github.sha }}+ token: ${{ secrets.RELEASE_TOKEN }}+ - uses: actions/download-artifact@v7+ with:+ name: docs-site+ path: site+ - uses: actions/setup-python@v6+ with:+ python-version: '3.12'+ - uses: astral-sh/setup-uv@v7+ - name: Publish the verified site without rebuilding+ run: uvx --from ghp-import==2.1.0 ghp-import -n -p -f sitediff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.ymlindex 8c556d54..a70631d3 100644--- a/.github/workflows/python-package.yml+++ b/.github/workflows/python-package.yml@@ -1,6 +1,3 @@-# This workflow will install Python dependencies, run tests and lint with a variety of Python versions-# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python-name: Python packageon:@@ -12,54 +9,34 @@ on:permissions:contents: read+concurrency:+ group: release-${{ github.ref }}+ cancel-in-progress: false+jobs:- update-version:+ validate-source:+ if: github.repository == 'opendatalab/MinerU'runs-on: ubuntu-latest+ timeout-minutes: 5+ env:+ RELEASE_TAG: ${{ github.ref_type == 'tag' && github.ref_name || '' }}steps:- - name: Checkout repository- uses: actions/checkout@v6+ - uses: actions/checkout@v6with:- ref: master- fetch-depth: 0- # Push to master must authenticate as the PAT; the default GITHUB_TOKEN- # only has contents:read and is rejected with 403.- token: ${{ secrets.RELEASE_TOKEN }}-- - name: Set up Python- uses: actions/setup-python@v6+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-python@v6with:- python-version: "3.11"-- - name: Update version.py- run: |- python -m pip install packaging- python update_version.py-- - name: Verify version.py- run: |- ls -l mineru/version.py- cat mineru/version.py+ python-version: '3.12'+ - uses: astral-sh/setup-uv@v7+ - name: Verify release source before running the matrix+ run: uv run --no-project --with packaging python scripts/ci/check_release.py --tag "$RELEASE_TAG" --commit "$GITHUB_SHA"- - name: Commit changes- id: commit_changes- run: |- git config --local user.name "github-actions[bot]"- git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"- git add mineru/version.py- if git diff-index --quiet HEAD; then- echo "No changes to commit"- echo "committed=false" >> "$GITHUB_OUTPUT"- else- git commit -m "Update version.py with new version"- echo "committed=true" >> "$GITHUB_OUTPUT"- fi-- - name: Push changes- if: steps.commit_changes.outputs.committed == 'true'- run: |- git push origin HEAD:master+ tests:+ needs: validate-source+ uses: ./.github/workflows/cli.ymlcheck-install:needs: [ build ]@@ -71,6 +48,7 @@ jobs:matrix:os: [ubuntu-latest, windows-latest, macos-latest]python-version: ["3.11", "3.12", "3.13", "3.14"]+ timeout-minutes: 15defaults:run:shell: bash@@ -90,23 +68,26 @@ jobs:- name: Install and verify release wheelrun: |python -m pip install --upgrade pip- python -m pip install dist/*.whl+ python -m pip install --only-binary=docvortex dist/*.whlpython -m pip checkpython -I -c "from mineru.parser import MinerUParser, MinerUApiParser, parse, parse_async; from mineru.render import render; from mineru.types import MiddleJson"mineru version --jsonmineru-kit --versionbuild:- needs: [ update-version ]+ needs: [ tests ]runs-on: ubuntu-latest+ timeout-minutes: 10+ env:+ RELEASE_TAG: ${{ github.ref_type == 'tag' && github.ref_name || '' }}steps:- name: Checkout codeuses: actions/checkout@v6with:- ref: master- fetch-depth: 0+ ref: ${{ github.sha }}+ persist-credentials: false- name: Set up Pythonuses: actions/setup-python@v6@@ -118,6 +99,9 @@ jobs:python -m pip install wheelpip install build twine+ - name: Verify tagged source+ run: python scripts/ci/check_release.py --tag "$RELEASE_TAG" --commit "$GITHUB_SHA"+- name: Build wheelrun: |python -m build --wheel@@ -125,23 +109,8 @@ jobs:- name: Check wheel metadatarun: |python -m twine check --strict dist/*.whl- python - <<'PY'- from email.parser import BytesParser- from pathlib import Path- from zipfile import ZipFile-- from packaging.specifiers import SpecifierSet-- # 核验待发布产物的实际声明,安装矩阵与发布任务复用同一份 wheel。- wheels = list(Path("dist").glob("*.whl"))- assert len(wheels) == 1, wheels- with ZipFile(wheels[0]) as archive:- metadata_path = next(name for name in archive.namelist() if name.endswith(".dist-info/METADATA"))- metadata = BytesParser().parsebytes(archive.read(metadata_path))- assert SpecifierSet(metadata["Requires-Python"]) == SpecifierSet(">=3.11,<3.15"), metadata["Requires-Python"]- classifiers = set(metadata.get_all("Classifier", []))- assert all(f"Programming Language :: Python :: 3.{minor}" in classifiers for minor in range(11, 15))- PY+ python scripts/ci/check_release.py --tag "$RELEASE_TAG" --commit "$GITHUB_SHA" \+ --wheel-dir dist --output build/release.json- name: Upload artifactuses: actions/upload-artifact@v6@@ -150,9 +119,17 @@ jobs:path: dist/*.whlretention-days: 30+ - name: Upload release provenance+ uses: actions/upload-artifact@v6+ with:+ name: release-provenance+ path: build/release.json+ if-no-files-found: error+ retention-days: 30+publish:- needs: [ build, check-install ]- if: startsWith(github.ref, 'refs/tags/')+ needs: [ tests, build, check-install ]+ if: github.repository == 'opendatalab/MinerU' && startsWith(github.ref, 'refs/tags/')runs-on: ubuntu-latestenvironment:name: pypi@@ -166,11 +143,19 @@ jobs:name: wheel-filepath: dist+ - name: Download release provenance+ uses: actions/download-artifact@v7+ with:+ name: release-provenance+ path: provenance+- name: Create and Upload Releaseid: create_releaseuses: softprops/action-gh-release@4634c16e79c963813287e889244c50009e7f0981with:- files: './dist/*.whl'+ files: |+ dist/*.whl+ provenance/release.jsonenv:GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}diff --git a/.github/workflows/rerun.yml b/.github/workflows/rerun.ymldeleted file mode 100644index b607019a..00000000--- a/.github/workflows/rerun.yml+++ /dev/null@@ -1,23 +0,0 @@-name: check-status--on:- workflow_run:- workflows: [ci]- types: [completed]--jobs:- on-failure:- runs-on: pdf- permissions:- actions: write- if: ${{ (github.event.workflow_run.head_branch == 'master') && github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.run_attempt < 3 }}- steps:- - run: |- echo 'The triggering workflow failed'- sleep 600- curl -L \- -X POST \- -H "Accept: application/vnd.github+json" \- -H "Authorization: Bearer ${{ github.token }}" \- -H "X-GitHub-Api-Version: 2022-11-28" \- https://api.github.com/repos/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }}/rerun-failed-jobsdiff --git a/docs/docvortex-0.4-migration.md b/docs/docvortex-0.4-migration.mdindex 7f75d22c..2ccec9f0 100644--- a/docs/docvortex-0.4-migration.md+++ b/docs/docvortex-0.4-migration.md@@ -36,4 +36,4 @@ MinerU 使用 `docvortex>=0.4.0,<0.5.0`。本轮调整 Python 模块边界,保`tools/validate_docvortex_boundary.py` 可对指定两仓库源码或当前安装包捕获真实 PDF 的中间协议与全部渲染。记录实际导入路径、样本 SHA256 和页数;比较时只允许忽略 DocVortex producer 版本、DOCX/EPUB 容器时间字段,以及经独立复算确认由 producer 版本派生的 EPUB 标识。-MinerU 的 `DocVortex boundary integration` 手动工作流接受未发布的 0.4 wheel URL,以及可选的 mineru-vl-utils 配套 wheel URL,在三种操作系统及 Python 3.11–3.14 上验证边界、协议和固定推理结果。DocVortex 自身 CI 验证独立安装与基础算法。配置工作流不代表已经通过远端 CI。+迁移期间用于验证未发布 DocVortex 产物的手动联调工作流已移除。MinerU CI 按 `pyproject.toml` 的版本约束安装 PyPI wheel,并在常规测试中验证导入边界、共享协议、路由及固定推理结果。DocVortex 的构建、产物校验、独立安装与基础算法回归由其自身 CI 负责。diff --git a/pyproject.toml b/pyproject.tomlindex b3b9714e..f37c6456 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -149,6 +149,8 @@ zip-safe = falsetestpaths = ["tests"]addopts = "-s --cov=mineru --cov-report html"markers = [+ "torch: 需要可选 Torch/Transformers 依赖,由独立 CPU 测试任务执行",+ "accelerator: 需要实际 GPU/NPU 设备,不属于 CPU CI 回归","e2e: MinerU CLI 端到端用例(脚本化 docs/next/cli/mineru-e2e-test-cases.md)","smoke: 快速回归子集(无需本地 quality tier)","slow: 单用例预计超过 60s",diff --git a/scripts/ci/changes.py b/scripts/ci/changes.pynew file mode 100644index 00000000..6143f2de--- /dev/null+++ b/scripts/ci/changes.py@@ -0,0 +1,60 @@+"""根据 GitHub 事件中的固定提交判定代码和文档是否需要验证。"""++from __future__ import annotations++import json+import os+import re+import subprocess+from pathlib import Path+from typing import Any+++def classify_paths(paths: list[str]) -> dict[str, bool]:+ """文档变更只构建文档,CI 公共脚本变更同时验证两个工作流。"""+ docs = any(+ path.startswith("docs/")+ or path.startswith("README")+ or path in {"mkdocs.yml", ".github/workflows/mkdocs.yml", "scripts/ci/changes.py"}+ for path in paths+ )+ code = any(not (path.startswith(("docs/", "cmds/")) or path.endswith(".md") or path == "mkdocs.yml") for path in paths)+ return {"code": code, "docs": docs}+++def changed_paths(event_name: str, event: dict[str, Any], head: str) -> list[str] | None:+ """PR 对比合并提交与基分支;首次推送和手动/发布调用执行完整检查。"""+ if event_name == "pull_request":+ base = event["pull_request"]["base"]["sha"]+ elif event_name == "push" and not event.get("ref", "").startswith("refs/tags/"):+ base = event.get("before", "")+ if not base or base == "0" * 40:+ return None+ else:+ return None+ if not all(re.fullmatch(r"[0-9a-f]{40}", value) for value in (base, head)):+ raise ValueError("Expected full commit SHAs in the GitHub event")+ # 被强制推送移出的提交可能不在 checkout 中;无法取回时保守运行全部检查。+ if subprocess.run(["git", "cat-file", "-e", f"{base}^{{commit}}"], capture_output=True).returncode:+ fetched = subprocess.run(["git", "fetch", "--no-tags", "--depth=1", "origin", base], capture_output=True)+ if fetched.returncode:+ return None+ result = subprocess.run(+ ["git", "diff", "--name-only", "--no-renames", "-z", base, head], check=True, capture_output=True, text=True+ )+ return [path for path in result.stdout.split("\0") if path]+++def main() -> None:+ """把变化分类写入 Actions 输出,供始终存在的汇总检查决定跳过哪些任务。"""+ event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8"))+ paths = changed_paths(os.environ["GITHUB_EVENT_NAME"], event, os.environ["GITHUB_SHA"])+ changes = {"code": True, "docs": True} if paths is None else classify_paths(paths)+ with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as output:+ for name, changed in changes.items():+ output.write(f"{name}={str(changed).lower()}\n")+ print(json.dumps(changes))+++if __name__ == "__main__":+ main()diff --git a/scripts/ci/check_release.py b/scripts/ci/check_release.pynew file mode 100644index 00000000..86687142--- /dev/null+++ b/scripts/ci/check_release.py@@ -0,0 +1,84 @@+"""校验固定源码提交、release 标签和最终 wheel,输出可追溯的发布记录。"""++from __future__ import annotations++import argparse+import hashlib+import json+import re+import subprocess+import tomllib+from email.parser import BytesParser+from pathlib import Path+from zipfile import ZipFile++from packaging.specifiers import SpecifierSet+from packaging.version import Version+++def source_version(root: Path, tag: str) -> Version:+ """发版只验证已经提交的版本,拒绝用移动分支或临时改版本替代标签源码。"""+ source = (root / "mineru/version.py").read_text(encoding="utf-8")+ match = re.search(r'^__version__ = "([^"]+)"$', source, re.MULTILINE)+ if match is None:+ raise ValueError("Missing __version__ assignment")+ version = Version(match.group(1))+ if tag:+ tag_match = re.fullmatch(r"mineru-(.+)-released", tag)+ if tag_match is None or Version(tag_match.group(1)) != version:+ raise ValueError(f"Release tag {tag!r} must match the committed version {version}; update it before tagging")+ return version+++def verify_wheel(root: Path, directory: Path, version: Version) -> dict[str, str]:+ """检查实际发布产物的版本、Python 范围和 classifiers,记录完整 wheel 摘要。"""+ wheels = list(directory.glob("*.whl"))+ if len(wheels) != 1:+ raise ValueError(f"Expected exactly one wheel, found {len(wheels)}")+ wheel = wheels[0]+ project = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]+ with ZipFile(wheel) as archive:+ metadata_paths = [name for name in archive.namelist() if name.endswith(".dist-info/METADATA")]+ if len(metadata_paths) != 1:+ raise ValueError("Wheel must have exactly one METADATA file")+ metadata = BytesParser().parsebytes(archive.read(metadata_paths[0]))+ for field in ("Name", "Version", "Requires-Python"):+ if len(metadata.get_all(field, [])) != 1:+ raise ValueError(f"Missing or duplicate wheel metadata: {field}")+ if metadata["Name"] != project["name"] or Version(metadata["Version"]) != version:+ raise ValueError("Wheel name/version does not match the release source")+ if SpecifierSet(metadata["Requires-Python"]) != SpecifierSet(project["requires-python"]):+ raise ValueError("Wheel Python requirement does not match pyproject.toml")+ if set(metadata.get_all("Classifier", [])) != set(project["classifiers"]):+ raise ValueError("Wheel classifiers do not match pyproject.toml")+ with wheel.open("rb") as stream:+ digest = hashlib.file_digest(stream, "sha256").hexdigest()+ return {"wheel": wheel.name, "wheel_sha256": digest}+++def main() -> None:+ """在构建前校验标签,在构建后补充 wheel 身份,两个阶段都锁定相同源码提交。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--tag", default="")+ parser.add_argument("--commit", required=True)+ parser.add_argument("--wheel-dir", type=Path)+ parser.add_argument("--output", type=Path)+ args = parser.parse_args()+ root = Path.cwd()+ commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()+ if not re.fullmatch(r"[0-9a-f]{40}", args.commit) or commit != args.commit:+ raise ValueError("Checkout must match the workflow commit SHA")+ subprocess.run(["git", "diff", "--exit-code", "HEAD", "--", "mineru", "pyproject.toml"], check=True)+ version = source_version(root, args.tag)+ record = {"source_commit": commit, "tag": args.tag, "version": str(version)}+ if args.wheel_dir is not None:+ record.update(verify_wheel(root, args.wheel_dir, version))+ result = json.dumps(record, indent=2)+ if args.output is not None:+ args.output.parent.mkdir(parents=True, exist_ok=True)+ args.output.write_text(result + "\n", encoding="utf-8")+ print(result)+++if __name__ == "__main__":+ main()diff --git a/tests/README.md b/tests/README.mdindex f82875cf..ff604f80 100644--- a/tests/README.md+++ b/tests/README.md@@ -7,10 +7,40 @@## 本地运行```sh-.venv1/bin/python -m pytest tests/unittest -o addopts= -q -m 'not remote and not full_stack'+.venv4/bin/python -m pytest tests/unittest -o addopts= -q -m 'not torch'+.venv4/bin/python -m pytest tests/unittest -o addopts= -q -m 'torch and not accelerator'```-迁移前后均存在的三个失败为两项 Doclib extras 元数据断言及一项 MFR LaTeX 修复断言;本次没有新增排除项或改变对应断言。+第二条命令需要安装 `.[test,torch]`。`torch` 标记用于真实依赖 Torch/Transformers 的测试;仅模拟设备策略的测试仍属于基础集合。+`accelerator` 标记用于必须访问实际 MPS/XPU 等设备的测试,独立 CPU CI 不运行这些用例,本地可用 `-m accelerator` 验证。++## CI 分层与报告++- 上游 `master/dev` 的 push、PR 和手动触发运行 `mineru-cli-test`,fork 的主测试保持跳过。+- 代码测试保留 Linux Python 3.11–3.14 全量基础回归,以及 Windows/macOS 的公开接口矩阵;Linux Python 3.12 单独采集覆盖率。+- Torch CPU job 显式安装 CPU 依赖并验证导入,执行所有 `torch and not accelerator` 用例。+- 纯文档变更跳过代码矩阵,`CI result` 始终汇总适用任务;分支保护可把该名称设置为 required check。+- 覆盖率使用 pytest-cov 的原生 `--cov-fail-under=58 --cov-precision=2` 门槛。2026-10-24 本地 Python 3.12 无 Torch 环境实测 59.87%,为平台差异保留余量,并避免整数四舍五入影响门槛判断。+- 每个测试 job 输出 JUnit XML 和最慢 30 项,覆盖率 job 额外输出 XML;成功或失败均保留报告 14 天。+- 全仓 Ruff 先检查 `E9,F63,F7,F82`,新增 CI 脚本和 `tests/ci` 执行项目完整规则及格式检查;其余存量规则逐步治理。++CI 脚本的轻依赖验证不加载产品测试的自动 fixture:++```sh+.venv4/bin/python -m pytest tests/ci --confcutdir=tests/ci -o addopts= -q+actionlint+```++文档 job 只安装 `docs/requirements.txt`;HTTP 示例回归由 Linux 基础套件执行。发布文档时直接上传已经通过 strict build 的 `site/`,不再次构建。++## 发布与 DocVortex 依赖++正式发布前先提交 `mineru/version.py` 的目标版本,再在该提交创建 `mineru-<version>-released` 标签。+构建和测试只检出事件的固定 SHA;标签和源码版本不一致会立即失败,不再自动改写或推送 `master`。+完整 CI 与跨平台 wheel 安装检查通过后才发布同一份 wheel。GitHub Release 附带 `release.json`,记录源码 SHA、版本、标签和 wheel SHA-256。++MinerU CI 按 `pyproject.toml` 的版本约束直接安装 PyPI 上的 DocVortex wheel,使用 `--only-binary=docvortex` 禁止回退到源码构建。+DocVortex 的源码构建、原生协议和产物身份验证由其自身仓库负责;MinerU 保留常规测试中的导入边界、共享协议、路由及真实文档集成回归。## Hybrid 输入与原始语料@@ -24,7 +54,7 @@普通测试只读取本仓库快照。显式再生新增快照时,由调用者提供 DocVortex 源码目录:```sh-.venv1/bin/python tests/fixtures/capture_hybrid_native_script_inputs.py \+.venv4/bin/python tests/fixtures/capture_hybrid_native_script_inputs.py \--fixture tests/fixtures/hybrid_pdf_script_inputs.json \--source-root /path/to/DocVortex --check```diff --git a/tests/ci/test_checks.py b/tests/ci/test_checks.pynew file mode 100644index 00000000..394eed89--- /dev/null+++ b/tests/ci/test_checks.py@@ -0,0 +1,169 @@+"""用真实 Git 差异和模拟 wheel 验证 CI 分流及发布身份,不依赖 MinerU 运行时。"""++from __future__ import annotations++import json+import os+import subprocess+import sys+from pathlib import Path+from zipfile import ZipFile++import pytest+from packaging.version import Version++from scripts.ci.changes import changed_paths, classify_paths+from scripts.ci.check_release import source_version, verify_wheel++ROOT = Path(__file__).resolve().parents[2]+++def git(root: Path, *args: str) -> str:+ """只在测试临时仓库执行 Git,避免触碰开发者的分支和暂存区。"""+ return subprocess.check_output(["git", "-C", str(root), *args], text=True).strip()+++def repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """建立独立仓库,允许测试真实提交差异、标签校验和工作区漂移。"""+ git(tmp_path, "init", "--initial-branch=main")+ git(tmp_path, "config", "user.name", "CI tests")+ git(tmp_path, "config", "user.email", "[email protected]")+ (tmp_path / "mineru").mkdir()+ (tmp_path / "mineru/version.py").write_text('__version__ = "4.0.12"\n', encoding="utf-8")+ (tmp_path / "pyproject.toml").write_text(+ '[project]\nname="mineru"\nrequires-python=">=3.11,<3.15"\nclassifiers=["Programming Language :: Python :: 3.11"]\n',+ encoding="utf-8",+ )+ git(tmp_path, "add", ".")+ git(tmp_path, "commit", "-m", "initial")+ monkeypatch.chdir(tmp_path)+ return tmp_path+++ ("paths", "code", "docs"),+ [+ (["docs/next/api/tasks.md"], False, True),+ (["docs/requirements.txt"], False, True),+ (["docs/images/example.png"], False, True),+ (["README_zh-CN.md"], False, True),+ (["mkdocs.yml"], False, True),+ (["mineru/parser/base.py"], True, False),+ (["scripts/http_task_example.py"], True, False),+ (["scripts/ci/changes.py"], True, True),+ ([".github/workflows/cli.yml"], True, False),+ (["docs/index.md", "mineru/config.py"], True, True),+ ([], False, False),+ ],+)+def test_change_classification(paths: list[str], code: bool, docs: bool) -> None:+ """真实产品、文档资源和公共分流脚本分别触发所需检查。"""+ assert classify_paths(paths) == {"code": code, "docs": docs}+++def test_rename_out_of_code_is_not_misclassified_as_docs_only(repository: Path) -> None:+ """移动源码到文档目录仍包含原路径删除,不能绕过代码测试。"""+ base = git(repository, "rev-parse", "HEAD")+ (repository / "docs").mkdir()+ git(repository, "mv", "mineru/version.py", "docs/version.md")+ git(repository, "commit", "-m", "move")+ head = git(repository, "rev-parse", "HEAD")+ paths = changed_paths("pull_request", {"pull_request": {"base": {"sha": base}}}, head)+ assert paths == ["docs/version.md", "mineru/version.py"]+ assert classify_paths(paths) == {"code": True, "docs": True}++[email protected]("event", [{"before": "0" * 40}, {"ref": "refs/tags/mineru-4.0.12-released"}])+def test_first_push_and_release_run_every_check(event: dict[str, str]) -> None:+ """没有可信差异基点的新分支和 release 必须完整验证。"""+ assert changed_paths("push", event, "1" * 40) is None+ assert changed_paths("workflow_dispatch", {}, "1" * 40) is None+++def test_changes_script_writes_outputs_for_docs_only_push(repository: Path, tmp_path: Path) -> None:+ """执行真实 CLI 并检查 Actions 输出,验证 push 的多提交差异入口。"""+ base = git(repository, "rev-parse", "HEAD")+ (repository / "README.md").write_text("docs", encoding="utf-8")+ git(repository, "add", ".")+ git(repository, "commit", "-m", "docs")+ payload = tmp_path / "event.json"+ payload.write_text(json.dumps({"before": base, "ref": "refs/heads/main"}), encoding="utf-8")+ output = tmp_path / "outputs"+ subprocess.run(+ [sys.executable, str(ROOT / "scripts/ci/changes.py")],+ check=True,+ env={+ **os.environ,+ "GITHUB_EVENT_NAME": "push",+ "GITHUB_EVENT_PATH": str(payload),+ "GITHUB_SHA": git(repository, "rev-parse", "HEAD"),+ "GITHUB_OUTPUT": str(output),+ },+ )+ assert output.read_text() == "code=false\ndocs=true\n"++[email protected]("tag", ["mineru-4.0.13-released", "mineru-4.0.11-released", "v4.0.12", "mineru-bad-released"])+def test_release_rejects_mismatched_tag_without_rewriting_source(repository: Path, tag: str) -> None:+ """不同版本及非法标签必须失败,不能通过改源码或回退版本掩盖错误。"""+ version_file = repository / "mineru/version.py"+ before = version_file.read_bytes()+ with pytest.raises(ValueError):+ source_version(repository, tag)+ assert version_file.read_bytes() == before+++def wheel(directory: Path, *, version: str = "4.0.12", requires_python: str = ">=3.11,<3.15") -> Path:+ """构造最小发行包以测试实际 METADATA 和摘要,无需安装模型依赖。"""+ directory.mkdir(parents=True, exist_ok=True)+ target = directory / "mineru-4.0.12-py3-none-any.whl"+ with ZipFile(target, "w") as archive:+ archive.writestr(+ "mineru-4.0.12.dist-info/METADATA",+ f"Name: mineru\nVersion: {version}\nRequires-Python: {requires_python}\n"+ "Classifier: Programming Language :: Python :: 3.11\n",+ )+ return target++[email protected]("failure", ["version", "python", "multiple", "missing"])+def test_release_rejects_wrong_or_ambiguous_wheel(repository: Path, failure: str) -> None:+ """构建内容漂移、产物缺失或多个候选不能进入发布。"""+ directory = repository / "dist"+ artifact = wheel(+ directory,+ version="4.0.13" if failure == "version" else "4.0.12",+ requires_python=">=3.10" if failure == "python" else ">=3.11,<3.15",+ )+ if failure == "multiple":+ (directory / "another.whl").write_bytes(artifact.read_bytes())+ elif failure == "missing":+ artifact.unlink()+ with pytest.raises(ValueError):+ verify_wheel(repository, directory, Version("4.0.12"))+++def test_release_cli_records_exact_commit_and_rejects_dirty_source(repository: Path) -> None:+ """端到端校验标签、源码 SHA 和 wheel 摘要,未提交的版本漂移必须失败。"""+ artifact = wheel(repository / "dist")+ head = git(repository, "rev-parse", "HEAD")+ command = [+ sys.executable,+ str(ROOT / "scripts/ci/check_release.py"),+ "--commit",+ head,+ "--tag",+ "mineru-4.0.12-released",+ "--wheel-dir",+ str(artifact.parent),+ "--output",+ "release.json",+ ]+ subprocess.run(command, check=True)+ record = json.loads((repository / "release.json").read_text())+ assert record["source_commit"] == head and record["version"] == "4.0.12"+ assert record["wheel"] == artifact.name and len(record["wheel_sha256"]) == 64+ (repository / "mineru/version.py").write_text('__version__ = "4.0.13"\n', encoding="utf-8")+ assert subprocess.run(command, capture_output=True).returncode != 0+ assert json.loads((repository / "release.json").read_text()) == recorddiff --git a/tests/clean_coverage.py b/tests/clean_coverage.pydeleted file mode 100644index 970ac1e3..00000000--- a/tests/clean_coverage.py+++ /dev/null@@ -1,26 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""-clean coverage-"""-import os-import shutil--def delete_file(path):- """delete file."""- if not os.path.exists(path):- if os.path.isfile(path):- try:- os.remove(path)- print(f"File '{path}' deleted.")- except TypeError as e:- print(f"Error deleting file '{path}': {e}")- elif os.path.isdir(path):- try:- shutil.rmtree(path)- print(f"Directory '{path}' and its contents deleted.")- except TypeError as e:- print(f"Error deleting directory '{path}': {e}")--if __name__ == "__main__":- delete_file("htmlcov/")- #delete_file(".coverage")diff --git a/tests/get_coverage.py b/tests/get_coverage.pydeleted file mode 100644index b3af04ce..00000000--- a/tests/get_coverage.py+++ /dev/null@@ -1,23 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""-get cov-"""-from bs4 import BeautifulSoup-import shutil-def get_covrage():- """get covrage"""- # 发送请求获取网页内容- html_content = open("htmlcov/index.html", "r", encoding="utf-8").read()- soup = BeautifulSoup(html_content, 'html.parser')-- # 查找包含"pc_cov"的span标签- pc_cov_span = soup.find('span', class_='pc_cov')-- # 提取百分比值- percentage_value = pc_cov_span.text.strip()- percentage_float = float(percentage_value.rstrip('%'))- print ("percentage_float:", percentage_float)- assert percentage_float >= 0.2--if __name__ == '__main__':- get_covrage()\ No newline at end of filediff --git a/tests/unittest/test_mfr_latex_utils.py b/tests/unittest/test_mfr_latex_utils.pyindex de892302..f003242b 100644--- a/tests/unittest/test_mfr_latex_utils.py+++ b/tests/unittest/test_mfr_latex_utils.py@@ -7,6 +7,8 @@ import pytestimport numpy as npfrom types import SimpleNamespace+pytestmark = pytest.mark.torch+torch = pytest.importorskip("torch")pytest.importorskip("transformers", minversion="5.10.1")diff --git a/tests/unittest/test_ocr_detector_precision.py b/tests/unittest/test_ocr_detector_precision.pyindex 6b8e35b0..090b8ef4 100644--- a/tests/unittest/test_ocr_detector_precision.py+++ b/tests/unittest/test_ocr_detector_precision.py@@ -10,6 +10,8 @@ from unittest.mock import Mockimport numpy as npimport pytest+pytestmark = pytest.mark.torch+torch = pytest.importorskip("torch")from mineru.model._internal.pytorchocr import base_ocr_v20diff --git a/tests/unittest/test_ocr_text_crop_degenerate.py b/tests/unittest/test_ocr_text_crop_degenerate.pyindex c5a0e5cc..90537f6e 100644--- a/tests/unittest/test_ocr_text_crop_degenerate.py+++ b/tests/unittest/test_ocr_text_crop_degenerate.py@@ -41,9 +41,11 @@ def test_formula_split_zero_width_fragment_preserves_valid_text() -> None:np.testing.assert_array_equal(output[0]["np_img"], image[4:12, 11:20])@pytest.mark.parametrize("mask_right", (10, 20))def test_torch_ocr_discards_invalid_crops_without_text_misalignment(mask_right: int) -> None:"""Torch 整体 OCR 同步过滤零宽框和裁图,全部被过滤时不调用识别器。"""+ pytest.importorskip("torch")from mineru.model.ocr.pytorch_paddle import PytorchPaddleOCRmodel = object.__new__(PytorchPaddleOCR)diff --git a/tests/unittest/test_opencv_boundaries.py b/tests/unittest/test_opencv_boundaries.pyindex e1b6c1f2..6849353b 100644--- a/tests/unittest/test_opencv_boundaries.py+++ b/tests/unittest/test_opencv_boundaries.py@@ -216,6 +216,7 @@ def test_table_classifier_tensor_keeps_channel_calculation_order() -> None:_assert_model_reference(classifier.batch_preprocess([image]), "table_classifier", 1)@pytest.mark.parametrize("channels", [None, 1, 3])def test_unimer_crop_and_zero_padding_keep_shape(channels: int | None) -> None:"""单通道和 RGB 公式图沿用冻结裁边、缩放和零填充像素。"""diff --git a/tests/unittest/test_pdf_native_text_5635_5636.py b/tests/unittest/test_pdf_native_text_5635_5636.pyindex 577c013e..b918cbd6 100644--- a/tests/unittest/test_pdf_native_text_5635_5636.py+++ b/tests/unittest/test_pdf_native_text_5635_5636.py@@ -56,7 +56,7 @@ def test_frozen_native_text_pipeline_restores_source_words(effort: str, owned: bmodel_dict["pages"] = pagesmodel = ModelJson.from_dict(model_dict)middle = model_json_to_middle_json(model)- markdown = ParseResult(middle, model).markdown()+ markdown = ParseResult(middle_json=middle).markdown()for value in [json.dumps(model.to_dict(), ensure_ascii=False), json.dumps(middle.to_dict(), ensure_ascii=False), markdown]:assert "This book is a practical" in valueassert value.count("financial") == 5diff --git a/tests/unittest/test_pp_doclayoutv2_postprocess.py b/tests/unittest/test_pp_doclayoutv2_postprocess.pyindex 76008ebe..f9208b2c 100644--- a/tests/unittest/test_pp_doclayoutv2_postprocess.py+++ b/tests/unittest/test_pp_doclayoutv2_postprocess.py@@ -14,6 +14,8 @@ from PIL import Imagefrom mineru.backend.analysis.pdf.formulas import _build_formula_inputsfrom mineru.backend.analysis.pdf.layout import _build_vl_style_layout_blocks+pytestmark = pytest.mark.torch+pytest.importorskip("torch")pytest.importorskip("transformers", minversion="5.10.1")diff --git a/tests/unittest/test_pp_doclayoutv2_thresholds.py b/tests/unittest/test_pp_doclayoutv2_thresholds.pyindex 07a304fa..50912efd 100644--- a/tests/unittest/test_pp_doclayoutv2_thresholds.py+++ b/tests/unittest/test_pp_doclayoutv2_thresholds.py@@ -61,7 +61,7 @@ def _predict(backend: str, probabilities: np.ndarray) -> dict[str, Any]:return _onnx_predictions(rows[::-1], [len(rows)])[0][email protected]("backend", ["torch", "onnx"])[email protected]("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])@pytest.mark.parametrize("cls_id", range(len(PP_DOCLAYOUT_V2_LABELS)), ids=PP_DOCLAYOUT_V2_LABELS)def test_class_threshold_boundaries(backend: str, cls_id: int) -> None:"""逐类验证低于阈值拒绝,等于阈值和高于阈值均可保留。"""@@ -75,7 +75,7 @@ def test_class_threshold_boundaries(backend: str, cls_id: int) -> None:np.testing.assert_allclose(result["scores"], [threshold, threshold + 0.001], rtol=0, atol=1e-7)[email protected]("backend", ["torch", "onnx"])[email protected]("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])def test_inline_formula_uses_045_without_changing_other_class_thresholds(backend: str) -> None:"""行内公式低于 0.45 时拒绝,行间公式和正文仍保留 0.4 以上的候选。"""probabilities = np.full((7, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)@@ -90,7 +90,7 @@ def test_inline_formula_uses_045_without_changing_other_class_thresholds(backendnp.testing.assert_allclose(result["scores"], [0.45, 0.451, 0.425, 0.425], rtol=0, atol=1e-7)[email protected]("backend", ["torch", "onnx"])[email protected]("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])def test_invalid_primary_class_cannot_be_reintroduced_by_secondary_label(backend: str) -> None:"""摘要主类别未达标时,即使次高正文类别达标也不能重新进入输出。"""probabilities = np.full((4, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)@@ -103,7 +103,7 @@ def test_invalid_primary_class_cannot_be_reintroduced_by_secondary_label(backendassert result["labels"].tolist() == [17][email protected]("backend", ["torch", "onnx"])[email protected]("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])def test_summary_page_scores_restore_title_and_four_paragraphs(backend: str) -> None:"""用第八页实测分数复现大摘要框抢序和低分第二段丢失,验证分类筛选修复。"""probabilities = np.full((10, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)@@ -119,7 +119,7 @@ def test_summary_page_scores_restore_title_and_four_paragraphs(backend: str) ->np.testing.assert_allclose(result["scores"][1], 0.4426, rtol=0, atol=1e-7)[email protected]("backend", ["torch", "onnx"])[email protected]("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])def test_valid_primary_keeps_only_secondary_labels_above_their_own_threshold(backend: str) -> None:"""有效候选保留达到自身阈值的次高正文标签,拒绝未达标的页眉标签。"""probabilities = np.full((4, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)@@ -132,7 +132,7 @@ def test_valid_primary_keeps_only_secondary_labels_above_their_own_threshold(bacassert set(result["labels"].tolist()) == {0, 22}[email protected]("backend", ["torch", "onnx"])[email protected]("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])@pytest.mark.parametrize(("first_cls", "second_cls", "expected"), [(0, 22, []), (6, 8, [6])])def test_primary_class_ties_use_the_smallest_class_id(backend: str, first_cls: int, second_cls: int, expected: list[int]@@ -146,6 +146,7 @@ def test_primary_class_ties_use_the_smallest_class_id(assert result["labels"].tolist() == expecteddef test_torch_uses_loaded_model_thresholds() -> None:"""Torch 按已加载模型配置筛选,不以共享默认常量覆盖模型自带阈值。"""probabilities = np.full((1, 1, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)@@ -158,6 +159,7 @@ def test_torch_uses_loaded_model_thresholds() -> None:assert result["labels"].tolist() == []@pytest.mark.parametrize("query_count", [0, 2])def test_torch_empty_and_all_rejected_candidates(query_count: int) -> None:"""无候选和全部未达标的批次均保留逐页空结果与框数组形状。"""@@ -200,7 +202,7 @@ def test_onnx_candidate_validity_is_isolated_by_page() -> None:assert all(result["boxes"].shape == (0, 4) for result in results[:2])[email protected]("backend", ["torch", "onnx"])[email protected]("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])def test_layout_constructor_rejects_removed_uniform_conf(backend: str) -> None:"""包装类明确移除统一 conf 参数,禁止调用方再次覆盖分类阈值。"""if backend == "torch":diff --git a/tests/unittest/test_seal_crop_degenerate.py b/tests/unittest/test_seal_crop_degenerate.pyindex d5feefbe..a934037f 100644--- a/tests/unittest/test_seal_crop_degenerate.py+++ b/tests/unittest/test_seal_crop_degenerate.py@@ -102,6 +102,7 @@ def test_valid_crop_does_not_hide_unrelated_warp_errors(seal_image: np.ndarray,def _build_seal_model(engine: str, boxes: list[np.ndarray], recognizer: Mock, debug_dir: Path) -> Any:"""只替换检测和识别推理,保留两个引擎的真实裁剪、过滤与结果封装。"""if engine == "torch":+ pytest.importorskip("torch")from mineru.model.ocr.pytorch_paddle import PytorchPaddleOCRmodel = PytorchPaddleOCR.__new__(PytorchPaddleOCR)@@ -121,7 +122,7 @@ def _build_seal_model(engine: str, boxes: list[np.ndarray], recognizer: Mock, dereturn model[email protected]("engine", ["torch", "onnx"])[email protected]("engine", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])def test_seal_recognition_keeps_boxes_and_debug_outputs_aligned(seal_image: np.ndarray, engine: str, tmp_path: Path) -> None:"""跳过中间真实无效轮廓后,后一个识别文字和调试裁片仍对应最后的检测框。"""first = np.asarray(_REFERENCE["valid_cases"][0]["points"])@@ -142,7 +143,7 @@ def test_seal_recognition_keeps_boxes_and_debug_outputs_aligned(seal_image: np.nnp.testing.assert_array_equal(np.asarray(saved), crop[:, :, ::-1])[email protected]("engine", ["torch", "onnx"])[email protected]("engine", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])def test_all_invalid_seal_crops_skip_recognition(seal_image: np.ndarray, engine: str, tmp_path: Path) -> None:"""全部轮廓无效时外层 OCR 返回既有空结果,并且不执行识别模型。"""invalid = np.asarray(_REFERENCE["degenerate_polygon"])@@ -152,6 +153,7 @@ def test_all_invalid_seal_crops_skip_recognition(seal_image: np.ndarray, engine:recognizer.assert_not_called()@pytest.mark.parametrize("all_invalid", [False, True])def test_torch_detection_only_keeps_debug_crops_aligned(seal_image: np.ndarray, tmp_path: Path, all_invalid: bool) -> None:"""Torch 仅检测入口实际执行裁剪时,同步过滤返回框及调试图,空裁片也能安全输出。"""diff --git a/tests/unittest/test_torch_cpu_threads.py b/tests/unittest/test_torch_cpu_threads.pyindex cff4e433..270cd20f 100644--- a/tests/unittest/test_torch_cpu_threads.py+++ b/tests/unittest/test_torch_cpu_threads.py@@ -81,6 +81,7 @@ assert "torch" not in sys.modulessubprocess.run([sys.executable, "-c", code], check=True)def test_real_torch_thread_pool_propagation() -> None:"""用独立进程验证实际 PyTorch 的后续线程按首次选定上限执行算子。"""# 基础 ONNX 安装不要求 Torch,真实算子验证仅在可选后端可用时执行。diff --git a/tests/unittest/test_transformers5_models.py b/tests/unittest/test_transformers5_models.pyindex 0d8e6e85..08dc5b8e 100644--- a/tests/unittest/test_transformers5_models.py+++ b/tests/unittest/test_transformers5_models.py@@ -8,6 +8,8 @@ from pathlib import Pathimport pytest+pytestmark = pytest.mark.torch+torch = pytest.importorskip("torch")transformers = pytest.importorskip("transformers", minversion="5.10.1")@@ -213,7 +215,9 @@ def test_layout_configuration_constructs_the_inference_graph() -> None:assert any(True for _ in model.parameters())[email protected]("device", ["cpu", "mps", "xpu"])+ "device", ["cpu", pytest.param("mps", marks=pytest.mark.accelerator), pytest.param("xpu", marks=pytest.mark.accelerator)]+)def test_layout_position_embedding_preserves_native_math(device: str) -> None:"""CPU/MPS/XPU 包装保持官方位置编码数值,且没有新增或改名的模型权重。"""from transformers.models.pp_doclayout_v2.modeling_pp_doclayout_v2 import PPDocLayoutV2SinePositionEmbeddingdiff --git a/update_version.py b/update_version.pydeleted file mode 100644index b8e678a6..00000000--- a/update_version.py+++ /dev/null@@ -1,50 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-import os-import re-import sys-from pathlib import Path--from packaging.version import Version--VERSION_FILE = Path(__file__).parent / "mineru" / "version.py"-TAG_PATTERN = re.compile(r"^mineru-(.+)-released$")-VERSION_PATTERN = re.compile(r'^__version__ = "(.+)"$', re.MULTILINE)---def get_tag_version() -> str | None:- """Return the version carried by the tag that triggered the workflow, or None when not triggered by a release tag."""- ref_name = os.environ.get("GITHUB_REF_NAME", "").strip()- match = TAG_PATTERN.match(ref_name)- if match:- return match.group(1)- if os.environ.get("GITHUB_REF_TYPE") == "tag":- raise ValueError(f"Invalid release tag {ref_name!r}. Expected format is mineru-<version>-released.")- return None---def get_file_version() -> str:- match = VERSION_PATTERN.search(VERSION_FILE.read_text())- if match is None:- raise ValueError(f"No __version__ assignment found in {VERSION_FILE}.")- return match.group(1)---def main() -> None:- tag_version = get_tag_version()- if tag_version is None:- print("Not triggered by a release tag; leaving mineru/version.py unchanged.")- return- file_version = get_file_version()- if Version(file_version) >= Version(tag_version):- print(f"mineru/version.py ({file_version}) is not lower than the tag ({tag_version}); leaving it unchanged.")- return- VERSION_FILE.write_text(f'__version__ = "{tag_version}"\n')- print(f"Updated mineru/version.py: {file_version} -> {tag_version}")---if __name__ == "__main__":- try:- main()- except ValueError as e:- print(f"error: {e}", file=sys.stderr)- raise SystemExit(1)