-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsplit_book.py
More file actions
289 lines (232 loc) · 9.27 KB
/
Copy pathsplit_book.py
File metadata and controls
289 lines (232 loc) · 9.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/usr/bin/env python3
"""Split a book PDF into chapter-sized (or fixed-size) chunks for NotebookLM."""
import argparse
import re
import shutil
import sys
from pathlib import Path
from pypdf import PdfReader, PdfWriter
from pypdf.errors import PdfReadError
def load_reader(path):
p = Path(path)
if not p.exists():
print(f"Error: input file not found: {path}", file=sys.stderr)
sys.exit(1)
try:
reader = PdfReader(str(p))
except PdfReadError as e:
print(f"Error: could not read PDF '{path}': {e}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: could not open '{path}': {e}", file=sys.stderr)
sys.exit(1)
if reader.is_encrypted:
try:
result = reader.decrypt("")
except Exception:
result = 0
if not result:
stem = p.stem
print(
f"Error: '{path}' is encrypted and could not be opened with an "
f"empty password. Try decrypting it first, e.g.:\n"
f" qpdf --decrypt {path} {stem}_decrypted.pdf",
file=sys.stderr,
)
sys.exit(1)
try:
num_pages = len(reader.pages)
except Exception as e:
print(f"Error: could not read pages from '{path}': {e}", file=sys.stderr)
sys.exit(1)
if num_pages == 0:
print(f"Error: '{path}' has zero pages.", file=sys.stderr)
sys.exit(1)
return reader, num_pages
def _walk_outline(items, depth, level, reader, out):
for item in items:
if isinstance(item, list):
# A list immediately following an item is that item's children,
# one level deeper.
_walk_outline(item, depth + 1, level, reader, out)
continue
if depth == level:
try:
page_num = reader.get_destination_page_number(item)
except Exception:
continue
title = item.title if item.title else "Untitled"
out.append((page_num, title))
def get_chapters_from_outline(reader, level, num_pages):
try:
outline = reader.outline
except Exception:
outline = None
if not outline:
return None
entries = []
_walk_outline(outline, 1, level, reader, entries)
if not entries:
return None
entries.sort(key=lambda x: x[0])
deduped = []
seen_pages = set()
for page_num, title in entries:
if page_num in seen_pages:
continue
seen_pages.add(page_num)
deduped.append((page_num, title))
chapters = []
for i, (page_num, title) in enumerate(deduped):
start = page_num
end = deduped[i + 1][0] if i + 1 < len(deduped) else num_pages
if end <= start:
continue
chapters.append({"title": title, "start": start, "end": end})
return chapters if chapters else None
def group_chapters(chapters, target_pages):
if not chapters:
return []
groups = []
current = None
current_titles = []
for ch in chapters:
ch_pages = ch["end"] - ch["start"]
if current is None:
current = {"start": ch["start"], "end": ch["end"]}
current_titles = [ch["title"]]
else:
current_pages = current["end"] - current["start"]
if current_pages >= target_pages / 2 and ch_pages >= target_pages:
groups.append(_finalize_group(current, current_titles))
current = {"start": ch["start"], "end": ch["end"]}
current_titles = [ch["title"]]
else:
current["end"] = ch["end"]
current_titles.append(ch["title"])
current_pages = current["end"] - current["start"]
if current_pages >= target_pages:
groups.append(_finalize_group(current, current_titles))
current = None
current_titles = []
if current is not None:
groups.append(_finalize_group(current, current_titles))
# Fold a too-small trailing group into the previous one rather than
# leaving a tiny leftover file. Only applies to the final group.
if len(groups) >= 2:
last = groups[-1]
last_pages = last["end"] - last["start"]
if last_pages < target_pages / 2:
prev = groups[-2]
merged_title = f"{prev['title']}_to_{last['title']}"
prev["end"] = last["end"]
prev["title"] = merged_title
groups.pop()
return groups
def _finalize_group(current, titles):
title = titles[0] if len(titles) == 1 else f"{titles[0]}_to_{titles[-1]}"
return {"title": title, "start": current["start"], "end": current["end"]}
def get_chapters_fixed(num_pages, fixed_n):
if fixed_n <= 0:
raise ValueError(f"fixed_n must be a positive integer, got {fixed_n}")
chapters = []
start = 0
while start < num_pages:
end = min(start + fixed_n, num_pages)
chapters.append({"title": f"pages_{start + 1}-{end}", "start": start, "end": end})
start = end
return chapters
def slugify(title, max_len=60):
if title is None:
title = ""
cleaned = re.sub(r"[^\w\s-]", "", title, flags=re.UNICODE)
cleaned = re.sub(r"\s+", "_", cleaned.strip())
cleaned = cleaned.strip("_")
cleaned = cleaned[:max_len].strip("_")
return cleaned if cleaned else "untitled"
def write_chunks(reader, chunks, out_dir):
out_path = Path(out_dir)
if out_path.exists():
# Clear any stale files from a prior run at this path (e.g. a
# different --level/--target-pages produced a different chunk
# count/plan) so old files never linger alongside the new ones.
shutil.rmtree(out_path)
out_path.mkdir(parents=True, exist_ok=True)
width = len(str(len(chunks)))
written = []
for i, chunk in enumerate(chunks, start=1):
writer = PdfWriter()
for page_idx in range(chunk["start"], chunk["end"]):
writer.add_page(reader.pages[page_idx])
idx_str = str(i).zfill(width)
filename = f"{idx_str}_{slugify(chunk['title'])}.pdf"
file_path = out_path / filename
with open(file_path, "wb") as f:
writer.write(f)
num_pages = chunk["end"] - chunk["start"]
print(f"Wrote {file_path} ({num_pages} pages)")
written.append(file_path)
return written
def print_plan(chapters, num_pages):
print(f"{'Idx':>4} {'Pages':>15} {'Count':>6} Title")
total_pages_covered = 0
for i, ch in enumerate(chapters, start=1):
page_count = ch["end"] - ch["start"]
total_pages_covered += page_count
page_range = f"{ch['start'] + 1}-{ch['end']}"
print(f"{i:>4} {page_range:>15} {page_count:>6} {ch['title']}")
print(f"\nTotal chunks: {len(chapters)}, total pages covered: {total_pages_covered}")
def build_arg_parser():
parser = argparse.ArgumentParser(
description="Split a book PDF into smaller PDFs sized for NotebookLM sources."
)
parser.add_argument("input", help="Path to the source PDF.")
parser.add_argument("--level", type=int, default=1, help="Outline depth to split at (default 1).")
parser.add_argument(
"--target-pages", type=int, default=None,
help="Grouping mode: merge consecutive chapters until each group is at least N pages.",
)
parser.add_argument(
"--fixed", type=int, default=None,
help="Fallback mode: ignore the outline and split every N pages.",
)
parser.add_argument("--out", type=str, default="./chunks", help="Base output directory (default ./chunks).")
parser.add_argument("--list", action="store_true", help="Print the plan and exit without writing files.")
return parser
def main():
parser = build_arg_parser()
args = parser.parse_args()
if args.fixed is not None and args.fixed <= 0:
print(f"Error: --fixed must be a positive integer, got {args.fixed}.", file=sys.stderr)
sys.exit(1)
if args.target_pages is not None and args.target_pages <= 0:
print(f"Error: --target-pages must be a positive integer, got {args.target_pages}.", file=sys.stderr)
sys.exit(1)
input_path = Path(args.input)
reader, num_pages = load_reader(args.input)
print(f"Loaded {input_path.name}: {num_pages} pages")
if args.fixed is not None:
chapters = get_chapters_fixed(num_pages, args.fixed)
else:
chapters = get_chapters_from_outline(reader, args.level, num_pages)
if chapters is None:
if args.target_pages is not None:
chapters = get_chapters_fixed(num_pages, args.target_pages)
else:
print(
f"Error: no usable outline found at --level {args.level}. "
f"Try a different --level (e.g. --level {args.level + 1}), "
f"or use --fixed N / --target-pages N to split without an outline.",
file=sys.stderr,
)
sys.exit(1)
elif args.target_pages is not None:
chapters = group_chapters(chapters, args.target_pages)
print_plan(chapters, num_pages)
if args.list:
return
out_dir = Path(args.out) / input_path.stem
print(f"\nOutput directory: {out_dir}")
write_chunks(reader, chapters, out_dir)
if __name__ == "__main__":
main()