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: standardize polling intervals and timeout for API job processing
myhloli5caf1abea92f
diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.pyindex a4f659da..ebc37f07 100644--- a/mineru/parser/api_client.py+++ b/mineru/parser/api_client.py@@ -26,6 +26,10 @@ from ..types import PageInfo, Tier, validate_tierfrom ..utils.image_payload import validate_image_sidecar_pathfrom .base import DocumentParser, ParseResult+_POLL_INTERVAL_SECONDS = 1+_POLL_MAX_ATTEMPTS = 3600+_TERMINAL_JOB_STATUSES = {"completed", "partial", "failed", "canceled"}+class MinerUApiParser(DocumentParser):"""Parser that delegates to a MinerU v1 API server.@@ -223,7 +227,7 @@ class MinerUApiParser(DocumentParser):with httpx.Client(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:r = cli.post(f"{self._base}/v1/parse/jobs", headers=self._headers(), json=payload)job = self._check(r)- if job.get("status") not in ("completed", "partial", "failed", "canceled"):+ if job.get("status") not in _TERMINAL_JOB_STATUSES:# poll if wait timed outjob = self._poll(cli, job["job_id"])return job@@ -232,30 +236,26 @@ class MinerUApiParser(DocumentParser):async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:r = await cli.post(f"{self._base}/v1/parse/jobs", headers=self._headers(), json=payload)job = self._check(r)- if job.get("status") not in ("completed", "partial", "failed", "canceled"):+ if job.get("status") not in _TERMINAL_JOB_STATUSES:job = await self._async_poll(cli, job["job_id"])return jobdef _poll(self, cli: Any, job_id: str) -> dict[str, Any]:- delay = 2- for _ in range(150): # max 5 min- time.sleep(delay)+ for _ in range(_POLL_MAX_ATTEMPTS): # max 1 hour+ time.sleep(_POLL_INTERVAL_SECONDS)r = cli.get(f"{self._base}/v1/parse/jobs/{job_id}", headers=self._headers())job = self._check(r)- if job.get("status") in ("completed", "partial", "failed", "canceled"):+ if job.get("status") in _TERMINAL_JOB_STATUSES:return job- delay = min(delay * 2, 30)raise _V1APIError("timeout", f"Job {job_id} did not complete within timeout")async def _async_poll(self, cli: Any, job_id: str) -> dict[str, Any]:- delay = 2- for _ in range(150):- await asyncio.sleep(delay)+ for _ in range(_POLL_MAX_ATTEMPTS):+ await asyncio.sleep(_POLL_INTERVAL_SECONDS)r = await cli.get(f"{self._base}/v1/parse/jobs/{job_id}", headers=self._headers())job = self._check(r)- if job.get("status") in ("completed", "partial", "failed", "canceled"):+ if job.get("status") in _TERMINAL_JOB_STATUSES:return job- delay = min(delay * 2, 30)raise _V1APIError("timeout", f"Job {job_id} did not complete within timeout")# ── build ParseResult ────────────────────────────────────────────diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 0c783fb2..ac1f11d1 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -489,6 +489,69 @@ def test_api_client_passes_trust_env_from_api_url(monkeypatch: pytest.MonkeyPatcassert calls == [False, True]+def test_api_client_poll_uses_fixed_one_second_interval(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证同步 v1 job 轮询使用固定 1 秒间隔,避免指数退避放大本地等待。"""+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="high")+ statuses = iter(["pending", "processing", "completed"])+ sleep_delays: list[int] = []++ def fake_sleep(delay: int) -> None:+ """记录同步轮询 sleep 参数,避免测试真的等待。"""+ sleep_delays.append(delay)++ def fake_get(url: str, headers: dict[str, str]) -> object:+ """按顺序返回 job 状态,模拟第三次轮询完成。"""+ assert url == "http://localhost:8000/v1/parse/jobs/job_1"+ assert headers == {}+ status = next(statuses)+ return types.SimpleNamespace(+ status_code=200,+ text="",+ json=lambda: {"job_id": "job_1", "status": status},+ )++ monkeypatch.setattr(api_client.time, "sleep", fake_sleep)++ job = parser._poll(types.SimpleNamespace(get=fake_get), "job_1")++ assert job["status"] == "completed"+ assert sleep_delays == [1, 1, 1]+++def test_async_api_client_poll_uses_fixed_one_second_interval(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证异步 v1 job 轮询也使用固定 1 秒间隔,保持 Gradio 路径一致。"""+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="high")+ statuses = iter(["pending", "processing", "completed"])+ sleep_delays: list[int] = []++ async def fake_sleep(delay: int) -> None:+ """记录异步轮询 sleep 参数,避免测试真的等待。"""+ sleep_delays.append(delay)++ async def fake_get(url: str, headers: dict[str, str]) -> object:+ """按顺序返回 job 状态,模拟第三次异步轮询完成。"""+ assert url == "http://localhost:8000/v1/parse/jobs/job_1"+ assert headers == {}+ status = next(statuses)+ return types.SimpleNamespace(+ status_code=200,+ text="",+ json=lambda: {"job_id": "job_1", "status": status},+ )++ monkeypatch.setattr(api_client.asyncio, "sleep", fake_sleep)++ job = asyncio.run(parser._async_poll(types.SimpleNamespace(get=fake_get), "job_1"))++ assert job["status"] == "completed"+ assert sleep_delays == [1, 1, 1]+++def test_api_client_poll_timeout_budget_is_one_hour() -> None:+ """验证 v1 job 轮询最大等待预算为 1 小时。"""+ assert api_client._POLL_INTERVAL_SECONDS * api_client._POLL_MAX_ATTEMPTS == 60 * 60++def test_api_client_omits_tier_when_unspecified(tmp_path: Path) -> None:pdf = tmp_path / "demo.pdf"pdf.write_bytes(b"%PDF-1.7\n")