Skip to content

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

fix: enforce HTML source policies

myhlolib5ce7b008f54
diff --git a/mineru/model/flash/html/document.py b/mineru/model/flash/html/document.py
index 3bb94468..94fc68ff 100644
--- a/mineru/model/flash/html/document.py
+++ b/mineru/model/flash/html/document.py
@@ -117,7 +117,10 @@ def parse_html_document(file_bytes: bytes, source_context: HtmlSourceContext | N
(
value
for element in root.iter()
- if isinstance(element.tag, str) and local_name(element) == "base" and (value := (element.get("href") or "").strip())
+ if isinstance(element.tag, str)
+ and local_name(element) == "base"
+ and not _has_discarded_active_ancestor(element)
+ and (value := (element.get("href") or "").strip())
),
None,
)
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index 97b09793..a415b629 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -1232,8 +1232,13 @@ def _source_name(source: FileSource, file_store: FileStore | None = None) -> str
return "unknown"
-def _job_has_only_flash_only_inputs(req: CreateJobRequest, file_store: FileStore) -> bool:
- return all(is_flash_only_parse_extension(_source_name(entry.source, file_store)) for entry in req.files)
+def _job_can_default_to_flash(req: CreateJobRequest, file_store: FileStore) -> bool:
+ """判断整批输入是否已知为 Flash-only,或需下载后识别类型的无扩展名 URL。"""
+ return all(
+ is_flash_only_parse_extension(_source_name(entry.source, file_store))
+ or (isinstance(entry.source, UrlSource) and not pathlib.Path(_source_name(entry.source)).suffix)
+ for entry in req.files
+ )
def _job_has_any_flash_only_inputs(req: CreateJobRequest, file_store: FileStore) -> bool:
@@ -1354,6 +1359,7 @@ async def _run_job(
allow_local_source: bool = False,
max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,
allow_http_source: bool = False,
+ flash_enabled: bool = True,
) -> None:
rec.status = "running"
rec.started_at = JobStore._now()
@@ -1381,6 +1387,8 @@ async def _run_job(
suffix = ".html"
if not stype:
raise ValueError(f"Unsupported file type: {fr.name}")
+ if not flash_enabled and is_flash_only_parse_extension(stype):
+ raise ValueError("Flash parsing is disabled in this server, but this input requires the Flash backend")
# write to temp file for parsers that require a path
suffix = suffix or ".pdf"
@@ -1809,7 +1817,7 @@ async def create_job(
# 按请求 tier 选择启动时预先解析好的 runtime;全轻量输入可按 ADR-0024 直接归一到 flash 执行。
default_tier: Tier | None = request.app.state.default_tier
- only_flash_only_inputs = _job_has_only_flash_only_inputs(body, file_store)
+ can_default_to_flash = _job_can_default_to_flash(body, file_store)
if not request.app.state.flash_enabled and _job_has_any_flash_only_inputs(body, file_store):
_raise_api_error(
400,
@@ -1819,7 +1827,7 @@ async def create_job(
param="files",
)
if body.tier is None and default_tier is None:
- if only_flash_only_inputs:
+ if can_default_to_flash:
body.tier = "flash"
else:
_raise_api_error(
@@ -1835,7 +1843,7 @@ async def create_job(
body.tier = body.tier or default_tier
runtime_options: dict[Tier, ParserRuntimeOptions] = request.app.state.tier_runtime_options
runtime = runtime_options.get(body.tier)
- if runtime is None and only_flash_only_inputs:
+ if runtime is None and can_default_to_flash:
runtime = runtime_options.get("flash") or runtime_options_for_tier("flash")
if runtime is None:
_raise_api_error(
@@ -1857,6 +1865,7 @@ async def create_job(
allow_local_source_val: bool = request.app.state.allow_local_source
max_inline_bytes_val: int = request.app.state.max_inline_bytes
allow_http_source_val: bool = request.app.state.allow_http_source
+ flash_enabled_val: bool = request.app.state.flash_enabled
ocr_mode_val: str = request.app.state.ocr_mode
image_analysis_val: bool = request.app.state.image_analysis
@@ -1873,6 +1882,7 @@ async def create_job(
allow_local_source=allow_local_source_val,
max_inline_bytes=max_inline_bytes_val,
allow_http_source=allow_http_source_val,
+ flash_enabled=flash_enabled_val,
)
asyncio.create_task(_bg_run())
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 57d4b3d2..fb2d2031 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -13,6 +13,7 @@ from zipfile import ZipFile
import httpx
import pytest
from bs4 import BeautifulSoup
+from fastapi.testclient import TestClient
from lxml import etree, html as lxml_html # type: ignore[reportMissingImports]
from PIL import Image
@@ -392,6 +393,74 @@ def test_html_parse_server_url_accepts_extensionless_text_html(
assert middle_payload["pages"][0]["blocks"][0]["content"] == expected
+def test_html_parse_server_flash_only_admits_extensionless_url(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 Flash-only server 在下载识别类型前不会拒绝无扩展名 URL。"""
+
+ async def fake_run_job(*args: object, **kwargs: object) -> None:
+ """跳过后台解析,仅验证 admission 已选择 Flash tier。"""
+
+ monkeypatch.setattr(api_server, "_run_job", fake_run_job)
+ app = api_server.create_app(upload_dir=str(tmp_path / "api"), tier="flash")
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/jobs",
+ json={"files": [{"source": {"type": "url", "url": "https://example.com/article"}}]},
+ )
+
+ assert response.status_code == 202
+ assert response.json()["tier"] == "flash"
+
+
+def test_html_parse_server_no_flash_rejects_extensionless_text_html_after_fetch(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证无扩展名 URL 下载为 HTML 后仍执行禁用 Flash 的后置策略检查。"""
+ url = "https://example.com/article"
+ response = httpx.Response(
+ 200,
+ content=b"<html><body><p>HTML</p></body></html>",
+ 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
+ parse_async_mock = AsyncMock()
+ monkeypatch.setattr(api_server, "httpx", SimpleNamespace(AsyncClient=lambda **_: client))
+ monkeypatch.setattr(api_server, "parse_async", parse_async_mock)
+ file_store = FileStore(tmp_path / "api-files")
+ request = CreateJobRequest.model_validate(
+ {
+ "files": [{"source": {"type": "url", "url": url}}],
+ "tier": "standard",
+ }
+ )
+ record = api_server.JobStore().create(request, file_store)
+
+ asyncio.run(
+ api_server._run_job(
+ record,
+ request,
+ file_store,
+ ocr_mode="auto",
+ image_analysis=True,
+ flash_enabled=False,
+ )
+ )
+
+ assert record.status == "failed"
+ assert record.files[0].error is not None
+ assert record.files[0].error.message == (
+ "Flash parsing is disabled in this server, but this input requires the Flash backend"
+ )
+ parse_async_mock.assert_not_awaited()
+
+
def test_html_auto_selection_preserves_all_repeated_forum_posts() -> None:
"""验证重复 article 场景不会只保留论坛中的首个帖子。"""
payload = b"""<html><body><header>Forum</header><main>
@@ -718,6 +787,18 @@ def test_html_fragment_only_link_honors_external_base_document() -> None:
assert "https://example.com/other.html#fn1" in markdown
+def test_html_ignores_base_inside_discarded_template() -> None:
+ """验证惰性 template 中的 base 不会改写正文相对链接。"""
+ payload = b"""<html><head><template><base href="https://discarded.example/assets/"></template></head>
+ <body><main><h1>Title</h1><p><a href="article.html">Relative link</a></p></main></body></html>"""
+ context = HtmlSourceContext(source_uri="https://origin.example/docs/page.html")
+
+ markdown = render_markdown(doc_analyze(payload, file_suffix="html", source_context=context)[0])
+
+ assert "https://origin.example/docs/article.html" in markdown
+ assert "discarded.example" not in markdown
+
+
def test_html_formula_wrapper_stops_after_second_non_nested_carrier(monkeypatch: pytest.MonkeyPatch) -> None:
"""验证通用公式 wrapper 发现第二个并列 carrier 后立即失败,不继续扫描全部公式。"""
wrapper = lxml_html.fromstring('<div class="math">' + "<math></math>" * 1_000 + "</div>")