paper-plane-x-cli 0.2.3__tar.gz → 0.2.4__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.
Files changed (23) hide show
  1. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/PKG-INFO +11 -1
  2. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/README.md +10 -0
  3. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/pyproject.toml +1 -1
  4. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/skills/ppx-pdf-to-markdown/SKILL.md +4 -3
  5. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/__init__.py +1 -1
  6. paper_plane_x_cli-0.2.4/src/paper_plane_x_cli/cli/pdf.py +399 -0
  7. paper_plane_x_cli-0.2.3/src/paper_plane_x_cli/cli/pdf.py +0 -171
  8. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/.gitignore +0 -0
  9. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/LICENSE +0 -0
  10. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/skills/ppx-paper-acquisition/SKILL.md +0 -0
  11. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/skills/ppx-researcher/SKILL.md +0 -0
  12. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/skills/ppx-researcher/references/advanced-topics.md +0 -0
  13. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/skills/ppx-researcher/references/tool-guide.md +0 -0
  14. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/__init__.py +0 -0
  15. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/context.py +0 -0
  16. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/files.py +0 -0
  17. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/librarian.py +0 -0
  18. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/paper.py +0 -0
  19. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/paper_note.py +0 -0
  20. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/project.py +0 -0
  21. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/skills.py +0 -0
  22. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/task.py +0 -0
  23. {paper_plane_x_cli-0.2.3 → paper_plane_x_cli-0.2.4}/src/paper_plane_x_cli/cli/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: paper-plane-x-cli
3
- Version: 0.2.3
3
+ Version: 0.2.4
4
4
  Summary: HTTP CLI and external-agent skills for Paper Plane X
5
5
  Author-email: windlx <1418043337@qq.com>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -229,6 +229,16 @@ The command uploads the PDF to the configured backend parser, writes Markdown an
229
229
  }
230
230
  ```
231
231
 
232
+ Progress goes to stderr; a successful parse still prints only the result JSON to stdout. Use `--no-wait` to print the task receipt immediately, or resume a lost connection without uploading again:
233
+
234
+ ```bash
235
+ ppx pdf wait --task-id <task-id> --save-dir ./paper-pdf
236
+ ```
237
+
238
+ `--timeout` limits the wait for an accepted task, not the server's execution. Exit **3** means waiting stopped (possibly because status or the result was temporarily unreachable), not that the task failed; use the task ID in stderr to resume. Exit **4** means the server reported a failed task. For `submission_unknown`, query the reported ID or retry `pdf parse` with that exact `--submission-id` and the same input. Completed results are retained on the backend for 24 hours.
239
+
240
+ This command requires a PPX backend exposing `/api/v1/parse/pdf/tasks`.
241
+
232
242
  Parser choice and credentials are managed by the backend Settings, not by the CLI.
233
243
 
234
244
  ## Agent Skills
@@ -217,6 +217,16 @@ The command uploads the PDF to the configured backend parser, writes Markdown an
217
217
  }
218
218
  ```
219
219
 
220
+ Progress goes to stderr; a successful parse still prints only the result JSON to stdout. Use `--no-wait` to print the task receipt immediately, or resume a lost connection without uploading again:
221
+
222
+ ```bash
223
+ ppx pdf wait --task-id <task-id> --save-dir ./paper-pdf
224
+ ```
225
+
226
+ `--timeout` limits the wait for an accepted task, not the server's execution. Exit **3** means waiting stopped (possibly because status or the result was temporarily unreachable), not that the task failed; use the task ID in stderr to resume. Exit **4** means the server reported a failed task. For `submission_unknown`, query the reported ID or retry `pdf parse` with that exact `--submission-id` and the same input. Completed results are retained on the backend for 24 hours.
227
+
228
+ This command requires a PPX backend exposing `/api/v1/parse/pdf/tasks`.
229
+
220
230
  Parser choice and credentials are managed by the backend Settings, not by the CLI.
221
231
 
