zero-agent-core-mineru 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .mypy_cache/
7
+ .coverage
8
+ htmlcov/
9
+ dist/
10
+ build/
11
+
12
+ site/
13
+ *.db
14
+ *.sqlite
15
+ *.sqlite3
16
+ .venv/*
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Agent Core contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.5
2
+ Name: zero-agent-core-mineru
3
+ Version: 0.1.0
4
+ Summary: Handwritten Agent Core 的 MinerU 文档解析扩展
5
+ Project-URL: Homepage, https://github.com/qiuzixu/agent-core
6
+ Project-URL: Repository, https://github.com/qiuzixu/agent-core
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: <3.14,>=3.13
15
+ Requires-Dist: httpx<1,>=0.28
16
+ Requires-Dist: zero-agent-core<0.3,>=0.2.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: mypy<2,>=1.18; extra == 'dev'
19
+ Requires-Dist: pytest-asyncio<2,>=1.3; extra == 'dev'
20
+ Requires-Dist: pytest<10,>=9; extra == 'dev'
21
+ Requires-Dist: ruff<1,>=0.14; extra == 'dev'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Handwritten Agent Core MinerU
25
+
26
+ `zero-agent-core-mineru` 是 Agent Core 的可选文档解析扩展。它调用已经部署好的 MinerU
27
+ 自托管 `/file_parse` HTTP 服务,把 Markdown 或 `content_list` 转换成 Core `Document`。
28
+
29
+ ```bash
30
+ pip install zero-agent-core-mineru
31
+ ```
32
+
33
+ ```python
34
+ from agent_core_mineru import MinerUConfig, MinerUDocumentLoader
35
+
36
+ loader = MinerUDocumentLoader(
37
+ "./manual.pdf",
38
+ config=MinerUConfig(endpoint="http://127.0.0.1:8000/file_parse"),
39
+ )
40
+ documents = await loader.load()
41
+ ```
42
+
43
+ 本包不安装 MinerU、OCR 模型或 GPU 运行时。MinerU 云端异步批处理 API 使用不同协议,可以实现
44
+ `MinerUTransport` 后注入。
@@ -0,0 +1,21 @@
1
+ # Handwritten Agent Core MinerU
2
+
3
+ `zero-agent-core-mineru` 是 Agent Core 的可选文档解析扩展。它调用已经部署好的 MinerU
4
+ 自托管 `/file_parse` HTTP 服务,把 Markdown 或 `content_list` 转换成 Core `Document`。
5
+
6
+ ```bash
7
+ pip install zero-agent-core-mineru
8
+ ```
9
+
10
+ ```python
11
+ from agent_core_mineru import MinerUConfig, MinerUDocumentLoader
12
+
13
+ loader = MinerUDocumentLoader(
14
+ "./manual.pdf",
15
+ config=MinerUConfig(endpoint="http://127.0.0.1:8000/file_parse"),
16
+ )
17
+ documents = await loader.load()
18
+ ```
19
+
20
+ 本包不安装 MinerU、OCR 模型或 GPU 运行时。MinerU 云端异步批处理 API 使用不同协议,可以实现
21
+ `MinerUTransport` 后注入。
@@ -0,0 +1,62 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "zero-agent-core-mineru"
7
+ version = "0.1.0"
8
+ description = "Handwritten Agent Core 的 MinerU 文档解析扩展"
9
+ readme = "README.md"
10
+ requires-python = ">=3.13,<3.14"
11
+ license = "Apache-2.0"
12
+ dependencies = [
13
+ "zero-agent-core>=0.2.0,<0.3",
14
+ "httpx>=0.28,<1",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/qiuzixu/agent-core"
26
+ Repository = "https://github.com/qiuzixu/agent-core"
27
+
28
+ [project.optional-dependencies]
29
+ dev = [
30
+ "mypy>=1.18,<2",
31
+ "pytest>=9,<10",
32
+ "pytest-asyncio>=1.3,<2",
33
+ "ruff>=0.14,<1",
34
+ ]
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/agent_core_mineru"]
38
+
39
+ [tool.uv.sources]
40
+ zero-agent-core = { path = "../..", editable = true }
41
+
42
+ [tool.pytest.ini_options]
43
+ addopts = "-ra"
44
+ asyncio_mode = "auto"
45
+ testpaths = ["tests"]
46
+
47
+ [tool.ruff]
48
+ line-length = 110
49
+ target-version = "py313"
50
+
51
+ [tool.ruff.lint]
52
+ select = ["E", "F", "I", "UP", "B", "ASYNC", "RUF"]
53
+ ignore = ["RUF001", "RUF002", "RUF003"]
54
+
55
+ [tool.mypy]
56
+ python_version = "3.13"
57
+ strict = true
58
+ files = ["src"]
59
+
60
+ [[tool.mypy.overrides]]
61
+ module = ["httpx"]
62
+ ignore_missing_imports = true
@@ -0,0 +1,14 @@
1
+ """Agent Core 的 MinerU 文档解析扩展。"""
2
+
3
+ from agent_core_mineru.config import MinerUConfig, MinerUOutputMode
4
+ from agent_core_mineru.parser import MinerUBlobParser, MinerUDocumentLoader
5
+ from agent_core_mineru.transport import HttpxMinerUTransport, MinerUTransport
6
+
7
+ __all__ = [
8
+ "HttpxMinerUTransport",
9
+ "MinerUBlobParser",
10
+ "MinerUConfig",
11
+ "MinerUDocumentLoader",
12
+ "MinerUOutputMode",
13
+ "MinerUTransport",
14
+ ]
@@ -0,0 +1,50 @@
1
+ """MinerU 扩展配置。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from typing import Literal
8
+ from urllib.parse import urlparse
9
+
10
+ MinerUOutputMode = Literal["blocks", "markdown"]
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class MinerUConfig:
15
+ """MinerU ``/file_parse`` 请求配置。
16
+
17
+ 扩展包只调用已经部署好的 MinerU HTTP 服务,不负责下载模型或启动 OCR 运行时。
18
+ ``endpoint`` 应指向 MinerU 自托管服务的 ``/file_parse`` 路由。
19
+ """
20
+
21
+ endpoint: str = "http://127.0.0.1:8000/file_parse"
22
+ api_key: str | None = None
23
+ timeout_seconds: float = 300.0
24
+ backend: str = "pipeline"
25
+ parse_method: str = "auto"
26
+ language: str = "ch"
27
+ formula_enabled: bool = True
28
+ table_enabled: bool = True
29
+ start_page_id: int = 0
30
+ end_page_id: int = 99999
31
+ output_mode: MinerUOutputMode = "blocks"
32
+ parser_version: str = "mineru-http-v1"
33
+ max_file_bytes: int = 100 * 1024 * 1024
34
+ headers: Mapping[str, str] = field(default_factory=dict)
35
+ extra_form_fields: Mapping[str, str] = field(default_factory=dict)
36
+
37
+ def __post_init__(self) -> None:
38
+ parsed = urlparse(self.endpoint)
39
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
40
+ raise ValueError("MinerU endpoint 必须是有效的 http 或 https URL")
41
+ if self.timeout_seconds <= 0:
42
+ raise ValueError("timeout_seconds 必须大于 0")
43
+ if self.start_page_id < 0:
44
+ raise ValueError("start_page_id 不能小于 0")
45
+ if self.end_page_id < self.start_page_id:
46
+ raise ValueError("end_page_id 不能小于 start_page_id")
47
+ if self.max_file_bytes <= 0:
48
+ raise ValueError("max_file_bytes 必须大于 0")
49
+ if not self.parser_version.strip():
50
+ raise ValueError("parser_version 不能为空")
@@ -0,0 +1,262 @@
1
+ """MinerU 响应到 Agent Core Document 的转换。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import mimetypes
8
+ import uuid
9
+ from collections.abc import AsyncIterator, Mapping
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from agent_core import Blob, Document, DocumentLocator, DocumentParsingError, DocumentServiceError
14
+
15
+ from agent_core_mineru.config import MinerUConfig
16
+ from agent_core_mineru.transport import HttpxMinerUTransport, MinerUTransport, source_filename
17
+
18
+
19
+ class MinerUBlobParser:
20
+ """把 MinerU Markdown 或 content list 响应转换成 Core Document。"""
21
+
22
+ def __init__(
23
+ self,
24
+ config: MinerUConfig | None = None,
25
+ *,
26
+ transport: MinerUTransport | None = None,
27
+ ) -> None:
28
+ self._config = config or MinerUConfig()
29
+ self._transport = transport or HttpxMinerUTransport()
30
+
31
+ async def parse(self, blob: Blob) -> list[Document]:
32
+ if not blob.data:
33
+ raise DocumentParsingError("不能解析空文件")
34
+ if len(blob.data) > self._config.max_file_bytes:
35
+ raise DocumentParsingError(
36
+ f"文件大小 {len(blob.data)} 字节超过限制 {self._config.max_file_bytes} 字节"
37
+ )
38
+
39
+ payload = await self._transport.parse(blob, config=self._config)
40
+ result = _resolve_result(payload, source_filename(blob.source))
41
+ _raise_for_service_error(payload, result)
42
+
43
+ blocks = _read_blocks(result)
44
+ block_documents = self._build_block_documents(blob, blocks, result)
45
+ markdown = _read_text(result, ("md_content", "markdown", "content", "text"))
46
+
47
+ if self._config.output_mode == "blocks" and block_documents:
48
+ return block_documents
49
+ if markdown:
50
+ return [self._build_markdown_document(blob, markdown, result, len(blocks))]
51
+ if block_documents:
52
+ merged = "\n\n".join(document.content for document in block_documents)
53
+ return [self._build_markdown_document(blob, merged, result, len(blocks))]
54
+ raise DocumentParsingError("MinerU 响应中没有可用的 Markdown 或文本区块")
55
+
56
+ def _build_block_documents(
57
+ self,
58
+ blob: Blob,
59
+ blocks: list[Mapping[str, Any]],
60
+ result: Mapping[str, Any],
61
+ ) -> list[Document]:
62
+ documents: list[Document] = []
63
+ source_key = blob.source or f"blob:{blob.checksum}"
64
+ mineru_version = _read_scalar_text(result, ("version", "mineru_version"))
65
+ for index, block in enumerate(blocks):
66
+ content = _block_content(block)
67
+ if not content:
68
+ continue
69
+ page = _block_page(block)
70
+ block_id = _read_scalar_text(block, ("block_id", "id")) or str(index)
71
+ block_type = _read_scalar_text(block, ("type", "block_type")) or "text"
72
+ identity = (
73
+ f"{source_key}:{blob.checksum}:{self._config.parser_version}:"
74
+ f"{page}:{block_id}:{content}"
75
+ )
76
+ metadata: dict[str, Any] = {
77
+ **blob.metadata,
78
+ "source_checksum": blob.checksum,
79
+ "parser": "mineru",
80
+ "parser_version": self._config.parser_version,
81
+ "mineru_block_index": index,
82
+ "mineru_block_type": block_type,
83
+ }
84
+ if mineru_version:
85
+ metadata["mineru_version"] = mineru_version
86
+ documents.append(
87
+ Document(
88
+ document_id=str(uuid.uuid5(uuid.NAMESPACE_URL, identity)),
89
+ content=content,
90
+ source=blob.source,
91
+ mime_type="text/markdown",
92
+ metadata=metadata,
93
+ locator=DocumentLocator(uri=blob.source, page=page, block_id=block_id),
94
+ )
95
+ )
96
+ return documents
97
+
98
+ def _build_markdown_document(
99
+ self,
100
+ blob: Blob,
101
+ markdown: str,
102
+ result: Mapping[str, Any],
103
+ block_count: int,
104
+ ) -> Document:
105
+ source_key = blob.source or f"blob:{blob.checksum}"
106
+ identity = f"{source_key}:{blob.checksum}:{self._config.parser_version}:markdown"
107
+ metadata: dict[str, Any] = {
108
+ **blob.metadata,
109
+ "source_checksum": blob.checksum,
110
+ "parser": "mineru",
111
+ "parser_version": self._config.parser_version,
112
+ "mineru_block_count": block_count,
113
+ }
114
+ mineru_version = _read_scalar_text(result, ("version", "mineru_version"))
115
+ if mineru_version:
116
+ metadata["mineru_version"] = mineru_version
117
+ return Document(
118
+ document_id=str(uuid.uuid5(uuid.NAMESPACE_URL, identity)),
119
+ content=markdown,
120
+ source=blob.source,
121
+ mime_type="text/markdown",
122
+ metadata=metadata,
123
+ locator=DocumentLocator(uri=blob.source),
124
+ )
125
+
126
+
127
+ class MinerUDocumentLoader:
128
+ """读取本地文件并通过 MinerU HTTP 服务解析。"""
129
+
130
+ def __init__(
131
+ self,
132
+ path: str | Path,
133
+ *,
134
+ config: MinerUConfig | None = None,
135
+ transport: MinerUTransport | None = None,
136
+ metadata: Mapping[str, Any] | None = None,
137
+ ) -> None:
138
+ self._path = Path(path)
139
+ self._parser = MinerUBlobParser(config, transport=transport)
140
+ self._metadata = dict(metadata or {})
141
+
142
+ async def load(self) -> list[Document]:
143
+ try:
144
+ data = await asyncio.to_thread(self._path.read_bytes)
145
+ except OSError as exc:
146
+ raise DocumentParsingError(f"读取文档失败:{self._path}") from exc
147
+ mime_type, _ = mimetypes.guess_type(self._path.name)
148
+ blob = Blob(
149
+ data=data,
150
+ source=str(self._path.resolve()),
151
+ mime_type=mime_type or "application/octet-stream",
152
+ metadata=self._metadata,
153
+ )
154
+ return await self._parser.parse(blob)
155
+
156
+ async def lazy_load(self) -> AsyncIterator[Document]:
157
+ for document in await self.load():
158
+ yield document
159
+
160
+
161
+ def _has_output_fields(value: Mapping[str, Any]) -> bool:
162
+ return any(key in value for key in ("md_content", "markdown", "content_list", "blocks"))
163
+
164
+
165
+ def _resolve_result(payload: Mapping[str, Any], filename: str) -> Mapping[str, Any]:
166
+ current = payload
167
+ for _ in range(4):
168
+ if _has_output_fields(current):
169
+ return current
170
+ data = current.get("data")
171
+ if isinstance(data, Mapping):
172
+ current = data
173
+ continue
174
+ results = current.get("results")
175
+ if isinstance(results, Mapping):
176
+ current = _select_file_result(results, filename)
177
+ continue
178
+ break
179
+ return current
180
+
181
+
182
+ def _select_file_result(results: Mapping[str, Any], filename: str) -> Mapping[str, Any]:
183
+ if _has_output_fields(results):
184
+ return results
185
+ stem = Path(filename).stem
186
+ for key in (filename, stem):
187
+ value = results.get(key)
188
+ if isinstance(value, Mapping):
189
+ return value
190
+ mappings = [value for value in results.values() if isinstance(value, Mapping)]
191
+ if len(mappings) == 1:
192
+ return mappings[0]
193
+ raise DocumentParsingError("MinerU 响应包含多个文件,但无法匹配当前文件名")
194
+
195
+
196
+ def _raise_for_service_error(
197
+ payload: Mapping[str, Any],
198
+ result: Mapping[str, Any],
199
+ ) -> None:
200
+ code = payload.get("code")
201
+ if isinstance(code, int) and code != 0:
202
+ message = _read_scalar_text(payload, ("msg", "message", "error")) or str(code)
203
+ raise DocumentServiceError(f"MinerU 解析失败:{message}")
204
+ error = _read_scalar_text(result, ("error", "err_msg"))
205
+ if error:
206
+ raise DocumentServiceError(f"MinerU 解析失败:{error}")
207
+
208
+
209
+ def _read_blocks(result: Mapping[str, Any]) -> list[Mapping[str, Any]]:
210
+ value = result.get("content_list", result.get("blocks"))
211
+ if isinstance(value, str):
212
+ try:
213
+ value = json.loads(value)
214
+ except json.JSONDecodeError as exc:
215
+ raise DocumentParsingError("MinerU content_list 不是有效 JSON") from exc
216
+ if value is None:
217
+ return []
218
+ if not isinstance(value, list):
219
+ raise DocumentParsingError("MinerU content_list 必须是数组")
220
+ return [item for item in value if isinstance(item, Mapping)]
221
+
222
+
223
+ def _block_content(block: Mapping[str, Any]) -> str:
224
+ direct = _read_text(block, ("text", "content", "md_content", "table_body", "latex"))
225
+ if direct:
226
+ return direct
227
+ for key in ("image_caption", "image_footnote", "table_caption", "table_footnote"):
228
+ value = block.get(key)
229
+ if isinstance(value, list):
230
+ parts = [str(item).strip() for item in value if str(item).strip()]
231
+ if parts:
232
+ return "\n".join(parts)
233
+ return ""
234
+
235
+
236
+ def _block_page(block: Mapping[str, Any]) -> int | None:
237
+ page_index = block.get("page_idx")
238
+ if isinstance(page_index, int) and page_index >= 0:
239
+ return page_index + 1
240
+ for key in ("page_no", "page"):
241
+ value = block.get(key)
242
+ if isinstance(value, int) and value >= 0:
243
+ return value
244
+ return None
245
+
246
+
247
+ def _read_text(value: Mapping[str, Any], keys: tuple[str, ...]) -> str:
248
+ for key in keys:
249
+ item = value.get(key)
250
+ if isinstance(item, str) and item.strip():
251
+ return item.strip()
252
+ return ""
253
+
254
+
255
+ def _read_scalar_text(value: Mapping[str, Any], keys: tuple[str, ...]) -> str:
256
+ for key in keys:
257
+ item = value.get(key)
258
+ if isinstance(item, (str, int, float)) and not isinstance(item, bool):
259
+ text = str(item).strip()
260
+ if text:
261
+ return text
262
+ return ""
@@ -0,0 +1,123 @@
1
+ """MinerU HTTP 传输实现。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+ from typing import Any, Protocol, runtime_checkable
8
+ from urllib.parse import unquote, urlparse
9
+
10
+ from agent_core import Blob, DocumentParsingError, DocumentServiceError
11
+
12
+ from agent_core_mineru.config import MinerUConfig
13
+
14
+
15
+ @runtime_checkable
16
+ class MinerUTransport(Protocol):
17
+ """MinerU 请求传输端口,便于替换认证、网关或测试实现。"""
18
+
19
+ async def parse(self, blob: Blob, *, config: MinerUConfig) -> Mapping[str, Any]: ...
20
+
21
+
22
+ class HttpxMinerUTransport:
23
+ """使用 httpx 调用 MinerU ``/file_parse`` 接口。"""
24
+
25
+ def __init__(self, client: Any | None = None) -> None:
26
+ self._client = client
27
+
28
+ async def parse(self, blob: Blob, *, config: MinerUConfig) -> Mapping[str, Any]:
29
+ filename = source_filename(blob.source)
30
+ headers = {"Accept": "application/json", **dict(config.headers)}
31
+ if config.api_key:
32
+ headers.setdefault("Authorization", f"Bearer {config.api_key}")
33
+ form = {
34
+ "backend": config.backend,
35
+ "parse_method": config.parse_method,
36
+ "lang_list": config.language,
37
+ "formula_enable": _form_bool(config.formula_enabled),
38
+ "table_enable": _form_bool(config.table_enabled),
39
+ "return_md": "true",
40
+ "return_content_list": "true",
41
+ "return_images": "false",
42
+ "start_page_id": str(config.start_page_id),
43
+ "end_page_id": str(config.end_page_id),
44
+ **dict(config.extra_form_fields),
45
+ }
46
+ files = {
47
+ "files": (
48
+ filename,
49
+ blob.data,
50
+ blob.mime_type or "application/octet-stream",
51
+ )
52
+ }
53
+
54
+ if self._client is not None:
55
+ return await self._post(
56
+ self._client,
57
+ config=config,
58
+ headers=headers,
59
+ form=form,
60
+ files=files,
61
+ )
62
+
63
+ import httpx
64
+
65
+ try:
66
+ async with httpx.AsyncClient() as client:
67
+ return await self._post(
68
+ client,
69
+ config=config,
70
+ headers=headers,
71
+ form=form,
72
+ files=files,
73
+ )
74
+ except DocumentServiceError:
75
+ raise
76
+ except Exception as exc:
77
+ raise DocumentServiceError(f"MinerU 服务调用失败:{exc}") from exc
78
+
79
+ @staticmethod
80
+ async def _post(
81
+ client: Any,
82
+ *,
83
+ config: MinerUConfig,
84
+ headers: Mapping[str, str],
85
+ form: Mapping[str, str],
86
+ files: Mapping[str, tuple[str, bytes, str]],
87
+ ) -> Mapping[str, Any]:
88
+ try:
89
+ response = await client.post(
90
+ config.endpoint,
91
+ headers=dict(headers),
92
+ data=dict(form),
93
+ files=dict(files),
94
+ timeout=config.timeout_seconds,
95
+ )
96
+ except Exception as exc:
97
+ raise DocumentServiceError(f"MinerU 服务调用失败:{exc}") from exc
98
+
99
+ status_code = int(getattr(response, "status_code", 0))
100
+ if status_code < 200 or status_code >= 300:
101
+ response_text = str(getattr(response, "text", ""))[:500]
102
+ raise DocumentServiceError(f"MinerU 服务返回 HTTP {status_code}:{response_text}")
103
+ try:
104
+ payload = response.json()
105
+ except Exception as exc:
106
+ raise DocumentParsingError("MinerU 服务返回了无效 JSON") from exc
107
+ if not isinstance(payload, Mapping):
108
+ raise DocumentParsingError("MinerU 响应根节点必须是对象")
109
+ return payload
110
+
111
+
112
+ def source_filename(source: str | None) -> str:
113
+ """从本地路径或 URL 提取上传文件名。"""
114
+ if not source:
115
+ return "document.bin"
116
+ parsed = urlparse(source)
117
+ path = unquote(parsed.path) if parsed.scheme else source
118
+ filename = Path(path).name
119
+ return filename or "document.bin"
120
+
121
+
122
+ def _form_bool(value: bool) -> str:
123
+ return "true" if value else "false"
@@ -0,0 +1,187 @@
1
+ """MinerU 文档适配器测试。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ import unittest
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from agent_core import (
12
+ Blob,
13
+ DocumentParsingError,
14
+ DocumentServiceError,
15
+ )
16
+
17
+ from agent_core_mineru import (
18
+ HttpxMinerUTransport,
19
+ MinerUBlobParser,
20
+ MinerUConfig,
21
+ MinerUDocumentLoader,
22
+ )
23
+
24
+
25
+ class _FakeTransport:
26
+ def __init__(self, response: Mapping[str, Any]) -> None:
27
+ self.response = response
28
+ self.blobs: list[Blob] = []
29
+ self.configs: list[MinerUConfig] = []
30
+
31
+ async def parse(self, blob: Blob, *, config: MinerUConfig) -> Mapping[str, Any]:
32
+ self.blobs.append(blob)
33
+ self.configs.append(config)
34
+ return self.response
35
+
36
+
37
+ class _FakeResponse:
38
+ def __init__(self, payload: object, *, status_code: int = 200, text: str = "") -> None:
39
+ self._payload = payload
40
+ self.status_code = status_code
41
+ self.text = text
42
+
43
+ def json(self) -> object:
44
+ return self._payload
45
+
46
+
47
+ class _FakeHttpClient:
48
+ def __init__(self, response: _FakeResponse) -> None:
49
+ self.response = response
50
+ self.requests: list[dict[str, Any]] = []
51
+
52
+ async def post(self, url: str, **kwargs: Any) -> _FakeResponse:
53
+ self.requests.append({"url": url, **kwargs})
54
+ return self.response
55
+
56
+
57
+ class MinerUParserTests(unittest.IsolatedAsyncioTestCase):
58
+ async def test_blocks_preserve_page_lineage_and_stable_ids(self) -> None:
59
+ response = {
60
+ "results": {
61
+ "manual": {
62
+ "version": "2.1.0",
63
+ "md_content": "# 飞行手册\n\n起飞前检查。",
64
+ "content_list": [
65
+ {"type": "title", "text": "飞行手册", "page_idx": 0, "block_id": "b-1"},
66
+ {"type": "text", "text": "起飞前检查。", "page_idx": 1},
67
+ ],
68
+ }
69
+ }
70
+ }
71
+ transport = _FakeTransport(response)
72
+ parser = MinerUBlobParser(transport=transport)
73
+ blob = Blob(b"pdf", source="C:/docs/manual.pdf", mime_type="application/pdf")
74
+
75
+ first = await parser.parse(blob)
76
+ second = await parser.parse(blob)
77
+
78
+ self.assertEqual([document.content for document in first], ["飞行手册", "起飞前检查。"])
79
+ self.assertEqual(
80
+ [document.document_id for document in first],
81
+ [document.document_id for document in second],
82
+ )
83
+ assert first[0].locator is not None
84
+ assert first[1].locator is not None
85
+ self.assertEqual(first[0].locator.page, 1)
86
+ self.assertEqual(first[0].locator.block_id, "b-1")
87
+ self.assertEqual(first[1].locator.page, 2)
88
+ self.assertEqual(first[1].metadata["parser"], "mineru")
89
+ self.assertEqual(first[1].metadata["mineru_version"], "2.1.0")
90
+
91
+ async def test_markdown_mode_uses_full_markdown(self) -> None:
92
+ transport = _FakeTransport(
93
+ {
94
+ "data": {
95
+ "results": {
96
+ "document.pdf": {
97
+ "md_content": "# 标题\n\n正文",
98
+ "content_list": [{"type": "text", "text": "正文", "page_idx": 0}],
99
+ }
100
+ }
101
+ }
102
+ }
103
+ )
104
+ parser = MinerUBlobParser(
105
+ MinerUConfig(output_mode="markdown"),
106
+ transport=transport,
107
+ )
108
+
109
+ documents = await parser.parse(Blob(b"pdf", source="document.pdf"))
110
+
111
+ self.assertEqual(len(documents), 1)
112
+ self.assertEqual(documents[0].content, "# 标题\n\n正文")
113
+ self.assertEqual(documents[0].metadata["mineru_block_count"], 1)
114
+
115
+ async def test_loader_reads_local_file_and_propagates_metadata(self) -> None:
116
+ transport = _FakeTransport(
117
+ {"results": {"manual": {"md_content": "内容", "content_list": []}}}
118
+ )
119
+ with tempfile.TemporaryDirectory() as directory:
120
+ path = Path(directory) / "manual.pdf"
121
+ path.write_bytes(b"pdf-data")
122
+ loader = MinerUDocumentLoader(
123
+ path,
124
+ transport=transport,
125
+ metadata={"namespace": "manual"},
126
+ )
127
+
128
+ documents = await loader.load()
129
+
130
+ self.assertEqual(transport.blobs[0].data, b"pdf-data")
131
+ self.assertEqual(transport.blobs[0].mime_type, "application/pdf")
132
+ self.assertEqual(documents[0].metadata["namespace"], "manual")
133
+
134
+ async def test_invalid_content_list_and_service_error_are_explicit(self) -> None:
135
+ malformed = MinerUBlobParser(
136
+ transport=_FakeTransport({"results": {"document": {"content_list": "{"}}})
137
+ )
138
+ failed = MinerUBlobParser(transport=_FakeTransport({"code": 500, "msg": "模型不可用"}))
139
+
140
+ with self.assertRaises(DocumentParsingError):
141
+ await malformed.parse(Blob(b"pdf", source="document.pdf"))
142
+ with self.assertRaises(DocumentServiceError):
143
+ await failed.parse(Blob(b"pdf", source="document.pdf"))
144
+
145
+ async def test_file_size_limit_is_checked_before_transport(self) -> None:
146
+ transport = _FakeTransport({})
147
+ parser = MinerUBlobParser(MinerUConfig(max_file_bytes=2), transport=transport)
148
+
149
+ with self.assertRaises(DocumentParsingError):
150
+ await parser.parse(Blob(b"pdf"))
151
+ self.assertEqual(transport.blobs, [])
152
+
153
+
154
+ class MinerUTransportTests(unittest.IsolatedAsyncioTestCase):
155
+ async def test_http_transport_builds_multipart_request(self) -> None:
156
+ client = _FakeHttpClient(_FakeResponse({"results": {}}))
157
+ transport = HttpxMinerUTransport(client)
158
+ config = MinerUConfig(
159
+ endpoint="http://mineru.local/file_parse",
160
+ api_key="secret",
161
+ formula_enabled=False,
162
+ extra_form_fields={"return_middle_json": "false"},
163
+ )
164
+
165
+ payload = await transport.parse(
166
+ Blob(b"pdf", source="manual.pdf", mime_type="application/pdf"),
167
+ config=config,
168
+ )
169
+
170
+ self.assertEqual(payload, {"results": {}})
171
+ request = client.requests[0]
172
+ self.assertEqual(request["url"], config.endpoint)
173
+ self.assertEqual(request["headers"]["Authorization"], "Bearer secret")
174
+ self.assertEqual(request["data"]["formula_enable"], "false")
175
+ self.assertEqual(request["data"]["return_content_list"], "true")
176
+ self.assertEqual(request["files"]["files"][0], "manual.pdf")
177
+
178
+ async def test_http_error_is_wrapped(self) -> None:
179
+ client = _FakeHttpClient(_FakeResponse({}, status_code=503, text="unavailable"))
180
+ transport = HttpxMinerUTransport(client)
181
+
182
+ with self.assertRaises(DocumentServiceError):
183
+ await transport.parse(Blob(b"pdf"), config=MinerUConfig())
184
+
185
+
186
+ if __name__ == "__main__":
187
+ unittest.main()