paper2mdviallm 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 s1n4sh4
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include README.md
2
+ include LICENSE
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: paper2mdviallm
3
+ Version: 0.1.0
4
+ Summary: LLM-native academic PDF to Obsidian Markdown converter.
5
+ Author: s1n4sh4
6
+ License-Expression: MIT
7
+ Keywords: pdf,markdown,obsidian,llm,academic
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
13
+ Classifier: Topic :: Utilities
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: anthropic>=0.40.0
18
+ Requires-Dist: openai>=1.0.0
19
+ Requires-Dist: PyMuPDF>=1.24.0
20
+ Requires-Dist: pydantic>=2.0
21
+ Requires-Dist: python-dotenv>=1.0.0
22
+ Requires-Dist: tenacity>=8.0.0
23
+ Requires-Dist: rich>=13.0.0
24
+ Requires-Dist: typer>=0.12.0
25
+ Dynamic: license-file
26
+
27
+ # paper2mdviallm
28
+
29
+ `paper2mdviallm` is a Python CLI for converting digital academic PDFs into
30
+ Obsidian-friendly Markdown.
31
+
32
+ It is the external conversion backend used by the Scholia Obsidian plugin, but
33
+ it can also be installed and run on its own.
34
+
35
+ ## Install
36
+
37
+ When `paper2mdviallm` is published to PyPI, install it into a dedicated environment:
38
+
39
+ ```sh
40
+ conda create -n scholia python=3.11
41
+ conda activate scholia
42
+ pip install paper2mdviallm
43
+ ```
44
+
45
+ For local development from this repository:
46
+
47
+ ```sh
48
+ python -m venv .venv
49
+ .venv/bin/pip install -r requirements-dev.txt
50
+ .venv/bin/pip install -e .
51
+ ```
52
+
53
+ ## Requirements
54
+
55
+ - Python 3.10+
56
+ - An OpenAI or Anthropic API key
57
+ - Digital PDFs with a text layer
58
+
59
+ The CLI reads API keys from the environment:
60
+
61
+ - `OPENAI_API_KEY`
62
+ - `ANTHROPIC_API_KEY`
63
+
64
+ ## Usage
65
+
66
+ Inspect a PDF before conversion:
67
+
68
+ ```sh
69
+ paper2mdviallm inspect paper.pdf
70
+ ```
71
+
72
+ Convert a PDF to Markdown:
73
+
74
+ ```sh
75
+ paper2mdviallm convert paper.pdf -o out/
76
+ ```
77
+
78
+ Override the model or concurrency when needed:
79
+
80
+ ```sh
81
+ paper2mdviallm convert paper.pdf -o out/ --model claude-sonnet-4-6 --concurrency 3
82
+ ```
83
+
84
+ ## With Scholia
85
+
86
+ After installing into a conda environment, point Scholia at either:
87
+
88
+ - the environment root, such as `/Users/me/miniconda3/envs/scholia`, or
89
+ - the concrete executable, such as `/Users/me/miniconda3/envs/scholia/bin/paper2mdviallm`
90
+
91
+ Scholia resolves the binary and executes it directly.
92
+
93
+ ## Development
94
+
95
+ Run tests:
96
+
97
+ ```sh
98
+ python -m pytest tests
99
+ ```
100
+
101
+ Bootstrap from the repo root:
102
+
103
+ ```sh
104
+ tools/paper2mdviallm/bootstrap.sh
105
+ ```
106
+
107
+ ## Boundaries
108
+
109
+ - The current target is digital PDFs, not OCR-heavy scanned documents.
110
+ - Formula-heavy papers still need manual inspection after conversion.
111
+ - The output is optimized for Obsidian reading workflows rather than general
112
+ document fidelity.
@@ -0,0 +1,86 @@
1
+ # paper2mdviallm
2
+
3
+ `paper2mdviallm` is a Python CLI for converting digital academic PDFs into
4
+ Obsidian-friendly Markdown.
5
+
6
+ It is the external conversion backend used by the Scholia Obsidian plugin, but
7
+ it can also be installed and run on its own.
8
+
9
+ ## Install
10
+
11
+ When `paper2mdviallm` is published to PyPI, install it into a dedicated environment:
12
+
13
+ ```sh
14
+ conda create -n scholia python=3.11
15
+ conda activate scholia
16
+ pip install paper2mdviallm
17
+ ```
18
+
19
+ For local development from this repository:
20
+
21
+ ```sh
22
+ python -m venv .venv
23
+ .venv/bin/pip install -r requirements-dev.txt
24
+ .venv/bin/pip install -e .
25
+ ```
26
+
27
+ ## Requirements
28
+
29
+ - Python 3.10+
30
+ - An OpenAI or Anthropic API key
31
+ - Digital PDFs with a text layer
32
+
33
+ The CLI reads API keys from the environment:
34
+
35
+ - `OPENAI_API_KEY`
36
+ - `ANTHROPIC_API_KEY`
37
+
38
+ ## Usage
39
+
40
+ Inspect a PDF before conversion:
41
+
42
+ ```sh
43
+ paper2mdviallm inspect paper.pdf
44
+ ```
45
+
46
+ Convert a PDF to Markdown:
47
+
48
+ ```sh
49
+ paper2mdviallm convert paper.pdf -o out/
50
+ ```
51
+
52
+ Override the model or concurrency when needed:
53
+
54
+ ```sh
55
+ paper2mdviallm convert paper.pdf -o out/ --model claude-sonnet-4-6 --concurrency 3
56
+ ```
57
+
58
+ ## With Scholia
59
+
60
+ After installing into a conda environment, point Scholia at either:
61
+
62
+ - the environment root, such as `/Users/me/miniconda3/envs/scholia`, or
63
+ - the concrete executable, such as `/Users/me/miniconda3/envs/scholia/bin/paper2mdviallm`
64
+
65
+ Scholia resolves the binary and executes it directly.
66
+
67
+ ## Development
68
+
69
+ Run tests:
70
+
71
+ ```sh
72
+ python -m pytest tests
73
+ ```
74
+
75
+ Bootstrap from the repo root:
76
+
77
+ ```sh
78
+ tools/paper2mdviallm/bootstrap.sh
79
+ ```
80
+
81
+ ## Boundaries
82
+
83
+ - The current target is digital PDFs, not OCR-heavy scanned documents.
84
+ - Formula-heavy papers still need manual inspection after conversion.
85
+ - The output is optimized for Obsidian reading workflows rather than general
86
+ document fidelity.
@@ -0,0 +1,3 @@
1
+ """paper2mdviallm: Academic PDF to Obsidian Markdown converter."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,189 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import re
5
+ import shutil
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.progress import Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
13
+ from rich.table import Table
14
+
15
+ from .config import load_config
16
+ from .converter import convert_all
17
+ from .metadata import extract_metadata
18
+ from .postprocess import postprocess
19
+ from .splitter import split_pdf
20
+ from .stitcher import stitch
21
+ from .verifier import verify
22
+
23
+ app = typer.Typer(
24
+ name="paper2mdviallm",
25
+ help="Convert academic paper PDFs to Obsidian-compatible Markdown.",
26
+ add_completion=False
27
+ )
28
+ console = Console()
29
+
30
+ logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
31
+
32
+
33
+ @app.command()
34
+ def convert(
35
+ pdf: Path = typer.Argument(..., help="Path to the PDF file"),
36
+ output: Optional[Path] = typer.Option(None, "-o", "--output", help="Output directory"),
37
+ model: Optional[str] = typer.Option(None, "--model", help="Override model"),
38
+ concurrency: Optional[int] = typer.Option(None, "--concurrency", help="Max concurrent API calls"),
39
+ keep_intermediate: bool = typer.Option(False, "--keep-intermediate", help="Keep sub-PDFs and raw responses"),
40
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose logging")
41
+ ) -> None:
42
+ if verbose:
43
+ logging.getLogger().setLevel(logging.DEBUG)
44
+
45
+ if not pdf.exists():
46
+ console.print(f"[red]Error:[/red] File not found: {pdf}")
47
+ raise typer.Exit(1)
48
+
49
+ cfg = load_config()
50
+ if model:
51
+ cfg.api.model = model
52
+ if concurrency:
53
+ cfg.api.concurrency = concurrency
54
+
55
+ from .converter import _is_openai
56
+
57
+ if _is_openai(cfg.api.model):
58
+ if not cfg.openai_api_key:
59
+ console.print("[red]Error:[/red] OPENAI_API_KEY not set. Add it to .env or environment.")
60
+ raise typer.Exit(1)
61
+ else:
62
+ if not cfg.api_key:
63
+ console.print("[red]Error:[/red] ANTHROPIC_API_KEY not set. Add it to .env or environment.")
64
+ raise typer.Exit(1)
65
+
66
+ out_dir = output or Path(cfg.output.default_dir).expanduser()
67
+ out_dir.mkdir(parents=True, exist_ok=True)
68
+
69
+ with tempfile.TemporaryDirectory() as tmp:
70
+ tmp_path = Path(tmp)
71
+ _run_conversion(pdf, out_dir, tmp_path, cfg, keep_intermediate)
72
+
73
+
74
+ def _run_conversion(pdf: Path, out_dir: Path, tmp_path: Path, cfg, keep_intermediate: bool) -> None:
75
+ with Progress(
76
+ SpinnerColumn(),
77
+ TextColumn("[progress.description]{task.description}"),
78
+ TimeElapsedColumn(),
79
+ console=console
80
+ ) as progress:
81
+ metadata_task = progress.add_task("Extracting metadata...", total=None)
82
+ meta = extract_metadata(pdf)
83
+ progress.update(metadata_task, description=f"[green]Metadata:[/green] {meta.title or pdf.stem}")
84
+ progress.stop_task(metadata_task)
85
+
86
+ split_task = progress.add_task("Splitting PDF...", total=None)
87
+ specs = split_pdf(
88
+ pdf,
89
+ tmp_path,
90
+ chunk_size=cfg.chunking.max_pages_per_chunk,
91
+ overlap=cfg.chunking.overlap_pages,
92
+ single_pass_threshold=cfg.chunking.single_pass_threshold
93
+ )
94
+ progress.update(split_task, description=f"[green]Split:[/green] {len(specs)} chunk(s)")
95
+ progress.stop_task(split_task)
96
+
97
+ convert_task = progress.add_task(f"Converting {len(specs)} chunk(s)...", total=None)
98
+ title = meta.title or pdf.stem
99
+ raw_chunks = convert_all(specs, title, meta.authors, cfg)
100
+ progress.update(convert_task, description=f"[green]Converted[/green] {len(raw_chunks)} chunk(s)")
101
+ progress.stop_task(convert_task)
102
+
103
+ stitch_task = progress.add_task("Stitching...", total=None)
104
+ stitched = stitch(raw_chunks)
105
+ progress.stop_task(stitch_task)
106
+
107
+ post_task = progress.add_task("Post-processing...", total=None)
108
+ final_md = postprocess(stitched, meta)
109
+ progress.stop_task(post_task)
110
+
111
+ verify_task = progress.add_task("Verifying...", total=None)
112
+ result = verify(pdf, final_md)
113
+ progress.stop_task(verify_task)
114
+
115
+ if result.warnings:
116
+ console.print("\n[yellow]Verification warnings:[/yellow]")
117
+ for warning in result.warnings:
118
+ console.print(f" • {warning}")
119
+ if result.missing_passages:
120
+ console.print("\n[dim]Sample missing passages:[/dim]")
121
+ for passage in result.missing_passages[:5]:
122
+ console.print(f" - {passage}")
123
+
124
+ safe_title = re.sub(r'[\\/:*?"<>|]', "_", meta.title or pdf.stem)[:120]
125
+ out_file = out_dir / f"{safe_title}.md"
126
+ out_file.write_text(final_md, encoding="utf-8")
127
+
128
+ status = "[green]OK[/green]" if result.passed else "[yellow]WARN[/yellow]"
129
+ console.print(f"\n{status} Written -> {out_file}")
130
+
131
+ if keep_intermediate:
132
+ keep_dir = out_dir / f"{safe_title}_intermediate"
133
+ keep_dir.mkdir(exist_ok=True)
134
+ for spec in (specs if specs and hasattr(specs[0], "path") else []):
135
+ try:
136
+ shutil.copy(spec.path, keep_dir)
137
+ except Exception:
138
+ pass
139
+ console.print(f" Intermediate artifacts saved to {keep_dir}")
140
+
141
+
142
+ @app.command()
143
+ def inspect(
144
+ pdf: Path = typer.Argument(..., help="Path to the PDF file")
145
+ ) -> None:
146
+ if not pdf.exists():
147
+ console.print(f"[red]Error:[/red] File not found: {pdf}")
148
+ raise typer.Exit(1)
149
+
150
+ cfg = load_config()
151
+
152
+ console.print("\n[bold]Metadata[/bold]")
153
+ meta = extract_metadata(pdf)
154
+ table = Table(show_header=False)
155
+ table.add_row("Title", meta.title or "[dim]not found[/dim]")
156
+ table.add_row("Authors", ", ".join(meta.authors) or "[dim]not found[/dim]")
157
+ table.add_row("Year", meta.year or "[dim]not found[/dim]")
158
+ table.add_row("Venue", meta.venue or "[dim]not found[/dim]")
159
+ table.add_row("DOI", meta.doi or "[dim]not found[/dim]")
160
+ table.add_row("arXiv", meta.arxiv or "[dim]not found[/dim]")
161
+ console.print(table)
162
+
163
+ console.print("\n[bold]Split Plan[/bold]")
164
+ with tempfile.TemporaryDirectory() as tmp:
165
+ specs = split_pdf(
166
+ pdf,
167
+ Path(tmp),
168
+ chunk_size=cfg.chunking.max_pages_per_chunk,
169
+ overlap=cfg.chunking.overlap_pages,
170
+ single_pass_threshold=cfg.chunking.single_pass_threshold
171
+ )
172
+
173
+ chunk_table = Table("Chunk", "Pages", "Context pages")
174
+ for spec in specs:
175
+ chunk_table.add_row(
176
+ str(spec.chunk_idx + 1),
177
+ f"{spec.start + 1}-{spec.end + 1}",
178
+ str(spec.context_pages)
179
+ )
180
+ console.print(chunk_table)
181
+ console.print(f"\nTotal chunks: {len(specs)}")
182
+
183
+
184
+ def main() -> None:
185
+ app()
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import tomllib
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ from dotenv import load_dotenv
9
+ from pydantic import BaseModel, Field
10
+
11
+ load_dotenv()
12
+
13
+ _CONFIG_PATH = Path.home() / ".paper2mdviallm" / "config.toml"
14
+
15
+
16
+ class ApiConfig(BaseModel):
17
+ model: str = "claude-sonnet-4-6"
18
+ max_tokens: int = 16000
19
+ concurrency: int = 3
20
+
21
+
22
+ class OutputConfig(BaseModel):
23
+ default_dir: str = "~/Documents/ObsidianVault/Papers"
24
+
25
+
26
+ class ChunkingConfig(BaseModel):
27
+ max_pages_per_chunk: int = 10
28
+ overlap_pages: int = 1
29
+ single_pass_threshold: int = 12
30
+
31
+
32
+ class Config(BaseModel):
33
+ api: ApiConfig = Field(default_factory=ApiConfig)
34
+ output: OutputConfig = Field(default_factory=OutputConfig)
35
+ chunking: ChunkingConfig = Field(default_factory=ChunkingConfig)
36
+ api_key: Optional[str] = None
37
+ openai_api_key: Optional[str] = None
38
+
39
+ @classmethod
40
+ def load(cls) -> "Config":
41
+ raw: dict = {}
42
+ if _CONFIG_PATH.exists():
43
+ with open(_CONFIG_PATH, "rb") as f:
44
+ raw = tomllib.load(f)
45
+ obj = cls(**raw)
46
+ obj.api_key = os.environ.get("ANTHROPIC_API_KEY")
47
+ obj.openai_api_key = os.environ.get("OPENAI_API_KEY")
48
+ return obj
49
+
50
+
51
+ def load_config() -> Config:
52
+ return Config.load()
@@ -0,0 +1,233 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import base64
5
+ import logging
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import anthropic
10
+ import openai
11
+ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
12
+
13
+ from .config import Config
14
+ from .prompts import SYSTEM_PROMPT, build_user_instruction
15
+ from .splitter import ChunkSpec
16
+
17
+ log = logging.getLogger(__name__)
18
+
19
+ _ANTHROPIC_RETRYABLE = (
20
+ anthropic.RateLimitError,
21
+ anthropic.APITimeoutError,
22
+ anthropic.APIConnectionError
23
+ )
24
+
25
+ _OPENAI_RETRYABLE = (
26
+ openai.RateLimitError,
27
+ openai.APITimeoutError,
28
+ openai.APIConnectionError
29
+ )
30
+
31
+ _RETRY_KWARGS = dict(
32
+ wait=wait_exponential(multiplier=1, min=2, max=60),
33
+ stop=stop_after_attempt(5),
34
+ reraise=True
35
+ )
36
+
37
+
38
+ def _is_openai(model: str) -> bool:
39
+ return model.startswith(("gpt-", "o1-", "o3-", "o4-"))
40
+
41
+
42
+ def _make_client(cfg: Config) -> Any:
43
+ if _is_openai(cfg.api.model):
44
+ return openai.OpenAI(api_key=cfg.openai_api_key)
45
+ return anthropic.Anthropic(api_key=cfg.api_key)
46
+
47
+
48
+ def convert_chunk(
49
+ spec: ChunkSpec,
50
+ title: str,
51
+ authors: list[str],
52
+ cfg: Config,
53
+ client: Any = None
54
+ ) -> str:
55
+ if client is None:
56
+ client = _make_client(cfg)
57
+ return _call_with_retry(spec, title, authors, cfg, client)
58
+
59
+
60
+ def _call_with_retry(
61
+ spec: ChunkSpec,
62
+ title: str,
63
+ authors: list[str],
64
+ cfg: Config,
65
+ client: Any,
66
+ attempt: int = 0
67
+ ) -> str:
68
+ bad_request = openai.BadRequestError if _is_openai(cfg.api.model) else anthropic.BadRequestError
69
+ try:
70
+ if _is_openai(cfg.api.model):
71
+ return _do_call_openai(spec, title, authors, cfg, client)
72
+ return _do_call_anthropic(spec, title, authors, cfg, client)
73
+ except bad_request as exc:
74
+ if attempt >= 2:
75
+ raise
76
+ log.warning("Chunk %d failed (attempt %d), halving and retrying: %s", spec.chunk_idx, attempt, exc)
77
+ return _halve_and_retry(spec, title, authors, cfg, client, attempt)
78
+
79
+
80
+ @retry(retry=retry_if_exception_type(_ANTHROPIC_RETRYABLE), **_RETRY_KWARGS)
81
+ def _do_call_anthropic(
82
+ spec: ChunkSpec,
83
+ title: str,
84
+ authors: list[str],
85
+ cfg: Config,
86
+ client: anthropic.Anthropic
87
+ ) -> str:
88
+ pdf_bytes = spec.path.read_bytes()
89
+ pdf_b64 = base64.standard_b64encode(pdf_bytes).decode("utf-8")
90
+ user_text = build_user_instruction(
91
+ title=title,
92
+ authors=authors,
93
+ chunk_idx=spec.chunk_idx,
94
+ total=spec.total,
95
+ start=spec.start,
96
+ end=spec.end,
97
+ context_pages=spec.context_pages
98
+ )
99
+
100
+ response = client.messages.create(
101
+ model=cfg.api.model,
102
+ max_tokens=cfg.api.max_tokens,
103
+ system=SYSTEM_PROMPT,
104
+ messages=[
105
+ {
106
+ "role": "user",
107
+ "content": [
108
+ {
109
+ "type": "document",
110
+ "source": {
111
+ "type": "base64",
112
+ "media_type": "application/pdf",
113
+ "data": pdf_b64
114
+ },
115
+ "cache_control": {"type": "ephemeral"}
116
+ },
117
+ {"type": "text", "text": user_text}
118
+ ]
119
+ }
120
+ ]
121
+ )
122
+ return response.content[0].text
123
+
124
+
125
+ @retry(retry=retry_if_exception_type(_OPENAI_RETRYABLE), **_RETRY_KWARGS)
126
+ def _do_call_openai(
127
+ spec: ChunkSpec,
128
+ title: str,
129
+ authors: list[str],
130
+ cfg: Config,
131
+ client: openai.OpenAI
132
+ ) -> str:
133
+ import fitz
134
+
135
+ doc = fitz.open(spec.path)
136
+ content: list[dict] = []
137
+
138
+ mat = fitz.Matrix(150 / 72, 150 / 72)
139
+ for page in doc:
140
+ pix = page.get_pixmap(matrix=mat)
141
+ img_b64 = base64.standard_b64encode(pix.tobytes("png")).decode("utf-8")
142
+ content.append({
143
+ "type": "image_url",
144
+ "image_url": {"url": f"data:image/png;base64,{img_b64}", "detail": "high"}
145
+ })
146
+ doc.close()
147
+
148
+ user_text = build_user_instruction(
149
+ title=title,
150
+ authors=authors,
151
+ chunk_idx=spec.chunk_idx,
152
+ total=spec.total,
153
+ start=spec.start,
154
+ end=spec.end,
155
+ context_pages=spec.context_pages
156
+ )
157
+ content.append({"type": "text", "text": user_text})
158
+
159
+ response = client.chat.completions.create(
160
+ model=cfg.api.model,
161
+ max_completion_tokens=cfg.api.max_tokens,
162
+ messages=[
163
+ {"role": "system", "content": SYSTEM_PROMPT},
164
+ {"role": "user", "content": content}
165
+ ]
166
+ )
167
+ return response.choices[0].message.content
168
+
169
+
170
+ def _halve_and_retry(
171
+ spec: ChunkSpec,
172
+ title: str,
173
+ authors: list[str],
174
+ cfg: Config,
175
+ client: Any,
176
+ attempt: int
177
+ ) -> str:
178
+ import fitz
179
+
180
+ doc = fitz.open(spec.path)
181
+ n = len(doc)
182
+ mid = n // 2
183
+ tmp_dir = spec.path.parent
184
+
185
+ halves = []
186
+ for hi, (fr, to) in enumerate([(0, mid - 1), (mid, n - 1)]):
187
+ sub = fitz.open()
188
+ sub.insert_pdf(doc, from_page=fr, to_page=to)
189
+ sub_path = tmp_dir / f"{spec.path.stem}_half{hi}.pdf"
190
+ sub.save(sub_path)
191
+ sub.close()
192
+
193
+ half_spec = ChunkSpec(
194
+ path=sub_path,
195
+ start=spec.start + fr,
196
+ end=spec.start + to,
197
+ context_pages=spec.context_pages if hi == 0 else 0,
198
+ chunk_idx=spec.chunk_idx,
199
+ total=spec.total
200
+ )
201
+ halves.append(half_spec)
202
+
203
+ doc.close()
204
+
205
+ results = [_call_with_retry(half, title, authors, cfg, client, attempt + 1) for half in halves]
206
+ return "\n\n".join(results)
207
+
208
+
209
+ async def convert_chunks_async(
210
+ specs: list[ChunkSpec],
211
+ title: str,
212
+ authors: list[str],
213
+ cfg: Config
214
+ ) -> list[str]:
215
+ client = _make_client(cfg)
216
+ sem = asyncio.Semaphore(cfg.api.concurrency)
217
+
218
+ async def bounded(spec: ChunkSpec) -> str:
219
+ async with sem:
220
+ loop = asyncio.get_event_loop()
221
+ return await loop.run_in_executor(None, convert_chunk, spec, title, authors, cfg, client)
222
+
223
+ tasks = [bounded(spec) for spec in specs]
224
+ return await asyncio.gather(*tasks)
225
+
226
+
227
+ def convert_all(
228
+ specs: list[ChunkSpec],
229
+ title: str,
230
+ authors: list[str],
231
+ cfg: Config
232
+ ) -> list[str]:
233
+ return asyncio.run(convert_chunks_async(specs, title, authors, cfg))