222
232
  ## Agent Skills
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "paper-plane-x-cli"
3
- version = "0.2.3"
3
+ version = "0.2.4"
4
4
  description = "HTTP CLI and external-agent skills for Paper Plane X"
5
5
  readme = "README.md"
6
6
  license = "AGPL-3.0-or-later"
@@ -46,9 +46,10 @@ Important options:
46
46
  - `--source`: local PDF file path.
47
47
  - `--save-dir`: local directory where Markdown and `images/` are written.
48
48
  - `--output-md-name`: Markdown filename. Defaults to the PDF stem plus `.md`.
49
- - `--timeout`: HTTP timeout in seconds, default `1800`. Allow this time for cold startup and parsing; a timeout does not cancel remote work.
49
+ - `--timeout`: wait budget in seconds after acceptance, default `1800`. It does not cancel the task.
50
+ - `--no-wait`: submit and print the task receipt immediately.
50
51
 
51
- Local deployments require MinerU 4.x V1. PPX handles upload, job polling, and artifact download using the `standard` quality tier and all PDF pages. Point the CLI at the PPX backend, using the configured CLI base URL; configure the MinerU address in the backend settings. An on-demand deployment may take several minutes on first use.
52
+ Use a PPX backend exposing `/api/v1/parse/pdf/tasks`. Its local MinerU parser uses the MinerU 4.3.0 Tasks API. PPX handles upload, job polling, and artifact download using the `standard` quality tier and all PDF pages. Point the CLI at the PPX backend, using the configured CLI base URL; configure the MinerU address in the backend settings. An on-demand deployment may take several minutes on first use.
52
53
 
53
54
  The command prints JSON:
54
55
 
@@ -63,5 +64,5 @@ The command prints JSON:
63
64
  ## Reading Rules
64
65
 
65
66
  - Base claims on the generated Markdown, not guessed PDF contents or filenames.
66
- - If conversion fails, report the CLI error and retry only when there is a clear adjustment: wrong base URL, smaller file, or timeout.
67
+ - If waiting stops with exit code 3, use the task ID from stderr with `ppx pdf wait --task-id <id> --save-dir <dir>`; do not resubmit. If submission was not confirmed, look up the reported task ID or retry the same input with the same `--submission-id`. Exit code 4 means the backend reported failure.
67
68
  - If Markdown contains figure links, keep the `images/` directory together with the Markdown when the target workflow needs figures.
@@ -2,4 +2,4 @@
2
2
 
3
3
  __all__ = ["__version__"]
4
4
 
