-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
803 lines (664 loc) · 29.8 KB
/
Copy pathmain.py
File metadata and controls
803 lines (664 loc) · 29.8 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
#!/usr/bin/env python3
"""NCERT Books Downloader — download and assemble NCERT textbooks as PDFs."""
import os
import json
import time
import queue
import shutil
import zipfile
import argparse
import threading
import multiprocessing
from pathlib import Path
from collections import deque
from contextlib import ExitStack
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
import questionary
import requests
from prompt_toolkit.keys import Keys
from prompt_toolkit.key_binding.key_processor import KeyPress
from pypdf import PdfWriter
from rich.console import Console
from rich.progress import (
Progress, SpinnerColumn, BarColumn, MofNCompleteColumn, TextColumn,
TimeElapsedColumn, TimeRemainingColumn, TaskProgressColumn, ProgressColumn,
)
from rich.table import Table
from rich.text import Text
console = Console()
BASE_URL = "https://ncert.nic.in/textbook/pdf/"
DATA_FILE = Path(__file__).parent / "data.json"
# Consistent prompt style: cyan highlight, no reverse-video white overlay
STYLE = questionary.Style([
("highlighted", "fg:cyan bold noreverse"),
("selected", "fg:green bold"),
("pointer", "fg:cyan bold"),
("answer", "fg:cyan bold"),
("instruction", "fg:#666666"),
("checkbox", "fg:#666666"),
("checkbox-selected", "fg:green bold"),
])
# ---------------------------------------------------------------------------
# Data
# ---------------------------------------------------------------------------
def load_data():
with open(DATA_FILE) as f:
return json.load(f)
def iter_books(data, cls_filter=None, subj_filter=None):
for cls, subjects in sorted(data.items(), key=lambda x: int(x[0])):
if cls_filter and cls != str(cls_filter):
continue
for subject, books in subjects.items():
if subj_filter and subject.lower() != subj_filter.lower():
continue
for book in books:
if book.get("code"):
yield cls, subject, book
# ---------------------------------------------------------------------------
# Interactive prompts
# ---------------------------------------------------------------------------
BACK = "__back__"
CANCEL = "__cancel__"
SEPARATOR = "────────"
NAV_HINT = " (↑↓ to move, → or enter to select, ← to go back)"
NAV_HINT_FIRST = " (↑↓ to move, → or enter to select)"
def with_nav(choices, back=True):
"""Wrap a menu's real choices in navigation entries.
Back goes on top, the way `..` sits at the top of a directory listing;
Cancel goes at the bottom, out of the way of everything you'd normally
pick."""
head = [questionary.Choice("← Back", value=BACK), questionary.Separator(SEPARATOR)] if back else []
tail = [questionary.Separator(SEPARATOR), questionary.Choice("✕ Cancel", value=CANCEL)]
return head + list(choices) + tail
def first_value(choices):
"""The first real choice — what the cursor should start on, since with Back
at the top an unguarded Enter would otherwise step backwards."""
for choice in choices:
if isinstance(choice, str):
return choice
if isinstance(choice, questionary.Choice) and choice.value not in (BACK, CANCEL):
return choice.value
return None
def add_arrow_nav(question, back=True):
"""Left steps back a level, right steps forward — file-browser keys.
Right re-feeds Enter rather than duplicating the accept logic, so it stays
correct for both select (take the pointed choice) and checkbox (validate,
then confirm)."""
bindings = question.application.key_bindings
if back:
@bindings.add(Keys.Left, eager=True)
def _go_back(event):
event.app.exit(result=BACK)
@bindings.add(Keys.Right, eager=True)
def _go_forward(event):
# first=True: anything already queued behind this key belongs to the
# *next* prompt, so the synthetic Enter has to jump the queue
event.app.key_processor.feed(KeyPress(Keys.ControlM, "\r"), first=True)
return question
def ask_nav(question, back=True):
"""Run a prompt, mapping Ctrl+C to Back — or to Cancel at the first level.
kbi_msg is silenced because stepping back isn't an error."""
answer = add_arrow_nav(question, back=back).ask(kbi_msg="")
return (BACK if back else CANCEL) if answer is None else answer
def interactive_select(data):
"""Guided prompts: class → subject → all or pick specific books.
Navigation is file-browser style: → or enter goes forward, ← goes back a
level, and every menu also carries a Back row at the top and a Cancel row
at the bottom. Ctrl+C behaves like ← (cancelling at the first level).
Earlier answers are remembered, so going back and forward doesn't lose them.
Returns a list of (cls, subject, book) tuples, or None if cancelled."""
classes = sorted(data.keys(), key=int)
seen = {} # remembered answers, keyed by step
step = 0
while True:
# --- Step 0: class ---------------------------------------------------
if step == 0:
choices = ["All classes"] + [f"Class {c}" for c in classes]
answer = ask_nav(questionary.select(
"Which class?",
choices=with_nav(choices, back=False),
default=seen.get("cls") if seen.get("cls") in choices else choices[0],
instruction=NAV_HINT_FIRST,
style=STYLE,
), back=False)
if answer == CANCEL:
return None
seen["cls"] = answer
step = 1
# --- Step 1: subject -------------------------------------------------
elif step == 1:
cls_filter = None if seen["cls"] == "All classes" else seen["cls"].split()[1]
subjects = sorted({
subj
for cls, subj_dict in data.items()
if not cls_filter or cls == cls_filter
for subj in subj_dict
})
choices = ["All subjects"] + subjects
answer = ask_nav(questionary.select(
"Which subject?",
choices=with_nav(choices),
default=seen.get("subj") if seen.get("subj") in choices else choices[0],
instruction=NAV_HINT,
style=STYLE,
))
if answer == CANCEL:
return None
if answer == BACK:
step = 0
continue
seen["subj"] = answer
step = 2
# --- Step 2: all or pick ---------------------------------------------
else:
cls_filter = None if seen["cls"] == "All classes" else seen["cls"].split()[1]
subj_filter = None if seen["subj"] == "All subjects" else seen["subj"]
all_books = list(iter_books(data, cls_filter, subj_filter))
if not all_books:
return []
n = len(all_books)
if step == 2:
mode_choices = [
questionary.Choice(f"All {n} books", value="all"),
questionary.Choice("Let me pick specific ones", value="pick"),
]
answer = ask_nav(questionary.select(
f"Found {n} book{'s' if n != 1 else ''}. What would you like to download?",
choices=with_nav(mode_choices),
default=first_value(mode_choices),
instruction=NAV_HINT,
style=STYLE,
))
if answer == CANCEL:
return None
if answer == BACK:
step = 1
continue
if answer == "all":
return all_books
step = 3
# --- Step 3: pick specific books ---------------------------------
# Show context when spanning multiple subjects/classes
multi_subject = subj_filter is None
def book_label(cls, subject, book):
return f"{subject} — {book['text']}" if multi_subject else book["text"]
# None pre-selected, so the user makes deliberate choices
choices = [
questionary.Choice(title=book_label(cls, subject, book), value=(cls, subject, book))
for cls, subject, book in all_books
]
# A "← Back" row would sit oddly among checkable books, so here the
# left arrow is the only way back
selected = add_arrow_nav(questionary.checkbox(
"Select books:",
choices=choices,
instruction=" (space to check/uncheck, → or enter to confirm, ← to go back)",
validate=lambda x: True if x else "Press space to select at least one book first",
style=STYLE,
)).ask(kbi_msg="")
if selected in (None, BACK): # ← or Ctrl+C — back to the all-or-pick menu
step = 2
continue
return selected
# ---------------------------------------------------------------------------
# Catalog
# ---------------------------------------------------------------------------
def show_catalog(data, cls_filter=None, subj_filter=None):
table = Table(title="NCERT Books Catalog", show_lines=True)
table.add_column("Class", style="cyan", justify="center", no_wrap=True)
table.add_column("Subject", style="green", no_wrap=True)
table.add_column("Books", style="white")
seen = set()
for cls, subject, _ in iter_books(data, cls_filter, subj_filter):
if (cls, subject) not in seen:
titles = [b["text"] for b in data[cls][subject] if b.get("code")]
table.add_row(f"Class {cls}", subject, "\n".join(titles))
seen.add((cls, subject))
console.print(table)
# ---------------------------------------------------------------------------
# Download
# ---------------------------------------------------------------------------
def book_paths(cls, subject, book, out_dir):
"""Zip destination, the merged PDF, and the partial-download file."""
dest = out_dir / f"Class {cls}" / subject / f"{book['text']}.zip"
return dest, dest.with_suffix(".pdf"), dest.with_suffix(".zip.tmp")
def already_have(dest, pdf):
"""Merging deletes the zip, so a finished book is one with either file."""
return dest.exists() or pdf.exists()
def download_book(cls, subject, book, out_dir, tracker=None):
dest, pdf, tmp = book_paths(cls, subject, book, out_dir)
if already_have(dest, pdf):
return "skipped"
url = f"{BASE_URL}{book['code']}dd.zip"
dest.parent.mkdir(parents=True, exist_ok=True)
if tracker:
tracker.begin(book["text"])
try:
# Resume from a previous partial download if the tmp file exists
resume_at = tmp.stat().st_size if tmp.exists() else 0
headers = {"Range": f"bytes={resume_at}-"} if resume_at else {}
r = requests.get(url, stream=True, timeout=30, headers=headers)
r.raise_for_status()
# Server may ignore the Range header (returns 200 instead of 206)
if r.status_code == 200 and resume_at:
resume_at = 0 # restart; don't append stale bytes
with open(tmp, "ab" if resume_at else "wb") as f:
for chunk in r.iter_content(65536):
f.write(chunk)
if tracker:
tracker.add(len(chunk))
tmp.rename(dest)
return "ok"
except Exception as e:
return f"error: {e}" # keep tmp for next resume attempt
finally:
if tracker:
tracker.end(book["text"])
# ---------------------------------------------------------------------------
# Size probe
# ---------------------------------------------------------------------------
MISSING = "missing"
UNKNOWN = "unknown"
def probe_book(cls, subject, book, out_dir):
"""Ask the server how big a book is. Returns (bytes still to fetch, status).
NCERT's catalog lists titles they never published, so a 404 here means the
book is missing rather than that anything went wrong."""
dest, pdf, tmp = book_paths(cls, subject, book, out_dir)
if already_have(dest, pdf):
return 0, "skipped"
try:
r = requests.head(f"{BASE_URL}{book['code']}dd.zip", timeout=15, allow_redirects=True)
if r.status_code == 404:
return 0, MISSING
r.raise_for_status()
size = int(r.headers.get("Content-Length", 0))
except Exception:
return 0, UNKNOWN
if not size:
return 0, UNKNOWN
# Bytes already on disk from an interrupted run don't need fetching again
resume_at = tmp.stat().st_size if tmp.exists() else 0
return max(size - resume_at, 0), "ok"
def probe_sizes(books, out_dir, concurrency):
"""HEAD every book up front, so the download bar can show size and ETA —
and so books NCERT never published are reported before we start, not as
failures halfway through.
Returns (total bytes to fetch or None if any size is unknown, missing)."""
total = 0
missing = []
known = True
with Progress(
SpinnerColumn(),
TextColumn(" [bold]Checking sizes[/bold]"),
BarColumn(bar_width=24),
MofNCompleteColumn(),
console=console,
transient=True, # a means to an end; the download bar replaces it
) as progress:
task = progress.add_task("probe", total=len(books))
with ThreadPoolExecutor(max_workers=concurrency) as executor:
futures = {
executor.submit(probe_book, cls, subject, book, out_dir): (cls, subject, book)
for cls, subject, book in books
}
for future in as_completed(futures):
size, status = future.result()
if status == MISSING:
missing.append(futures[future])
elif status == UNKNOWN:
known = False # one unknown makes the whole total a guess
total += size
progress.advance(task)
return (total if known else None), missing
def report_missing(missing, limit=5):
"""Name the books NCERT lists but doesn't host."""
n = len(missing)
# highlight=False throughout: Rich would otherwise colour stray numbers and
# words inside book titles
console.print(f" [yellow]{n} book{'s' if n != 1 else ''} not published by NCERT — skipping[/yellow]",
highlight=False)
for cls, subject, book in missing[:limit]:
console.print(f" [dim]Class {cls} · {subject} · {book['text']}[/dim]", highlight=False)
if n > limit:
console.print(f" [dim]… and {n - limit} more[/dim]", highlight=False)
# ---------------------------------------------------------------------------
# Merge
# ---------------------------------------------------------------------------
def merge_book(zip_path, keep_zip, tracker=None):
out_pdf = zip_path.with_suffix(".pdf")
if out_pdf.exists():
return "skipped"
temp_dir = zip_path.parent / f"_tmp_{zip_path.stem}"
if tracker:
tracker.begin(zip_path.stem)
try:
with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(temp_dir)
# Sort alphabetically; NCERT names prelim/cover with a non-numeric
# suffix (e.g. *ps.pdf) which sorts last — move it to the front.
pdf_files = sorted(temp_dir.rglob("*.pdf"))
if not pdf_files:
return "error: no PDFs found in zip"
if len(pdf_files) > 1:
pdf_files.insert(0, pdf_files.pop())
writer = PdfWriter()
for pdf in pdf_files:
writer.append(str(pdf))
with open(out_pdf, "wb") as f:
writer.write(f)
if not keep_zip:
zip_path.unlink()
return "ok"
except Exception as e:
return f"error: {e}"
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
if tracker:
tracker.end(zip_path.stem)
# ---------------------------------------------------------------------------
# Progress
# ---------------------------------------------------------------------------
def human_bytes(n):
for unit in ("B", "KB", "MB", "GB"):
if n < 1024 or unit == "GB":
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
n /= 1024
class QueueReporter:
"""What a worker *process* reports through: events go over a manager queue
for the parent's Tracker to apply. Same interface workers see either way."""
def __init__(self, queue):
self._queue = queue
def begin(self, name):
self._queue.put(("begin", name))
def add(self, n):
self._queue.put(("bytes", n))
def end(self, name):
self._queue.put(("end", name))
class Tracker:
"""Thread-safe view of what the workers are doing right now.
Workers report bytes and the item they're on; the progress columns read
the aggregate back on every refresh."""
WINDOW = 3.0 # seconds of history used for the speed reading
def __init__(self):
self._lock = threading.Lock()
self._bytes = 0
self._active = {} # name -> start time, insertion-ordered
self._samples = deque(maxlen=64) # (timestamp, total bytes)
self._queue = None # set when worker processes report in
# -- worker side (called from threads, or via QueueReporter from processes)
def begin(self, name):
with self._lock:
self._active[name] = time.monotonic()
def add(self, n):
with self._lock:
self._bytes += n
def end(self, name):
with self._lock:
self._active.pop(name, None)
def reporter(self, manager):
"""A picklable stand-in for worker processes, which can't share memory.
Its events are applied here on the next read. Chatty for per-chunk byte
counts — meant for coarse begin/end reporting."""
self._queue = manager.Queue()
return QueueReporter(self._queue)
def detach(self):
"""Stop reading the queue — call before its manager shuts down, or
later reads (including Rich's final refresh) hit a dead proxy."""
with self._lock:
self._drain()
self._queue = None
self._active.clear()
def _drain(self):
"""Apply queued events from worker processes. Caller holds the lock."""
while self._queue is not None:
try:
kind, value = self._queue.get_nowait()
except queue.Empty:
return
except (OSError, EOFError): # manager already gone
self._queue = None
return
if kind == "begin":
self._active[value] = time.monotonic()
elif kind == "end":
self._active.pop(value, None)
else:
self._bytes += value
# -- reader side
def total_bytes(self):
with self._lock:
self._drain()
return self._bytes
def speed(self):
"""Bytes/sec over the trailing window, or None until there's history."""
now = time.monotonic()
with self._lock:
self._drain()
self._samples.append((now, self._bytes))
window = [s for s in self._samples if s[0] >= now - self.WINDOW]
if len(window) < 2:
return None
(t0, b0), (t1, b1) = window[0], window[-1]
return (b1 - b0) / (t1 - t0) if t1 > t0 else None
def status(self):
"""What's in flight: one name, plus a count of the rest."""
with self._lock:
self._drain()
names = list(self._active)
if not names:
return ""
# Oldest in-flight item — the one most likely to be holding things up
head = names[0]
if len(head) > 42:
head = head[:41] + "…"
return f"{head} (+{len(names) - 1} more)" if len(names) > 1 else head
class StatsColumn(ProgressColumn):
"""Transferred bytes — against a known total when we have one — and speed."""
def __init__(self, tracker, expected=None):
self.tracker = tracker
self.expected = expected
super().__init__()
def render(self, task):
got = self.tracker.total_bytes()
if not got and not self.expected:
return Text("")
text = human_bytes(got)
if self.expected:
text += f"/{human_bytes(self.expected)}"
speed = self.tracker.speed()
if speed:
text += f" · {human_bytes(speed)}/s"
return Text.assemble(("· ", "dim"), (text, "cyan"))
class ItemsColumn(ProgressColumn):
"""Books finished, for when the bar itself is measuring bytes."""
def __init__(self, counter):
self.counter = counter
super().__init__()
def render(self, task):
return Text.assemble(("· ", "dim"), (f"{self.counter['done']}/{self.counter['total']}", "green"))
class EtaColumn(TimeRemainingColumn):
"""Rich's time-remaining estimate, labelled so it isn't mistaken for elapsed."""
def render(self, task):
out = Text("· eta ", style="dim")
out.append(super().render(task))
return out
class StatusColumn(ProgressColumn):
"""Dim trailing line naming the item(s) currently being worked on."""
def __init__(self, tracker):
self.tracker = tracker
super().__init__()
def render(self, task):
status = self.tracker.status()
if not status:
return Text("")
return Text(f"· {status}", style="dim", overflow="ellipsis", no_wrap=True)
def run_concurrent(label, items, fn, concurrency, tracker=None, use_processes=False,
expected_bytes=None, show_bytes=True):
"""Run fn over items, reporting into a shared progress bar.
use_processes escapes the GIL for CPU-bound work (merging); downloads are
I/O-bound and cheaper in threads. expected_bytes switches the bar from
counting items to counting bytes, which is what makes a percentage and an
ETA meaningful — books vary from a few MB to 2 GB, so 3/10 books done says
very little about how far along you are."""
ok = skipped = errors = 0
counter = {"done": 0, "total": len(items)}
if expected_bytes and not tracker:
expected_bytes = None # bytes come from the tracker; without one, count items
columns = [
SpinnerColumn(),
TextColumn(f" [bold]{label}[/bold]"),
BarColumn(bar_width=24 if expected_bytes else 30),
]
if expected_bytes:
columns += [TaskProgressColumn(), ItemsColumn(counter),
StatsColumn(tracker, expected_bytes), EtaColumn()]
else:
columns += [MofNCompleteColumn(), TextColumn("[dim]·[/dim]"), TimeElapsedColumn()]
if tracker and show_bytes: # merging moves no bytes; don't reserve the space
columns.append(StatsColumn(tracker))
if tracker:
columns.append(StatusColumn(tracker))
with Progress(*columns, console=console) as progress, ExitStack() as stack:
task = progress.add_task(label, total=expected_bytes or len(items))
if expected_bytes:
# Bytes land in the tracker continuously; mirror them onto the task
# so the bar, percentage and ETA move between completions.
done = threading.Event()
stack.callback(done.set)
def mirror_bytes():
while not done.wait(0.1):
progress.update(task, completed=tracker.total_bytes())
threading.Thread(target=mirror_bytes, daemon=True).start()
if use_processes:
manager = stack.enter_context(multiprocessing.Manager())
reporter = tracker.reporter(manager) if tracker else None
if tracker:
stack.callback(tracker.detach) # LIFO: runs before the manager stops
executor = stack.enter_context(ProcessPoolExecutor(max_workers=concurrency))
else:
reporter = tracker
executor = stack.enter_context(ThreadPoolExecutor(max_workers=concurrency))
kwargs = {"tracker": reporter} if reporter else {}
futures = {executor.submit(fn, *item, **kwargs): item for item in items}
for future in as_completed(futures):
result = future.result()
if result == "ok":
ok += 1
elif result == "skipped":
skipped += 1
else:
errors += 1
console.log(f"[red]{result}[/red]")
counter["done"] += 1
if not expected_bytes:
progress.advance(task)
if expected_bytes: # land on the real figure, not the last sample
progress.update(task, completed=tracker.total_bytes())
return ok, skipped, errors
def print_summary(ok, skipped, errors, total_bytes=0):
parts = []
if ok:
parts.append(f"[green]{ok} done[/green]")
if skipped:
parts.append(f"[dim]{skipped} skipped[/dim]")
if errors:
parts.append(f"[red]{errors} failed[/red]")
if total_bytes:
parts.append(f"[dim]{human_bytes(total_bytes)} transferred[/dim]")
if parts:
console.print(" " + ", ".join(parts), highlight=False)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="Download NCERT textbooks as merged PDFs.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""\
examples:
uv run main.py interactive mode (default)
uv run main.py --class 10 all Class 10 books, no prompts
uv run main.py --class 10 --subject Mathematics
uv run main.py --list browse the full catalog
uv run main.py --download-only download zips, skip merging
uv run main.py --merge-only merge existing zips, skip downloading
uv run main.py --keep-zips keep zip files after merging
""",
)
parser.add_argument("--class", dest="cls", metavar="N", help="filter by class number")
parser.add_argument("--subject", metavar="NAME", help="filter by subject name")
parser.add_argument("--list", action="store_true", help="list available books and exit")
parser.add_argument("--download-only", action="store_true", help="skip PDF merging")
parser.add_argument("--merge-only", action="store_true", help="skip downloading")
parser.add_argument("--keep-zips", action="store_true", help="keep zip files after merging")
parser.add_argument("--out", default="downloads", metavar="DIR", help="output directory (default: downloads)")
parser.add_argument("--concurrency", type=int, default=20, metavar="N", help="parallel downloads (default: 20)")
parser.add_argument("--merge-concurrency", type=int, default=os.cpu_count() or 4, metavar="N",
help="parallel merge processes (default: one per CPU)")
parser.add_argument("--no-probe", action="store_true",
help="skip the size check (no total or ETA, missing books fail mid-download)")
args = parser.parse_args()
out_dir = Path(args.out)
data = load_data()
console.print("\n[bold cyan]NCERT Books Downloader[/bold cyan]\n")
if args.list:
show_catalog(data, args.cls, args.subject)
return
cls_filter = args.cls
subj_filter = args.subject
interactive = not cls_filter and not subj_filter and not args.merge_only
if interactive:
books = interactive_select(data)
if books is None:
console.print("[yellow]Cancelled.[/yellow]\n")
return
console.print()
else:
books = list(iter_books(data, cls_filter, subj_filter))
if not books:
console.print("[yellow]No books selected.[/yellow]")
return
n = len(books)
if not args.merge_only:
expected = None
if not args.no_probe:
expected, missing = probe_sizes(books, out_dir, args.concurrency)
if missing:
report_missing(missing)
skip = {(cls, subject, book["code"]) for cls, subject, book in missing}
books = [b for b in books if (b[0], b[1], b[2]["code"]) not in skip]
n = len(books)
if not books:
console.print("\n[yellow]Nothing left to download.[/yellow]\n")
return
size_note = f" ([cyan]{human_bytes(expected)}[/cyan])" if expected else ""
console.print(f"[bold]Downloading {n} book{'s' if n != 1 else ''}{size_note}...[/bold]")
items = [(cls, subject, book, out_dir) for cls, subject, book in books]
tracker = Tracker()
ok, skipped, errors = run_concurrent(
"Downloading", items, download_book, args.concurrency,
tracker=tracker, expected_bytes=expected,
)
print_summary(ok, skipped, errors, tracker.total_bytes())
if not args.download_only:
zip_files = sorted(out_dir.rglob("*.zip"))
if zip_files:
console.print(f"\n[bold]Merging {len(zip_files)} book{'s' if len(zip_files) != 1 else ''}...[/bold]")
items = [(z, args.keep_zips) for z in zip_files]
# Merging is CPU-bound (pypdf is pure Python), so it needs real
# processes — threads just contend on the GIL.
ok, skipped, errors = run_concurrent(
"Merging", items, merge_book,
concurrency=args.merge_concurrency,
tracker=Tracker(),
use_processes=True,
show_bytes=False,
)
print_summary(ok, skipped, errors)
console.print(f"\n[bold green]Done![/bold green] Books saved to [cyan]{out_dir.resolve()}[/cyan]\n")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
# Partial zips are kept, so a re-run resumes where this left off
console.print("\n[yellow]Interrupted.[/yellow]\n")