Skip to content

Fast, accurate OCR with correctness assessment.

sdk: align layout input and Markdown assembly with PaddleOCR-VL 1.6

caowanxia9f883730b4c5
diff --git a/sdk/minicpmvocr/config.py b/sdk/minicpmvocr/config.py
index 32bc8bf..b6f7d76 100644
--- a/sdk/minicpmvocr/config.py
+++ b/sdk/minicpmvocr/config.py
@@ -12,6 +12,7 @@ import yaml
from .backends import normalize_backend_name, validate_engine_config
from .layouts import normalize_layout_provider, resolve_layout_provider_class
+from .postprocess.markdown import DEFAULT_MARKDOWN, validate_markdown
LOGGER = logging.getLogger(__name__)
@@ -146,6 +147,7 @@ DEFAULT_CONFIG: Dict[str, Any] = {
"override_mode": "legacy",
"prompt_map": "",
},
+ "markdown": deepcopy(DEFAULT_MARKDOWN),
"decode": {
"temperature": 0.01,
"top_p": 0.001,
@@ -462,6 +464,7 @@ def _validate_config(cfg: Dict[str, Any], raw: Dict[str, Any] | None = None) ->
raise ValueError("pipeline.page_workers must be >= 1")
+ validate_markdown(cfg["markdown"])
_validate_tts_sampling(cfg, cfg if raw is None else raw)
@@ -473,7 +476,11 @@ def load_config(config_path: str, overrides: Dict[str, Any] | None = None) -> Di
if overrides:
raw = _deep_merge(raw, overrides)
+ # Markdown templates are not expanded: "${content}$" is an inline formula, not an environment variable.
+ markdown = raw.pop("markdown", None)
raw = _expand_env(_expand_builtins(raw, builtin_vars(path)))
+ if markdown is not None:
+ raw["markdown"] = markdown
ignored_engine_keys = sorted(k for k in LEGACY_LAUNCH_KEYS if k in (raw.get("engine") or {}))
cfg = _deep_merge(DEFAULT_CONFIG, raw)
base_dir = path.parent
diff --git a/sdk/minicpmvocr/configs/minicpmvocr.yaml b/sdk/minicpmvocr/configs/minicpmvocr.yaml
index 9699c58..2db4728 100644
--- a/sdk/minicpmvocr/configs/minicpmvocr.yaml
+++ b/sdk/minicpmvocr/configs/minicpmvocr.yaml
@@ -123,6 +123,22 @@ prompt:
override_mode: legacy
prompt_map: ''
+# Markdown assembly (defaults: postprocess/markdown.py DEFAULT_MARKDOWN).
+markdown:
+ ignore_labels: [number, footnote, header, header_image, footer, footer_image, aside_text]
+ title_style: numbered # numbered: heading depth from section numbering (PaddleOCR-VL); template: title_format
+ first_line_headings: true # a leading "Abstract" / "References" line becomes a heading
+ show_formula_number: false # true folds the formula number into the formula as \tag*{}
+ table_figures: inline # inline: figures inside tables go into their cell; separate: own image blocks
+ image_render: reference # reference: link the saved crop; placeholder: emit image_format
+ image_show_ocr_content: null # null shows text recognized in an image block; false hides it
+ 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]()'
+ chart_format: '{content}'
+ seal_format: '{content}'
+
decode:
temperature: 0.01
diff --git a/sdk/minicpmvocr/layouts/ppdoclayout3_paddlex.py b/sdk/minicpmvocr/layouts/ppdoclayout3_paddlex.py
index ec5905a..9a5b9d5 100644
--- a/sdk/minicpmvocr/layouts/ppdoclayout3_paddlex.py
+++ b/sdk/minicpmvocr/layouts/ppdoclayout3_paddlex.py
@@ -89,11 +89,13 @@ class PPDocLayoutV3PaddleXDetector(BaseLayoutDetector):
return [self._detect_one(image) for image in images]
def _detect_one(self, image) -> List[Dict]:
-
-
+ # PaddleX reads ndarray input as BGR and converts it to RGB for the model, so
+ # hand it BGR like PaddleOCR-VL's cv2 reader does; an RGB array would reach the
+ # model with red and blue swapped.
+ bgr = np.ascontiguousarray(np.asarray(image.convert("RGB"))[:, :, ::-1])
results = list(
self._model.predict(
- np.asarray(image.convert("RGB")),
+ bgr,
batch_size=1,
layout_shape_mode=LAYOUT_SHAPE_MODE,
filter_overlap_boxes=False,
diff --git a/sdk/minicpmvocr/layouts/ppdoclayout3_torch.py b/sdk/minicpmvocr/layouts/ppdoclayout3_torch.py
index 3a48b88..4a319f8 100644
--- a/sdk/minicpmvocr/layouts/ppdoclayout3_torch.py
+++ b/sdk/minicpmvocr/layouts/ppdoclayout3_torch.py
@@ -699,8 +699,8 @@ class PPDocLayoutV3TorchDetector(BaseLayoutDetector):
img_rgb = np.asarray(img)
h0, w0 = img_rgb.shape[:2]
sizes.append((w0, h0))
- img_bgr = self._cv2.cvtColor(img_rgb, self._cv2.COLOR_RGB2BGR)
- img_resized = self._cv2.resize(img_bgr, (800, 800), interpolation=self._cv2.INTER_CUBIC)
+ # The model takes RGB, as PaddleX's ReadImage(format="RGB") and the HF image processor feed it.
+ img_resized = self._cv2.resize(img_rgb, (800, 800), interpolation=self._cv2.INTER_CUBIC)
sp = list(self._cv2.split(img_resized))
for c in range(3):
sp[c] = sp[c].astype(np.float32) * (1.0 / 255.0)
@@ -744,9 +744,8 @@ class PPDocLayoutV3TorchDetector(BaseLayoutDetector):
img_rgb = np.asarray(img)
h0, w0 = img_rgb.shape[:2]
-
- img_bgr = self._cv2.cvtColor(img_rgb, self._cv2.COLOR_RGB2BGR)
- img_resized = self._cv2.resize(img_bgr, (800, 800), interpolation=self._cv2.INTER_CUBIC)
+ # The model takes RGB, as PaddleX's ReadImage(format="RGB") and the HF image processor feed it.
+ img_resized = self._cv2.resize(img_rgb, (800, 800), interpolation=self._cv2.INTER_CUBIC)
sp = list(self._cv2.split(img_resized))
for c in range(3):
sp[c] = sp[c].astype(np.float32) * (1.0 / 255.0)
diff --git a/sdk/minicpmvocr/pipeline/_blocks.py b/sdk/minicpmvocr/pipeline/_blocks.py
index af71d53..693ba0c 100644
--- a/sdk/minicpmvocr/pipeline/_blocks.py
+++ b/sdk/minicpmvocr/pipeline/_blocks.py
@@ -8,6 +8,7 @@ from typing import Dict, List, Optional
from PIL import Image
from ._response import RESPONSE_DIRNAME, page_response, public_block_status
+from ._table_figures import untokenize_table_figures
from ._text import _normalize_and_dedupe_blocks
from ._tts import _execute_block_adaptive, _execute_block_tts
from ..backends import PNG_COMPRESS_LEVEL
@@ -17,6 +18,7 @@ from ..postprocess.markdown import (
has_mixed_inline_formula_content,
image_render_mode,
postprocess_content,
+ table_figures_inline,
)
from ..prompts import get_element_cfg
from .._utils import classify_engine_text, ensure_dir, write_json
@@ -449,7 +451,8 @@ def _attach_output_images(run_dir: Path, image_id: str, blocks: List[Dict], prom
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"):
+ # A recognized chart/seal renders as text, unless a table references it as a figure.
+ if label in ("chart", "seal") and block.get("content") and not block.get("in_table"):
continue
crop_filename = block.get("crop_filename") or ""
crop_array = (crop_arrays or {}).get(crop_filename)
@@ -555,7 +558,17 @@ def _finalize_page(
post_t0 = time.time()
final_blocks = _normalize_and_dedupe_blocks(result_blocks)
+ layout_by_order = {b.get("order"): b for b in blocks}
+ for block in final_blocks:
+ for key in ("figure_tokens", "in_table"):
+ if key in layout_by_order.get(block.get("order"), {}):
+ block[key] = layout_by_order[block.get("order")][key]
_attach_output_images(run_dir, image_id, final_blocks, prompt_map, crop_arrays)
+ blocks_by_order = {b.get("order"): b for b in final_blocks}
+ inline = table_figures_inline(prompt_map.get("markdown_assembly", {}))
+ for block in final_blocks:
+ if block.get("figure_tokens") and block.get("content"):
+ block["content"] = untokenize_table_figures(block["content"], block["figure_tokens"], blocks_by_order, inline)
markdown = assemble_markdown(final_blocks, prompt_map)
post_process_sec = time.time() - post_t0
diff --git a/sdk/minicpmvocr/pipeline/_layout_record.py b/sdk/minicpmvocr/pipeline/_layout_record.py
index fa9c1ad..3ea64e2 100644
--- a/sdk/minicpmvocr/pipeline/_layout_record.py
+++ b/sdk/minicpmvocr/pipeline/_layout_record.py
@@ -7,6 +7,7 @@ from typing import Dict, List
from PIL import Image
from ._inputs import _open_page_image
+from ._table_figures import tokenize_page_tables
from ..backends import PNG_COMPRESS_LEVEL
from .._utils import ensure_dir, write_json
@@ -61,10 +62,13 @@ def _build_layout_from_blocks(
)
+ painted_tables, table_tokens, in_table = tokenize_page_tables(blocks, detections, image.width, image.height)
+
for order, block in enumerate(blocks):
crop_image = block.get("image")
if crop_image is None:
continue
+ crop_image = painted_tables.get(order, crop_image)
label = block["label"]
x1, y1, x2, y2 = (int(v) for v in block["bbox"])
crop_filename = f"{order:03d}_{label}.png"
@@ -79,8 +83,14 @@ def _build_layout_from_blocks(
regions = [[x1, y1, x2, y2]] + folded_by_leader.get(order, [])
+ extra = {}
+ if order in table_tokens:
+ extra["figure_tokens"] = table_tokens[order]
+ if order in in_table:
+ extra["in_table"] = True
layout_blocks.append(
{
+ **extra,
"block_id": order,
"label": label,
"bbox": [x1, y1, x2, y2],
diff --git a/sdk/minicpmvocr/pipeline/_table_figures.py b/sdk/minicpmvocr/pipeline/_table_figures.py
new file mode 100644
index 0000000..74c9fd4
--- /dev/null
+++ b/sdk/minicpmvocr/pipeline/_table_figures.py
@@ -0,0 +1,180 @@
+"""Figures inside tables, ported from PaddleX paddleocr_vl/uilts.py (Apache-2.0).
+
+PaddleOCR-VL paints every figure that lies wholly inside a table with a ``[F<n>]``
+token before the table crop goes to the VLM, drops those figures from the page
+flow, and swaps each token in the recognized table back for the figure's image.
+"""
+from __future__ import annotations
+
+import math
+import random
+import re
+from typing import Dict, List, Sequence, Tuple
+
+import numpy as np
+
+from ..postprocess.markdown import markdown_url
+
+# PaddleX gather_imgs: BLOCK_LABEL_MAP["image_labels"].
+TABLE_FIGURE_LABELS = ("image", "figure", "seal")
+TOKEN_RE = re.compile(r"\[F(\d+)\]")
+MIN_TOKEN_SIDE = 25
+
+
+def _gen_random_map(num: int) -> List[int]:
+ exclude_digits = {"0", "1", "9"}
+ seq = []
+ i = 0
+ while len(seq) < num:
+ if not (set(str(i)) & exclude_digits):
+ seq.append(i)
+ i += 1
+ return seq
+
+
+def _paint_token(image: np.ndarray, box: Sequence[float], token_str: str) -> np.ndarray:
+ 'White out `box` and write `token_str` centered in it, in place.'
+ import cv2
+
+ def optimal_font_scale(text, font_face, square_size, fill_ratio=0.9):
+ left, right = 0.2, 10
+ scale = left
+ while right - left > 1e-2:
+ mid = (left + right) / 2
+ (w, h), _ = cv2.getTextSize(text, font_face, mid, thickness=1)
+ if w < square_size * fill_ratio and h < square_size * fill_ratio:
+ scale = mid
+ left = mid
+ else:
+ right = mid
+ return scale, w, h
+
+ x1, y1, x2, y2 = [int(v) for v in box]
+ box_w, box_h = x2 - x1, y2 - y1
+ cv2.rectangle(image, (x1, y1), (x2, y2), color=(255, 255, 255), thickness=-1)
+ font = cv2.FONT_HERSHEY_SIMPLEX
+ font_scale, text_w, text_h = optimal_font_scale(token_str, font, min(box_w, box_h))
+ thickness = max(1, math.floor(font_scale * 4))
+ cv2.putText(
+ image,
+ token_str,
+ (x1 + (box_w - text_w) // 2, y1 + (box_h + text_h) // 2),
+ font,
+ font_scale,
+ (0, 0, 0),
+ thickness,
+ lineType=cv2.LINE_AA,
+ )
+ return image
+
+
+def gather_figures(detections: Sequence[Dict], width: int, height: int) -> List[Dict]:
+ 'Figure candidates from the raw (unfiltered) detections, clamped like PaddleX gather_imgs.'
+ figures = []
+ for detection in detections:
+ label = detection["label"]
+ if label not in TABLE_FIGURE_LABELS:
+ continue
+ raw = [float(v) for v in detection["bbox"]]
+ x1, y1, x2, y2 = (int(v) for v in raw)
+ x1, x2 = max(0, min(x1, width)), max(0, min(x2, width))
+ y1, y2 = max(0, min(y1, height)), max(0, min(y2, height))
+ if x2 <= x1 or y2 <= y1:
+ continue
+ figures.append({"label": label, "raw_bbox": raw, "coordinate": (x1, y1, x2, y2)})
+ return figures
+
+
+def tokenize_table_figures(
+ table_image: np.ndarray, table_box: Sequence[float], figures: Sequence[Dict]
+) -> Tuple[np.ndarray, Dict[str, int], List[int]]:
+ """Paint the figures inside `table_box` with tokens.
+
+ Returns the painted copy of the table crop, ``{token: figure index}`` and the
+ indices of every contained figure (also the ones too small to carry a token).
+ """
+ random.seed(1024)
+ random_map = _gen_random_map(len(figures))
+ random.shuffle(random_map)
+ tx1, ty1, tx2, ty2 = table_box
+ painted = table_image.copy()
+ token_map: Dict[str, int] = {}
+ contained: List[int] = []
+ for index, figure in enumerate(figures):
+ fx1, fy1, fx2, fy2 = figure["coordinate"]
+ if not (fx1 >= tx1 and fy1 >= ty1 and fx2 <= tx2 and fy2 <= ty2):
+ continue
+ contained.append(index)
+ if min(fx2 - fx1, fy2 - fy1) < MIN_TOKEN_SIDE:
+ continue
+ token = "[F%d]" % random_map[index]
+ _paint_token(painted, [fx1 - tx1, fy1 - ty1, fx2 - tx1, fy2 - ty1], token)
+ token_map[token] = index
+ return painted, token_map, contained
+
+
+def tokenize_page_tables(blocks: Sequence[Dict], detections: Sequence[Dict], width: int, height: int):
+ """Tokenize every table crop of one page.
+
+ `blocks` are the provider's cropped blocks (their list index is the block
+ order); `detections` the raw boxes they were built from. Returns
+ ``({table order: painted crop}, {table order: {token: figure block order}},
+ {orders of figure blocks that live inside a table})``.
+ """
+ figures = gather_figures(detections, width, height)
+ if not figures:
+ return {}, {}, set()
+
+ def rounded(bbox):
+ return [int(round(float(v))) for v in bbox]
+
+ # A figure maps to the block cropped from the same detection, as PaddleX keys both by label + box.
+ order_by_box = {
+ (block["label"], tuple(rounded(block["bbox"]))): order
+ for order, block in enumerate(blocks)
+ if block.get("image") is not None and block["label"] in TABLE_FIGURE_LABELS
+ }
+ figure_orders = [order_by_box.get((f["label"], tuple(rounded(f["raw_bbox"])))) for f in figures]
+ raw_table_boxes = {
+ tuple(rounded(d["bbox"])): [float(v) for v in d["bbox"]] for d in detections if d["label"] == "table"
+ }
+
+ painted_by_order: Dict[int, np.ndarray] = {}
+ tokens_by_order: Dict[int, Dict[str, int | None]] = {}
+ in_table: set = set()
+ for order, block in enumerate(blocks):
+ if block["label"] != "table" or block.get("image") is None:
+ continue
+ table_box = raw_table_boxes.get(tuple(rounded(block["bbox"])), [float(v) for v in block["bbox"]])
+ painted, token_map, contained = tokenize_table_figures(block["image"], table_box, figures)
+ if not contained:
+ continue
+ painted_by_order[order] = painted
+ tokens_by_order[order] = {token: figure_orders[index] for token, index in token_map.items()}
+ in_table.update(figure_orders[index] for index in contained if figure_orders[index] is not None)
+ return painted_by_order, tokens_by_order, in_table
+
+
+def untokenize_table_figures(
+ content: str, figure_tokens: Dict[str, int | None], blocks_by_order: Dict[int, Dict], inline: bool = True
+) -> str:
+ """Resolve the figure tokens in a recognized table; unknown tokens stay as text.
+
+ ``inline`` puts the figure's image (and recognized text) in the cell, as
+ PaddleOCR-VL does; otherwise the cell is left empty and the figure keeps its
+ own place in the page.
+ """
+
+ def repl(match: re.Match) -> str:
+ order = figure_tokens.get(match.group(0))
+ block = blocks_by_order.get(order) if order is not None else None
+ if block is None:
+ return match.group(0)
+ if not inline:
+ return ""
+ info = '<img src="%s" alt="Image" />' % markdown_url((block.get("image_path") or "").replace("-\n", "").replace("\n", " "))
+ if block.get("content"):
+ info += "\n\n" + block["content"] + "\n\n"
+ return info
+
+ return TOKEN_RE.sub(repl, content)
diff --git a/sdk/minicpmvocr/pipeline/_text.py b/sdk/minicpmvocr/pipeline/_text.py
index 3f6f189..c90aa93 100644
--- a/sdk/minicpmvocr/pipeline/_text.py
+++ b/sdk/minicpmvocr/pipeline/_text.py
@@ -4,49 +4,21 @@ import re
from typing import Dict, List
from ..constants import OTSL_LABELS
-from ..postprocess.markdown import TEXT_BLOCK_LABELS, split_text_block
+from ..postprocess.markdown import TEXT_BLOCK_LABELS, VERBATIM_LABELS, split_text_block
INLINE_LATEX_RE = re.compile(r"\\\((.+?)\\\)")
DISPLAY_BRACKET_SEP_RE = re.compile(re.escape(r"\]") + r"\s*" + re.escape(r"\["))
-_CLOSING_TOKENS_RE = re.compile(r"\\end\{[^}]*\}|\\\]|\$\$|</(?:table|tr|td|th)>")
-
-
-def _truncate_repetitive_suffix(text: str) -> str:
-
- words = list(re.finditer(r"\S+", text))
- if len(words) < 18:
- return text
-
- normalized = [match.group(0).lower() for match in words]
- earliest_cut = len(text)
- max_window = min(64, len(words) // 3)
- for window in range(6, max_window + 1):
- limit = len(words) - (window * 3) + 1
- for start in range(limit):
- first = normalized[start : start + window]
- if (
- first == normalized[start + window : start + (window * 2)]
- and first == normalized[start + (window * 2) : start + (window * 3)]
- ):
- earliest_cut = min(earliest_cut, words[start].start())
- break
-
- if earliest_cut < len(text):
- truncated = text[:earliest_cut].rstrip()
-
-
- tail = text[earliest_cut:]
- closing = _CLOSING_TOKENS_RE.findall(tail)
- if closing:
- truncated = truncated + " " + " ".join(closing)
- return truncated
- return text
def _normalize_crop_text(text: str, label: str) -> str:
if text is None:
return ""
- out = _truncate_repetitive_suffix(text.strip())
+ if label in VERBATIM_LABELS:
+ # Code / terminal output: keep indentation and line structure, as PaddleOCR-VL does.
+ return INLINE_LATEX_RE.sub(lambda m: f"${m.group(1).strip()}$", text.strip("\n"))
+ # Repetition loops are cut once, in postprocess_content (PaddleOCR-VL's truncate_repetitive_content).
+ # No word-level cut here: it took legitimately repeated matrix rows and table cells for a loop.
+ out = text.strip()
if label != "display_formula":
out = INLINE_LATEX_RE.sub(lambda m: f"${m.group(1).strip()}$", out)
else:
diff --git a/sdk/minicpmvocr/postprocess/markdown.py b/sdk/minicpmvocr/postprocess/markdown.py
index 2223920..aaad3c2 100644
--- a/sdk/minicpmvocr/postprocess/markdown.py
+++ b/sdk/minicpmvocr/postprocess/markdown.py
@@ -17,13 +17,15 @@ TEXT_BLOCK_LABELS = {
"reference_content",
"vertical_text",
"vision_footnote",
- "algorithm",
"header",
"footer",
"footnote",
"aside_text",
}
+# Blocks kept line for line (code, terminal output): never re-flowed or whitespace-collapsed.
+VERBATIM_LABELS = {"algorithm"}
+
def _strip_spacing_tokens(content: str) -> str:
content = re.sub(
@@ -224,7 +226,8 @@ def truncate_repetitive_content(content: str, min_count: int = 50) -> str:
def postprocess_content(content: str, output_format: str, label: str = "") -> str:
if content is None:
return ""
- content = truncate_repetitive_content(content.strip(), min_count=5000 if label == "table" else 50)
+ content = content.strip("\n") if label in VERBATIM_LABELS else content.strip()
+ content = truncate_repetitive_content(content, min_count=5000 if label == "table" else 50)
if output_format == "latex":
if label == "display_formula":
@@ -262,17 +265,120 @@ def postprocess_content(content: str, output_format: str, label: str = "") -> st
IMAGE_RENDER_MODES = ("reference", "placeholder")
+# Title / section-heading / formula-number formatting ported from PaddleX
+# common/result/converter/markdown_format_funcs.py (Apache-2.0), as PaddleOCR-VL renders Markdown.
+_TITLE_NUMBERING = (
+ r"(?:" + r"[1-9][0-9]*(?:\.[1-9][0-9]*)*[\.、]?|" + r"[\(\(](?:[1-9][0-9]*|["
+ r"一二三四五六七八九十百千万亿零壹贰叁肆伍陆柒捌玖拾]+)[\)\)]|" + r"["
+ r"一二三四五六七八九十百千万亿零壹贰叁肆伍陆柒捌玖拾]+"
+ r"[、\.]?|" + r"(?:I|II|III|IV|V|VI|VII|VIII|IX|X)(?:\.|\s)" + r")"
+)
+TITLE_RE = re.compile(r"^\s*(" + _TITLE_NUMBERING + r")(\s*)(.*)$")
+
+# label -> (first-line templates, heading format, splitter), as PaddleOCR-VL's abstract/reference handlers.
+FIRST_LINE_HEADINGS = {
+ "abstract": (("摘要", "abstract"), "## {line}\n", " "),
+ "reference": (("参考文献", "references"), "## {line}", "\n"),
+}
+
+
+def _collapse_soft_newlines(text: str) -> str:
+ return text.replace("-\n", "").replace("\n", " ")
+
+
+def format_numbered_title(content: str) -> str:
+ 'Paragraph title whose depth follows its numbering: "2" -> ##, "2.1" -> ###, unnumbered -> ##.'
+ title = content
+ match = TITLE_RE.match(title)
+ if match:
+ title = match.group(1).strip() + " " + match.group(3).lstrip()
+ title = title.rstrip(".")
+ level = title.count(".") + 1 if "." in title else 1
+ return _collapse_soft_newlines("#%s %s" % ("#" * level, title))
+
+
+def format_first_line(content: str, label: str) -> str:
+ 'Turn the first non-empty line into a heading when it is just "Abstract" / "References" (or 摘要 / 参考文献).'
+ templates, heading, splitter = FIRST_LINE_HEADINGS[label]
+ lines = content.split(splitter)
+ for index, line in enumerate(lines):
+ if line.strip() == "":
+ continue
+ if line.lower() in templates:
+ lines[index] = heading.format(line=line)
+ break
+ return splitter.join(lines)
+
+
+def merge_formula_and_number(formula: str, number: str) -> str:
+ return "%s \\tag*{%s}" % (formula.replace("$$", ""), number)
+
+
+TABLE_FIGURE_MODES = ("separate", "inline")
+
+
+def table_figures_inline(assembly: dict) -> bool:
+ 'markdown.table_figures: "inline" puts a figure found inside a table into its cell (PaddleOCR-VL); "separate" leaves the cell empty and keeps the figure as its own block.'
+ mode = str(assembly.get("table_figures") or "inline").strip().lower()
+ if mode not in TABLE_FIGURE_MODES:
+ raise ValueError(
+ "markdown.table_figures must be one of %s, got %r"
+ % (", ".join(TABLE_FIGURE_MODES), assembly.get("table_figures"))
+ )
+ return mode == "inline"
+
+
+def markdown_url(path: str) -> str:
+ 'Image paths carry page names, which may hold spaces, parentheses or "%"; percent-encode those for the link target.'
+ return path.replace("%", "%25").replace(" ", "%20").replace("(", "%28").replace(")", "%29")
+
+
def image_render_mode(assembly: dict) -> str:
- 'markdown_assembly.image_render: "reference" links the saved crop, "placeholder" emits image_format.'
+ 'markdown.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"
+ "markdown.image_render must be one of %s, got %r"
% (", ".join(IMAGE_RENDER_MODES), assembly.get("image_render"))
)
return mode
+# Defaults of the config `markdown:` section, i.e. the prompt map's markdown_assembly.
+DEFAULT_MARKDOWN = {
+ "ignore_labels": ["number", "footnote", "header", "header_image", "footer", "footer_image", "aside_text"],
+ "title_format": {"doc_title": "# {content}", "paragraph_title": "## {content}", "figure_title": "*{content}*"},
+ # PaddleOCR-VL Markdown: "numbered" derives the paragraph-title depth from its numbering
+ # ("template" uses title_format); first_line_headings turns a leading "Abstract" / "References"
+ # line into a heading; formula numbers are dropped unless show_formula_number folds them in as \tag*{}.
+ "title_style": "numbered",
+ "first_line_headings": True,
+ "show_formula_number": False,
+ # Figures painted as [F<n>] tokens inside a table: "inline" puts the <img> in the cell (PaddleOCR-VL);
+ # "separate" empties the cell and keeps the figure as its own image (OmniDocBench leaves such cells empty).
+ "table_figures": "inline",
+ "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}",
+}
+TITLE_STYLES = ("numbered", "template")
+
+
+def validate_markdown(assembly: dict) -> None:
+ 'Reject unknown modes up front instead of on the first page.'
+ image_render_mode(assembly)
+ table_figures_inline(assembly)
+ style = str(assembly.get("title_style") or "template").strip().lower()
+ if style not in TITLE_STYLES:
+ raise ValueError("markdown.title_style must be one of %s, got %r" % (", ".join(TITLE_STYLES), assembly.get("title_style")))
+ if not isinstance(assembly.get("ignore_labels", []), (list, tuple, set)):
+ raise ValueError("markdown.ignore_labels must be a list of label names, got %r" % (assembly.get("ignore_labels"),))
+
+
def assemble_markdown(blocks: list, prompt_cfg: dict) -> str:
assembly = prompt_cfg.get("markdown_assembly", {})
ignore_labels = set(assembly.get("ignore_labels", []))
@@ -285,12 +391,18 @@ def assemble_markdown(blocks: list, prompt_cfg: dict) -> str:
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
+ # "numbered": PaddleOCR-VL titles (paragraph depth from numbering, newlines folded); "template": title_format.
+ numbered_titles = str(assembly.get("title_style") or "template").strip().lower() == "numbered"
+ first_line_headings = bool(assembly.get("first_line_headings", False))
+ # PaddleOCR-VL drops formula numbers unless asked to fold them into the formula as \tag*{}.
+ show_formula_number = bool(assembly.get("show_formula_number", False))
+ figures_inline = table_figures_inline(assembly)
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
+ part = "![image](%s)" % markdown_url(image_path)
elif "{content}" in image_fmt:
return image_fmt.replace("{content}", content)
else:
@@ -300,20 +412,32 @@ def assemble_markdown(blocks: list, prompt_cfg: dict) -> str:
return part
parts = []
- for block in sorted(blocks, key=lambda x: x.get("order", 0)):
+ ordered = sorted(blocks, key=lambda x: x.get("order", 0))
+ for index, block in enumerate(ordered):
label = block.get("label", "")
content = block.get("content", "")
- if label in ignore_labels:
+ if label in ignore_labels or (figures_inline and block.get("in_table")):
+ continue
+ if label == "formula_number":
continue
if not content and label not in ("image", "header_image", "footer_image", "chart", "seal"):
continue
- if label in title_fmt:
+ if numbered_titles and label == "doc_title":
+ parts.append(_collapse_soft_newlines("# " + content))
+ elif numbered_titles and label == "paragraph_title":
+ parts.append(format_numbered_title(content))
+ elif label in title_fmt:
parts.append(title_fmt[label].format(content=content))
elif label in formula_fmt:
if label == "inline_formula" and block.get("inline_formula_mixed", False):
parts.append(content)
else:
+ next_block = ordered[index + 1] if index + 1 < len(ordered) else {}
+ if show_formula_number and label == "display_formula" and next_block.get("label") == "formula_number":
+ content = merge_formula_and_number(content, (next_block.get("content") or "").replace("$", "").strip())
parts.append(formula_fmt[label].format(content=content))
+ elif first_line_headings and label in FIRST_LINE_HEADINGS:
+ parts.append(format_first_line(content, label))
elif label == "table":
parts.append(table_fmt.format(content=content))
elif label in ("image", "header_image", "footer_image"):
diff --git a/sdk/minicpmvocr/postprocess/otsl/types.py b/sdk/minicpmvocr/postprocess/otsl/types.py
index 33f9f95..23f7ac9 100644
--- a/sdk/minicpmvocr/postprocess/otsl/types.py
+++ b/sdk/minicpmvocr/postprocess/otsl/types.py
@@ -3,11 +3,16 @@
from __future__ import annotations
import html
+import re
from typing import Any, Dict, List
from pydantic import BaseModel, computed_field, model_validator
+# Inline formatting the VLM writes inside cells; everything else in a cell is escaped, as PaddleX does.
+CELL_TAGS_RE = re.compile(r"&lt;(/?(?:br|sup|sub|b|i|u|s|em|strong|del|ul|ol|li))\s*(/?)&gt;", re.IGNORECASE)
+
+
class TableCell(BaseModel):
'A single cell in a table, with optional row/col span.'
@@ -92,7 +97,7 @@ def export_to_html(table_data: TableData) -> str:
cell: TableCell = grid[i][j]
if cell.start_row_offset_idx != i or cell.start_col_offset_idx != j:
continue
- content = html.escape(cell.text.strip())
+ content = CELL_TAGS_RE.sub(r"<\1\2>", html.escape(cell.text.strip()))
celltag = "th" if cell.column_header else "td"
opening = celltag
if cell.row_span > 1:
diff --git a/sdk/minicpmvocr/prompts.py b/sdk/minicpmvocr/prompts.py
index d9fc820..f6981ff 100644
--- a/sdk/minicpmvocr/prompts.py
+++ b/sdk/minicpmvocr/prompts.py
@@ -1,11 +1,17 @@
from __future__ import annotations
+import copy
import json
+import logging
from pathlib import Path
from typing import Dict
import yaml
+from .postprocess.markdown import DEFAULT_MARKDOWN, validate_markdown
+
+LOGGER = logging.getLogger(__name__)
+
DEFAULT_PROMPT_MAP = {
"default": {
"prompt": "Text Recognition:",
@@ -44,17 +50,8 @@ DEFAULT_PROMPT_MAP = {
},
- "markdown_assembly": {
- "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}",
- },
+ # Markdown assembly is run configuration (config `markdown:`); the copy here serves callers without a config.
+ "markdown_assembly": copy.deepcopy(DEFAULT_MARKDOWN),
}
@@ -71,12 +68,17 @@ def _merge_prompt_map_section(base: Dict, external: Dict) -> None:
def load_prompt_map(cfg: Dict) -> Dict:
- 'The effective prompt map for a run.'
+ 'The effective prompt map for a run; its markdown_assembly comes from the config `markdown:` section.'
prompt_map_path = cfg["prompt"].get("prompt_map", "")
prompt_map = json.loads(json.dumps(DEFAULT_PROMPT_MAP))
+ _merge_prompt_map_section(prompt_map["markdown_assembly"], cfg.get("markdown") or {})
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 {}
+ if isinstance(external.get("markdown_assembly"), dict):
+ # Deprecated: older prompt maps carried the Markdown settings; they still win over the config.
+ LOGGER.warning("prompt map %s sets markdown_assembly; move these settings to the config `markdown:` section",
+ prompt_map_path)
for section in _NESTED_PROMPT_MAP_SECTIONS:
if isinstance(external.get(section), dict):
_merge_prompt_map_section(prompt_map[section], external.pop(section))
@@ -84,8 +86,7 @@ def load_prompt_map(cfg: Dict) -> Dict:
prompt_map = apply_prompt_override_mode(prompt_map, cfg["prompt"].get("override_mode", "legacy"))
from .layouts.base import resolve_skip_vlm_labels
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"])
+ validate_markdown(prompt_map["markdown_assembly"])
return prompt_map
diff --git a/sdk/scripts/eval_omnidocbench_v16_docker.sh b/sdk/scripts/eval_omnidocbench_v16_docker.sh
index 69146f3..a0474bd 100755
--- a/sdk/scripts/eval_omnidocbench_v16_docker.sh
+++ b/sdk/scripts/eval_omnidocbench_v16_docker.sh
@@ -116,6 +116,7 @@ run_sdk() {
--set layout.device=cuda:0 \
--set engine.max_model_len=40960 \
--set pipeline.overlap_layout=true --set pipeline.max_workers=32 \
+ --set markdown.table_figures=separate \
--set logging.progress_log_every=50
' 2>&1 | grep -v "Warning\|warnings.warn\|Connectivity check" | tee "$RUN_ROOT/$tag.log"
local actual; actual="$(find "$RUN_ROOT/$tag/output" -maxdepth 1 -type f -name '*.md' | wc -l)"
diff --git a/sdk/tests/test_paddle_alignment.py b/sdk/tests/test_paddle_alignment.py
new file mode 100644
index 0000000..3c57e63
--- /dev/null
+++ b/sdk/tests/test_paddle_alignment.py
@@ -0,0 +1,271 @@
+"Behaviour ported from PaddleOCR-VL 1.6 (PaddleX 3.7.2): layout input channels, table figures, Markdown assembly."
+import copy
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image
+
+import minicpmvocr
+
+from minicpmvocr.pipeline._layout_record import _build_layout_from_blocks
+from minicpmvocr.pipeline._table_figures import tokenize_page_tables, untokenize_table_figures
+from minicpmvocr.pipeline._text import _normalize_and_dedupe_blocks
+from minicpmvocr.postprocess.markdown import assemble_markdown, format_numbered_title, postprocess_content
+from minicpmvocr.prompts import DEFAULT_PROMPT_MAP
+
+
+def _prompt_map(**assembly):
+ prompt_map = copy.deepcopy(DEFAULT_PROMPT_MAP)
+ prompt_map["markdown_assembly"].update(assembly)
+ return prompt_map
+
+
+def _md(blocks, **assembly):
+ return assemble_markdown(blocks, _prompt_map(**assembly))
+
+
+# ---- layout input channels -------------------------------------------------
+
+
+def test_paddlex_provider_hands_paddlex_bgr():
+ from minicpmvocr.layouts.ppdoclayout3_paddlex import PPDocLayoutV3PaddleXDetector
+
+ seen = []
+
+ class FakeModel:
+ def predict(self, array, **kwargs):
+ seen.append(array)
+ return [{"boxes": []}]
+
+ detector = PPDocLayoutV3PaddleXDetector({"model_dir": "", "device": "cpu"})
+ detector._model = FakeModel()
+ detector.detect([Image.new("RGB", (4, 3), (255, 0, 0))])
+ # PaddleX treats ndarrays as BGR (cv2.imread order) and converts to RGB itself.
+ assert seen[0].shape == (3, 4, 3)
+ assert seen[0][0, 0].tolist() == [0, 0, 255]
+ assert seen[0].flags["C_CONTIGUOUS"]
+
+
+# ---- titles, abstract / references, formula numbers ------------------------
+
+
+ "content, expected",
+ [
+ ("Introduction", "## Introduction"),
+ ("2 Method", "## 2 Method"),
+ ("2.1 Data", "### 2.1 Data"),
+ ("2.1.3 Setup.", "#### 2.1.3 Setup"),
+ # PaddleX keeps the numbering's trailing dot, and counts it as one more level.
+ ("2.1.3. Setup.", "##### 2.1.3. Setup"),
+ ("(一)总体要求", "## (一) 总体要求"),
+ ("Related\nWork", "## Related Work"),
+ ],
+)
+def test_paragraph_title_depth_follows_numbering(content, expected):
+ assert format_numbered_title(content) == expected
+ assert _md([{"order": 0, "label": "paragraph_title", "content": content}]) == expected
+
+
+def test_template_title_style_keeps_title_format():
+ blocks = [{"order": 0, "label": "paragraph_title", "content": "2.1 Data"}]
+ assert _md(blocks, title_style="template") == "## 2.1 Data"
+
+
+def test_doc_title_folds_newlines():
+ assert _md([{"order": 0, "label": "doc_title", "content": "A Long\nTitle"}]) == "# A Long Title"
+
+
+def test_abstract_and_reference_first_line_become_headings():
+ blocks = [
+ {"order": 0, "label": "abstract", "content": "Abstract We study OCR."},
+ {"order": 1, "label": "reference", "content": "References\n[1] A. Author."},
+ ]
+ assert _md(blocks) == "## Abstract\n We study OCR.\n\n## References\n[1] A. Author."
+ # Only an exact first line counts.
+ assert _md([{"order": 0, "label": "abstract", "content": "Abstract: We study OCR."}]) == "Abstract: We study OCR."
+ assert _md(blocks, first_line_headings=False) == "Abstract We study OCR.\n\nReferences\n[1] A. Author."
+
+
+def test_formula_number_dropped_by_default_and_folded_on_request():
+ blocks = [
+ {"order": 0, "label": "display_formula", "content": "E=mc^2"},
+ {"order": 1, "label": "formula_number", "content": "(1)"},
+ {"order": 2, "label": "text", "content": "where"},
+ ]
+ assert _md(blocks) == "$$\nE=mc^2\n$$\n\nwhere"
+ assert _md(blocks, show_formula_number=True) == "$$\nE=mc^2 \\tag*{(1)}\n$$\n\nwhere"
+
+
+# ---- algorithm blocks stay verbatim -----------------------------------------
+
+
+def test_algorithm_keeps_indentation_and_lines():
+ raw = "\ndef f(x):\n if x:\n return x\n return 0\n"
+ content = postprocess_content(raw, "text", label="algorithm")
+ blocks = _normalize_and_dedupe_blocks([{"order": 0, "label": "algorithm", "content": content}])
+ assert _md(blocks) == "def f(x):\n if x:\n return x\n return 0"
+
+
+# ---- figures inside tables ---------------------------------------------------
+
+
+def _block(label, bbox, image):
+ return {"label": label, "class_id": 0, "score": 0.9, "bbox": list(bbox), "image": image,
+ "polygon": [], "skip_vlm": label == "image", "group_id": None}
+
+
+def _det(label, bbox):
+ return {"label": label, "class_id": 0, "score": 0.9, "bbox": [float(v) for v in bbox], "polygon": []}
+
+
+def _table_page():
+ table = np.full((200, 300, 3), 128, dtype=np.uint8)
+ blocks = [
+ _block("table", (100, 100, 400, 300), table),
+ _block("image", (150, 150, 250, 250), np.zeros((100, 100, 3), dtype=np.uint8)),
+ _block("image", (500, 500, 600, 600), np.zeros((100, 100, 3), dtype=np.uint8)),
+ _block("image", (300, 120, 310, 130), np.zeros((10, 10, 3), dtype=np.uint8)),
+ ]
+ detections = [_det(b["label"], b["bbox"]) for b in blocks]
+ return blocks, detections
+
+
+def test_figures_inside_a_table_are_tokenized():
+ blocks, detections = _table_page()
+ painted, tokens, in_table = tokenize_page_tables(blocks, detections, 800, 1000)
+ # The big figure is painted with a token; the tiny one (<25 px) is dropped without one; the outside one stays.
+ assert list(tokens) == [0] and len(tokens[0]) == 1
+ token, figure_order = next(iter(tokens[0].items()))
+ assert figure_order == 1 and token.startswith("[F")
+ assert in_table == {1, 3}
+ region = painted[0][50:150, 50:150]
+ assert region.min() == 0 and region.max() == 255 # white box with black text
+ assert (blocks[0]["image"] == 128).all() # the provider's crop is not modified
+
+
+def test_layout_record_carries_tokens_and_paints_crop(tmp_path):
+ blocks, detections = _table_page()
+ sink = {}
+ layout, _ = _build_layout_from_blocks(
+ image=Image.new("RGB", (800, 1000)), image_id="p", source_path="p.png", source_type="image",
+ page_index=None, detections=detections, blocks=blocks, crops_root=tmp_path, crop_sink=sink,
+ )
+ by_order = {b["order"]: b for b in layout["blocks"]}
+ assert set(by_order[0]["figure_tokens"].values()) == {1}
+ assert by_order[1]["in_table"] and by_order[3]["in_table"] and "in_table" not in by_order[2]
+ assert not (sink["000_table.png"] == 128).all()
+
+
+def _figure_table_blocks():
+ return [
+ {"order": 0, "label": "table", "content": "<table><tr><td>[F23]</td><td>[F99]</td></tr></table>",
+ "figure_tokens": {"[F23]": 1}},
+ {"order": 1, "label": "image", "content": "", "image_path": "imgs/p/001.png", "in_table": True},
+ {"order": 2, "label": "image", "content": "", "image_path": "imgs/p/002.png"},
+ ]
+
+
+def test_inline_table_figures_go_into_the_cell_by_default():
+ blocks = _figure_table_blocks()
+ by_order = {b["order"]: b for b in blocks}
+ blocks[0]["content"] = untokenize_table_figures(blocks[0]["content"], blocks[0]["figure_tokens"], by_order, inline=True)
+ assert blocks[0]["content"] == '<table><tr><td><img src="imgs/p/001.png" alt="Image" /></td><td>[F99]</td></tr></table>'
+ md = _md(blocks)
+ assert md.count("001.png") == 1 and "![image](imgs/p/001.png)" not in md and "![image](imgs/p/002.png)" in md
+
+
+def test_separate_table_figures_leave_the_cell_empty():
+ blocks = _figure_table_blocks()
+ by_order = {b["order"]: b for b in blocks}
+ blocks[0]["content"] = untokenize_table_figures(blocks[0]["content"], blocks[0]["figure_tokens"], by_order, inline=False)
+ # OmniDocBench ground truth leaves a figure's cell empty; the figure keeps its own place in the page.
+ assert blocks[0]["content"] == "<table><tr><td></td><td>[F99]</td></tr></table>"
+ md = _md(blocks, table_figures="separate")
+ assert "<img" not in md and "![image](imgs/p/001.png)" in md and "![image](imgs/p/002.png)" in md
+
+
+def test_unknown_table_figure_mode_is_rejected():
+ with pytest.raises(ValueError):
+ _md(_figure_table_blocks(), table_figures="cell")
+
+
+# ---- repetition truncation -------------------------------------------------
+
+
+def _clean(raw, label, output_format):
+ block = {"order": 0, "label": label, "content": postprocess_content(raw, output_format, label=label)}
+ return _normalize_and_dedupe_blocks([block])[0]["content"]
+
+
+def test_repeated_matrix_rows_are_not_taken_for_a_loop():
+ # OmniDocBench page-b4b6b1d1: six identical rows of a 10x10 block matrix were cut as a "loop" (CDM 0.995 -> 0.722).
+ row = r"\chi_{20}^{5} & \chi_{20}^{5} & & & & & & & 0 & 0 \\ "
+ last = r"\chi_{80}^{8} & -\chi_{80}^{8} & 0 & 0 & 0 & 0 & 0 & 0 & \chi_{180}^{14} & -\chi_{20}^{6}"
+ raw = "\\[\n\\begin{pmatrix} 1 & x \\\\ " + row * 6 + last + " \\end{pmatrix}\n\\]"
+ out = _clean(raw, "display_formula", "latex")
+ assert out.count(r"\chi_{20}^{5} & \chi_{20}^{5}") == 6
+ assert out.endswith(last + r" \end{pmatrix}")
+
+
+def test_repetition_loops_are_still_cut_as_paddleocr_vl_does():
+ out = _clean("Intro sentence. " + "the same phrase " * 40, "text", "text")
+ assert out.startswith("Intro sentence.") and len(out) < 100
+
+
+# ---- rendering -------------------------------------------------------------
+
+
+def test_image_links_with_spaces_and_parentheses_stay_links():
+ block = {"order": 0, "label": "image", "content": "", "image_path": "imgs/Daily Star (2025) a%2Fb/001.png"}
+ assert "![image](imgs/Daily%20Star%20%282025%29%20a%252Fb/001.png)" in _md([block])
+
+
+def test_table_cells_keep_line_breaks_and_inline_formatting():
+ from minicpmvocr.postprocess.otsl import convert_otsl_to_html
+
+ html = convert_otsl_to_html("<fcel>a<br>b<fcel>H<sub>2</sub>O<fcel>x < y & <script><nl>")
+ assert "a<br>b" in html and "H<sub>2</sub>O" in html
+ assert "x &lt; y &amp; &lt;script&gt;" in html
+
+
+# ---- markdown config -------------------------------------------------------
+
+
+def _cfg(tmp_path, **overrides):
+ from minicpmvocr.config import load_config
+
+ model_dir = tmp_path / "layout"
+ model_dir.mkdir(exist_ok=True)
+ (model_dir / "inference.pdiparams").write_bytes(b"")
+ (model_dir / "inference.json").write_text("{}")
+ base = {"input": {"image_dir": str(tmp_path)}, "layout": {"model_dir": str(model_dir)}}
+ for key, value in overrides.items():
+ section, name = key.split("__")
+ base.setdefault(section, {})[name] = value
+ return load_config(str(Path(minicpmvocr.__file__).parent / "configs/minicpmvocr.yaml"), base)
+
+
+def test_markdown_settings_come_from_the_config(tmp_path):
+ from minicpmvocr.prompts import load_prompt_map
+
+ default = load_prompt_map(_cfg(tmp_path))["markdown_assembly"]
+ assert default["table_figures"] == "inline"
+ assert default["formula_format"]["inline_formula"] == "${content}$" # not taken for an environment variable
+ assembly = load_prompt_map(_cfg(tmp_path, markdown__table_figures="separate"))["markdown_assembly"]
+ assert assembly["table_figures"] == "separate" and assembly["title_style"] == "numbered"
+
+
+def test_unknown_markdown_mode_is_rejected_when_the_config_loads(tmp_path):
+ with pytest.raises(ValueError, match="markdown.table_figures"):
+ _cfg(tmp_path, markdown__table_figures="cell")
+
+
+def test_legacy_prompt_map_markdown_assembly_still_applies(tmp_path):
+ from minicpmvocr.prompts import load_prompt_map
+
+ legacy = tmp_path / "prompt_map.yaml"
+ legacy.write_text("markdown_assembly:\n table_figures: separate\n")
+ cfg = _cfg(tmp_path, prompt__prompt_map=str(legacy))
+ assert load_prompt_map(cfg)["markdown_assembly"]["table_figures"] == "separate"
diff --git a/sdk/tests/test_truncate_repetitive_suffix.py b/sdk/tests/test_truncate_repetitive_suffix.py
deleted file mode 100644
index dfc9da1..0000000
--- a/sdk/tests/test_truncate_repetitive_suffix.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from minicpmvocr.pipeline._text import _truncate_repetitive_suffix as f
-
-
-def test_no_truncation_when_no_loop():
- text = r"a = b + c \end{array}"
- assert f(text) == text
-
-
-def test_closing_env_preserved_after_qquad_loop():
- text = r"\frac{1}{2}" + r" \qquad" * 18 + r" \end{array}"
- assert r"\end{array}" in f(text)
-
-
-def test_closing_bracket_preserved_after_loop():
- text = "x = 1" + " abc" * 18 + r" \]"
- assert r"\]" in f(text)
-
-
-def test_display_dollar_preserved_after_loop():
- text = "E = mc^2" + " foo" * 18 + " $$"
- assert "$$" in f(text)
-
-
-def test_html_table_close_preserved_after_loop():
- text = "<table><tr><td>x</td></tr>" + " spam" * 18 + " </table>"
- assert "</table>" in f(text)
-
-
-def test_loop_without_closing_still_truncated():
- text = "hello world " + " abc" * 18
- result = f(text)
- assert len(result) < len(text)
- assert "hello" in result
-
-
-def test_short_text_untouched():
- assert f("short text") == "short text"