Skip to content

Fast, accurate OCR with correctness assessment.

sdk: keep recognized image-block text and link image crops in markdown

huangfw36bf514dd94c
diff --git a/sdk/minicpmvocr/cli.py b/sdk/minicpmvocr/cli.py
index 59062ac..18682a5 100644
--- a/sdk/minicpmvocr/cli.py
+++ b/sdk/minicpmvocr/cli.py
@@ -4,6 +4,7 @@ import argparse
import json
import os
import re
+import shutil
import sys
from contextlib import redirect_stdout
from datetime import datetime
@@ -273,6 +274,33 @@ def _load_parse_config(args: argparse.Namespace) -> dict:
raise
+_IMAGE_LINK_RE = re.compile(r"(!\[[^\]]*\]\()(imgs/[^)\s]+)\)")
+
+
+def _sync_markdown_images(run_dir: Path, markdown: str, output_path: Path) -> None:
+ 'Copy the run images that relative imgs/ links point at next to the written markdown.'
+ if not _IMAGE_LINK_RE.search(markdown):
+ return
+ src_imgs = run_dir / "output" / "imgs"
+ if not src_imgs.is_dir():
+ return
+ if output_path.parent.resolve() == (run_dir / "output").resolve():
+ return
+ # Merge into an existing imgs/ instead of replacing it: it may hold the user's own files.
+ shutil.copytree(src_imgs, output_path.parent / "imgs", dirs_exist_ok=True)
+
+
+def _absolute_image_links(markdown: str, run_dir: Path) -> str:
+ 'Point imgs/ links at the run directory, for markdown that has no directory of its own (stdout).'
+ root = (run_dir / "output").resolve().as_posix()
+
+ def _target(match: re.Match) -> str:
+ path = "%s/%s" % (root, match.group(2))
+ return match.group(1) + ("<%s>" % path if re.search(r"\s", path) else path) + ")"
+
+ return _IMAGE_LINK_RE.sub(_target, markdown)
+
+
def _read_markdown_from_run(
run_dir: Path, merge_pages: bool, page_delimiter: str, cfg: dict | None = None
) -> tuple[str, int]:
@@ -368,11 +396,12 @@ def main() -> int:
)
if args.stdout or not args.output:
- print(markdown)
+ 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(
diff --git a/sdk/minicpmvocr/pipeline/_blocks.py b/sdk/minicpmvocr/pipeline/_blocks.py
index ff5563e..56cfb4f 100644
--- a/sdk/minicpmvocr/pipeline/_blocks.py
+++ b/sdk/minicpmvocr/pipeline/_blocks.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import shutil
import time
from pathlib import Path
from typing import Dict, List, Optional
@@ -8,9 +9,12 @@ from PIL import Image
from ._text import _normalize_and_dedupe_blocks
from ._tts import _execute_block_adaptive, _execute_block_tts
+from ..backends import PNG_COMPRESS_LEVEL
+from ..constants import IMAGE_LABELS
from ..postprocess.markdown import (
assemble_markdown,
has_mixed_inline_formula_content,
+ image_render_mode,
postprocess_content,
)
from ..prompts import get_element_cfg
@@ -422,6 +426,45 @@ def _failed_page_result(image_id: str, page_started: float, layout_stage_sec: fl
}
return {"page_row": row, "page_timing": page_timing, "crop_rows": []}
+
+IMAGE_RENDITION_LABELS = IMAGE_LABELS + ("chart", "seal")
+
+
+def _attach_output_images(run_dir: Path, image_id: str, blocks: List[Dict], prompt_map: Dict,
+ crop_arrays: Optional[Dict] = None) -> None:
+ 'Publish the crops markdown renders as images under output/imgs/ and record their paths.'
+ assembly = prompt_map.get("markdown_assembly", {})
+ if image_render_mode(assembly) != "reference":
+ return
+ ignore_labels = set(assembly.get("ignore_labels", []))
+ crops_dir = run_dir / "runtime" / "intermediate" / "crops" / image_id
+ imgs_dir = run_dir / "output" / "imgs" / image_id
+ for block in blocks:
+ label = block.get("label", "")
+ if label not in IMAGE_RENDITION_LABELS or label in ignore_labels:
+ continue
+ if label in ("chart", "seal") and block.get("content"):
+ continue
+ crop_filename = block.get("crop_filename") or ""
+ crop_array = (crop_arrays or {}).get(crop_filename)
+ crop_path = crops_dir / crop_filename
+ if not crop_filename or (crop_array is None and not crop_path.is_file()):
+ continue
+ try:
+ x1, y1, x2, y2 = (int(round(float(v))) for v in (block.get("bbox") or [])[:4])
+ except (TypeError, ValueError):
+ continue
+ name = "{:03d}_img_in_{}_box_{}_{}_{}_{}.png".format(
+ int(block.get("order", 0)), label, x1, y1, x2, y2
+ )
+ ensure_dir(imgs_dir)
+ if crop_array is not None:
+ Image.fromarray(crop_array).save(imgs_dir / name, compress_level=PNG_COMPRESS_LEVEL)
+ else:
+ shutil.copyfile(crop_path, imgs_dir / name)
+ block["image_path"] = f"imgs/{image_id}/{name}"
+
+
def _finalize_page(
*,
run_dir: Path,
@@ -432,6 +475,7 @@ def _finalize_page(
prompt_map: Dict,
page_started: float,
layout_stage_sec: float,
+ crop_arrays: Optional[Dict] = None,
) -> Dict:
result_blocks = []
crop_rows: List[Dict] = []
@@ -505,6 +549,7 @@ def _finalize_page(
post_t0 = time.time()
final_blocks = _normalize_and_dedupe_blocks(result_blocks)
+ _attach_output_images(run_dir, image_id, final_blocks, prompt_map, crop_arrays)
markdown = assemble_markdown(final_blocks, prompt_map)
post_process_sec = time.time() - post_t0
diff --git a/sdk/minicpmvocr/pipeline/overlapped.py b/sdk/minicpmvocr/pipeline/overlapped.py
index 93aa601..a5c4bde 100644
--- a/sdk/minicpmvocr/pipeline/overlapped.py
+++ b/sdk/minicpmvocr/pipeline/overlapped.py
@@ -404,7 +404,7 @@ def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None)
]
page_states.append({
"image_id": image_id, "layout": layout, "blocks": blocks,
- "crop_dir": crop_dir, "page_started": page_started,
+ "crop_dir": crop_dir, "crops": crops, "page_started": page_started,
"layout_stage_sec": layout_stage_sec,
"outputs": [None] * len(blocks), "remaining": len(blocks),
})
@@ -428,6 +428,7 @@ def pipelined_run(cfg: Dict, resources: Dict | None = None, on_layout_idle=None)
run_dir=run_dir, image_id=state["image_id"], layout=state["layout"],
blocks=state["blocks"], block_outputs=state["outputs"], prompt_map=prompt_map,
page_started=state["page_started"], layout_stage_sec=state["layout_stage_sec"],
+ crop_arrays=state.pop("crops", None),
)
except Exception as e:
result = _failed_page_result(state["image_id"], state["page_started"], state["layout_stage_sec"], str(e))
diff --git a/sdk/minicpmvocr/postprocess/markdown.py b/sdk/minicpmvocr/postprocess/markdown.py
index 6f5fc42..2223920 100644
--- a/sdk/minicpmvocr/postprocess/markdown.py
+++ b/sdk/minicpmvocr/postprocess/markdown.py
@@ -259,6 +259,20 @@ def postprocess_content(content: str, output_format: str, label: str = "") -> st
return content
+IMAGE_RENDER_MODES = ("reference", "placeholder")
+
+
+def image_render_mode(assembly: dict) -> str:
+ 'markdown_assembly.image_render: "reference" links the saved crop, "placeholder" emits image_format.'
+ mode = str(assembly.get("image_render") or "reference").strip().lower()
+ if mode not in IMAGE_RENDER_MODES:
+ raise ValueError(
+ "markdown_assembly.image_render must be one of %s, got %r"
+ % (", ".join(IMAGE_RENDER_MODES), assembly.get("image_render"))
+ )
+ return mode
+
+
def assemble_markdown(blocks: list, prompt_cfg: dict) -> str:
assembly = prompt_cfg.get("markdown_assembly", {})
ignore_labels = set(assembly.get("ignore_labels", []))
@@ -268,6 +282,22 @@ def assemble_markdown(blocks: list, prompt_cfg: dict) -> str:
image_fmt = assembly.get("image_format", "![image]()")
chart_fmt = assembly.get("chart_format", "{content}")
seal_fmt = assembly.get("seal_format", "{content}")
+ image_render = image_render_mode(assembly)
+ # None (default): show whatever text an image block was recognized with; False hides it.
+ show_image_ocr = assembly.get("image_show_ocr_content") is not False
+
+ def render_image_block(block: dict, content: str) -> str:
+ 'PaddleOCR-VL plain style: the image reference, then its recognized text when enabled.'
+ image_path = block.get("image_path") if image_render == "reference" else ""
+ if image_path:
+ part = "![image](%s)" % image_path
+ elif "{content}" in image_fmt:
+ return image_fmt.replace("{content}", content)
+ else:
+ part = image_fmt
+ if show_image_ocr and content:
+ part += "\n\n" + content
+ return part
parts = []
for block in sorted(blocks, key=lambda x: x.get("order", 0)):
@@ -287,11 +317,11 @@ def assemble_markdown(blocks: list, prompt_cfg: dict) -> str:
elif label == "table":
parts.append(table_fmt.format(content=content))
elif label in ("image", "header_image", "footer_image"):
- parts.append(image_fmt)
+ parts.append(render_image_block(block, content))
elif label == "chart":
- parts.append(chart_fmt.format(content=content) if content else image_fmt)
+ parts.append(chart_fmt.format(content=content) if content else render_image_block(block, content))
elif label == "seal":
- parts.append(seal_fmt.format(content=content) if content else image_fmt)
+ parts.append(seal_fmt.format(content=content) if content else render_image_block(block, content))
else:
parts.append(content)
- return "\n\n".join(parts)
+ return "\n\n".join(part for part in parts if part)
diff --git a/sdk/minicpmvocr/prompts.py b/sdk/minicpmvocr/prompts.py
index 8978ec5..d9fc820 100644
--- a/sdk/minicpmvocr/prompts.py
+++ b/sdk/minicpmvocr/prompts.py
@@ -45,17 +45,31 @@ DEFAULT_PROMPT_MAP = {
},
"markdown_assembly": {
- "ignore_labels": ["number", "footnote", "header", "footer", "aside_text"],
+ "ignore_labels": ["number", "footnote", "header", "header_image", "footer", "footer_image", "aside_text"],
"title_format": {"doc_title": "# {content}", "paragraph_title": "## {content}", "figure_title": "*{content}*"},
"formula_format": {"display_formula": "$$\n{content}\n$$", "inline_formula": "${content}$"},
"table_format": "{content}",
"image_format": "![image]()",
+ "image_render": "reference",
+ "image_show_ocr_content": None,
"chart_format": "{content}",
"seal_format": "{content}",
},
}
+_NESTED_PROMPT_MAP_SECTIONS = ("markdown_assembly", "element_prompts")
+
+
+def _merge_prompt_map_section(base: Dict, external: Dict) -> None:
+ 'Merge an external prompt-map section into the default instead of replacing it.'
+ for key, value in external.items():
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
+ base[key].update(value)
+ else:
+ base[key] = value
+
+
def load_prompt_map(cfg: Dict) -> Dict:
'The effective prompt map for a run.'
prompt_map_path = cfg["prompt"].get("prompt_map", "")
@@ -63,10 +77,16 @@ def load_prompt_map(cfg: Dict) -> Dict:
if prompt_map_path and Path(prompt_map_path).is_file():
with Path(prompt_map_path).open("r", encoding="utf-8") as f:
external = yaml.safe_load(f) or {}
+ for section in _NESTED_PROMPT_MAP_SECTIONS:
+ if isinstance(external.get(section), dict):
+ _merge_prompt_map_section(prompt_map[section], external.pop(section))
prompt_map.update(external)
prompt_map = apply_prompt_override_mode(prompt_map, cfg["prompt"].get("override_mode", "legacy"))
from .layouts.base import resolve_skip_vlm_labels
- return apply_skip_vlm_labels(prompt_map, resolve_skip_vlm_labels(cfg.get("layout")))
+ prompt_map = apply_skip_vlm_labels(prompt_map, resolve_skip_vlm_labels(cfg.get("layout")))
+ from .postprocess.markdown import image_render_mode
+ image_render_mode(prompt_map["markdown_assembly"])
+ return prompt_map
def get_element_cfg(prompt_map: Dict, label: str) -> Dict | None:
diff --git a/sdk/tests/test_image_block_render.py b/sdk/tests/test_image_block_render.py
new file mode 100644
index 0000000..f29f382
--- /dev/null
+++ b/sdk/tests/test_image_block_render.py
@@ -0,0 +1,219 @@
+import copy
+import re
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from minicpmvocr.cli import _absolute_image_links, _sync_markdown_images
+from minicpmvocr.pipeline._blocks import _attach_output_images
+from minicpmvocr.postprocess.markdown import assemble_markdown
+from minicpmvocr.prompts import DEFAULT_PROMPT_MAP, get_element_cfg, load_prompt_map
+
+
+IMAGE_PATH = "imgs/page/002_img_in_image_box_95_301_1148_1574.png"
+DRAWING_TEXT = "7号交叉口平面布置图\n1:150"
+
+
+def _prompt_map(**assembly):
+ prompt_map = copy.deepcopy(DEFAULT_PROMPT_MAP)
+ prompt_map["markdown_assembly"].update(assembly)
+ return prompt_map
+
+
+def _image(content=DRAWING_TEXT, image_path=IMAGE_PATH, label="image", order=0):
+ block = {"order": order, "label": label, "content": content}
+ if image_path:
+ block["image_path"] = image_path
+ return block
+
+
+def _load(tmp_path=None, use_ocr_for_image_block=False, external=None):
+ prompt_map_path = ""
+ if external is not None:
+ prompt_map_path = tmp_path / "prompt_map.yaml"
+ prompt_map_path.write_text(external, encoding="utf-8")
+ return load_prompt_map({
+ "prompt": {"prompt_map": str(prompt_map_path), "override_mode": "legacy"},
+ "layout": {"use_ocr_for_image_block": use_ocr_for_image_block},
+ })
+
+
+def test_unrecognized_image_links_the_crop():
+ out = assemble_markdown([_image(content="")], _prompt_map())
+ assert out == "![image](%s)" % IMAGE_PATH
+ # Plain markdown image syntax, so text-only consumers can strip it.
+ assert re.sub(r"!\[.*?\]\(.*?\)", "", out) == ""
+
+
+def test_recognized_image_text_follows_the_reference():
+ out = assemble_markdown([_image()], _prompt_map())
+ assert out == "![image](%s)\n\n%s" % (IMAGE_PATH, DRAWING_TEXT)
+
+
+def test_recognized_image_text_can_be_hidden():
+ out = assemble_markdown([_image()], _prompt_map(image_show_ocr_content=False))
+ assert out == "![image](%s)" % IMAGE_PATH
+
+
[email protected]("assembly, block", [
+ ({"image_render": "placeholder"}, _image()),
+ ({}, _image(image_path=None)),
+])
+def test_placeholder_fallback_keeps_recognized_text(assembly, block):
+ out = assemble_markdown([block], _prompt_map(**assembly))
+ assert out == "![image]()\n\n" + DRAWING_TEXT
+
+
+def test_issue_12_reproduction_keeps_image_text():
+ blocks = [
+ {"order": 0, "label": "image", "content": "main bore right tunnel / reinforcement section / 500 / 250"},
+ {"order": 1, "label": "chart", "content": "<table><tr><td>A</td></tr></table>"},
+ {"order": 2, "label": "seal", "content": "Design Institute"},
+ ]
+ assert assemble_markdown(blocks, copy.deepcopy(DEFAULT_PROMPT_MAP)) == (
+ "![image]()\n\nmain bore right tunnel / reinforcement section / 500 / 250"
+ "\n\n<table><tr><td>A</td></tr></table>\n\nDesign Institute"
+ )
+
+
+def test_image_format_content_template():
+ prompt_map = _prompt_map(image_render="placeholder", image_format="{content}")
+ assert assemble_markdown([_image()], prompt_map) == DRAWING_TEXT
+ text = {"order": 1, "label": "text", "content": "body"}
+ assert assemble_markdown([_image(content=""), text], prompt_map) == "body"
+
+
+def test_header_and_footer_images_are_ignored_by_default():
+ blocks = [
+ _image(label="header_image", order=0),
+ {"order": 1, "label": "text", "content": "body"},
+ _image(label="footer_image", order=2),
+ ]
+ assert assemble_markdown(blocks, _prompt_map()) == "body"
+
+
[email protected]("label", ["chart", "seal"])
+def test_chart_and_seal_render_as_images_only_without_content(label):
+ prompt_map = _prompt_map()
+ assert assemble_markdown([_image(content="<table></table>", label=label)], prompt_map) == "<table></table>"
+ assert assemble_markdown([_image(content="", label=label)], prompt_map) == "![image](%s)" % IMAGE_PATH
+
+
+def test_unknown_image_render_mode_is_rejected(tmp_path):
+ with pytest.raises(ValueError, match="image_render"):
+ assemble_markdown([_image()], _prompt_map(image_render="html"))
+ with pytest.raises(ValueError, match="image_render"):
+ _load(tmp_path, external="markdown_assembly:\n image_render: html\n")
+
+
[email protected]("layout_cfg", [
+ {"use_ocr_for_image_block": True},
+ {"use_ocr_for_image_block": False, "skip_vlm_labels": []},
+])
+def test_every_way_of_recognizing_images_shows_their_text(layout_cfg):
+ prompt_map = load_prompt_map({"prompt": {"prompt_map": "", "override_mode": "legacy"}, "layout": layout_cfg})
+ assert get_element_cfg(prompt_map, "image") is not None
+ assert assemble_markdown([_image()], prompt_map) == "![image](%s)\n\n%s" % (IMAGE_PATH, DRAWING_TEXT)
+
+
+def test_prompt_map_can_hide_recognized_image_text(tmp_path):
+ prompt_map = _load(tmp_path, True, "markdown_assembly:\n image_show_ocr_content: false\n")
+ assert assemble_markdown([_image()], prompt_map) == "![image](%s)" % IMAGE_PATH
+
+
+def test_external_prompt_map_merges_into_the_defaults(tmp_path):
+ prompt_map = _load(tmp_path, external=(
+ "markdown_assembly:\n image_format: '{content}'\n"
+ "element_prompts:\n table:\n max_new_tokens: 16\n"
+ ))
+ assembly = prompt_map["markdown_assembly"]
+ assert assembly["image_format"] == "{content}"
+ assert assembly["title_format"] == DEFAULT_PROMPT_MAP["markdown_assembly"]["title_format"]
+ assert assembly["ignore_labels"] == DEFAULT_PROMPT_MAP["markdown_assembly"]["ignore_labels"]
+ assert prompt_map["element_prompts"]["table"]["max_new_tokens"] == 16
+ assert prompt_map["element_prompts"]["table"]["prompt"] == "Table Recognition:"
+ assert "seal" in prompt_map["element_prompts"]
+
+
+def _crop_blocks():
+ return [
+ {"order": 0, "label": "text", "content": "body", "crop_filename": "000_text.png", "bbox": [0, 0, 4, 2]},
+ {"order": 1, "label": "image", "content": "", "crop_filename": "001_image.png", "bbox": [1, 2, 5, 6]},
+ {"order": 2, "label": "chart", "content": "<table></table>", "crop_filename": "002_chart.png", "bbox": [0, 0, 4, 2]},
+ {"order": 3, "label": "seal", "content": "", "crop_filename": "003_seal.png", "bbox": [0, 0, 4, 2]},
+ {"order": 4, "label": "header_image", "content": "", "crop_filename": "004_header_image.png", "bbox": [0, 0, 4, 2]},
+ ]
+
+
+def _crop_arrays():
+ return {
+ block["crop_filename"]: np.full((2, 4, 3), index, dtype=np.uint8)
+ for index, block in enumerate(_crop_blocks())
+ }
+
+
+def test_rendered_image_crops_are_published_from_memory(tmp_path):
+ blocks = _crop_blocks()
+ _attach_output_images(tmp_path, "page", blocks, _prompt_map(), _crop_arrays())
+ paths = {block["label"]: block.get("image_path") for block in blocks}
+ assert paths == {
+ "text": None,
+ "image": "imgs/page/001_img_in_image_box_1_2_5_6.png",
+ "chart": None,
+ "seal": "imgs/page/003_img_in_seal_box_0_0_4_2.png",
+ "header_image": None,
+ }
+ published = sorted(p.name for p in (tmp_path / "output" / "imgs" / "page").iterdir())
+ assert published == ["001_img_in_image_box_1_2_5_6.png", "003_img_in_seal_box_0_0_4_2.png"]
+ assert np.asarray(Image.open(tmp_path / "output" / paths["image"])).max() == 1
+
+
+def test_rendered_image_crops_are_copied_from_disk(tmp_path):
+ crops_dir = tmp_path / "runtime" / "intermediate" / "crops" / "page"
+ crops_dir.mkdir(parents=True)
+ for name, array in _crop_arrays().items():
+ Image.fromarray(array).save(crops_dir / name)
+ blocks = _crop_blocks()
+ _attach_output_images(tmp_path, "page", blocks, _prompt_map())
+ assert (tmp_path / "output" / blocks[1]["image_path"]).read_bytes() == (crops_dir / "001_image.png").read_bytes()
+
+
+def test_placeholder_mode_publishes_nothing(tmp_path):
+ blocks = _crop_blocks()
+ _attach_output_images(tmp_path, "page", blocks, _prompt_map(image_render="placeholder"), _crop_arrays())
+ assert not any("image_path" in block for block in blocks)
+ assert not (tmp_path / "output").exists()
+
+
+def test_sync_merges_into_an_existing_imgs_dir(tmp_path):
+ run_dir = tmp_path / "run"
+ (run_dir / "output" / "imgs" / "page").mkdir(parents=True)
+ (run_dir / "output" / "imgs" / "page" / "001.png").write_bytes(b"crop")
+ user_imgs = tmp_path / "out" / "imgs"
+ user_imgs.mkdir(parents=True)
+ (user_imgs / "photo.jpg").write_bytes(b"user")
+
+ _sync_markdown_images(run_dir, "![image](imgs/page/001.png)", tmp_path / "out" / "doc.md")
+
+ assert (user_imgs / "photo.jpg").read_bytes() == b"user"
+ assert (user_imgs / "page" / "001.png").read_bytes() == b"crop"
+
+
+def test_sync_skips_markdown_without_image_links(tmp_path):
+ run_dir = tmp_path / "run"
+ (run_dir / "output" / "imgs").mkdir(parents=True)
+ _sync_markdown_images(run_dir, "see imgs/ folder\n\n![image]()", tmp_path / "out" / "doc.md")
+ assert not (tmp_path / "out").exists()
+
+
+def test_stdout_links_point_into_the_run(tmp_path):
+ run_dir = tmp_path / "run"
+ root = (run_dir / "output").resolve().as_posix()
+ markdown = "![image](imgs/page/001.png)\n\nsee imgs/notes\n\n![image]()"
+ assert _absolute_image_links(markdown, run_dir) == (
+ "![image](%s/imgs/page/001.png)\n\nsee imgs/notes\n\n![image]()" % root
+ )
+ spaced = tmp_path / "my run"
+ root = (spaced / "output").resolve().as_posix()
+ assert _absolute_image_links("![image](imgs/a.png)", spaced) == "![image](<%s/imgs/a.png>)" % root