5
- __version__ = "0.2.3"
5
+ __version__ = "0.2.4"
@@ -0,0 +1,399 @@
1
+ """PDF parsing commands for the Paper Plane X CLI.
2
+
3
+ Exit codes:
4
+ - 1: Request, HTTP, or receipt/result protocol error
5
+ - 2: Invalid CLI arguments or local input
6
+ - 3: Wait budget exhausted (remote task is NOT canceled; resume with `ppx pdf wait`)
7
+ - 4: Remote PDF task failed
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import json
14
+ import re
15
+ import time
16
+ from pathlib import Path
17
+ from typing import Annotated, Any, NoReturn, TypedDict, cast
18
+ from urllib.parse import unquote, urlparse
19
+ from uuid import UUID, uuid4
20
+
21
+ import httpx
22
+ import typer
23
+
24
+ from paper_plane_x_cli.cli.utils import (
25
+ fail,
26
+ get_output_md_name,
27
+ print_json,
28
+ )
29
+
30
+ pdf_app = typer.Typer(
31
+ no_args_is_help=True,
32
+ help="Parse local PDFs to Markdown through the Paper Plane X API.",
33
+ )
34
+
35
+ _ACTIVE_STATUSES = {"queued", "waiting_for_mineru", "parsing"}
36
+ _TERMINAL_STATUSES = {"completed", "failed"}
37
+ _RETRYABLE_HTTP_STATUSES = {429, 502, 503, 504}
38
+ _MD_IMAGE_RE = re.compile(r"!\[[^\]]*\]\(([^)]+)\)")
39
+ _HTML_IMAGE_RE = re.compile(r"<img[^>]+src=[\"']([^\"']+)[\"'][^>]*>", re.IGNORECASE)
40
+
41
+
42
+ class PdfTask(TypedDict):
43
+ """CLI 续等依赖的回执字段,不包含上游 MinerU 的内部任务 ID。"""
44
+
45
+ task_id: str
46
+ status: str
47
+ output_md_name: str
48
+ error: dict[str, str] | None
49
+
50
+
51
+ TaskContext = dict[str, str | None]
52
+
53
+
54
+ def _stop(
55
+ code: str, message: str, exit_code: int, task_id: str, status: str | None = None
56
+ ) -> NoReturn:
57
+ """将带 task_id 的结构化诊断写入 stderr 并退出,保持 stdout 纯净。"""
58
+ payload = {"error": message, "code": code, "task_id": task_id}
59
+ if status is not None:
60
+ payload["status"] = status
61
+ typer.echo(json.dumps(payload), err=True)
62
+ raise typer.Exit(exit_code)
63
+
64
+
65
+ def _parse_receipt(response: httpx.Response, task_id: str) -> PdfTask:
66
+ """校验服务端回执归属与输出文件名,拒绝服务端路径越权写入本地。"""
67
+ try:
68
+ data = cast(dict[str, object], response.json())
69
+ if not isinstance(data, dict) or data.get("task_id") != task_id:
70
+ raise ValueError
71
+ status = data.get("status")
72
+ if not isinstance(status, str) or status not in (
73
+ _ACTIVE_STATUSES | _TERMINAL_STATUSES
74
+ ):
75
+ raise ValueError
76
+ output = data.get("output_md_name")
77
+ if (
78
+ not isinstance(output, str)
79
+ or Path(output).name != output
80
+ or "\\" in output
81
+ or not output.lower().endswith(".md")
82
+ ):
83
+ raise ValueError
84
+ error = data.get("error")
85
+ if error is not None and (
86
+ not isinstance(error, dict)
87
+ or not isinstance(error.get("code"), str)
88
+ or not isinstance(error.get("message"), str)
89
+ ):
90
+ raise ValueError
91
+ return {
92
+ "task_id": task_id,
93
+ "status": status,
94
+ "output_md_name": output,
95
+ "error": cast(dict[str, str] | None, error),
96
+ }
97
+ except ValueError:
98
+ _stop(
99
+ "invalid_receipt",
100
+ "Invalid PPX PDF task receipt; check the task by ID.",
101
+ 1,
102
+ task_id,
103
+ )
104
+
105
+
106
+ def _get_with_retry(
107
+ client: httpx.Client,
108
+ url: str,
109
+ deadline: float,
110
+ task_id: str,
111
+ status: str | None,
112
+ *,
113
+ request_cap: float,
114
+ timeout_code: str,
115
+ ) -> httpx.Response:
116
+ """在等待预算内发起 GET;对瞬时网络错误与 429/5xx 重试,其它错误直接中止。"""
117
+ had_transient_failure = False
118
+ while True:
119
+ remaining = deadline - time.monotonic()
120
+ if remaining <= 0:
121
+ code = (
122
+ "status_unavailable"
123
+ if timeout_code == "wait_timeout"
124
+ and (had_transient_failure or status is None)
125
+ else timeout_code
126
+ )
127
+ _stop(
128
+ code,
129
+ "Stopped waiting; the task was not canceled. Resume with ppx pdf wait.",
130
+ 3,
131
+ task_id,
132
+ status,
133
+ )
134
+ try:
135
+ response = client.get(url, timeout=min(remaining, request_cap))
136
+ except httpx.RequestError:
137
+ had_transient_failure = True
138
+ time.sleep(min(2.0, max(0.0, deadline - time.monotonic())))
139
+ continue
140
+ if response.status_code in _RETRYABLE_HTTP_STATUSES:
141
+ had_transient_failure = True
142
+ time.sleep(min(2.0, max(0.0, deadline - time.monotonic())))
143
+ continue
144
+ if not response.is_success:
145
+ _stop(
146
+ "task_http_error",
147
+ f"PPX returned HTTP {response.status_code}.",
148
+ 1,
149
+ task_id,
150
+ status,
151
+ )
152
+ return response
153
+
154
+
155
+ def _wait_for_pdf(
156
+ context: TaskContext,
157
+ task_id: str,
158
+ save_dir: Path,
159
+ timeout: float,
160
+ task: PdfTask | None = None,
161
+ ) -> None:
162
+ """两阶段等待:先轮询任务直到 completed,再拉取结果并落盘。"""
163
+ base = f"{context['base_url']}/parse/pdf/tasks/{task_id}"
164
+ deadline = time.monotonic() + timeout
165
+ status = task["status"] if task else None
166
+
167
+ with httpx.Client() as client:
168
+ # 阶段 1:轮询任务状态直到终态。
169
+ while task is None or task["status"] in _ACTIVE_STATUSES:
170
+ if task is not None:
171
+ time.sleep(min(2.0, max(0.0, deadline - time.monotonic())))
172
+ response = _get_with_retry(
173
+ client,
174
+ base,
175
+ deadline,
176
+ task_id,
177
+ status,
178
+ request_cap=8.0,
179
+ timeout_code="wait_timeout",
180
+ )
181
+ task = _parse_receipt(response, task_id)
182
+ if task["status"] != status:
183
+ status = task["status"]
184
+ typer.echo(f"PDF task {task_id}: {status}", err=True)
185
+
186
+ if task["status"] == "failed":
187
+ error = task["error"] or {
188
+ "code": "parse_failed",
189
+ "message": "PDF task failed",
190
+ }
191
+ _stop(error["code"], error["message"], 4, task_id, "failed")
192
+
193
+ # 阶段 2:任务已 completed,下载完整 Markdown 与内联图片结果。
194
+ result_resp = _get_with_retry(
195
+ client,
196
+ f"{base}/result",
197
+ deadline,
198
+ task_id,
199
+ status,
200
+ request_cap=30.0,
201
+ timeout_code="result_unavailable",
202
+ )
203
+ try:
204
+ result = result_resp.json()
205
+ except ValueError:
206
+ _stop(
207
+ "invalid_result",
208
+ "PPX returned an invalid PDF result.",
209
+ 1,
210
+ task_id,
211
+ status,
212
+ )
213
+ _save_result(result, task["output_md_name"], save_dir)
214
+
215
+
216
+ @pdf_app.command("parse", help="Convert a local PDF into Markdown and image files.")
217
+ def pdf_parse(
218
+ ctx: typer.Context,
219
+ source: Annotated[
220
+ Path,
221
+ typer.Option(
222
+ "--source",
223
+ exists=True,
224
+ dir_okay=False,
225
+ help="Local PDF file to parse.",
226
+ ),
227
+ ],
228
+ save_dir: Annotated[
229
+ Path,
230
+ typer.Option(
231
+ "--save-dir",
232
+ help="Directory where Markdown and referenced images are written.",
233
+ ),
234
+ ],
235
+ output_md_name: Annotated[
236
+ str | None,
237
+ typer.Option(
238
+ "--output-md-name",
239
+ help="Markdown filename. Defaults to the PDF stem plus .md.",
240
+ ),
241
+ ] = None,
242
+ timeout: Annotated[
243
+ float,
244
+ typer.Option(
245
+ "--timeout",
246
+ min=1,
247
+ help="How long to wait for an accepted task, in seconds.",
248
+ ),
249
+ ] = 1800.0,
250
+ no_wait: Annotated[
251
+ bool,
252
+ typer.Option("--no-wait", help="Submit and print the task ID without waiting."),
253
+ ] = False,
254
+ submission_id: Annotated[
255
+ UUID | None,
256
+ typer.Option(
257
+ "--submission-id",
258
+ help="Reuse a previous UUIDv4 submission ID after a lost response.",
259
+ ),
260
+ ] = None,
261
+ ) -> None:
262
+ if source.suffix.lower() != ".pdf":
263
+ fail(f"pdf parse expects a PDF file: {source}")
264
+ if submission_id is not None and submission_id.version != 4:
265
+ fail("--submission-id must be a UUIDv4")
266
+ md_name = get_output_md_name(source, output_md_name)
267
+ # 先生成幂等 ID 再上传:即使回执丢失,也可用同一 --submission-id 重试或续等。
268
+ task_id = str(submission_id or uuid4())
269
+ context = cast(TaskContext, ctx.obj["ctx"])
270
+
271
+ with source.open("rb") as file_obj:
272
+ try:
273
+ response = httpx.request(
274
+ "POST",
275
+ f"{context['base_url']}/parse/pdf/tasks",
276
+ data={"output_md_name": md_name},
277
+ files={"pdf_file": (source.name, file_obj, "application/pdf")},
278
+ headers={"Idempotency-Key": task_id},
279
+ # 上传与受理回执使用独立超时,不挤占后续等待预算。
280
+ timeout=httpx.Timeout(connect=8, write=180, read=30, pool=8),
281
+ )
282
+ except httpx.RequestError:
283
+ _stop(
284
+ "submission_unknown",
285
+ "Submission was not confirmed. Query the task ID or retry with the same --submission-id.",
286
+ 1,
287
+ task_id,
288
+ )
289
+
290
+ if response.status_code != 202:
291
+ if response.status_code in {408, 500, 502, 503, 504}:
292
+ _stop(
293
+ "submission_unknown",
294
+ f"PPX returned HTTP {response.status_code} without a receipt. Query or reuse the same --submission-id.",
295
+ 1,
296
+ task_id,
297
+ )
298
+ _stop(
299
+ "submission_rejected",
300
+ f"PPX did not accept the upload (HTTP {response.status_code}).",
301
+ 1,
302
+ task_id,
303
+ )
304
+
305
+ task = _parse_receipt(response, task_id)
306
+ if no_wait:
307
+ print_json(task)
308
+ return
309
+ typer.echo(f"PDF task {task_id}: {task['status']}", err=True)
310
+ _wait_for_pdf(context, task_id, save_dir, timeout, task)
311
+
312
+
313
+ @pdf_app.command(
314
+ "wait", help="Wait for a previously accepted PDF task and save its result."
315
+ )
316
+ def pdf_wait(
317
+ ctx: typer.Context,
318
+ task_id: Annotated[
319
+ UUID, typer.Option("--task-id", help="Task ID returned at submission.")
320
+ ],
321
+ save_dir: Annotated[
322
+ Path, typer.Option("--save-dir", help="Destination for Markdown and images.")
323
+ ],
324
+ timeout: Annotated[
325
+ float, typer.Option("--timeout", min=1, help="Maximum wait in seconds.")
326
+ ] = 1800.0,
327
+ ) -> None:
328
+ _wait_for_pdf(cast(TaskContext, ctx.obj["ctx"]), str(task_id), save_dir, timeout)
329
+
330
+
331
+ def _extract_referenced_image_names(md_content: str) -> set[str]:
332
+ """从 Markdown 与 HTML <img> 标签中提取被引用的图片文件名。"""
333
+ raw_refs = cast(list[str], _MD_IMAGE_RE.findall(md_content)) + cast(
334
+ list[str], _HTML_IMAGE_RE.findall(md_content)
335
+ )
336
+ references: set[str] = set()
337
+ for raw_ref in raw_refs:
338
+ ref = raw_ref.strip()
339
+ if " " in ref:
340
+ ref = ref.split(" ", 1)[0]
341
+ ref = ref.strip("<>'\"")
342
+ name = Path(unquote(urlparse(ref).path)).name
343
+ if name:
344
+ references.add(name)
345
+ return references
346
+
347
+
348
+ def _save_result(response: object, md_name: str, save_dir: Path) -> None:
349
+ """将 Markdown 与被引用的图片写入目标目录,并在 stdout 输出机器可读摘要。"""
350
+ if not isinstance(response, dict):
351
+ fail("Invalid PDF result")
352
+ response_data = cast(dict[str, object], response)
353
+ md_content = response_data.get("md_content")
354
+ if not isinstance(md_content, str):
355
+ fail("Invalid response: 'md_content' missing or not a string")
356
+
357
+ save_dir.mkdir(parents=True, exist_ok=True)
358
+ md_path = save_dir / md_name
359
+ md_path.write_text(md_content, encoding="utf-8")
360
+
361
+ image_dir = save_dir / "images"
362
+ image_dir.mkdir(parents=True, exist_ok=True)
363
+ referenced = _extract_referenced_image_names(md_content)
364
+
365
+ images_raw = response_data.get("images", [])
366
+ if isinstance(images_raw, list):
367
+ for image_info in cast(list[Any], images_raw):
368
+ if not isinstance(image_info, dict):
369
+ continue
370
+ name = image_info.get("name")
371
+ b64 = image_info.get("base64")
372
+ if not isinstance(name, str) or not isinstance(b64, str):
373
+ continue
374
+ target_name = Path(name).name
375
+ if target_name not in referenced:
376
+ continue
377
+ try:
378
+ img_bytes = base64.b64decode(b64)
379
+ except ValueError:
380
+ continue
381
+ (image_dir / target_name).write_bytes(img_bytes)
382
+
383
+ # 清理目标 images/ 目录中不再被引用的残留图片。
384
+ for candidate in image_dir.iterdir():
385
+ if candidate.is_file() and candidate.name not in referenced:
386
+ candidate.unlink(missing_ok=True)
387
+
388
+ image_paths = [
389
+ str(image_dir / name)
390
+ for name in sorted(referenced)
391
+ if (image_dir / name).is_file()
392
+ ]
393
+ print_json(
394
+ {
395
+ "md_path": str(md_path),
396
+ "image_paths": image_paths,
397
+ "parser_type": response_data.get("parser_type", ""),
398
+ }
399
+ )
@@ -1,171 +0,0 @@
1
- """PDF parsing commands for the Paper Plane X CLI."""
2
-
3
- from __future__ import annotations
4
-
5
- import base64
6
- import re
7
- from pathlib import Path
8
- from typing import Annotated, Any, cast
9
- from urllib.parse import unquote, urlparse
10
-
11
- import typer
12
-
13
- from paper_plane_x_cli.cli.utils import (
14
- fail,
15
- get_output_md_name,
16
- print_json,
17
- request,
18
- )
19
-
20
- pdf_app = typer.Typer(
21
- no_args_is_help=True,
22
- help="Parse local PDFs to Markdown through the Paper Plane X API.",
23
- )
24
-
25
-
26
- @pdf_app.command("parse", help="Convert a local PDF into Markdown and image files.")
27
- def pdf_parse(
28
- ctx: typer.Context,
29
- source: Annotated[
30
- Path,
31
- typer.Option(
32
- "--source",
33
- exists=True,
34
- dir_okay=False,
35
- help="Local PDF file to parse.",
36
- ),
37
- ],
38
- save_dir: Annotated[
39
- Path,
40
- typer.Option(
41
- "--save-dir",
42
- help="Directory where Markdown and referenced images are written.",
43
- ),
44
- ],
45
- output_md_name: Annotated[
46
- str | None,
47
- typer.Option(
48
- "--output-md-name",
49
- help="Markdown filename. Defaults to the PDF stem plus .md.",
50
- ),
51
- ] = None,
52
- timeout: Annotated[
53
- float,
54
- typer.Option(
55
- "--timeout",
56
- min=1,
57
- help="HTTP timeout in seconds, including MinerU cold startup and parsing.",
58
- ),
59
- ] = 1800.0,
60
- ) -> None:
61
- if source.suffix.lower() != ".pdf":
62
- fail(f"pdf parse expects a PDF file: {source}")
63
-
64
- md_name = get_output_md_name(source, output_md_name)
65
-
66
- with source.open("rb") as file_obj:
67
- data = {"output_md_name": md_name}
68
- files = {"pdf_file": (source.name, file_obj, "application/pdf")}
69
- response = request(
70
- "POST",
71
- "/parse/pdf",
72
- ctx.obj["ctx"],
73
- data=data,
74
- files=files,
75
- timeout=timeout,
76
- )
77
-
78
- response_data = cast(dict[str, Any], response)
79
- md_content = response_data.get("md_content")
80
- if not isinstance(md_content, str):
81
- fail("Invalid response: 'md_content' missing or not a string")
82
-
83
- save_dir.mkdir(parents=True, exist_ok=True)
84
- md_path = save_dir / md_name
85
- md_path.write_text(md_content, encoding="utf-8")
86
-
87
- image_save_dir = save_dir / "images"
88
- image_save_dir.mkdir(parents=True, exist_ok=True)
89
-
90
- _write_images(response_data.get("images", []), image_save_dir)
91
- _prune_unreferenced_images(md_content, image_save_dir)
92
- image_paths = _get_image_paths(md_content, image_save_dir)
93
-
94
- payload: dict[str, object] = {
95
- "md_path": str(md_path),
96
- "image_paths": [str(path) for path in image_paths],
97
- "parser_type": response_data.get("parser_type", ""),
98
- }
99
- print_json(payload)
100
-
101
-
102
- def _write_images(images_raw: object, image_save_dir: Path) -> None:
103
- if not isinstance(images_raw, list):
104
- return
105
-
106
- for image_info in cast(list[Any], images_raw):
107
- if not isinstance(image_info, dict):
108
- continue
109
-
110
- name = image_info.get("name")
111
- b64 = image_info.get("base64")
112
- if not isinstance(name, str) or not isinstance(b64, str):
113
- continue
114
-
115
- try:
116
- img_bytes = base64.b64decode(b64)
117
- except ValueError:
118
- continue
119
-
120
- target_path = image_save_dir / Path(name).name
121
- target_path.write_bytes(img_bytes)
122
-
123
-
124
- def _get_image_paths(md_content: str, image_dir: Path) -> list[Path]:
125
- if not image_dir.exists():
126
- return []
127
-
128
- referenced_names = _extract_referenced_image_names(md_content)
129
- image_paths: list[Path] = []
130
- for file_name in sorted(referenced_names):
131
- candidate = image_dir / file_name
132
- if candidate.exists() and candidate.is_file():
133
- image_paths.append(candidate)
134
- return image_paths
135
-
136
-
137
- def _prune_unreferenced_images(md_content: str, image_dir: Path) -> None:
138
- if not image_dir.exists():
139
- return
140
-
141
- referenced_names = _extract_referenced_image_names(md_content)
142
- for candidate in image_dir.iterdir():
143
- if candidate.is_file() and candidate.name not in referenced_names:
144
- candidate.unlink(missing_ok=True)
145
-
146
-
147
- def _extract_referenced_image_names(md_content: str) -> set[str]:
148
- references: set[str] = set()
149
-
150
- md_pattern = r"!\[[^\]]*\]\(([^)]+)\)"
151
- html_pattern = r"<img[^>]+src=[\"']([^\"']+)[\"'][^>]*>"
152
-
153
- for raw_ref in cast(list[str], re.findall(md_pattern, md_content)):
154
- ref = raw_ref.strip()
155
- if " " in ref:
156
- ref = ref.split(" ", 1)[0]
157
- ref = ref.strip("<>'\"")
158
- parsed_path = Path(unquote(urlparse(ref).path))
159
- if parsed_path.name:
160
- references.add(parsed_path.name)
161
-
162
- for raw_ref in cast(
163
- list[str],
164
- re.findall(html_pattern, md_content, flags=re.IGNORECASE),
165
- ):
166
- ref = raw_ref.strip("<>'\"")
167
- parsed_path = Path(unquote(urlparse(ref).path))
168
- if parsed_path.name:
169
- references.add(parsed_path.name)
170
-
171
- return references