Skip to content

Fast, accurate OCR with correctness assessment.

sdk: align page output with the online document-parse API.

huangfw70982e8374a9
diff --git a/docs/minicpm_ocr_sdk_api.md b/docs/minicpm_ocr_sdk_api.md
index 89380e7..13d27fb 100644
--- a/docs/minicpm_ocr_sdk_api.md
+++ b/docs/minicpm_ocr_sdk_api.md
@@ -15,8 +15,9 @@ minicpmvocr parse doc.pdf -o doc.md --device cuda:0 \
| 参数 | 说明 |
|---|---|
-| `INPUT` / `--input FILE` | 输入文件,支持 PDF、PNG、JPG、JPEG、BMP、WebP、TIF、TIFF;两种写法任选其一 |
+| `INPUT` / `--input FILE` | 输入文件,支持 PDF、PNG、JPG、JPEG、GIF、BMP、WebP、TIF、TIFF;两种写法任选其一 |
| `-o FILE` / `--output FILE` | 输出 Markdown 路径;省略时输出到标准输出 |
+| `--json FILE` | 另外输出 JSON,结构与线上文档解析异步任务一致:`status`、`pages_done`、`pages_total`、`pages[]` 和 `markdown` |
| `--server-url URL` | 必填,识别服务地址;可重复传入以连接多个服务实例 |
| `--model NAME` | 必填,服务暴露的模型名称,对应 vLLM 的 `--served-model-name` |
| `--device DEVICE` | 版面检测设备,例如 `cuda:0`;不改变识别服务使用的设备 |
@@ -37,9 +38,11 @@ minicpmvocr parse doc.pdf -o doc.md --device cuda:0 \
指定 `--config` 时,先读取所选配置文件,再应用命令行选项;`--set` 的优先级高于其他命令行选项。完整配置项见 [SDK 配置文件](../sdk/minicpmvocr/configs/minicpmvocr.yaml)。
-省略 `--config` 时,快速开始配置使用 GPU 0 进行版面检测,识别上下文长度为 40960,识别请求并发数为 32,版面检测与识别重叠执行,关闭跨页表格合并。服务地址和模型名称没有默认值。
+省略 `--config` 时,快速开始配置使用 GPU 0 进行版面检测,开启自适应旋转(`upright`),识别上下文长度为 40960,识别请求并发数为 32,版面检测与识别重叠执行,关闭跨页表格合并。服务地址和模型名称没有默认值。
-默认 Paddle 版面模型位于运行目录下的 `models/PP-DocLayoutV3_infer/`。文件完整时直接复用;缺失或不完整时自动下载。`OCR_ASSETS_DIR` 可更改模型所在的资产根目录。
+默认 Paddle 版面模型位于运行目录下的 `models/PP-DocLayoutV3_infer/`,自适应旋转使用的三个 Paddle 模型位于 `models/paddle_upright/`。文件完整时直接复用;缺失或不完整时自动下载。`OCR_ASSETS_DIR` 可更改模型所在的资产根目录,`OCR_UPRIGHT_DIR` 可指向已准备好的 `paddle_upright` 目录。运行环境缺少可选的 `paddleocr` 依赖时解析不会失败:记录告警后本次运行跳过摆正。
+
+关闭旋转用 `--set upright.enabled=false`。
使用 `--layout-model DIR`、`OCR_LAYOUT_MODEL_DIR` 或自定义配置文件指定模型路径时,需提前准备本地模型。自定义 YAML 中的相对路径以配置文件所在目录为基准;`--layout-model` 的相对路径以运行命令时的目录为基准。
@@ -91,4 +94,4 @@ if __name__ == "__main__":
`ensure_layout_model()` 复用或下载官方版面模型;`load_config()` 合并配置并校验输入;`pipelined_run()` 执行版面检测和识别;`assemble_document_markdown()` 返回合并后的 Markdown、页数和跨页表格合并次数。
-运行产物默认写入当前目录下的 `runs/<run_tag>/`,包括逐页 Markdown、结构化结果和运行记录。可通过配置项 `run.run_root` 或环境变量 `OCR_RUN_ROOT` 更改输出根目录。
+运行产物默认写入当前目录下的 `runs/<run_tag>/`,包括逐页 Markdown、结构化结果和运行记录。其中 `pages_json/<image_id>.json` 与线上 [文档解析 API](https://platform.modelbest.cn/console/docs/api/document-parse) 的单页响应同构:`metadata.page_index`(从 0 起)、`choices[0].message.content`(整页 Markdown)和 `ocr`(`image_width`、`image_height`、`blocks[]`、`rotation`)。块的 `status` 取值为 `ok`、`failed`、`skipped_no_vlm`、`skipped_seal`;`rotation.total_angle` 以逆时针为正,`applied=true` 时坐标基于摆正后的页面。`assemble_document_json(run_dir)` 返回与 `--json` 相同的整份结果,页间 Markdown 以空行连接。可通过配置项 `run.run_root` 或环境变量 `OCR_RUN_ROOT` 更改输出根目录。
diff --git a/docs/minicpm_ocr_sdk_api_en.md b/docs/minicpm_ocr_sdk_api_en.md
index 25485e6..05bad8c 100644
--- a/docs/minicpm_ocr_sdk_api_en.md
+++ b/docs/minicpm_ocr_sdk_api_en.md
@@ -15,8 +15,9 @@ minicpmvocr parse doc.pdf -o doc.md --device cuda:0 \
| Option | Description |
|---|---|
-| `INPUT` / `--input FILE` | Input file: PDF, PNG, JPG, JPEG, BMP, WebP, TIF, or TIFF; use either form |
+| `INPUT` / `--input FILE` | Input file: PDF, PNG, JPG, JPEG, GIF, BMP, WebP, TIF, or TIFF; use either form |
| `-o FILE` / `--output FILE` | Output Markdown path; writes to standard output when omitted |
+| `--json FILE` | Also write JSON shaped like an online document-parse job: `status`, `pages_done`, `pages_total`, `pages[]`, and `markdown` |
| `--server-url URL` | Required recognition service URL; repeat to connect to multiple service instances |
| `--model NAME` | Required model name exposed by the service, matching vLLM's `--served-model-name` |
| `--device DEVICE` | Layout detection device, such as `cuda:0`; does not change the device used by the recognition service |
@@ -37,9 +38,11 @@ Run `minicpmvocr parse --help` for the complete option list.
When `--config` is supplied, the selected configuration file is loaded first, then command-line options are applied. `--set` takes precedence over other command-line options. See the [SDK configuration file](../sdk/minicpmvocr/configs/minicpmvocr.yaml) for all configuration fields.
-Without `--config`, the quickstart configuration uses GPU 0 for layout detection, a recognition context length of 40960, and 32 concurrent recognition requests. Layout detection and recognition overlap, and cross-page table merging is disabled. The service URL and model name have no default values.
+Without `--config`, the quickstart configuration uses GPU 0 for layout detection, enables rotation adaptation (`upright`), a recognition context length of 40960, and 32 concurrent recognition requests. Layout detection and recognition overlap, and cross-page table merging is disabled. The service URL and model name have no default values.
-The default Paddle layout model is stored in `models/PP-DocLayoutV3_infer/` under the working directory. Complete model files are reused; missing or incomplete files trigger an automatic download. Set `OCR_ASSETS_DIR` to change the root directory for model assets.
+The default Paddle layout model is stored in `models/PP-DocLayoutV3_infer/` under the working directory, and the three Paddle models used by rotation adaptation are stored in `models/paddle_upright/`. Complete model files are reused; missing or incomplete files trigger an automatic download. Set `OCR_ASSETS_DIR` to change the root directory for model assets, or `OCR_UPRIGHT_DIR` to point at a prepared `paddle_upright` directory. If the optional `paddleocr` dependency is missing, parsing does not fail: a warning is logged and rotation adaptation is skipped for that run.
+
+Disable rotation with `--set upright.enabled=false`.
When specifying a model path through `--layout-model DIR`, `OCR_LAYOUT_MODEL_DIR`, or a custom configuration file, prepare the local model first. Relative paths in a custom YAML file are resolved against that file's directory; relative `--layout-model` paths are resolved against the directory where the command is run.
@@ -91,4 +94,4 @@ if __name__ == "__main__":
`ensure_layout_model()` reuses or downloads the official layout model; `load_config()` merges the configuration and validates the input; `pipelined_run()` runs layout detection and recognition; `assemble_document_markdown()` returns the combined Markdown, page count, and number of cross-page table merges.
-Run artifacts are written to `runs/<run_tag>/` under the working directory by default, including per-page Markdown, structured results, and run records. Change the output root with `run.run_root` in the configuration or the `OCR_RUN_ROOT` environment variable.
+Run artifacts are written to `runs/<run_tag>/` under the working directory by default, including per-page Markdown, structured results, and run records. `pages_json/<image_id>.json` has the same shape as one page of the online [Document Parsing API](https://platform.modelbest.cn/console/docs/api/document-parse): `metadata.page_index` (zero-based), `choices[0].message.content` (page Markdown), and `ocr` (`image_width`, `image_height`, `blocks[]`, `rotation`). Block `status` is `ok`, `failed`, `skipped_no_vlm`, or `skipped_seal`; `rotation.total_angle` is positive counterclockwise, and coordinates refer to the corrected page when `applied=true`. `assemble_document_json(run_dir)` returns the same document as `--json`, joining page Markdown with a blank line. Change the output root with `run.run_root` in the configuration or the `OCR_RUN_ROOT` environment variable.
diff --git a/sdk/minicpmvocr/__init__.py b/sdk/minicpmvocr/__init__.py
index 53f96b1..20f1822 100644
--- a/sdk/minicpmvocr/__init__.py
+++ b/sdk/minicpmvocr/__init__.py
@@ -12,6 +12,7 @@ _EXPORTS = {
"load_config": "minicpmvocr.config",
"parse_layout_run": "minicpmvocr.pipeline",
+ "assemble_document_json": "minicpmvocr.pipeline",
"prepare_run": "minicpmvocr.pipeline",
"infer_run": "minicpmvocr.pipeline",
"pipelined_run": "minicpmvocr.pipeline",
@@ -59,6 +60,12 @@ if TYPE_CHECKING:
assemble_markdown,
convert_otsl_to_html,
)
- from .pipeline import infer_run, parse_layout_run, pipelined_run, prepare_run
+ from .pipeline import (
+ assemble_document_json,
+ infer_run,
+ parse_layout_run,
+ pipelined_run,
+ prepare_run,
+ )
from .prompts import DEFAULT_PROMPT_MAP, get_element_cfg, load_prompt_map
from .pipeline.upright import UprightCorrector
diff --git a/sdk/minicpmvocr/cli.py b/sdk/minicpmvocr/cli.py
index 18682a5..e4d3d72 100644
--- a/sdk/minicpmvocr/cli.py
+++ b/sdk/minicpmvocr/cli.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import argparse
+import importlib.util
import json
import os
import re
@@ -16,7 +17,7 @@ from .backends import BACKEND_ALIASES, list_backends
from .config import _deep_merge, load_config
from .constants import PARAMS_FILENAME, SUPPORTED_INPUT_SUFFIXES
from .layouts import LAYOUT_ALIASES, list_layout_providers, normalize_layout_provider
-from .layouts.download import ensure_layout_model
+from .layouts.download import ensure_layout_model, ensure_upright_models
from .pipeline import infer_run, parse_layout_run, pipelined_run, prepare_run
from ._utils import read_jsonl
@@ -84,6 +85,7 @@ def _build_parser() -> argparse.ArgumentParser:
p_parse.add_argument("--stdout", action="store_true", help="Print markdown to stdout")
p_parse.add_argument("--run-tag", default="", help="Optional run tag for this one-shot run")
p_parse.add_argument("--no-merge-pages", action="store_true", help="Do not merge pages into a single markdown")
+ p_parse.add_argument("--json", default="", metavar="FILE", help="Also write the result as JSON in the online document-parse job shape (pages[] + markdown)")
p_parse.add_argument("--page-delimiter", default="\n\n<!-- page-break -->\n\n", help="Delimiter between pages when merging")
_add_engine_args(p_parse, require_connection=True)
@@ -222,6 +224,23 @@ def _quickstart_layout_model() -> str:
return str(next((path for path in candidates if (path / PARAMS_FILENAME).is_file()), candidates[0]))
+def _quickstart_upright_root() -> str:
+ configured = os.environ.get("OCR_UPRIGHT_DIR", "").strip()
+ if configured:
+ return str(Path(configured).expanduser().resolve())
+ assets = Path(os.environ.get("OCR_ASSETS_DIR") or Path.cwd() / "models").expanduser().resolve()
+ return str(assets / "paddle_upright")
+
+
+def _quickstart_upright_dirs() -> dict:
+ root = Path(_quickstart_upright_root())
+ return {
+ "model_dir": str(root / "PP-LCNet_x1_0_doc_ori"),
+ "det_model_dir": str(root / "PP-OCRv5_mobile_det"),
+ "textline_model_dir": str(root / "PP-LCNet_x1_0_textline_ori"),
+ }
+
+
def _load_parse_config(args: argparse.Namespace) -> dict:
if not args.server_url or any(not url.strip() for url in args.server_url):
raise ValueError("--server-url URL is required and must not be empty")
@@ -249,6 +268,7 @@ def _load_parse_config(args: argparse.Namespace) -> dict:
"model_dir": _quickstart_layout_model(),
"device": os.environ.get("OCR_LAYOUT_DEVICE") or "cuda:0",
},
+ "upright": _quickstart_upright_dirs(),
"engine": {"max_model_len": 40960},
"pipeline": {"overlap_layout": True},
}
@@ -262,6 +282,21 @@ def _load_parse_config(args: argparse.Namespace) -> dict:
and normalize_layout_provider(overrides["layout"].get("provider", "ppdoclayout3_paddlex")) == "ppdoclayout3_paddlex"
):
ensure_layout_model(Path(overrides["layout"]["model_dir"]))
+ explicit_upright = explicit_overrides.get("upright") or {}
+ upright_models_managed = (
+ "model_dir" in explicit_upright
+ or "det_model_dir" in explicit_upright
+ or "textline_model_dir" in explicit_upright
+ or bool(os.environ.get("OCR_UPRIGHT_DIR", "").strip())
+ )
+ if (
+ not args.config
+ and not upright_models_managed
+ and overrides.get("upright", {}).get("enabled") is not False
+ # Without paddleocr the run skips rotation; the models would go unused.
+ and importlib.util.find_spec("paddleocr") is not None
+ ):
+ ensure_upright_models(Path(_quickstart_upright_root()))
config = args.config or str(Path(__file__).parent / "configs" / "minicpmvocr.yaml")
try:
return load_config(config, overrides=overrides)
@@ -395,6 +430,17 @@ def main() -> int:
cfg=cfg,
)
+ json_path = None
+ if args.json:
+ from .pipeline._response import assemble_document_json
+
+ json_path = Path(args.json).resolve()
+ json_path.parent.mkdir(parents=True, exist_ok=True)
+ json_path.write_text(
+ json.dumps(assemble_document_json(run_dir), ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+
if args.stdout or not args.output:
print(_absolute_image_links(markdown, run_dir))
return 0
@@ -410,6 +456,7 @@ def main() -> int:
"command": "parse",
"input": str(Path(args.input).resolve()),
"output_md": str(output_path),
+ **({"output_json": str(json_path)} if json_path else {}),
"pages": pages,
"run_dir": str(run_dir),
"layout_summary": layout_summary,
diff --git a/sdk/minicpmvocr/config.py b/sdk/minicpmvocr/config.py
index a06d27b..32bc8bf 100644
--- a/sdk/minicpmvocr/config.py
+++ b/sdk/minicpmvocr/config.py
@@ -62,7 +62,7 @@ DEFAULT_CONFIG: Dict[str, Any] = {
},
"upright": {
- "enabled": False,
+ "enabled": True,
"doc_gate": True,
@@ -213,7 +213,7 @@ DEFAULT_CONFIG: Dict[str, Any] = {
}
-ALLOWED_FILE_SUFFIXES = {".pdf", ".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tif", ".tiff"}
+ALLOWED_FILE_SUFFIXES = {".pdf", ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".tif", ".tiff"}
REQUIRED_TTS_SAMPLING_KEYS = ("temperature", "top_k", "top_p")
diff --git a/sdk/minicpmvocr/configs/minicpmvocr.yaml b/sdk/minicpmvocr/configs/minicpmvocr.yaml
index 07e3f66..9699c58 100644
--- a/sdk/minicpmvocr/configs/minicpmvocr.yaml
+++ b/sdk/minicpmvocr/configs/minicpmvocr.yaml
@@ -45,7 +45,7 @@ engine:
upright:
- enabled: false
+ enabled: true
doc_gate: true
gate_min_side: 500
gate_min_lines: 6
diff --git a/sdk/minicpmvocr/constants.py b/sdk/minicpmvocr/constants.py
index 32f8d50..c5a014f 100644
--- a/sdk/minicpmvocr/constants.py
+++ b/sdk/minicpmvocr/constants.py
@@ -41,7 +41,7 @@ CONFIG_FILENAME = "inference.yml"
SUPPORTED_IMAGE_SUFFIXES: Set[str] = {
- ".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tif", ".tiff",
+ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".tif", ".tiff",
}
SUPPORTED_INPUT_SUFFIXES: Set[str] = SUPPORTED_IMAGE_SUFFIXES | {".pdf"}
diff --git a/sdk/minicpmvocr/layouts/download.py b/sdk/minicpmvocr/layouts/download.py
index e98e584..f2657d1 100644
--- a/sdk/minicpmvocr/layouts/download.py
+++ b/sdk/minicpmvocr/layouts/download.py
@@ -22,6 +22,15 @@ LAYOUT_MODEL_SHA256 = "98b9bac88c80f6bc0fda7e0bfc2cae180020371c0b2edbb1eb498a70a
MODEL_FILES = (PARAMS_FILENAME, "inference.json", CONFIG_FILENAME)
_INSTALL_MARKER = ".minicpmvocr-installing"
+UPRIGHT_MODEL_BASE = (
+ "https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0"
+)
+UPRIGHT_MODELS = {
+ "PP-LCNet_x1_0_doc_ori": "282337df5c41f7cdf8dacd5acf71fddfdc10218399f4b318463c17f4eae96c97",
+ "PP-OCRv5_mobile_det": "50446e5d01ac2a73d5319c89513281f6578414c888c602f9af13f93feefffc58",
+ "PP-LCNet_x1_0_textline_ori": "6171f69605215a85624d650e9079fa45f7c3eaf944296181bcc5395bf3ddc7f6",
+}
+
def layout_model_ready(directory: Path) -> bool:
return not (directory / _INSTALL_MARKER).exists() and all(
@@ -56,11 +65,11 @@ def _model_lock(path: Path):
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
-def _download_archive(archive: Path) -> str:
+def _download_archive(archive: Path, url: str, sha256: str, display: str) -> str:
checksum = hashlib.sha256()
downloaded = 0
try:
- with requests.get(LAYOUT_MODEL_URL, stream=True, timeout=(10, 120)) as response:
+ with requests.get(url, stream=True, timeout=(10, 120)) as response:
response.raise_for_status()
with archive.open("wb") as handle:
for chunk in response.iter_content(chunk_size=1024 * 1024):
@@ -70,27 +79,27 @@ def _download_archive(archive: Path) -> str:
downloaded += len(chunk)
expected_size = response.headers.get("Content-Length")
if expected_size is not None and downloaded != int(expected_size):
- raise OSError("Incomplete PP-DocLayoutV3 download; run the command again to retry")
+ raise OSError(f"Incomplete {display} download; run the command again to retry")
except requests.RequestException as exc:
- raise OSError(f"Cannot download PP-DocLayoutV3 from {LAYOUT_MODEL_URL}: {exc}") from exc
+ raise OSError(f"Cannot download {display} from {url}: {exc}") from exc
digest = checksum.hexdigest()
- if LAYOUT_MODEL_SHA256 and digest != LAYOUT_MODEL_SHA256:
- raise OSError("PP-DocLayoutV3 archive checksum mismatch; existing model files were preserved")
+ if sha256 and digest != sha256:
+ raise OSError(f"{display} archive checksum mismatch; existing model files were preserved")
return digest
-def _unpack_model(archive: Path, destination: Path) -> None:
+def _unpack_model(archive: Path, destination: Path, root_name: str, model_name: str, display: str) -> None:
found = set()
try:
with tarfile.open(archive) as source:
for member in source:
path = PurePosixPath(member.name)
if path.is_absolute() or ".." in path.parts or "\\" in member.name:
- raise OSError("Unsafe path in PP-DocLayoutV3 model archive")
+ raise OSError(f"Unsafe path in {display} model archive")
if not member.isfile() and not member.isdir():
- raise OSError("Unsupported entry in PP-DocLayoutV3 model archive")
+ raise OSError(f"Unsupported entry in {display} model archive")
parts = path.parts
- if len(parts) == 2 and parts[0] == "PP-DocLayoutV3_infer":
+ if len(parts) == 2 and parts[0] == root_name:
name = parts[1]
elif len(parts) == 1:
name = parts[0]
@@ -99,51 +108,52 @@ def _unpack_model(archive: Path, destination: Path) -> None:
if name not in MODEL_FILES or member.isdir():
continue
if name in found or member.size <= 0:
- raise OSError(f"Invalid model file in PP-DocLayoutV3 archive: {name}")
+ raise OSError(f"Invalid model file in {display} model archive: {name}")
found.add(name)
with source.extractfile(member) as incoming, (destination / name).open("wb") as outgoing:
shutil.copyfileobj(incoming, outgoing)
except tarfile.TarError as exc:
- raise OSError("Invalid PP-DocLayoutV3 model archive") from exc
+ raise OSError(f"Invalid {display} model archive") from exc
if found != set(MODEL_FILES):
- raise OSError("PP-DocLayoutV3 archive is missing required inference files")
+ raise OSError(f"{display} archive is missing required inference files")
try:
config = yaml.safe_load((destination / CONFIG_FILENAME).read_text(encoding="utf-8")) or {}
- if (config.get("Global") or {}).get("model_name") != MODEL_NAME:
- raise OSError("Downloaded layout model is not PP-DocLayoutV3")
+ if (config.get("Global") or {}).get("model_name") != model_name:
+ raise OSError(f"Downloaded model is not {model_name}")
with (destination / "inference.json").open(encoding="utf-8") as handle:
json.load(handle)
except (yaml.YAMLError, ValueError, AttributeError) as exc:
- raise OSError("Invalid PP-DocLayoutV3 inference configuration") from exc
+ raise OSError(f"Invalid {display} inference configuration") from exc
-def ensure_layout_model(directory: Path) -> Path:
- """Reuse or install the official PP-DocLayoutV3 Paddle inference model."""
+def _ensure_model(directory: Path, url: str, sha256: str, root_name: str,
+ model_name: str, display: str) -> Path:
+ """Reuse or install one official Paddle inference model."""
directory = directory.expanduser().resolve()
if directory.exists() and not directory.is_dir():
- raise NotADirectoryError(f"Layout model path is not a directory: {directory}")
+ raise NotADirectoryError(f"Model path is not a directory: {directory}")
if layout_model_ready(directory):
return directory
directory.parent.mkdir(parents=True, exist_ok=True)
with _model_lock(directory.parent / f".{directory.name}.lock"):
if layout_model_ready(directory):
return directory
- print(f"Downloading PP-DocLayoutV3 layout model to {directory} ...", file=sys.stderr, flush=True)
+ print(f"Downloading {display} to {directory} ...", file=sys.stderr, flush=True)
with tempfile.TemporaryDirectory(prefix=f".{directory.name}-", dir=directory.parent) as work:
work = Path(work)
archive = work / "model.tar"
- digest = _download_archive(archive)
+ digest = _download_archive(archive, url, sha256, display)
staged = work / "model"
staged.mkdir()
- _unpack_model(archive, staged)
+ _unpack_model(archive, staged, root_name, model_name, display)
directory.mkdir(exist_ok=True)
marker = directory / _INSTALL_MARKER
marker.touch()
for name in MODEL_FILES:
os.replace(staged / name, directory / name)
metadata = {
- "model": MODEL_NAME,
- "source": LAYOUT_MODEL_URL,
+ "model": model_name,
+ "source": url,
"archive_sha256": digest,
}
metadata_path = work / "model-source.json"
@@ -151,3 +161,39 @@ def ensure_layout_model(directory: Path) -> Path:
os.replace(metadata_path, directory / ".minicpmvocr-model.json")
marker.unlink()
return directory
+
+
+def ensure_layout_model(directory: Path) -> Path:
+ """Reuse or install the official PP-DocLayoutV3 Paddle inference model."""
+ return _ensure_model(
+ directory,
+ LAYOUT_MODEL_URL,
+ LAYOUT_MODEL_SHA256,
+ "PP-DocLayoutV3_infer",
+ MODEL_NAME,
+ "PP-DocLayoutV3 layout model",
+ )
+
+
+def upright_models_ready(root: Path) -> bool:
+ return all(layout_model_ready(root / name) for name in UPRIGHT_MODELS)
+
+
+def ensure_upright_models(root: Path) -> dict:
+ """Reuse or install the three public Paddle models used for rotation adaptation.
+
+ ``root`` is the paddle_upright directory; each model lands in ``root/<name>``
+ so it matches the packaged config's ``upright.model_dir`` defaults.
+ """
+ root = Path(root).expanduser()
+ installed = {}
+ for name, sha256 in UPRIGHT_MODELS.items():
+ installed[name] = _ensure_model(
+ root / name,
+ f"{UPRIGHT_MODEL_BASE}/{name}_infer.tar",
+ sha256,
+ f"{name}_infer",
+ name,
+ f"{name} (rotation) model",
+ )
+ return installed
diff --git a/sdk/minicpmvocr/pipeline/__init__.py b/sdk/minicpmvocr/pipeline/__init__.py
index 86b0316..52fc1d0 100644
--- a/sdk/minicpmvocr/pipeline/__init__.py
+++ b/sdk/minicpmvocr/pipeline/__init__.py
@@ -1,6 +1,7 @@
from __future__ import annotations
__all__ = [
+ "assemble_document_json",
"infer_run",
"parse_layout_run",
"pipelined_run",
@@ -9,6 +10,9 @@ __all__ = [
def __getattr__(name: str):
+ if name == "assemble_document_json":
+ from ._response import assemble_document_json
+ return assemble_document_json
if name == "pipelined_run":
from .overlapped import pipelined_run
return pipelined_run
diff --git a/sdk/minicpmvocr/pipeline/_blocks.py b/sdk/minicpmvocr/pipeline/_blocks.py
index 56cfb4f..af71d53 100644
--- a/sdk/minicpmvocr/pipeline/_blocks.py
+++ b/sdk/minicpmvocr/pipeline/_blocks.py
@@ -7,6 +7,7 @@ from typing import Dict, List, Optional
from PIL import Image
+from ._response import RESPONSE_DIRNAME, page_response, public_block_status
from ._text import _normalize_and_dedupe_blocks
from ._tts import _execute_block_adaptive, _execute_block_tts
from ..backends import PNG_COMPRESS_LEVEL
@@ -52,13 +53,16 @@ def _execute_block(engine, prompt_map: Dict, image_id: str, crop_dir: Path, bloc
queue_wait_sec = round(crop_started - submitted_at, 6) if submitted_at else 0.0
if elem_cfg is None or block.get("skip_vlm", False):
+ # Skipped seal blocks keep the online contract status; every other
+ # skipped label reports skipped_no_vlm.
+ skip_status = "skipped_seal" if label == "seal" else "skipped_no_vlm"
return {
"result_block": {
"label": label,
"order": block.get("order", 0),
"bbox": block.get("bbox"),
"crop_filename": crop_filename,
- "status": "skipped_no_vlm",
+ "status": skip_status,
"content": "",
"raw_content": "",
},
@@ -66,7 +70,7 @@ def _execute_block(engine, prompt_map: Dict, image_id: str, crop_dir: Path, bloc
"image_id": image_id,
"label": label,
"crop_filename": crop_filename,
- "status": "skipped_no_vlm",
+ "status": skip_status,
"duration_sec": 0.0,
},
"prep_sec": 0.0,
@@ -83,7 +87,7 @@ def _execute_block(engine, prompt_map: Dict, image_id: str, crop_dir: Path, bloc
"order": block.get("order", 0),
"bbox": block.get("bbox"),
"crop_filename": crop_filename,
- "status": "missing_crop",
+ "status": "failed",
"content": "",
"raw_content": "",
},
@@ -253,7 +257,9 @@ def _execute_block(engine, prompt_map: Dict, image_id: str, crop_dir: Path, bloc
"order": block.get("order", 0),
"bbox": block.get("bbox"),
"crop_filename": crop_filename,
- "status": infer_status,
+ # The crop row keeps the specific failure reason; the block carries the
+ # public status only.
+ "status": public_block_status(infer_status),
"content": content,
"raw_content": raw_text,
"inline_formula_mixed": (
@@ -568,6 +574,15 @@ def _finalize_page(
"result_stage": "infer_final",
}
write_json(json_path, result_obj)
+ usage = {
+ "prompt_tokens": sum(int(r.get("prompt_tokens") or 0) for r in crop_rows),
+ "completion_tokens": sum(int(r.get("completion_tokens") or 0) for r in crop_rows),
+ }
+ usage["total_tokens"] = usage["prompt_tokens"] + usage["completion_tokens"]
+ write_json(
+ run_dir / RESPONSE_DIRNAME / f"{image_id}.json",
+ page_response(layout=layout, blocks=final_blocks, markdown=markdown, usage=usage),
+ )
status = "ok" if num_failed_blocks == 0 else "partial_failed"
row = {
diff --git a/sdk/minicpmvocr/pipeline/_layout_record.py b/sdk/minicpmvocr/pipeline/_layout_record.py
index 18901bc..fa9c1ad 100644
--- a/sdk/minicpmvocr/pipeline/_layout_record.py
+++ b/sdk/minicpmvocr/pipeline/_layout_record.py
@@ -215,6 +215,9 @@ def _parse_one_page(
layout["page_image"] = page_image_rel
if upright_record is not None:
layout["upright"] = upright_record
+ elif bool((cfg.get("upright") or {}).get("enabled", False)):
+ # Requested but no corrector could be built (paddleocr missing).
+ layout["upright"] = {"skipped_reason": "unavailable"}
phase["png_save_sec"] = float(layout.get("png_save_sec", 0.0))
diff --git a/sdk/minicpmvocr/pipeline/_response.py b/sdk/minicpmvocr/pipeline/_response.py
new file mode 100644
index 0000000..2d9c5c4
--- /dev/null
+++ b/sdk/minicpmvocr/pipeline/_response.py
@@ -0,0 +1,120 @@
+'Page and document JSON in the shape of the online document-parse API.'
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Dict, List, Optional
+
+from .._utils import read_json, read_jsonl
+
+#: Block statuses of the online contract. Anything else is an internal failure
+#: reason (``missing_crop``, ``vllm_error``, ...) and is reported as ``failed``.
+PUBLIC_BLOCK_STATUSES = ("ok", "failed", "skipped_no_vlm", "skipped_seal")
+
+#: Online jobs join page Markdown with a blank line and no page marker.
+DOCUMENT_PAGE_DELIMITER = "\n\n"
+
+RESPONSE_DIRNAME = "pages_json"
+
+
+def public_block_status(status: str) -> str:
+ return status if status in PUBLIC_BLOCK_STATUSES else "failed"
+
+
+def rotation_record(upright: Optional[Dict]) -> Dict:
+ """Map the corrector's record (layout["upright"]) to the online ``ocr.rotation``.
+
+ ``upright`` is None when rotation was not requested. Angles are degrees,
+ counterclockwise positive; ``total_angle`` is orientation plus deskew.
+ """
+ out = {
+ "enabled": upright is not None,
+ "applied": False,
+ "predicted_angle": None,
+ "predicted_score": None,
+ "confirmed": None,
+ "orientation_angle": 0,
+ "deskew_angle": 0.0,
+ "total_angle": 0.0,
+ "skipped_reason": None,
+ }
+ if upright is None:
+ return out
+ if upright.get("skipped_reason"):
+ out["skipped_reason"] = upright["skipped_reason"]
+ return out
+ if upright.get("gated"):
+ out["skipped_reason"] = "gated"
+ return out
+ predicted = upright.get("label_vetoed", upright.get("label", 0))
+ out.update(
+ applied=bool(upright.get("applied", False)),
+ predicted_angle=predicted,
+ predicted_score=upright.get("score"),
+ orientation_angle=upright.get("label", 0),
+ deskew_angle=float(upright.get("deskew", 0.0)),
+ total_angle=float(upright.get("correction", 0.0)),
+ )
+ # The vote only runs for a non-zero prediction; without it there is nothing
+ # that confirmed or vetoed the classifier.
+ if "vote" in upright:
+ out["confirmed"] = "label_vetoed" not in upright
+ return out
+
+
+def page_response(*, layout: Dict, blocks: List[Dict], markdown: str,
+ usage: Optional[Dict] = None) -> Dict:
+ 'One page as the online synchronous response / one item of a job\'s pages[].'
+ regions = {b.get("order"): b.get("regions") for b in layout.get("blocks") or []}
+ source = layout.get("source") or {}
+ ocr_blocks = []
+ for block in blocks:
+ bbox = block.get("bbox")
+ ocr_blocks.append({
+ "order": block.get("order", 0),
+ "label": block.get("label", ""),
+ "bbox": bbox,
+ "regions": regions.get(block.get("order")) or ([bbox] if bbox else []),
+ "content": block.get("content", ""),
+ "status": public_block_status(block.get("status", "")),
+ "inline_formula_mixed": bool(block.get("inline_formula_mixed", False)),
+ })
+ response = {
+ "metadata": {"page_index": source.get("page_index") or 0},
+ "choices": [{"message": {"content": markdown}}],
+ "ocr": {
+ "coordinate_space": "processed_image",
+ "mode": "ocr_only",
+ "image_width": layout.get("image_width"),
+ "image_height": layout.get("image_height"),
+ "blocks": ocr_blocks,
+ "rotation": rotation_record(layout.get("upright")),
+ },
+ }
+ if usage is not None:
+ response["usage"] = usage
+ return response
+
+
+def assemble_document_json(run_dir: Path) -> Dict:
+ """Collect a run's pages into the online job shape: pages[] plus job markdown.
+
+ ``status`` is ``Success`` only when every planned page produced a response.
+ """
+ run_dir = Path(run_dir)
+ tasks = read_jsonl(run_dir / "runtime" / "page_tasks.jsonl")
+ pages = []
+ for task in tasks:
+ page = read_json(run_dir / RESPONSE_DIRNAME / f"{task['image_id']}.json", default=None)
+ if page is not None:
+ pages.append(page)
+ pages.sort(key=lambda p: p["metadata"]["page_index"])
+ complete = bool(tasks) and len(pages) == len(tasks)
+ return {
+ "status": "Success" if complete else "Failed",
+ "pages_done": len(pages),
+ "pages_total": len(tasks),
+ "pages": pages,
+ "markdown": DOCUMENT_PAGE_DELIMITER.join(
+ p["choices"][0]["message"]["content"] for p in pages
+ ),
+ }
diff --git a/sdk/minicpmvocr/pipeline/upright.py b/sdk/minicpmvocr/pipeline/upright.py
index af84b56..220cbec 100644
--- a/sdk/minicpmvocr/pipeline/upright.py
+++ b/sdk/minicpmvocr/pipeline/upright.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import base64
import io
import json
+import logging
import os
import queue
import threading
@@ -14,6 +15,8 @@ from typing import Dict, List, Optional, Tuple
import numpy as np
+LOGGER = logging.getLogger(__name__)
+
SMALL = 1100
@@ -310,8 +313,12 @@ class UprightCorrector:
def _predictor_kwargs(model_name: str, model_dir: str, up: Dict) -> Dict:
kwargs = {"model_name": model_name}
- if model_dir:
+ if model_dir and os.path.isdir(model_dir):
kwargs["model_dir"] = model_dir
+ elif model_dir:
+ # The packaged config points at ${ASSETS_DIR}/paddle_upright, which only
+ # the CLI prepares; let paddleocr fetch the same official model instead.
+ LOGGER.warning("%s 模型目录不存在:%s,改由 paddleocr 按模型名下载。", model_name, model_dir)
device = str(up.get("device") or os.environ.get("OCR_UPRIGHT_DEVICE") or "").strip()
if device:
kwargs["device"] = device
@@ -524,4 +531,16 @@ def build_upright_fleet(local: "UprightPool | None", registry: str) -> UprightFl
def build_upright_corrector(cfg: Dict) -> "UprightCorrector | None":
'A corrector when the config asks for one, else None.'
- return UprightCorrector(cfg) if upright_enabled(cfg) else None
+ if not upright_enabled(cfg):
+ return None
+ try:
+ return UprightCorrector(cfg)
+ except RuntimeError as exc:
+ # Missing optional paddleocr dependency degrades to "no upright" with a
+ # warning instead of failing the whole run; model problems still raise.
+ if "requires paddleocr" not in str(exc):
+ raise
+ LOGGER.warning(
+ "upright.enabled=true 但缺少 paddleocr 依赖,本次运行跳过摆正(%s)。"
+ "安装 minicpm-ocr[upright] 后重启可启用。", exc)
+ return None
diff --git a/sdk/tests/test_layout_download.py b/sdk/tests/test_layout_download.py
index c4a9b6a..a689a8f 100644
--- a/sdk/tests/test_layout_download.py
+++ b/sdk/tests/test_layout_download.py
@@ -182,3 +182,70 @@ def test_concurrent_callers_download_once(tmp_path, remote):
assert results == [model] * 4
assert len(remote["calls"]) == 1
assert download.layout_model_ready(model)
+
+
+def upright_archive(name):
+ output = io.BytesIO()
+ files = {
+ "inference.pdiparams": b"upright-weights",
+ "inference.json": b'{"model": "test"}',
+ "inference.yml": f"Global:\n model_name: {name}\n".encode(),
+ }
+ with tarfile.open(fileobj=output, mode="w") as archive:
+ for fname, content in files.items():
+ info = tarfile.TarInfo(f"{name}_infer/" + fname)
+ info.size = len(content)
+ archive.addfile(info, io.BytesIO(content))
+ return output.getvalue()
+
+
+def test_ensure_upright_models_downloads_missing_and_reuses_existing(tmp_path, monkeypatch):
+ root = tmp_path / "models/paddle_upright"
+ bodies = {name: upright_archive(name) for name in download.UPRIGHT_MODELS}
+ monkeypatch.setattr(download, "UPRIGHT_MODELS", {
+ name: hashlib.sha256(body).hexdigest() for name, body in bodies.items()
+ })
+ calls = []
+
+ class Response:
+ def __init__(self, body):
+ self._body = body
+ self.headers = {"Content-Length": str(len(body))}
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ pass
+
+ def raise_for_status(self):
+ pass
+
+ def iter_content(self, chunk_size):
+ yield self._body
+
+ def get(url, **kwargs):
+ calls.append(url)
+ name = url.rsplit("/", 1)[-1][: -len("_infer.tar")]
+ return Response(bodies[name])
+
+ monkeypatch.setattr(download.requests, "get", get)
+ # One model already present locally: only the other two download.
+ ready_name = next(iter(download.UPRIGHT_MODELS))
+ write_local(root / ready_name, {
+ "inference.pdiparams": b"upright-weights",
+ "inference.json": b'{"model": "test"}',
+ "inference.yml": f"Global:\n model_name: {ready_name}\n".encode(),
+ })
+ installed = download.ensure_upright_models(root)
+ assert set(installed) == set(download.UPRIGHT_MODELS)
+ for name in download.UPRIGHT_MODELS:
+ assert download.layout_model_ready(root / name)
+ if name == ready_name:
+ continue
+ metadata = json.loads((root / name / ".minicpmvocr-model.json").read_text())
+ assert metadata["source"] == f"{download.UPRIGHT_MODEL_BASE}/{name}_infer.tar"
+ assert len(calls) == len(download.UPRIGHT_MODELS) - 1
+ # A second call reuses everything without more downloads.
+ download.ensure_upright_models(root)
+ assert len(calls) == len(download.UPRIGHT_MODELS) - 1
diff --git a/sdk/tests/test_page_response.py b/sdk/tests/test_page_response.py
new file mode 100644
index 0000000..f09224b
--- /dev/null
+++ b/sdk/tests/test_page_response.py
@@ -0,0 +1,142 @@
+from pathlib import Path
+
+import pytest
+
+from minicpmvocr import assemble_document_json, prompts
+from minicpmvocr.pipeline._blocks import _execute_block
+from minicpmvocr.pipeline._response import (
+ RESPONSE_DIRNAME,
+ page_response,
+ public_block_status,
+ rotation_record,
+)
+from minicpmvocr._utils import append_jsonl, write_json
+
+
[email protected]("status,expected", [
+ ("ok", "ok"),
+ ("skipped_no_vlm", "skipped_no_vlm"),
+ ("skipped_seal", "skipped_seal"),
+ ("failed", "failed"),
+ ("missing_crop", "failed"),
+ ("vllm_error", "failed"),
+ ("openai_error", "failed"),
+])
+def test_block_status_follows_online_contract(status, expected):
+ assert public_block_status(status) == expected
+
+
+def test_missing_crop_block_reports_failed_and_keeps_reason_in_crop_row():
+ out = _execute_block(None, prompts.DEFAULT_PROMPT_MAP, "img", Path("/nonexistent"), {
+ "label": "text", "order": 0, "bbox": [0, 0, 1, 1], "crop_filename": "000_text.png",
+ })
+ assert out["result_block"]["status"] == "failed"
+ assert out["crop_row"]["status"] == "missing_crop"
+
+
+# Expected values are the ocr.rotation objects returned by the online API for the
+# same kinds of page: disabled, gated (small image), not applied, applied 270.
+def test_rotation_disabled():
+ assert rotation_record(None) == {
+ "enabled": False, "applied": False, "predicted_angle": None,
+ "predicted_score": None, "confirmed": None, "orientation_angle": 0,
+ "deskew_angle": 0.0, "total_angle": 0.0, "skipped_reason": None,
+ }
+
+
+def test_rotation_gated():
+ assert rotation_record({"gated": True}) == {
+ "enabled": True, "applied": False, "predicted_angle": None,
+ "predicted_score": None, "confirmed": None, "orientation_angle": 0,
+ "deskew_angle": 0.0, "total_angle": 0.0, "skipped_reason": "gated",
+ }
+
+
+def test_rotation_below_apply_threshold():
+ record = {"deskew": 0.2, "label": 0, "score": 0.9271, "deskew_search": "coarse",
+ "correction": 0.2, "applied": False}
+ assert rotation_record(record) == {
+ "enabled": True, "applied": False, "predicted_angle": 0,
+ "predicted_score": 0.9271, "confirmed": None, "orientation_angle": 0,
+ "deskew_angle": 0.2, "total_angle": 0.2, "skipped_reason": None,
+ }
+
+
+def test_rotation_confirmed_and_applied():
+ record = {"deskew": 0.6, "label": 270, "score": 0.9246, "deskew_search": "refined",
+ "vote": 270, "correction": 270.6, "applied": True}
+ assert rotation_record(record) == {
+ "enabled": True, "applied": True, "predicted_angle": 270,
+ "predicted_score": 0.9246, "confirmed": True, "orientation_angle": 270,
+ "deskew_angle": 0.6, "total_angle": 270.6, "skipped_reason": None,
+ }
+
+
+def test_rotation_vetoed_prediction():
+ record = {"deskew": 0.0, "label": 0, "score": 0.6, "vote": 0, "label_vetoed": 180,
+ "correction": 0.0, "applied": False}
+ out = rotation_record(record)
+ assert out["predicted_angle"] == 180
+ assert out["orientation_angle"] == 0
+ assert out["confirmed"] is False
+
+
+def test_rotation_unavailable():
+ out = rotation_record({"skipped_reason": "unavailable"})
+ assert out["enabled"] is True and out["applied"] is False
+ assert out["skipped_reason"] == "unavailable"
+
+
+def _layout(page_index=None):
+ return {
+ "image_width": 1700, "image_height": 2200,
+ "source": {"page_index": page_index},
+ "blocks": [
+ {"order": 0, "regions": [[1, 2, 3, 4]]},
+ {"order": 16, "regions": [[5, 6, 7, 8], [9, 10, 11, 12]]},
+ ],
+ }
+
+
+def test_page_response_shape():
+ blocks = [
+ {"order": 0, "label": "number", "bbox": [1, 2, 3, 4], "content": "6", "status": "ok",
+ "raw_content": "6", "crop_filename": "000_number.png"},
+ {"order": 16, "label": "text", "bbox": [5, 6, 7, 8], "content": "", "status": "vllm_error"},
+ ]
+ page = page_response(layout=_layout(), blocks=blocks, markdown="md",
+ usage={"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3})
+ assert set(page) == {"metadata", "choices", "ocr", "usage"}
+ assert page["metadata"] == {"page_index": 0}
+ assert page["choices"] == [{"message": {"content": "md"}}]
+ ocr = page["ocr"]
+ assert (ocr["image_width"], ocr["image_height"]) == (1700, 2200)
+ assert ocr["rotation"]["enabled"] is False
+ assert ocr["blocks"][0] == {
+ "order": 0, "label": "number", "bbox": [1, 2, 3, 4], "regions": [[1, 2, 3, 4]],
+ "content": "6", "status": "ok", "inline_formula_mixed": False,
+ }
+ assert ocr["blocks"][1]["regions"] == [[5, 6, 7, 8], [9, 10, 11, 12]]
+ assert ocr["blocks"][1]["status"] == "failed"
+
+
+def test_document_json_orders_pages_and_joins_markdown(tmp_path):
+ for idx, image_id in [(1, "doc_page_002"), (0, "doc_page_001")]:
+ append_jsonl(tmp_path / "runtime" / "page_tasks.jsonl", {"image_id": image_id})
+ write_json(tmp_path / RESPONSE_DIRNAME / f"{image_id}.json",
+ page_response(layout=_layout(idx), blocks=[], markdown=f"page {idx}"))
+ doc = assemble_document_json(tmp_path)
+ assert doc["status"] == "Success"
+ assert (doc["pages_done"], doc["pages_total"]) == (2, 2)
+ assert [p["metadata"]["page_index"] for p in doc["pages"]] == [0, 1]
+ assert doc["markdown"] == "page 0\n\npage 1"
+
+
+def test_document_json_missing_page_is_failed(tmp_path):
+ append_jsonl(tmp_path / "runtime" / "page_tasks.jsonl", {"image_id": "a"})
+ append_jsonl(tmp_path / "runtime" / "page_tasks.jsonl", {"image_id": "b"})
+ write_json(tmp_path / RESPONSE_DIRNAME / "a.json",
+ page_response(layout=_layout(), blocks=[], markdown="a"))
+ doc = assemble_document_json(tmp_path)
+ assert doc["status"] == "Failed"
+ assert (doc["pages_done"], doc["pages_total"]) == (1, 2)
diff --git a/sdk/tests/test_parse_quickstart.py b/sdk/tests/test_parse_quickstart.py
index eda6952..fc09337 100644
--- a/sdk/tests/test_parse_quickstart.py
+++ b/sdk/tests/test_parse_quickstart.py
@@ -49,7 +49,7 @@ class FakeEngine:
@pytest.fixture
def quickstart(tmp_path, monkeypatch):
- for name in ("OCR_LAYOUT_MODEL_DIR", "OCR_ASSETS_DIR", "OCR_LAYOUT_DEVICE", "VLLM_URL", "OCR_SERVED_NAME", "OCR_INPUT_DIR", "OCR_RUN_ROOT"):
+ for name in ("OCR_LAYOUT_MODEL_DIR", "OCR_ASSETS_DIR", "OCR_LAYOUT_DEVICE", "OCR_UPRIGHT_DIR", "VLLM_URL", "OCR_SERVED_NAME", "OCR_INPUT_DIR", "OCR_RUN_ROOT"):
monkeypatch.delenv(name, raising=False)
monkeypatch.chdir(tmp_path)
def reject_network(*args, **kwargs):
@@ -61,7 +61,13 @@ def quickstart(tmp_path, monkeypatch):
(model / "inference.pdiparams").write_bytes(b"test-weights")
(model / "inference.json").write_text("{}")
(model / "inference.yml").write_text("Global:\n model_name: PP-DocLayoutV3\n")
- seen = {"configs": [], "layouts": []}
+ for name in download.UPRIGHT_MODELS:
+ upright_model = tmp_path / "models/paddle_upright" / name
+ upright_model.mkdir(parents=True)
+ (upright_model / "inference.pdiparams").write_bytes(b"test-weights")
+ (upright_model / "inference.json").write_text("{}")
+ (upright_model / "inference.yml").write_text(f"Global:\n model_name: {name}\n")
+ seen = {"configs": [], "layouts": [], "uprights": []}
def build_detector(config):
seen["layouts"].append(deepcopy(config))
@@ -71,9 +77,14 @@ def quickstart(tmp_path, monkeypatch):
seen["configs"].append(deepcopy(config))
return FakeEngine()
+ def build_upright(config):
+ seen["uprights"].append(deepcopy(config))
+ return None
+
for module in (staged, overlapped):
monkeypatch.setattr(module, "create_layout_detector", build_detector)
monkeypatch.setattr(module, "create_backend", build_engine)
+ monkeypatch.setattr(module, "build_upright_corrector", build_upright)
return tmp_path, model, seen
@@ -91,11 +102,32 @@ def test_short_cpu_and_gpu_commands_write_markdown(quickstart, monkeypatch, caps
assert cfg["engine"]["server_urls"] == [SERVER_URL]
assert cfg["pipeline"]["max_workers"] == 32
assert cfg["pipeline"]["merge_cross_page_tables"] is False
+ assert cfg["upright"]["enabled"] is True
+ assert cfg["upright"]["model_dir"] == str(root / "models/paddle_upright/PP-LCNet_x1_0_doc_ori")
+ assert cfg["upright"]["det_model_dir"] == str(root / "models/paddle_upright/PP-OCRv5_mobile_det")
+ assert cfg["upright"]["textline_model_dir"] == str(root / "models/paddle_upright/PP-LCNet_x1_0_textline_ori")
+ assert seen["uprights"], "quickstart should build an upright corrector"
summary = json.loads(capsys.readouterr().out)
assert summary["pages"] == 1
assert summary["layout_summary"]["overlapped"] is True
+def test_upright_can_be_disabled_with_set(quickstart, monkeypatch, capsys):
+ _, _, seen = quickstart
+ _set_argv(monkeypatch, [
+ "minicpmvocr", "parse", "input.png", "-o", "result.md", "--device", "cpu",
+ "--set", "upright.enabled=false",
+ ])
+ assert cli.main() == 0
+ cfg = seen["configs"][0]
+ assert cfg["upright"]["enabled"] is False
+ # The runners ask for a corrector unconditionally and drop it when
+ # disabled, so every recorded config must be an upright-off one.
+ assert seen["uprights"]
+ assert all(not entry["upright"]["enabled"] for entry in seen["uprights"])
+ assert json.loads(capsys.readouterr().out)["pages"] == 1
+
+
def test_pdf_quickstart_renders_and_exports_all_pages(quickstart, monkeypatch, capsys):
fitz = pytest.importorskip("fitz")
root, _, _ = quickstart
diff --git a/sdk/tests/test_skip_vlm_labels.py b/sdk/tests/test_skip_vlm_labels.py
index 3366911..f8ad22a 100644
--- a/sdk/tests/test_skip_vlm_labels.py
+++ b/sdk/tests/test_skip_vlm_labels.py
@@ -203,3 +203,28 @@ def test_explicitly_ignored_header_footer_images_stay_hidden(label):
assert assemble_markdown(
[{"label": label, "content": "COURT OFFICE"}], prompt_map
) == ""
+
+
+def test_skipped_seal_reports_online_contract_status():
+ from pathlib import Path
+
+ from minicpmvocr.pipeline._blocks import _execute_block
+
+ out = _execute_block(None, prompts.DEFAULT_PROMPT_MAP, "img", Path("."), {
+ "label": "seal", "order": 0, "bbox": [0, 0, 1, 1], "skip_vlm": True,
+ })
+ assert out["result_block"]["status"] == "skipped_seal"
+ assert out["result_block"]["content"] == ""
+ assert out["crop_row"]["status"] == "skipped_seal"
+
+
+def test_other_skipped_labels_keep_skipped_no_vlm():
+ from pathlib import Path
+
+ from minicpmvocr.pipeline._blocks import _execute_block
+
+ out = _execute_block(None, prompts.DEFAULT_PROMPT_MAP, "img", Path("."), {
+ "label": "image", "order": 0, "bbox": [0, 0, 1, 1], "skip_vlm": True,
+ })
+ assert out["result_block"]["status"] == "skipped_no_vlm"
+ assert out["crop_row"]["status"] == "skipped_no_vlm"