Skip to content

Fast, accurate OCR with correctness assessment.

sdk: parse several inputs in one run, with one result per file.

huangfw7bbab7d8d2b4
diff --git a/docs/minicpm_ocr_sdk_api.md b/docs/minicpm_ocr_sdk_api.md
index 13d27fb..9652441 100644
--- a/docs/minicpm_ocr_sdk_api.md
+++ b/docs/minicpm_ocr_sdk_api.md
@@ -13,11 +13,21 @@ minicpmvocr parse doc.pdf -o doc.md --device cuda:0 \
--server-url http://127.0.0.1:18499 --model minicpm-ocr
```
+一次解析多个文件时,每个文件各写一份结果:
+
+```bash
+minicpmvocr parse a.png b.png doc.pdf -o out/ --json \
+ --device cuda:0 --server-url http://127.0.0.1:18499 --model minicpm-ocr
+```
+
+`out/` 下得到 `a.md`、`a.json`、`b.md`、`b.json`、`doc.md`、`doc.json`。也可以直接传一个目录,只取该目录顶层的图片和 PDF,不递归。
+
| 参数 | 说明 |
|---|---|
-| `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` |
+| `INPUT` / `--input FILE` | 输入文件,支持 PDF、PNG、JPG、JPEG、GIF、BMP、WebP、TIF、TIFF;两种写法都可以重复,也可以传一个目录 |
+| `-o PATH` / `--output PATH` | 单个输入时为 Markdown 路径;多个输入时必须是目录,每个输入写一份 `<文件名>.md`;省略时输出到标准输出 |
+| `--json [PATH]` | 另外输出 JSON,结构与线上文档解析异步任务一致。单个输入时 `PATH` 是文件,省略时写在 Markdown 旁边;多个输入时写 `<文件名>.json` |
+| `--split-images` | 把每张单图当作独立文档,而不是同一份文档的各页。PDF 始终按文件合并 |
| `--server-url URL` | 必填,识别服务地址;可重复传入以连接多个服务实例 |
| `--model NAME` | 必填,服务暴露的模型名称,对应 vLLM 的 `--served-model-name` |
| `--device DEVICE` | 版面检测设备,例如 `cuda:0`;不改变识别服务使用的设备 |
@@ -94,4 +104,8 @@ if __name__ == "__main__":
`ensure_layout_model()` 复用或下载官方版面模型;`load_config()` 合并配置并校验输入;`pipelined_run()` 执行版面检测和识别;`assemble_document_markdown()` 返回合并后的 Markdown、页数和跨页表格合并次数。
+多个输入时,`runtime/sources.json` 记录每个输入文件对应哪些页以及单图的文档范围;`pages_json/<image_id>.json` 与线上单页响应同构,`metadata` 里额外带 `source`(原文件路径)和 `image_id`。`assemble_documents_json(run_dir)` 返回与 `--json` 相同的按文件分组结果,整批状态为 `Success`、`Partial` 或 `Failed`。
+
+单图的文档范围由 `pipeline.image_document_scope` 控制:默认 `collection` 把一次运行里的所有单图视作同一份文档的各页,跨页表格合并可以在图片之间生效;`file` 让每张单图各自成文档,等价于命令行 `--split-images`。PDF 始终按文件合并。单图输入也可以写在 `input.file_paths` 中,按给定顺序处理。
+
运行产物默认写入当前目录下的 `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 05bad8c..6fe8073 100644
--- a/docs/minicpm_ocr_sdk_api_en.md
+++ b/docs/minicpm_ocr_sdk_api_en.md
@@ -13,11 +13,21 @@ minicpmvocr parse doc.pdf -o doc.md --device cuda:0 \
--server-url http://127.0.0.1:18499 --model minicpm-ocr
```
+Parsing several files writes one result per file:
+
+```bash
+minicpmvocr parse a.png b.png doc.pdf -o out/ --json \
+ --device cuda:0 --server-url http://127.0.0.1:18499 --model minicpm-ocr
+```
+
+This writes `a.md`, `a.json`, `b.md`, `b.json`, `doc.md`, and `doc.json` under `out/`. A directory may be given instead; only its top-level PDFs and images are read, without recursion.
+
| Option | Description |
|---|---|
-| `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` |
+| `INPUT` / `--input FILE` | Input file: PDF, PNG, JPG, JPEG, GIF, BMP, WebP, TIF, or TIFF; either form repeats, and a directory is accepted |
+| `-o PATH` / `--output PATH` | Markdown path for one input; must be a directory for several, which writes one `<name>.md` per input; standard output when omitted |
+| `--json [PATH]` | Also write JSON shaped like an online document-parse job. For one input `PATH` is a file and is written next to the Markdown when omitted; several inputs write `<name>.json` |
+| `--split-images` | Treat each standalone image as its own document instead of pages of one collection. PDFs always stay one document per file |
| `--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 |
@@ -94,4 +104,8 @@ 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.
+With several inputs, `runtime/sources.json` records which pages each input file produced and the image document scope. `pages_json/<image_id>.json` matches the online page response, with `metadata` also carrying `source` (the input path) and `image_id`. `assemble_documents_json(run_dir)` returns the same per-file grouping as `--json`, with a batch status of `Success`, `Partial`, or `Failed`.
+
+`pipeline.image_document_scope` sets how standalone images are grouped: `collection` (default) treats every image in the run as pages of one document, so cross-page table merging can span them; `file` makes each image its own document and matches `--split-images`. PDFs always merge per file. Images may also be listed in `input.file_paths`, processed in the given order.
+
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/cli.py b/sdk/minicpmvocr/cli.py
index e4d3d72..e51fc00 100644
--- a/sdk/minicpmvocr/cli.py
+++ b/sdk/minicpmvocr/cli.py
@@ -19,6 +19,7 @@ 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, ensure_upright_models
from .pipeline import infer_run, parse_layout_run, pipelined_run, prepare_run
+from .pipeline._sources import read_sources
from ._utils import read_jsonl
@@ -75,9 +76,14 @@ def _build_parser() -> argparse.ArgumentParser:
epilog="Example:\n minicpmvocr parse doc.pdf -o doc.md --device cuda:0 "
"--server-url http://127.0.0.1:18499 --model minicpm-ocr",
)
- p_parse.add_argument("path", nargs="?", metavar="INPUT", help="PDF or image to parse")
+ p_parse.add_argument(
+ "path", nargs="*", metavar="INPUT",
+ help="PDF or image to parse; repeat for several inputs, or pass one directory",
+ )
p_parse.add_argument("--config", default="", help="Custom YAML config; default uses the bundled quickstart settings")
- p_parse.add_argument("--input", default="", help="Alias for the INPUT positional argument")
+ p_parse.add_argument(
+ "--input", action="append", default=[], metavar="FILE",
+ help="Alias for the INPUT positional argument; repeat for several inputs")
p_parse.add_argument("-o", "--output", default="", help="Output Markdown path; default is stdout")
p_parse.add_argument("--device", default="", help="Layout detection device, e.g. cuda:0 (quickstart default)")
p_parse.add_argument("--layout-model", default="", metavar="DIR", help="Local PP-DocLayoutV3 inference model directory")
@@ -85,7 +91,15 @@ 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(
+ "--split-images", action="store_true",
+ help="Treat each standalone image as its own document instead of pages of one collection "
+ "(sets pipeline.image_document_scope=file); PDFs are always one document per file")
+ p_parse.add_argument(
+ "--json", nargs="?", const="", default=None, metavar="PATH",
+ help="Also write JSON in the online document-parse shape (pages[] + markdown); "
+ "PATH is a file for one input, a directory for several, and omitted writes "
+ "it next to the 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)
@@ -191,15 +205,21 @@ def _build_engine_overrides(args: argparse.Namespace) -> dict:
def _build_parse_overrides(args: argparse.Namespace) -> dict:
- input_path = Path(args.input).resolve()
- run_tag = args.run_tag or f"minicpmvocr_parse_{input_path.stem}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
- return {
+ inputs = args.inputs
+ stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ if len(inputs) == 1:
+ default_tag = f"minicpmvocr_parse_{inputs[0].stem}_{stamp}"
+ input_block = {"file_path": str(inputs[0]), "file_paths": []}
+ else:
+ default_tag = f"minicpmvocr_parse_{len(inputs)}files_{stamp}"
+ input_block = {"file_path": "", "file_paths": [str(p) for p in inputs]}
+ overrides = {
"run": {
- "run_tag": run_tag,
+ "run_tag": args.run_tag or default_tag,
"mode": "oneshot_file",
},
"input": {
- "file_path": str(input_path),
+ **input_block,
"manifest": "",
"image_dir": "",
"files_dir": "",
@@ -213,6 +233,45 @@ def _build_parse_overrides(args: argparse.Namespace) -> dict:
"progress_log_every": 10**9,
},
}
+ if getattr(args, "split_images", False):
+ overrides["pipeline"] = {"image_document_scope": "file"}
+ return overrides
+
+
+def _expand_directory(path: Path) -> list:
+ 'Top-level supported files of a directory, in name order. Directories do not recurse.'
+ files = [
+ p for p in sorted(path.iterdir())
+ if p.is_file() and p.suffix.lower() in SUPPORTED_INPUT_SUFFIXES
+ ]
+ if not files:
+ raise ValueError(f"Directory has no PDF or image files: {path}")
+ return files
+
+
+def _resolve_parse_inputs(args: argparse.Namespace) -> list:
+ 'Every input file, in the order given; directories expand to their top-level files.'
+ requested = [Path(p) for p in (args.path or [])] + [Path(p) for p in (args.input or [])]
+ if not requested:
+ raise ValueError("An input PDF or image is required")
+ resolved: list = []
+ seen = set()
+ for item in requested:
+ if item.is_dir():
+ candidates = _expand_directory(item)
+ elif not item.exists():
+ raise FileNotFoundError(f"Input file not found: {item}")
+ elif item.suffix.lower() not in SUPPORTED_INPUT_SUFFIXES:
+ raise ValueError(f"Unsupported input file type: {item.suffix}")
+ else:
+ candidates = [item]
+ for candidate in candidates:
+ key = str(candidate.resolve())
+ if key in seen:
+ continue
+ seen.add(key)
+ resolved.append(candidate.resolve())
+ return resolved
def _quickstart_layout_model() -> str:
@@ -246,19 +305,7 @@ def _load_parse_config(args: argparse.Namespace) -> dict:
raise ValueError("--server-url URL is required and must not be empty")
if not args.model.strip():
raise ValueError("--model NAME is required and must not be empty")
- positional = args.path or ""
- if positional and args.input:
- raise ValueError("Specify INPUT or --input, not both")
- args.input = positional or args.input
- if not args.input:
- raise ValueError("An input PDF or image is required")
- if Path(args.input).is_dir():
- raise ValueError("INPUT must be a PDF or image file")
- input_path = Path(args.input)
- if not input_path.is_file():
- raise FileNotFoundError(f"Input file not found: {input_path}")
- if input_path.suffix.lower() not in SUPPORTED_INPUT_SUFFIXES:
- raise ValueError(f"Unsupported input file type: {input_path.suffix}")
+ args.inputs = _resolve_parse_inputs(args)
overrides = _build_parse_overrides(args)
explicit_overrides = _build_engine_overrides(args)
@@ -370,7 +417,7 @@ def _read_markdown_from_run(
from .prompts import load_prompt_map
markdown, pages, _ = assemble_document_markdown(
- run_dir, load_prompt_map(cfg), merge_tables=True, delimiter=page_delimiter
+ run_dir, load_prompt_map(cfg), merge_tables=True, delimiter=page_delimiter, cfg=cfg
)
if pages:
return markdown, pages
@@ -380,6 +427,87 @@ def _read_markdown_from_run(
return page_texts[0], 1
+def _output_names(sources: list) -> dict:
+ 'source_id -> file stem; a stem shared by two inputs gets its source_id in front.'
+ stems = [Path(source.get("path") or source.get("source_id") or "input").stem for source in sources]
+ shared = {stem for stem in stems if stems.count(stem) > 1}
+ names = {}
+ for source, stem in zip(sources, stems):
+ prefix = f"{source.get('source_id', '')}_" if stem in shared else ""
+ names[source.get("source_id", "")] = f"{prefix}{stem}"
+ return names
+
+
+def _parse_many(args: argparse.Namespace, cfg: dict, run_dir: Path,
+ layout_summary: dict, infer_summary: dict) -> int:
+ """Write one Markdown (and with --json one JSON) per input file."""
+ if args.stdout:
+ raise ValueError("--stdout writes a single document; use -o DIR for several inputs")
+ if not args.output:
+ raise ValueError("Several inputs need -o DIR to hold one result per input")
+ output_dir = Path(args.output).resolve()
+ if output_dir.exists() and not output_dir.is_dir():
+ raise ValueError(f"-o must be a directory for several inputs: {output_dir}")
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ from .pipeline._response import assemble_documents_json
+ from .postprocess.crosspage import assemble_documents_markdown
+ from .prompts import load_prompt_map
+
+ document = assemble_documents_json(run_dir)
+ markdowns = assemble_documents_markdown(
+ run_dir, load_prompt_map(cfg),
+ merge_tables=bool(cfg["pipeline"].get("merge_cross_page_tables", False)),
+ delimiter=args.page_delimiter, cfg=cfg,
+ )
+ sources = (read_sources(run_dir) or {}).get("sources") or []
+ names = _output_names(sources)
+
+ outputs = []
+ for entry in document["files"]:
+ source_id = entry["source_id"]
+ name = names.get(source_id, source_id or "input")
+ if args.no_merge_pages and entry["pages_total"] > 1:
+ raise ValueError(
+ f"{entry['path']}: {entry['pages_total']} pages; remove --no-merge-pages "
+ "or parse that input on its own")
+ markdown_path = output_dir / f"{name}.md"
+ markdown = markdowns.get(source_id, {}).get("markdown", entry["markdown"])
+ _sync_markdown_images(run_dir, markdown, markdown_path)
+ markdown_path.write_text(markdown, encoding="utf-8")
+ record = {
+ "source_id": source_id,
+ "input": entry["path"],
+ "status": entry["status"],
+ "pages": f"{entry['pages_done']}/{entry['pages_total']}",
+ "output_md": str(markdown_path),
+ }
+ if args.json is not None:
+ json_path = output_dir / f"{name}.json"
+ json_path.write_text(
+ json.dumps(entry, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ record["output_json"] = str(json_path)
+ outputs.append(record)
+
+ print(
+ json.dumps(
+ {
+ "command": "parse",
+ "status": document["status"],
+ "inputs": len(args.inputs),
+ "outputs": outputs,
+ "run_dir": str(run_dir),
+ "layout_summary": layout_summary,
+ "infer_summary": infer_summary,
+ },
+ ensure_ascii=False,
+ indent=2,
+ )
+ )
+ failed = [o for o in outputs if o["status"] == "Failed"]
+ return 1 if len(failed) == len(outputs) else 0
+
+
def main() -> int:
@@ -423,6 +551,12 @@ def main() -> int:
infer_summary = infer_run(cfg)
run_dir = Path(cfg["_meta"]["run_dir"])
+ if len(args.inputs) > 1:
+ try:
+ return _parse_many(args, cfg, run_dir, layout_summary, infer_summary)
+ except (ValueError, OSError) as exc:
+ parser.error(str(exc))
+
markdown, pages = _read_markdown_from_run(
run_dir=run_dir,
merge_pages=not args.no_merge_pages,
@@ -431,10 +565,17 @@ def main() -> int:
)
json_path = None
- if args.json:
+ if args.json is not None:
from .pipeline._response import assemble_document_json
- json_path = Path(args.json).resolve()
+ if not args.json and not args.output:
+ raise ValueError("--json needs a PATH when the Markdown goes to standard output")
+ target = Path(args.json).resolve() if args.json else None
+ if target is not None and target.is_dir():
+ target = target / f"{Path(args.output).stem}.json"
+ elif target is None:
+ target = Path(args.output).with_suffix(".json").resolve()
+ json_path = target
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",
@@ -454,7 +595,7 @@ def main() -> int:
json.dumps(
{
"command": "parse",
- "input": str(Path(args.input).resolve()),
+ "input": str(args.inputs[0]),
"output_md": str(output_path),
**({"output_json": str(json_path)} if json_path else {}),
"pages": pages,
diff --git a/sdk/minicpmvocr/config.py b/sdk/minicpmvocr/config.py
index b6f7d76..b1fe5c8 100644
--- a/sdk/minicpmvocr/config.py
+++ b/sdk/minicpmvocr/config.py
@@ -27,6 +27,7 @@ DEFAULT_CONFIG: Dict[str, Any] = {
"input": {
"manifest": "",
"file_path": "",
+ "file_paths": [],
"image_dir": "",
"files_dir": "",
"limit": 0,
@@ -133,6 +134,8 @@ DEFAULT_CONFIG: Dict[str, Any] = {
"merge_cross_page_tables": False,
+ #: Standalone images as one document ("collection") or one document each ("file").
+ "image_document_scope": "collection",
},
"mm": {
@@ -420,9 +423,33 @@ def _validate_config(cfg: Dict[str, Any], raw: Dict[str, Any] | None = None) ->
validate_engine_config(cfg["engine"])
input_cfg = cfg["input"]
- has_any_input = bool(input_cfg.get("image_dir") or input_cfg.get("files_dir") or input_cfg.get("file_path"))
+ file_paths = input_cfg.get("file_paths") or []
+ if not isinstance(file_paths, (list, tuple)):
+ raise ValueError(
+ "input.file_paths must be a list of file paths, got %r" % (file_paths,))
+ for item in file_paths:
+ if not isinstance(item, str) or not item.strip():
+ raise ValueError("input.file_paths entries must be non-empty paths, got %r" % (item,))
+ path = Path(item)
+ if not path.exists():
+ raise FileNotFoundError(f"input.file_paths entry not found: {item}")
+ if not path.is_file():
+ raise ValueError(f"input.file_paths entry is not a file: {item}")
+ if path.suffix.lower() not in ALLOWED_FILE_SUFFIXES:
+ raise ValueError(f"Unsupported input.file_paths suffix: {path.suffix}")
+
+ has_any_input = bool(
+ input_cfg.get("image_dir") or input_cfg.get("files_dir")
+ or input_cfg.get("file_path") or file_paths)
if not has_any_input:
- raise ValueError("At least one of input.image_dir / input.files_dir / input.file_path is required")
+ raise ValueError(
+ "At least one of input.image_dir / input.files_dir / input.file_path / "
+ "input.file_paths is required")
+
+ scope = (cfg.get("pipeline") or {}).get("image_document_scope", "collection")
+ if scope not in ("collection", "file"):
+ raise ValueError(
+ "pipeline.image_document_scope must be 'collection' or 'file', got %r" % (scope,))
if input_cfg.get("image_dir") and not Path(input_cfg["image_dir"]).exists():
raise FileNotFoundError(f"input.image_dir not found: {input_cfg['image_dir']}")
@@ -491,6 +518,9 @@ def load_config(config_path: str, overrides: Dict[str, Any] | None = None) -> Di
cfg["input"]["manifest"] = _resolve_path(base_dir, cfg["input"].get("manifest", ""))
cfg["input"]["file_path"] = _resolve_path(base_dir, cfg["input"].get("file_path", ""))
+ cfg["input"]["file_paths"] = [
+ _resolve_path(base_dir, item) for item in cfg["input"].get("file_paths") or []
+ ]
cfg["input"]["image_dir"] = _resolve_path(base_dir, cfg["input"].get("image_dir", ""))
cfg["input"]["files_dir"] = _resolve_path(base_dir, cfg["input"].get("files_dir", ""))
diff --git a/sdk/minicpmvocr/configs/minicpmvocr.yaml b/sdk/minicpmvocr/configs/minicpmvocr.yaml
index 2db4728..c297dcf 100644
--- a/sdk/minicpmvocr/configs/minicpmvocr.yaml
+++ b/sdk/minicpmvocr/configs/minicpmvocr.yaml
@@ -9,6 +9,7 @@ run:
input:
manifest: ''
file_path: ''
+ file_paths: []
image_dir: ''
files_dir: ${OCR_INPUT_DIR:-}
limit: 0
@@ -108,6 +109,12 @@ pipeline:
merge_cross_page_tables: false
+ # Standalone images: 'collection' treats every image in the run as pages of one
+ # document (tables may merge across them); 'file' makes each image its own
+ # document. PDFs always stay one document per file.
+ image_document_scope: collection
+
+
mm:
diff --git a/sdk/minicpmvocr/pipeline/_inputs.py b/sdk/minicpmvocr/pipeline/_inputs.py
index b9ffc3d..3c25040 100644
--- a/sdk/minicpmvocr/pipeline/_inputs.py
+++ b/sdk/minicpmvocr/pipeline/_inputs.py
@@ -6,6 +6,7 @@ from typing import Dict, List
from PIL import Image
+from ._sources import image_document_scope, write_sources
from ..constants import (
PDF_RENDER_PAGES_PER_JOB,
PDF_RENDER_ZOOM,
@@ -52,6 +53,17 @@ def _collect_raw_inputs(cfg: Dict) -> List[Path]:
paths: List[Path] = []
seen = set()
+ # An explicit list keeps the caller's order; single files and directories follow.
+ for item in cfg["input"].get("file_paths") or []:
+ p = Path(item)
+ if not p.is_file() or p.suffix.lower() not in SUPPORTED_INPUT_SUFFIXES:
+ continue
+ rp = str(p.resolve())
+ if rp in seen:
+ continue
+ seen.add(rp)
+ paths.append(p)
+
file_path = cfg["input"].get("file_path", "")
if file_path:
p = Path(file_path)
@@ -163,6 +175,8 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:
source_files = _collect_raw_inputs(cfg)
page_entries: List[Dict] = []
+ # Which input file each page entry came from, parallel to page_entries.
+ page_sources: List[int] = []
pdf_files = [p for p in source_files if p.suffix.lower() == ".pdf"]
if pdf_files and fitz is None:
@@ -178,7 +192,7 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:
_render_sec = 0.0
_render_workers = 1
- for path in source_files:
+ for index, path in enumerate(source_files):
suffix = path.suffix.lower()
if suffix in SUPPORTED_IMAGE_SUFFIXES:
page_entries.append(
@@ -190,6 +204,7 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:
"image_path": str(path),
}
)
+ page_sources.append(index)
continue
if suffix == ".pdf":
@@ -215,6 +230,7 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:
"image_bytes": samples,
}
)
+ page_sources.append(index)
continue
@@ -237,6 +253,7 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:
"image_bytes": pix.samples,
}
)
+ page_sources.append(index)
continue
meta = cfg.setdefault("_meta", {})
@@ -246,6 +263,7 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:
limit = _mode_limit(cfg)
if limit > 0:
page_entries = page_entries[:limit]
+ page_sources = page_sources[:limit]
used = set()
for item in page_entries:
@@ -258,6 +276,20 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:
used.add(name)
item["image_id"] = name
+ by_source: Dict[int, List[str]] = {}
+ for item, index in zip(page_entries, page_sources):
+ by_source.setdefault(index, []).append(item["image_id"])
+ manifest = [
+ {
+ "source_type": "pdf" if source_files[index].suffix.lower() == ".pdf" else "image",
+ "source_path": str(source_files[index]),
+ "page_count": len(image_ids),
+ "image_ids": image_ids,
+ }
+ for index, image_ids in sorted(by_source.items())
+ ]
+ write_sources(runtime_intermediate.parent, manifest, image_document_scope(None, cfg))
+
return page_entries
diff --git a/sdk/minicpmvocr/pipeline/_response.py b/sdk/minicpmvocr/pipeline/_response.py
index 2d9c5c4..e9b858a 100644
--- a/sdk/minicpmvocr/pipeline/_response.py
+++ b/sdk/minicpmvocr/pipeline/_response.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from pathlib import Path
from typing import Dict, List, Optional
+from ._sources import read_sources
from .._utils import read_json, read_jsonl
#: Block statuses of the online contract. Anything else is an internal failure
@@ -79,7 +80,13 @@ def page_response(*, layout: Dict, blocks: List[Dict], markdown: str,
"inline_formula_mixed": bool(block.get("inline_formula_mixed", False)),
})
response = {
- "metadata": {"page_index": source.get("page_index") or 0},
+ "metadata": {
+ "page_index": source.get("page_index") or 0,
+ # Which input file this page came from. The online API has one file
+ # per request; a local run can hold several, so the page says which.
+ "source": source.get("path") or "",
+ "image_id": layout.get("image_id", ""),
+ },
"choices": [{"message": {"content": markdown}}],
"ocr": {
"coordinate_space": "processed_image",
@@ -96,9 +103,11 @@ def page_response(*, layout: Dict, blocks: List[Dict], markdown: str,
def assemble_document_json(run_dir: Path) -> Dict:
- """Collect a run's pages into the online job shape: pages[] plus job markdown.
+ """Collect a single-source run's pages into the online job shape.
``status`` is ``Success`` only when every planned page produced a response.
+ A run with several inputs is a batch of documents; use
+ ``assemble_documents_json`` for it.
"""
run_dir = Path(run_dir)
tasks = read_jsonl(run_dir / "runtime" / "page_tasks.jsonl")
@@ -118,3 +127,72 @@ def assemble_document_json(run_dir: Path) -> Dict:
p["choices"][0]["message"]["content"] for p in pages
),
}
+
+
+def _file_entry(source: Dict, pages: List[Dict]) -> Dict:
+ planned = int(source.get("pages") or len(source.get("image_ids") or []))
+ done = len(pages)
+ if done and done == planned:
+ status = "Success"
+ elif done:
+ status = "Partial"
+ else:
+ status = "Failed"
+ return {
+ "source_id": source.get("source_id", ""),
+ "path": source.get("path", ""),
+ "type": source.get("type", ""),
+ "status": status,
+ "pages_done": done,
+ "pages_total": planned,
+ "pages": pages,
+ "markdown": DOCUMENT_PAGE_DELIMITER.join(
+ p["choices"][0]["message"]["content"] for p in pages),
+ }
+
+
+def assemble_documents_json(run_dir: Path) -> Dict:
+ """One entry per input file: the online job shape, plus which file it was.
+
+ A run without a source manifest (written before it existed) is reported as
+ one entry, which is what such a run was.
+ """
+ run_dir = Path(run_dir)
+ manifest = read_sources(run_dir)
+ if manifest is None:
+ document = assemble_document_json(run_dir)
+ document["files"] = [{
+ "source_id": "",
+ "path": "",
+ "type": "",
+ "status": document["status"],
+ "pages_done": document["pages_done"],
+ "pages_total": document["pages_total"],
+ "pages": document["pages"],
+ "markdown": document["markdown"],
+ }]
+ document["status"] = "Success" if document["pages_done"] else "Failed"
+ return document
+
+ files = []
+ for source in manifest.get("sources") or []:
+ pages = []
+ for image_id in source.get("image_ids") or []:
+ page = read_json(run_dir / RESPONSE_DIRNAME / f"{image_id}.json", default=None)
+ if page is not None:
+ pages.append(page)
+ files.append(_file_entry(source, pages))
+
+ statuses = [f["status"] for f in files]
+ if statuses and all(s == "Success" for s in statuses):
+ status = "Success"
+ elif any(s != "Failed" for s in statuses):
+ status = "Partial"
+ else:
+ status = "Failed"
+ return {
+ "status": status,
+ "files_done": sum(1 for s in statuses if s == "Success"),
+ "files_total": len(files),
+ "files": files,
+ }
diff --git a/sdk/minicpmvocr/pipeline/_sources.py b/sdk/minicpmvocr/pipeline/_sources.py
new file mode 100644
index 0000000..3217c94
--- /dev/null
+++ b/sdk/minicpmvocr/pipeline/_sources.py
@@ -0,0 +1,70 @@
+'Input manifest: which source file produced which pages.'
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Dict, List, Optional
+
+from .._utils import now_iso, write_json
+
+#: ``collection`` groups every standalone image in a run into one document (the
+#: historical behaviour); ``file`` makes each image its own document, as a batch
+#: of unrelated pictures needs.
+IMAGE_DOCUMENT_SCOPES = ("collection", "file")
+
+SOURCES_FILENAME = "sources.json"
+
+
+def write_sources(runtime_dir: Path, entries: List[Dict], image_document_scope: str) -> Path:
+ 'Record input -> pages for ``entries`` in input order; returns the manifest path.'
+ sources = []
+ for index, entry in enumerate(entries, start=1):
+ sources.append({
+ "source_id": "s%03d" % index,
+ "path": str(entry.get("source_path") or ""),
+ "type": str(entry.get("source_type") or ""),
+ "pages": int(entry.get("page_count") or 0),
+ "image_ids": list(entry.get("image_ids") or []),
+ })
+ path = Path(runtime_dir) / SOURCES_FILENAME
+ write_json(path, {
+ "generated_at": now_iso(),
+ "image_document_scope": image_document_scope,
+ "sources": sources,
+ })
+ return path
+
+
+def read_sources(run_dir: Path) -> Optional[Dict]:
+ 'The manifest of a run, or None for runs written before it existed.'
+ path = Path(run_dir) / "runtime" / SOURCES_FILENAME
+ if not path.is_file():
+ return None
+ with path.open("r", encoding="utf-8") as handle:
+ data = json.load(handle)
+ if not isinstance(data, dict) or not data.get("sources"):
+ return None
+ return data
+
+
+def image_document_scope(manifest: Optional[Dict], cfg: Optional[Dict] = None) -> str:
+ 'Scope recorded with the run, falling back to the current config.'
+ if manifest and manifest.get("image_document_scope") in IMAGE_DOCUMENT_SCOPES:
+ return manifest["image_document_scope"]
+ configured = ((cfg or {}).get("pipeline") or {}).get("image_document_scope")
+ return configured if configured in IMAGE_DOCUMENT_SCOPES else "collection"
+
+
+def page_lookup(manifest: Optional[Dict]) -> Dict[str, Dict]:
+ 'image_id -> {source_id, path, type, page_index, order} from the manifest.'
+ lookup: Dict[str, Dict] = {}
+ for index, source in enumerate((manifest or {}).get("sources") or []):
+ for order, image_id in enumerate(source.get("image_ids") or []):
+ lookup[str(image_id)] = {
+ "source_id": source.get("source_id", ""),
+ "path": source.get("path", ""),
+ "type": source.get("type", ""),
+ "source_index": index,
+ "order": order,
+ }
+ return lookup
diff --git a/sdk/minicpmvocr/postprocess/crosspage.py b/sdk/minicpmvocr/postprocess/crosspage.py
index d46ce79..dcf8284 100644
--- a/sdk/minicpmvocr/postprocess/crosspage.py
+++ b/sdk/minicpmvocr/postprocess/crosspage.py
@@ -214,34 +214,53 @@ def merge_cross_page_tables(pages: List[List[Dict]]) -> tuple[List[List[Dict]],
return merged, count
-def load_document_pages(run_dir) -> List[Dict]:
+def _source_document(path: str, is_pdf: bool, scope: str) -> str:
+ """The document a page belongs to, for cross-page grouping.
+
+ A PDF is always one document. A standalone image joins the run's single
+ image document under ``collection`` and is its own document under ``file``.
+ """
+ if is_pdf:
+ return path
+ return "" if scope == "collection" else path
+
+
+def load_document_pages(run_dir, cfg: Dict | None = None) -> List[Dict]:
"Read a run's per-page results back in document order."
from pathlib import Path
from .._utils import read_json
+ from ..pipeline._sources import image_document_scope, page_lookup, read_sources
- results_dir = Path(run_dir) / "results_json"
+ run_dir = Path(run_dir)
+ results_dir = run_dir / "results_json"
if not results_dir.is_dir():
return []
+ manifest = read_sources(run_dir)
+ lookup = page_lookup(manifest)
+ scope = image_document_scope(manifest, cfg)
pages: List[Dict] = []
for path in sorted(results_dir.glob("*.json")):
data = read_json(path, default=None)
if not data:
continue
source = data.get("source") or {}
+ image_id = data.get("image_id", path.stem)
page_index = source.get("page_index")
is_pdf = str(source.get("type") or "") == "pdf" or page_index is not None
+ info = lookup.get(image_id) or {}
pages.append(
{
- "image_id": data.get("image_id", path.stem),
- "document": str(source.get("path") or "") if is_pdf else "",
-
+ "image_id": image_id,
+ "document": _source_document(str(source.get("path") or ""), is_pdf, scope),
+ "source_id": info.get("source_id", ""),
"page_index": int(page_index) if page_index is not None else -1,
+ "order": (info.get("source_index", len(pages)), info.get("order", 0)),
"markdown": data.get("markdown", ""),
"blocks": data.get("crop_blocks") or [],
}
)
- pages.sort(key=lambda p: (p["document"], p["page_index"], p["image_id"]))
+ pages.sort(key=lambda p: (p["document"], p["page_index"], p["order"], p["image_id"]))
return pages
@@ -282,11 +301,51 @@ def apply_cross_page_merge(pages: List[Dict], prompt_map: Dict) -> Dict[str, Dic
return changes
+def assemble_documents_markdown(
+ run_dir, prompt_map: Dict, *, merge_tables: bool, delimiter: str, cfg: Dict | None = None
+) -> Dict[str, Dict]:
+ """One markdown per input file, each joined with ``delimiter``.
+
+ Keys are image_id lists from the source manifest; a run without one yields a
+ single entry holding every page.
+ """
+ from ..pipeline._sources import read_sources
+
+ pages = load_document_pages(run_dir, cfg)
+ if not pages:
+ return {}
+ changes = apply_cross_page_merge(pages, prompt_map) if merge_tables else {}
+ by_id = {p["image_id"]: p for p in pages}
+ manifest = read_sources(run_dir)
+ out: Dict[str, Dict] = {}
+ if manifest is None:
+ out[""] = {
+ "source_id": "",
+ "path": "",
+ "markdown": delimiter.join(p["markdown"] for p in pages),
+ "missing": [],
+ }
+ return out
+ for source in manifest.get("sources") or []:
+ image_ids = list(source.get("image_ids") or [])
+ missing = [i for i in image_ids if i not in by_id]
+ out[source.get("source_id", "")] = {
+ "source_id": source.get("source_id", ""),
+ "path": source.get("path", ""),
+ "markdown": delimiter.join(
+ changes.get(i, by_id.get(i, {"markdown": ""}))["markdown"]
+ for i in image_ids if i in by_id
+ ),
+ "missing": missing,
+ }
+ return out
+
+
def assemble_document_markdown(
- run_dir, prompt_map: Dict, *, merge_tables: bool, delimiter: str
+ run_dir, prompt_map: Dict, *, merge_tables: bool, delimiter: str, cfg: Dict | None = None
) -> tuple[str, int, int]:
"Join a run's pages into one markdown document."
- pages = load_document_pages(run_dir)
+ pages = load_document_pages(run_dir, cfg)
if not pages:
return "", 0, 0
changes = apply_cross_page_merge(pages, prompt_map) if merge_tables else {}
diff --git a/sdk/tests/test_multi_input.py b/sdk/tests/test_multi_input.py
new file mode 100644
index 0000000..9cef5b6
--- /dev/null
+++ b/sdk/tests/test_multi_input.py
@@ -0,0 +1,264 @@
+"""Several input files in one run: one result per file, plus the two image scopes."""
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from PIL import Image
+
+from minicpmvocr.prompts import DEFAULT_PROMPT_MAP
+from minicpmvocr.pipeline._sources import (
+ read_sources,
+ image_document_scope,
+ page_lookup,
+ write_sources,
+)
+from minicpmvocr.pipeline._response import RESPONSE_DIRNAME, page_response, assemble_documents_json
+from minicpmvocr.postprocess.crosspage import (
+ apply_cross_page_merge,
+ assemble_document_markdown,
+ assemble_documents_markdown,
+ load_document_pages,
+)
+from minicpmvocr._utils import write_json
+
+
+def _page_json(image_id, path, text, page_index=0):
+ layout = {
+ "image_id": image_id,
+ "image_width": 100,
+ "image_height": 200,
+ "source": {"type": "pdf" if page_index is not None and path.endswith(".pdf") else "image",
+ "path": path, "page_index": page_index},
+ "blocks": [],
+ }
+ page = page_response(layout=layout, blocks=[], markdown=text)
+ page["ocr"]["blocks"] = []
+ return page
+
+
+def _write_run(tmp_path, sources, pages, scope="collection"):
+ """sources: [(path, type, [image_id...])]; pages: {image_id: (text, blocks)}."""
+ write_sources(tmp_path / "runtime", [
+ {"source_type": kind, "source_path": path, "page_count": len(ids), "image_ids": ids}
+ for path, kind, ids in sources
+ ], scope)
+ for image_id, (text, blocks) in pages.items():
+ path = next(p for p, _k, ids in sources if image_id in ids)
+ page_index = 0
+ if path.endswith(".pdf"):
+ page_index = next(k for k, i in enumerate(next(ids for p, _k, ids in sources if p == path)) if i == image_id)
+ layout = {
+ "image_id": image_id, "image_width": 100, "image_height": 200,
+ "source": {"type": "pdf" if path.endswith(".pdf") else "image",
+ "path": path, "page_index": page_index if path.endswith(".pdf") else None},
+ "blocks": [],
+ }
+ write_json(tmp_path / RESPONSE_DIRNAME / f"{image_id}.json",
+ page_response(layout=layout, blocks=[], markdown=text))
+ write_json(tmp_path / "results_json" / f"{image_id}.json", {
+ "image_id": image_id,
+ "image_width": 100,
+ "image_height": 200,
+ "source": layout["source"],
+ "crop_blocks": blocks,
+ "markdown": text,
+ "result_stage": "infer_final",
+ })
+
+
+def _block(content):
+ return {"order": 0, "label": "text", "bbox": [0, 0, 10, 10], "content": content,
+ "status": "ok"}
+
+
+def _table(rows):
+ html = "<table>" + "".join(
+ "<tr>" + "".join(f"<td>{c}</td>" for c in row) + "</tr>" for row in rows) + "</table>"
+ return {"order": 0, "label": "table", "bbox": [0, 0, 10, 10], "content": html,
+ "status": "ok"}
+
+
+def test_sources_manifest_round_trips(tmp_path):
+ write_sources(tmp_path / "runtime", [
+ {"source_type": "image", "source_path": "/in/a.png", "page_count": 1, "image_ids": ["a"]},
+ {"source_type": "pdf", "source_path": "/in/b.pdf", "page_count": 2,
+ "image_ids": ["b_page_001", "b_page_002"]},
+ ], "file")
+ manifest = read_sources(tmp_path)
+ assert manifest["image_document_scope"] == "file"
+ assert [s["source_id"] for s in manifest["sources"]] == ["s001", "s002"]
+ assert [s["path"] for s in manifest["sources"]] == ["/in/a.png", "/in/b.pdf"]
+ assert page_lookup(manifest)["b_page_002"]["source_id"] == "s002"
+ assert page_lookup(manifest)["b_page_002"]["order"] == 1
+
+
+def test_run_without_manifest_keeps_working(tmp_path):
+ assert read_sources(tmp_path) is None
+ assert image_document_scope(None, {"pipeline": {"image_document_scope": "file"}}) == "file"
+ assert image_document_scope(None, {}) == "collection"
+ assert image_document_scope({"image_document_scope": "file"}, {}) == "file"
+
+
+def test_documents_json_one_entry_per_input_in_input_order(tmp_path):
+ _write_run(tmp_path, [
+ ("/in/b.png", "image", ["b"]),
+ ("/in/a.png", "image", ["a"]),
+ ("/in/doc.pdf", "pdf", ["doc_page_001", "doc_page_002"]),
+ ], {"a": ("alpha", []), "b": ("beta", []), "doc_page_001": ("one", []),
+ "doc_page_002": ("two", [])})
+ document = assemble_documents_json(tmp_path)
+ assert document["status"] == "Success"
+ assert (document["files_done"], document["files_total"]) == (3, 3)
+ assert [f["path"] for f in document["files"]] == ["/in/b.png", "/in/a.png", "/in/doc.pdf"]
+ assert [f["markdown"] for f in document["files"]] == ["beta", "alpha", "one\n\ntwo"]
+ assert document["files"][2]["pages_total"] == 2
+ assert document["files"][0]["pages"][0]["metadata"]["source"] == "/in/b.png"
+
+
+def test_documents_json_reports_partial_and_failed(tmp_path):
+ _write_run(tmp_path, [
+ ("/in/a.png", "image", ["a"]),
+ ("/in/b.png", "image", ["b"]),
+ ("/in/c.png", "image", ["c"]),
+ ], {"a": ("alpha", [])})
+ document = assemble_documents_json(tmp_path)
+ assert document["status"] == "Partial"
+ assert [f["status"] for f in document["files"]] == ["Success", "Failed", "Failed"]
+ assert (document["files_done"], document["files_total"]) == (1, 3)
+
+ fresh = tmp_path / "fresh"
+ _write_run(fresh, [("/in/a.png", "image", ["a"])], {})
+ assert assemble_documents_json(fresh)["status"] == "Failed"
+
+
+def test_documents_markdown_is_one_document_per_input(tmp_path):
+ _write_run(tmp_path, [
+ ("/in/a.png", "image", ["a"]),
+ ("/in/b.png", "image", ["b"]),
+ ], {"a": ("alpha", []), "b": ("beta", [])})
+ markdowns = assemble_documents_markdown(
+ tmp_path, DEFAULT_PROMPT_MAP, merge_tables=False, delimiter="\n---\n")
+ assert {k: v["markdown"] for k, v in markdowns.items()} == {"s001": "alpha", "s002": "beta"}
+
+
+def test_collection_scope_merges_tables_across_images(tmp_path):
+ _write_run(tmp_path, [
+ ("/in/a.png", "image", ["a"]),
+ ("/in/b.png", "image", ["b"]),
+ ], {"a": ("", [_table([["h"], ["1"]])]), "b": ("", [_table([["h"], ["2"]])])})
+ pages = load_document_pages(tmp_path)
+ assert [p["document"] for p in pages] == ["", ""]
+ assert set(apply_cross_page_merge(pages, DEFAULT_PROMPT_MAP)) == {"a", "b"}
+ merged, _, merges = assemble_document_markdown(
+ tmp_path, DEFAULT_PROMPT_MAP, merge_tables=True, delimiter="\n---\n")
+ assert merges == 1 and merged.count("<table") == 1
+
+
+def test_file_scope_keeps_each_image_separate(tmp_path):
+ _write_run(tmp_path, [
+ ("/in/a.png", "image", ["a"]),
+ ("/in/b.png", "image", ["b"]),
+ ], {"a": ("", [_table([["h"], ["1"]])]), "b": ("", [_table([["h"], ["2"]])])}, scope="file")
+ pages = load_document_pages(tmp_path)
+ assert [p["document"] for p in pages] == ["/in/a.png", "/in/b.png"]
+ assert apply_cross_page_merge(pages, DEFAULT_PROMPT_MAP) == {}
+ _, _, merges = assemble_document_markdown(
+ tmp_path, DEFAULT_PROMPT_MAP, merge_tables=True, delimiter="\n---\n")
+ assert merges == 0
+
+
+def test_pdf_pages_still_merge_under_file_scope(tmp_path):
+ _write_run(tmp_path, [
+ ("/in/doc.pdf", "pdf", ["doc_page_001", "doc_page_002"]),
+ ], {"doc_page_001": ("", [_table([["h"], ["1"]])]),
+ "doc_page_002": ("", [_table([["h"], ["2"]])])}, scope="file")
+ _, _, merges = assemble_document_markdown(
+ tmp_path, DEFAULT_PROMPT_MAP, merge_tables=True, delimiter="\n---\n")
+ assert merges == 1
+
+
+def test_config_reads_file_paths_and_scope(tmp_path, monkeypatch):
+ from minicpmvocr.config import load_config
+
+ for name in ("a.png", "b.png"):
+ Image.new("RGB", (10, 10)).save(tmp_path / name)
+ model = tmp_path / "PP-DocLayoutV3_infer"
+ model.mkdir()
+ (model / "inference.pdiparams").write_bytes(b"w")
+ config_path = tmp_path / "cfg.yaml"
+ config_path.write_text(
+ "input:\n file_paths: [a.png, b.png]\n"
+ "pipeline:\n image_document_scope: file\n"
+ f"layout:\n model_dir: {model}\n"
+ "engine:\n type: vllm\n server_url: http://localhost:1\n model_name: m\n",
+ encoding="utf-8")
+ cfg = load_config(str(config_path))
+ assert cfg["input"]["file_paths"] == [str(tmp_path / "a.png"), str(tmp_path / "b.png")]
+ assert cfg["pipeline"]["image_document_scope"] == "file"
+
+
+def test_config_rejects_unknown_scope_and_missing_file_paths(tmp_path):
+ from minicpmvocr.config import load_config
+
+ model = tmp_path / "PP-DocLayoutV3_infer"
+ model.mkdir()
+ (model / "inference.pdiparams").write_bytes(b"w")
+ base = ("engine:\n type: vllm\n server_url: http://localhost:1\n model_name: m\n"
+ f"layout:\n model_dir: {model}\n")
+ bad_scope = tmp_path / "bad_scope.yaml"
+ bad_scope.write_text("input:\n image_dir: .\npipeline:\n image_document_scope: pages\n" + base,
+ encoding="utf-8")
+ with pytest.raises(ValueError, match="image_document_scope"):
+ load_config(str(bad_scope))
+
+ missing = tmp_path / "missing.yaml"
+ missing.write_text("input:\n file_paths: [nope.png]\n" + base, encoding="utf-8")
+ with pytest.raises(FileNotFoundError, match="nope.png"):
+ load_config(str(missing))
+
+
+def _args(**kwargs):
+ defaults = dict(path=[], input=[], inputs=[], run_tag="", split_images=False)
+ defaults.update(kwargs)
+ return SimpleNamespace(**defaults)
+
+
+def test_expanding_a_directory_takes_top_level_files_only(tmp_path):
+ from minicpmvocr.cli import _resolve_parse_inputs
+
+ for name in ("b.png", "a.png", "notes.txt"):
+ (tmp_path / name).write_text("x")
+ nested = tmp_path / "nested"
+ nested.mkdir()
+ (nested / "c.png").write_text("x")
+ inputs = _resolve_parse_inputs(_args(path=[str(tmp_path)]))
+ assert [p.name for p in inputs] == ["a.png", "b.png"]
+
+
+def test_inputs_keep_order_and_drop_duplicates(tmp_path):
+ from minicpmvocr.cli import _resolve_parse_inputs
+
+ for name in ("a.png", "b.png"):
+ (tmp_path / name).write_text("x")
+ inputs = _resolve_parse_inputs(
+ _args(path=[str(tmp_path / "b.png")], input=[str(tmp_path / "a.png"),
+ str(tmp_path / "b.png")]))
+ assert [p.name for p in inputs] == ["b.png", "a.png"]
+
+
+def test_output_names_prefix_shared_stems():
+ from minicpmvocr.cli import _output_names
+
+ names = _output_names([
+ {"source_id": "s001", "path": "/x/a.png"},
+ {"source_id": "s002", "path": "/y/a.png"},
+ {"source_id": "s003", "path": "/z/b.pdf"},
+ ])
+ assert names == {"s001": "s001_a", "s002": "s002_a", "s003": "b"}
+
+
+def test_split_images_sets_file_scope():
+ from minicpmvocr.cli import _build_parse_overrides
+
+ overrides = _build_parse_overrides(_args(inputs=[Path("/in/a.png")], split_images=True))
+ assert overrides["pipeline"] == {"image_document_scope": "file"}
diff --git a/sdk/tests/test_page_response.py b/sdk/tests/test_page_response.py
index f09224b..6092c2a 100644
--- a/sdk/tests/test_page_response.py
+++ b/sdk/tests/test_page_response.py
@@ -107,7 +107,7 @@ def test_page_response_shape():
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["metadata"] == {"page_index": 0, "source": "", "image_id": ""}
assert page["choices"] == [{"message": {"content": "md"}}]
ocr = page["ocr"]
assert (ocr["image_width"], ocr["image_height"]) == (1700, 2200)
diff --git a/sdk/tests/test_parse_quickstart.py b/sdk/tests/test_parse_quickstart.py
index fc09337..baf7a8f 100644
--- a/sdk/tests/test_parse_quickstart.py
+++ b/sdk/tests/test_parse_quickstart.py
@@ -141,6 +141,61 @@ def test_pdf_quickstart_renders_and_exports_all_pages(quickstart, monkeypatch, c
assert json.loads(capsys.readouterr().out)["pages"] == 2
+def test_several_inputs_write_one_result_each(quickstart, monkeypatch, capsys):
+ root, _, _ = quickstart
+ Image.new("RGB", (40, 30), "white").save(root / "second.png")
+ (root / "out").mkdir()
+ _set_argv(monkeypatch, [
+ "minicpmvocr", "parse", "input.png", "second.png", "-o", "out", "--json", "--device", "cpu",
+ ])
+ assert cli.main() == 0
+ summary = json.loads(capsys.readouterr().out)
+ assert summary["status"] == "Success" and summary["inputs"] == 2
+ assert [Path(o["input"]).name for o in summary["outputs"]] == ["input.png", "second.png"]
+ assert {p.name for p in (root / "out").iterdir()} == {
+ "input.md", "input.json", "second.md", "second.json"}
+ assert (root / "out/second.md").read_text() == "Recognized page."
+ document = json.loads((root / "out/second.json").read_text())
+ assert document["status"] == "Success"
+ assert document["pages_total"] == 1
+ assert document["pages"][0]["metadata"]["source"].endswith("second.png")
+
+
+def test_a_directory_input_expands_to_its_files(quickstart, monkeypatch, capsys):
+ root, _, _ = quickstart
+ Image.new("RGB", (40, 30), "white").save(root / "second.png")
+ _set_argv(monkeypatch, ["minicpmvocr", "parse", ".", "-o", "out", "--device", "cpu"])
+ assert cli.main() == 0
+ summary = json.loads(capsys.readouterr().out)
+ assert summary["inputs"] == 2
+ assert (root / "out/input.md").is_file() and (root / "out/second.md").is_file()
+
+
+def test_split_images_keeps_each_image_separate(quickstart, monkeypatch, capsys):
+ root, _, seen = quickstart
+ Image.new("RGB", (40, 30), "white").save(root / "second.png")
+ _set_argv(monkeypatch, [
+ "minicpmvocr", "parse", "input.png", "second.png", "-o", "out",
+ "--split-images", "--device", "cpu",
+ ])
+ assert cli.main() == 0
+ capsys.readouterr()
+ assert seen["configs"][-1]["pipeline"]["image_document_scope"] == "file"
+ from minicpmvocr.pipeline._sources import read_sources
+
+ run_dir = Path(seen["configs"][-1]["_meta"]["run_dir"])
+ assert read_sources(run_dir)["image_document_scope"] == "file"
+
+
+def test_several_inputs_without_output_directory_are_rejected(quickstart, monkeypatch, capsys):
+ root, _, _ = quickstart
+ Image.new("RGB", (40, 30), "white").save(root / "second.png")
+ _set_argv(monkeypatch, ["minicpmvocr", "parse", "input.png", "second.png", "--device", "cpu"])
+ with pytest.raises(SystemExit):
+ cli.main()
+ assert "need -o DIR" in capsys.readouterr().err
+
+
def test_no_output_option_writes_only_markdown_to_stdout(quickstart, monkeypatch, capsys):
_set_argv(monkeypatch, ["minicpmvocr", "parse", "input.png", "--device", "cpu"])
assert cli.main() == 0
@@ -213,8 +268,7 @@ def test_layout_model_option_is_relative_to_working_directory(quickstart, monkey
@pytest.mark.parametrize(("arguments", "message"), [
(["parse"], "input PDF or image is required"),
- (["parse", "input.png", "--input", "input.png"], "Specify INPUT or --input"),
- (["parse", "."], "must be a PDF or image file"),
+ (["parse", "missing.png"], "Input file not found"),
(["parse", "input.png", "--workers", "0"], "must be greater than zero"),
])
def test_invalid_short_commands_report_cli_errors(quickstart, monkeypatch, capsys, arguments, message):