Skip to content

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

fix: preserve HTML visibility and URL typing

myhloli95a92978c31c
diff --git a/mineru/model/flash/html/document.py b/mineru/model/flash/html/document.py
index ce9ba827..117395e4 100644
--- a/mineru/model/flash/html/document.py
+++ b/mineru/model/flash/html/document.py
@@ -39,6 +39,7 @@ _ACTIVE_TAGS = frozenset(
)
_FORMULA_GENERATOR_CLASS_TOKENS = frozenset({"katex", "mathjax", "mineru-math"})
_GENERIC_FORMULA_CLASS_TOKENS = frozenset({"formula", "math", "tex"})
+_FORMULA_VISIBILITY_ATTRIBUTES = ("hidden", "aria-hidden", "style", "class")
_MEANINGFUL_FORMULA_SIBLING_TAGS = frozenset(
{"audio", "br", "canvas", "figure", "hr", "iframe", "image", "img", "object", "svg", "table", "video"}
)
@@ -327,6 +328,9 @@ def _replace_with_formula(element: etree._Element, formula: FormulaExtraction) -
replacement = etree.Element("math")
replacement.set("data-mineru-latex", formula.latex)
replacement.set("data-formula-display", formula.display)
+ for attribute in _FORMULA_VISIBILITY_ATTRIBUTES:
+ if (value := element.get(attribute)) is not None:
+ replacement.set(attribute, value)
if formula.display == "block":
replacement.set("display", "block")
if (element.get("data-block-type") or "").strip() == "equation":
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index f9b1b73e..97b09793 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -1287,12 +1287,13 @@ def _count_pages_in_range(page_range: str) -> int:
@dataclass(frozen=True, slots=True)
class _ExtractedSource:
- """保存 API 输入字节及 HTML 来源上下文。"""
+ """保存 API 输入字节、响应类型及 HTML 来源上下文。"""
data: bytes
source_uri: str | None = None
local_resource_root: pathlib.Path | None = None
transport_encoding: str | None = None
+ media_type: str | None = None
async def _extract_bytes(
@@ -1324,6 +1325,7 @@ async def _extract_bytes(
r.content,
source_uri=str(r.url),
transport_encoding=r.charset_encoding,
+ media_type=(r.headers.get("content-type") or "").partition(";")[0].strip().casefold() or None,
)
if isinstance(source, InlineSource):
return _ExtractedSource(_decode_inline_data(source.data))
@@ -1372,17 +1374,21 @@ async def _run_job(
allow_http_source=allow_http_source,
)
data = extracted.data
+ suffix = pathlib.Path(fr.name).suffix
stype = _suffix_type(fr.name)
+ if not stype and not suffix and isinstance(entry.source, UrlSource) and extracted.media_type == "text/html":
+ stype = "html"
+ suffix = ".html"
if not stype:
raise ValueError(f"Unsupported file type: {fr.name}")
# write to temp file for parsers that require a path
- suffix = pathlib.Path(fr.name).suffix or ".pdf"
+ suffix = suffix or ".pdf"
tmp_path = pathlib.Path(tmpdir) / f"input_{i}{suffix}"
tmp_path.write_bytes(data)
page_range = entry.page_range or ""
- effective_tier = batch_effective_parse_tier(rec.tier, fr.name)
+ effective_tier = batch_effective_parse_tier(rec.tier, suffix)
source_context = None
if stype == "html":
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 9267a167..dcaebd81 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -341,6 +341,57 @@ def test_html_parse_server_url_preserves_http_declared_charset(tmp_path: Path, m
assert middle_payload["pages"][0]["blocks"][0]["content"] == expected
+ "url",
+ ["https://example.com/article", "https://example.com/"],
+ ids=["path-without-extension", "trailing-slash"],
+)
+def test_html_parse_server_url_accepts_extensionless_text_html(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ url: str,
+) -> None:
+ """验证无扩展名 URL 可按 HTTP text/html 响应进入 HTML Flash 路由。"""
+ expected = "Extensionless HTML"
+ response = httpx.Response(
+ 200,
+ content=f"<html><body><p>{expected}</p></body></html>".encode(),
+ headers={"Content-Type": "text/html; charset=utf-8"},
+ request=httpx.Request("GET", url),
+ )
+ client = AsyncMock()
+ client.__aenter__.return_value = client
+ client.get.return_value = response
+ monkeypatch.setattr(api_server, "httpx", SimpleNamespace(AsyncClient=lambda **_: client))
+ file_store = FileStore(tmp_path / "api-files")
+ request = CreateJobRequest.model_validate(
+ {
+ "files": [{"source": {"type": "url", "url": url}}],
+ "tier": "standard",
+ "output_formats": ["middle_json"],
+ }
+ )
+ record = api_server.JobStore().create(request, file_store)
+
+ asyncio.run(
+ api_server._run_job(
+ record,
+ request,
+ file_store,
+ ocr_mode="auto",
+ image_analysis=True,
+ )
+ )
+
+ parsed_file = record.files[0]
+ assert parsed_file.status == "completed"
+ assert parsed_file.output_files is not None and parsed_file.output_files.middle_json is not None
+ middle_record = file_store.get_file(parsed_file.output_files.middle_json.file_id)
+ assert middle_record.sha256sum is not None
+ middle_payload = json.loads(file_store.read_blob(middle_record.sha256sum))
+ assert middle_payload["pages"][0]["blocks"][0]["content"] == expected
+
+
def test_html_auto_selection_preserves_all_repeated_forum_posts() -> None:
"""验证重复 article 场景不会只保留论坛中的首个帖子。"""
payload = b"""<html><body><header>Forum</header><main>
@@ -2145,6 +2196,29 @@ def test_html_formula_priority_delimiters_and_supported_mathml_are_normalized()
assert equations == ["display_value"]
+ ("attributes", "stylesheet"),
+ [
+ ("hidden", ""),
+ ('aria-hidden="true"', ""),
+ ('style="display:none"', ""),
+ ('class="hidden-formula"', "<style>.hidden-formula{display:none}</style>"),
+ ],
+ ids=["hidden", "aria-hidden", "inline-style", "stylesheet-class"],
+)
+def test_html_formula_normalization_preserves_direct_visibility(attributes: str, stylesheet: str) -> None:
+ """验证公式 carrier 归一化后仍保留直接声明的隐藏语义。"""
+ payload = (
+ f"<html><head>{stylesheet}</head><body><p>Before <math {attributes} data-tex='x'></math> After</p></body></html>"
+ ).encode()
+
+ middle = doc_analyze(payload, file_suffix="html")[0]
+ markdown = render_markdown(middle)
+
+ assert "$x$" not in markdown
+ assert "Before" in markdown and "After" in markdown
+
+
def test_html_block_formulas_nested_in_text_containers_preserve_dom_order() -> None:
"""验证文本容器内的 display 公式切成独立 Equation,并保留前后阅读顺序。"""
payload = b"""<html><body><p>Before<script type="math/tex; mode=display">x</script>Between