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.
File without changes
pyread/core/budget.py ADDED
@@ -0,0 +1,14 @@
1
+ WPM_NONFICTION = 238
2
+ WPM_FICTION = 260
3
+
4
+
5
+ def target_words(minutes: int, kind: str = "nonfiction") -> int:
6
+ """Estimate how many words a reader can cover in `minutes`.
7
+
8
+ Uses genre-specific silent reading speeds (Brysbaert 2019):
9
+ non-fiction ≈ 238 wpm, fiction ≈ 260 wpm.
10
+ """
11
+ if minutes < 0:
12
+ raise ValueError("minutes must be non-negative")
13
+ wpm = WPM_FICTION if kind == "fiction" else WPM_NONFICTION
14
+ return int(minutes * wpm)
pyread/core/cache.py ADDED
@@ -0,0 +1,46 @@
1
+ """Local copies of source text; stable bytes keep saved bookmarks valid."""
2
+
3
+ import hashlib
4
+ import os
5
+ import tempfile
6
+ from pathlib import Path
7
+ from collections.abc import Callable
8
+
9
+
10
+ def _cache_path(directory: Path, identifier: str) -> Path:
11
+ key = hashlib.sha256(identifier.encode("utf-8")).hexdigest()
12
+ return directory / f"{key}.txt"
13
+
14
+
15
+ def read_cached_text(directory: Path, identifier: str) -> str | None:
16
+ """Read the exact cached edition without contacting the network."""
17
+ try:
18
+ with _cache_path(directory, identifier).open(encoding="utf-8", newline="") as cached:
19
+ return cached.read()
20
+ except FileNotFoundError:
21
+ return None
22
+
23
+
24
+ def cached_text(directory: Path, identifier: str, fetch: Callable[[], str]) -> str:
25
+ """Read a previously downloaded edition, or atomically cache its text."""
26
+ path = _cache_path(directory, identifier)
27
+ cached = read_cached_text(directory, identifier)
28
+ if cached is not None:
29
+ return cached
30
+ text = fetch()
31
+ if not text.strip():
32
+ raise ValueError("The book server returned an empty text.")
33
+ directory.mkdir(parents=True, exist_ok=True)
34
+ fd, temporary = tempfile.mkstemp(dir=directory, prefix=".download-")
35
+ try:
36
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as output:
37
+ output.write(text)
38
+ # Avoid replacing a copy used by another reader and invalidating offsets.
39
+ try:
40
+ os.link(temporary, path)
41
+ except FileExistsError:
42
+ with path.open(encoding="utf-8", newline="") as cached:
43
+ return cached.read()
44
+ finally:
45
+ os.unlink(temporary)
46
+ return text
@@ -0,0 +1,118 @@
1
+ """Extract readable passages while retaining positions in the original OCR text."""
2
+
3
+ import re
4
+
5
+
6
+ # Facing pages can use either a book/chapter marker or a date and page number.
7
+ _PAGE_NUMBER = r"(?:[0-9Il|Oo]{1,4}|[1Il][aAzZ])"
8
+ _HEADER_TITLE = r"[A-Z][A-Z .,'’&–—-]+"
9
+ _RUNNING_HEAD = re.compile(
10
+ rf"(?:{_PAGE_NUMBER}[ \t]+{_HEADER_TITLE}[ \t]+"
11
+ rf"\[[ \t]*(?i:bk|book|ch|chap)\.[^\n]*"
12
+ rf"|[12][0-9]{{3}}\][ \t]+{_HEADER_TITLE}[ \t]+{_PAGE_NUMBER})"
13
+ )
14
+
15
+
16
+ def strip_front_matter(text: str) -> tuple[str, int]:
17
+ """Return the text after likely front matter and its original offset."""
18
+ marker = re.search(r"^\*\*\*\s*START OF (?:THE|THIS) PROJECT GUTENBERG EBOOK.*$",
19
+ text, re.MULTILINE | re.IGNORECASE)
20
+ start = marker.end() if marker else 0
21
+ opening = text[start:start + 30000]
22
+ illustration = re.search(
23
+ r"^[ \t]*(?:fr+ontispiece\b|(?:list of )?(?:illustrations|plates)[ \t]*$)",
24
+ opening, re.MULTILINE | re.IGNORECASE,
25
+ )
26
+ if illustration:
27
+ # A chapter heading on its own line distinguishes the body from caption entries.
28
+ body = re.search(
29
+ r"^[ \t]*chapter[ \t]+(?:[ivxlcdm]+|[0-9]+)[. \t]*\r?$",
30
+ opening[illustration.end():], re.MULTILINE | re.IGNORECASE,
31
+ )
32
+ if body:
33
+ start += illustration.end() + body.start()
34
+ return text[start:], start
35
+ if marker:
36
+ while start < len(text) and text[start] in "\r\n":
37
+ start += 1
38
+ return text[start:], start
39
+ heading = re.search(
40
+ r"^[ \t]*(?:CHAPTER|BOOK|PART)\s+(?:[IVXLCDM]+|\d+)\b",
41
+ text, re.MULTILINE | re.IGNORECASE,
42
+ )
43
+ for match in re.finditer(r"\S[\s\S]*?(?=\n\s*\n|\Z)", text):
44
+ block = match.group()
45
+ letters = [c for c in block if c.isalpha()]
46
+ if len(letters) >= 100 and sum(c.islower() for c in letters) / len(letters) > 0.6 and block.count('.') >= 2:
47
+ return text[match.start():], match.start()
48
+ if heading:
49
+ return text[heading.start():], heading.start()
50
+ return text, 0
51
+
52
+
53
+ def _clean_block(block: str) -> str:
54
+ # Remove scan artifacts without editing the original bookmark coordinates.
55
+ block = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", block)
56
+ block = re.sub(r"[\x00-\x08\x0e-\x1f\x7f\ufeff\u00ad]", "", block)
57
+ # Remove distinctive scan debris while preserving ordinary punctuation and quotes.
58
+ block = re.sub(r"(?<!\S)(?:[|¦©®]+[ \t]*)+[)»]+(?=\s|$)", " ", block)
59
+ block = re.sub(r"(?<!\S)(?:[|¦]+|[|¦«»©®�]{2,})(?!\S)", " ", block)
60
+ block = block.replace("�", "")
61
+ block = re.sub(r"(?<!\S)\^(?=[A-Za-z]{3,}\b)", "", block)
62
+ block = re.sub(r"(\w)-[ \t]*\r?\n[ \t]*(\w)", r"\1\2", block)
63
+ lines = []
64
+ for line in block.splitlines():
65
+ line = line.strip()
66
+ if (not line or _RUNNING_HEAD.fullmatch(line)
67
+ or not any(char.isalnum() for char in line)
68
+ or re.fullmatch(r"(?:\[\d+\]|\d{1,3})", line)):
69
+ continue
70
+ lines.append(re.sub(r"\s*\[\d+\]\s*", " ", line))
71
+ cleaned = re.sub(r"\s+", " ", " ".join(lines)).strip()
72
+ return re.sub(r"[ \t]+([,.;:!?])", r"\1", cleaned)
73
+
74
+
75
+ def book_text_end(text: str) -> int:
76
+ """Return the end of the book body, before a Gutenberg footer."""
77
+ marker = re.search(r"^\*\*\*\s*END OF (?:THE|THIS) PROJECT GUTENBERG EBOOK.*$",
78
+ text, re.MULTILINE | re.IGNORECASE)
79
+ end = marker.start() if marker else len(text)
80
+ return len(text[:end].rstrip())
81
+
82
+
83
+ def collect_segments(text: str, target: int) -> list[tuple[str, int, int]]:
84
+ """Return cleaned blocks with their start and end offsets in *text*."""
85
+ text = text[:book_text_end(text)]
86
+ segments = []
87
+ words = 0
88
+ header_gap = False
89
+ for match in re.finditer(r"\S[\s\S]*?(?=\r?\n\s*\r?\n|\Z)", text):
90
+ block = match.group()
91
+ if _RUNNING_HEAD.fullmatch(block.strip()):
92
+ header_gap = True
93
+ continue
94
+ cleaned = _clean_block(block)
95
+ if not cleaned:
96
+ continue
97
+ if (header_gap and segments and cleaned[0].islower()
98
+ and not segments[-1][0].endswith((".", "!", "?", "”", '"'))):
99
+ previous, start, _ = segments[-1]
100
+ segments[-1] = (previous + " " + cleaned, start, match.end())
101
+ elif words >= target and segments:
102
+ break
103
+ else:
104
+ segments.append((cleaned, match.start(), match.end()))
105
+ header_gap = False
106
+ words += len(cleaned.split())
107
+ return segments
108
+
109
+
110
+ def paragraphs(text: str) -> list[str]:
111
+ """Return cleaned OCR paragraphs without removing front matter."""
112
+ return [segment[0] for segment in collect_segments(text, float('inf'))]
113
+
114
+
115
+ def collect_until(text: str, target: int) -> tuple[str, int]:
116
+ """Return an excerpt and the original character span it consumes."""
117
+ segments = collect_segments(text, target)
118
+ return "\n\n".join(s[0] for s in segments), segments[-1][2] if segments else 0
pyread/core/fetcher.py ADDED
@@ -0,0 +1,317 @@
1
+ """Discover public books and prefer downloadable Project Gutenberg editions."""
2
+
3
+ from urllib.parse import quote, urlparse
4
+ from collections.abc import Iterator
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ import re
7
+
8
+ import requests
9
+
10
+ OL_SEARCH_URL = "https://openlibrary.org/search.json"
11
+ IA_METADATA_URL = "https://archive.org/metadata/{identifier}"
12
+ IA_DOWNLOAD_URL = "https://archive.org/download/{identifier}/{filename}"
13
+ GUTENDEX_URL = "https://gutendex.com/books"
14
+ GUTENBERG_MIRRORS = ("https://gutenberg.pglaf.org",
15
+ "https://www.ibiblio.org/pub/docs/books/gutenberg")
16
+ HEADERS = {"User-Agent": "pyread/0.1 (terminal reading tool)"}
17
+
18
+
19
+ def _public_text_filename(identifier: str, language: str = "any") -> str | None:
20
+ response = requests.get(IA_METADATA_URL.format(identifier=quote(identifier, safe="")),
21
+ headers=HEADERS, timeout=30)
22
+ if response.status_code == 404:
23
+ return None
24
+ response.raise_for_status()
25
+ metadata = response.json()
26
+ if str(metadata.get("is_dark", "false")).lower() == "true":
27
+ return None
28
+ languages = (metadata.get("metadata") or {}).get("language") or []
29
+ if isinstance(languages, str):
30
+ languages = [languages]
31
+ if language == "en" and languages and not any(
32
+ re.search(r"\b(?:en|eng|english)\b", str(value), re.IGNORECASE)
33
+ for value in languages
34
+ ):
35
+ return None
36
+ for file in metadata.get("files", []):
37
+ name = file.get("name", "")
38
+ if name.endswith("_djvu.txt") and str(file.get("private", "false")).lower() != "true":
39
+ return name
40
+ return None
41
+
42
+
43
+ def is_text_public(identifier: str, language: str = "any") -> bool:
44
+ """Check for a public OCR file in item metadata."""
45
+ return bool(_public_text_filename(identifier, language))
46
+
47
+
48
+ def fetch_ia_text(identifier: str) -> str:
49
+ """Download public OCR, using the filename reported by the archive."""
50
+ filename = _public_text_filename(identifier)
51
+ if not filename:
52
+ raise FileNotFoundError(f"No public full text found for {identifier}")
53
+ url = IA_DOWNLOAD_URL.format(identifier=quote(identifier, safe=""),
54
+ filename=quote(filename, safe=""))
55
+ response = requests.get(url, headers=HEADERS, timeout=60)
56
+ if response.status_code == 404:
57
+ raise FileNotFoundError(f"No full text found for {identifier}")
58
+ response.raise_for_status()
59
+ return response.text
60
+
61
+
62
+
63
+ def _description_value(value: object) -> str:
64
+ """Normalize catalog fields that may be text, a list, or a typed value."""
65
+ if isinstance(value, list):
66
+ return _description_value(value[0]) if value else ""
67
+ if isinstance(value, dict):
68
+ return _description_value(value.get("value"))
69
+ return " ".join(value.split()) if isinstance(value, str) else ""
70
+
71
+
72
+ def book_description(book: dict) -> str:
73
+ """Fetch an Open Library work description; use catalog summaries otherwise."""
74
+ key = book.get("work_key", "")
75
+ if re.fullmatch(r"/works/OL[0-9]+W", key):
76
+ try:
77
+ response = requests.get(f"https://openlibrary.org{key}.json", headers=HEADERS, timeout=3)
78
+ response.raise_for_status()
79
+ description = _description_value(response.json().get("description"))
80
+ if description:
81
+ return description
82
+ except (requests.RequestException, ValueError):
83
+ pass
84
+ return book.get("description", "")
85
+
86
+ def _search_open_library(query: str, limit: int, language: str = "en") -> list[dict]:
87
+ language_filter = " AND language:eng" if language == "en" else ""
88
+ response = requests.get(OL_SEARCH_URL, params={
89
+ "q": f"({query}) AND ebook_access:public{language_filter}",
90
+ "fields": "key,title,author_name,ia,subject", "limit": limit,
91
+ }, headers=HEADERS, timeout=15)
92
+ response.raise_for_status()
93
+ results = []
94
+ for doc in response.json().get("docs", []):
95
+ identifiers = doc.get("ia") or []
96
+ if isinstance(identifiers, str):
97
+ identifiers = [identifiers]
98
+ identifiers = [identifier for identifier in identifiers if identifier]
99
+ if identifiers:
100
+ results.append({"title": doc.get("title") or "Untitled",
101
+ "author": (doc.get("author_name") or ["Unknown"])[0],
102
+ "identifiers": identifiers, "source": "Open Library",
103
+ "work_key": doc.get("key", ""),
104
+ "subjects": doc.get("subject") or []})
105
+ return results
106
+
107
+
108
+ def _search_gutenberg(query: str, limit: int, language: str = "en") -> list[dict]:
109
+ results = []
110
+ # Gutendex separates subject searches from title/author searches.
111
+ for field in ("topic", "search"):
112
+ try:
113
+ params = {field: query, "mime_type": "text/plain"}
114
+ if language == "en":
115
+ params["languages"] = "en"
116
+ response = requests.get(GUTENDEX_URL, params=params, headers=HEADERS, timeout=6)
117
+ response.raise_for_status()
118
+ except requests.RequestException:
119
+ if results:
120
+ break
121
+ raise
122
+ for book in response.json().get("results", []):
123
+ if not any(key.startswith("text/plain") for key in book.get("formats", {})):
124
+ continue
125
+ authors = book.get("authors") or []
126
+ results.append({"title": book.get("title") or "Untitled",
127
+ "author": authors[0].get("name", "Unknown") if authors else "Unknown",
128
+ "identifiers": [f"gutenberg:{book['id']}"], "source": "Gutenberg",
129
+ "description": _description_value(book.get("summaries")),
130
+ "subjects": book.get("subjects") or []})
131
+ if len(results) >= limit:
132
+ break
133
+ return results
134
+
135
+
136
+ def search_books(subject: str, limit: int = 10, language: str = "en", *,
137
+ parallel: bool = True) -> list[dict]:
138
+ """Prefer Gutenberg editions and retain matching Archive scans as fallbacks."""
139
+ if language not in ("en", "any"):
140
+ raise ValueError("Language must be en or any")
141
+ direct = re.fullmatch(r"gutenberg:([1-9][0-9]*)", subject.strip(), re.IGNORECASE)
142
+ if direct:
143
+ number = direct[1]
144
+ try:
145
+ response = requests.get(f"{GUTENDEX_URL}/{number}", headers=HEADERS, timeout=6)
146
+ response.raise_for_status()
147
+ book = response.json()
148
+ except (requests.RequestException, ValueError):
149
+ # An explicit ID can still be checked and read directly from a mirror.
150
+ book = {}
151
+ authors = book.get("authors") or []
152
+ return [{"title": book.get("title") or f"Gutenberg eBook #{number}",
153
+ "author": authors[0].get("name", "Unknown") if authors else "Unknown",
154
+ "identifiers": [f"gutenberg:{number}"], "source": "Gutenberg",
155
+ "description": _description_value(book.get("summaries"))}]
156
+
157
+ def query(search):
158
+ try:
159
+ return search(subject, limit, language), None
160
+ except (requests.RequestException, ValueError) as error:
161
+ return [], error
162
+
163
+ providers = (_search_gutenberg, _search_open_library)
164
+ if parallel:
165
+ with ThreadPoolExecutor(max_workers=2) as executor:
166
+ responses = list(executor.map(query, providers))
167
+ else:
168
+ responses = [query(provider) for provider in providers]
169
+ catalogs = [books for books, _ in responses]
170
+ errors = [error for _, error in responses if error is not None]
171
+ if not any(catalogs) and errors:
172
+ raise requests.RequestException("A book catalog was unavailable and no results were found") from errors[-1]
173
+ works = {}
174
+ for catalog in catalogs:
175
+ for book in catalog:
176
+ title = " ".join(re.findall(r"\w+", book["title"].casefold()))
177
+ author = tuple(sorted(re.findall(r"\w+", book["author"].casefold())))
178
+ if not title:
179
+ continue
180
+ key = (title, author)
181
+ if key not in works:
182
+ works[key] = dict(book, identifiers=list(book["identifiers"]))
183
+ continue
184
+ preferred = works[key]
185
+ preferred["identifiers"] = list(dict.fromkeys(
186
+ preferred["identifiers"] + book["identifiers"]
187
+ ))
188
+ if not preferred.get("work_key") and book.get("work_key"):
189
+ preferred["work_key"] = book["work_key"]
190
+ return list(works.values())[:limit]
191
+
192
+
193
+ def _gutenberg_urls(number: str) -> Iterator[str]:
194
+ """Try known mirror paths before asking the catalog for alternate file names."""
195
+ parent = "/".join((*number[:-1], number))
196
+ paths = [
197
+ f"/cache/epub/{number}/pg{number}.txt",
198
+ f"/{parent}/{number}-0.txt",
199
+ f"/{parent}/{number}.txt",
200
+ ]
201
+ utf8_mirrors = (
202
+ f"https://mirror.csclub.uwaterloo.ca/gutenberg/{parent}/{number}-0.txt",
203
+ f"https://readingroo.ms/{parent}/{number}-0.txt",
204
+ )
205
+ seen = set(utf8_mirrors)
206
+ yield from utf8_mirrors
207
+ for path in paths:
208
+ for mirror in GUTENBERG_MIRRORS:
209
+ url = mirror + path
210
+ seen.add(url)
211
+ yield url
212
+
213
+ try:
214
+ response = requests.get(f"{GUTENDEX_URL}/{number}", headers=HEADERS, timeout=6)
215
+ response.raise_for_status()
216
+ formats = response.json().get("formats", {})
217
+ except (requests.RequestException, ValueError):
218
+ return
219
+ candidates = [(mime, url) for mime, url in formats.items() if mime.startswith("text/plain")]
220
+ candidates.sort(key=lambda item: "utf-8" not in item[0].lower())
221
+ for _, url in candidates:
222
+ parsed = urlparse(url)
223
+ if parsed.hostname not in ("www.gutenberg.org", "gutenberg.org"):
224
+ continue
225
+ path = parsed.path
226
+ if path.startswith(f"/files/{number}/"):
227
+ path = f"/{parent}/{path.rsplit('/', 1)[-1]}"
228
+ elif not path.startswith(f"/cache/epub/{number}/"):
229
+ continue
230
+ for mirror in GUTENBERG_MIRRORS:
231
+ url = mirror + path
232
+ if url not in seen:
233
+ seen.add(url)
234
+ yield url
235
+
236
+
237
+ def _is_plain_text(response) -> bool:
238
+ return response.headers.get("Content-Type", "").partition(";")[0].strip().lower() == "text/plain"
239
+
240
+
241
+ def _gutenberg_text(identifier: str) -> str:
242
+ number = identifier.removeprefix("gutenberg:")
243
+ if not re.fullmatch(r"[0-9]+", number):
244
+ raise ValueError("Invalid Gutenberg book identifier")
245
+ for url in _gutenberg_urls(number):
246
+ try:
247
+ response = requests.get(url, headers=HEADERS, timeout=10)
248
+ response.raise_for_status()
249
+ if _is_plain_text(response) and response.text.strip():
250
+ # Most Gutenberg mirror files are UTF-8 even without a charset header.
251
+ try:
252
+ return response.content.decode("utf-8-sig")
253
+ except UnicodeDecodeError:
254
+ return response.text
255
+ except requests.RequestException:
256
+ continue
257
+ raise FileNotFoundError(f"No public text found for Gutenberg book {number}")
258
+
259
+
260
+ def fetch_book_text(identifier: str) -> str:
261
+ """Fetch the selected edition without switching to a different text."""
262
+ if identifier.startswith("gutenberg:"):
263
+ return _gutenberg_text(identifier)
264
+ return fetch_ia_text(identifier)
265
+
266
+
267
+ def resolve_public_identifier(identifiers: list[str], language: str = "any") -> str | None:
268
+ """Find a public scan, tolerating a failure on an individual scan."""
269
+ last_error = None
270
+ for identifier in identifiers:
271
+ if identifier.startswith("gutenberg:"):
272
+ return identifier
273
+ try:
274
+ if is_text_public(identifier, language):
275
+ return identifier
276
+ except requests.RequestException as error:
277
+ last_error = error
278
+ if last_error:
279
+ raise last_error
280
+ return None
281
+
282
+
283
+ def find_book(subject: str, limit: int = 20) -> dict | None:
284
+ """Find the first candidate with a public scan."""
285
+ for book in search_books(subject, limit):
286
+ identifier = resolve_public_identifier(book["identifiers"])
287
+ if identifier:
288
+ return {"title": book["title"], "author": book["author"], "identifier": identifier}
289
+ return None
290
+
291
+
292
+ def available_identifier(identifiers: list[str], language: str) -> str | None:
293
+ """Return an edition whose text server actually serves plain text."""
294
+ for identifier in sorted(identifiers, key=lambda value: not value.startswith("gutenberg:")):
295
+ if identifier.startswith("gutenberg:"):
296
+ number = identifier.removeprefix("gutenberg:")
297
+ if not re.fullmatch(r"[0-9]+", number):
298
+ continue
299
+ urls = _gutenberg_urls(number)
300
+ else:
301
+ try:
302
+ filename = _public_text_filename(identifier, language)
303
+ except requests.RequestException:
304
+ continue
305
+ if not filename:
306
+ continue
307
+ urls = [IA_DOWNLOAD_URL.format(identifier=quote(identifier, safe=""),
308
+ filename=quote(filename, safe=""))]
309
+ for url in urls:
310
+ try:
311
+ with requests.get(url, headers=HEADERS, timeout=5, stream=True) as response:
312
+ if response.ok and _is_plain_text(response):
313
+ if next(response.iter_content(chunk_size=512), b"").strip():
314
+ return identifier
315
+ except requests.RequestException:
316
+ continue
317
+ return None
@@ -0,0 +1,52 @@
1
+ """A bounded word language model for local, conservative text cleanup."""
2
+
3
+ import re
4
+ from collections import Counter
5
+
6
+ _WORD = re.compile(r"\b[A-Za-z]{3,24}\b")
7
+ _PAIR = re.compile(r"(?=\b([A-Za-z]{3,24}) +([A-Za-z]{3,24})\b)")
8
+ _BROKEN = re.compile(r"(?=\b([A-Za-z]{2,24})(?:[|¦�>][ \t]*| )([a-z]{2,24})\b)")
9
+ SAMPLE_SIZE = 128_000
10
+
11
+
12
+ class TextModel:
13
+ """Learn word and adjacent word frequencies from a small text sample."""
14
+
15
+ def __init__(self, reference: str):
16
+ sample = reference[:SAMPLE_SIZE].lower()
17
+ self.words = Counter(match.group() for match in _WORD.finditer(sample))
18
+ self.pairs = Counter(match.groups() for match in _PAIR.finditer(sample))
19
+
20
+ def clean(self, text: str) -> str:
21
+ parts = []
22
+ start = 0
23
+ for match in _BROKEN.finditer(text):
24
+ if match.start() < start:
25
+ continue
26
+ left, right = match.groups()
27
+ a, b = left.lower(), right.lower()
28
+ combined = self.words[a + b]
29
+ separate = self.pairs[a, b]
30
+ if (combined >= 4 and combined >= 4 * separate
31
+ and min(self.words[a], self.words[b]) <= 1):
32
+ parts.extend((text[start:match.start()], left + right))
33
+ start = match.end(2)
34
+ parts.append(text[start:])
35
+ return _WORD.sub(self._split, "".join(parts))
36
+
37
+ def _split(self, match: re.Match[str]) -> str:
38
+ word = match.group()
39
+ if not word.islower() or self.words[word] > 1:
40
+ return word
41
+ options = [(self.pairs[word[:i], word[i:]], i) for i in range(3, len(word) - 2)]
42
+ ranked = sorted((option for option in options if option[0] >= 4), reverse=True)
43
+ if len(ranked) != 1:
44
+ return word
45
+ _, split = ranked[0]
46
+ return word[:split] + " " + word[split:]
47
+
48
+
49
+ def clean_segments(segments: list[tuple[str, int, int]], reference: str) -> list[tuple[str, int, int]]:
50
+ """Clean text without moving the original bookmark coordinates."""
51
+ model = TextModel(reference)
52
+ return [(model.clean(text), start, end) for text, start, end in segments]
pyread/core/timer.py ADDED
@@ -0,0 +1,27 @@
1
+ """A cancellable reading timer that can be used by terminal or other clients."""
2
+
3
+ from collections.abc import Callable
4
+ from threading import Event, Timer
5
+
6
+
7
+ class ReadingTimer:
8
+ """Signal once after a duration in seconds; cancel when reading ends."""
9
+
10
+ def __init__(self, seconds: float, on_expire: Callable[[], None] | None = None):
11
+ if seconds <= 0:
12
+ raise ValueError("Timer duration must be positive")
13
+ self.expired = Event()
14
+ self._on_expire = on_expire
15
+ self._timer = Timer(seconds, self._expire)
16
+ self._timer.daemon = True
17
+
18
+ def _expire(self) -> None:
19
+ self.expired.set()
20
+ if self._on_expire:
21
+ self._on_expire()
22
+
23
+ def start(self) -> None:
24
+ self._timer.start()
25
+
26
+ def cancel(self) -> None:
27
+ self._timer.cancel()