Fast, accurate OCR with correctness assessment.
sdk: stream pages, blocks and decoded text while a run is still going.
caowanxia7b252a51f522
diff --git a/docs/minicpm_ocr_sdk_api.md b/docs/minicpm_ocr_sdk_api.mdindex 9652441..7c32951 100644--- a/docs/minicpm_ocr_sdk_api.md+++ b/docs/minicpm_ocr_sdk_api.md@@ -38,6 +38,7 @@ minicpmvocr parse a.png b.png doc.pdf -o out/ --json \| `--config FILE` | 自定义 YAML 配置文件;省略时使用内置快速开始配置 || `--set KEY=VALUE` | 按点分路径覆盖配置项,可重复传入,例如 `--set input.limit=1` || `--stdout` | 将 Markdown 输出到标准输出,即使同时传入了 `-o` |+| `--stream` / `--stream-ordered` | 每解析完一页就向标准输出写一行 JSON,不等全部解析完,最后一行是运行摘要。`--stream` 按完成先后输出,`--stream-ordered` 按阅读顺序输出。`--stream-detail LEVEL` 设置粒度:`page`(默认)每页一行,`block` 另有版面和每个块的行,`token` 再加每个块解码过程中的文本。`-o`、`--json` 指定的文件仍在结束时写出;多个输入时可以省略 `-o`,此时不写文件。不能与 `--stdout` 同用,见[逐页返回结果](#逐页返回结果) || `--run-tag NAME` | 指定中间产物目录名;未指定时根据输入文件名和时间生成 |`--server-url` 和 `--model` 必须在每次 `parse` 命令中显式传入,即使使用了 `--config` 或设置了环境变量。@@ -104,6 +105,92 @@ if __name__ == "__main__":`ensure_layout_model()` 复用或下载官方版面模型;`load_config()` 合并配置并校验输入;`pipelined_run()` 执行版面检测和识别;`assemble_document_markdown()` 返回合并后的 Markdown、页数和跨页表格合并次数。+### 逐页返回结果++PDF 或多张图片不必等全部解析完:`stream_pages(cfg)` 是一个生成器,每解析完一页就产出这一页的结果,其余页继续在后台解析。`cfg` 与上面的例子相同:++```python+from minicpmvocr import stream_pages++for page in stream_pages(cfg):+ print(f"[{page['pages_done']}/{page['pages_total']}] {page['source']} 第 {page['page_index'] + 1} 页 {page['status']}")+ print(page["markdown"])+```++默认按完成的先后产出,不一定是页码顺序;`stream_pages(cfg, ordered=True)` 按输入顺序产出,先完成的页会等它前面的页。每个页事件的字段:++| 字段 | 说明 |+|---|---|+| `index` | 这一页在整次运行输入顺序中的位置,从 0 起 |+| `pages_done` / `pages_total` | 已产出的页数和总页数 |+| `source` / `source_id` | 这一页来自哪个输入文件,以及它在 `runtime/sources.json` 中的编号 |+| `page_index` | 这一页在所属文件中的页码,从 0 起;单图恒为 0 |+| `image_id` | 页标识,对应 `pages_json/<image_id>.json` |+| `status` / `error` | `ok`、`partial_failed`(部分块失败)或 `failed`;失败时 `error` 给出原因 |+| `markdown` | 这一页的 Markdown |+| `output_md` | 这一页的 Markdown 文件路径;Markdown 中的 `imgs/` 链接相对于该文件所在目录 |+| `page` | 与线上单页响应同构的完整结果(含 `ocr.blocks[]`);页失败时为 `None` |++单页失败只体现在该页事件的 `status` 上,其余页照常产出;导致整次运行中止的错误会在已完成的页产出之后抛出。提前结束迭代不会取消运行,剩余页仍在后台解析并写入运行目录。生成器的返回值是运行摘要。也可以不用生成器,直接把回调传给 `pipelined_run(cfg, on_page=...)` 或 `infer_run(cfg, on_page=...)`,回调收到的事件相同。++逐页结果在跨页表格合并之前产出;开启 `pipeline.merge_cross_page_tables` 时,以运行结束后的 `assemble_document_markdown()` 为准。++逐页返回时前面的页优先:PDF 在后台按页码顺序渲染,前几页渲染好就开始版面检测,不等整份 PDF 渲染完;识别请求也按页依次发出,前面的页先完成。某一页渲染失败时只有该页报告 `failed`。不逐页返回时仍按整次运行“最长的块优先”发出,总耗时最短,但各页会集中在接近结束时才完成。因此逐页返回的总耗时略长:在单张 A100 上实测 18 到 45 页的 PDF 慢约 5% 到 13%。启用 `OCR_SHARED_CROP_POOL=1` 的共享线程池时不改变发出顺序。++#### 块级和逐字++`detail` 决定事件的粒度,默认 `"page"` 只有上面的页事件(`"event": "page"`)。`detail="block"` 在每页的页事件之前多两种事件,`detail="token"` 再多一种:++| 事件 | 何时产出 | 字段 |+|---|---|---|+| `layout` | 一页完成版面检测、识别开始之前 | `image_width`、`image_height`、`blocks[]`(按阅读顺序,每项有 `order`、`label`、`bbox`) |+| `block` | 一个块识别完成 | `order`、`label`、`bbox`、`status`、`content` |+| `delta` | 一个块解码的过程中(仅 `detail="token"`) | `order`、`text`(这一小段新文本) |++这三种事件都带 `index` 和 `image_id`,`layout` 和 `block` 还带 `source`、`source_id`、`page_index`。用 `image_id` 加 `order` 定位到块:++```python+for event in stream_pages(cfg, ordered=True, detail="token"):+ if event["event"] == "delta":+ print(event["text"], end="", flush=True) # 逐字显示+ elif event["event"] == "block":+ replace_block(event["image_id"], event["order"], event["content"])+```++- `delta` 的文本是模型的原始输出;`block` 的 `content` 是整理后的结果(例如行内公式改写为 `$...$`、表格转成 HTML),应当用它替换这个块此前累计的 `delta` 文本。带 `"restart": true` 的 `delta` 表示这个块的请求被重发,之前累计的文本作废。+- `block` 的内容与最终页结果一致;只有表格里引用了本页图片的块,要等整页组装时才定稿,以页事件为准。+- 不需要识别的块(图片等)同样有 `block` 事件,`content` 为空,没有 `delta`。开启 `tts`(多候选重排)时结果要等候选比较完才确定,因此没有 `delta`,`block` 事件照常。+- 默认各页、各块并行识别,事件交错到达。`ordered=True` 时严格按阅读顺序:一页的 `layout`,然后逐块依次是它的 `delta` 和 `block`,最后是这一页的 `page`,再到下一页;轮到的块实时透传,还没轮到的先缓存。此时把 `delta` 的文本直接顺序拼接就是文档的阅读顺序。+- 逐字需要识别服务支持流式输出,`vllm`、`openai`、`llamacpp`、`ollama` 后端均按各自的流式接口请求。++命令行用 `--stream`,每解析完一页就向标准输出写一行 JSON(字段同上),最后一行是 `"event": "done"` 的运行摘要;加 `--stream-detail block` 或 `--stream-detail token` 输出块级或逐字的行:++```bash+minicpmvocr parse doc.pdf --stream \+ --device cuda:0 --server-url http://127.0.0.1:18499 --model minicpm-ocr+```++### 模型只加载一次++每次运行默认各自加载版面模型(以及开启摆正时的摆正模型),结束时卸载。同一个进程里要解析多批文件时,用 `load_models(cfg)` 先加载一次,再把返回值作为 `resources` 传给每次运行,后面的运行就不再等模型加载:++```python+from minicpmvocr import load_models, pipelined_run, stream_pages++def make_cfg(path):+ return load_config(str(config_path), overrides={**overrides, "input": {"file_path": path}})++with load_models(make_cfg("a.pdf")) as models:+ for path in ["a.pdf", "b.pdf", "c.pdf"]:+ for page in stream_pages(make_cfg(path), resources=models): # 逐页返回+ print(page["markdown"])+ pipelined_run(make_cfg("d.pdf"), resources=models) # 不逐页返回,同样复用+```++`load_models()` 读取 `layout`、`upright` 和 `pipeline.layout_workers`;复用它的各次运行应保持这些配置不变,否则以已加载的模型为准。一组已加载的模型同一时间只服务一次运行。离开 `with` 块或调用 `models.close()` 时卸载。++命令行每次调用都是一个新进程,模型无法留在内存里;一次调用里传入多个输入只加载一次。+多个输入时,`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` 中,按给定顺序处理。diff --git a/docs/minicpm_ocr_sdk_api_en.md b/docs/minicpm_ocr_sdk_api_en.mdindex 6fe8073..f2f56c9 100644--- a/docs/minicpm_ocr_sdk_api_en.md+++ b/docs/minicpm_ocr_sdk_api_en.md@@ -38,6 +38,7 @@ This writes `a.md`, `a.json`, `b.md`, `b.json`, `doc.md`, and `doc.json` under `| `--config FILE` | Custom YAML configuration file; uses the built-in quickstart configuration when omitted || `--set KEY=VALUE` | Override a configuration value using a dotted path; repeat as needed, for example `--set input.limit=1` || `--stdout` | Print Markdown to standard output even when `-o` is supplied |+| `--stream` / `--stream-ordered` | Write one JSON line to standard output as soon as each page is parsed, without waiting for the whole run, then a last line with the run summary. `--stream` writes pages in the order they finish, `--stream-ordered` in reading order. `--stream-detail LEVEL` sets how fine the lines are: `page` (default) one line per page, `block` also the layout and each block, `token` also the text of each block while it is decoded. Files requested with `-o` and `--json` are still written at the end; with several inputs `-o` may be omitted, which writes no files. Cannot be combined with `--stdout`; see [Page-by-Page Results](#page-by-page-results) || `--run-tag NAME` | Name of the intermediate output directory; generated from the input filename and time when omitted |Pass `--server-url` and `--model` explicitly on every `parse` invocation, even when using `--config` or environment variables.@@ -104,6 +105,92 @@ 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.+### Page-by-Page Results++A PDF or a batch of images does not have to finish before you see results: `stream_pages(cfg)` is a generator that yields each page as soon as it is parsed, while the remaining pages keep going in the background. `cfg` is the same as in the example above:++```python+from minicpmvocr import stream_pages++for page in stream_pages(cfg):+ print(f"[{page['pages_done']}/{page['pages_total']}] {page['source']} page {page['page_index'] + 1} {page['status']}")+ print(page["markdown"])+```++Pages are yielded in the order they finish, which is not necessarily page order; `stream_pages(cfg, ordered=True)` yields them in input order, so a page that finishes early waits for the ones before it. Each page event has these fields:++| Field | Description |+|---|---|+| `index` | Position of the page in the input order of the whole run, zero-based |+| `pages_done` / `pages_total` | Pages yielded so far and the total |+| `source` / `source_id` | The input file the page came from, and its id in `runtime/sources.json` |+| `page_index` | Page number inside its own file, zero-based; always 0 for a standalone image |+| `image_id` | Page id, matching `pages_json/<image_id>.json` |+| `status` / `error` | `ok`, `partial_failed` (some blocks failed), or `failed`; `error` gives the reason for a failure |+| `markdown` | Markdown of the page |+| `output_md` | Path of the page's Markdown file; `imgs/` links in the Markdown are relative to its directory |+| `page` | The full result in the shape of the online page response (including `ocr.blocks[]`); `None` when the page failed |++A page that fails only shows in the `status` of its own event, and the other pages still arrive; an error that stops the whole run is raised after the pages finished before it have been yielded. Ending the iteration early does not cancel the run: the remaining pages are still parsed in the background and written to the run directory. The generator's return value is the run summary. Instead of the generator you can pass a callback to `pipelined_run(cfg, on_page=...)` or `infer_run(cfg, on_page=...)`; it receives the same events.++Pages are yielded before cross-page table merging; with `pipeline.merge_cross_page_tables` enabled, `assemble_document_markdown()` after the run is the authoritative result.++When pages are streamed, earlier pages go first: the PDF renders in page order in the background and layout detection starts on the first pages as soon as they are rendered, without waiting for the whole PDF; recognition requests are also sent page by page, so earlier pages finish first. A page that fails to render is reported as `failed` on its own. Otherwise the run still sends its longest blocks first across all pages, which gives the shortest total time but makes most pages finish close to the end. Streaming therefore takes slightly longer in total: about 5% to 13% on 18- to 45-page PDFs measured on a single A100. With the shared worker pool (`OCR_SHARED_CROP_POOL=1`) the sending order is unchanged.++#### Blocks and Text as It Is Decoded++`detail` sets how fine the events are. The default `"page"` yields only the page events above (`"event": "page"`). `detail="block"` adds two kinds of event before each page event, and `detail="token"` one more:++| Event | When | Fields |+|---|---|---|+| `layout` | A page has been laid out, before recognition starts | `image_width`, `image_height`, `blocks[]` (in reading order, each with `order`, `label`, `bbox`) |+| `block` | One block has been recognized | `order`, `label`, `bbox`, `status`, `content` |+| `delta` | While a block is being decoded (`detail="token"` only) | `order`, `text` (the new piece of text) |++All three carry `index` and `image_id`; `layout` and `block` also carry `source`, `source_id`, and `page_index`. `image_id` plus `order` identifies a block:++```python+for event in stream_pages(cfg, ordered=True, detail="token"):+ if event["event"] == "delta":+ print(event["text"], end="", flush=True) # text as it is decoded+ elif event["event"] == "block":+ replace_block(event["image_id"], event["order"], event["content"])+```++- A `delta` carries the model's raw output; the `content` of a `block` is the tidied result (inline formulas rewritten as `$...$`, tables converted to HTML, and so on) and should replace the `delta` text collected for that block. A `delta` with `"restart": true` means the request for that block was sent again: drop the text collected so far.+- The content of a `block` matches the final page; only a table that references figures of its page is settled when the whole page is assembled, so the page event is authoritative.+- Blocks that are not recognized (images and the like) still get a `block` event, with empty `content` and no `delta`. With `tts` (candidate reranking) enabled the result is only known after the candidates are compared, so there are no `delta` events; `block` events come as usual.+- By default pages and blocks are recognized in parallel and their events interleave. With `ordered=True` everything is strictly in reading order: a page's `layout`, then block after block its `delta` events and its `block`, then the `page`, then the next page. The block whose turn it is passes through live; whatever is ahead of its turn is held. Concatenating the `delta` text then reads as the document does.+- Text as it is decoded needs a recognition service that streams; the `vllm`, `openai`, `llamacpp`, and `ollama` backends are each asked through their own streaming interface.++On the command line, `--stream` writes one JSON line to standard output as soon as each page is parsed (the fields above), and a last line with `"event": "done"` carrying the run summary; add `--stream-detail block` or `--stream-detail token` for the block-level or text-level lines:++```bash+minicpmvocr parse doc.pdf --stream \+ --device cuda:0 --server-url http://127.0.0.1:18499 --model minicpm-ocr+```++### Loading the Models Once++By default every run loads the layout model (and the upright models when rotation is enabled) for itself and unloads it at the end. To parse several batches in one process, load once with `load_models(cfg)` and pass the result to each run as `resources`; later runs no longer wait for the models:++```python+from minicpmvocr import load_models, pipelined_run, stream_pages++def make_cfg(path):+ return load_config(str(config_path), overrides={**overrides, "input": {"file_path": path}})++with load_models(make_cfg("a.pdf")) as models:+ for path in ["a.pdf", "b.pdf", "c.pdf"]:+ for page in stream_pages(make_cfg(path), resources=models): # page by page+ print(page["markdown"])+ pipelined_run(make_cfg("d.pdf"), resources=models) # not streamed, reused all the same+```++`load_models()` reads `layout`, `upright`, and `pipeline.layout_workers`; the runs that reuse it should keep those settings, because the loaded models win. One loaded set serves one run at a time. Leaving the `with` block or calling `models.close()` unloads them.++Each command-line invocation is a new process, so the models cannot stay in memory between invocations; several inputs in one invocation load them once.+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.diff --git a/sdk/minicpmvocr/__init__.py b/sdk/minicpmvocr/__init__.pyindex 20f1822..6d03ecc 100644--- a/sdk/minicpmvocr/__init__.py+++ b/sdk/minicpmvocr/__init__.py@@ -15,7 +15,9 @@ _EXPORTS = {"assemble_document_json": "minicpmvocr.pipeline","prepare_run": "minicpmvocr.pipeline","infer_run": "minicpmvocr.pipeline",+ "load_models": "minicpmvocr.pipeline","pipelined_run": "minicpmvocr.pipeline",+ "stream_pages": "minicpmvocr.pipeline","DEFAULT_PROMPT_MAP": "minicpmvocr.prompts","load_prompt_map": "minicpmvocr.prompts",@@ -63,9 +65,11 @@ if TYPE_CHECKING:from .pipeline import (assemble_document_json,infer_run,+ load_models,parse_layout_run,pipelined_run,prepare_run,+ stream_pages,)from .prompts import DEFAULT_PROMPT_MAP, get_element_cfg, load_prompt_mapfrom .pipeline.upright import UprightCorrectordiff --git a/sdk/minicpmvocr/backends/client.py b/sdk/minicpmvocr/backends/client.pyindex 6beab02..f1d13a5 100644--- a/sdk/minicpmvocr/backends/client.py+++ b/sdk/minicpmvocr/backends/client.py@@ -9,7 +9,7 @@ from typing import Dict, Optionalimport requests-from .dialects import CropRequest, Dialect, DialectError+from .dialects import CropRequest, Dialect, DialectError, collect_stream, stream_payloadclass EngineError(RuntimeError):@@ -140,8 +140,22 @@ class VLMClient:return any(marker in lowered for marker in self.dialect.context_overflow_markers)def recognize(self, image, prompt: str, max_new_tokens: int, slice_nums: Optional[int] = None,- n: int = 1, decode_overrides: Optional[Dict] = None) -> Dict:-+ n: int = 1, decode_overrides: Optional[Dict] = None, on_delta=None) -> Dict:+ """Recognize one crop.++ ``on_delta(text, restart)`` receives the text piece by piece while the+ backend decodes it. ``restart`` is true on the first piece of a request+ that had to be sent again after pieces were already handed over: what+ came before it is to be dropped. The result is the same either way.+ """+ stream_format = self.dialect.stream_format if on_delta is not None and n == 1 else None+ handed_over = False+ restart = False++ def _on_text(text: str) -> None:+ nonlocal handed_over, restart+ on_delta(text, restart)+ handed_over, restart = True, Falseencode_t0 = time.time()image_b64 = encode_image_b64(image)@@ -174,6 +188,9 @@ class VLMClient:)build_t0 = time.time()payload = self.dialect.build_payload(req, self.engine_cfg, self.mm_cfg, self.decode_cfg)+ if stream_format:+ payload = stream_payload(payload, stream_format)+ restart = handed_overbuild_sec = time.time() - build_t0try:started = time.time()@@ -182,6 +199,7 @@ class VLMClient:json=payload,headers=headers,timeout=request_timeout_sec,+ stream=bool(stream_format),)latency = time.time() - started@@ -196,8 +214,17 @@ class VLMClient:breakresp.raise_for_status()+ if stream_format:+ try:+ body = collect_stream(stream_format, resp.iter_lines(), _on_text)+ finally:+ resp.close()+ # The reply was still arriving when post() returned.+ latency = time.time() - started+ else:+ body = resp.json()parse_t0 = time.time()- result = self.dialect.parse_response(resp.json())+ result = self.dialect.parse_response(body)parse_sec = time.time() - parse_t0metrics = result.setdefault("request_metrics", {})metrics["latency_sec"] = latencydiff --git a/sdk/minicpmvocr/backends/dialects.py b/sdk/minicpmvocr/backends/dialects.pyindex 7a02745..00289ce 100644--- a/sdk/minicpmvocr/backends/dialects.py+++ b/sdk/minicpmvocr/backends/dialects.py@@ -1,7 +1,8 @@from __future__ import annotations+import jsonfrom dataclasses import dataclass-from typing import Callable, Dict, List, Optional+from typing import Callable, Dict, Iterable, List, Optionalclass DialectError(RuntimeError):@@ -34,6 +35,9 @@ class Dialect:check_health: Callable[[Dict, object], Optional[str]] = lambda cfg, body: Nonecontext_overflow_codes: tuple = (400,)context_overflow_markers: tuple = ("maximum context length",)+ #: How the backend sends text while it is still decoding: "sse" (OpenAI+ #: chunks), "ndjson" (Ollama's native API), or None when it cannot.+ stream_format: Optional[str] = Nonedef _data_uri(image_b64: str) -> str:@@ -98,6 +102,67 @@ def parse_openai_response(data: Dict) -> Dict:)+def stream_payload(payload: Dict, stream_format: str) -> Dict:+ 'The same request, asking for the text as it is decoded.'+ payload = dict(payload, stream=True)+ if stream_format == "sse":+ # Without this the chunks carry no token counts.+ payload.setdefault("stream_options", {"include_usage": True})+ return payload+++def collect_stream(stream_format: str, lines: Iterable[bytes], on_text: Callable[[str], None]) -> Dict:+ """Read a streamed reply, passing each piece of text to ``on_text``.++ Returns the body the backend would have sent without streaming, so the+ dialect's ``parse_response`` reads both the same way.+ """+ pieces: List[str] = []+ if stream_format == "ndjson":+ final: Dict = {}+ for line in lines:+ if not line.strip():+ continue+ chunk = json.loads(line)+ if chunk.get("error"):+ raise DialectError(str(chunk["error"]))+ text = (chunk.get("message") or {}).get("content") or ""+ if text:+ pieces.append(text)+ on_text(text)+ if chunk.get("done"):+ final = chunk+ final = dict(final)+ final["message"] = dict(final.get("message") or {}, content="".join(pieces))+ return final++ finish_reason = None+ usage: Dict = {}+ for line in lines:+ if not line.startswith(b"data:"):+ continue+ data = line[len(b"data:"):].strip()+ if data == b"[DONE]":+ break+ chunk = json.loads(data)+ if chunk.get("error"):+ raise DialectError(str(chunk["error"]))+ if chunk.get("usage"):+ usage = chunk["usage"]+ for choice in chunk.get("choices") or []:+ if choice.get("index", 0) != 0:+ continue+ text = (choice.get("delta") or {}).get("content") or ""+ if text:+ pieces.append(text)+ on_text(text)+ finish_reason = choice.get("finish_reason") or finish_reason+ return {+ "choices": [{"message": {"content": "".join(pieces)}, "finish_reason": finish_reason}],+ "usage": usage,+ }++def check_models_endpoint(engine_cfg: Dict, body) -> Optional[str]:ids = [item.get("id") for item in (body or {}).get("data", []) if item.get("id")]return None if ids else "model list is empty"@@ -249,6 +314,7 @@ DIALECTS: Dict[str, Dialect] = {build_payload=build_openai_payload,parse_response=parse_openai_response,check_health=check_models_endpoint,+ stream_format="sse",),"vllm": Dialect(name="vllm",@@ -258,6 +324,7 @@ DIALECTS: Dict[str, Dialect] = {build_payload=build_vllm_payload,parse_response=parse_openai_response,check_health=check_models_endpoint,+ stream_format="sse",),"llamacpp": Dialect(name="llamacpp",@@ -274,6 +341,7 @@ DIALECTS: Dict[str, Dialect] = {"exceeds the available context size","context size",),+ stream_format="sse",),"ollama": Dialect(name="ollama",@@ -283,6 +351,7 @@ DIALECTS: Dict[str, Dialect] = {build_payload=build_ollama_payload,parse_response=parse_ollama_response,check_health=check_ollama_health,+ stream_format="ndjson",),"ollama_openai": Dialect(@@ -293,5 +362,6 @@ DIALECTS: Dict[str, Dialect] = {build_payload=build_llamacpp_payload,parse_response=parse_openai_response,check_health=check_ollama_health,+ stream_format="sse",),}diff --git a/sdk/minicpmvocr/cli.py b/sdk/minicpmvocr/cli.pyindex e51fc00..4ff46bd 100644--- a/sdk/minicpmvocr/cli.py+++ b/sdk/minicpmvocr/cli.py@@ -18,8 +18,9 @@ from .config import _deep_merge, load_configfrom .constants import PARAMS_FILENAME, SUPPORTED_INPUT_SUFFIXESfrom .layouts import LAYOUT_ALIASES, list_layout_providers, normalize_layout_providerfrom .layouts.download import ensure_layout_model, ensure_upright_models-from .pipeline import infer_run, parse_layout_run, pipelined_run, prepare_run+from .pipeline import infer_run, parse_layout_run, prepare_runfrom .pipeline._sources import read_sources+from .pipeline._stream import InputOrder, run_pagesfrom ._utils import read_jsonl@@ -101,6 +102,19 @@ def _build_parser() -> argparse.ArgumentParser:"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")+ p_parse.add_argument(+ "--stream", action="store_const", const="completed", default="", dest="stream",+ help="Write each page to standard output as one JSON line as soon as it is parsed, in "+ "the order pages finish, then one closing line with the run summary. Files asked "+ "for with -o / --json are still written at the end")+ p_parse.add_argument(+ "--stream-ordered", action="store_const", const="ordered", default="", dest="stream",+ help="Like --stream, but in reading order: whatever is ahead of its turn waits")+ p_parse.add_argument(+ "--stream-detail", choices=["page", "block", "token"], default="page", metavar="LEVEL",+ help="How fine the --stream lines are. page (default): one line per finished page. "+ "block: also one line when a page is laid out and one per recognized block. "+ "token: also the text of each block while it is being decoded")_add_engine_args(p_parse, require_connection=True)sub.add_parser("list-backends", help="List pluggable inference backends and layout providers")@@ -440,15 +454,20 @@ def _output_names(sources: list) -> dict: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."""+ """Write one Markdown (and with --json one JSON) per input file.++ With --stream the pages have already been written to standard output, so+ -o is optional and leaving it out writes no files.+ """if args.stdout:raise ValueError("--stdout writes a single document; use -o DIR for several inputs")- if not args.output:+ if not args.output and not args.stream: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)+ output_dir = Path(args.output).resolve() if args.output else None+ if output_dir is not None:+ 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_jsonfrom .postprocess.crosspage import assemble_documents_markdown@@ -467,6 +486,15 @@ def _parse_many(args: argparse.Namespace, cfg: dict, run_dir: Path,for entry in document["files"]:source_id = entry["source_id"]name = names.get(source_id, source_id or "input")+ record = {+ "source_id": source_id,+ "input": entry["path"],+ "status": entry["status"],+ "pages": f"{entry['pages_done']}/{entry['pages_total']}",+ }+ if output_dir is None:+ outputs.append(record)+ continueif args.no_merge_pages and entry["pages_total"] > 1:raise ValueError(f"{entry['path']}: {entry['pages_total']} pages; remove --no-merge-pages "@@ -475,13 +503,7 @@ def _parse_many(args: argparse.Namespace, cfg: dict, run_dir: Path,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),- }+ record["output_md"] = str(markdown_path)if args.json is not None:json_path = output_dir / f"{name}.json"json_path.write_text(@@ -489,25 +511,41 @@ def _parse_many(args: argparse.Namespace, cfg: dict, run_dir: Path,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,- )- )+ _print_parse_summary(args, {+ "command": "parse",+ "status": document["status"],+ "inputs": len(args.inputs),+ "outputs": outputs,+ "run_dir": str(run_dir),+ "layout_summary": layout_summary,+ "infer_summary": infer_summary,+ })failed = [o for o in outputs if o["status"] == "Failed"]return 1 if len(failed) == len(outputs) else 0+def _page_stream(args: argparse.Namespace):+ 'The on_page callback for --stream, or None; it has a flush() when it holds pages back.'+ if not args.stream:+ return None+ # Captured now: the run itself has standard output pointed at standard error.+ out = sys.stdout++ def _write(event: dict) -> None:+ out.write(json.dumps(event, ensure_ascii=False) + "\n")+ out.flush()++ return InputOrder(_write) if args.stream == "ordered" else _write+++def _print_parse_summary(args: argparse.Namespace, summary: dict) -> None:+ 'The closing report: pretty JSON, or with --stream one more line of the stream.'+ if args.stream:+ print(json.dumps({"event": "done", **summary}, ensure_ascii=False), flush=True)+ else:+ print(json.dumps(summary, ensure_ascii=False, indent=2))++def main() -> int:@@ -536,19 +574,20 @@ def main() -> int:return 0if args.command == "parse":+ if args.stream and args.stdout:+ parser.error("--stream already writes to standard output; drop --stdout")+ if args.stream_detail != "page" and not args.stream:+ parser.error("--stream-detail needs --stream or --stream-ordered")try:cfg = _load_parse_config(args)except (ValueError, OSError) as exc:parser.error(str(exc))+ on_page = _page_stream(args)with redirect_stdout(sys.stderr):- if bool(cfg["pipeline"].get("overlap_layout", False)):- infer_summary = pipelined_run(cfg)- layout_summary = {"overlapped": True, **infer_summary.get("pipelined", {})}- else:- layout_summary = parse_layout_run(cfg)- prepare_run(cfg)- infer_summary = infer_run(cfg)+ layout_summary, infer_summary = run_pages(cfg, on_page, detail=args.stream_detail)+ if isinstance(on_page, InputOrder):+ on_page.flush()run_dir = Path(cfg["_meta"]["run_dir"])if len(args.inputs) > 1:@@ -557,6 +596,18 @@ def main() -> int:except (ValueError, OSError) as exc:parser.error(str(exc))+ if args.stream and not args.output and args.json is None:+ # Every page is already on standard output; there is no file to assemble.+ _print_parse_summary(args, {+ "command": "parse",+ "input": str(args.inputs[0]),+ "pages": int((infer_summary.get("counts") or {}).get("planned", 0)),+ "run_dir": str(run_dir),+ "layout_summary": layout_summary,+ "infer_summary": infer_summary,+ })+ return 0+markdown, pages = _read_markdown_from_run(run_dir=run_dir,merge_pages=not args.no_merge_pages,@@ -582,31 +633,27 @@ def main() -> int:encoding="utf-8",)- if args.stdout or not args.output:+ if not args.stream and (args.stdout or not args.output):print(_absolute_image_links(markdown, run_dir))return 0- output_path = Path(args.output).resolve()- output_path.parent.mkdir(parents=True, exist_ok=True)- _sync_markdown_images(run_dir, markdown, output_path)- output_path.write_text(markdown, encoding="utf-8")-- print(- json.dumps(- {- "command": "parse",- "input": str(args.inputs[0]),- "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,- "infer_summary": infer_summary,- },- ensure_ascii=False,- indent=2,- )- )+ output_path = None+ if args.output:+ output_path = Path(args.output).resolve()+ output_path.parent.mkdir(parents=True, exist_ok=True)+ _sync_markdown_images(run_dir, markdown, output_path)+ output_path.write_text(markdown, encoding="utf-8")++ _print_parse_summary(args, {+ "command": "parse",+ "input": str(args.inputs[0]),+ **({"output_md": str(output_path)} if output_path else {}),+ **({"output_json": str(json_path)} if json_path else {}),+ "pages": pages,+ "run_dir": str(run_dir),+ "layout_summary": layout_summary,+ "infer_summary": infer_summary,+ })return 0cfg = load_config(args.config, overrides=_build_engine_overrides(args))@@ -631,13 +678,7 @@ def main() -> int:return 0if args.command == "run":- if bool(cfg["pipeline"].get("overlap_layout", False)):- infer_summary = pipelined_run(cfg)- layout_summary = {"overlapped": True, **infer_summary.get("pipelined", {})}- else:- layout_summary = parse_layout_run(cfg)- prepare_run(cfg)- infer_summary = infer_run(cfg)+ layout_summary, infer_summary = run_pages(cfg)print(json.dumps({diff --git a/sdk/minicpmvocr/constants.py b/sdk/minicpmvocr/constants.pyindex c5a014f..95f4859 100644--- a/sdk/minicpmvocr/constants.py+++ b/sdk/minicpmvocr/constants.py@@ -53,3 +53,9 @@ PDF_RENDER_ZOOM = 2.0PDF_RENDER_PAGES_PER_JOB = 16++# Front-first rendering hands pages over while later ones still render, so its+# jobs are small. It also keeps to few processes: each one takes about a second+# to start, and two already render far faster than pages are recognized.+PDF_RENDER_PAGES_PER_EARLY_JOB = 2+PDF_RENDER_EARLY_WORKERS = 2diff --git a/sdk/minicpmvocr/pipeline/__init__.py b/sdk/minicpmvocr/pipeline/__init__.pyindex 52fc1d0..0f40b33 100644--- a/sdk/minicpmvocr/pipeline/__init__.py+++ b/sdk/minicpmvocr/pipeline/__init__.py@@ -3,9 +3,11 @@ from __future__ import annotations__all__ = ["assemble_document_json","infer_run",+ "load_models","parse_layout_run","pipelined_run","prepare_run",+ "stream_pages",]@@ -13,6 +15,12 @@ def __getattr__(name: str):if name == "assemble_document_json":from ._response import assemble_document_jsonreturn assemble_document_json+ if name == "load_models":+ from ._models import load_models+ return load_models+ if name == "stream_pages":+ from ._stream import stream_pages+ return stream_pagesif name == "pipelined_run":from .overlapped import pipelined_runreturn pipelined_rundiff --git a/sdk/minicpmvocr/pipeline/_blocks.py b/sdk/minicpmvocr/pipeline/_blocks.pyindex 693ba0c..49f0539 100644--- a/sdk/minicpmvocr/pipeline/_blocks.py+++ b/sdk/minicpmvocr/pipeline/_blocks.py@@ -43,7 +43,13 @@ def _block_priority(prompt_map: Dict, block: Dict) -> tuple:def _execute_block(engine, prompt_map: Dict, image_id: str, crop_dir: Path, block: Dict,crop_array=None, rm_client=None, tts_cfg: Optional[Dict] = None,submitted_at: Optional[float] = None,- prior_candidate: Optional[Dict] = None) -> Dict:+ prior_candidate: Optional[Dict] = None, on_delta=None) -> Dict:+ """Recognize one block.++ ``on_delta(text, restart)`` hears the raw text while it is decoded. Only a+ plain single request can be heard: with test-time sampling the answer is+ chosen among candidates afterwards, so nothing is passed on meanwhile.+ """label = block.get("label", "")elem_cfg = get_element_cfg(prompt_map, label)@@ -157,6 +163,8 @@ def _execute_block(engine, prompt_map: Dict, image_id: str, crop_dir: Path, blocprompt=elem_cfg["prompt"],max_new_tokens=elem_cfg["max_new_tokens"],slice_nums=elem_cfg["slice_nums"],+ # Engines that cannot stream are never asked to.+ **({"on_delta": on_delta} if on_delta is not None else {}),)infer_sec = time.time() - infer_t0raw_text = pred["text"]diff --git a/sdk/minicpmvocr/pipeline/_inputs.py b/sdk/minicpmvocr/pipeline/_inputs.pyindex 3c25040..3dae61e 100644--- a/sdk/minicpmvocr/pipeline/_inputs.py+++ b/sdk/minicpmvocr/pipeline/_inputs.py@@ -8,6 +8,8 @@ from PIL import Imagefrom ._sources import image_document_scope, write_sourcesfrom ..constants import (+ PDF_RENDER_EARLY_WORKERS,+ PDF_RENDER_PAGES_PER_EARLY_JOB,PDF_RENDER_PAGES_PER_JOB,PDF_RENDER_ZOOM,SUPPORTED_IMAGE_SUFFIXES,@@ -120,10 +122,18 @@ def _render_pdf_chunk(args):return out-def _render_pdf_pages(pdf_paths: List[Path], workers: int) -> Dict[tuple, tuple]:+def _render_pdf_pages(pdf_paths: List[Path], workers: int, front_first: bool = False) -> Dict[tuple, tuple]:+ """Render every page of ``pdf_paths``: {(path, page): (width, height, samples)}.+ ``front_first`` returns at once with {(path, page): (future, position in its+ result)} instead: the jobs run in page order in the background, so the first+ pages can be used while the later ones are still rendering. The very first+ job is left out, for the caller to render on the spot: those pages are then+ ready before any background process has started.+ """import fitz+ pages_per_job = PDF_RENDER_PAGES_PER_EARLY_JOB if front_first else PDF_RENDER_PAGES_PER_JOBjobs = []for path in pdf_paths:doc = fitz.open(str(path))@@ -131,8 +141,8 @@ def _render_pdf_pages(pdf_paths: List[Path], workers: int) -> Dict[tuple, tuple]page_count = doc.page_countfinally:doc.close()- for first in range(0, page_count, PDF_RENDER_PAGES_PER_JOB):- jobs.append((str(path), first, min(first + PDF_RENDER_PAGES_PER_JOB, page_count)))+ for first in range(0, page_count, pages_per_job):+ jobs.append((str(path), first, min(first + pages_per_job, page_count)))if not jobs:return {}@@ -143,6 +153,25 @@ def _render_pdf_pages(pdf_paths: List[Path], workers: int) -> Dict[tuple, tuple]import os+ if front_first:+ jobs = jobs[1:]+ if not jobs:+ return {}+ if workers <= 0:+ workers = PDF_RENDER_EARLY_WORKERS+ pool = cf.ProcessPoolExecutor(+ max_workers=max(1, min(workers, len(jobs))),+ mp_context=multiprocessing.get_context("spawn"),+ )+ futures = [pool.submit(_render_pdf_chunk, job) for job in jobs]+ # Not waited for: the jobs already submitted still run, in the order submitted.+ pool.shutdown(wait=False)+ return {+ (source, index): (future, index - first)+ for (source, first, last), future in zip(jobs, futures)+ for index in range(first, last)+ }+if workers <= 0:workers = min(16, os.cpu_count() or 1)workers = max(1, min(workers, len(jobs)))@@ -164,7 +193,14 @@ def _render_pdf_pages(pdf_paths: List[Path], workers: int) -> Dict[tuple, tuple]return rendered-def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:+def _iter_source_pages(cfg: Dict, runtime_intermediate: Path, front_first: bool = False) -> List[Dict]:+ """Every page of the run, in input order.++ A rendered PDF page carries ``image_bytes``. With ``front_first`` this+ returns before PDF rendering is over and such a page carries+ ``image_future`` instead; ``_open_page_image`` waits for it, and a rendering+ error is raised there, for that page, rather than here.+ """try:import fitzexcept Exception:@@ -184,7 +220,7 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:if pdf_files and render_workers_cfg != 1:_t0 = time.time()- rendered = _render_pdf_pages(pdf_files, render_workers_cfg)+ rendered = _render_pdf_pages(pdf_files, render_workers_cfg, front_first)_render_sec = time.time() - _t0_render_workers = render_workers_cfgelse:@@ -217,6 +253,19 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:for idx in range(page_count):image_id = f"{path.stem}_page_{idx + 1:03d}"hit = rendered.get((str(path), idx))+ if hit is not None and len(hit) == 2:+ page_entries.append(+ {+ "image_id": image_id,+ "source_type": "pdf",+ "source_path": str(path),+ "page_index": idx,+ "image_path": "",+ "image_future": hit,+ }+ )+ page_sources.append(index)+ continueif hit is not None:width, height, samples = hitpage_entries.append(@@ -259,6 +308,13 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:meta = cfg.setdefault("_meta", {})meta["render_sec"] = round(_render_sec, 6)meta["render_workers"] = _render_workers+ if pdf_files and render_workers_cfg != 1:+ # Rendering still under way: the last job to finish leaves the time the whole took.+ def _note_render_sec(_future, started=_t0):+ meta["render_sec"] = round(time.time() - started, 6)++ for future in {hit[0] for hit in rendered.values() if len(hit) == 2}:+ future.add_done_callback(_note_render_sec)limit = _mode_limit(cfg)if limit > 0:@@ -295,6 +351,11 @@ def _iter_source_pages(cfg: Dict, runtime_intermediate: Path) -> List[Dict]:def _open_page_image(entry: Dict) -> Image.Image:+ pending = entry.get("image_future")+ if pending is not None:+ future, position = pending+ _index, width, height, samples = future.result()[position]+ return Image.frombytes("RGB", [width, height], samples)buf = entry.get("image_bytes")if buf:width, height = entry["image_size"]diff --git a/sdk/minicpmvocr/pipeline/_models.py b/sdk/minicpmvocr/pipeline/_models.pynew file mode 100644index 0000000..2453cce--- /dev/null+++ b/sdk/minicpmvocr/pipeline/_models.py@@ -0,0 +1,48 @@+'Models loaded once and used by several runs.'+from __future__ import annotations++from typing import Dict++from .upright import build_upright_corrector+from ..layouts import create_layout_detector+++class LoadedModels(dict):+ """The ``resources`` of a run, loaded ahead of it: pass it to as many runs as you like.++ Holds the layout detectors and the upright corrector. A run that is given+ them neither loads nor unloads its own, so only the first run pays for+ loading. One set serves one run at a time. ``close()`` unloads; so does+ leaving a ``with`` block.+ """++ def close(self) -> None:+ for detector in self.pop("detectors", []):+ detector.stop()+ self.pop("upright", None)++ def __enter__(self) -> "LoadedModels":+ return self++ def __exit__(self, *exc_info) -> None:+ self.close()+++def load_models(cfg: Dict) -> LoadedModels:+ """Load what ``cfg`` needs for layout detection, once, for several runs.++ Reads ``layout``, ``upright`` and ``pipeline.layout_workers``; the runs that+ reuse the result must keep those settings, since the loaded models win.+ """+ workers = max(1, int((cfg.get("pipeline") or {}).get("layout_workers", 1) or 1))+ models = LoadedModels(detectors=[])+ try:+ for _ in range(workers):+ detector = create_layout_detector(cfg["layout"])+ detector.start()+ models["detectors"].append(detector)+ models["upright"] = build_upright_corrector(cfg)+ except BaseException:+ models.close()+ raise+ return modelsdiff --git a/sdk/minicpmvocr/pipeline/_stream.py b/sdk/minicpmvocr/pipeline/_stream.pynew file mode 100644index 0000000..e9ee8a1--- /dev/null+++ b/sdk/minicpmvocr/pipeline/_stream.py@@ -0,0 +1,310 @@+'Per-page results while a run is still going.'+from __future__ import annotations++import logging+import threading+from pathlib import Path+from queue import Queue+from typing import Callable, Dict, Iterator, List, Optional++from ._response import RESPONSE_DIRNAME+from ._sources import page_lookup, read_sources+from ._text import _normalize_and_dedupe_blocks+from .._utils import read_json+++LOGGER = logging.getLogger(__name__)++PageCallback = Callable[[Dict], None]+++#: How fine the events are: whole pages, also their layout and blocks, also the+#: text of each block while it is decoded.+DETAILS = ("page", "block", "token")+++class PageReporter:+ """Turn what a run finishes into events and hand them to ``on_page``.++ ``detail`` says how fine. "page": one ``page`` event per finished page.+ "block": before it, a ``layout`` event when the page is laid out and a+ ``block`` event for each of its blocks as it is recognized. "token": also+ ``delta`` events carrying a block's text while it is being decoded.++ Pages are reported from the thread that drives the run, in the order they+ finish, which is not the input order; blocks and text come from the threads+ that recognize them. The callback is still never in two calls at once.+ """++ def __init__(self, run_dir: Path, planned_ids: List[str], on_page: PageCallback,+ detail: str = "page") -> None:+ if detail not in DETAILS:+ raise ValueError("stream detail must be one of %s, got %r" % (", ".join(DETAILS), detail))+ self.blocks = detail != "page"+ self.tokens = detail == "token"+ self._run_dir = Path(run_dir)+ self._on_page = on_page+ self._lock = threading.Lock()+ self._lookup = page_lookup(read_sources(self._run_dir))+ # Input order is the manifest's; pages it does not list keep theirs, after it.+ rank = {image_id: position for position, image_id in enumerate(self._lookup)}+ in_order = sorted(planned_ids, key=lambda image_id: rank.get(image_id, len(rank)))+ self._index = {image_id: position for position, image_id in enumerate(in_order)}+ self._done = 0++ def _emit(self, event: Dict) -> None:+ with self._lock:+ try:+ self._on_page(event)+ except Exception:+ # What was parsed is on disk either way; a broken consumer must not cost the run.+ LOGGER.exception("on_page callback failed for the %s event of %s",+ event["event"], event["image_id"])++ def _where(self, image_id: str) -> Dict:+ origin = self._lookup.get(image_id, {})+ return {+ # Position in input order across the whole run, from 0.+ "index": self._index.setdefault(image_id, len(self._index)),+ "image_id": image_id,+ "source_id": origin.get("source_id", ""),+ "source": origin.get("path", ""),+ # Position inside its own input file, from 0.+ "page_index": origin.get("order", 0),+ }++ def layout(self, image_id: str, layout: Dict) -> None:+ 'The page is laid out: which blocks it has, before any of them is recognized.'+ if not self.blocks:+ return+ self._emit({+ "event": "layout",+ **self._where(image_id),+ "image_width": layout.get("image_width"),+ "image_height": layout.get("image_height"),+ "blocks": [+ {"order": block.get("order", 0), "label": block.get("label", ""), "bbox": block.get("bbox")}+ for block in layout.get("blocks") or []+ ],+ })++ def block(self, image_id: str, result_block: Dict) -> None:+ """One block is recognized.++ Its content is tidied the way the page will tidy it. What only the whole+ page can settle (figures referenced from a table) may still change it.+ """+ if not self.blocks:+ return+ tidied = _normalize_and_dedupe_blocks([result_block])[0]+ self._emit({+ "event": "block",+ **self._where(image_id),+ "order": tidied.get("order", 0),+ "label": tidied.get("label", ""),+ "bbox": tidied.get("bbox"),+ "status": tidied.get("status", ""),+ "content": tidied.get("content", ""),+ })++ def delta_listener(self, image_id: str, block: Dict):+ 'What to hand a recognition request so that its text is passed on; None when nobody asked.'+ if not self.tokens:+ return None+ index = self._where(image_id)["index"]+ order = block.get("order", 0)++ def _on_delta(text: str, restart: bool = False) -> None:+ event = {"event": "delta", "index": index, "image_id": image_id, "order": order, "text": text}+ if restart:+ # The request was sent again: drop the text this block had so far.+ event["restart"] = True+ self._emit(event)++ return _on_delta++ def report(self, result: Dict) -> None:+ 'One page is finished.'+ row = result["page_row"]+ image_id = row["image_id"]+ self._done += 1+ page = None+ markdown = ""+ md_path = self._run_dir / "output" / f"{image_id}.md"+ if row["status"] != "failed":+ page = read_json(self._run_dir / RESPONSE_DIRNAME / f"{image_id}.json", default=None)+ if page is not None:+ markdown = page["choices"][0]["message"]["content"]+ elif md_path.is_file():+ # A page resumed from a run written before pages_json existed.+ markdown = md_path.read_text(encoding="utf-8")+ event = {+ "event": "page",+ **self._where(image_id),+ "pages_done": self._done,+ "pages_total": len(self._index),+ "status": row["status"],+ "error": row.get("error", ""),+ "markdown": markdown,+ # imgs/ links in the Markdown are relative to this file's directory.+ "output_md": str(md_path) if md_path.is_file() else "",+ "page": page,+ }+ if page is not None:+ event["page_index"] = page["metadata"]["page_index"]+ self._emit(event)+++class _HeldPage:+ 'What has arrived about one page that is not yet due.'++ def __init__(self) -> None:+ self.layout: Optional[Dict] = None+ self.orders: List = [] # block orders, in reading order+ self.cursor = 0 # the block being delivered+ self.blocks: Dict = {} # order -> its delta and block events, oldest first+ self.page: Optional[Dict] = None+++class InputOrder:+ """Wrap ``on_page`` so everything arrives in reading order.++ Pages come in input order: a page that finishes early waits for the ones+ before it, and ``pages_done`` then counts the pages delivered so far. With+ finer events the same holds inside a page: its ``layout`` first, then block+ after block in reading order, each block's ``delta`` events followed by its+ ``block`` event, then the ``page``. The block whose turn it is passes+ through as it happens; whatever is ahead of its turn waits.+ """++ def __init__(self, on_page: PageCallback) -> None:+ self._on_page = on_page+ self._held: Dict[int, _HeldPage] = {}+ self._next = 0+ self._delivered = 0++ def __call__(self, event: Dict) -> None:+ held = self._held.setdefault(event["index"], _HeldPage())+ kind = event["event"]+ if kind == "page":+ held.page = event+ elif kind == "layout":+ held.layout = event+ held.orders = [block["order"] for block in event["blocks"]]+ else:+ held.blocks.setdefault(event["order"], []).append(event)+ self._drain()++ def _drain(self) -> None:+ while self._next in self._held:+ held = self._held[self._next]+ if held.layout is not None:+ layout, held.layout = held.layout, None+ self._on_page(layout)+ while held.cursor < len(held.orders):+ waiting = held.blocks.get(held.orders[held.cursor], [])+ finished = False+ while waiting and not finished:+ event = waiting.pop(0)+ finished = event["event"] == "block"+ self._on_page(event)+ if not finished:+ break+ held.cursor += 1+ if held.page is None:+ return+ # Move on first: a consumer that raises must not block the pages after it.+ del self._held[self._next]+ self._next += 1+ self._deliver_rest(held)++ def _deliver_rest(self, held: _HeldPage) -> None:+ if held.layout is not None:+ self._on_page(held.layout)+ # Blocks that never reported being finished still hand over what they had.+ known = [order for order in held.orders[held.cursor:] if order in held.blocks]+ for order in known + [order for order in held.blocks if order not in known]:+ for event in held.blocks[order]:+ self._on_page(event)+ if held.page is not None:+ self._delivered += 1+ held.page["pages_done"] = self._delivered+ self._on_page(held.page)++ def flush(self) -> None:+ 'Deliver what is still waiting, for a run that ended with pages missing.'+ for index in sorted(self._held):+ self._deliver_rest(self._held.pop(index))+++def run_pages(cfg: Dict, on_page: Optional[PageCallback] = None,+ resources: Optional[Dict] = None, detail: str = "page") -> tuple:+ 'Run layout and recognition the way the config asks; returns (layout_summary, infer_summary).'+ if bool(cfg["pipeline"].get("overlap_layout", False)):+ from .overlapped import pipelined_run++ infer_summary = pipelined_run(cfg, resources, on_page=on_page, stream_detail=detail)+ return {"overlapped": True, **infer_summary.get("pipelined", {})}, infer_summary++ from .staged import infer_run, parse_layout_run, prepare_run++ layout_summary = parse_layout_run(cfg, resources)+ prepare_run(cfg)+ return layout_summary, infer_run(cfg, on_page=on_page, stream_detail=detail)+++def stream_pages(cfg: Dict, *, ordered: bool = False, resources: Optional[Dict] = None,+ detail: str = "page") -> Iterator[Dict]:+ """Run the pipeline and yield one event per page as soon as that page is done.++ ``detail="block"`` also yields a ``layout`` event when a page is laid out and+ a ``block`` event for each block as it is recognized; ``detail="token"``+ also yields ``delta`` events with a block's text while it is being decoded.++ Events come as things finish; ``ordered=True`` puts them in reading order,+ holding back whatever is ahead of its turn. The run itself happens on a+ background thread, and the generator's return value is its summary. A page+ that failed is yielded with ``status == "failed"``; an error that stops the+ whole run is raised once the pages finished before it have been yielded.++ Closing the generator early does not cancel the run: the remaining pages+ are still parsed in the background and written to the run directory.++ ``resources`` from ``load_models`` keeps the layout models loaded between+ calls, so only the first one waits for them.+ """+ done = object()+ events: Queue = Queue()+ closed = threading.Event()+ outcome: Dict = {}++ def _put(event: Dict) -> None:+ if not closed.is_set():+ events.put(event)++ sink = InputOrder(_put) if ordered else _put++ def _run() -> None:+ try:+ outcome["summary"] = run_pages(cfg, sink, resources, detail)[1]+ except BaseException as exc:+ outcome["error"] = exc+ finally:+ if isinstance(sink, InputOrder):+ sink.flush()+ events.put(done)++ worker = threading.Thread(target=_run, name="minicpmvocr-stream", daemon=True)+ worker.start()+ try:+ while True:+ event = events.get()+ if event is done:+ break+ yield event+ finally:+ closed.set()+ worker.join()+ if "error" in outcome:+ raise outcome["error"]+ return outcome["summary"]diff --git a/sdk/minicpmvocr/pipeline/overlapped.py b/sdk/minicpmvocr/pipeline/overlapped.pyindex a5c4bde..7e9c1ed 100644--- a/sdk/minicpmvocr/pipeline/overlapped.py+++ b/sdk/minicpmvocr/pipeline/overlapped.py@@ -22,6 +22,7 @@ from ._blocks import (from ._inputs import _iter_source_pages, _open_page_imagefrom ._layout_record import _parse_one_pagefrom ._metrics import build_summary, write_per_page_metrics, write_summary+from ._stream import PageReporterfrom .upright import build_upright_corrector, upright_enabledfrom .._utils import append_jsonl, ensure_dir, now_iso, read_json, write_jsonfrom ..backends import create_backend@@ -90,8 +91,14 @@ def _failed_layout_row(entry: Dict, error: str, started: float) -> Dict:}-def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None) -> Dict:- 'Run layout detection and VLM inference concurrently when pipeline.overlap_layout is enabled.'+def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None,+ on_page=None, stream_detail: str = "page") -> Dict:+ """Run layout detection and VLM inference concurrently when pipeline.overlap_layout is enabled.++ ``on_page`` is called with one event per page as soon as that page is done,+ in the order pages finish. ``stream_detail`` "block" or "token" makes it+ hear about layouts, blocks and decoded text as well; see ``stream_pages``.+ """run_dir = Path(cfg["_meta"]["run_dir"])runtime_dir = run_dir / "runtime"runtime_intermediate = Path(cfg["_meta"]["runtime_intermediate_dir"])@@ -125,6 +132,13 @@ def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None)owns_detectors = not resources.get("detectors")owns_engine = resources.get("engine") is None+ # Pages are listed before the models load. For a stream the PDF then renders front+ # pages first in the background, and the first page is ready as soon as the models are.+ _enum_t0 = time.time()+ page_entries = _iter_source_pages(cfg, runtime_intermediate, front_first=on_page is not None)+ enumerate_sec = time.time() - _enum_t0+ if not page_entries:+ raise ValueError("No input pages found. Provide input.file_path or input.image_dir or input.files_dir with png/jpg/pdf files.")layout_workers = max(1, int(cfg["pipeline"].get("layout_workers", 1) or 1))_ld_t0 = time.time()@@ -163,12 +177,12 @@ def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None)tts_cfg.get("n"), tts_cfg.get("rm_url"), tts_cfg.get("rm_batch") or "off")- _enum_t0 = time.time()- page_entries = _iter_source_pages(cfg, runtime_intermediate)- enumerate_sec = time.time() - _enum_t0boot_sec = time.time() - _boot_t0- if not page_entries:- raise ValueError("No input pages found. Provide input.file_path or input.image_dir or input.files_dir with png/jpg/pdf files.")+ reporter = None+ if on_page is not None:+ reporter = PageReporter(+ run_dir, [entry["image_id"] for entry in page_entries], on_page, stream_detail)+ page_rank = {entry["image_id"]: rank for rank, entry in enumerate(page_entries)}events: Queue = Queue()@@ -275,6 +289,8 @@ def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None)for dump in state_result.get("tts_dumps", []):append_jsonl(tts_dump_path, dump)append_jsonl(page_timing_path, state_result["page_timing"])+ if reporter is not None:+ reporter.report(state_result)pages_done += 1if pages_done % progress_every == 0:print(f"[pipelined] pages done {pages_done}", flush=True)@@ -283,6 +299,10 @@ def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None)work_queue: PriorityQueue = PriorityQueue()tie = count()crop_pool = shared_crop_pool()+ # Longest blocks of the whole run first is the fastest order, but it leaves every page+ # waiting on its short blocks until the end. Someone reading pages as they finish is+ # better served page by page. The shared pool keeps one order for all its runs.+ page_first = reporter is not None and crop_pool is Nonepending_cv = threading.Condition()pending = [0]@@ -371,6 +391,8 @@ def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None)if md_path.exists() and json_path.exists():_finish(_skipped_page_result(image_id, page_started, layout_stage_sec, len(blocks), md_path))continue+ if reporter is not None:+ reporter.layout(image_id, layout)if not blocks:_finish(_finalize_page(run_dir=run_dir, image_id=image_id, layout=layout, blocks=blocks,@@ -385,23 +407,28 @@ def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None)submitted_at = time.time()+ on_delta = reporter.delta_listener(image_id, block) if reporter is not None else Nonedef _work():try:- return _execute_block(engine, prompt_map, image_id, crop_dir, block,- crop_array, rm_client=rm_caller, tts_cfg=tts_cfg,- submitted_at=submitted_at)+ output = _execute_block(engine, prompt_map, image_id, crop_dir, block,+ crop_array, rm_client=rm_caller, tts_cfg=tts_cfg,+ submitted_at=submitted_at, on_delta=on_delta)except Exception as e:- return _failed_block_output(image_id, block, str(e))+ output = _failed_block_output(image_id, block, str(e))+ if reporter is not None:+ reporter.block(image_id, output["result_block"])+ return outputreturn _work- items = [- _block_priority(prompt_map, block)- + (next(tie), pos, bpos, _make_work(block))- for bpos, block in enumerate(blocks)- ]+ items = []+ for bpos, block in enumerate(blocks):+ priority = _block_priority(prompt_map, block)+ if page_first:+ priority = (page_rank.get(image_id, pos), priority[0])+ items.append(priority + (next(tie), pos, bpos, _make_work(block)))page_states.append({"image_id": image_id, "layout": layout, "blocks": blocks,"crop_dir": crop_dir, "crops": crops, "page_started": page_started,diff --git a/sdk/minicpmvocr/pipeline/staged.py b/sdk/minicpmvocr/pipeline/staged.pyindex 66ddddd..0a023a0 100644--- a/sdk/minicpmvocr/pipeline/staged.py+++ b/sdk/minicpmvocr/pipeline/staged.py@@ -22,6 +22,7 @@ from ..prompts import load_prompt_mapfrom ..backends import create_backendfrom ..layouts import create_layout_detectorfrom ._metrics import build_summary, write_per_page_metrics, write_summary+from ._stream import PageReporterfrom .upright import build_upright_correctorfrom .rm_client import RMClient, build_rm_callerfrom .._utils import (@@ -43,8 +44,14 @@ def _update_run_meta(run_meta_path: Path, updates: Dict) -> None:write_json(run_meta_path, meta)-def parse_layout_run(cfg: Dict) -> Dict:+def parse_layout_run(cfg: Dict, resources: Dict | None = None) -> Dict:+ """Detect the layout of every input page.++ ``resources`` from ``load_models`` supplies a detector and an upright+ corrector that are already loaded; they are used as they are and left loaded.+ """_stage_t0 = time.time()+ resources = resources or {}run_dir = Path(cfg["_meta"]["run_dir"])runtime_dir = run_dir / "runtime"runtime_intermediate = Path(cfg["_meta"]["runtime_intermediate_dir"])@@ -57,11 +64,17 @@ def parse_layout_run(cfg: Dict) -> Dict:ensure_dir(crops_root)ensure_dir(run_dir / "logs")- layout_detector = create_layout_detector(cfg["layout"])- layout_detector.start()+ shared_detectors = list(resources.get("detectors") or [])+ if shared_detectors:+ layout_detector = shared_detectors[0]+ else:+ layout_detector = create_layout_detector(cfg["layout"])+ layout_detector.start()provider = layout_detector.name- upright_corrector = build_upright_corrector(cfg)+ upright_corrector = resources.get("upright")+ if upright_corrector is None:+ upright_corrector = build_upright_corrector(cfg)page_entries = _iter_source_pages(cfg, runtime_intermediate)if not page_entries:@@ -80,7 +93,8 @@ def parse_layout_run(cfg: Dict) -> Dict:parse_rows.append(row)layout_loop_sec = time.time() - layout_loop_t0- layout_detector.stop()+ if not shared_detectors:+ layout_detector.stop()layout_timing_path = runtime_dir / "layout_timing.jsonl"with layout_timing_path.open("w", encoding="utf-8") as f:@@ -217,6 +231,17 @@ def prepare_run(cfg: Dict) -> Dict:return run_meta+def _recognize_block(reporter, engine, prompt_map: Dict, image_id: str, crop_dir: Path, block: Dict,+ **kwargs) -> Dict:+ '``_execute_block``, telling ``reporter`` about the text as it is decoded and the finished block.'+ if reporter is None:+ return _execute_block(engine, prompt_map, image_id, crop_dir, block, **kwargs)+ output = _execute_block(engine, prompt_map, image_id, crop_dir, block,+ on_delta=reporter.delta_listener(image_id, block), **kwargs)+ reporter.block(image_id, output["result_block"])+ return output++def _infer_concurrent(*,run_dir: Path,@@ -227,11 +252,17 @@ def _infer_concurrent(progress_every: int,rm_client=None,tts_cfg: Optional[Dict] = None,+ reporter=None,) -> Dict[int, Dict]:page_states: List[Dict] = []flat: List[tuple] = []+ def _settle(state: Dict, result: Dict) -> None:+ state["result"] = result+ if reporter is not None:+ reporter.report(result)+for pos, task in enumerate(tasks):image_id = task["image_id"]page_started = time.time()@@ -246,9 +277,11 @@ def _infer_concurrent(md_path = run_dir / "output" / f"{image_id}.md"json_path = run_dir / "results_json" / f"{image_id}.json"if md_path.exists() and json_path.exists():- state["result"] = _skipped_page_result(image_id, page_started, layout_stage_sec, len(blocks), md_path)+ _settle(state, _skipped_page_result(image_id, page_started, layout_stage_sec, len(blocks), md_path))elif not blocks:- state["result"] = _finalize_page(+ if reporter is not None:+ reporter.layout(image_id, layout)+ _settle(state, _finalize_page(run_dir=run_dir,image_id=image_id,layout=layout,@@ -257,8 +290,10 @@ def _infer_concurrent(prompt_map=prompt_map,page_started=page_started,layout_stage_sec=layout_stage_sec,- )+ ))else:+ if reporter is not None:+ reporter.layout(image_id, layout)state.update({"layout": layout,@@ -273,11 +308,16 @@ def _infer_concurrent(for bpos, block in enumerate(blocks):flat.append((pos, bpos, block))except Exception as e:- state["result"] = _failed_page_result(image_id, page_started, layout_stage_sec, str(e))+ if state["result"] is None:+ _settle(state, _failed_page_result(image_id, page_started, layout_stage_sec, str(e)))page_states.append(state)- flat.sort(key=lambda item: _block_priority(prompt_map, item[2]))+ if reporter is None:+ flat.sort(key=lambda item: _block_priority(prompt_map, item[2]))+ else:+ # Page by page, so that pages finish one after another instead of all at the end.+ flat.sort(key=lambda item: (item[0],) + _block_priority(prompt_map, item[2]))total_pages = len(tasks)completed_pages = sum(1 for s in page_states if s["result"] is not None)@@ -285,11 +325,14 @@ def _infer_concurrent(def _run_one(pos: int, block: Dict, submitted_at: float = 0.0) -> Dict:state = page_states[pos]try:- return _execute_block(engine, prompt_map, state["image_id"], state["crop_dir"], block,- rm_client=rm_client, tts_cfg=tts_cfg,- submitted_at=submitted_at or None)+ return _recognize_block(reporter, engine, prompt_map, state["image_id"], state["crop_dir"],+ block, rm_client=rm_client, tts_cfg=tts_cfg,+ submitted_at=submitted_at or None)except Exception as e:- return _failed_block_output(state["image_id"], block, str(e))+ output = _failed_block_output(state["image_id"], block, str(e))+ if reporter is not None:+ reporter.block(state["image_id"], output["result_block"])+ return outputif flat:with ThreadPoolExecutor(max_workers=min(request_workers, len(flat))) as executor:@@ -303,7 +346,7 @@ def _infer_concurrent(if state["remaining"] > 0:continuetry:- state["result"] = _finalize_page(+ result = _finalize_page(run_dir=run_dir,image_id=state["image_id"],layout=state["layout"],@@ -314,9 +357,10 @@ def _infer_concurrent(layout_stage_sec=state["layout_stage_sec"],)except Exception as e:- state["result"] = _failed_page_result(+ result = _failed_page_result(state["image_id"], state["page_started"], state["layout_stage_sec"], str(e))+ _settle(state, result)completed_pages += 1if completed_pages % progress_every == 0 or completed_pages == total_pages:print(f"[infer] progress {completed_pages}/{total_pages}")@@ -324,7 +368,13 @@ def _infer_concurrent(return {pos: state["result"] for pos, state in enumerate(page_states)}-def infer_run(cfg: Dict) -> Dict:+def infer_run(cfg: Dict, on_page=None, stream_detail: str = "page") -> Dict:+ """Recognize the pages a run has laid out.++ ``on_page`` is called with one event per page as soon as that page is done,+ in the order pages finish. ``stream_detail`` "block" or "token" makes it+ hear about layouts, blocks and decoded text as well; see ``stream_pages``.+ """run_dir = Path(cfg["_meta"]["run_dir"])run_meta_path = run_dir / "run_meta.json"if not run_meta_path.exists():@@ -332,6 +382,10 @@ def infer_run(cfg: Dict) -> Dict:prompt_map = load_prompt_map(cfg)tasks = read_jsonl(run_dir / "runtime" / "page_tasks.jsonl")+ reporter = None+ if on_page is not None:+ reporter = PageReporter(run_dir, [task["image_id"] for task in tasks], on_page, stream_detail)+ on_result = reporter.report if reporter is not None else Noneengine = create_backend(cfg)engine.start()@@ -374,11 +428,13 @@ def infer_run(cfg: Dict) -> Dict:json_path = run_dir / "results_json" / f"{image_id}.json"if md_path.exists() and json_path.exists():return _skipped_page_result(image_id, page_started, layout_stage_sec, len(blocks), md_path)+ if reporter is not None:+ reporter.layout(image_id, layout)if block_workers == 1 or len(blocks) <= 1:block_outputs = [- _execute_block(engine, prompt_map, image_id, crop_dir, block,- rm_client=rm_caller, tts_cfg=tts_cfg)+ _recognize_block(reporter, engine, prompt_map, image_id, crop_dir, block,+ rm_client=rm_caller, tts_cfg=tts_cfg)for block in blocks]else:@@ -386,8 +442,8 @@ def infer_run(cfg: Dict) -> Dict:with ThreadPoolExecutor(max_workers=min(block_workers, len(blocks))) as executor:_now = time.time()futures = {- executor.submit(_execute_block, engine, prompt_map, image_id, crop_dir, block,- rm_client=rm_caller, tts_cfg=tts_cfg,+ executor.submit(_recognize_block, reporter, engine, prompt_map, image_id,+ crop_dir, block, rm_client=rm_caller, tts_cfg=tts_cfg,submitted_at=_now): ifor i, block in enumerate(blocks)}@@ -419,10 +475,13 @@ def infer_run(cfg: Dict) -> Dict:progress_every=progress_every,rm_client=rm_caller,tts_cfg=tts_cfg,+ reporter=reporter,)elif page_workers == 1 or len(tasks) <= 1:for idx, task in enumerate(tasks, start=1):page_results_by_idx[idx - 1] = _process_page(task)+ if on_result is not None:+ on_result(page_results_by_idx[idx - 1])if idx % progress_every == 0:print(f"[infer] progress {idx}/{len(tasks)}")else:@@ -454,6 +513,8 @@ def infer_run(cfg: Dict) -> Dict:"page_timing": {"image_id": image_id, "status": "failed", "duration_sec": 0.0, "error": str(e)},"crop_rows": [],}+ if on_result is not None:+ on_result(page_results_by_idx[task_idx])completed += 1if completed % progress_every == 0 or completed == len(tasks):print(f"[infer] progress {completed}/{len(tasks)}")diff --git a/sdk/tests/test_backend_streaming.py b/sdk/tests/test_backend_streaming.pynew file mode 100644index 0000000..3625478--- /dev/null+++ b/sdk/tests/test_backend_streaming.py@@ -0,0 +1,164 @@+"""The client reads a streamed reply the same way as a plain one, handing the text over as it comes."""+import json++import pytest+from PIL import Image++from minicpmvocr.backends import VLMClient, resolve_dialect+from minicpmvocr.backends.dialects import DIALECTS, DialectError, collect_stream, stream_payload+from minicpmvocr.config import DEFAULT_CONFIG+++def _sse(*chunks, done=True):+ lines = []+ for chunk in chunks:+ lines += [b"data: " + json.dumps(chunk).encode(), b""]+ return lines + ([b"data: [DONE]"] if done else [])+++def _delta(text, finish_reason=None):+ return {"choices": [{"index": 0, "delta": {"content": text}, "finish_reason": finish_reason}]}+++USAGE = {"choices": [], "usage": {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}}+++def test_sse_stream_collects_to_the_plain_reply():+ heard = []+ lines = _sse({"choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}}]},+ _delta("\u4f60\u597d"), _delta("\uff0c"), _delta("world", "stop"), USAGE)+ body = collect_stream("sse", lines, heard.append)++ assert heard == ["\u4f60\u597d", "\uff0c", "world"]+ result = DIALECTS["vllm"].parse_response(body)+ assert result["text"] == "\u4f60\u597d\uff0cworld"+ assert result["finish_reason"] == "stop"+ assert result["output_token_count"] == 3+ assert result["request_metrics"]["prompt_tokens"] == 7+++def test_sse_stream_ignores_keep_alives_and_other_choices():+ heard = []+ lines = [b": ping", b""] + _sse(+ _delta("a"), {"choices": [{"index": 1, "delta": {"content": "other"}}]}, _delta("b", "length"))+ body = collect_stream("sse", lines, heard.append)+ assert heard == ["a", "b"]+ assert body["choices"][0] == {"message": {"content": "ab"}, "finish_reason": "length"}+++def test_sse_stream_raises_an_error_sent_in_the_stream():+ with pytest.raises(DialectError, match="boom"):+ collect_stream("sse", _sse(_delta("a"), {"error": {"message": "boom"}}), lambda text: None)+++def test_ndjson_stream_collects_to_the_plain_reply():+ heard = []+ lines = [json.dumps(chunk).encode() for chunk in (+ {"message": {"role": "assistant", "content": "Hel"}, "done": False},+ {"message": {"role": "assistant", "content": "lo"}, "done": False},+ {"message": {"role": "assistant", "content": ""}, "done": True, "done_reason": "stop",+ "eval_count": 2, "prompt_eval_count": 5},+ )]+ body = collect_stream("ndjson", lines, heard.append)++ assert heard == ["Hel", "lo"]+ result = DIALECTS["ollama"].parse_response(body)+ assert (result["text"], result["finish_reason"], result["output_token_count"]) == ("Hello", "stop", 2)+++def test_stream_payload_asks_for_token_counts_only_where_they_exist():+ assert stream_payload({"model": "m"}, "sse") == {+ "model": "m", "stream": True, "stream_options": {"include_usage": True}}+ assert stream_payload({"model": "m", "stream": False}, "ndjson") == {"model": "m", "stream": True}+++def test_every_backend_says_how_it_streams():+ assert {name: dialect.stream_format for name, dialect in DIALECTS.items()} == {+ "openai": "sse", "vllm": "sse", "llamacpp": "sse", "ollama": "ndjson", "ollama_openai": "sse"}+++class _Reply:+ def __init__(self, lines=None, body=None, fail_after=None):+ self.status_code = 200+ self._lines, self._body, self._fail_after = lines, body, fail_after+ self.closed = False++ def iter_lines(self):+ for position, line in enumerate(self._lines):+ if self._fail_after is not None and position >= self._fail_after:+ raise ConnectionError("connection dropped")+ yield line++ def json(self):+ return self._body++ def close(self):+ self.closed = True+++class _Session:+ def __init__(self, replies):+ self.replies = list(replies)+ self.posts = []++ def post(self, url, json=None, headers=None, timeout=None, stream=False):+ self.posts.append({"payload": json, "stream": stream})+ return self.replies.pop(0)+++def _client(monkeypatch, replies):+ cfg = json.loads(json.dumps(DEFAULT_CONFIG))+ cfg["engine"].update({"type": "vllm", "server_url": "http://localhost:1", "model_name": "m",+ "request_retry_interval_sec": 0})+ client = VLMClient(cfg, resolve_dialect(cfg["engine"]))+ session = _Session(replies)+ monkeypatch.setattr(client, "_session", lambda: session)+ return client, session+++IMAGE = Image.new("RGB", (8, 8), "white")+PLAIN = {"choices": [{"message": {"content": "hello"}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}}+++def test_client_streams_only_when_someone_listens(monkeypatch):+ client, session = _client(monkeypatch, [_Reply(body=PLAIN)])+ result = client.recognize(IMAGE, prompt="p", max_new_tokens=64)+ assert result["text"] == "hello"+ assert session.posts[0]["stream"] is False+ assert "stream" not in session.posts[0]["payload"] and "stream_options" not in session.posts[0]["payload"]+++def test_client_hands_over_the_text_and_returns_the_same_result(monkeypatch):+ reply = _Reply(lines=_sse(_delta("hel"), _delta("lo", "stop"), USAGE))+ client, session = _client(monkeypatch, [reply])+ heard = []+ result = client.recognize(IMAGE, prompt="p", max_new_tokens=64,+ on_delta=lambda text, restart: heard.append((text, restart)))++ assert heard == [("hel", False), ("lo", False)]+ assert (result["text"], result["finish_reason"], result["output_token_count"]) == ("hello", "stop", 3)+ assert session.posts[0]["stream"] is True+ assert session.posts[0]["payload"]["stream"] is True+ assert session.posts[0]["payload"]["stream_options"] == {"include_usage": True}+ assert reply.closed+++def test_client_marks_the_restart_when_a_stream_breaks_and_is_sent_again(monkeypatch):+ broken = _Reply(lines=_sse(_delta("hel"), _delta("lo", "stop"), USAGE), fail_after=2)+ whole = _Reply(lines=_sse(_delta("hel"), _delta("lo", "stop"), USAGE))+ client, session = _client(monkeypatch, [broken, whole])+ heard = []+ result = client.recognize(IMAGE, prompt="p", max_new_tokens=64,+ on_delta=lambda text, restart: heard.append((text, restart)))++ # "hel" from the broken try, then the second try starts over and says so once.+ assert heard == [("hel", False), ("hel", True), ("lo", False)]+ assert result["text"] == "hello"+ assert len(session.posts) == 2 and broken.closed+++def test_client_does_not_stream_several_candidates(monkeypatch):+ client, session = _client(monkeypatch, [_Reply(body=PLAIN)])+ client.recognize(IMAGE, prompt="p", max_new_tokens=64, n=3, on_delta=lambda text, restart: None)+ assert session.posts[0]["stream"] is Falsediff --git a/sdk/tests/test_pdf_rendering.py b/sdk/tests/test_pdf_rendering.pyindex e014032..6367826 100644--- a/sdk/tests/test_pdf_rendering.py+++ b/sdk/tests/test_pdf_rendering.py@@ -90,3 +90,40 @@ def test_render_pool_agrees_with_the_serial_fallback(tmp_path, many_page_pdf, reassert pooled_cfg["_meta"]["render_workers"] == render_workersassert [e["image_size"] for e in serial] == [e["image_size"] for e in pooled]assert [e["image_bytes"] for e in serial] == [e["image_bytes"] for e in pooled]+++def test_front_first_rendering_hands_over_the_same_pages(tmp_path, many_page_pdf):++ serial = _iter_source_pages(_cfg(many_page_pdf, render_workers=1), tmp_path)+ cfg = _cfg(many_page_pdf, render_workers=3)+ early = _iter_source_pages(cfg, tmp_path, front_first=True)++ assert [e["image_id"] for e in early] == [e["image_id"] for e in serial]+ # The first job's pages are rendered on the spot; the rest come back as a promise,+ # because they are still rendering.+ from minicpmvocr.constants import PDF_RENDER_PAGES_PER_EARLY_JOB as on_the_spot++ assert all("image_bytes" in e for e in early[:on_the_spot])+ assert all("image_future" in e and "image_bytes" not in e for e in early[on_the_spot:])+ for eager, lazy in zip(serial, early):+ assert _open_page_image(lazy).tobytes() == eager["image_bytes"]+ assert cfg["_meta"]["render_workers"] == 3+ assert cfg["_meta"]["render_sec"] > 0+++def test_front_first_rendering_reports_a_broken_page_when_it_is_opened(tmp_path, many_page_pdf, monkeypatch):+ from concurrent.futures import Future++ from minicpmvocr.pipeline import _inputs++ broken = Future()+ broken.set_exception(RuntimeError("cannot render"))+ monkeypatch.setattr(+ _inputs, "_render_pdf_pages",+ lambda paths, workers, front_first=False: {(str(many_page_pdf), 5): (broken, 0)})++ entries = _iter_source_pages(_cfg(many_page_pdf, render_workers=3), tmp_path, front_first=True)+ with pytest.raises(RuntimeError, match="cannot render"):+ _open_page_image(entries[5])+ # Pages the pool did not cover are rendered in this process.+ assert "image_bytes" in entries[0]diff --git a/sdk/tests/test_stream_pages.py b/sdk/tests/test_stream_pages.pynew file mode 100644index 0000000..8b04b9d--- /dev/null+++ b/sdk/tests/test_stream_pages.py@@ -0,0 +1,593 @@+"""Pages are handed over one at a time, while the rest of the run is still going."""+import json+import threading+from pathlib import Path++import pytest+from PIL import Image++import minicpmvocr+from minicpmvocr import cli+from minicpmvocr.pipeline import overlapped, staged+from minicpmvocr.pipeline._stream import InputOrder++from tests.test_parse_quickstart import ( # noqa: F401 (quickstart is a fixture)+ FakeDetector,+ FakeEngine,+ _set_argv,+ quickstart,+)+++def _images(root, names):+ for name in names:+ Image.new("RGB", (40, 30), "white").save(root / name)+++def _parse_config(monkeypatch, root, inputs, *extra):+ """The config `minicpmvocr parse` would build for these inputs."""+ _set_argv(monkeypatch, ["minicpmvocr", "parse", *inputs, "--device", "cpu", *extra])+ args = cli._build_parser().parse_args()+ return cli._load_parse_config(args)+++class GatedEngine(FakeEngine):+ """Recognizes one page, then waits until the test lets the next ones through."""++ def __init__(self):+ self.gate = threading.Event()+ self.calls = 0+ self.lock = threading.Lock()++ def recognize(self, image, prompt, max_new_tokens, slice_nums=None):+ with self.lock:+ self.calls += 1+ first = self.calls == 1+ if not first:+ assert self.gate.wait(timeout=30), "the test never opened the gate"+ return {"text": "Recognized page.", "output_token_count": 2}++[email protected]("overlap", [True, False])+def test_first_page_arrives_before_the_run_is_over(quickstart, monkeypatch, overlap):+ root, _, _ = quickstart+ _images(root, ["second.png", "third.png"])+ engine = GatedEngine()+ for module in (staged, overlapped):+ monkeypatch.setattr(module, "create_backend", lambda config: engine)+ cfg = _parse_config(+ monkeypatch, root, ["input.png", "second.png", "third.png"],+ "--workers", "1", "--set", f"pipeline.overlap_layout={str(overlap).lower()}")++ stream = minicpmvocr.stream_pages(cfg)+ first = next(stream)+ # Two pages are still stuck behind the gate, so the run cannot have finished.+ assert not engine.gate.is_set()+ assert first["event"] == "page" and first["status"] == "ok"+ assert (first["pages_done"], first["pages_total"]) == (1, 3)+ assert first["markdown"] == "Recognized page."+ assert first["page"]["choices"][0]["message"]["content"] == "Recognized page."+ assert Path(first["output_md"]).read_text() == "Recognized page."++ engine.gate.set()+ rest = list(stream)+ assert [event["pages_done"] for event in rest] == [2, 3]+ assert sorted(event["index"] for event in [first, *rest]) == [0, 1, 2]+++def test_events_say_which_input_and_page_they_are(quickstart, monkeypatch):+ fitz = pytest.importorskip("fitz")+ root, _, _ = quickstart+ with fitz.open() as doc:+ for _ in range(3):+ doc.new_page(width=72, height=72)+ doc.save(root / "doc.pdf")+ cfg = _parse_config(monkeypatch, root, ["input.png", "doc.pdf"])++ events = sorted(minicpmvocr.stream_pages(cfg), key=lambda event: event["index"])+ assert [event["image_id"] for event in events] == [+ "input", "doc_page_001", "doc_page_002", "doc_page_003"]+ assert [event["source_id"] for event in events] == ["s001", "s002", "s002", "s002"]+ assert [Path(event["source"]).name for event in events] == [+ "input.png", "doc.pdf", "doc.pdf", "doc.pdf"]+ assert [event["page_index"] for event in events] == [0, 0, 1, 2]+++def test_generator_returns_the_run_summary(quickstart, monkeypatch):+ root, _, _ = quickstart+ cfg = _parse_config(monkeypatch, root, ["input.png"])+ stream = minicpmvocr.stream_pages(cfg)+ with pytest.raises(StopIteration) as stop:+ while True:+ next(stream)+ assert stop.value.value["counts"]["ok"] == 1+++def test_a_page_that_fails_is_reported_and_the_rest_still_arrive(quickstart, monkeypatch):+ root, _, _ = quickstart+ _images(root, ["second.png"])++ class BrokenOnce(FakeDetector):+ def detect(self, images):+ if images[0].width == 41:+ raise RuntimeError("layout exploded")+ return super().detect(images)++ Image.new("RGB", (41, 30), "white").save(root / "bad.png")+ monkeypatch.setattr(overlapped, "create_layout_detector", lambda config: BrokenOnce(config))+ cfg = _parse_config(monkeypatch, root, ["input.png", "bad.png", "second.png"])++ events = {event["image_id"]: event for event in minicpmvocr.stream_pages(cfg, ordered=True)}+ assert list(events) == ["input", "bad", "second"]+ assert events["bad"]["status"] == "failed"+ assert "layout exploded" in events["bad"]["error"]+ assert events["bad"]["page"] is None and events["bad"]["markdown"] == ""+ assert events["second"]["status"] == "ok"+++def test_an_error_that_stops_the_run_is_raised(quickstart, monkeypatch):+ root, _, _ = quickstart++ def _no_engine(config):+ raise RuntimeError("no engine")++ monkeypatch.setattr(overlapped, "create_backend", _no_engine)+ cfg = _parse_config(monkeypatch, root, ["input.png"])+ with pytest.raises(RuntimeError, match="no engine"):+ list(minicpmvocr.stream_pages(cfg))+++def test_a_consumer_that_raises_does_not_stop_the_run(quickstart, monkeypatch):+ root, _, _ = quickstart+ _images(root, ["second.png"])+ cfg = _parse_config(monkeypatch, root, ["input.png", "second.png"])+ seen = []++ def _on_page(event):+ seen.append(event["image_id"])+ raise ValueError("consumer bug")++ summary = overlapped.pipelined_run(cfg, on_page=_on_page)+ assert sorted(seen) == ["input", "second"]+ assert summary["counts"]["ok"] == 2+++def test_input_order_holds_pages_until_their_turn():+ delivered = []+ ordered = InputOrder(delivered.append)+ for index in (2, 0, 3, 1):+ ordered({"event": "page", "index": index, "pages_done": 99})+ assert [event["index"] for event in delivered] == [0, 1, 2, 3]+ assert [event["pages_done"] for event in delivered] == [1, 2, 3, 4]+++def test_input_order_flush_releases_pages_behind_a_missing_one():+ delivered = []+ ordered = InputOrder(delivered.append)+ ordered({"event": "page", "index": 2, "pages_done": 1})+ ordered({"event": "page", "index": 1, "pages_done": 2})+ assert delivered == []+ ordered.flush()+ assert [event["index"] for event in delivered] == [1, 2]+++def _lines(text):+ return [json.loads(line) for line in text.splitlines()]+++def test_cli_stream_writes_one_line_per_page_then_the_summary(quickstart, monkeypatch, capsys):+ root, _, _ = quickstart+ _images(root, ["second.png"])+ _set_argv(monkeypatch, [+ "minicpmvocr", "parse", "input.png", "second.png", "--stream-ordered", "--device", "cpu"])+ assert cli.main() == 0+ lines = _lines(capsys.readouterr().out)+ assert [line["event"] for line in lines] == ["page", "page", "done"]+ assert [line["image_id"] for line in lines[:2]] == ["input", "second"]+ assert [line["markdown"] for line in lines[:2]] == ["Recognized page."] * 2+ assert lines[-1]["status"] == "Success" and lines[-1]["inputs"] == 2+ # No -o: the stream is the result, nothing is written beside it.+ assert all("output_md" not in output for output in lines[-1]["outputs"])+++def test_cli_stream_still_writes_the_files_asked_for(quickstart, monkeypatch, capsys):+ fitz = pytest.importorskip("fitz")+ root, _, _ = quickstart+ with fitz.open() as doc:+ for _ in range(2):+ doc.new_page(width=72, height=72)+ doc.save(root / "input.pdf")+ _set_argv(monkeypatch, [+ "minicpmvocr", "parse", "input.pdf", "-o", "result.md", "--json", "--stream",+ "--device", "cpu"])+ assert cli.main() == 0+ lines = _lines(capsys.readouterr().out)+ assert [line["event"] for line in lines] == ["page", "page", "done"]+ assert sorted(line["page_index"] for line in lines[:2]) == [0, 1]+ assert lines[-1]["pages"] == 2+ assert (root / "result.md").read_text() == "Recognized page.\n\n<!-- page-break -->\n\nRecognized page."+ assert json.loads((root / "result.json").read_text())["pages_done"] == 2+++def test_cli_stream_of_one_input_needs_no_output_path(quickstart, monkeypatch, capsys):+ _set_argv(monkeypatch, ["minicpmvocr", "parse", "input.png", "--stream", "--device", "cpu"])+ assert cli.main() == 0+ lines = _lines(capsys.readouterr().out)+ assert [line["event"] for line in lines] == ["page", "done"]+ assert lines[-1]["pages"] == 1+++def test_cli_stream_and_stdout_are_rejected_before_the_run(quickstart, monkeypatch, capsys):+ _, _, seen = quickstart+ _set_argv(monkeypatch, [+ "minicpmvocr", "parse", "input.png", "--stream", "--stdout", "--device", "cpu"])+ with pytest.raises(SystemExit):+ cli.main()+ assert "--stream" in capsys.readouterr().err+ assert seen["configs"] == []+++def test_stream_of_a_pdf_rendered_in_the_background(quickstart, monkeypatch):+ fitz = pytest.importorskip("fitz")+ root, _, _ = quickstart+ with fitz.open() as doc:+ for _ in range(9):+ doc.new_page(width=72, height=72)+ doc.save(root / "long.pdf")+ cfg = _parse_config(monkeypatch, root, ["long.pdf"])++ events = list(minicpmvocr.stream_pages(cfg, ordered=True))+ assert [event["page_index"] for event in events] == list(range(9))+ assert all(event["status"] == "ok" for event in events)+ # Nine pages are more than one rendering job, so they came through the background pool.+ assert cfg["_meta"]["render_workers"] != 1 and cfg["_meta"]["render_sec"] > 0+++# --- dispatch order: a stream gets its pages one after another, not all at the end ----------++def test_staged_stream_recognizes_page_by_page(tmp_path, monkeypatch):+ from minicpmvocr import pipeline+ from tests.test_infer_scheduling import BLOCKS_PER_PAGE, PAGES, RecordingEngine, _build_run, _cfg++ def _pages_in_call_order(on_page):+ run_dir = _build_run(tmp_path / ("stream" if on_page else "batch"))+ engine = RecordingEngine()+ monkeypatch.setattr(staged, "create_backend", lambda cfg: engine)+ pipeline.infer_run(_cfg(run_dir, "concurrent", 1, 1), on_page=on_page)+ # _build_run makes every crop of page N exactly 20 + N pixels high.+ return [height - 20 for _width, height in engine.calls]++ grouped = [page for page in range(PAGES) for _ in range(BLOCKS_PER_PAGE)]+ seen = []+ assert _pages_in_call_order(seen.append) == grouped+ assert [event["image_id"] for event in seen] == [f"page{page}" for page in range(PAGES)]+ # Without a consumer the run keeps its fastest order: longest blocks first, across pages.+ assert _pages_in_call_order(None) != grouped+++def test_overlapped_stream_recognizes_page_by_page(tmp_path, monkeypatch):+ import numpy as np+ from copy import deepcopy++ from minicpmvocr.config import DEFAULT_CONFIG+ from tests.test_crop_priority import LABELS, _MultiLabelDetector++ pages = 3+ all_laid_out = threading.Event()++ class PageCodedDetector(_MultiLabelDetector):+ cropped = 0++ def crop(self, image, detections):+ blocks = super().crop(image, detections)+ for block in blocks:+ # Page N is 60 + N pixels wide; its crops are 20 + N wide.+ block["image"] = np.full((10, image.width - 40, 3), 200, dtype=np.uint8)+ PageCodedDetector.cropped += 1+ if PageCodedDetector.cropped == pages:+ all_laid_out.set()+ return blocks++ class PageRecordingEngine(FakeEngine):+ def __init__(self):+ self.pages = []++ def recognize(self, image, prompt, max_new_tokens, slice_nums=None):+ if not self.pages:+ # Hold the first block until every page is queued, so the order is a choice.+ assert all_laid_out.wait(timeout=30)+ threading.Event().wait(0.3)+ self.pages.append(image.size[0] - 20)+ return {"text": "x", "output_token_count": 1}++ src = tmp_path / "src"+ src.mkdir()+ for page in range(pages):+ Image.fromarray(np.full((40, 60 + page, 3), 200, dtype=np.uint8)).save(src / f"p{page}.png")+ engine = PageRecordingEngine()+ monkeypatch.setattr(overlapped, "create_layout_detector", lambda c: PageCodedDetector(c))+ monkeypatch.setattr(overlapped, "create_backend", lambda c: engine)++ run_dir = tmp_path / "run"+ cfg = deepcopy(DEFAULT_CONFIG)+ cfg["run"].update({"run_tag": "t", "run_root": str(tmp_path), "mode": "full"})+ cfg["input"].update({"image_dir": str(src)})+ cfg["layout"].update({"provider": "fake", "device": "cpu"})+ cfg["pipeline"].update({"max_workers": 1, "layout_workers": 1, "overlap_layout": True})+ cfg["logging"]["progress_log_every"] = 1000+ cfg["_meta"] = {+ "run_dir": str(run_dir),+ "runtime_intermediate_dir": str(run_dir / "runtime" / "intermediate"),+ }+ finished = []+ overlapped.pipelined_run(cfg, on_page=lambda event: finished.append(event["image_id"]))++ assert engine.pages == [page for page in range(pages) for _ in LABELS]+ assert finished == ["p0", "p1", "p2"]+++# --- models loaded once, used by several runs ----------------------------------------------++class CountingDetector(FakeDetector):+ started = 0+ stopped = 0++ def _start(self):+ CountingDetector.started += 1++ def stop(self):+ CountingDetector.stopped += 1+ super().stop()+++def loaded(quickstart, monkeypatch):+ from minicpmvocr.pipeline import _models++ CountingDetector.started = CountingDetector.stopped = 0+ monkeypatch.setattr(_models, "create_layout_detector", lambda config: CountingDetector(config))+ monkeypatch.setattr(_models, "build_upright_corrector", lambda config: None)+ return quickstart++[email protected]("overlap", [True, False])+def test_loaded_models_serve_several_runs_without_reloading(loaded, monkeypatch, overlap):+ root, _, seen = loaded+ _images(root, ["second.png"])+ extra = ["--set", f"pipeline.overlap_layout={str(overlap).lower()}"]+ first = _parse_config(monkeypatch, root, ["input.png"], "--run-tag", "one", *extra)++ with minicpmvocr.load_models(first) as models:+ assert CountingDetector.started == 1+ assert [e["status"] for e in minicpmvocr.stream_pages(first, resources=models)] == ["ok"]+ second = _parse_config(monkeypatch, root, ["second.png"], "--run-tag", "two", *extra)+ assert [e["image_id"] for e in minicpmvocr.stream_pages(second, resources=models)] == ["second"]+ # Neither run built a detector of its own, and neither unloaded the shared one.+ assert seen["layouts"] == []+ assert (CountingDetector.started, CountingDetector.stopped) == (1, 0)+ assert CountingDetector.stopped == 1+++def test_loaded_models_also_serve_a_run_that_is_not_streamed(loaded, monkeypatch):+ root, _, seen = loaded+ cfg = _parse_config(monkeypatch, root, ["input.png"])+ models = minicpmvocr.load_models(cfg)+ summary = minicpmvocr.pipelined_run(cfg, resources=models)+ assert summary["counts"]["ok"] == 1+ assert seen["layouts"] == [] and CountingDetector.stopped == 0+ models.close()+ assert CountingDetector.stopped == 1 and "detectors" not in models+++def test_load_models_unloads_what_it_loaded_when_loading_fails(loaded, monkeypatch):+ from minicpmvocr.pipeline import _models++ root, _, _ = loaded+ cfg = _parse_config(monkeypatch, root, ["input.png"], "--set", "pipeline.layout_workers=2")++ def _no_upright(config):+ raise RuntimeError("upright model missing")++ monkeypatch.setattr(_models, "build_upright_corrector", _no_upright)+ with pytest.raises(RuntimeError, match="upright model missing"):+ minicpmvocr.load_models(cfg)+ assert (CountingDetector.started, CountingDetector.stopped) == (2, 2)+++# --- a run nobody is streaming keeps the order that finishes the whole run soonest ---------++def test_a_run_that_is_not_streamed_renders_and_dispatches_as_before(quickstart, monkeypatch):+ root, _, _ = quickstart+ calls = []+ real = overlapped._iter_source_pages++ def _spy(cfg, runtime_intermediate, front_first=False):+ calls.append(front_first)+ return real(cfg, runtime_intermediate, front_first=front_first)++ priorities = []+ real_put = overlapped.PriorityQueue.put++ class RecordingQueue(overlapped.PriorityQueue):+ def put(self, item, *args, **kwargs):+ if item[-1] is not None:+ priorities.append(item[:2])+ return real_put(self, item, *args, **kwargs)++ monkeypatch.setattr(overlapped, "_iter_source_pages", _spy)+ monkeypatch.setattr(overlapped, "PriorityQueue", RecordingQueue)+ _images(root, ["second.png"])++ overlapped.pipelined_run(_parse_config(monkeypatch, root, ["input.png", "second.png"], "--run-tag", "plain"))+ plain = list(priorities)+ priorities.clear()+ overlapped.pipelined_run(+ _parse_config(monkeypatch, root, ["input.png", "second.png"], "--run-tag", "streamed"),+ on_page=lambda event: None)++ assert calls == [False, True]+ # Not streamed: keyed by the block alone (-token cap, -area), the same for both pages.+ assert len(set(plain)) == 1 and plain[0][0] < 0+ # Streamed: keyed by the page first.+ assert [priority[0] for priority in priorities] == [0, 1]+++# --- finer events: the layout of a page, each block, the text while it is decoded ----------++class TypingEngine(FakeEngine):+ """Decodes "Recognized page." in three pieces, like a backend that streams."""++ pieces = ("Recog", "nized ", "page.")++ def recognize(self, image, prompt, max_new_tokens, slice_nums=None, on_delta=None):+ if on_delta is not None:+ for piece in self.pieces:+ on_delta(piece, False)+ return {"text": "".join(self.pieces), "output_token_count": 3}+++def typing(quickstart, monkeypatch):+ for module in (staged, overlapped):+ monkeypatch.setattr(module, "create_backend", lambda config: TypingEngine())+ return quickstart+++def _kinds(events):+ return [event["event"] for event in events]++[email protected]("overlap", [True, False])+def test_block_detail_reports_the_layout_then_each_block_then_the_page(typing, monkeypatch, overlap):+ root, _, _ = typing+ cfg = _parse_config(monkeypatch, root, ["input.png"],+ "--set", f"pipeline.overlap_layout={str(overlap).lower()}")+ events = list(minicpmvocr.stream_pages(cfg, detail="block"))++ assert _kinds(events) == ["layout", "block", "page"]+ layout, block, page = events+ assert layout["blocks"] == [{"order": 0, "label": "text", "bbox": [0, 0, 40, 30]}]+ assert (layout["image_width"], layout["image_height"]) == (40, 30)+ assert (block["order"], block["label"], block["status"]) == (0, "text", "ok")+ assert block["content"] == "Recognized page."+ assert block["bbox"] == page["page"]["ocr"]["blocks"][0]["bbox"]+ assert {event["image_id"] for event in events} == {"input"}+ assert {event["index"] for event in events} == {0}++[email protected]("overlap", [True, False])+def test_token_detail_passes_on_the_text_while_it_is_decoded(typing, monkeypatch, overlap):+ root, _, _ = typing+ cfg = _parse_config(monkeypatch, root, ["input.png"],+ "--set", f"pipeline.overlap_layout={str(overlap).lower()}")+ events = list(minicpmvocr.stream_pages(cfg, detail="token"))++ assert _kinds(events) == ["layout", "delta", "delta", "delta", "block", "page"]+ deltas = [event for event in events if event["event"] == "delta"]+ assert [event["text"] for event in deltas] == list(TypingEngine.pieces)+ assert all(event["order"] == 0 and "restart" not in event for event in deltas)+ assert "".join(event["text"] for event in deltas) == events[-2]["content"] == events[-1]["markdown"]+++def test_page_detail_never_asks_the_engine_to_stream(quickstart, monkeypatch):+ # FakeEngine.recognize takes no on_delta: being handed one would fail the block.+ root, _, _ = quickstart+ cfg = _parse_config(monkeypatch, root, ["input.png"])+ for detail in ("page", "block"):+ events = list(minicpmvocr.stream_pages(cfg, detail=detail))+ assert events[-1]["status"] == "ok"+++def test_unknown_detail_is_rejected(quickstart, monkeypatch):+ root, _, _ = quickstart+ cfg = _parse_config(monkeypatch, root, ["input.png"])+ with pytest.raises(ValueError, match="stream detail"):+ list(minicpmvocr.stream_pages(cfg, detail="word"))+++def test_input_order_puts_finer_events_in_reading_order():+ def page(index):+ return {"event": "page", "index": index, "pages_done": 0}++ def layout(index, orders):+ return {"event": "layout", "index": index, "blocks": [{"order": order} for order in orders]}++ def delta(index, order, text):+ return {"event": "delta", "index": index, "order": order, "text": text}++ def block(index, order):+ return {"event": "block", "index": index, "order": order}++ delivered = []+ ordered = InputOrder(delivered.append)++ def tags():+ seen = [(e["event"], e["index"], e.get("order"), e.get("text")) for e in delivered]+ delivered.clear()+ return seen++ # Page 1 is done before page 0 has said anything: all of it waits.+ for event in (layout(1, [0]), delta(1, 0, "x"), block(1, 0), page(1)):+ ordered(event)+ assert tags() == []++ # Page 0: its layout passes at once; block 1 is ahead of block 0 and waits.+ ordered(layout(0, [0, 1]))+ ordered(delta(0, 1, "late"))+ ordered(block(0, 1))+ assert tags() == [("layout", 0, None, None)]++ # Block 0 is the one whose turn it is: its text passes as it comes.+ ordered(delta(0, 0, "a"))+ assert tags() == [("delta", 0, 0, "a")]+ ordered(delta(0, 0, "b"))+ assert tags() == [("delta", 0, 0, "b")]++ # Finishing block 0 releases block 1, already complete.+ ordered(block(0, 0))+ assert tags() == [("block", 0, 0, None), ("delta", 0, 1, "late"), ("block", 0, 1, None)]++ # The page closes page 0 and lets all of page 1 through, in order.+ ordered(page(0))+ assert tags() == [("page", 0, None, None), ("layout", 1, None, None), ("delta", 1, 0, "x"),+ ("block", 1, 0, None), ("page", 1, None, None)]+++def test_input_order_does_not_lose_a_block_that_never_reported_finishing():+ delivered = []+ ordered = InputOrder(delivered.append)+ ordered({"event": "layout", "index": 0, "blocks": [{"order": 0}, {"order": 1}]})+ ordered({"event": "delta", "index": 0, "order": 1, "text": "kept"})+ ordered({"event": "page", "index": 0, "pages_done": 0})+ assert [(e["event"], e.get("text")) for e in delivered] == [+ ("layout", None), ("delta", "kept"), ("page", None)]+++def test_ordered_token_stream_reads_like_the_document(typing, monkeypatch):+ root, _, _ = typing+ _images(root, ["second.png", "third.png"])+ cfg = _parse_config(monkeypatch, root, ["input.png", "second.png", "third.png"])+ events = list(minicpmvocr.stream_pages(cfg, ordered=True, detail="token"))++ per_page = ["layout", "delta", "delta", "delta", "block", "page"]+ assert _kinds(events) == per_page * 3+ assert [event["index"] for event in events] == [0] * 6 + [1] * 6 + [2] * 6+ assert [event["pages_done"] for event in events if event["event"] == "page"] == [1, 2, 3]+++def test_cli_stream_detail_writes_the_finer_lines(typing, monkeypatch, capsys):+ _set_argv(monkeypatch, [+ "minicpmvocr", "parse", "input.png", "--stream-ordered", "--stream-detail", "token",+ "--device", "cpu"])+ assert cli.main() == 0+ lines = _lines(capsys.readouterr().out)+ assert _kinds(lines) == ["layout", "delta", "delta", "delta", "block", "page", "done"]+ assert "".join(line["text"] for line in lines if line["event"] == "delta") == "Recognized page."+++def test_cli_stream_detail_needs_stream(quickstart, monkeypatch, capsys):+ _set_argv(monkeypatch, [+ "minicpmvocr", "parse", "input.png", "--stream-detail", "block", "--device", "cpu"])+ with pytest.raises(SystemExit):+ cli.main()+ assert "--stream-detail needs --stream" in capsys.readouterr().err