pyread-cli 0.1.0__py3-none-any.whl

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.
pyread/cli.py ADDED
@@ -0,0 +1,1088 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import random
6
+ import re
7
+ import sys
8
+ from urllib.parse import quote as url_quote
9
+ from collections.abc import Callable, Iterator
10
+ from dataclasses import asdict, dataclass
11
+ from queue import Empty, SimpleQueue
12
+ from threading import Thread
13
+ from time import monotonic
14
+ from contextlib import contextmanager, nullcontext
15
+ from functools import wraps
16
+ from concurrent.futures import ThreadPoolExecutor
17
+
18
+ import click
19
+ import requests
20
+ import typer
21
+ from rich.console import Console
22
+ from rich.panel import Panel
23
+ from rich.prompt import Prompt
24
+ from rich.table import Table
25
+ from rich.text import Text
26
+ from rich.markup import escape
27
+
28
+ from pyread import state
29
+ from pyread.terminal import key_reader
30
+ from pyread.core.budget import target_words
31
+ from pyread.core.cache import cached_text, read_cached_text
32
+ from pyread.core.timer import ReadingTimer
33
+ from pyread.core.text_model import SAMPLE_SIZE, clean_segments
34
+ from pyread.core.extractor import book_text_end, collect_segments, strip_front_matter
35
+ from pyread.core.fetcher import (
36
+ book_description,
37
+ available_identifier,
38
+ fetch_book_text,
39
+ search_books,
40
+ )
41
+
42
+ app = typer.Typer(help="A terminal-based reading tool.")
43
+ console = Console()
44
+
45
+
46
+ @contextmanager
47
+ def _screen():
48
+ """Keep one alternate screen open across nested views."""
49
+ with (nullcontext() if console.is_alt_screen else console.screen()):
50
+ yield
51
+
52
+
53
+ def _wait_to_close(message: str) -> None:
54
+ console.print(Text(message, style="dim"))
55
+ try:
56
+ click.getchar()
57
+ except (KeyboardInterrupt, EOFError):
58
+ pass
59
+
60
+
61
+ def _fullscreen_command(command):
62
+ @wraps(command)
63
+ def run(*args, **kwargs):
64
+ if (console.is_alt_screen
65
+ or kwargs.get("no_pager") or not sys.stdin.isatty() or not sys.stdout.isatty()):
66
+ return command(*args, **kwargs)
67
+ with _screen():
68
+ try:
69
+ return command(*args, **kwargs)
70
+ finally:
71
+ _wait_to_close("Press any key to close.")
72
+ return run
73
+
74
+
75
+ # ---------- Pager helpers ----------
76
+
77
+ def _paginate(segments: list[tuple[str, int, int]], width: int, height: int) -> list[tuple[str, int]]:
78
+ """Make bounded pages; resume at a paragraph start to avoid losing text."""
79
+ pages = []
80
+ lines: list[str] = []
81
+ page_start = 0
82
+ for paragraph, start, _ in segments:
83
+ wrapped = [line.plain for line in Text(paragraph).wrap(console, max(1, width), overflow="fold")]
84
+ if lines and len(lines) + 1 + len(wrapped) <= height:
85
+ lines.append("")
86
+ elif lines:
87
+ pages.append(("\n".join(lines), page_start))
88
+ lines = []
89
+ while wrapped:
90
+ if not lines:
91
+ page_start = start
92
+ available = height - len(lines)
93
+ lines.extend(wrapped[:available])
94
+ wrapped = wrapped[available:]
95
+ if len(lines) == height:
96
+ pages.append(("\n".join(lines), page_start))
97
+ lines = []
98
+ if lines:
99
+ pages.append(("\n".join(lines), page_start))
100
+ return pages
101
+
102
+
103
+ def _terminal_size() -> tuple[int, int]:
104
+ """Prefer the output terminal's current size over stale COLUMNS/LINES."""
105
+ try:
106
+ size = os.get_terminal_size(console.file.fileno())
107
+ if size.columns > 0 and size.lines > 0:
108
+ return size.columns, size.lines
109
+ except (AttributeError, OSError, ValueError):
110
+ pass
111
+ size = console.size
112
+ return size.width, size.height
113
+
114
+
115
+ def _page_size(max_lines: int = 12) -> tuple[int, int]:
116
+ """Reserve space for the border, controls and a bottom margin."""
117
+ width, height = _terminal_size()
118
+ return max(1, min(width - 4, 100)), max(1, min(max_lines, height - 8))
119
+
120
+
121
+ def _render_page(text: str, num: int, total: int, title: str, timer_expired: bool = False,
122
+ progress: str | None = None) -> None:
123
+ width, height = _terminal_size()
124
+ # Rich also consults COLUMNS when rendering; use the same measured dimensions
125
+ # for wrapping and output so a stale environment cannot add extra rows.
126
+ screen = Console(file=console.file, width=width, height=height,
127
+ force_terminal=console.is_terminal, color_system=console.color_system,
128
+ no_color=console.no_color)
129
+ screen.clear()
130
+ heading = Text(title, style="bold cyan", overflow="ellipsis", no_wrap=True)
131
+ subtitle = f"{num} / {total}" + (f" · Book {progress}" if progress else "")
132
+ screen.print(Panel(Text(text), title=heading, subtitle=subtitle,
133
+ border_style="cyan", padding=(0, 1), width=min(width, 104)),
134
+ width=width)
135
+ controls_text = "Timer finished • " if timer_expired else ""
136
+ controls_text += "n/space next p previous q save & quit"
137
+ controls = Text(controls_text, style="yellow" if timer_expired else "dim", no_wrap=True, overflow="ellipsis")
138
+ screen.print(controls, justify="center", crop=True, width=width)
139
+
140
+
141
+ def _read_interactive(
142
+ segments: list[tuple[str, int, int]], title: str, total_chars: int,
143
+ timer: ReadingTimer | None = None, page_lines: int = 12,
144
+ progress: BookProgress | None = None, excerpt_start: int = 0,
145
+ ) -> tuple[int, bool, int]:
146
+ """Navigate pages, counting each completed page once per layout."""
147
+ width, height = _page_size(page_lines)
148
+ pages = state.cached_pages(segments, width, height, _paginate)
149
+ idx = 0
150
+ completed: set[int] = set()
151
+ pages_read = 0
152
+ while True:
153
+ new_width, new_height = _page_size(page_lines)
154
+ if (new_width, new_height) != (width, height):
155
+ # Save completed counts before rebuilding; resume at a safe paragraph boundary.
156
+ pages_read += len(completed)
157
+ completed.clear()
158
+ offset = pages[idx][1]
159
+ width, height = new_width, new_height
160
+ pages = state.cached_pages(segments, width, height, _paginate)
161
+ idx = next((i for i, page in enumerate(pages) if page[1] >= offset), len(pages) - 1)
162
+ _render_page(pages[idx][0], idx + 1, len(pages), title,
163
+ timer_expired=bool(timer and timer.expired.is_set()),
164
+ progress=progress.label(excerpt_start + pages[idx][1]) if progress else None)
165
+ try:
166
+ key = click.getchar()
167
+ except (KeyboardInterrupt, EOFError):
168
+ return pages[idx][1], False, pages_read + len(completed)
169
+
170
+ if key in ("q", "Q"):
171
+ return pages[idx][1], False, pages_read + len(completed)
172
+ if key in ("n", "N", " ", "\r", "\n", "\x1b[C"):
173
+ completed.add(idx)
174
+ if idx < len(pages) - 1:
175
+ idx += 1
176
+ else:
177
+ return total_chars, True, pages_read + len(completed)
178
+ elif key in ("p", "P", "\x7f", "\x1b[D") and idx > 0:
179
+ idx -= 1
180
+
181
+
182
+ def _preview_lines(value: str, width: int, height: int) -> Text:
183
+ """Wrap preview text and mark omitted content without slicing words."""
184
+ lines: list[list[str]] = [[]]
185
+ used = 0
186
+ for word in value.split():
187
+ cells = Text(word).cell_len
188
+ if cells > width:
189
+ word = "…"
190
+ cells = 1
191
+ if lines[-1] and used + 1 + cells > width:
192
+ lines.append([])
193
+ used = 0
194
+ used += cells + bool(lines[-1])
195
+ lines[-1].append(word)
196
+
197
+ visible = [" ".join(words) for words in lines[:height]]
198
+ if len(lines) > height:
199
+ last_words = lines[height - 1]
200
+ while last_words and Text(" ".join(last_words) + "…").cell_len > width:
201
+ last_words.pop()
202
+ visible[-1] = " ".join(last_words) + "…"
203
+ # The preview is already wrapped to the panel's inner width.
204
+ return Text("\n".join(visible), no_wrap=True, overflow="ignore")
205
+
206
+
207
+ def _select_search_results(results: list[dict], query: str) -> list[int]:
208
+ """Choose results with keys on a terminal, or numbered input when piped."""
209
+ suggested = any("category" in book for book in results)
210
+ title = "Suggested books" if suggested else f"Results for {query!r}"
211
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
212
+ table = Table(title=Text(title))
213
+ table.add_column("#", justify="right")
214
+ table.add_column("Title")
215
+ table.add_column("Author")
216
+ table.add_column("Category" if suggested else "Source")
217
+ for index, result in enumerate(results, 1):
218
+ table.add_row(str(index), Text(result["title"]), Text(result["author"]), result.get("category", result.get("source", "Archive")))
219
+ console.print(table)
220
+ raw = Prompt.ask("Numbers to add, comma-separated (or q to cancel)", default="q")
221
+ if raw.strip().lower() == "q":
222
+ return []
223
+ try:
224
+ indices = list(dict.fromkeys(int(value.strip()) - 1 for value in raw.split(",")))
225
+ except ValueError:
226
+ console.print("[red]Invalid selection.[/red]")
227
+ return []
228
+ return [index for index in indices if 0 <= index < len(results)]
229
+
230
+ with key_reader() as read_key:
231
+ executor = ThreadPoolExecutor(max_workers=1)
232
+ try:
233
+ return _browse_results(results, title, suggested, read_key, executor)
234
+ finally:
235
+ executor.shutdown(wait=False, cancel_futures=True)
236
+
237
+
238
+ def _browse_results(results, title, suggested, read_key, executor) -> list[int]:
239
+ cursor = 0
240
+ selected: set[int] = set()
241
+ descriptions = {}
242
+ pending = None
243
+ while True:
244
+ # Leave room for the title, table borders, controls and the terminal's last row.
245
+ terminal_width, terminal_height = _terminal_size()
246
+ detail_lines = min(3, max(0, terminal_height - 11))
247
+ page_size = max(1, min(8, terminal_height - 10 - detail_lines))
248
+ start = (cursor // page_size) * page_size
249
+ console.clear()
250
+ table = Table(title=Text(f"{title} ({cursor + 1}/{len(results)})"),
251
+ expand=True)
252
+ table.add_column("", width=2, no_wrap=True)
253
+ table.add_column("", width=3, no_wrap=True)
254
+ table.add_column("Title", overflow="ellipsis", no_wrap=True)
255
+ table.add_column("Author", overflow="ellipsis", no_wrap=True)
256
+ table.add_column("Category" if suggested else "Source", overflow="ellipsis", no_wrap=True)
257
+ for index in range(start, min(start + page_size, len(results))):
258
+ result = results[index]
259
+ table.add_row("›" if index == cursor else " ",
260
+ Text("[x]" if index in selected else "[ ]"),
261
+ Text(result["title"]), Text(result["author"]),
262
+ Text(result.get("category", result.get("source", "Archive"))),
263
+ style="bold black on cyan" if index == cursor else None)
264
+ console.print(table)
265
+ if detail_lines:
266
+ result = results[cursor]
267
+ if pending and pending[1].done():
268
+ index, future = pending
269
+ descriptions[index] = future.result()
270
+ pending = None
271
+ if cursor not in descriptions and pending is None:
272
+ if result.get("work_key"):
273
+ pending = (cursor, executor.submit(book_description, result))
274
+ else:
275
+ descriptions[cursor] = result.get("description", "")
276
+ description = descriptions.get(cursor, "Loading…") or "No description available."
277
+ subjects = results[cursor].get("subjects") or []
278
+ width = max(1, min(terminal_width, console.width) - 4)
279
+ subject_line = None
280
+ if subjects and detail_lines > 1:
281
+ subject_line = _preview_lines("Subjects: " + ", ".join(subjects[:4]), width, 1)
282
+ summary = _preview_lines(
283
+ "Description: " + description, width, detail_lines - bool(subject_line)
284
+ )
285
+ if subject_line:
286
+ summary.append("\n").append_text(subject_line)
287
+ console.print(Panel(summary, title="About this book", border_style="dim", padding=(0, 1)))
288
+ console.print(Text("↑/↓ move space select enter add q cancel", style="dim",
289
+ no_wrap=True, overflow="ellipsis"), crop=True)
290
+ try:
291
+ key = read_key(0.1 if detail_lines and pending else None)
292
+ if key is None:
293
+ continue
294
+ except (KeyboardInterrupt, EOFError):
295
+ return []
296
+ if key in ("q", "Q", "\x1b"):
297
+ return []
298
+ if key in ("\x1b[A", "\x1bOA", "k", "K"):
299
+ cursor = max(0, cursor - 1)
300
+ elif key in ("\x1b[B", "\x1bOB", "j", "J"):
301
+ cursor = min(len(results) - 1, cursor + 1)
302
+ elif key == " ":
303
+ if cursor in selected:
304
+ selected.remove(cursor)
305
+ else:
306
+ selected.add(cursor)
307
+ elif key in ("\r", "\n"):
308
+ return sorted(selected) if selected else [cursor]
309
+
310
+
311
+ # ---------- Commands ----------
312
+
313
+ @app.command()
314
+ def version() -> None:
315
+ """Print the pyread version."""
316
+ from pyread import __version__
317
+ typer.echo(f"pyread {__version__}")
318
+
319
+
320
+ SUGGESTION_TABS = {
321
+ "Fiction": ("science fiction", "mystery", "fantasy", "classics"),
322
+ "Nonfiction": ("history", "philosophy", "psychology", "science", "biography", "travel"),
323
+ }
324
+
325
+
326
+ def _menu(title: str, rows: list[tuple[str, str]], cursor: int = 0,
327
+ header: tuple[str | Text, ...] = (), *, tabs: bool = False, home: bool = False,
328
+ poll: Callable[[], tuple[str | Text, ...] | None] | None = None) -> str | None:
329
+ """Choose a row immediately with arrows and Enter, restoring the shell on exit."""
330
+ with _screen(), key_reader() as read_key:
331
+ while True:
332
+ width, height = _terminal_size()
333
+ shown_header = header[-max(0, height - 7):] if height > 7 else ()
334
+ visible = max(1, height - 5 - len(shown_header))
335
+ start = max(0, cursor - visible + 1)
336
+ body = Text()
337
+ for index in range(start, min(start + visible, len(rows))):
338
+ label, _ = rows[index]
339
+ line = Text(("› " if index == cursor else " ") + " ".join(label.split()))
340
+ line.truncate(max(1, min(width, console.width) - 4), overflow="ellipsis")
341
+ body.append_text(line)
342
+ if index == cursor:
343
+ body.stylize("bold black on cyan", len(body) - len(line))
344
+ if index + 1 < min(start + visible, len(rows)):
345
+ body.append("\n")
346
+ console.clear()
347
+ for line in shown_header:
348
+ content = line if isinstance(line, Text) else Text(line, style="bold cyan")
349
+ console.print(content, width=width, no_wrap=True, overflow="ellipsis")
350
+ console.print(Panel(body, title=Text(title), border_style="cyan",
351
+ padding=(0, 1)), width=width)
352
+ controls = "←/→ Tabs " if tabs else ""
353
+ hint = "↑/↓ Move Enter Select"
354
+ hint += " q Quit" if home else " Esc Back"
355
+ console.print(Text(controls + hint, no_wrap=True,
356
+ overflow="ellipsis", style="dim"), width=width)
357
+ try:
358
+ if poll:
359
+ while (key := read_key(0.25)) is None:
360
+ selected = rows[cursor][1]
361
+ updated = poll()
362
+ if updated is not None:
363
+ header = updated
364
+ poll = None
365
+ cursor = next(i for i, (_, action) in enumerate(rows) if action == selected)
366
+ break
367
+ if key is None:
368
+ continue
369
+ else:
370
+ key = read_key()
371
+ except (KeyboardInterrupt, EOFError):
372
+ return None
373
+ if key in ("q", "Q") or (not home and key == "\x1b"):
374
+ return None
375
+ if tabs and key in ("\x1b[D", "\x1bOD"):
376
+ return "previous-tab"
377
+ if tabs and key in ("\x1b[C", "\x1bOC", "\t"):
378
+ return "next-tab"
379
+ if key in ("\r", "\n", " "):
380
+ return rows[cursor][1]
381
+ if key in ("\x1b[A", "\x1bOA", "k"):
382
+ cursor = max(0, cursor - 1)
383
+ elif key in ("\x1b[B", "\x1bOB", "j"):
384
+ cursor = min(len(rows) - 1, cursor + 1)
385
+
386
+
387
+ def _setup_preferences() -> None:
388
+ language = state.get_setting("language")
389
+ minutes = int(state.get_setting("minutes"))
390
+ categories = set(filter(None, map(str.strip, state.get_setting("categories").split(","))))
391
+ known = {category for choices in SUGGESTION_TABS.values() for category in choices}
392
+ extra = tuple(sorted(categories - known))
393
+ tab_names = ("General", *SUGGESTION_TABS)
394
+ tab_index = 0
395
+ cursor = 0
396
+ while True:
397
+ tab = tab_names[tab_index]
398
+ if tab == "General":
399
+ rows = [
400
+ (f"Search language {'English' if language == 'en' else 'Any language'}", "language"),
401
+ (f"Reading time {minutes} min", "minutes"),
402
+ ("Choose suggestion topics", "suggestions"),
403
+ ]
404
+ else:
405
+ choices = SUGGESTION_TABS[tab] + (extra if tab == "Nonfiction" else ())
406
+ rows = [(f"{'✓' if category in categories else '○'} {category.title()}", f"category:{category}")
407
+ for category in choices]
408
+ rows.append(("Save and return", "save"))
409
+ header = ("Suggest books", " ".join(f"[{name}]" if name == tab else name for name in tab_names))
410
+ action = _menu("Settings", rows, cursor, header, tabs=True)
411
+ if action is None:
412
+ return
413
+ if action in ("previous-tab", "next-tab", "suggestions"):
414
+ step = -1 if action == "previous-tab" else 1
415
+ tab_index = (tab_index + step) % len(tab_names)
416
+ cursor = 0
417
+ continue
418
+ cursor = next(index for index, (_, key) in enumerate(rows) if key == action)
419
+ if action == "save":
420
+ state.set_setting("language", language)
421
+ state.set_setting("minutes", str(minutes))
422
+ state.set_setting("categories", ", ".join(sorted(categories)))
423
+ return
424
+ if action == "language":
425
+ language = "any" if language == "en" else "en"
426
+ elif action == "minutes":
427
+ times = sorted({5, 10, 15, 20, 30, 45, 60, minutes})
428
+ selection = _menu("Reading time", [(f"{time} minutes", str(time)) for time in times],
429
+ times.index(minutes))
430
+ if selection is not None:
431
+ minutes = int(selection)
432
+ else:
433
+ categories.symmetric_difference_update({action.removeprefix("category:")})
434
+
435
+
436
+ def _reading_time(seconds: int | None) -> str:
437
+ if seconds is None:
438
+ return "Time unavailable"
439
+ minutes, remainder = divmod(seconds, 60)
440
+ hours, minutes = divmod(minutes, 60)
441
+ if hours:
442
+ return f"{hours}h {minutes:02d}m {remainder:02d}s"
443
+ return f"{minutes}m {remainder:02d}s" if minutes else f"{remainder}s"
444
+
445
+
446
+ # Generated with pyfiglet -f standard PYREAD.
447
+ HOME_BANNER = (
448
+ ' ______ ______ _____ _ ____',
449
+ '| _ \\ \\ / / _ \\| ____| / \\ | _ \\',
450
+ '| |_) \\ V /| |_) | _| / _ \\ | | | |',
451
+ '| __/ | | | _ <| |___ / ___ \\| |_| |',
452
+ '|_| |_| |_| \\_\\_____/_/ \\_\\____/',
453
+ )
454
+
455
+ @dataclass(frozen=True)
456
+ class FeaturedBook:
457
+ identifier: str
458
+ title: str
459
+ author: str
460
+ category: str
461
+ excerpt: tuple[str, ...]
462
+
463
+
464
+ def _featured_candidates(books: list[dict], previous: str, queued: list[FeaturedBook],
465
+ topics: str, language: str) -> Iterator[FeaturedBook]:
466
+ categories = [topic.strip() for topic in topics.split(",") if topic.strip()]
467
+ if not categories:
468
+ return
469
+ if previous.isdecimal():
470
+ previous = f"gutenberg:{previous}"
471
+ excluded = {book["identifier"] for book in books} | {previous} | {book.identifier for book in queued}
472
+ directory = state.DB_PATH.parent / "books"
473
+ random.shuffle(categories)
474
+ for category in categories[:3]:
475
+ try:
476
+ candidates = search_books(category, limit=20, language=language, parallel=False)
477
+ except requests.RequestException:
478
+ continue
479
+ random.shuffle(candidates)
480
+ eligible = [book for book in candidates if excluded.isdisjoint(book["identifiers"])]
481
+ for book in eligible[:5]:
482
+ if not excluded.isdisjoint(book["identifiers"]):
483
+ continue
484
+ identifier = available_identifier(book["identifiers"][:3], language)
485
+ if not identifier:
486
+ continue
487
+ try:
488
+ raw = cached_text(directory, identifier, lambda: fetch_book_text(identifier))
489
+ except (OSError, ValueError, requests.RequestException):
490
+ continue
491
+ content, _ = strip_front_matter(raw)
492
+ passage = " ".join(text for text, _, _ in collect_segments(content, 160))
493
+ sentences = re.findall(r'[^.!?]*[.!?]+[”"]?(?=\s|$)', passage)
494
+ excerpt = tuple(sentence.strip() for sentence in sentences[:3] if sentence.strip())
495
+ if len(excerpt) >= 2:
496
+ excluded.update(book["identifiers"])
497
+ yield FeaturedBook(identifier, book["title"], book["author"], category, excerpt)
498
+
499
+ FEATURED_QUEUE_SIZE = 5
500
+
501
+
502
+ def _prepare_featured(books: list[dict]) -> tuple[FeaturedBook | None, SimpleQueue]:
503
+ topics = state.get_setting("categories")
504
+ language = state.get_setting("language")
505
+ previous = state.get_setting("last_featured")
506
+ owned = {book["identifier"] for book in books}
507
+ queued = []
508
+ payload = json.loads(state.get_setting("featured_queue"))
509
+ if payload.get("topics") == topics and payload.get("language") == language:
510
+ queued = [FeaturedBook(**entry) for entry in payload["books"]
511
+ if entry["identifier"] not in owned and entry["identifier"] != previous]
512
+ featured = queued.pop(0) if queued else None
513
+ ready = SimpleQueue()
514
+
515
+ def save():
516
+ state.set_setting("featured_queue", json.dumps({
517
+ "topics": topics, "language": language, "books": [asdict(book) for book in queued],
518
+ }))
519
+
520
+ if featured:
521
+ save()
522
+ if topics and len(queued) < FEATURED_QUEUE_SIZE:
523
+ def refill():
524
+ try:
525
+ previous_id = featured.identifier if featured else previous
526
+ for candidate in _featured_candidates(books, previous_id, queued, topics, language):
527
+ if topics != state.get_setting("categories") or language != state.get_setting("language"):
528
+ break
529
+ queued.append(candidate)
530
+ save()
531
+ if not featured and len(queued) == 1:
532
+ ready.put(candidate)
533
+ if len(queued) >= FEATURED_QUEUE_SIZE + (not featured):
534
+ break
535
+ finally:
536
+ ready.put(None)
537
+
538
+ Thread(target=refill, daemon=True, name="pyread-featured").start()
539
+ return featured, ready
540
+
541
+
542
+ def _quote_header(book: FeaturedBook) -> tuple[Text, ...]:
543
+ width = max(1, min(_terminal_size()[0], console.width) - 2)
544
+ excerpt = f"“{' '.join(book.excerpt)}”"
545
+ preview = _preview_lines(excerpt, width, 5).plain.splitlines()
546
+ if book.identifier.startswith("gutenberg:"):
547
+ number = book.identifier.removeprefix("gutenberg:")
548
+ url = f"https://www.gutenberg.org/ebooks/{number}"
549
+ else:
550
+ url = f"https://archive.org/details/{url_quote(book.identifier, safe='')}"
551
+ attribution = Text("— ", style="bold")
552
+ attribution.append(book.title, style=f"underline cyan link {url}")
553
+ attribution.append(f" · {book.author} · {book.category.title()}", style="bold")
554
+ return (*(Text(line, style="italic") for line in preview), attribution)
555
+
556
+
557
+ @dataclass(frozen=True)
558
+ class BookProgress:
559
+ start: int
560
+ end: int
561
+
562
+ def fraction(self, offset: int) -> float:
563
+ length = self.end - self.start
564
+ if length <= 0:
565
+ return 0.0
566
+ return min(1.0, max(0.0, (offset - self.start) / length))
567
+
568
+ def label(self, offset: int) -> str:
569
+ length = self.end - self.start
570
+ percent = (offset - self.start) * 100 // length if length > 0 else 0
571
+ return f"{min(100, max(0, percent))}%"
572
+
573
+
574
+ def _book_progress(text: str) -> BookProgress:
575
+ return BookProgress(strip_front_matter(text)[1], book_text_end(text))
576
+
577
+
578
+ def _saved_book_labels(books: list[dict]) -> tuple[dict[int, str], str | None]:
579
+ labels = {}
580
+ closest = None
581
+ best_fraction = 0.0
582
+ for book in books:
583
+ text = read_cached_text(state.DB_PATH.parent / "books", book["identifier"])
584
+ edition = _book_progress(text) if text else None
585
+ progress = edition.label(book["offset"]) if edition else (
586
+ "Not started" if not book["offset"] else "Progress unavailable"
587
+ )
588
+ labels[book["id"]] = f"{book['title']} · {progress}"
589
+ fraction = edition.fraction(book["offset"]) if edition else 0.0
590
+ if best_fraction < fraction < 1:
591
+ closest = labels[book["id"]]
592
+ best_fraction = fraction
593
+ return labels, closest
594
+
595
+
596
+ def _stats_highlights(stats: list[dict]) -> list[str]:
597
+ measured = [row for row in stats if row["seconds"] is not None]
598
+ seconds = sum(row["seconds"] for row in measured)
599
+ lines = [
600
+ f"{_reading_time(seconds)} read | {sum(row['pages'] for row in stats):,} pages",
601
+ ]
602
+ if measured:
603
+ favorite = max(measured, key=lambda row: row["seconds"])
604
+ lines.append(f"Most read: {favorite['title']} · {_reading_time(favorite['seconds'])}")
605
+ else:
606
+ lines.append("Most read: no timed sessions yet")
607
+ return lines
608
+
609
+
610
+ def _home() -> None:
611
+ first_launch = state.get_setting("setup_complete") == "no"
612
+ if first_launch:
613
+ _setup_preferences()
614
+ state.set_setting("setup_complete", "yes")
615
+ empty_prompted = False
616
+ featured, ready = _prepare_featured(state.list_books())
617
+ awaiting = featured is None and bool(state.get_setting("categories"))
618
+ if featured:
619
+ state.set_setting("last_featured", featured.identifier)
620
+ while True:
621
+ books = state.list_books()
622
+ discovery = first_launch or (not books and not empty_prompted)
623
+ title = "Find your first book" if first_launch else "Your library is empty"
624
+ first_launch = False
625
+ empty_prompted = not books
626
+ last = state.last_read()
627
+ labels, closest = _saved_book_labels(books)
628
+ rows = []
629
+ if last:
630
+ rows.append((f"Continue · {labels.get(last['id'], last['title'])}", "continue"))
631
+ rows.extend((labels[book["id"]], str(book["id"]))
632
+ for book in books)
633
+ if featured:
634
+ rows.append((f"Read featured book · {featured.title}", "featured"))
635
+ rows.append(("Search for books", "search"))
636
+ stats = state.reading_stats()
637
+ if books or stats:
638
+ rows.append(("Edit library", "remove"))
639
+ if state.get_setting("categories"):
640
+ rows.append(("Random book suggestions", "suggest"))
641
+ rows.extend([("Settings", "settings"), ("Quit", "quit")])
642
+ width, height = _terminal_size()
643
+ banner = HOME_BANNER if width >= max(map(len, HOME_BANNER)) and height >= 19 else ("PYREAD",)
644
+ highlights = tuple(_stats_highlights(stats))
645
+ if closest:
646
+ highlights += (f"Closest to finishing · {closest}",)
647
+ quote = _quote_header(featured) if featured else ()
648
+ def show_ready():
649
+ nonlocal featured, awaiting
650
+ if not awaiting:
651
+ return None
652
+ try:
653
+ book = ready.get_nowait()
654
+ except Empty:
655
+ return None
656
+ awaiting = False
657
+ if book is None:
658
+ return (*banner, *highlights)
659
+ if (book.category not in {topic.strip() for topic in state.get_setting("categories").split(",")}
660
+ or any(item["identifier"] == book.identifier for item in state.list_books())):
661
+ return (*banner, *highlights)
662
+ featured = book
663
+ state.set_setting("last_featured", book.identifier)
664
+ rows.insert(len(rows) - 1, (f"Read featured book · {book.title}", "featured"))
665
+ return (*banner, *highlights, *_quote_header(book))
666
+
667
+ if discovery:
668
+ rows = [
669
+ ("Search for books", "search"),
670
+ ("Browse random book suggestions", "suggest"),
671
+ ("Settings", "settings"),
672
+ ("Go to your library", "library"),
673
+ ]
674
+ if featured:
675
+ rows.insert(2, (f"Read featured book · {featured.title}", "featured"))
676
+ action = _menu(title if discovery else "Your library", rows,
677
+ header=(*banner, *highlights, *quote), home=not discovery,
678
+ poll=show_ready if awaiting else None)
679
+ if discovery and action in (None, "library"):
680
+ continue
681
+ if action in (None, "quit"):
682
+ return
683
+ if action == "settings":
684
+ preferences = (state.get_setting("categories"), state.get_setting("language"))
685
+ _setup_preferences()
686
+ if not featured and preferences != (state.get_setting("categories"), state.get_setting("language")):
687
+ featured, ready = _prepare_featured(books)
688
+ awaiting = featured is None and bool(state.get_setting("categories"))
689
+ if featured:
690
+ state.set_setting("last_featured", featured.identifier)
691
+ if discovery and not books:
692
+ empty_prompted = False
693
+ continue
694
+ if action == "remove":
695
+ edits = [(f"Remove · {book['title']}", str(book["id"])) for book in books]
696
+ edits.append(("Reset all reading progress", "reset"))
697
+ if books:
698
+ edits.append(("Reset progress and remove all books", "reset-library"))
699
+ selected = _menu("Edit library", edits)
700
+ if selected == "reset-library":
701
+ confirmed = _menu(
702
+ "Reset progress and remove all books?",
703
+ [("Keep library", "keep"), ("Remove all books and progress", "reset")],
704
+ header=("Clears the library, bookmarks, pages read, and reading time.",
705
+ "Your settings and downloads are kept."),
706
+ )
707
+ if confirmed == "reset":
708
+ state.reset_progress(remove_books=True)
709
+ elif selected == "reset":
710
+ confirmed = _menu(
711
+ "Reset all reading progress?",
712
+ [("Keep progress", "keep"), ("Clear all progress", "reset")],
713
+ header=("Clears bookmarks, pages read, and reading time for every book.",
714
+ "Your library and settings are kept."),
715
+ )
716
+ if confirmed == "reset":
717
+ state.reset_progress()
718
+ elif selected is not None:
719
+ book = next(book for book in books if str(book["id"]) == selected)
720
+ if _menu(f"Remove {book['title']}?", [("Keep book", "keep"), ("Remove book", "remove")]) == "remove":
721
+ state.remove_book(book["id"])
722
+ continue
723
+ console.clear()
724
+ try:
725
+ if action == "featured" and featured:
726
+ _open_featured_book(featured)
727
+ elif action == "suggest":
728
+ category = None
729
+ kind = "nonfiction"
730
+ if not state.get_setting("categories"):
731
+ category = _menu("Choose a topic", [
732
+ (topic.title(), topic)
733
+ for topics in SUGGESTION_TABS.values() for topic in topics
734
+ ])
735
+ if category is None:
736
+ continue
737
+ if category in SUGGESTION_TABS["Fiction"]:
738
+ kind = "fiction"
739
+ suggest_cmd(category=category, kind=kind)
740
+ elif action == "search":
741
+ query = Prompt.ask("Search by title, author, or subject", default="", console=console).strip()
742
+ if query:
743
+ search_cmd(query, "nonfiction", 10, None)
744
+ else:
745
+ next_command(None, action == "continue", int(action) if action.isdecimal() else None,
746
+ 12, None, False)
747
+ except typer.Exit:
748
+ pass
749
+ _wait_to_close("Press any key to return to the library.")
750
+
751
+
752
+ def _open_featured_book(book: FeaturedBook) -> None:
753
+ saved = next((item for item in state.list_books() if item["identifier"] == book.identifier), None)
754
+ action = "Read book" if saved else "Add and read"
755
+ if _menu(book.title, [(action, "read"), ("Back", "back")],
756
+ header=_quote_header(book)) != "read":
757
+ return
758
+ console.clear()
759
+ kind = "fiction" if book.category in SUGGESTION_TABS["Fiction"] else "nonfiction"
760
+ if not saved and not state.add_book(book.identifier, title=book.title, author=book.author,
761
+ kind=kind, genre=book.category):
762
+ console.print("Your library is full. Remove a book before adding this one.")
763
+ return
764
+ saved = saved or next(item for item in state.list_books() if item["identifier"] == book.identifier)
765
+ next_command(None, False, saved["id"], 12, None, False)
766
+
767
+
768
+ @app.callback(invoke_without_command=True)
769
+ def launch(ctx: typer.Context) -> None:
770
+ """Open the keyboard-driven library when started without a command."""
771
+ if ctx.invoked_subcommand is None:
772
+ if sys.stdin.isatty() and sys.stdout.isatty():
773
+ with _screen():
774
+ _home()
775
+ else:
776
+ console.print(ctx.get_help(), markup=False, highlight=False)
777
+
778
+
779
+ @app.command("config")
780
+ @_fullscreen_command
781
+ def config_cmd(
782
+ language: str | None = typer.Option(None, "--language", help="Default search language: en or any."),
783
+ interactive: bool = typer.Option(False, "--interactive", help="Open interactive setup."),
784
+ ) -> None:
785
+ """Show or update reading preferences."""
786
+ if interactive or (language is None and sys.stdin.isatty() and sys.stdout.isatty()):
787
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
788
+ raise typer.BadParameter("Interactive setup requires a terminal.", param_hint="--interactive")
789
+ _setup_preferences()
790
+ state.set_setting("setup_complete", "yes")
791
+ return
792
+ if language is not None:
793
+ try:
794
+ state.set_setting("language", language)
795
+ except ValueError as error:
796
+ raise typer.BadParameter(str(error), param_hint="--language") from error
797
+ console.print(f"[green]Default search language set to {language}.[/green]")
798
+ else:
799
+ console.print(f"Default search language: [bold]{state.get_setting('language')}[/bold]")
800
+ console.print(f"Reading time: {state.get_setting('minutes')} minutes")
801
+ console.print(Text("Favorite categories: " + (state.get_setting("categories") or "Disabled")))
802
+
803
+
804
+ @app.command("search")
805
+ @_fullscreen_command
806
+ def search_cmd(
807
+ query: str = typer.Argument(..., help="Subject or genre to search for, such as science fiction."),
808
+ kind: str = typer.Option("nonfiction", help="Reading speed to use: fiction or nonfiction."),
809
+ limit: int = typer.Option(10, min=1, max=100, help="Maximum candidate results to fetch (1–100)."),
810
+ language: str | None = typer.Option(None, "--language", help="Override configured language: en or any."),
811
+ ) -> None:
812
+ """Search Open Library and add books to your pool."""
813
+ language = language or state.get_setting("language")
814
+ if language not in ("en", "any"):
815
+ raise typer.BadParameter("Choose en or any.", param_hint="--language")
816
+ if kind not in ("fiction", "nonfiction"):
817
+ raise typer.BadParameter("Choose fiction or nonfiction.", param_hint="--kind")
818
+ if state.count() >= state.MAX_POOL_SIZE:
819
+ console.print(f"[yellow]Pool full ({state.MAX_POOL_SIZE}). Remove one first.[/yellow]")
820
+ raise typer.Exit(1)
821
+
822
+ with console.status(f"Searching for {query!r}..."):
823
+ try:
824
+ results = search_books(query, limit=limit, language=language)
825
+ except requests.RequestException as e:
826
+ console.print(f"[red]Search failed: {escape(str(e))}[/red]")
827
+ raise typer.Exit(1)
828
+
829
+ if not results:
830
+ console.print(f"[red]No books found for {query!r}.[/red]")
831
+ raise typer.Exit(1)
832
+
833
+ _add_search_results(results, query, kind, language)
834
+
835
+
836
+ @app.command("suggest")
837
+ @_fullscreen_command
838
+ def suggest_cmd(
839
+ category: str | None = typer.Option(None, "--category", help="Use this category for one suggestion list."),
840
+ kind: str = typer.Option("nonfiction", help="Reading speed to use: fiction or nonfiction."),
841
+ ) -> None:
842
+ """Suggest random books from a favorite category."""
843
+ if kind not in ("fiction", "nonfiction"):
844
+ raise typer.BadParameter("Choose fiction or nonfiction.", param_hint="--kind")
845
+ categories = [value.strip() for value in (category or state.get_setting("categories")).split(",")
846
+ if value.strip()]
847
+ if not categories:
848
+ console.print("Set favorite categories with pyread config --interactive, or supply --category.")
849
+ return
850
+ if state.count() >= state.MAX_POOL_SIZE:
851
+ console.print("[yellow]Your reading pool is full. Remove a book before adding suggestions.[/yellow]")
852
+ return
853
+ language = state.get_setting("language")
854
+ owned = {book["identifier"] for book in state.list_books()}
855
+ topics = list(dict.fromkeys(categories))
856
+ random.shuffle(topics)
857
+ suggestions = []
858
+
859
+ with console.status("Finding books across your categories…"):
860
+ with ThreadPoolExecutor(max_workers=4) as executor:
861
+ searches = [(topic, executor.submit(search_books, topic, limit=30, language=language))
862
+ for topic in topics]
863
+ groups = []
864
+ for topic, future in searches:
865
+ try:
866
+ books = future.result()
867
+ except requests.RequestException:
868
+ continue
869
+ random.shuffle(books)
870
+ groups.append((topic, iter(books)))
871
+
872
+ while groups and len(suggestions) < 8:
873
+ remaining = []
874
+ for topic, books in groups:
875
+ for book in books:
876
+ if owned.isdisjoint(book["identifiers"]):
877
+ suggested_kind = ("fiction" if topic in SUGGESTION_TABS["Fiction"] else
878
+ "nonfiction" if topic in SUGGESTION_TABS["Nonfiction"] else kind)
879
+ suggestions.append(dict(book, category=topic, kind=suggested_kind if category is None else kind))
880
+ owned.update(book["identifiers"])
881
+ remaining.append((topic, books))
882
+ break
883
+ if len(suggestions) == 8:
884
+ break
885
+ groups = remaining
886
+
887
+ if not suggestions:
888
+ console.print("No new suggestions available. Try again or change your categories.")
889
+ return
890
+ _add_search_results(suggestions, "Suggested books", kind, language)
891
+
892
+
893
+ def _add_search_results(results: list[dict], query: str, kind: str, language: str) -> None:
894
+ with console.status("Checking which books have downloadable text…"):
895
+ with ThreadPoolExecutor(max_workers=6) as executor:
896
+ identifiers = executor.map(
897
+ lambda book: available_identifier(book["identifiers"], language), results
898
+ )
899
+ results = [dict(book, available_id=identifier,
900
+ source="Gutenberg" if identifier.startswith("gutenberg:") else "Internet Archive")
901
+ for book, identifier in zip(results, identifiers) if identifier]
902
+ if not results:
903
+ console.print("No downloadable books could be verified. Try another search.")
904
+ return
905
+ if sys.stdin.isatty() and sys.stdout.isatty():
906
+ with _screen():
907
+ indices = _select_search_results(results, query)
908
+ else:
909
+ indices = _select_search_results(results, query)
910
+ if sys.stdout.isatty():
911
+ console.clear()
912
+ if not indices:
913
+ return
914
+ for index in indices:
915
+ result = results[index]
916
+ title = escape(result["title"])
917
+ identifier = result["available_id"]
918
+ if state.add_book(identifier, title=result["title"], author=result["author"],
919
+ kind=result.get("kind", kind), genre=result.get("category", query)):
920
+ console.print(f"[green]Added:[/green] {title} — {escape(result['author'])}")
921
+ else:
922
+ console.print(f"[yellow]Already in pool or full: {title}[/yellow]")
923
+ if state.count() >= state.MAX_POOL_SIZE:
924
+ console.print(f"[yellow]Pool now full ({state.MAX_POOL_SIZE}).[/yellow]")
925
+ return
926
+
927
+
928
+ @app.command("list")
929
+ @_fullscreen_command
930
+ def list_cmd() -> None:
931
+ """Show your reading pool."""
932
+ books = state.list_books()
933
+ if not books:
934
+ console.print("[dim]Pool is empty. Try: pyread search psychology[/dim]")
935
+ return
936
+
937
+ last = state.last_read()
938
+ last_id = last["id"] if last else None
939
+
940
+ table = Table(title=f"Reading pool ({len(books)}/{state.MAX_POOL_SIZE})")
941
+ table.add_column("ID", style="dim", width=3)
942
+ table.add_column("Title")
943
+ table.add_column("Author", style="cyan")
944
+ table.add_column("Kind/Genre", style="green")
945
+ table.add_column("Pages read", justify="right")
946
+ page_totals = state.pages_by_book()
947
+ for b in books:
948
+ marker = "→" if b["id"] == last_id else " "
949
+ table.add_row(str(b["id"]), f"{marker} {b['title']}",
950
+ b["author"], b["genre"] or b["kind"], f"{page_totals.get(b['identifier'], 0):,}" if b["offset"] else "Not started")
951
+ console.print(table)
952
+
953
+
954
+ @app.command("stats")
955
+ @_fullscreen_command
956
+ def stats_cmd() -> None:
957
+ """Show completed screen pages and reading sessions."""
958
+ stats = state.reading_stats()
959
+ if not stats:
960
+ console.print("[dim]No completed pages recorded yet. Advance a page while reading to begin.[/dim]")
961
+ return
962
+ for line in _stats_highlights(stats):
963
+ console.print(Text(line, style="bold"))
964
+ console.print("[dim]Pages depend on terminal size; printing excerpts does not count pages.[/dim]")
965
+
966
+
967
+ @app.command("remove")
968
+ @_fullscreen_command
969
+ def remove_cmd(book_id: int = typer.Argument(..., help="Book ID from pyread list.")) -> None:
970
+ """Remove a book from your pool."""
971
+ if state.remove_book(book_id):
972
+ console.print(f"[green]Removed book {book_id}.[/green]")
973
+ else:
974
+ console.print(f"[red]No book with id {book_id}.[/red]")
975
+ raise typer.Exit(1)
976
+
977
+
978
+ @app.command("next")
979
+ @_fullscreen_command
980
+ def next_command(
981
+ minutes: int | None = typer.Option(None, min=1, help="Override the configured excerpt duration."),
982
+ continue_last: bool = typer.Option(False, "--continue", "-c",
983
+ help="Resume the last-read book."),
984
+ book_id: int | None = typer.Option(None, "--book", "-b",
985
+ help="Read a specific book by pool id."),
986
+ page_lines: int = typer.Option(12, "--page-lines", min=1,
987
+ help="Maximum text lines per reader page (default: 12)."),
988
+ timer_minutes: int | None = typer.Option(None, "--timer", min=1,
989
+ help="Alert after this many minutes while reading interactively."),
990
+ no_pager: bool = typer.Option(False, "--no-pager",
991
+ help="Print excerpt and exit (no interactive reader)."),
992
+ clean_text: bool = typer.Option(True, "--clean-text/--no-clean-text", help="Use the built-in text model to fix broken spacing."),
993
+ ) -> None:
994
+ """Fetch the next excerpt from your pool."""
995
+ if book_id is not None and continue_last:
996
+ raise typer.BadParameter("Choose either --book or --continue, not both.")
997
+ interactive = not no_pager and sys.stdin.isatty() and sys.stdout.isatty()
998
+ if timer_minutes is not None and not interactive:
999
+ raise typer.BadParameter("--timer requires an interactive terminal without --no-pager.")
1000
+
1001
+ # --- pick a book ---
1002
+ if book_id is not None:
1003
+ book = state.get_book(book_id)
1004
+ if not book:
1005
+ console.print(f"[red]No book with id {book_id}.[/red]")
1006
+ raise typer.Exit(1)
1007
+ elif continue_last:
1008
+ book = state.last_read()
1009
+ if not book:
1010
+ console.print("[red]No last-read book yet.[/red]")
1011
+ raise typer.Exit(1)
1012
+ else:
1013
+ last = state.last_read()
1014
+ book = state.pick_random(exclude_id=last["id"] if last else None)
1015
+ if not book:
1016
+ console.print("[red]Pool is empty. Try: pyread search psychology[/red]")
1017
+ raise typer.Exit(1)
1018
+
1019
+ minutes = minutes if minutes is not None else int(state.get_setting("minutes"))
1020
+ target = target_words(minutes, book["kind"])
1021
+
1022
+ # --- fetch raw text ---
1023
+ with console.status(f"Fetching {escape(book['title'])}..."):
1024
+ try:
1025
+ raw_text = cached_text(state.DB_PATH.parent / "books", book["identifier"],
1026
+ lambda: fetch_book_text(book["identifier"]))
1027
+ except (FileNotFoundError, ValueError, requests.RequestException) as e:
1028
+ console.print(f"[red]{escape(str(e))}[/red]")
1029
+ raise typer.Exit(1)
1030
+
1031
+ # --- compute absolute start in RAW coordinates ---
1032
+ progress = _book_progress(raw_text)
1033
+ start = max(book["offset"], progress.start)
1034
+ text = raw_text[start:]
1035
+
1036
+ segments = collect_segments(text, target)
1037
+ if clean_text is not False and segments:
1038
+ sample_start = max(progress.start, start - SAMPLE_SIZE // 4)
1039
+ segments = clean_segments(segments, raw_text[sample_start:sample_start + SAMPLE_SIZE])
1040
+ excerpt = "\n\n".join(segment[0] for segment in segments)
1041
+ chars = segments[-1][2] if segments else 0
1042
+ if not excerpt:
1043
+ console.print(f"[yellow]You have reached the end of {escape(book['title'])}.[/yellow]")
1044
+ raise typer.Exit(1)
1045
+
1046
+ # --- non-interactive: print panel, save full progress ---
1047
+ if not interactive:
1048
+ console.print()
1049
+ console.print(Panel(Text(excerpt), padding=(1, 2), border_style="cyan"))
1050
+ console.print(
1051
+ f"[dim]— {escape(book['title'])}, {escape(book['author'])} · "
1052
+ f"{escape(book['genre'] or book['kind'])} · {minutes} min · "
1053
+ "excerpt saved[/dim]",
1054
+ justify="right",
1055
+ )
1056
+ state.record_reading(book["id"], start + chars, 0)
1057
+ return
1058
+
1059
+ # Pagination follows the current terminal size and preserves safe resume points.
1060
+ timer = ReadingTimer(timer_minutes * 60, on_expire=console.bell) if timer_minutes else None
1061
+ if timer:
1062
+ timer.start()
1063
+ try:
1064
+ # Keep redraws in a dedicated screen so terminal scrollback and the
1065
+ # shell prompt cannot move the page away from the visible viewport.
1066
+ with _screen():
1067
+ started = monotonic()
1068
+ final_offset, read_to_end, pages_read = _read_interactive(
1069
+ segments, book["title"], chars, timer, page_lines, progress, start
1070
+ )
1071
+ finally:
1072
+ if timer:
1073
+ timer.cancel()
1074
+ state.record_reading(book["id"], start + final_offset, pages_read, int(monotonic() - started))
1075
+ if console.is_alt_screen:
1076
+ console.clear()
1077
+
1078
+ if read_to_end:
1079
+ console.print(f"[green]Finished this excerpt from {escape(book['title'])} · {pages_read} page(s) read.[/green]")
1080
+ console.print("[dim]Run again for more, or: pyread next --continue[/dim]")
1081
+ else:
1082
+ console.print(
1083
+ f"[dim]Saved: {escape(book['title'])} · {pages_read} page(s) read this session.[/dim]"
1084
+ )
1085
+
1086
+
1087
+ if __name__ == "__main__":
1088
+ app()