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/state.py ADDED
@@ -0,0 +1,226 @@
1
+ import hashlib
2
+ import json
3
+ import random
4
+ import sqlite3
5
+ from contextlib import contextmanager
6
+ from collections.abc import Iterator
7
+ from pathlib import Path
8
+
9
+ DB_PATH = Path.home() / ".pyread" / "state.db"
10
+ MAX_POOL_SIZE = 5
11
+
12
+ SCHEMA = """
13
+ CREATE TABLE IF NOT EXISTS books (
14
+ id INTEGER PRIMARY KEY,
15
+ identifier TEXT UNIQUE NOT NULL,
16
+ title TEXT NOT NULL DEFAULT '',
17
+ author TEXT NOT NULL DEFAULT '',
18
+ kind TEXT NOT NULL DEFAULT 'nonfiction',
19
+ genre TEXT NOT NULL DEFAULT '',
20
+ offset INTEGER NOT NULL DEFAULT 0,
21
+ added_at TEXT,
22
+ last_read_at TEXT
23
+ );
24
+ CREATE TABLE IF NOT EXISTS settings (
25
+ key TEXT PRIMARY KEY,
26
+ value TEXT NOT NULL
27
+ );
28
+ CREATE TABLE IF NOT EXISTS page_cache (
29
+ cache_key TEXT PRIMARY KEY,
30
+ pages TEXT NOT NULL,
31
+ used_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now'))
32
+ );
33
+ CREATE TABLE IF NOT EXISTS reading_sessions (
34
+ id INTEGER PRIMARY KEY,
35
+ book_identifier TEXT NOT NULL,
36
+ title TEXT NOT NULL,
37
+ pages INTEGER NOT NULL DEFAULT 0,
38
+ seconds INTEGER,
39
+ read_at TEXT NOT NULL DEFAULT (datetime('now'))
40
+ );
41
+ """
42
+
43
+
44
+ def _migrate(conn: sqlite3.Connection) -> None:
45
+ sessions = {row["name"] for row in conn.execute("PRAGMA table_info(reading_sessions)")}
46
+ if "seconds" not in sessions:
47
+ conn.execute("ALTER TABLE reading_sessions ADD COLUMN seconds INTEGER")
48
+ cols = {row["name"] for row in conn.execute("PRAGMA table_info(books)")}
49
+ for col, ddl in (
50
+ ("author", "ALTER TABLE books ADD COLUMN author TEXT NOT NULL DEFAULT ''"),
51
+ ("kind", "ALTER TABLE books ADD COLUMN kind TEXT NOT NULL DEFAULT 'nonfiction'"),
52
+ ("genre", "ALTER TABLE books ADD COLUMN genre TEXT NOT NULL DEFAULT ''"),
53
+ ("added_at", "ALTER TABLE books ADD COLUMN added_at TEXT"),
54
+ ("last_read_at", "ALTER TABLE books ADD COLUMN last_read_at TEXT"),
55
+ ):
56
+ if col not in cols:
57
+ conn.execute(ddl)
58
+
59
+
60
+ @contextmanager
61
+ def _conn() -> Iterator[sqlite3.Connection]:
62
+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)
63
+ conn = sqlite3.connect(DB_PATH)
64
+ conn.row_factory = sqlite3.Row
65
+ conn.executescript(SCHEMA)
66
+ _migrate(conn)
67
+ try:
68
+ with conn:
69
+ yield conn
70
+ finally:
71
+ conn.close()
72
+
73
+
74
+
75
+ DEFAULT_SETTINGS = {"language": "en", "categories": "", "setup_complete": "no", "minutes": "15", "last_featured": "", "featured_queue": "{}"}
76
+
77
+
78
+ def get_setting(key: str) -> str:
79
+ """Return a supported setting, using its default for existing installations."""
80
+ if key not in DEFAULT_SETTINGS:
81
+ raise KeyError(key)
82
+ with _conn() as conn:
83
+ row = conn.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone()
84
+ return row[0] if row else DEFAULT_SETTINGS[key]
85
+
86
+
87
+ def set_setting(key: str, value: str) -> None:
88
+ """Persist a validated setting."""
89
+ if key not in DEFAULT_SETTINGS:
90
+ raise KeyError(key)
91
+ if key == "language" and value not in ("en", "any"):
92
+ raise ValueError("Language must be 'en' or 'any'.")
93
+ if key == "setup_complete" and value not in ("yes", "no"):
94
+ raise ValueError("Setup status must be yes or no.")
95
+ if key == "minutes" and (not value.isascii() or not value.isdecimal() or not 1 <= int(value) <= 180):
96
+ raise ValueError("Reading time must be between 1 and 180 minutes.")
97
+ with _conn() as conn:
98
+ conn.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, value))
99
+
100
+ def count() -> int:
101
+ with _conn() as c:
102
+ return c.execute("SELECT COUNT(*) FROM books").fetchone()[0]
103
+
104
+
105
+ def add_book(identifier: str, title="", author="", kind="nonfiction", genre="") -> bool:
106
+ """Return True if added; False if pool full or already present."""
107
+ with _conn() as c:
108
+ n = c.execute("SELECT COUNT(*) FROM books").fetchone()[0]
109
+ if n >= MAX_POOL_SIZE:
110
+ return False
111
+ try:
112
+ c.execute(
113
+ "INSERT INTO books (identifier, title, author, kind, genre, added_at) "
114
+ "VALUES (?, ?, ?, ?, ?, datetime('now'))",
115
+ (identifier, title, author, kind, genre),
116
+ )
117
+ return True
118
+ except sqlite3.IntegrityError:
119
+ return False
120
+
121
+
122
+ def get_book(book_id: int) -> dict | None:
123
+ with _conn() as c:
124
+ row = c.execute("SELECT * FROM books WHERE id=?", (book_id,)).fetchone()
125
+ return dict(row) if row else None
126
+
127
+
128
+ def list_books() -> list[dict]:
129
+ with _conn() as c:
130
+ rows = c.execute("SELECT * FROM books ORDER BY id").fetchall()
131
+ return [dict(r) for r in rows]
132
+
133
+
134
+ def remove_book(book_id: int) -> bool:
135
+ with _conn() as c:
136
+ cur = c.execute("DELETE FROM books WHERE id=?", (book_id,))
137
+ return cur.rowcount > 0
138
+
139
+ def reset_progress(*, remove_books: bool = False) -> None:
140
+ """Clear reading history and either reset bookmarks or empty the library."""
141
+ with _conn() as conn:
142
+ if remove_books:
143
+ conn.execute("DELETE FROM books")
144
+ else:
145
+ conn.execute("UPDATE books SET offset=0, last_read_at=NULL")
146
+ conn.execute("DELETE FROM reading_sessions")
147
+
148
+
149
+ def set_offset(book_id: int, offset: int) -> None:
150
+ with _conn() as c:
151
+ c.execute(
152
+ "UPDATE books SET offset=?, last_read_at=strftime('%Y-%m-%d %H:%M:%f', 'now') WHERE id=?",
153
+ (offset, book_id),
154
+ )
155
+
156
+ def record_reading(book_id: int, offset: int, pages: int, seconds: int | None = None) -> None:
157
+ """Save a bookmark and record completed interactive pages atomically."""
158
+ with _conn() as c:
159
+ book = c.execute("SELECT identifier, title FROM books WHERE id=?", (book_id,)).fetchone()
160
+ if book is None:
161
+ return
162
+ c.execute(
163
+ "UPDATE books SET offset=?, last_read_at=strftime('%Y-%m-%d %H:%M:%f', 'now') WHERE id=?",
164
+ (offset, book_id),
165
+ )
166
+ if pages or seconds:
167
+ c.execute("INSERT INTO reading_sessions (book_identifier, title, pages, seconds) VALUES (?, ?, ?, ?)",
168
+ (book["identifier"], book["title"], pages, seconds))
169
+
170
+
171
+ def cached_pages(segments: list[tuple[str, int, int]], width: int, height: int,
172
+ paginate) -> list[tuple[str, int]]:
173
+ """Cache recent page layouts, keyed by text, offsets and terminal dimensions."""
174
+ encoded = json.dumps([1, segments, width, height], ensure_ascii=False).encode("utf-8")
175
+ key = hashlib.sha256(encoded).hexdigest()
176
+ with _conn() as c:
177
+ row = c.execute("SELECT pages FROM page_cache WHERE cache_key=?", (key,)).fetchone()
178
+ if row:
179
+ c.execute("UPDATE page_cache SET used_at=strftime('%Y-%m-%d %H:%M:%f', 'now') WHERE cache_key=?", (key,))
180
+ return [(page, offset) for page, offset in json.loads(row[0])]
181
+ pages = paginate(segments, width, height)
182
+ with _conn() as c:
183
+ c.execute("INSERT OR REPLACE INTO page_cache (cache_key, pages) VALUES (?, ?)",
184
+ (key, json.dumps(pages, ensure_ascii=False)))
185
+ c.execute("DELETE FROM page_cache WHERE cache_key NOT IN "
186
+ "(SELECT cache_key FROM page_cache ORDER BY used_at DESC LIMIT 30)")
187
+ return pages
188
+
189
+
190
+ def pages_by_book() -> dict[str, int]:
191
+ return {row["book_identifier"]: row["pages"] for row in reading_stats()}
192
+
193
+
194
+ def reading_stats() -> list[dict]:
195
+ """Summarize completed screen pages, including books removed from the pool."""
196
+ with _conn() as c:
197
+ rows = c.execute(
198
+ "SELECT book_identifier, title, SUM(pages) AS pages, COUNT(*) AS sessions, SUM(seconds) AS seconds "
199
+ "FROM reading_sessions GROUP BY book_identifier ORDER BY pages DESC, title"
200
+ ).fetchall()
201
+ return [dict(row) for row in rows]
202
+
203
+
204
+ def advance_offset(book_id: int, chars: int) -> None:
205
+ with _conn() as c:
206
+ c.execute(
207
+ "UPDATE books SET offset = offset + ?, last_read_at = datetime('now') WHERE id=?",
208
+ (chars, book_id),
209
+ )
210
+
211
+
212
+ def last_read() -> dict | None:
213
+ with _conn() as c:
214
+ row = c.execute(
215
+ "SELECT * FROM books WHERE last_read_at IS NOT NULL "
216
+ "ORDER BY last_read_at DESC LIMIT 1"
217
+ ).fetchone()
218
+ return dict(row) if row else None
219
+
220
+
221
+ def pick_random(exclude_id: int | None = None) -> dict | None:
222
+ books = list_books()
223
+ if not books:
224
+ return None
225
+ candidates = [b for b in books if b["id"] != exclude_id] or books
226
+ return random.choice(candidates)
pyread/terminal.py ADDED
@@ -0,0 +1,60 @@
1
+ """Read individual terminal keys without echoing buffered input."""
2
+
3
+ import os
4
+ import re
5
+ import select
6
+ import sys
7
+ from contextlib import contextmanager
8
+
9
+ import click
10
+
11
+ try:
12
+ import termios
13
+ import tty
14
+ except ImportError:
15
+ termios = tty = None
16
+
17
+
18
+ @contextmanager
19
+ def key_reader():
20
+ try:
21
+ fd = sys.stdin.fileno()
22
+ settings = termios.tcgetattr(fd) if termios else None
23
+ except (AttributeError, OSError, ValueError, termios.error if termios else OSError):
24
+ settings = None
25
+ if settings is None:
26
+ yield lambda timeout=None: click.getchar()
27
+ return
28
+
29
+ pending = bytearray()
30
+
31
+ def read(timeout=None):
32
+ if not pending:
33
+ if not select.select([fd], [], [], timeout)[0]:
34
+ return None
35
+ pending.extend(os.read(fd, 64))
36
+ if not pending:
37
+ raise EOFError
38
+ if pending.startswith(b"\x1b"):
39
+ while len(pending) < 3 and select.select([fd], [], [], 0.03)[0]:
40
+ chunk = os.read(fd, 64)
41
+ if not chunk:
42
+ break
43
+ pending.extend(chunk)
44
+ match = re.match(rb"\x1b(?:\[[0-?]*[ -/]*[@-~]|O.)", pending)
45
+ if match:
46
+ sequence = match.group()
47
+ del pending[:len(sequence)]
48
+ return sequence.decode("ascii", "replace")
49
+ key = pending.pop(0)
50
+ if key == 3:
51
+ raise KeyboardInterrupt
52
+ if key == 4:
53
+ raise EOFError
54
+ return chr(key)
55
+
56
+ try:
57
+ tty.setcbreak(fd)
58
+ yield read
59
+ finally:
60
+ termios.tcsetattr(fd, termios.TCSADRAIN, settings)
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyread-cli
3
+ Version: 0.1.0
4
+ Summary: A terminal-based reading tool.
5
+ Project-URL: Repository, https://github.com/MShafquat/pyread
6
+ Project-URL: Issues, https://github.com/MShafquat/pyread/issues
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.11
10
+ Requires-Dist: click>=8.5.1
11
+ Requires-Dist: pyyaml>=6.0.4
12
+ Requires-Dist: requests>=2.34.2
13
+ Requires-Dist: rich>=15.0.0
14
+ Requires-Dist: typer>=0.29.3
15
+ Description-Content-Type: text/markdown
16
+
17
+ # pyread
18
+
19
+ [![Build](https://github.com/MShafquat/pyread/actions/workflows/build.yml/badge.svg?branch=main)](https://github.com/MShafquat/pyread/actions/workflows/build.yml)
20
+ [![Tests](https://github.com/MShafquat/pyread/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/MShafquat/pyread/actions/workflows/tests.yml)
21
+
22
+ A terminal reader for books from Project Gutenberg and the Internet Archive.
23
+ Find a book, read an excerpt sized to your time, and pick up where you left off.
24
+
25
+ ## Install
26
+
27
+ Requires Python 3.11 or later.
28
+
29
+ ```sh
30
+ python -m pip install "git+https://github.com/MShafquat/pyread.git"
31
+ pyread
32
+ ```
33
+
34
+ Use **↑/↓** to move, **Enter** to select, and **q** to quit. First launch opens
35
+ Settings, where you can set your reading time and choose suggestion topics.
36
+
37
+ ```sh
38
+ pyread search "science fiction"
39
+ pyread suggest
40
+ pyread next --continue
41
+ pyread stats
42
+ ```
43
+
44
+ Downloads and reading progress are stored in `~/.pyread/`. Downloaded books
45
+ can be read offline. Run `pyread --help` for all commands.
46
+
47
+ ## Development
48
+
49
+ ```sh
50
+ uv sync --locked
51
+ uv run --locked pytest -q
52
+ uv build --no-sources
53
+ ```
54
+
55
+ Stable GitHub releases publish to PyPI once you configure [Trusted Publishing](https://docs.pypi.org/trusted-publishers/).
56
+ For an existing release, run **Publish to PyPI** from the Actions tab with its
57
+ version tag and select **Upload to PyPI**.
@@ -0,0 +1,16 @@
1
+ pyread/__init__.py,sha256=Pru0BlFBASFCFo7McHdohtKkUtgMPDwbGfyUZlE2_Vw,21
2
+ pyread/cli.py,sha256=BzfKUCyMeDqFulecPgHHZCj0ZT4VZFRKhqIm3eGBPqw,47960
3
+ pyread/state.py,sha256=FL4kiVs0HN9eNGhZNBIF7hVqIwur2tmjD9mb0SJ8aiU,8408
4
+ pyread/terminal.py,sha256=e-iO64mo8iBUqxajcvcBiWq_IyBVfsZBbRDfRfosq4A,1641
5
+ pyread/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ pyread/core/budget.py,sha256=Guq__VBzOSWsoPybpHU1wf11Vze5l1I5DmOdvVVeAa4,462
7
+ pyread/core/cache.py,sha256=XuXXEyjsKb-QGfdZwqA49phzziklNPdDHllrABrgYlI,1658
8
+ pyread/core/extractor.py,sha256=BZwywX_E9x7xVGO4dlZpru4hATgvQfc8BaQg5nVuy_c,4994
9
+ pyread/core/fetcher.py,sha256=VsUAXygpZ51Q3vheXSU4Xmm_hF_nE0QGSdMWIfgXBEs,13563
10
+ pyread/core/text_model.py,sha256=mhU3ygh6HE7yeEF7WmfbYH7d1dIMsTQMSQuYT2lFcoA,2111
11
+ pyread/core/timer.py,sha256=Fxigc_N3wjY-jSUOJjXeJwS1Y5vc5zRHRNZIJNalduY,815
12
+ pyread_cli-0.1.0.dist-info/METADATA,sha256=-u0hHAJNpEO9l9vsVMVK3E0CHJVvs-g39KCQYYOAxJA,1830
13
+ pyread_cli-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ pyread_cli-0.1.0.dist-info/entry_points.txt,sha256=JPVS0vt6NfOfWEJajhK3hL-1ZESYhV1k5W7bu8G62Iw,42
15
+ pyread_cli-0.1.0.dist-info/licenses/LICENSE,sha256=SJArOVIo4iSn8YhJRPsl1SKfq8xMVZUvrqhiXNbj2-Y,1072
16
+ pyread_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pyread = pyread.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shafquat Mahbub
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.