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
fix: address URL fallback and preview trace navigation
myhloli95892d7d1fc5
diff --git a/mineru/parser/url_source.py b/mineru/parser/url_source.pyindex ce9c0f78..77b73a96 100644--- a/mineru/parser/url_source.py+++ b/mineru/parser/url_source.py@@ -78,6 +78,8 @@ class UrlSourceTransport(httpx.AsyncHTTPTransport):remaining = deadline - time.monotonic() if deadline is not None else Noneif remaining is not None and remaining <= 0:raise httpx.ConnectTimeout("URL source connection timed out", request=request)+ # 按剩余候选地址均分连接预算,首个地址超时后仍有时间回退。+ attempt_timeout = remaining / (len(addresses) - index) if remaining is not None else Nonepinned = httpx.Request(method=request.method,url=request.url.copy_with(host=address),@@ -86,7 +88,7 @@ class UrlSourceTransport(httpx.AsyncHTTPTransport):extensions={**request.extensions,"sni_hostname": request.url.raw_host.decode("ascii"),- "timeout": {**timeouts, "connect": remaining},+ "timeout": {**timeouts, "connect": attempt_timeout},},)try:diff --git a/mineru/resources/gradio_trace_html.js b/mineru/resources/gradio_trace_html.jsindex da57bb17..4edaac5d 100644--- a/mineru/resources/gradio_trace_html.js+++ b/mineru/resources/gradio_trace_html.js@@ -28,7 +28,8 @@const positionNavigation = () => {if (!selected) return;const rect = selected.getBoundingClientRect();- navigation.style.top = `${Math.max(8, Math.min(innerHeight - navigation.offsetHeight - 8, rect.top))}px`;+ const offset = parseFloat(getComputedStyle(document.body).getPropertyValue("--mineru-preview-offset")) || 8;+ navigation.style.top = `${Math.max(offset, Math.min(innerHeight - navigation.offsetHeight - 8, rect.top))}px`;};// 仅调整结果 iframe 自身滚动,避免带动整个 Gradio 页面。const align = () => {diff --git a/mineru/resources/pdf_preview/trace.mjs b/mineru/resources/pdf_preview/trace.mjsindex fc07bfde..68e03687 100644--- a/mineru/resources/pdf_preview/trace.mjs+++ b/mineru/resources/pdf_preview/trace.mjs@@ -41,7 +41,13 @@ export function installTrace({ viewer, eventBus, container, documentId, messagesif (!box) return;const rect = box.getBoundingClientRect();const host = container.getBoundingClientRect();+ // 放大后同时沿横纵方向对齐,超宽区域保留左侧起始部分可见。container.scrollTo({+ left:+ container.scrollLeft ++ rect.left -+ host.left -+ Math.max(16, (container.clientWidth - Math.min(rect.width, container.clientWidth - 32)) / 2),top:container.scrollTop +rect.top -diff --git a/tests/unittest/test_kit_gradio_trace.cjs b/tests/unittest/test_kit_gradio_trace.cjsindex 7663b161..dbbede55 100644--- a/tests/unittest/test_kit_gradio_trace.cjs+++ b/tests/unittest/test_kit_gradio_trace.cjs@@ -56,3 +56,92 @@ emit(pdf, { type: "select", id: entry.id }, location.origin);assert.equal(delivered.length, switched);window.__mineruTrace.reset();console.log("Trace identity, handshake and bidirectional routing passed");++// 执行完整正文脚本,验证滚动后的跨页按钮避开目录工具栏并受视口边界限制。+const checkHtmlNavigation = (offset, blockTop, expectedTop) => {+ const htmlHandlers = {};+ const navigation = {+ style: {}, offsetHeight: 30,+ setAttribute() {}, replaceChildren() {}, append() {}+ };+ const selected = {+ dataset: {+ docvortexTraceId: entry.id,+ docvortexSources: JSON.stringify(entry.sources.map(source => ({ ...source, child_path: [] })))+ },+ setAttribute() {}, removeAttribute() {},+ getBoundingClientRect: () => ({ top: blockTop })+ };+ const htmlParent = { postMessage() {} };+ const context = {+ parent: htmlParent, navigator: { language: "en" }, innerHeight: 600,+ document: {+ querySelectorAll: () => [selected],+ createElement: tag => tag === "nav" ? navigation : { setAttribute() {}, addEventListener() {} },+ body: { append() {} }, addEventListener() {}+ },+ window: { addEventListener: (name, callback) => { htmlHandlers[name] = callback; } },+ getComputedStyle: () => ({ getPropertyValue: () => offset }),+ // 此用例仅驱动滚动事件,尺寸观察器保留生产注册入口。+ ResizeObserver: class { observe() {} }+ };+ const source = fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_trace_html.js"), "utf8");+ vm.runInNewContext(`(${source})(${JSON.stringify({+ pageLabels: ["Source page", "来源页"], documentId: "one", parentOrigin: location.origin, pageIndices: [2, 5]+ })})`, context);+ htmlHandlers.message({ source: htmlParent, origin: location.origin, data: {+ channel: "mineru-trace", documentId: "one", type: "select", id: entry.id, pageIdx: 2, scroll: false+ } });+ htmlHandlers.scroll();+ assert.equal(navigation.hidden, false);+ assert.equal(navigation.style.top, `${expectedTop}px`);+};+checkHtmlNavigation("52px", -100, 52);+checkHtmlNavigation("", -100, 8);+checkHtmlNavigation("52px", 250, 250);+checkHtmlNavigation("52px", 700, 562);+console.log("HTML source-page controls respect the outline toolbar and viewport");++// 执行 PDF 溯源入口,用放大后的真实边界语义检查横纵两个方向的定位。+const pdfHandlers = {};+const pdfParent = { postMessage() {} };+const scrolls = [];+let boxRect = { left: 950, top: 800, width: 100, height: 80 };+const pdfBox = { traceIds: [entry.id], getBoundingClientRect: () => boxRect };+const container = {+ scrollTop: 300, scrollLeft: 200, clientWidth: 500, clientHeight: 600,+ getBoundingClientRect: () => ({ left: 100, top: 40 }),+ scrollTo: options => scrolls.push(options)+};+const pdfContext = {+ parent: pdfParent, location, AbortController, container,+ document: {+ createElement: () => ({ setAttribute() {}, addEventListener() {} }),+ getElementById: () => ({ append() {} })+ },+ window: { addEventListener: (name, callback) => { pdfHandlers[name] = callback; } },+ viewer: {+ getPageView: () => ({ div: { querySelector: () => ({ children: [pdfBox] }) } }),+ getCachedPageViews: () => [], scrollPageIntoView() {}+ },+ eventBus: { on() {}, off() {} }+};+const pdfScript = fs.readFileSync(path.join(__dirname, "../../mineru/resources/pdf_preview/trace.mjs"), "utf8");+vm.runInNewContext(`${pdfScript.replace("export function", "function")}+installTrace({ viewer, eventBus, container, documentId: "one", messages: {} });`, pdfContext);+// 模拟已验证的父页面消息,复用生产 init/select 的完整分发路径。+const emitPdf = data => pdfHandlers.message({ source: pdfParent, origin: location.origin, data: {+ channel: "mineru-trace", documentId: "one", ...data+} });+emitPdf({ type: "init", entries: [entry], pageIndices: [2, 5] });+emitPdf({ type: "select", id: entry.id, pageIdx: 2, scroll: true });+assert.equal(scrolls.at(-1).top, 800);+assert.equal(scrolls.at(-1).left, 850);+// 已经横向滚动后再定位左侧及超宽区域,均把区域起始部分带回可见范围。+boxRect = { left: -50, top: 800, width: 100, height: 80 };+emitPdf({ type: "select", id: entry.id, pageIdx: 2, scroll: true });+assert.ok(scrolls.at(-1).left <= 0);+boxRect = { left: 950, top: 800, width: 700, height: 80 };+emitPdf({ type: "select", id: entry.id, pageIdx: 2, scroll: true });+assert.equal(scrolls.at(-1).left, 1034);+console.log("PDF source navigation handles horizontal zoom overflow");diff --git a/tests/unittest/test_url_source_security.py b/tests/unittest/test_url_source_security.pyindex 4e9b9aea..6799791b 100644--- a/tests/unittest/test_url_source_security.py+++ b/tests/unittest/test_url_source_security.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport socketfrom pathlib import Path+from types import SimpleNamespacefrom typing import Anyimport httpx@@ -159,30 +160,47 @@ def test_pin_ip_preserve_host_sni_and_signed_url(assert extracted.data == HTML[email protected]("failure", ["refused", "timeout"])def test_dns_rebinding_and_connection_fallback(- dns: tuple[list[str], list[str]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ dns: tuple[list[str], list[str]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, failure: str) -> None:- """首个地址失败后仅使用首次校验过的候选地址,DNS 变更不会重新进入连接。"""+ """首个地址拒绝或耗尽分配时间后仍能回退,且仅使用首次校验过的候选地址。"""addresses, dns_calls = dnsaddresses[:] = ["2606:4700:4700::1111", "93.184.216.34", "93.184.216.34"]connections: list[httpx.Request] = []+ started_at = 100.0+ timeout = 60+ now = started_at++ def monotonic() -> float:+ """提供可控时钟,确定性模拟连接耗尽预算而无需实际等待。"""+ return now++ monkeypatch.setattr(url_source, "time", SimpleNamespace(monotonic=monotonic))async def respond(self: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:"""首个 IPv6 连接失败时把后续 DNS 应答改成回环地址。"""+ nonlocal nowconnections.append(request)if len(connections) == 1:addresses[:] = ["127.0.0.1"]+ if failure == "timeout":+ now += request.extensions["timeout"]["connect"]+ raise httpx.ConnectTimeout("simulated black-holed IPv6")raise httpx.ConnectError("simulated unreachable IPv6")return httpx.Response(200, content=HTML)monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", respond)extracted = asyncio.run(- api_server._extract_bytes(api_server._UrlSource(url="https://source.example/a.html"), api_server.FileStore(tmp_path))+ api_server._extract_bytes(+ api_server._UrlSource(url="https://source.example/a.html"), api_server.FileStore(tmp_path), url_timeout=timeout+ ))assert extracted.data == HTMLassert dns_calls == ["source.example"]assert [request.url.host for request in connections] == ["2606:4700:4700::1111", "93.184.216.34"]- assert connections[1].extensions["timeout"]["connect"] <= connections[0].extensions["timeout"]["connect"]+ assert 0 < connections[0].extensions["timeout"]["connect"] <= timeout / 2+ assert 0 < connections[1].extensions["timeout"]["connect"] <= started_at + timeout - nowdef test_redirect_target_is_never_requested(