Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: implement shared image encoding and update related modules
myhloli5b945a40a610
diff --git a/mineru/backend/analysis/pdf/images.py b/mineru/backend/analysis/pdf/images.pyindex 2892c3c1..c2caa574 100644--- a/mineru/backend/analysis/pdf/images.py+++ b/mineru/backend/analysis/pdf/images.py@@ -17,7 +17,8 @@ from loguru import loggerfrom PIL import Imagefrom ....model.flash.pdf.pdfium import close_pdfium_child, pdfium_guard-from ....model.flash.pdf.raster import image_to_b64str, page_to_image+from ....model.flash._shared.image import image_to_b64str+from ....model.flash.pdf.raster import page_to_imagefrom ....types import BBox, IntBBoxfrom ....utils.geometry import normalize_to_int_bboxfrom ....utils.platform import is_windows_environmentdiff --git a/mineru/model/flash/_shared/__init__.py b/mineru/model/flash/_shared/__init__.pyindex 0f2e49ec..ba024d36 100644--- a/mineru/model/flash/_shared/__init__.py+++ b/mineru/model/flash/_shared/__init__.py@@ -1,4 +1,4 @@# Copyright (c) Opendatalab. All rights reserved.-"""Flash PDF 与 Office 复用的轻量算法。"""+"""Flash 各文档格式复用的轻量叶子能力。"""__all__: list[str] = []diff --git a/mineru/model/flash/_shared/image.py b/mineru/model/flash/_shared/image.pynew file mode 100644index 00000000..341f8b16--- /dev/null+++ b/mineru/model/flash/_shared/image.py@@ -0,0 +1,31 @@+# Copyright (c) Opendatalab. All rights reserved.+"""Flash 各格式复用的轻量图片编码能力。"""++from __future__ import annotations++import base64+from io import BytesIO++from PIL import Image+++def image_to_bytes(+ image: Image.Image,+ image_format: str = "JPEG",+) -> bytes:+ """按指定格式把 Pillow 图片编码为字节。"""+ with BytesIO() as image_buffer:+ image.save(image_buffer, format=image_format)+ return image_buffer.getvalue()+++def image_to_b64str(+ image: Image.Image,+ image_format: str = "JPEG",+) -> str:+ """按指定格式把 Pillow 图片编码为 data URI。"""+ image_bytes = image_to_bytes(image, image_format)+ return f"data:image/{image_format.lower()};base64,{base64.b64encode(image_bytes).decode('utf-8')}"+++__all__ = ["image_to_b64str", "image_to_bytes"]diff --git a/mineru/model/flash/office/doc/bookmarks.py b/mineru/model/flash/office/doc/bookmarks.pyindex cfb77fbf..02da86e1 100644--- a/mineru/model/flash/office/doc/bookmarks.py+++ b/mineru/model/flash/office/doc/bookmarks.py@@ -4,7 +4,8 @@from __future__ import annotations-from .records import DocBudget, bounded_slice, get_u16, parse_plc+from ..legacy.binary import bounded_slice, get_u16+from .records import DocBudget, parse_plcdef _parse_string_table(data: bytes, budget: DocBudget) -> list[str]:@@ -80,4 +81,3 @@ def parse_bookmarks(continueresult.setdefault(start, []).append(name)return result-diff --git a/mineru/model/flash/office/doc/formatting.py b/mineru/model/flash/office/doc/formatting.pyindex aff94b7f..9aa2cf6e 100644--- a/mineru/model/flash/office/doc/formatting.py+++ b/mineru/model/flash/office/doc/formatting.py@@ -9,7 +9,8 @@ from dataclasses import dataclassfrom loguru import logger-from .records import DocBudget, bounded_slice, get_u32+from ..legacy.binary import bounded_slice, get_u32+from .records import DocBudgetfrom .sprm import PapDelta, apply_paragraph_sprms@@ -170,4 +171,3 @@ def parse_formatting_runs(continueparagraphs.extend(_parse_papx_page(page, data_stream, budget))return FormattingRuns(characters, paragraphs)-diff --git a/mineru/model/flash/office/doc/images.py b/mineru/model/flash/office/doc/images.pyindex f898f4fe..39830237 100644--- a/mineru/model/flash/office/doc/images.py+++ b/mineru/model/flash/office/doc/images.py@@ -10,6 +10,7 @@ import hashlibfrom loguru import loggerfrom ..legacy import LegacyOfficeResourceLimitError+from ..legacy.binary import bounded_slice, get_u16, get_u32from ..legacy.limits import MAX_ASSET_TOTAL_BYTESfrom ..legacy.officeart import (OfficeImagePayload,@@ -23,7 +24,7 @@ from ..image_equation import ()from .models import DocImage, DocImagePayload-from .records import DocBudget, bounded_slice, get_u16, get_u32, parse_plc+from .records import DocBudget, parse_plc_PLACEABLE_WMF_MAGIC = b"\xd7\xcd\xc6\x9a"diff --git a/mineru/model/flash/office/doc/lists.py b/mineru/model/flash/office/doc/lists.pyindex 1db1ab97..c612999c 100644--- a/mineru/model/flash/office/doc/lists.py+++ b/mineru/model/flash/office/doc/lists.py@@ -6,8 +6,9 @@ from __future__ import annotationsfrom dataclasses import dataclass, field+from ..legacy.binary import bounded_slice, get_u16, get_u32from .models import DocListInfo-from .records import DocBudget, bounded_slice, get_u16, get_u32+from .records import DocBudgetLEVELS = 9@@ -355,4 +356,3 @@ def parse_list_tables(overrides=tuple(overrides),)return ListTables(definitions)-diff --git a/mineru/model/flash/office/doc/parser.py b/mineru/model/flash/office/doc/parser.pyindex 0c520346..b6f330b1 100644--- a/mineru/model/flash/office/doc/parser.py+++ b/mineru/model/flash/office/doc/parser.py@@ -8,6 +8,7 @@ from dataclasses import dataclass, fieldfrom loguru import loggerfrom ..legacy import LegacyOfficeMalformedError+from ..legacy.binary import bounded_slicefrom .bookmarks import parse_bookmarksfrom .fib import (@@ -51,7 +52,7 @@ from .models import (DocVisualPayload,)from .pieces import Piece, TextStream, codec_for_lid, extract_text, legacy_single_piece, parse_clx-from .records import DocBudget, bounded_slice, parse_plc+from .records import DocBudget, parse_plcfrom .sprm import (PapDelta,apply_character_sprms,diff --git a/mineru/model/flash/office/doc/pieces.py b/mineru/model/flash/office/doc/pieces.pyindex 896377d5..c04090a2 100644--- a/mineru/model/flash/office/doc/pieces.py+++ b/mineru/model/flash/office/doc/pieces.py@@ -9,8 +9,9 @@ from dataclasses import dataclassimport structfrom ..legacy import LegacyOfficeMalformedError+from ..legacy.binary import bounded_slice, get_u16, get_u32-from .records import DocBudget, bounded_slice, get_u16, get_u32+from .records import DocBudget@dataclass(frozen=True, slots=True)@@ -255,4 +256,3 @@ def extract_text(cursor += widthbudget.charge(unit_count)return TextStream(chars=chars, cps=cps, fcs=fcs, piece_indexes=piece_indexes)-diff --git a/mineru/model/flash/office/doc/records.py b/mineru/model/flash/office/doc/records.pyindex 69b5e153..fa226931 100644--- a/mineru/model/flash/office/doc/records.py+++ b/mineru/model/flash/office/doc/records.py@@ -25,38 +25,6 @@ class DocBudget:self.visited += amount-def get_u16(data: bytes, offset: int) -> int | None:- """有界读取小端 u16。"""-- if offset < 0 or offset + 2 > len(data):- return None- return int(struct.unpack_from("<H", data, offset)[0])---def get_i16(data: bytes, offset: int) -> int | None:- """有界读取小端 i16。"""-- if offset < 0 or offset + 2 > len(data):- return None- return int(struct.unpack_from("<h", data, offset)[0])---def get_u32(data: bytes, offset: int) -> int | None:- """有界读取小端 u32。"""-- if offset < 0 or offset + 4 > len(data):- return None- return int(struct.unpack_from("<I", data, offset)[0])---def bounded_slice(data: bytes, offset: int, size: int) -> bytes | None:- """返回无溢出的指定字节范围。"""-- if offset < 0 or size < 0 or offset > len(data) - size:- return None- return data[offset : offset + size]--def parse_plc(data: bytes, *, item_size: int, budget: DocBudget) -> tuple[list[int], list[bytes]]:"""解析由 CP 数组和定长数据项组成的通用 PLC。"""@@ -75,4 +43,3 @@ def parse_plc(data: bytes, *, item_size: int, budget: DocBudget) -> tuple[list[ifor index in range(count)]return cps, items-diff --git a/mineru/model/flash/office/doc/sprm.py b/mineru/model/flash/office/doc/sprm.pyindex 028e0335..27c257c3 100644--- a/mineru/model/flash/office/doc/sprm.py+++ b/mineru/model/flash/office/doc/sprm.py@@ -8,8 +8,9 @@ from dataclasses import dataclass, replaceimport structfrom typing import Callable+from ..legacy.binary import get_i16, get_u16, get_u32from .models import DocCharStyle, DocTableCellFormat, DocTableFormat-from .records import DocBudget, get_i16, get_u16, get_u32+from .records import DocBudgetdef _operand_length(opcode: int, operand: bytes) -> int:@@ -270,4 +271,3 @@ def apply_paragraph_sprms(walk_sprms(grpprl, consume, budget=budget)return delta-diff --git a/mineru/model/flash/office/doc/styles.py b/mineru/model/flash/office/doc/styles.pyindex 7ab135df..5c6d4cea 100644--- a/mineru/model/flash/office/doc/styles.py+++ b/mineru/model/flash/office/doc/styles.py@@ -9,8 +9,9 @@ import refrom loguru import logger+from ..legacy.binary import bounded_slice, get_u16from .models import DocCharStyle-from .records import DocBudget, bounded_slice, get_u16+from .records import DocBudgetfrom .sprm import PapDelta, apply_character_sprms, apply_paragraph_sprmsISTD_NIL = 0x0FFF@@ -214,4 +215,3 @@ def parse_stylesheet(for style_id in raw_styles:resolve(style_id)return Stylesheet(memo)-diff --git a/mineru/model/flash/office/docx/docx_converter.py b/mineru/model/flash/office/docx/docx_converter.pyindex 0e1234e3..9deccc5d 100644--- a/mineru/model/flash/office/docx/docx_converter.py+++ b/mineru/model/flash/office/docx/docx_converter.py@@ -32,7 +32,7 @@ from ..image_equation import (from .....types import RAW_CAPTIONfrom .equationxml import DocxEquationXmlDecoderfrom .package_normalizer import normalize_docx_package-from .tools.math.omml import oMath2Latex+from ..math.omml import oMath2Latexfrom .tools.office_xml import read_strfrom .....types import BlockTypefrom .formatting_types import Formatting, Scriptdiff --git a/mineru/model/flash/office/docx/equationxml.py b/mineru/model/flash/office/docx/equationxml.pyindex afdc9b89..dc67bd84 100644--- a/mineru/model/flash/office/docx/equationxml.py+++ b/mineru/model/flash/office/docx/equationxml.py@@ -9,7 +9,7 @@ import hashlibfrom lxml import etree # type: ignore[reportAttributeAccessIssue]-from .tools.math.omml import oMath2Latex+from ..math.omml import oMath2Latexfrom ..legacy.errors import (LegacyOfficeResourceLimitError,)diff --git a/mineru/model/flash/office/docx/package_normalizer.py b/mineru/model/flash/office/docx/package_normalizer.pyindex 52ed1a63..26c690cb 100644--- a/mineru/model/flash/office/docx/package_normalizer.py+++ b/mineru/model/flash/office/docx/package_normalizer.py@@ -3,11 +3,13 @@ import posixpathimport zlibfrom io import BytesIOfrom typing import Iterator-from zipfile import BadZipFile, ZIP_DEFLATED, ZipFile, ZipInfo+from zipfile import BadZipFile, ZipFile, ZipInfofrom loguru import loggerfrom lxml import etree+from ..opc import relationship_source_base_dir, write_zip_package+PACKAGE_RELATIONSHIPS_NS = ("http://schemas.openxmlformats.org/package/2006/relationships"@@ -60,7 +62,7 @@ def normalize_docx_package(file_bytes: bytes) -> bytes:if not changed:return file_bytes- return _write_package(rewritten_members)+ return write_zip_package(rewritten_members)def _collect_relationship_reachable_members(@@ -253,7 +255,7 @@ def _resolve_internal_relationship_target(if target.startswith("/"):resolved = posixpath.normpath(target.lstrip("/"))else:- base_dir = _relationship_source_base_dir(rels_filename)+ base_dir = relationship_source_base_dir(rels_filename.replace("\\", "/"))if base_dir is None:return Noneresolved = posixpath.normpath(posixpath.join(base_dir, target))@@ -261,31 +263,3 @@ def _resolve_internal_relationship_target(if resolved in {"", "."} or resolved.startswith("../"):return Nonereturn resolved---def _relationship_source_base_dir(rels_filename: str) -> str | None:- """根据 .rels 路径推导源 part 所在目录。"""- rels_filename = rels_filename.replace("\\", "/")- if rels_filename == "_rels/.rels":- return ""-- marker = "/_rels/"- if marker not in rels_filename:- return None-- prefix, rels_basename = rels_filename.rsplit(marker, 1)- if not rels_basename.endswith(".rels"):- return None-- source_part_name = rels_basename[: -len(".rels")]- source_part_path = posixpath.normpath(posixpath.join(prefix, source_part_name))- return posixpath.dirname(source_part_path)---def _write_package(members: list[tuple[ZipInfo, bytes]]) -> bytes:- """把规范化后的成员重新写成 DOCX ZIP 包,并重新计算 CRC。"""- output = BytesIO()- with ZipFile(output, "w", ZIP_DEFLATED) as target:- for info, member_data in members:- target.writestr(info, member_data)- return output.getvalue()diff --git a/mineru/model/flash/office/image.py b/mineru/model/flash/office/image.pyindex c720d652..1ff07611 100644--- a/mineru/model/flash/office/image.py+++ b/mineru/model/flash/office/image.py@@ -11,7 +11,7 @@ from loguru import loggerfrom PIL import Image, ImageDraw, ImageFont, UnidentifiedImageErrorfrom ....utils.platform import is_windows_environment-from ..pdf.raster import image_to_b64str+from .._shared.image import image_to_b64strVECTOR_IMAGE_FORMATS = frozenset({"WMF", "EMF"})VECTOR_IMAGE_EXTENSIONS = frozenset({".wmf", ".emf"})diff --git a/mineru/model/flash/office/legacy/binary.py b/mineru/model/flash/office/legacy/binary.pynew file mode 100644index 00000000..7731dff8--- /dev/null+++ b/mineru/model/flash/office/legacy/binary.py@@ -0,0 +1,44 @@+# Copyright (c) Opendatalab. All rights reserved.+"""旧版 Office 二进制格式复用的有界小端读取能力。"""++from __future__ import annotations++import struct+++def get_u16(data: bytes, offset: int) -> int | None:+ """有界读取小端无符号 16 位整数。"""+ if offset < 0 or offset + 2 > len(data):+ return None+ return int(struct.unpack_from("<H", data, offset)[0])+++def get_i16(data: bytes, offset: int) -> int | None:+ """有界读取小端有符号 16 位整数。"""+ if offset < 0 or offset + 2 > len(data):+ return None+ return int(struct.unpack_from("<h", data, offset)[0])+++def get_u32(data: bytes, offset: int) -> int | None:+ """有界读取小端无符号 32 位整数。"""+ if offset < 0 or offset + 4 > len(data):+ return None+ return int(struct.unpack_from("<I", data, offset)[0])+++def get_f64(data: bytes, offset: int) -> float | None:+ """有界读取小端 IEEE-754 双精度浮点数。"""+ if offset < 0 or offset + 8 > len(data):+ return None+ return float(struct.unpack_from("<d", data, offset)[0])+++def bounded_slice(data: bytes, offset: int, size: int) -> bytes | None:+ """返回不越界且不允许负偏移或负长度的字节范围。"""+ if offset < 0 or size < 0 or offset > len(data) - size:+ return None+ return data[offset : offset + size]+++__all__ = ["bounded_slice", "get_f64", "get_i16", "get_u16", "get_u32"]diff --git a/mineru/model/flash/office/docx/tools/math/__init__.py b/mineru/model/flash/office/math/__init__.pysimilarity index 65%rename from mineru/model/flash/office/docx/tools/math/__init__.pyrename to mineru/model/flash/office/math/__init__.pyindex 818730ae..73641dfa 100644--- a/mineru/model/flash/office/docx/tools/math/__init__.py+++ b/mineru/model/flash/office/math/__init__.py@@ -1,3 +1,4 @@# Copyright (c) Opendatalab. All rights reserved.+"""Office Math 内部转换实现。"""__all__: list[str] = []diff --git a/mineru/model/flash/office/docx/tools/math/latex_dict.py b/mineru/model/flash/office/math/latex_dict.pysimilarity index 100%rename from mineru/model/flash/office/docx/tools/math/latex_dict.pyrename to mineru/model/flash/office/math/latex_dict.pydiff --git a/mineru/model/flash/office/docx/tools/math/omml.py b/mineru/model/flash/office/math/omml.pysimilarity index 100%rename from mineru/model/flash/office/docx/tools/math/omml.pyrename to mineru/model/flash/office/math/omml.pydiff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.pyindex aa3daca0..c86b18d2 100644--- a/mineru/model/flash/office/odf/text.py+++ b/mineru/model/flash/office/odf/text.py@@ -14,7 +14,7 @@ from lxml import etree # type: ignore[reportMissingImports]from .....types import BlockTypefrom ..._shared.mathml import mathml_to_latex-from ...pdf.raster import image_to_b64str+from ..._shared.image import image_to_b64strfrom ..image import create_text_placeholder, serialize_office_imagefrom ..rich_text import OfficeRichTextSegment, build_rich_text_from_segmentsfrom .chart import parse_chart_blockdiff --git a/mineru/model/flash/office/opc.py b/mineru/model/flash/office/opc.pynew file mode 100644index 00000000..f540c05f--- /dev/null+++ b/mineru/model/flash/office/opc.py@@ -0,0 +1,39 @@+# Copyright (c) Opendatalab. All rights reserved.+"""OOXML 格式复用的 Open Packaging Conventions 基础能力。"""++from __future__ import annotations++from collections.abc import Sequence+from io import BytesIO+import posixpath+from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo+++def write_zip_package(members: Sequence[tuple[ZipInfo, bytes]]) -> bytes:+ """把规范化后的成员重新写成 ZIP 包,并由标准库重新计算 CRC。"""+ output = BytesIO()+ with ZipFile(output, "w", ZIP_DEFLATED) as target:+ for info, member_data in members:+ target.writestr(info, member_data)+ return output.getvalue()+++def relationship_source_base_dir(rels_filename: str) -> str | None:+ """从规范 OPC relationship 成员路径推导源 part 所在目录。"""+ if rels_filename == "_rels/.rels":+ return ""++ marker = "/_rels/"+ if marker not in rels_filename:+ return None++ prefix, rels_basename = rels_filename.rsplit(marker, 1)+ if not rels_basename.endswith(".rels"):+ return None++ source_part_name = rels_basename[: -len(".rels")]+ source_part_path = posixpath.normpath(posixpath.join(prefix, source_part_name))+ return posixpath.dirname(source_part_path)+++__all__ = ["relationship_source_base_dir", "write_zip_package"]diff --git a/mineru/model/flash/office/ppt/parser.py b/mineru/model/flash/office/ppt/parser.pyindex a476f73c..3c0e1705 100644--- a/mineru/model/flash/office/ppt/parser.py+++ b/mineru/model/flash/office/ppt/parser.py@@ -19,6 +19,7 @@ from ..legacy import (LegacyOfficeMalformedError,LegacyOfficeResourceLimitError,)+from ..legacy.binary import get_i16, get_u16, get_u32from ..legacy.limits import (MAX_ASSET_TOTAL_BYTES,MAX_ENTRY_BYTES,@@ -54,9 +55,6 @@ from .records import (CONTAINER_VERSION,PptRecord,RecordBudget,- get_i16,- get_u16,- get_u32,iter_descendants,iter_records,record_at,diff --git a/mineru/model/flash/office/ppt/records.py b/mineru/model/flash/office/ppt/records.pyindex 82632e7e..04aa3a1f 100644--- a/mineru/model/flash/office/ppt/records.py+++ b/mineru/model/flash/office/ppt/records.py@@ -46,30 +46,6 @@ class RecordBudget:)-def get_u16(data: bytes, offset: int) -> int | None:- """安全读取小端无符号 16 位整数。"""-- if offset < 0 or offset + 2 > len(data):- return None- return struct.unpack_from("<H", data, offset)[0]---def get_i16(data: bytes, offset: int) -> int | None:- """安全读取小端有符号 16 位整数。"""-- if offset < 0 or offset + 2 > len(data):- return None- return struct.unpack_from("<h", data, offset)[0]---def get_u32(data: bytes, offset: int) -> int | None:- """安全读取小端无符号 32 位整数。"""-- if offset < 0 or offset + 4 > len(data):- return None- return struct.unpack_from("<I", data, offset)[0]--def record_at(data: bytes,offset: int,diff --git a/mineru/model/flash/office/ppt/style_text.py b/mineru/model/flash/office/ppt/style_text.pyindex c3c9a28b..3f185fdd 100644--- a/mineru/model/flash/office/ppt/style_text.py+++ b/mineru/model/flash/office/ppt/style_text.py@@ -6,7 +6,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, field-from .records import get_i16, get_u16, get_u32+from ..legacy.binary import get_i16, get_u16, get_u32@dataclass(frozen=True, slots=True)diff --git a/mineru/model/flash/office/pptx/package_normalizer.py b/mineru/model/flash/office/pptx/package_normalizer.pyindex b5842f6d..3d2dcd5c 100644--- a/mineru/model/flash/office/pptx/package_normalizer.py+++ b/mineru/model/flash/office/pptx/package_normalizer.py@@ -2,11 +2,13 @@import posixpathimport refrom io import BytesIO-from zipfile import BadZipFile, ZIP_DEFLATED, ZipFile, ZipInfo+from zipfile import BadZipFile, ZipFile, ZipInfofrom loguru import loggerfrom lxml import etree+from ..opc import relationship_source_base_dir, write_zip_package+LEGACY_PPT_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"WORDPROCESSINGML_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"@@ -123,7 +125,7 @@ def normalize_pptx_package(file_bytes: bytes) -> bytes:if not changed:return file_bytes- return _write_package(rewritten_members)+ return write_zip_package(rewritten_members)def _read_member_best_effort(source: ZipFile, info: ZipInfo) -> bytes | None:@@ -225,8 +227,9 @@ def _resolve_relationship_target(rels_filename: str, target: str) -> str:def _relationship_source_base_dir(rels_filename: str) -> str:"""根据 .rels 成员路径推导源 part 的基础目录。"""- if rels_filename == "_rels/.rels":- return ""+ shared_base_dir = relationship_source_base_dir(rels_filename)+ if shared_base_dir is not None:+ return shared_base_dirmarker = "/_rels/"if marker not in rels_filename:@@ -330,12 +333,3 @@ def _replace_single_alternate_content(alternate_content: etree._Element) -> boolparent.insert(insert_index, fallback_shape)insert_index += 1return True---def _write_package(members: list[tuple[ZipInfo, bytes]]) -> bytes:- """把规范化后的成员重新写成 PPTX ZIP 包,并重新计算 CRC。"""- output = BytesIO()- with ZipFile(output, "w", ZIP_DEFLATED) as target:- for info, member_data in members:- target.writestr(info, member_data)- return output.getvalue()diff --git a/mineru/model/flash/office/pptx/pptx_converter.py b/mineru/model/flash/office/pptx/pptx_converter.pyindex f3fca782..917325f6 100644--- a/mineru/model/flash/office/pptx/pptx_converter.py+++ b/mineru/model/flash/office/pptx/pptx_converter.py@@ -21,13 +21,13 @@ from ..ooxml_equation import (OoxmlEquationDecoder,is_mathtype_equation_prog_id,)-from ..docx.tools.math.omml import oMath2Latex+from ..math.omml import oMath2Latexfrom ..legacy.stream import read_stream_bytes_from_start, rewind_streamfrom .package_normalizer import normalize_pptx_packagefrom ..._shared.xycut import sort_entriesfrom .....types import BlockTypefrom ..rich_text import OfficeRichTextSegment, build_rich_text_from_segments-from ...pdf.raster import image_to_b64str+from ..._shared.image import image_to_b64strIGNORED_NOTES_PLACEHOLDER_TYPES: Final = {PP_PLACEHOLDER.SLIDE_IMAGE,diff --git a/mineru/model/flash/office/rtf/math.py b/mineru/model/flash/office/rtf/math.pyindex 9d4d0cfa..6fc28aa2 100644--- a/mineru/model/flash/office/rtf/math.py+++ b/mineru/model/flash/office/rtf/math.py@@ -8,7 +8,7 @@ from dataclasses import dataclass, fieldfrom lxml import etree # type: ignore[reportAttributeAccessIssue]from loguru import logger-from ..docx.tools.math.omml import oMath2Latex+from ..math.omml import oMath2Latexfrom .lexer import RtfClose, RtfControlWord, RtfHexByte, RtfLexer, RtfOpen, RtfTextBytes_MATH_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"diff --git a/mineru/model/flash/office/xls/embedded_chart.py b/mineru/model/flash/office/xls/embedded_chart.pyindex f3a82497..032917ce 100644--- a/mineru/model/flash/office/xls/embedded_chart.py+++ b/mineru/model/flash/office/xls/embedded_chart.py@@ -10,6 +10,7 @@ import structfrom loguru import loggerfrom ..legacy import BoundedOleReader+from ..legacy.binary import get_f64, get_u16from ..legacy.errors import (LegacyOfficeMalformedError,LegacyOfficeResourceLimitError,@@ -18,7 +19,7 @@ from ..legacy.limits import MAX_GRID_SLOTSfrom .models import XlsCell, XlsRichText, XlsSheet, XlsWorkbookfrom .number_format import builtin_number_format, format_numberfrom .parser import parse_xls_workbook-from .records import BOF, EOF, get_f64, get_u16, iter_records, record_at+from .records import BOF, EOF, iter_records, record_atfrom .strings import clean_textfrom .xls_converter import render_xls_chart_htmldiff --git a/mineru/model/flash/office/xls/parser.py b/mineru/model/flash/office/xls/parser.pyindex df727e94..2bde9cd2 100644--- a/mineru/model/flash/office/xls/parser.py+++ b/mineru/model/flash/office/xls/parser.py@@ -15,6 +15,7 @@ from ..legacy.errors import (LegacyOfficeEncryptedError,LegacyOfficeMalformedError,)+from ..legacy.binary import get_f64, get_u16, get_u32from ..legacy.officeart import (OfficeArtShape,OfficeImagePayload,@@ -48,9 +49,6 @@ from .records import (RecordBudget,SegmentReader,collect_continues,- get_f64,- get_u16,- get_u32,iter_records,record_at,)diff --git a/mineru/model/flash/office/xls/records.py b/mineru/model/flash/office/xls/records.pyindex 3c784d20..9fa544db 100644--- a/mineru/model/flash/office/xls/records.py+++ b/mineru/model/flash/office/xls/records.py@@ -44,38 +44,6 @@ class RecordBudget:)-def get_u16(data: bytes, offset: int) -> int | None:- """安全读取小端无符号 16 位整数。"""-- if offset < 0 or offset + 2 > len(data):- return None- return int(struct.unpack_from("<H", data, offset)[0])---def get_i16(data: bytes, offset: int) -> int | None:- """安全读取小端有符号 16 位整数。"""-- if offset < 0 or offset + 2 > len(data):- return None- return int(struct.unpack_from("<h", data, offset)[0])---def get_u32(data: bytes, offset: int) -> int | None:- """安全读取小端无符号 32 位整数。"""-- if offset < 0 or offset + 4 > len(data):- return None- return int(struct.unpack_from("<I", data, offset)[0])---def get_f64(data: bytes, offset: int) -> float | None:- """安全读取小端 IEEE-754 双精度数。"""-- if offset < 0 or offset + 8 > len(data):- return None- return float(struct.unpack_from("<d", data, offset)[0])--def record_at(data: bytes,offset: int,diff --git a/mineru/model/flash/office/xlsx/package_normalizer.py b/mineru/model/flash/office/xlsx/package_normalizer.pyindex 40e742bb..4fcb2f94 100644--- a/mineru/model/flash/office/xlsx/package_normalizer.py+++ b/mineru/model/flash/office/xlsx/package_normalizer.py@@ -1,9 +1,11 @@# Copyright (c) Opendatalab. All rights reserved.from io import BytesIOimport re-from zipfile import BadZipFile, ZIP_DEFLATED, ZipFile, ZipInfo+from zipfile import BadZipFile, ZipFile, ZipInfoimport xml.etree.ElementTree as ET+from ..opc import write_zip_package+SPREADSHEETML_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"SHARED_STRINGS_PATH = "xl/sharedStrings.xml"STYLES_PATH = "xl/styles.xml"@@ -54,7 +56,7 @@ def normalize_xlsx_package(file_bytes: bytes) -> bytes:if not changed:return file_bytes- return _write_package(rewritten_members)+ return write_zip_package(rewritten_members)def strip_xlsx_ole_objects_for_openpyxl(file_bytes: bytes) -> bytes:@@ -73,7 +75,7 @@ def strip_xlsx_ole_objects_for_openpyxl(file_bytes: bytes) -> bytes:rewritten_members.append((info, member_data))except BadZipFile as exc:raise ValueError("Invalid XLSX package: file is not a ZIP archive.") from exc- return _write_package(rewritten_members) if changed else file_bytes+ return write_zip_package(rewritten_members) if changed else file_bytesdef _remove_worksheet_ole_objects(xml_bytes: bytes) -> bytes:@@ -309,12 +311,3 @@ def _is_worksheet_xml(member_name: str) -> bool:and member_name.endswith(WORKSHEET_SUFFIX)and not member_name.startswith(f"{WORKSHEET_PREFIX}_rels/"))---def _write_package(members: list[tuple[ZipInfo, bytes]]) -> bytes:- """把规范化后的成员重新写成 XLSX ZIP 包,并重新计算 CRC。"""- output = BytesIO()- with ZipFile(output, "w", ZIP_DEFLATED) as target:- for info, member_data in members:- target.writestr(info, member_data)- return output.getvalue()diff --git a/mineru/model/flash/office/xlsx/xlsx_converter.py b/mineru/model/flash/office/xlsx/xlsx_converter.pyindex 3e144908..c9e61cce 100644--- a/mineru/model/flash/office/xlsx/xlsx_converter.py+++ b/mineru/model/flash/office/xlsx/xlsx_converter.py@@ -28,7 +28,7 @@ from ..image_equation import (from ..ooxml_equation import OoxmlEquationDecoderfrom ..legacy.errors import LegacyOfficeResourceLimitErrorfrom ..legacy.limits import MAX_ENTRY_BYTES-from ..docx.tools.math.omml import oMath2Latex+from ..math.omml import oMath2Latexfrom ..legacy.stream import read_stream_bytes_from_start, rewind_streamfrom .package_normalizer import (normalize_xlsx_package,@@ -42,7 +42,7 @@ from .ooxml_ole import (workbook_sheet_parts,)from .....types import BlockType-from ...pdf.raster import image_to_b64str+from ..._shared.image import image_to_b64strAUTO_GAP_TOLERANCE_CANDIDATES = (0, 1, 2)AUTO_GAP_TOLERANCE_PREFERENCE = {1: 0, 0: 1, 2: 2}diff --git a/mineru/model/flash/pdf/document.py b/mineru/model/flash/pdf/document.pyindex 90ffb4fe..30322109 100644--- a/mineru/model/flash/pdf/document.py+++ b/mineru/model/flash/pdf/document.py@@ -23,9 +23,9 @@ from PIL import Image, ImageOpsfrom ....types import BBox, PageInfofrom ....utils.image import crop_pil_image+from .._shared.image import image_to_bytesfrom .classify import classifyfrom .pdfium import _pdfium_lock-from .raster import image_to_byteslogger = logging.getLogger(__name__)diff --git a/mineru/model/flash/pdf/raster.py b/mineru/model/flash/pdf/raster.pyindex 5c1256a3..96079f8a 100644--- a/mineru/model/flash/pdf/raster.py+++ b/mineru/model/flash/pdf/raster.py@@ -1,7 +1,4 @@# Copyright (c) Opendatalab. All rights reserved.-import base64-from io import BytesIO-from loguru import loggerfrom PIL import Imagefrom pypdfium2 import PdfBitmap, PdfPage@@ -34,20 +31,4 @@ def page_to_image(return image, scale-def image_to_bytes(- image: Image.Image,- # image_format: str = "PNG", # 也可以用 "JPEG"- image_format: str = "JPEG",-) -> bytes:- with BytesIO() as image_buffer:- image.save(image_buffer, format=image_format)- return image_buffer.getvalue()---def image_to_b64str(- image: Image.Image,- # image_format: str = "PNG", # 也可以用 "JPEG"- image_format: str = "JPEG",-) -> str:- image_bytes = image_to_bytes(image, image_format)- return f"data:image/{image_format.lower()};base64,{base64.b64encode(image_bytes).decode('utf-8')}"+__all__ = ["page_to_image"]diff --git a/tests/unittest/test_backend_architecture.py b/tests/unittest/test_backend_architecture.pyindex 797bac31..bd670f41 100644--- a/tests/unittest/test_backend_architecture.py+++ b/tests/unittest/test_backend_architecture.py@@ -52,6 +52,7 @@ _REMOVED_INTERNAL_MODULES = ("mineru.model.model_types","mineru.model.flash.model","mineru.model.flash.native_pdf",+ "mineru.model.flash.office.docx.tools.math","mineru.model.utils","mineru.render.writer","mineru.render._internal.common.inline",@@ -204,6 +205,17 @@ def test_layer_dependencies_are_one_way() -> None:assert not offenders+def test_flash_office_does_not_depend_on_pdf_implementation() -> None:+ """守卫 Office 格式只复用中立能力,不反向依赖 Flash PDF 实现。"""+ offenders = {+ str(path.relative_to(_PROJECT_ROOT)): sorted(+ module for module in _resolved_imports(path) if module.startswith("mineru.model.flash.pdf")+ )+ for path in (_PROJECT_ROOT / "mineru/model/flash/office").rglob("*.py")+ }+ assert not {path: imports for path, imports in offenders.items() if imports}++def test_package_initializers_define_explicit_all() -> None:"""守卫目标目录下每个包入口都显式声明 __all__。"""offenders = [diff --git a/tests/unittest/test_flash_office_models.py b/tests/unittest/test_flash_office_models.pyindex 38def44d..27cbb84c 100644--- a/tests/unittest/test_flash_office_models.py+++ b/tests/unittest/test_flash_office_models.py@@ -15,6 +15,7 @@ import mineru.model.flash.models as flat_model_modulefrom mineru.model.flash import (DocModel,DocxModel,+ EpubModel,OdpModel,OdsModel,OdtModel,@@ -174,6 +175,7 @@ def test_models_are_exported_from_flash_root() -> None:assert flash_models.__all__ == ["PdfModel","CsvModel",+ "EpubModel","RtfModel","DocModel","DocxModel",@@ -189,6 +191,7 @@ def test_models_are_exported_from_flash_root() -> None:assert RtfModel is flat_model_module.RtfModelassert DocModel is flat_model_module.DocModelassert DocxModel is flat_model_module.DocxModel+ assert EpubModel is flat_model_module.EpubModelassert PptxModel is flat_model_module.PptxModelassert PptModel is flat_model_module.PptModelassert XlsModel is flat_model_module.XlsModeldiff --git a/tests/unittest/test_flash_office_package_normalizers.py b/tests/unittest/test_flash_office_package_normalizers.pynew file mode 100644index 00000000..e797a4fa--- /dev/null+++ b/tests/unittest/test_flash_office_package_normalizers.py@@ -0,0 +1,76 @@+from __future__ import annotations++from io import BytesIO+from zipfile import ZIP_DEFLATED, ZipFile+import xml.etree.ElementTree as ET++from lxml import etree++from mineru.model.flash.office.docx.package_normalizer import normalize_docx_package+from mineru.model.flash.office.pptx.package_normalizer import normalize_pptx_package+from mineru.model.flash.office.xlsx.package_normalizer import normalize_xlsx_package+++_PACKAGE_RELATIONSHIPS_NS = "http://schemas.openxmlformats.org/package/2006/relationships"+_SPREADSHEETML_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"+++def _zip_bytes(members: dict[str, bytes]) -> bytes:+ """把合成成员写成确定性的 OOXML 测试包。"""+ output = BytesIO()+ with ZipFile(output, "w", ZIP_DEFLATED) as archive:+ for name, data in members.items():+ archive.writestr(name, data)+ return output.getvalue()+++def test_docx_normalizer_removes_missing_internal_relationship() -> None:+ """验证 DOCX 仍删除指向缺失成员的内部 relationship。"""+ relationships = f"""+ <Relationships xmlns="{_PACKAGE_RELATIONSHIPS_NS}">+ <Relationship Id="rId1" Type="urn:test" Target="word/missing.xml"/>+ </Relationships>+ """.encode()+ source = _zip_bytes(+ {+ "[Content_Types].xml": b"<Types/>",+ "_rels/.rels": relationships,+ }+ )++ normalized = normalize_docx_package(source)++ with ZipFile(BytesIO(normalized)) as archive:+ root = etree.fromstring(archive.read("_rels/.rels"))+ assert list(root) == []+++def test_pptx_normalizer_translates_strict_ooxml_uri() -> None:+ """验证 PPTX 仍把 Strict PresentationML URI 转为 Transitional URI。"""+ strict_uri = b"http://purl.oclc.org/ooxml/presentationml/main"+ transitional_uri = b"http://schemas.openxmlformats.org/presentationml/2006/main"+ source = _zip_bytes({"ppt/presentation.xml": b'<p:presentation xmlns:p="' + strict_uri + b'"/>'})++ normalized = normalize_pptx_package(source)++ with ZipFile(BytesIO(normalized)) as archive:+ presentation = archive.read("ppt/presentation.xml")+ assert strict_uri not in presentation+ assert transitional_uri in presentation+++def test_xlsx_normalizer_fills_empty_style_fill() -> None:+ """验证 XLSX 仍为空 fill 补充 patternFill。"""+ styles = f"""+ <styleSheet xmlns="{_SPREADSHEETML_NS}">+ <fills count="1"><fill/></fills>+ </styleSheet>+ """.encode()+ source = _zip_bytes({"xl/styles.xml": styles})++ normalized = normalize_xlsx_package(source)++ with ZipFile(BytesIO(normalized)) as archive:+ root = ET.fromstring(archive.read("xl/styles.xml"))+ pattern_fill = root.find(f".//{{{_SPREADSHEETML_NS}}}patternFill")+ assert pattern_fill is not Nonediff --git a/tests/unittest/test_flash_shared_helpers.py b/tests/unittest/test_flash_shared_helpers.pynew file mode 100644index 00000000..1fc370bb--- /dev/null+++ b/tests/unittest/test_flash_shared_helpers.py@@ -0,0 +1,98 @@+from __future__ import annotations++import base64+from io import BytesIO+import struct+from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo++from PIL import Image+import pytest++from mineru.model.flash._shared.image import image_to_b64str, image_to_bytes+from mineru.model.flash.office.doc import records as doc_records+from mineru.model.flash.office.legacy.binary import bounded_slice, get_f64, get_i16, get_u16, get_u32+from mineru.model.flash.office.opc import relationship_source_base_dir, write_zip_package+from mineru.model.flash.office.ppt import records as ppt_records+from mineru.model.flash.office.xls import records as xls_records+++ ("mode", "image_format", "expected_format"),+ [+ ("RGB", "JPEG", "JPEG"),+ ("RGBA", "PNG", "PNG"),+ ],+)+def test_shared_image_encoding_preserves_format_and_data_uri(+ mode: str,+ image_format: str,+ expected_format: str,+) -> None:+ """验证共享图片编码同时保留字节格式与 data URI 载荷。"""+ image = Image.new(mode, (2, 3), (12, 34, 56, 78) if mode == "RGBA" else (12, 34, 56))++ image_bytes = image_to_bytes(image, image_format=image_format)+ data_uri = image_to_b64str(image, image_format=image_format)+ prefix, encoded = data_uri.split(",", 1)++ assert prefix == f"data:image/{image_format.lower()};base64"+ assert base64.b64decode(encoded) == image_bytes+ with Image.open(BytesIO(image_bytes)) as decoded:+ assert decoded.format == expected_format+ assert decoded.size == (2, 3)+++def test_legacy_binary_readers_preserve_bounds_and_values() -> None:+ """验证旧版 Office 共用读取器只在完整边界内返回小端数值。"""+ data = struct.pack("<HhId", 0xABCD, -123, 0x1234_5678, 1.25)++ assert get_u16(data, 0) == 0xABCD+ assert get_i16(data, 2) == -123+ assert get_u32(data, 4) == 0x1234_5678+ assert get_f64(data, 8) == 1.25+ assert get_u16(data, -1) is None+ assert get_u32(data, len(data) - 3) is None+ assert get_f64(data, len(data) - 7) is None+ assert bounded_slice(data, 2, 4) == data[2:6]+ assert bounded_slice(data, -1, 1) is None+ assert bounded_slice(data, 0, -1) is None+ assert bounded_slice(data, len(data), 1) is None+++def test_format_record_modules_no_longer_export_duplicate_binary_readers() -> None:+ """验证严格迁移后格式 records 模块不再暴露重复的读取函数。"""+ for module in (doc_records, ppt_records, xls_records):+ for name in ("get_u16", "get_i16", "get_u32", "get_f64", "bounded_slice"):+ assert not hasattr(module, name)+++ ("rels_filename", "expected"),+ [+ ("_rels/.rels", ""),+ ("word/_rels/document.xml.rels", "word"),+ ("ppt/slides/_rels/slide1.xml.rels", "ppt/slides"),+ ("word/document.xml.rels", None),+ ("word/_rels/document.xml", None),+ ],+)+def test_opc_relationship_source_base_dir(rels_filename: str, expected: str | None) -> None:+ """验证 OPC relationship 路径只接受根关系或规范 part 关系。"""+ assert relationship_source_base_dir(rels_filename) == expected+++def test_write_zip_package_preserves_member_data_and_metadata() -> None:+ """验证共享写包器保留成员内容与 ZipInfo 元数据。"""+ info = ZipInfo("word/document.xml", date_time=(2024, 1, 2, 3, 4, 6))+ info.compress_type = ZIP_DEFLATED+ info.external_attr = 0o640 << 16+ payload = b"<document/>"++ package = write_zip_package([(info, payload)])++ with ZipFile(BytesIO(package)) as archive:+ restored = archive.getinfo(info.filename)+ assert archive.read(info.filename) == payload+ assert restored.date_time == info.date_time+ assert restored.compress_type == info.compress_type+ assert restored.external_attr == info.external_attr