Skip to content

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

Add OFD preview functionality with lazy conversion and error handling

myhlolie32be37bf441
diff --git a/mineru/kit/gradio/_vendor/__init__.py b/mineru/kit/gradio/_vendor/__init__.py
new file mode 100644
index 00000000..8e54f5fe
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/__init__.py
@@ -0,0 +1,3 @@
+"""Gradio 专用第三方实现。"""
+
+__all__ = []
diff --git a/mineru/kit/gradio/_vendor/ofd2html/__init__.py b/mineru/kit/gradio/_vendor/ofd2html/__init__.py
new file mode 100644
index 00000000..cb40e4de
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/__init__.py
@@ -0,0 +1,6 @@
+"""ofd2html: OFD -> HTML converter (HTML export only)."""
+
+from .html.exporter import ofd_to_html
+
+__all__ = ["ofd_to_html"]
+__version__ = "0.1.0"
diff --git a/mineru/kit/gradio/_vendor/ofd2html/gv.py b/mineru/kit/gradio/_vendor/ofd2html/gv.py
new file mode 100644
index 00000000..43b19504
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/gv.py
@@ -0,0 +1,9 @@
+"""Global constants shared across modules."""
+
+# OFD XML namespace (GB/T 33190-2016).
+OFD_NS = "http://www.ofdspec.org/2016"
+NSMAP = {"ofd": OFD_NS}
+
+# OFD page coordinates are in millimeters; HTML SVG output uses 1 mm = 1 user unit
+# (we put `viewBox` in mm, then scale via CSS so 1 mm == ~3.78 px at 96 dpi).
+MM_TO_PX = 96.0 / 25.4
diff --git a/mineru/kit/gradio/_vendor/ofd2html/html/__init__.py b/mineru/kit/gradio/_vendor/ofd2html/html/__init__.py
new file mode 100644
index 00000000..5b694f7b
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/html/__init__.py
@@ -0,0 +1,3 @@
+
+
+__all__ = []
diff --git a/mineru/kit/gradio/_vendor/ofd2html/html/exporter.py b/mineru/kit/gradio/_vendor/ofd2html/html/exporter.py
new file mode 100644
index 00000000..34a3fd48
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/html/exporter.py
@@ -0,0 +1,32 @@
+"""High-level entry point: convert OFD bytes into a single HTML string."""
+
+from __future__ import annotations
+
+from ..reader.ofd_reader import OFDReader
+from ..render.page_renderer import render_page_to_svg
+from .template import FOOT, HEAD, PAGE_GAP
+
+
+# 将 OFD 字节转换为完整 HTML 页面。
+def ofd_to_html(ofd_bytes: bytes) -> str:
+ """Convert one OFD file (as bytes) into a complete HTML document.
+
+ Pure function with no I/O side effects -- the FastAPI layer just wraps it.
+ """
+ if not ofd_bytes:
+ raise ValueError("empty OFD payload")
+ parts: list[str] = [HEAD]
+ with OFDReader(ofd_bytes) as reader:
+ first_page = True
+ for doc in reader.documents:
+ for page in doc.pages:
+ if not first_page:
+ parts.append(PAGE_GAP)
+ first_page = False
+ parts.append(
+ '<div style="background:#fff;box-shadow:0 0 5px rgba(0,0,0,0.15);">'
+ )
+ parts.append(render_page_to_svg(reader, doc, page))
+ parts.append("</div>")
+ parts.append(FOOT)
+ return "".join(parts)
diff --git a/mineru/kit/gradio/_vendor/ofd2html/html/template.py b/mineru/kit/gradio/_vendor/ofd2html/html/template.py
new file mode 100644
index 00000000..e5d9cf13
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/html/template.py
@@ -0,0 +1,19 @@
+"""HTML head/footer templates -- mirrors the Java HTMLExporter output."""
+
+HEAD = (
+ "<!DOCTYPE html>\n"
+ '<html lang="zh-CN">\n'
+ "<head>\n"
+ ' <meta charset="UTF-8">\n'
+ ' <meta http-equiv="X-UA-Compatible" content="IE=edge">\n'
+ ' <meta name="viewport" content="width=device-width, initial-scale=1.0">\n'
+ " <title>OFD Preview</title>\n"
+ "</head>\n"
+ '<body style="margin:0;background:#E6E8EB;">\n'
+ ' <div style="display:flex;flex-direction:column;align-items:center;">'
+ '<div style="height:10px;"></div>'
+)
+
+PAGE_GAP = '<div style="height:10px;"></div>'
+
+FOOT = " </div>\n</body>\n</html>"
diff --git a/mineru/kit/gradio/_vendor/ofd2html/pkg/__init__.py b/mineru/kit/gradio/_vendor/ofd2html/pkg/__init__.py
new file mode 100644
index 00000000..5b694f7b
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/pkg/__init__.py
@@ -0,0 +1,3 @@
+
+
+__all__ = []
diff --git a/mineru/kit/gradio/_vendor/ofd2html/pkg/container.py b/mineru/kit/gradio/_vendor/ofd2html/pkg/container.py
new file mode 100644
index 00000000..a869b634
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/pkg/container.py
@@ -0,0 +1,62 @@
+"""Virtual OFD container: in-memory view of an OFD ZIP archive.
+
+Load the ZIP once, expose entries by virtual path (POSIX-style, optionally
+leading ``/``).
+"""
+
+from __future__ import annotations
+
+import io
+import zipfile
+from typing import Iterable
+
+
+class OFDContainer:
+ """In-memory view of an OFD ZIP archive."""
+
+ # 初始化当前转换对象及资源。
+ def __init__(self, ofd_bytes: bytes) -> None:
+ try:
+ self._zip = zipfile.ZipFile(io.BytesIO(ofd_bytes), "r")
+ except zipfile.BadZipFile as exc: # pragma: no cover - explicit boundary
+ raise ValueError(f"not a valid OFD/ZIP file: {exc}") from exc
+ # Normalise paths: drop leading slash, collapse backslashes.
+ self._entries: dict[str, zipfile.ZipInfo] = {
+ self._norm(info.filename): info
+ for info in self._zip.infolist()
+ if not info.is_dir()
+ }
+
+ @staticmethod
+ # 统一压缩包条目路径分隔符。
+ def _norm(path: str) -> str:
+ return path.replace("\\", "/").lstrip("/")
+
+ # 检查压缩包内是否存在指定条目。
+ def has(self, path: str) -> bool:
+ return self._norm(path) in self._entries
+
+ # 按虚拟路径读取压缩包条目。
+ def read(self, path: str) -> bytes:
+ key = self._norm(path)
+ info = self._entries.get(key)
+ if info is None:
+ raise FileNotFoundError(f"OFD entry not found: {path}")
+ return self._zip.read(info)
+
+ # 列出压缩包内全部文件路径。
+ def names(self) -> Iterable[str]:
+ return self._entries.keys()
+
+ # 关闭持有的 OFD 压缩包。
+ def close(self) -> None:
+ self._zip.close()
+
+ # Context manager sugar.
+ # 进入资源管理上下文。
+ def __enter__(self) -> "OFDContainer":
+ return self
+
+ # 退出上下文并释放资源。
+ def __exit__(self, *exc: object) -> None:
+ self.close()
diff --git a/mineru/kit/gradio/_vendor/ofd2html/reader/__init__.py b/mineru/kit/gradio/_vendor/ofd2html/reader/__init__.py
new file mode 100644
index 00000000..5b694f7b
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/reader/__init__.py
@@ -0,0 +1,3 @@
+
+
+__all__ = []
diff --git a/mineru/kit/gradio/_vendor/ofd2html/reader/ofd_reader.py b/mineru/kit/gradio/_vendor/ofd2html/reader/ofd_reader.py
new file mode 100644
index 00000000..849ea1e6
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/reader/ofd_reader.py
@@ -0,0 +1,370 @@
+"""High-level OFD reader: parses OFD.xml + Document.xml + per-page Content.xml.
+
+Designed for the HTML export pipeline only -- enough structure to render the
+page contents to SVG. We keep the parsed forms as light dataclasses since
+rendering is the only consumer here.
+"""
+
+from __future__ import annotations
+
+import posixpath
+from dataclasses import dataclass, field
+from typing import Optional
+
+from lxml import etree
+
+from ..gv import NSMAP
+from ..pkg.container import OFDContainer
+from .resource_locator import ResourceLocator
+
+
+# --------------------------------------------------------------------------- #
+# Light value objects.
+# --------------------------------------------------------------------------- #
+
+
+@dataclass(frozen=True)
+class Box:
+ """OFD ``ST_Box`` value: x, y, w, h in millimetres."""
+
+ x: float
+ y: float
+ w: float
+ h: float
+
+ @classmethod
+ # 将坐标文本转换为矩形。
+ def parse(cls, raw: Optional[str]) -> Optional["Box"]:
+ if not raw:
+ return None
+ parts = raw.replace(",", " ").split()
+ if len(parts) != 4:
+ return None
+ return cls(*(float(p) for p in parts))
+
+
+@dataclass
+class PageRef:
+ """A pointer to one page's Content.xml inside the container."""
+
+ page_id: str
+ base_loc: str # absolute virtual path
+
+
+@dataclass
+class MediaRes:
+ res_id: str
+ media_type: str # "Image" / "Sound" / ...
+ file_path: str # absolute virtual path resolved against res base
+
+
+@dataclass
+class DrawParam:
+ """Subset of OFD ``CT_DrawParam`` needed for HTML rendering.
+
+ OFD allows ``Relative`` to chain a base DrawParam; we keep the raw id
+ here and resolve transitively via :meth:`Document.resolve_draw_param`
+ so callers always see the merged effective values.
+ """
+
+ res_id: str
+ relative: Optional[str] = None
+ line_width: Optional[float] = None
+ fill_color: Optional[str] = None # raw ``Value`` channel string, e.g. "255 0 0"
+ stroke_color: Optional[str] = None
+
+
+@dataclass
+class TemplatePage:
+ """Reusable page-content shared by multiple pages.
+
+ A page references it via ``<ofd:Template TemplateID="..." ZOrder="..."/>``
+ and the renderer composites the template content under or over the page's
+ own content according to ``ZOrder`` (Background / Body / Foreground).
+ """
+
+ template_id: str
+ base_loc: str # absolute virtual path to the template's Content.xml
+ z_order: str = "Background"
+
+
+@dataclass
+class Document:
+ physical_box: Box
+ pages: list[PageRef] = field(default_factory=list)
+ medias: dict[str, MediaRes] = field(default_factory=dict)
+ draw_params: dict[str, DrawParam] = field(default_factory=dict)
+ templates: dict[str, TemplatePage] = field(default_factory=dict)
+
+ # 合并继承的绘制参数。
+ def resolve_draw_param(self, res_id: Optional[str]) -> Optional[DrawParam]:
+ """Return a flattened ``DrawParam`` with ``Relative`` chain merged in.
+
+ The OFD spec lets a DrawParam inherit from a base via ``Relative`` and
+ override individual properties. We walk the chain (base-first), then
+ let the leaf override -- mirroring the reference renderer behaviour.
+ Returns ``None`` for unknown ids so callers can do a single guarded
+ lookup.
+ """
+ if not res_id:
+ return None
+ leaf = self.draw_params.get(res_id)
+ if leaf is None:
+ return None
+ chain: list[DrawParam] = [leaf]
+ seen = {res_id}
+ cur = leaf
+ while cur.relative and cur.relative not in seen:
+ base = self.draw_params.get(cur.relative)
+ if base is None:
+ break
+ seen.add(cur.relative)
+ chain.append(base)
+ cur = base
+ # Walk base-first, then leaf, so leaf overrides win.
+ merged = DrawParam(res_id=res_id)
+ for dp in reversed(chain):
+ if dp.line_width is not None:
+ merged.line_width = dp.line_width
+ if dp.fill_color is not None:
+ merged.fill_color = dp.fill_color
+ if dp.stroke_color is not None:
+ merged.stroke_color = dp.stroke_color
+ return merged
+
+
+# --------------------------------------------------------------------------- #
+# Reader.
+# --------------------------------------------------------------------------- #
+
+
+class OFDReader:
+ """Read an OFD container and expose per-page content trees."""
+
+ # 初始化当前转换对象及资源。
+ def __init__(self, ofd_bytes: bytes) -> None:
+ self._container = OFDContainer(ofd_bytes)
+ self._locator = ResourceLocator(self._container, cwd="/")
+ self._documents: list[Document] = self._load_documents()
+
+ # ----- public API -------------------------------------------------------
+
+ @property
+ # 返回已加载的 OFD 文档列表。
+ def documents(self) -> list[Document]:
+ return self._documents
+
+ # 读取并解析页面 XML。
+ def page_content(self, doc: Document, page: PageRef) -> etree._Element:
+ """Return the parsed ``<ofd:Page>`` root for one page."""
+ del doc # currently unused, but kept for future multi-doc routing
+ xml = self._container.read(page.base_loc.lstrip("/"))
+ return etree.fromstring(xml, parser=_xml_parser())
+
+ # 读取并解析模板页 XML。
+ def template_content(
+ self, doc: Document, template_id: str
+ ) -> Optional[etree._Element]:
+ """Return the parsed root element of the template page identified by
+ ``template_id`` (or ``None`` if unknown / missing)."""
+ del doc
+ tpl = self._documents[0].templates.get(template_id) if self._documents else None
+ # Search across all documents because ``doc`` is currently unused above.
+ for d in self._documents:
+ tpl = d.templates.get(template_id)
+ if tpl is not None:
+ break
+ if tpl is None:
+ return None
+ path = tpl.base_loc.lstrip("/")
+ if not self._container.has(path):
+ return None
+ return etree.fromstring(self._container.read(path), parser=_xml_parser())
+
+ # 读取媒体资源字节。
+ def read_media(self, doc: Document, res_id: str) -> Optional[bytes]:
+ media = doc.medias.get(res_id)
+ if media is None:
+ return None
+ return self._container.read(media.file_path.lstrip("/"))
+
+ # 按资源编号查找媒体信息。
+ def media(self, doc: Document, res_id: str) -> Optional[MediaRes]:
+ return doc.medias.get(res_id)
+
+ # 关闭持有的 OFD 压缩包。
+ def close(self) -> None:
+ self._container.close()
+
+ # 进入资源管理上下文。
+ def __enter__(self) -> "OFDReader":
+ return self
+
+ # 退出上下文并释放资源。
+ def __exit__(self, *exc: object) -> None:
+ self.close()
+
+ # ----- loading ----------------------------------------------------------
+
+ # 从入口 XML 加载文档列表。
+ def _load_documents(self) -> list[Document]:
+ if not self._container.has("OFD.xml"):
+ raise ValueError("invalid OFD: missing OFD.xml")
+ ofd_root = etree.fromstring(self._container.read("OFD.xml"), parser=_xml_parser())
+ documents: list[Document] = []
+ for doc_body in ofd_root.findall("ofd:DocBody", NSMAP):
+ doc_root_el = doc_body.find("ofd:DocRoot", NSMAP)
+ if doc_root_el is None or not doc_root_el.text:
+ continue
+ doc_root_path = self._locator.resolve(doc_root_el.text.strip())
+ documents.append(self._load_document(doc_root_path))
+ if not documents:
+ raise ValueError("invalid OFD: no DocBody/DocRoot found")
+ return documents
+
+ # 加载文档页序、页面尺寸、模板和资源。
+ def _load_document(self, doc_root_path: str) -> Document:
+ doc_xml = self._container.read(doc_root_path)
+ doc_el = etree.fromstring(doc_xml, parser=_xml_parser())
+ doc_dir = posixpath.dirname("/" + doc_root_path)
+
+ # Page area.
+ physical_box = Box.parse(
+ _text(doc_el, ".//ofd:CommonData/ofd:PageArea/ofd:PhysicalBox")
+ ) or Box(0, 0, 210, 297)
+
+ # Pages list.
+ pages: list[PageRef] = []
+ for page_el in doc_el.findall(".//ofd:Pages/ofd:Page", NSMAP):
+ base_loc = page_el.get("BaseLoc") or ""
+ if not base_loc:
+ continue
+ pages.append(
+ PageRef(
+ page_id=page_el.get("ID") or "",
+ base_loc=_join_doc(doc_dir, base_loc),
+ )
+ )
+
+ # Resources (PublicRes + DocumentRes). Each entry can declare
+ # ``BaseLoc`` to relocate sub-files relative to the resource file.
+ medias: dict[str, MediaRes] = {}
+ draw_params: dict[str, DrawParam] = {}
+ for tag in ("ofd:PublicRes", "ofd:DocumentRes"):
+ for res_el in doc_el.findall(f".//ofd:CommonData/{tag}", NSMAP):
+ if not res_el.text:
+ continue
+ res_path = _join_doc(doc_dir, res_el.text.strip())
+ self._collect_resources(res_path, medias, draw_params)
+
+ # Template pages are referenced by individual pages via TemplateID;
+ # their content lives in a separate Content.xml that we resolve once
+ # here so the renderer can simply look it up.
+ templates: dict[str, TemplatePage] = {}
+ for tpl_el in doc_el.findall(
+ ".//ofd:CommonData/ofd:TemplatePage", NSMAP
+ ):
+ tpl_id = tpl_el.get("ID")
+ base_loc = tpl_el.get("BaseLoc") or ""
+ if not tpl_id or not base_loc:
+ continue
+ templates[tpl_id] = TemplatePage(
+ template_id=tpl_id,
+ base_loc=_join_doc(doc_dir, base_loc),
+ z_order=tpl_el.get("ZOrder") or "Background",
+ )
+
+ return Document(
+ physical_box=physical_box,
+ pages=pages,
+ medias=medias,
+ draw_params=draw_params,
+ templates=templates,
+ )
+
+ # 收集媒体资源和绘制参数。
+ def _collect_resources(
+ self,
+ res_path: str,
+ media_sink: dict[str, MediaRes],
+ draw_param_sink: dict[str, DrawParam],
+ ) -> None:
+ if not self._container.has(res_path.lstrip("/")):
+ return
+ res_el = etree.fromstring(self._container.read(res_path.lstrip("/")), parser=_xml_parser())
+ res_dir = posixpath.dirname(res_path)
+ # ``BaseLoc`` on <ofd:Res> further roots subsequent file refs.
+ base_loc = res_el.get("BaseLoc") or ""
+ media_dir = (
+ posixpath.normpath(posixpath.join(res_dir, base_loc))
+ if base_loc
+ else res_dir
+ )
+ if not media_dir.startswith("/"):
+ media_dir = "/" + media_dir
+
+ for mm in res_el.findall(".//ofd:MultiMedias/ofd:MultiMedia", NSMAP):
+ res_id = mm.get("ID")
+ if not res_id:
+ continue
+ mfile_el = mm.find("ofd:MediaFile", NSMAP)
+ if mfile_el is None or not mfile_el.text:
+ continue
+ file_path = posixpath.normpath(
+ posixpath.join(media_dir, mfile_el.text.strip())
+ )
+ if not file_path.startswith("/"):
+ file_path = "/" + file_path
+ media_sink[res_id] = MediaRes(
+ res_id=res_id,
+ media_type=mm.get("Type") or "Image",
+ file_path=file_path,
+ )
+
+ for dp_el in res_el.findall(".//ofd:DrawParams/ofd:DrawParam", NSMAP):
+ res_id = dp_el.get("ID")
+ if not res_id:
+ continue
+ line_width: Optional[float] = None
+ lw_raw = dp_el.get("LineWidth")
+ if lw_raw:
+ try:
+ line_width = float(lw_raw)
+ except ValueError:
+ line_width = None
+ fill_el = dp_el.find("ofd:FillColor", NSMAP)
+ stroke_el = dp_el.find("ofd:StrokeColor", NSMAP)
+ draw_param_sink[res_id] = DrawParam(
+ res_id=res_id,
+ relative=dp_el.get("Relative"),
+ line_width=line_width,
+ fill_color=(fill_el.get("Value") if fill_el is not None else None),
+ stroke_color=(stroke_el.get("Value") if stroke_el is not None else None),
+ )
+
+
+# --------------------------------------------------------------------------- #
+# helpers
+# --------------------------------------------------------------------------- #
+
+
+# 按 XPath 读取可选文字内容。
+def _text(node: etree._Element, xpath: str) -> Optional[str]:
+ el = node.find(xpath, NSMAP)
+ if el is None:
+ return None
+ return (el.text or "").strip() or None
+
+
+# 解析相对文档路径。
+def _join_doc(doc_dir: str, rel: str) -> str:
+ """Resolve a path that may be absolute (``/Doc_0/...``) or relative
+ to the directory of Document.xml."""
+ if rel.startswith("/"):
+ return posixpath.normpath(rel)
+ return posixpath.normpath(posixpath.join(doc_dir, rel))
+
+
+def _xml_parser() -> etree.XMLParser:
+ """每次读取使用独立解析器,禁止外部实体、DTD 加载和网络访问。"""
+ return etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True)
diff --git a/mineru/kit/gradio/_vendor/ofd2html/reader/resource_locator.py b/mineru/kit/gradio/_vendor/ofd2html/reader/resource_locator.py
new file mode 100644
index 00000000..60abd3ce
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/reader/resource_locator.py
@@ -0,0 +1,80 @@
+"""ResourceLocator: resolve OFD ``ST_Loc`` paths against the virtual container.
+
+Supports cd/pwd semantics:
+ * absolute path (``"/Doc_0/..."``) -> resolved from container root.
+ * relative path (``"Pages/Page_0/..."``) -> resolved from the current
+ working directory.
+"""
+
+from __future__ import annotations
+
+import posixpath
+
+from ..pkg.container import OFDContainer
+
+
+class ResourceLocator:
+ """Stateful path resolver bound to one ``OFDContainer``."""
+
+ # 初始化当前转换对象及资源。
+ def __init__(self, container: OFDContainer, cwd: str = "/") -> None:
+ self._container = container
+ self._cwd = self._normalize(cwd or "/")
+
+ # ----- working-directory management -------------------------------------
+
+ @property
+ # 返回当前虚拟目录。
+ def cwd(self) -> str:
+ return self._cwd
+
+ # 切换虚拟目录。
+ def cd(self, path: str) -> "ResourceLocator":
+ """Change working directory; ``path`` may be absolute or relative."""
+ self._cwd = self._normalize(self._join(path))
+ return self
+
+ # 保存当前虚拟目录。
+ def push(self) -> str:
+ """Snapshot current cwd; pair with :meth:`restore`."""
+ return self._cwd
+
+ # 恢复已保存的虚拟目录。
+ def restore(self, snapshot: str) -> None:
+ self._cwd = snapshot
+
+ # ----- path resolution --------------------------------------------------
+
+ # 解析资源的绝对虚拟路径。
+ def resolve(self, loc: str) -> str:
+ """Return absolute virtual path for ``loc`` (no leading slash)."""
+ return self._join(loc).lstrip("/")
+
+ # 按虚拟路径读取压缩包条目。
+ def read(self, loc: str) -> bytes:
+ return self._container.read(self.resolve(loc))
+
+ # 检查解析后的资源路径是否存在。
+ def exists(self, loc: str) -> bool:
+ return self._container.has(self.resolve(loc))
+
+ # ----- internals --------------------------------------------------------
+
+ # 拼接并规范化虚拟路径。
+ def _join(self, path: str) -> str:
+ if not path:
+ return self._cwd
+ if path.startswith("/"):
+ joined = path
+ else:
+ joined = posixpath.join(self._cwd, path)
+ return self._normalize(joined)
+
+ @staticmethod
+ # 消除路径中的点段。
+ def _normalize(path: str) -> str:
+ # posixpath.normpath collapses "..", "." and duplicate slashes.
+ norm = posixpath.normpath(path.replace("\\", "/"))
+ if not norm.startswith("/"):
+ norm = "/" + norm
+ return norm
diff --git a/mineru/kit/gradio/_vendor/ofd2html/render/__init__.py b/mineru/kit/gradio/_vendor/ofd2html/render/__init__.py
new file mode 100644
index 00000000..5b694f7b
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/render/__init__.py
@@ -0,0 +1,3 @@
+
+
+__all__ = []
diff --git a/mineru/kit/gradio/_vendor/ofd2html/render/color.py b/mineru/kit/gradio/_vendor/ofd2html/render/color.py
new file mode 100644
index 00000000..ab451b46
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/render/color.py
@@ -0,0 +1,56 @@
+"""Color helpers: OFD ``CT_Color`` ``Value`` attribute -> CSS color string.
+
+OFD colors are space-separated channel values, with channel space implied by
+the parent ``ColorSpace``. For the HTML preview we approximate everything to
+sRGB:
+
+* RGB triples: pass through.
+* CMYK quadruples: simple naive conversion (sufficient for preview).
+* Single-channel gray: replicate to RGB.
+
+Channel values may be ints (0-255) or normalized floats (0.0-1.0).
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+
+# 解析 OFD 颜色值。
+def parse_color(raw: Optional[str], default: str = "#000000") -> str:
+ if not raw:
+ return default
+ parts = raw.replace(",", " ").split()
+ if not parts:
+ return default
+ try:
+ nums = [float(p) for p in parts]
+ except ValueError:
+ return default
+ nums = [_to_byte(n) for n in nums]
+ if len(nums) == 1:
+ v = nums[0]
+ return _hex(v, v, v)
+ if len(nums) == 3:
+ return _hex(nums[0], nums[1], nums[2])
+ if len(nums) >= 4:
+ # CMYK -> sRGB approximation.
+ c, m, y, k = nums[0] / 255.0, nums[1] / 255.0, nums[2] / 255.0, nums[3] / 255.0
+ r = round(255 * (1 - c) * (1 - k))
+ g = round(255 * (1 - m) * (1 - k))
+ b = round(255 * (1 - y) * (1 - k))
+ return _hex(r, g, b)
+ return default
+
+
+# 将颜色分量限制到字节范围。
+def _to_byte(n: float) -> int:
+ # Heuristic: <=1 means normalized float; otherwise treat as 0-255 byte.
+ if 0 <= n <= 1:
+ n = n * 255
+ return max(0, min(255, int(round(n))))
+
+
+# 生成十六进制颜色。
+def _hex(r: int, g: int, b: int) -> str:
+ return f"#{r:02x}{g:02x}{b:02x}"
diff --git a/mineru/kit/gradio/_vendor/ofd2html/render/page_renderer.py b/mineru/kit/gradio/_vendor/ofd2html/render/page_renderer.py
new file mode 100644
index 00000000..87155c35
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/render/page_renderer.py
@@ -0,0 +1,420 @@
+"""Render one parsed OFD page into an SVG element string.
+
+This is intentionally a *single-pass* recursive walk over the page DOM. The
+mental model:
+
+* The SVG ``viewBox`` matches the OFD ``PhysicalBox`` (millimetres).
+* For every ``GraphicUnit`` (PathObject / TextObject / ImageObject), we emit
+ an SVG group with ``transform="translate(bx by) matrix(a b c d e f)"`` so
+ that local coordinates inside the object map to page coordinates the same
+ way an OFD reader would interpret them.
+* Text is emitted as plain ``<text>`` elements -- we rely on the browser's
+ font fallback rather than rasterising glyphs from embedded fonts. This is
+ the documented "fallback path 2" in the refactor plan.
+"""
+
+from __future__ import annotations
+
+import base64
+from typing import Iterable, Optional
+from xml.sax.saxutils import escape, quoteattr
+
+from lxml import etree
+
+from ..gv import NSMAP
+from ..reader.ofd_reader import Box, Document, DrawParam, OFDReader, PageRef
+from .color import parse_color
+from .path import abbr_data_to_svg_d
+
+
+# --------------------------------------------------------------------------- #
+# Public entry point.
+# --------------------------------------------------------------------------- #
+
+
+# 按模板和内容层次将页面渲染为 SVG。
+def render_page_to_svg(reader: OFDReader, doc: Document, page: PageRef) -> str:
+ """Return a complete ``<svg>...</svg>`` string for ``page``."""
+ page_el = reader.page_content(doc, page)
+ box = (
+ Box.parse(_xpath_text(page_el, ".//ofd:Area/ofd:PhysicalBox"))
+ or doc.physical_box
+ )
+ parts: list[str] = []
+ parts.append(
+ f'<svg xmlns="http://www.w3.org/2000/svg" '
+ f'xmlns:xlink="http://www.w3.org/1999/xlink" '
+ f'viewBox="0 0 {_num(box.w)} {_num(box.h)}" '
+ f'width="{_num(box.w)}mm" height="{_num(box.h)}mm" '
+ f'style="background:#fff;display:block;">'
+ )
+
+ # OFD page rendering composes three z-bands in order:
+ # Background templates -> page Body / Body templates -> Foreground
+ # templates. Each band may contain layers from either the template
+ # content or the page itself; any layer with no Type defaults to Body.
+ # Without this, paths defined only in template pages (a common pattern
+ # for form borders/grids) never render and the page looks "border-less".
+ bg: list[etree._Element] = []
+ body: list[etree._Element] = []
+ fg: list[etree._Element] = []
+
+ # 按绘制顺序收集页面图层。
+ def _bucket_layers(content_root: etree._Element, default_z: str) -> None:
+ for layer in content_root.findall(".//ofd:Content/ofd:Layer", NSMAP):
+ z = layer.get("Type") or default_z or "Body"
+ if z == "Background":
+ bg.append(layer)
+ elif z == "Foreground":
+ fg.append(layer)
+ else:
+ body.append(layer)
+
+ for tpl_el in page_el.findall("ofd:Template", NSMAP):
+ tpl_id = tpl_el.get("TemplateID")
+ if not tpl_id:
+ continue
+ tpl_root = reader.template_content(doc, tpl_id)
+ if tpl_root is None:
+ continue
+ _bucket_layers(tpl_root, tpl_el.get("ZOrder") or "Background")
+
+ _bucket_layers(page_el, "Body")
+
+ for layer in (*bg, *body, *fg):
+ layer_dp = doc.resolve_draw_param(layer.get("DrawParam"))
+ for child in layer:
+ _render_node(child, reader, doc, parts, layer_dp)
+ parts.append("</svg>")
+ return "".join(parts)
+
+
+# --------------------------------------------------------------------------- #
+# Recursive renderer.
+# --------------------------------------------------------------------------- #
+
+
+# 按对象类型分派渲染并继承绘制参数。
+def _render_node(
+ node: etree._Element,
+ reader: OFDReader,
+ doc: Document,
+ out: list[str],
+ layer_dp: Optional[DrawParam] = None,
+) -> None:
+ # lxml exposes XML comments / processing instructions when iterating
+ # element children; their ``.tag`` is a callable, not a string, so guard
+ # before passing to ``etree.QName`` to keep template-page rendering
+ # robust against documents that interleave comments with content.
+ if not isinstance(node.tag, str):
+ return
+ tag = etree.QName(node).localname
+ if tag == "PageBlock":
+ for child in node:
+ _render_node(child, reader, doc, out, layer_dp)
+ elif tag == "PathObject":
+ out.append(_render_path_object(node, doc, layer_dp))
+ elif tag == "TextObject":
+ out.append(_render_text_object(node, doc, layer_dp))
+ elif tag == "ImageObject":
+ out.append(_render_image_object(node, reader, doc))
+ # Unknown nodes are silently skipped so future OFD features
+ # don't break the whole page.
+
+
+# --------------------------------------------------------------------------- #
+# PathObject.
+# --------------------------------------------------------------------------- #
+
+
+# 将路径对象渲染为 SVG 路径。
+def _render_path_object(
+ node: etree._Element,
+ doc: Document,
+ layer_dp: Optional[DrawParam] = None,
+) -> str:
+ boundary = Box.parse(node.get("Boundary"))
+ ctm = node.get("CTM")
+ fill_attr = (node.get("Fill") or "").lower()
+ stroke_attr = (node.get("Stroke") or "").lower()
+
+ # OFD GB/T 33190-2016 Table 35 (CT_Path):
+ # Stroke defaults to true, Fill defaults to false.
+ # Earlier this code only enabled stroke when both attrs were absent,
+ # which dropped borders on paths declaring only Fill="true".
+ do_fill = fill_attr == "true"
+ do_stroke = stroke_attr != "false"
+
+ # Resolve DrawParam defaults: layer-level first, then path-level overrides.
+ path_dp = doc.resolve_draw_param(node.get("DrawParam"))
+ dp_line_width: Optional[float] = None
+ dp_fill_raw: Optional[str] = None
+ dp_stroke_raw: Optional[str] = None
+ for dp in (layer_dp, path_dp):
+ if dp is None:
+ continue
+ if dp.line_width is not None:
+ dp_line_width = dp.line_width
+ if dp.fill_color is not None:
+ dp_fill_raw = dp.fill_color
+ if dp.stroke_color is not None:
+ dp_stroke_raw = dp.stroke_color
+
+ # LineWidth precedence: PathObject@LineWidth > DrawParam.LineWidth > 0.353.
+ line_width_attr = node.get("LineWidth")
+ if line_width_attr:
+ line_width = line_width_attr
+ elif dp_line_width is not None:
+ line_width = _num(dp_line_width)
+ else:
+ line_width = "0.353"
+
+ # Color precedence: explicit child element > DrawParam > spec default.
+ fill_value = _xpath_attr(node, "ofd:FillColor", "Value") or dp_fill_raw
+ stroke_value = _xpath_attr(node, "ofd:StrokeColor", "Value") or dp_stroke_raw
+
+ fill_color = parse_color(fill_value, "#000000") if do_fill else "none"
+ if do_stroke:
+ if stroke_value:
+ stroke_color = parse_color(stroke_value, "#000000")
+ elif do_fill and fill_value:
+ # Mirror reference renderer: fall back to the fill colour when no
+ # StrokeColor is supplied -- otherwise a coloured filled shape
+ # would gain a hard black outline.
+ stroke_color = parse_color(fill_value, "#000000")
+ else:
+ stroke_color = "#000000"
+ else:
+ stroke_color = "none"
+
+ abbr = _xpath_text(node, "ofd:AbbreviatedData") or ""
+ d_attr = abbr_data_to_svg_d(abbr)
+ if not d_attr:
+ return ""
+
+ transform = _build_transform(boundary, ctm)
+ attrs = [f"d={quoteattr(d_attr)}"]
+ if fill_color != "none":
+ attrs.append(f'fill="{fill_color}"')
+ else:
+ attrs.append('fill="none"')
+ if stroke_color != "none":
+ attrs.append(f'stroke="{stroke_color}"')
+ attrs.append(f'stroke-width="{line_width}"')
+ if transform:
+ attrs.append(f'transform="{transform}"')
+ return "<path " + " ".join(attrs) + "/>"
+
+
+# --------------------------------------------------------------------------- #
+# TextObject.
+# --------------------------------------------------------------------------- #
+
+
+# 保留文字位置并转义 SVG 文本。
+def _render_text_object(
+ node: etree._Element,
+ doc: Document,
+ layer_dp: Optional[DrawParam] = None,
+) -> str:
+ boundary = Box.parse(node.get("Boundary"))
+ ctm = node.get("CTM")
+ size_raw = node.get("Size") or "3"
+ try:
+ size = float(size_raw)
+ except ValueError:
+ size = 3.0
+ weight = node.get("Weight") or ""
+ italic = (node.get("Italic") or "").lower() == "true"
+
+ # Fill colour precedence (mirrors the reference JS renderer):
+ # explicit <ofd:FillColor Value=...> on the TextObject
+ # > DrawParam referenced by the TextObject's @DrawParam
+ # > DrawParam inherited from the enclosing Layer's @DrawParam
+ # > spec default (black).
+ # Without the DrawParam fallbacks the brown / coloured labels in many
+ # form-style OFDs (e.g. 航空运输电子客票行程单) render entirely in black.
+ text_dp = doc.resolve_draw_param(node.get("DrawParam"))
+ explicit_fill = _xpath_attr(node, "ofd:FillColor", "Value")
+ dp_fill: Optional[str] = None
+ for dp in (layer_dp, text_dp):
+ if dp is not None and dp.fill_color is not None:
+ dp_fill = dp.fill_color
+ fill_value = explicit_fill or dp_fill
+ fill_color = parse_color(fill_value, "#000000")
+
+ transform = _build_transform(boundary, ctm)
+
+ out: list[str] = []
+ for tc in node.findall("ofd:TextCode", NSMAP):
+ text = tc.text or ""
+ if not text:
+ continue
+ try:
+ x0 = float(tc.get("X") or "0")
+ y0 = float(tc.get("Y") or "0")
+ except ValueError:
+ continue
+ delta_x = _parse_deltas(tc.get("DeltaX"))
+ delta_y = _parse_deltas(tc.get("DeltaY"))
+
+ # Build absolute x/y lists from deltas (OFD: each delta is the advance
+ # *between* successive characters).
+ xs: list[float] = [x0]
+ ys: list[float] = [y0]
+ for ch_index in range(1, len(text)):
+ dx = delta_x[ch_index - 1] if ch_index - 1 < len(delta_x) else 0.0
+ dy = delta_y[ch_index - 1] if ch_index - 1 < len(delta_y) else 0.0
+ xs.append(xs[-1] + dx)
+ ys.append(ys[-1] + dy)
+
+ attrs = [
+ f'x="{" ".join(_num(v) for v in xs)}"',
+ f'y="{" ".join(_num(v) for v in ys)}"',
+ f'font-size="{_num(size)}"',
+ f'fill="{fill_color}"',
+ "font-family=\"SimSun, 'Microsoft YaHei', 'Noto Sans CJK SC', serif\"",
+ ]
+ if weight and weight not in ("400", "normal"):
+ attrs.append(f'font-weight="{escape(weight)}"')
+ if italic:
+ attrs.append('font-style="italic"')
+ if transform:
+ attrs.append(f'transform="{transform}"')
+ out.append(f"<text {' '.join(attrs)}>{escape(text)}</text>")
+ return "".join(out)
+
+
+# --------------------------------------------------------------------------- #
+# ImageObject.
+# --------------------------------------------------------------------------- #
+
+
+# 将图片编码为内嵌数据并应用坐标变换。
+def _render_image_object(node: etree._Element, reader: OFDReader, doc: Document) -> str:
+ res_id = node.get("ResourceID") or ""
+ if not res_id:
+ return ""
+ media = reader.media(doc, res_id)
+ if media is None:
+ return ""
+ try:
+ data = reader.read_media(doc, res_id)
+ except FileNotFoundError:
+ return ""
+ if data is None:
+ return ""
+ mime = _sniff_mime(media.file_path, data)
+ href = "data:{0};base64,{1}".format(mime, base64.b64encode(data).decode("ascii"))
+
+ # An OFD ImageObject draws its source over the unit square (0,0)-(1,1),
+ # mapped to the page by Boundary + CTM. We therefore emit an <image>
+ # filling the unit square and let the transform place it.
+ boundary = Box.parse(node.get("Boundary"))
+ ctm = node.get("CTM")
+ transform = _build_transform(boundary, ctm)
+
+ return (
+ f'<image x="0" y="0" width="1" height="1" '
+ f'preserveAspectRatio="none" '
+ f"xlink:href={quoteattr(href)} "
+ f'transform="{transform}"/>'
+ )
+
+
+# --------------------------------------------------------------------------- #
+# helpers
+# --------------------------------------------------------------------------- #
+
+
+# 根据边界框和矩阵构造 SVG 变换。
+def _build_transform(boundary: Optional[Box], ctm: Optional[str]) -> str:
+ parts: list[str] = []
+ if boundary is not None:
+ parts.append(f"translate({_num(boundary.x)} {_num(boundary.y)})")
+ if ctm:
+ nums = ctm.replace(",", " ").split()
+ if len(nums) >= 6:
+ try:
+ a = " ".join(_num(float(n)) for n in nums[:6])
+ parts.append(f"matrix({a})")
+ except ValueError:
+ pass
+ return " ".join(parts)
+
+
+# 展开文字间距的压缩表达。
+def _parse_deltas(raw: Optional[str]) -> list[float]:
+ """Parse OFD ``DeltaX``/``DeltaY``. May contain ``g`` repeat operator
+ e.g. ``g 3 12.5`` -> ``[12.5, 12.5, 12.5]`` (count then value)."""
+ if not raw:
+ return []
+ tokens = raw.replace(",", " ").split()
+ out: list[float] = []
+ i = 0
+ while i < len(tokens):
+ tok = tokens[i]
+ if tok == "g" and i + 2 < len(tokens):
+ try:
+ count = int(float(tokens[i + 1]))
+ value = float(tokens[i + 2])
+ except ValueError:
+ i += 1
+ continue
+ out.extend([value] * count)
+ i += 3
+ continue
+ try:
+ out.append(float(tok))
+ except ValueError:
+ pass
+ i += 1
+ return out
+
+
+# 提取 XPath 对应的可选文本。
+def _xpath_text(node: etree._Element, xpath: str) -> Optional[str]:
+ el = node.find(xpath, NSMAP)
+ if el is None:
+ return None
+ return (el.text or "").strip() or None
+
+
+# 提取 XPath 对应的可选属性。
+def _xpath_attr(node: etree._Element, xpath: str, attr: str) -> Optional[str]:
+ el = node.find(xpath, NSMAP)
+ if el is None:
+ return None
+ return el.get(attr)
+
+
+# 格式化 SVG 数值。
+def _num(v: float) -> str:
+ """Format a float compactly for SVG (strip trailing zeros)."""
+ if isinstance(v, int):
+ return str(v)
+ s = f"{v:.4f}".rstrip("0").rstrip(".")
+ return s if s else "0"
+
+
+# 从文件名和字节识别图片类型。
+def _sniff_mime(file_path: str, data: bytes) -> str:
+ lower = file_path.lower()
+ if lower.endswith((".jpg", ".jpeg")):
+ return "image/jpeg"
+ if lower.endswith(".png"):
+ return "image/png"
+ if lower.endswith(".gif"):
+ return "image/gif"
+ if lower.endswith(".bmp"):
+ return "image/bmp"
+ # Magic-byte fallbacks.
+ if data[:3] == b"\xff\xd8\xff":
+ return "image/jpeg"
+ if data[:8] == b"\x89PNG\r\n\x1a\n":
+ return "image/png"
+ return "application/octet-stream"
+
+
+# Keep type-checker happy: Iterable is referenced indirectly elsewhere.
+_ = Iterable
diff --git a/mineru/kit/gradio/_vendor/ofd2html/render/path.py b/mineru/kit/gradio/_vendor/ofd2html/render/path.py
new file mode 100644
index 00000000..405be7ac
--- /dev/null
+++ b/mineru/kit/gradio/_vendor/ofd2html/render/path.py
@@ -0,0 +1,65 @@
+"""OFD ``AbbreviatedData`` -> SVG ``d`` attribute.
+
+OFD path operators (GB/T 33190-2016 sec 9):
+ S x y start (move-to)
+ M x y move-to
+ L x y line-to
+ Q x1 y1 x2 y2 quadratic bezier
+ B x1 y1 x2 y2 x3 y3 cubic bezier
+ A rx ry rot la sw x y elliptic arc (same args as SVG)
+ C close path
+
+We map them to the corresponding SVG path commands.
+"""
+
+from __future__ import annotations
+
+# Number of numeric arguments per OFD operator.
+_OP_ARITY = {
+ "S": 2,
+ "M": 2,
+ "L": 2,
+ "Q": 4,
+ "B": 6,
+ "A": 7,
+ "C": 0,
+}
+
+# Mapping to SVG operators.
+_OP_TO_SVG = {
+ "S": "M",
+ "M": "M",
+ "L": "L",
+ "Q": "Q",
+ "B": "C",
+ "A": "A",
+ "C": "Z",
+}
+
+
+# 将 OFD 缩写路径指令转换为 SVG 路径数据。
+def abbr_data_to_svg_d(raw: str) -> str:
+ """Convert an OFD ``AbbreviatedData`` string into an SVG ``d`` value."""
+ if not raw:
+ return ""
+ tokens = raw.replace(",", " ").split()
+ out: list[str] = []
+ i = 0
+ n = len(tokens)
+ while i < n:
+ op = tokens[i]
+ if op not in _OP_ARITY:
+ # Skip unknown tokens defensively rather than aborting the whole page.
+ i += 1
+ continue
+ arity = _OP_ARITY[op]
+ args = tokens[i + 1 : i + 1 + arity]
+ if len(args) < arity:
+ break
+ svg_op = _OP_TO_SVG[op]
+ if arity == 0:
+ out.append(svg_op)
+ else:
+ out.append(svg_op + " " + " ".join(args))
+ i += 1 + arity
+ return " ".join(out)
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.py
index 416a6f7a..0b057016 100644
--- a/mineru/kit/gradio/app.py
+++ b/mineru/kit/gradio/app.py
@@ -25,6 +25,7 @@ from .client import (
V1ServerCapabilities,
)
from .i18n import MESSAGES, localized_text, preview_placeholder, translations
+from .ofd_preview import prepare_ofd_preview
from .page_range import effective_page_range as _effective_page_range
from .page_range import pdf_page_metadata, validate_max_pages
from .pdf_preview import pdf_preview_js, register_pdf_preview_resources
@@ -164,6 +165,9 @@ _KIT_MENU_CSS = """
.mineru-kit-pdf-preview .prose { height: 100%; padding: 0 !important; }
.mineru-kit-pdf-preview:not(:has(.mineru-pdf-frame, [role="alert"])) { display: none !important; }
.mineru-pdf-frame { display: block; width: 100%; height: 100%; border: 0; }
+.mineru-kit-ofd-preview:not(:has(iframe)):not(:has([data-mineru-i18n-key])) { display: none !important; }
+.mineru-kit-ofd-preview, .mineru-kit-ofd-preview .html-container { padding: 0 !important; }
+.mineru-ofd-frame { width: 100%; height: var(--mineru-preview-content-height, 775px); border: 0; display: block; }
.mineru-kit-image-preview img { max-height: var(--mineru-pdf-page-height, 720px); object-fit: contain; }
/* 桌面两栏共用行高,PDF 填满伸展后的面板;窄屏仍采用独立预览高度。 */
@media (min-width: 901px) {
@@ -429,6 +433,12 @@ def build_gradio_app(
min_height=320,
elem_classes=["mineru-kit-office-preview", "mineru-office-preview-html"],
)
+ ofd_preview = gr.HTML(
+ value="", apply_default_css=False,
+ elem_classes=["mineru-kit-ofd-preview"],
+ )
+ ofd_ticket = gr.Textbox(value="", visible=False)
+ ofd_receipt = gr.Textbox(value="", visible=False)
generic_preview = gr.HTML(
value=preview_placeholder("empty_preview"),
visible=True,
@@ -526,6 +536,14 @@ def build_gradio_app(
_preview_update(gr, preview_placeholder("source_preview"), visible=False),
*reset_result,
)
+ if suffix == "ofd":
+ return (
+ _pdf_preview_update(gr, None),
+ _preview_update(gr, None, visible=False),
+ _preview_update(gr, "", visible=False),
+ _preview_update(gr, "", visible=False),
+ *reset_result,
+ )
if _is_office(file_path):
return (
_pdf_preview_update(gr, None),
@@ -554,6 +572,26 @@ def build_gradio_app(
input_file.change(fn=None, inputs=input_file, outputs=pdf_viewer, js=pdf_preview_js("reset"), **private_event_kwargs)
clear_button.click(fn=None, inputs=[], outputs=pdf_viewer, js=pdf_preview_js("clear"), **private_event_kwargs)
+ ofd_script = _resource_text("gradio_ofd_preview.js")
+ input_file.change(
+ fn=None, inputs=input_file, outputs=[ofd_ticket, ofd_preview],
+ js=f"(...args) => ({ofd_script})('begin', ...args)",
+ **private_event_kwargs,
+ )
+ # Gradio 6.8 的纯前端事件不可靠地触发 then;通过请求值变化启动后台转换。
+ render_ofd = ofd_ticket.change(
+ fn=prepare_ofd_preview, inputs=[input_file, ofd_ticket], outputs=ofd_receipt,
+ concurrency_limit=None, trigger_mode="multiple", **private_event_kwargs,
+ )
+ render_ofd.then(
+ fn=None, inputs=ofd_receipt, outputs=ofd_preview,
+ js=f"(...args) => ({ofd_script})('apply', ...args)", **private_event_kwargs,
+ )
+ clear_button.click(
+ fn=None, inputs=[], outputs=[ofd_ticket, ofd_preview],
+ js=f"(...args) => ({ofd_script})('clear', ...args)", **private_event_kwargs,
+ )
+
download_script = _resource_text("gradio_download.js")
def download_js(action: str, format_name: str = "", label: str = "") -> str:
@@ -759,8 +797,8 @@ def build_gradio_app(
gr.update(value="", visible=False),
gr.update(value=generic_html, visible=bool(generic_html)),
)
- if _is_office(source_path):
- # Office 源预览已在上传时挂载,成功后不重载 iframe,也不恢复已忽略的提示。
+ if _is_office(source_path) or suffix == "ofd":
+ # Office/OFD 源预览已在上传时挂载,成功后保留原内容和浏览位置。
result_preview_updates = tuple(gr.skip() for _ in range(4))
return (
rendered_html,
diff --git a/mineru/kit/gradio/i18n.py b/mineru/kit/gradio/i18n.py
index 7d100fcc..b039391f 100644
--- a/mineru/kit/gradio/i18n.py
+++ b/mineru/kit/gradio/i18n.py
@@ -63,6 +63,10 @@ MESSAGES: dict[str, tuple[str, str]] = {
"pdf_load_failed": ("Could not load the PDF preview. Please upload the file again.", "PDF 预览加载失败,请重新上传文件。"),
"empty_preview": ("No source document preview", "暂无源文档预览"),
"source_preview": ("Source document preview", "源文档预览"),
+ "ofd_preview_failed": (
+ "Could not preview this OFD file. You can still try converting it.",
+ "OFD 预览生成失败,仍可尝试解析该文件。",
+ ),
"unsupported_preview": ("No source preview for this format", "该格式暂无源文档预览"),
"result_ready": ("Results are ready", "结果已生成"),
"markdown": ("Markdown", "Markdown"),
diff --git a/mineru/kit/gradio/ofd_preview.py b/mineru/kit/gradio/ofd_preview.py
new file mode 100644
index 00000000..04a16c38
--- /dev/null
+++ b/mineru/kit/gradio/ofd_preview.py
@@ -0,0 +1,47 @@
+"""OFD 源文档预览适配,不参与语义解析或结果导出。"""
+
+from __future__ import annotations
+
+import asyncio
+import html
+import json
+from pathlib import Path
+
+from loguru import logger
+
+from .i18n import preview_placeholder
+
+__all__ = ["build_ofd_preview", "prepare_ofd_preview"]
+
+
+def build_ofd_preview(payload: bytes) -> str:
+ """惰性转换 OFD,并在无脚本权限的隔离框架中显示自包含页面。"""
+ from ._vendor.ofd2html import ofd_to_html
+
+ document = ofd_to_html(payload)
+ style = (
+ '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; '
+ "style-src 'unsafe-inline'; img-src data:; font-src data:\">"
+ "<style>body>div>div:has(>svg){max-width:100%;}"
+ "svg{display:block;max-width:100%;height:auto}</style>"
+ )
+ document = document.replace("<head>", "<head>" + style, 1)
+ return (
+ '<iframe class="mineru-ofd-frame" title="OFD preview" sandbox="" '
+ f'srcdoc="{html.escape(document, quote=True)}"></iframe>'
+ )
+
+
+async def prepare_ofd_preview(file_path: str | None, ticket: str) -> str:
+ """后台生成带请求标识的预览回执,交由浏览器丢弃过期结果。"""
+ request = json.loads(ticket)
+ result = {"id": request["id"], "html": ""}
+ if not file_path or request.get("path") != file_path or Path(file_path).suffix.lower() != ".ofd":
+ return json.dumps(result)
+ try:
+ payload = await asyncio.to_thread(Path(file_path).read_bytes)
+ result["html"] = await asyncio.to_thread(build_ofd_preview, payload)
+ except Exception as exc:
+ logger.warning("OFD source preview failed: {}", exc)
+ result["html"] = preview_placeholder("ofd_preview_failed")
+ return json.dumps(result)
diff --git a/mineru/resources/gradio_ofd_preview.js b/mineru/resources/gradio_ofd_preview.js
new file mode 100644
index 00000000..e191c30e
--- /dev/null
+++ b/mineru/resources/gradio_ofd_preview.js
@@ -0,0 +1,12 @@
+(action, ...args) => {
+ // 浏览器会话保存最新请求标识,清除和重复上传同一文件也会使旧请求失效。
+ const key = "__mineruOfdPreview";
+ if (action === "begin" || action === "clear") {
+ const file = action === "clear" ? null : args[0];
+ const ticket = {id: (window[key] || 0) + 1, path: file?.path || ""};
+ window[key] = ticket.id;
+ return [JSON.stringify(ticket), ""];
+ }
+ const receipt = JSON.parse(args[0]);
+ return receipt.id === window[key] ? receipt.html : {__type__: "update"};
+}
diff --git a/pyproject.toml b/pyproject.toml
index b47a30d8..29cbbe45 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -120,6 +120,7 @@ full = [
]
gradio = [
"gradio>=6.8,<7",
+ "lxml>=5,<7",
]
all = [
"mineru[full]",
@@ -151,6 +152,7 @@ namespaces = false
[tool.setuptools.package-data]
"mineru" = ["resources/**"]
+"mineru.kit.gradio._vendor.ofd2html" = ["LICENSE", "UPSTREAM.md"]
"mineru.doclib.migrations" = ["*.sql"]
"mineru.model._internal.pytorchocr.utils" = ["resources/**"]
diff --git a/tests/unittest/test_kit_gradio_ofd_preview.cjs b/tests/unittest/test_kit_gradio_ofd_preview.cjs
new file mode 100644
index 00000000..126412cc
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_ofd_preview.cjs
@@ -0,0 +1,18 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+let sequence = 0;
+const preview = vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../../mineru/resources/gradio_ofd_preview.js'), 'utf8'), {
+ window: {}, crypto: {randomUUID: () => String(++sequence)},
+});
+const first = JSON.parse(preview('begin', {path: '/first.ofd'})[0]);
+const second = JSON.parse(preview('begin', {path: '/second.ofd'})[0]);
+assert.equal(preview('apply', JSON.stringify({id: second.id, html: 'new'})), 'new');
+assert.equal(preview('apply', JSON.stringify({id: first.id, html: 'old'})).__type__, 'update');
+preview('clear');
+assert.equal(preview('apply', JSON.stringify({id: second.id, html: 'stale'})).__type__, 'update');
+const third = JSON.parse(preview('begin', {path: '/second.ofd'})[0]);
+assert.notEqual(third.id, second.id);
+assert.equal(preview('apply', JSON.stringify({id: third.id, html: 'reload'})), 'reload');
+console.log('OFD preview: switch, clear, re-upload and stale receipts passed');
diff --git a/tests/unittest/test_kit_gradio_ofd_preview.py b/tests/unittest/test_kit_gradio_ofd_preview.py
new file mode 100644
index 00000000..c3e3930f
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_ofd_preview.py
@@ -0,0 +1,155 @@
+"""OFD 预览的真实转换、隔离和失败回执回归。"""
+
+import asyncio
+import io
+import json
+import zipfile
+from pathlib import Path
+
+import pytest
+from lxml import html
+from PIL import Image
+
+from mineru.kit.gradio.ofd_preview import build_ofd_preview, prepare_ofd_preview
+
+
+def ofd_bytes(text: str = "中文发票 &amp; &lt;script&gt;", *, entity: str = "") -> bytes:
+ """构造包含两页、模板、路径及内嵌图片的有效 OFD 测试文档。"""
+ ns = 'xmlns:ofd="http://www.ofdspec.org/2016"'
+ image = io.BytesIO()
+ Image.new("RGB", (20, 20), "red").save(image, format="PNG")
+ files = {
+ "OFD.xml": (
+ f'<ofd:OFD {ns} Version="1.0" DocType="OFD">'
+ "<ofd:DocBody><ofd:DocRoot>Doc/Document.xml</ofd:DocRoot></ofd:DocBody></ofd:OFD>"
+ ),
+ "Doc/Document.xml": f"""<ofd:Document {ns}><ofd:CommonData>
+ <ofd:PageArea><ofd:PhysicalBox>0 0 210 297</ofd:PhysicalBox></ofd:PageArea>
+ <ofd:DocumentRes>Res.xml</ofd:DocumentRes>
+ <ofd:TemplatePage ID="9" BaseLoc="Template.xml" ZOrder="Background"/>
+ </ofd:CommonData><ofd:Pages><ofd:Page ID="1" BaseLoc="Page.xml"/>
+ <ofd:Page ID="2" BaseLoc="Page.xml"/></ofd:Pages></ofd:Document>""",
+ "Doc/Res.xml": f"""<ofd:Res {ns}><ofd:MultiMedias><ofd:MultiMedia ID="4" Type="Image">
+ <ofd:MediaFile>red.png</ofd:MediaFile></ofd:MultiMedia></ofd:MultiMedias></ofd:Res>""",
+ "Doc/Template.xml": f"""<ofd:Page {ns}><ofd:Content><ofd:Layer ID="10">
+ <ofd:PathObject ID="11" Boundary="10 10 190 277" Stroke="true" LineWidth="0.5">
+ <ofd:AbbreviatedData>M 0 0 L 190 0 L 190 277 L 0 277 C</ofd:AbbreviatedData>
+ </ofd:PathObject></ofd:Layer></ofd:Content></ofd:Page>""",
+ "Doc/Page.xml": f"""{entity}<ofd:Page {ns}><ofd:Template TemplateID="9"/>
+ <ofd:Content><ofd:Layer ID="1"><ofd:TextObject ID="2" Boundary="20 30 160 20" Size="5">
+ <ofd:TextCode X="0" Y="8" DeltaX="g 40 5">{text}</ofd:TextCode></ofd:TextObject>
+ <ofd:ImageObject ID="3" ResourceID="4" Boundary="20 60 30 30" CTM="30 0 0 30 0 0"/>
+ </ofd:Layer></ofd:Content></ofd:Page>""",
+ "Doc/red.png": image.getvalue(),
+ }
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
+ for name, value in files.items():
+ archive.writestr(name, value)
+ return output.getvalue()
+
+
+def test_real_conversion_embeds_pages_and_escapes_text() -> None:
+ """验证两页 SVG、模板路径、图片和文字转义,并禁止 iframe 脚本。"""
+ frame = html.fromstring(build_ofd_preview(ofd_bytes()))
+ assert frame.get("sandbox") == ""
+ document = html.fromstring(frame.get("srcdoc"))
+ assert len(document.xpath("//svg")) == 2
+ assert len(document.xpath("//svg/path")) == 2
+ assert "中文发票 & <script>" in document.text_content()
+ assert not document.xpath("//script")
+ assert "data:image/png;base64," in frame.get("srcdoc")
+ assert "max-width:100%" in frame.get("srcdoc")
+
+
[email protected]("payload", [b"", b"garbage", b"PK\x03\x04"])
+def test_invalid_payload(payload: bytes) -> None:
+ """空文件和损坏压缩包必须明确失败。"""
+ with pytest.raises((ValueError, zipfile.BadZipFile)):
+ build_ofd_preview(payload)
+
+
+def test_missing_ofd_xml() -> None:
+ """合法 ZIP 缺少 OFD 入口时不得显示空白成功预览。"""
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as archive:
+ archive.writestr("unrelated.xml", "<x/>")
+ with pytest.raises(ValueError, match="missing OFD.xml"):
+ build_ofd_preview(output.getvalue())
+
+
+def test_external_entity_is_not_read(tmp_path: Path) -> None:
+ """外部实体不得读取本地文件或进入最终 HTML。"""
+ secret = tmp_path / "secret.txt"
+ secret.write_text("OFD_EXTERNAL_ENTITY_SECRET")
+ entity = f'<!DOCTYPE ofd:Page [<!ENTITY leak SYSTEM "{secret.as_uri()}">]>'
+ frame = build_ofd_preview(ofd_bytes("&leak;", entity=entity))
+ assert "OFD_EXTERNAL_ENTITY_SECRET" not in frame
+
+
+def test_preview_receipts_and_failure(tmp_path: Path) -> None:
+ """成功和失败均回传请求标识,预览错误不向解析流程抛出。"""
+ source = tmp_path / "中文.OFD"
+ source.write_bytes(ofd_bytes())
+ ticket = json.dumps({"id": "request-1", "path": str(source)})
+ receipt = json.loads(asyncio.run(prepare_ofd_preview(str(source), ticket)))
+ assert receipt["id"] == "request-1" and "iframe" in receipt["html"]
+ source.write_bytes(b"bad")
+ receipt = json.loads(asyncio.run(prepare_ofd_preview(str(source), ticket)))
+ assert "ofd_preview_failed" in receipt["html"]
+ assert json.loads(asyncio.run(prepare_ofd_preview(None, ticket)))["html"] == ""
+ assert json.loads(asyncio.run(prepare_ofd_preview(str(source) + "x", ticket)))["html"] == ""
+
+
[email protected]("fail", [False, True])
+def test_parse_preserves_source_preview(tmp_path: Path, fail: bool) -> None:
+ """解析成功或失败只更新结果,OFD 源预览始终由独立事件维护。"""
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock
+
+ from test_kit_gradio import _middle_json
+
+ from mineru.kit.gradio.app import build_gradio_app
+ from mineru.kit.gradio.client import V1ServerCapabilities
+ from mineru.parser.base import ParseResult
+
+ source = tmp_path / "source.ofd"
+ source.write_bytes(ofd_bytes())
+ parse = AsyncMock(return_value=ParseResult(middle_json=_middle_json(with_image=False)))
+ if fail:
+ parse.side_effect = ValueError("expected parse failure")
+ demo = build_gradio_app(
+ SimpleNamespace(parse_file=parse),
+ V1ServerCapabilities("http://127.0.0.1:1", ("flash",), ("zip",), ("file_id",)),
+ output_root=tmp_path / "results",
+ enable_example=False,
+ )
+ convert = next(fn for fn in demo.fns.values() if fn.name == "convert_handler")
+ ofd = next(block for block in demo.blocks.values() if "mineru-kit-ofd-preview" in (block.elem_classes or []))
+ assert ofd not in convert.outputs
+ upload = next(fn for fn in demo.fns.values() if fn.name == "update_file_preview")
+ updates = upload.fn(str(source))
+ assert all(update.get("visible") is False for update in updates[:4])
+
+ async def collect() -> list:
+ """收集真实解析事件的完整输出序列。"""
+ return [value async for value in convert.fn(str(source), 0, "")]
+
+ final = asyncio.run(collect())[-1]
+ assert final[2:6] == ({"__type__": "update"},) * 4
+ if fail:
+ assert "expected parse failure" in final[0]
+ else:
+ assert final[6] is not None
+ assert final[-1]
+
+
+def test_browser_request_lifecycle() -> None:
+ """通过真实前端脚本验证乱序完成、清除和同文件重传不会恢复旧预览。"""
+ import shutil
+ import subprocess
+
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("Node.js is required for preview lifecycle checks")
+ subprocess.run([node, str(Path(__file__).with_suffix(".cjs"))], check=True, timeout=15)