Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: enhance text alignment handling and improve image cropping logic

myhlolicb216c09387d
diff --git a/CLAUDE.md b/CLAUDE.md
index 9d1ffbae..9f30be24 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -80,12 +80,9 @@ from mineru.render import RenderMode
MinerU 文档解析的目标是尽可能保留具有跨格式价值的内容和结构,并通过统一 Middle JSON 稳定导出多种格式;目标不是逐输入格式、逐排版细节地 100% 复刻源文件。
-- 优先保留正文、标题、列表层级、表格、图片、公式、链接、注释和脚注等具有语义价值的信息。
-- Middle JSON 是各输入格式的统一语义交集。新增信息应尽可能能被 Markdown 表达,并能稳定导出为 HTML、DOCX 和 Structured Content。
-- Markdown 是主要兼容基线,但不是纯文本上限;Markdown 原生能力不足时,可以复用现有安全 HTML、图片资源和结构化 block。
- 不为单一输入格式增加只用于还原罕见排版、编号样式或物理分页的私有 block、私有字段或 renderer 特判。
- 只有同时满足“常见、语义价值高、可进入统一 Middle JSON、可被多个 renderer 稳定消费”的格式私有信息,才应扩展公共契约。
-- Review 时,源格式细节未被 100% 还原不应自动视为缺陷。只有丢失统一契约支持的有价值内容、破坏结构、产生错误语义时才应报告。
+- Review 时,源格式细节未被 100% 还原不应自动视为缺陷。
- 禁止通过不断增加格式例外来追求源文件视觉级复刻;优先规范化为确定、可静态分析、跨格式一致的表示。
具体投影约束:
diff --git a/mineru/model/flash/office/metafile/models.py b/mineru/model/flash/office/metafile/models.py
index 15ca1d84..5f3985bd 100644
--- a/mineru/model/flash/office/metafile/models.py
+++ b/mineru/model/flash/office/metafile/models.py
@@ -233,6 +233,7 @@ class DrawTextCommand:
opaque: bool
bounds: Rect | None
clip: ClipStack
+ advance_end: Point | None = None
@dataclass(frozen=True, slots=True)
diff --git a/mineru/model/flash/office/metafile/parser.py b/mineru/model/flash/office/metafile/parser.py
index c3bedce0..f8c85a15 100644
--- a/mineru/model/flash/office/metafile/parser.py
+++ b/mineru/model/flash/office/metafile/parser.py
@@ -988,6 +988,7 @@ def _emit_text(
logical_origin = playback.state.current_position if update_current else reference
origin = playback.map_point(logical_origin)
positions: list[Point] = []
+ advance_end: Point | None = None
font = playback.state.font
if advances:
cursor_x, cursor_y = logical_origin
@@ -996,6 +997,7 @@ def _emit_text(
if index < len(advances):
cursor_x += advances[index][0]
cursor_y += advances[index][1]
+ advance_end = playback.map_point((cursor_x, cursor_y))
if update_current:
playback.state.current_position = (cursor_x, cursor_y)
elif update_current:
@@ -1039,6 +1041,7 @@ def _emit_text(
opaque=bool(options & _ETO_OPAQUE) or playback.state.background_mode == 2,
bounds=mapped_bounds,
clip=clip,
+ advance_end=advance_end,
)
)
diff --git a/mineru/model/flash/office/metafile/render.py b/mineru/model/flash/office/metafile/render.py
index a9fcd3e3..e390cce2 100644
--- a/mineru/model/flash/office/metafile/render.py
+++ b/mineru/model/flash/office/metafile/render.py
@@ -461,6 +461,22 @@ def _text_anchor(text_align: int) -> str:
return horizontal + vertical
+def _aligned_text_positions(
+ command: DrawTextCommand,
+ matrix: Matrix,
+ positions: list[Point],
+) -> tuple[list[Point], bool]:
+ """把显式字符位置按整串 CENTER/RIGHT alignment 平移一次。"""
+ if not command.positions or command.advance_end is None:
+ return positions, False
+ factor = 0.5 if command.text_align & _TA_CENTER == _TA_CENTER else 1.0 if command.text_align & _TA_RIGHT else 0.0
+ mapped_origin = matrix.transform_point(command.origin)
+ mapped_end = matrix.transform_point(command.advance_end)
+ offset_x = (mapped_end[0] - mapped_origin[0]) * factor
+ offset_y = (mapped_end[1] - mapped_origin[1]) * factor
+ return [(position[0] - offset_x, position[1] - offset_y) for position in positions], True
+
+
def _draw_rotated_text(
layer: Image.Image,
position: Point,
@@ -470,21 +486,41 @@ def _draw_rotated_text(
fill: tuple[int, int, int, int],
anchor: str,
rotation: float,
+ underline: bool,
+ strikeout: bool,
) -> tuple[int, int]:
"""在指定 anchor 绘制可旋转文字,并返回未旋转文字尺寸。"""
draw = ImageDraw.Draw(layer)
bbox = draw.textbbox((0, 0), text, font=font, anchor=anchor)
width = max(1, bbox[2] - bbox[0])
height = max(1, bbox[3] - bbox[1])
+ line_width = max(1, round(height / 14.0))
+
+ def draw_decorations(target_draw: ImageDraw.ImageDraw, reference: Point) -> None:
+ """围绕同一文字 reference 绘制下划线和删除线。"""
+ left = reference[0] + bbox[0]
+ right = reference[0] + bbox[2]
+ if underline:
+ y = reference[1] + bbox[3] + line_width
+ target_draw.line((left, y, right, y), fill=fill, width=line_width)
+ if strikeout:
+ y = reference[1] + (bbox[1] + bbox[3]) / 2.0
+ target_draw.line((left, y, right, y), fill=fill, width=line_width)
+
if abs(rotation) < 1e-6:
draw.text(position, text, font=font, fill=fill, anchor=anchor)
+ draw_decorations(draw, position)
return width, height
padding = max(4, ceil(max(width, height) * 0.1))
- patch = Image.new("RGBA", (width + padding * 2, height + padding * 2), (0, 0, 0, 0))
+ bottom = bbox[3] + line_width * 2 if underline else bbox[3]
+ radius = ceil(max(hypot(x, y) for x in (bbox[0], bbox[2]) for y in (bbox[1], bottom))) + padding
+ patch = Image.new("RGBA", (radius * 2 + 1, radius * 2 + 1), (0, 0, 0, 0))
patch_draw = ImageDraw.Draw(patch)
- patch_draw.text((padding - bbox[0], padding - bbox[1]), text, font=font, fill=fill)
- rotated = patch.rotate(-rotation, expand=True, resample=Image.Resampling.BICUBIC)
- target = round(position[0] - rotated.width / 2), round(position[1] - rotated.height / 2)
+ reference = float(radius), float(radius)
+ patch_draw.text(reference, text, font=font, fill=fill, anchor=anchor)
+ draw_decorations(patch_draw, reference)
+ rotated = patch.rotate(-rotation, expand=False, resample=Image.Resampling.BICUBIC, center=reference)
+ target = round(position[0] - radius), round(position[1] - radius)
layer.alpha_composite(rotated, target)
return width, height
@@ -506,6 +542,9 @@ def _render_text_command(
if command.positions
else [matrix.transform_point(command.origin)]
)
+ positions, positioned_run = _aligned_text_positions(command, matrix, positions)
+ if positioned_run:
+ anchor = "l" + anchor[1]
texts = tuple(command.text) if command.positions else (command.text,)
if command.opaque:
draw = ImageDraw.Draw(layer)
@@ -522,50 +561,41 @@ def _render_text_command(
)
draw.rectangle(background_bounds, fill=command.background_color.rgba())
if command.positions:
- sizes: list[tuple[int, int]] = []
for position, character in zip(positions, command.text):
- sizes.append(
- _draw_rotated_text(
- layer,
- position,
- character,
- font=font,
- fill=command.color.rgba(),
- anchor=anchor,
- rotation=command.rotation,
- )
- )
- else:
- position = positions[0]
- sizes = [
_draw_rotated_text(
layer,
position,
- command.text,
+ character,
font=font,
fill=command.color.rgba(),
anchor=anchor,
rotation=command.rotation,
+ underline=command.font.underline,
+ strikeout=command.font.strikeout,
)
- ]
- if (command.font.underline or command.font.strikeout) and positions:
- draw = ImageDraw.Draw(layer)
- width = sizes[-1][0] if sizes else font_size
- for position in positions:
- if command.font.underline:
- y = position[1] + max(1, font_size * 0.1)
- draw.line((position[0], y, position[0] + width, y), fill=command.color.rgba(), width=max(1, font_size // 14))
- if command.font.strikeout:
- y = position[1] - font_size * 0.3
- draw.line((position[0], y, position[0] + width, y), fill=command.color.rgba(), width=max(1, font_size // 14))
+ else:
+ position = positions[0]
+ _draw_rotated_text(
+ layer,
+ position,
+ command.text,
+ font=font,
+ fill=command.color.rgba(),
+ anchor=anchor,
+ rotation=command.rotation,
+ underline=command.font.underline,
+ strikeout=command.font.strikeout,
+ )
_apply_clip(layer, command.clip, matrix, budget)
return layer
-def _crop_source(image: Image.Image, source: Rect | None) -> Image.Image:
- """按 GDI source rect 裁剪位图,并兼容负宽高翻转。"""
+def _crop_source(image: Image.Image, source: Rect | None) -> tuple[Image.Image | None, Rect]:
+ """裁剪 GDI source rect,并返回交集在请求矩形中的归一化位置。"""
if source is None:
- return image
+ return image, Rect(0.0, 0.0, 1.0, 1.0)
+ if abs(source.width) <= 1e-9 or abs(source.height) <= 1e-9:
+ return None, Rect(0.0, 0.0, 0.0, 0.0)
flip_x = source.width < 0
flip_y = source.height < 0
normalized = source.normalized()
@@ -574,13 +604,42 @@ def _crop_source(image: Image.Image, source: Rect | None) -> Image.Image:
right = min(image.width, ceil(normalized.right))
bottom = min(image.height, ceil(normalized.bottom))
if right <= left or bottom <= top:
- return image
+ return None, Rect(0.0, 0.0, 0.0, 0.0)
+ horizontal = sorted(((left - source.left) / source.width, (right - source.left) / source.width))
+ vertical = sorted(((top - source.top) / source.height, (bottom - source.top) / source.height))
+ fraction = Rect(
+ max(0.0, horizontal[0]),
+ max(0.0, vertical[0]),
+ min(1.0, horizontal[1]),
+ min(1.0, vertical[1]),
+ )
cropped = image.crop((left, top, right, bottom))
if flip_x:
cropped = cropped.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
if flip_y:
cropped = cropped.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
- return cropped
+ return cropped, fraction
+
+
+def _crop_destination(
+ destination: tuple[Point, Point, Point, Point],
+ fraction: Rect,
+) -> tuple[Point, Point, Point, Point]:
+ """把 source 可见交集的归一化位置映射到目标平行四边形。"""
+ first, second, _third, fourth = destination
+ axis_x = second[0] - first[0], second[1] - first[1]
+ axis_y = fourth[0] - first[0], fourth[1] - first[1]
+
+ def mapped(u: float, v: float) -> Point:
+ """把 source 归一化坐标映射到 destination。"""
+ return first[0] + axis_x[0] * u + axis_y[0] * v, first[1] + axis_x[1] * u + axis_y[1] * v
+
+ return (
+ mapped(fraction.left, fraction.top),
+ mapped(fraction.right, fraction.top),
+ mapped(fraction.right, fraction.bottom),
+ mapped(fraction.left, fraction.bottom),
+ )
def _affine_image_layer(
@@ -626,11 +685,14 @@ def _render_image_command(
budget: FlattenBudget,
) -> Image.Image:
"""解码、裁剪并仿射放置单条位图命令。"""
- image = _crop_source(_decode_dib(command), command.source)
+ image, source_fraction = _crop_source(_decode_dib(command), command.source)
+ if image is None:
+ return Image.new("RGBA", size, (0, 0, 0, 0))
if command.constant_alpha < 255:
alpha = image.getchannel("A").point(lambda value: value * command.constant_alpha // 255)
image.putalpha(alpha)
- layer = _affine_image_layer(image, command.destination, matrix, size, command.stretch_mode)
+ destination = _crop_destination(command.destination, source_fraction)
+ layer = _affine_image_layer(image, destination, matrix, size, command.stretch_mode)
_apply_clip(layer, command.clip, matrix, budget)
return layer
@@ -889,16 +951,20 @@ def _svg_text_elements(command: DrawTextCommand, matrix: Matrix) -> str:
if command.font.strikeout:
decorations.append("line-through")
decoration_attr = f' text-decoration="{" ".join(decorations)}"' if decorations else ""
+ elements: list[str] = []
+ positions = command.positions or (command.origin,)
+ texts = tuple(command.text) if command.positions else (command.text,)
+ mapped_positions_list = [matrix.transform_point(position) for position in positions]
+ mapped_positions_list, positioned_run = _aligned_text_positions(command, matrix, mapped_positions_list)
+ if positioned_run:
+ anchor = "start"
common = (
f'fill="{command.color.svg()}"{_svg_opacity(command.color)} '
f'font-family="{escape(command.font.face_name, quote=True)}" font-size="{_svg_number(font_size)}" '
f'font-weight="{command.font.weight}" font-style="{"italic" if command.font.italic else "normal"}" '
f'text-anchor="{anchor}" dominant-baseline="{baseline}"{decoration_attr}'
)
- elements: list[str] = []
- positions = command.positions or (command.origin,)
- texts = tuple(command.text) if command.positions else (command.text,)
- mapped_positions = tuple(matrix.transform_point(position) for position in positions)
+ mapped_positions = tuple(mapped_positions_list)
for mapped, text in zip(mapped_positions, texts):
transform = ""
if abs(command.rotation) > 1e-6:
@@ -929,13 +995,16 @@ def _svg_text_elements(command: DrawTextCommand, matrix: Matrix) -> str:
def _svg_image_element(command: DrawImageCommand, matrix: Matrix) -> str:
"""把 DIB 转成内嵌 PNG 并以 SVG affine matrix 放置。"""
- image = _crop_source(_decode_dib(command), command.source)
+ image, source_fraction = _crop_source(_decode_dib(command), command.source)
+ if image is None:
+ return ""
if command.constant_alpha < 255:
image.putalpha(image.getchannel("A").point(lambda value: value * command.constant_alpha // 255))
output = BytesIO()
image.save(output, format="PNG")
encoded = base64.b64encode(output.getvalue()).decode("ascii")
- first, second, _third, fourth = (matrix.transform_point(point) for point in command.destination)
+ destination = _crop_destination(command.destination, source_fraction)
+ first, second, _third, fourth = (matrix.transform_point(point) for point in destination)
a = (second[0] - first[0]) / max(image.width, 1)
b = (second[1] - first[1]) / max(image.width, 1)
c = (fourth[0] - first[0]) / max(image.height, 1)
diff --git a/tests/unittest/test_flash_office_metafile.py b/tests/unittest/test_flash_office_metafile.py
index b0cb90a6..4b5289d4 100644
--- a/tests/unittest/test_flash_office_metafile.py
+++ b/tests/unittest/test_flash_office_metafile.py
@@ -10,7 +10,7 @@ from unittest.mock import Mock
import zlib
from zipfile import ZIP_DEFLATED, ZipFile
-from PIL import Image
+from PIL import Image, ImageFont
import pyclipper
import pytest
import pptx
@@ -319,6 +319,52 @@ def test_updatecp_text_without_explicit_spacing_advances_current_position(data:
assert not commands[1].positions
[email protected](("text_align", "expected_x"), [(6, (40.0, 50.0)), (2, (30.0, 40.0))])
+def test_explicit_spacing_applies_center_or_right_alignment_once(
+ text_align: int,
+ expected_x: tuple[float, float],
+) -> None:
+ """验证显式 DX 字符先按整串 alignment 平移,再从左侧 cell origin 绘制。"""
+ document = metafile_parser.parse_metafile(build_emf([emf_set_text_align(text_align), emf_text("AB", 50, 50, dx=10)]))
+ command = next(command for command in document.commands if isinstance(command, DrawTextCommand))
+ positions, positioned_run = metafile_render._aligned_text_positions(command, Matrix(), list(command.positions))
+ svg = metafile_render._svg_text_elements(command, Matrix())
+
+ assert command.advance_end == (70.0, 50.0)
+ assert positioned_run
+ assert tuple(position[0] for position in positions) == expected_x
+ assert all(position[1] == 50.0 for position in positions)
+ assert 'text-anchor="start"' in svg
+
+
+def test_rotated_text_preserves_left_and_right_anchor_without_clipping() -> None:
+ """验证旋转文字围绕 GDI reference 定位,左右 anchor 均保留完整字形。"""
+ font = ImageFont.load_default(size=20)
+ left = Image.new("RGBA", (180, 140), (0, 0, 0, 0))
+ right = Image.new("RGBA", (180, 140), (0, 0, 0, 0))
+
+ for layer, anchor in ((left, "la"), (right, "ra")):
+ metafile_render._draw_rotated_text(
+ layer,
+ (90.0, 70.0),
+ "Anchor",
+ font=font,
+ fill=(0, 0, 0, 255),
+ anchor=anchor,
+ rotation=35.0,
+ underline=True,
+ strikeout=True,
+ )
+
+ left_pixels = sum(value > 0 for value in left.getchannel("A").getdata())
+ right_pixels = sum(value > 0 for value in right.getchannel("A").getdata())
+
+ assert left.getbbox() is not None and right.getbbox() is not None
+ assert right_pixels == pytest.approx(left_pixels, rel=0.05)
+ assert left.getbbox()[2] > 90
+ assert right.getbbox()[0] < 90
+
+
@pytest.mark.parametrize(("sweep_angle", "expected_end_y"), [(90.0, -10.0), (-90.0, 10.0)])
def test_emf_anglearc_uses_sweep_direction_and_updates_current_position(
sweep_angle: float,
@@ -529,6 +575,29 @@ def test_stroke_mask_honors_caps_and_svg_miter_limit() -> None:
assert b'stroke-miterlimit="3.5"' in svg
+def test_bitmap_source_crop_preserves_empty_and_partial_destination_mapping() -> None:
+ """验证完全越界 source 不绘制,部分交集只映射到对应 destination 子区域。"""
+ image = Image.new("RGBA", (2, 2), "red")
+ destination = ((0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0))
+
+ outside, outside_fraction = metafile_render._crop_source(image, Rect(10.0, 10.0, 12.0, 12.0))
+ partial, partial_fraction = metafile_render._crop_source(image, Rect(-1.0, 0.0, 1.0, 2.0))
+ mirrored, mirrored_fraction = metafile_render._crop_source(image, Rect(3.0, 0.0, -1.0, 2.0))
+
+ assert outside is None
+ assert outside_fraction == Rect(0.0, 0.0, 0.0, 0.0)
+ assert partial is not None and partial.size == (1, 2)
+ assert partial_fraction == Rect(0.5, 0.0, 1.0, 1.0)
+ assert mirrored is not None and mirrored.size == (2, 2)
+ assert mirrored_fraction == Rect(0.25, 0.0, 0.75, 1.0)
+ assert metafile_render._crop_destination(destination, partial_fraction) == (
+ (50.0, 0.0),
+ (100.0, 0.0),
+ (100.0, 100.0),
+ (50.0, 100.0),
+ )
+
+
def test_placeable_wmf_renders_vector_content() -> None:
"""验证 placeable WMF 的 checksum、对象表和逻辑尺寸进入 PNG。"""
result = render_metafile(basic_wmf())