diff --git a/README.md b/README.md index 6d9d864..36d52ba 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,17 @@ for the [Gutendex](https://gutendex.com/) catalog of - **`gutendex.find_books`** — find public-domain books by **author**, **title**, or **genre** (author/title use Gutendex `search`; genre uses `topic`). - **`gutendex.read_book`** — resolve a book by name or Project Gutenberg id and - download its **full plain text**, saving it to a `.txt` file. + read it. It checks the **local library first** (the books folder): a book + already saved — matched by id, or by the name in the request — is read from + disk with no network at all, and a book resolved from the catalog is reused + from disk rather than downloaded again. A book not in the library is + downloaded and saved as a `.txt` file. Over a **voice front end** (the local + voice gateway, or an LXMF/Sideband voice chat) it instead **reads the book + aloud**: the text is streamed through Piper one chunk at a time until the user + says "stop", and the position is kept in a `bookmarks.json` beside the saved + books so a later request **resumes** where the listener stopped. A book is far + too long to speak as a chat reply, so over a text front end it is saved to a + file and summarised. Gutendex is a free public JSON API. This pack needs **no account, no credentials, and no bridge** — the skill bodies make the HTTP requests directly diff --git a/skills/gutendex/read_book/manifest.json b/skills/gutendex/read_book/manifest.json index b393435..832d4fa 100644 --- a/skills/gutendex/read_book/manifest.json +++ b/skills/gutendex/read_book/manifest.json @@ -1,3 +1,3 @@ { - "description": "Download the full text of a Project Gutenberg book by author or title and save it to a file, reporting the saved path." + "description": "Read a Project Gutenberg book by author or title: check the local library first, otherwise download the full text and save it; over the voice gateway, read it aloud until the user stops it, resuming from a saved bookmark." } diff --git a/skills/gutendex/read_book/skill.py b/skills/gutendex/read_book/skill.py index 0f349af..72301ce 100644 --- a/skills/gutendex/read_book/skill.py +++ b/skills/gutendex/read_book/skill.py @@ -4,8 +4,20 @@ Real integration: the free public Gutendex JSON API over HTTP (`gutendex_base_url`) resolves the book and its plain-text format, then that text is downloaded over HTTP. A book is far too long to read into a chat result, so the full text is saved to a `.txt` file under `output_dir` and a -short summary plus the path is returned. Real failures are reported honestly; -text is never invented. +short summary plus the path is returned. + +The **local library** (`output_dir`, where saved books live) is checked +first: a book already saved — matched by Project Gutenberg id, or by the name in +the request — is read from disk with no network at all, and a book resolved from +the catalog is reused from disk rather than downloaded again. + +When the request arrives from the **voice gateway**, the agent instead reads the +book aloud: the saved text is registered on the scheduler's speech channel +(`ctx.speech`) and the voice front end streams it through Piper one chunk at a +time until the user stops it. The position reached is kept in a +`bookmarks.json` beside the saved books, so asking for the same book again +resumes where the listener stopped. Real failures are reported honestly; text +is never invented. Gutendex sits behind Cloudflare, which rejects the default `Python-urllib` User-Agent with HTTP 403, so every request identifies itself with `USER_AGENT`. @@ -22,6 +34,7 @@ import urllib.request from pathlib import Path from semif_agent.decisions import DecisionRequest, Option +from semif_agent.reading import bookmarks_file, read_offset from semif_agent.skills import ActionResult INTEGRATION = { @@ -104,6 +117,114 @@ def _slug(text): return slug[:60] or "book" +# A saved book is `gutenberg--.txt` in the books directory (the +# "library"); the id and slug in the filename are the library's index. +LIBRARY_PREFIX = "gutenberg-" +LIBRARY_SUFFIX = ".txt" + + +def _library_entries(output_dir): + """Existing saved books in the local library: ``(id, path, slug)`` per file. + + The library is the books directory itself. Only files that follow the saved + shape are listed; anything else is ignored. + """ + directory = Path(output_dir) + if not directory.is_dir(): + return [] + entries = [] + for path in sorted(directory.glob(f"{LIBRARY_PREFIX}*{LIBRARY_SUFFIX}")): + stem = path.name[len(LIBRARY_PREFIX) : -len(LIBRARY_SUFFIX)] + book_id, _sep, slug = stem.partition("-") + if book_id.isdigit(): + entries.append((book_id, path, slug)) + return entries + + +def _title_from_slug(slug): + """A display title from a saved filename's slug (best effort).""" + return (slug or "").replace("-", " ").strip() or "Untitled" + + +def _local_by_id(entries, book_id): + """The saved library entry for a book id, or None.""" + for entry in entries: + if entry[0] == str(book_id): + return entry + return None + + +def _local_by_query(entries, query): + """A saved book whose title matches a name query, or None when ambiguous. + + Matches the request's search terms against the slug in each filename: an + exact slug match wins, otherwise a single substring match is used. Several + matches are left to the catalog (the human picks). + """ + want = _slug(query) + if len(want) < 3: + return None + exact = [entry for entry in entries if entry[2] == want] + if len(exact) == 1: + return exact[0] + partial = [entry for entry in entries if want in entry[2] or entry[2] in want] + if len(partial) == 1: + return partial[0] + return None + + +def _library_book(entry): + """A minimal book record for a book resolved from the local library.""" + return {"id": int(entry[0]), "title": _title_from_slug(entry[2]), "authors": []} + + +def _can_read_aloud(ctx, source): + """Whether the front end for `source` can stream a read-aloud. + + The scheduler's speech channel is told which sources its front ends can + stream to (the voice gateway; an LXMF chat that last messaged by voice). A + typed request, or a front end that cannot stream, gets the saved-file + summary instead. + """ + speech = getattr(ctx, "speech", None) + supports = getattr(speech, "supports", None) + return speech is not None and callable(supports) and supports(str(source or "")) + + +def _read_aloud(ctx, request, path, text, book, output_dir, from_library=False): + """Register a read-aloud request for the voice front end, from the bookmark. + + Returns the spoken summary, or None when there is no speech channel (a + non-gateway front end), so the caller falls back to the saved-file summary. + """ + speech = getattr(ctx, "speech", None) + if speech is None: + return None + bookmarks_path = bookmarks_file(output_dir) + key = f"gutenberg-{book.get('id')}" + start = read_offset(bookmarks_path, key) + resumed = 0 < start < len(text) + if start >= len(text): + start = 0 # the book was finished; start over + source = request.origin_source or request.source or "" + speech.read_aloud( + path=str(path), + key=key, + bookmarks_path=str(bookmarks_path), + run_id=request.id, + source=source, + title=str(book.get("title", "Untitled")), + start=start, + ) + title = book.get("title", "Untitled") + if resumed: + return f"Resuming '{title}' where you left off. Say stop to pause." + authors = _authors(book) + by = f" by {authors}" if authors and authors != "unknown author" else "" + origin = " from your library" if from_library else "" + return f"Reading '{title}'{by} aloud{origin}. Say stop to pause." + + def _get_json(base_url, path, params=None): url = base_url + path if params: @@ -132,14 +253,22 @@ def act(ctx, request): action_log="output_dir is not configured", new_state=request.text ) decisions = [] + # The local library is checked before the catalog: a book already saved + # needs no network at all. + library = _library_entries(output_dir) book = None + local_path = None id_match = _ID_RE.search(source or "") if id_match: - try: - book = _get_json(base_url, f"/books/{id_match.group(1)}") - except (urllib.error.URLError, TimeoutError, ValueError): - book = None + hit = _local_by_id(library, id_match.group(1)) + if hit is not None: + book, local_path = _library_book(hit), hit[1] + else: + try: + book = _get_json(base_url, f"/books/{id_match.group(1)}") + except (urllib.error.URLError, TimeoutError, ValueError): + book = None if book is None: query = _search_terms(source) @@ -149,61 +278,103 @@ def act(ctx, request): new_state=request.text, needs_input="Which book should I read?", ) - try: - payload = _get_json(base_url, "/books", {"search": query}) - except (urllib.error.URLError, TimeoutError, ValueError) as exc: - return ActionResult( - action_log=f"could not reach the Gutendex catalog at {base_url}: {exc}", - new_state=request.text, - ) - books = payload.get("results") or [] - if not books: - return ActionResult( - action_log=f"No Project Gutenberg book matched '{query}'.", - new_state=request.text, - needs_input="Which book should I read?", - ) - if len(books) == 1: - book = books[0] + hit = _local_by_query(library, query) + if hit is not None: + book, local_path = _library_book(hit), hit[1] else: - candidates = books[:MAX_CANDIDATES] - decision = DecisionRequest( - state=request.text, - question="Which Project Gutenberg book does the user mean?", - options=[Option(str(b.get("id")), _label(b)) for b in candidates], + try: + payload = _get_json(base_url, "/books", {"search": query}) + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + return ActionResult( + action_log=f"could not reach the Gutendex catalog at {base_url}: {exc}", + new_state=request.text, + ) + books = payload.get("results") or [] + if not books: + return ActionResult( + action_log=f"No Project Gutenberg book matched '{query}'.", + new_state=request.text, + needs_input="Which book should I read?", + ) + if len(books) == 1: + book = books[0] + else: + candidates = books[:MAX_CANDIDATES] + decision = DecisionRequest( + state=request.text, + question="Which Project Gutenberg book does the user mean?", + options=[Option(str(b.get("id")), _label(b)) for b in candidates], + ) + result = ctx.engine.call(decision) + decisions.append((decision, result)) + book = next( + (b for b in candidates if str(b.get("id")) == result.selected), + candidates[0], + ) + + # A book resolved from the catalog may still be saved already (matched by + # id): reuse the local copy instead of downloading it again. + if local_path is None: + hit = _local_by_id(library, book.get("id")) + if hit is not None: + local_path = hit[1] + + if local_path is not None: + path = local_path + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError as exc: + report = ( + f"could not read the saved copy of '{book.get('title', 'Untitled')}': " + f"{exc}" ) - result = ctx.engine.call(decision) - decisions.append((decision, result)) - book = next( - (b for b in candidates if str(b.get("id")) == result.selected), - candidates[0], + return ActionResult( + action_log=report, new_state=request.text, decisions=decisions + ) + from_library = True + else: + text_url = _plain_text_url(book.get("formats")) + if not text_url: + report = ( + f"'{book.get('title', 'Untitled')}' (ID {book.get('id')}) has no " + "plain-text format available to read." + ) + return ActionResult( + action_log=report, new_state=request.text, decisions=decisions ) - text_url = _plain_text_url(book.get("formats")) - if not text_url: + try: + text = _get_text(text_url) + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + report = f"could not download the text of '{book.get('title')}': {exc}" + return ActionResult( + action_log=report, new_state=request.text, decisions=decisions + ) + + os.makedirs(output_dir, exist_ok=True) + path = Path(output_dir) / ( + f"gutenberg-{book.get('id')}-{_slug(book.get('title'))}.txt" + ) + path.write_text(text, encoding="utf-8") + from_library = False + + if _can_read_aloud(ctx, request.origin_source or request.source): + spoken = _read_aloud( + ctx, request, path, text, book, output_dir, from_library=from_library + ) + if spoken is not None: + return ActionResult( + action_log=spoken, new_state=spoken, decisions=decisions + ) + + if from_library: report = ( - f"'{book.get('title', 'Untitled')}' (ID {book.get('id')}) has no " - "plain-text format available to read." + f"Using the saved copy of '{book.get('title', 'Untitled')}' " + f"({len(text):,} characters) already in your library: {path}." ) - return ActionResult( - action_log=report, new_state=request.text, decisions=decisions + else: + report = ( + f"Saved the full text of '{book.get('title', 'Untitled')}' by " + f"{_authors(book)} ({len(text):,} characters) to {path}." ) - - try: - text = _get_text(text_url) - except (urllib.error.URLError, TimeoutError, ValueError) as exc: - report = f"could not download the text of '{book.get('title')}': {exc}" - return ActionResult( - action_log=report, new_state=request.text, decisions=decisions - ) - - os.makedirs(output_dir, exist_ok=True) - path = Path(output_dir) / ( - f"gutenberg-{book.get('id')}-{_slug(book.get('title'))}.txt" - ) - path.write_text(text, encoding="utf-8") - report = ( - f"Saved the full text of '{book.get('title', 'Untitled')}' by " - f"{_authors(book)} ({len(text):,} characters) to {path}." - ) return ActionResult(action_log=report, new_state=report, decisions=decisions) diff --git a/skills/gutendex/read_book/skill.test.py b/skills/gutendex/read_book/skill.test.py index a0a8ef8..dbd4add 100644 --- a/skills/gutendex/read_book/skill.test.py +++ b/skills/gutendex/read_book/skill.test.py @@ -116,6 +116,40 @@ def run(url, output_dir, text, selected="1"): return skill.act(ctx, Request(text)), engine +class FakeSpeech: + """A speech-channel double: records read-aloud requests, speaks nothing.""" + + def __init__(self, stream_sources=("voice", "lxmf")): + self.reads = [] + self.stream_sources = set(stream_sources) + + def supports(self, source): + return str(source or "").split(":", 1)[0] in self.stream_sources + + def read_aloud(self, **kwargs): + self.reads.append(kwargs) + return kwargs + + +def run_voice(url, output_dir, text, source="voice:mic", selected="1"): + engine = FakeEngine(selected) + speech = FakeSpeech() + ctx = ActionContext( + engine=engine, + config={"gutendex_base_url": url, "output_dir": output_dir}, + speech=speech, + ) + request = Request(text, source=source, origin_source=source) + return skill.act(ctx, request), engine, speech + + +def save_library(output_dir, book_id, slug, text): + """Pre-save a book into the local library (as a previous run would).""" + path = Path(output_dir) / f"gutenberg-{book_id}-{slug}.txt" + path.write_text(text, encoding="utf-8") + return path + + def test_reads_a_named_book(): server, url = start_server() output_dir = tempfile.mkdtemp() @@ -248,6 +282,200 @@ def test_download_failure_is_reported_honestly(): shutil.rmtree(output_dir, ignore_errors=True) +def test_voice_reads_aloud_and_records_a_start(): + # Over the voice gateway the saved book is registered for read-aloud, not + # reported as a file path: the front end streams it until the user stops. + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + pride = book(1342, "Pride and Prejudice", "Jane Austen", url) + server.search_results = [pride] + server.by_id["1342"] = pride + action, _engine, speech = run_voice(url, output_dir, "read pride and prejudice") + assert len(speech.reads) == 1, speech.reads + read = speech.reads[0] + assert read["key"] == "gutenberg-1342", read + assert read["start"] == 0, read + assert read["source"] == "voice:mic", read + assert read["path"].endswith(".txt"), read + assert read["bookmarks_path"].endswith("bookmarks.json"), read + assert "Reading" in action.action_log, action.action_log + assert os.listdir(output_dir), "the text must still be saved" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_voice_resumes_from_a_bookmark(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + pride = book(1342, "Pride and Prejudice", "Jane Austen", url) + server.search_results = [pride] + server.by_id["1342"] = pride + bookmarks = os.path.join(output_dir, "bookmarks.json") + with open(bookmarks, "w", encoding="utf-8") as handle: + json.dump({"gutenberg-1342": {"offset": 12}}, handle) + action, _engine, speech = run_voice(url, output_dir, "read pride and prejudice") + assert speech.reads[0]["start"] == 12, speech.reads + assert "Resuming" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_voice_finished_book_starts_over(): + # A bookmark at (or past) the end means the book was finished; a new request + # starts from the beginning rather than replaying the final chunk. + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + pride = book(1342, "Pride and Prejudice", "Jane Austen", url) + server.search_results = [pride] + server.by_id["1342"] = pride + bookmarks = os.path.join(output_dir, "bookmarks.json") + with open(bookmarks, "w", encoding="utf-8") as handle: + json.dump({"gutenberg-1342": {"offset": len(TEXT_BODY)}}, handle) + _action, _engine, speech = run_voice(url, output_dir, "read pride and prejudice") + assert speech.reads[0]["start"] == 0, speech.reads + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_non_voice_source_does_not_read_aloud(): + # A typed (or messenger) request still gets the saved-file summary; only the + # voice gateway reads aloud. + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + pride = book(1342, "Pride and Prejudice", "Jane Austen", url) + server.search_results = [pride] + server.by_id["1342"] = pride + _action, _engine, speech = run_voice( + url, output_dir, "read pride and prejudice", source="typed" + ) + assert speech.reads == [], speech.reads + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_uses_the_local_library_by_name_without_network(): + # A book already saved is read from disk: the catalog is never contacted. + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + saved = save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) + action, _engine = run(url, output_dir, "read pride and prejudice") + assert server.seen == [], f"the catalog must not be contacted: {server.seen}" + assert "library" in action.action_log, action.action_log + assert str(saved) in action.action_log, action.action_log + assert Path(saved).read_text(encoding="utf-8") == TEXT_BODY + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_uses_the_local_library_by_id_without_network(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) + action, _engine = run(url, output_dir, "read gutenberg book 1342") + assert server.seen == [], f"the catalog must not be contacted: {server.seen}" + assert "library" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_ambiguous_local_match_falls_back_to_the_catalog(): + # Two saved books match the name; the human picks through the catalog. + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + save_library(output_dir, 98, "a-tale-of-two-cities", "OLD") + save_library(output_dir, 1400, "tale-of-two-cities-notes", "OLD") + first = book(98, "A Tale of Two Cities", "Charles Dickens", url) + server.search_results = [first] + server.by_id["98"] = first + action, _engine = run(url, output_dir, "read a tale of two cities") + assert any(path.startswith("/books") for path in server.seen), server.seen + assert "A Tale of Two Cities" in action.action_log, action.action_log + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_reuses_a_saved_book_resolved_from_the_catalog(): + # The catalog resolves the id, but the text is already saved: reuse it + # rather than downloading the text again. + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) + # A name that does not match the saved slug forces the catalog lookup. + pride = book(1342, "Pride and Prejudice", "Jane Austen", url) + server.search_results = [pride] + server.by_id["1342"] = pride + action, _engine = run(url, output_dir, "read austen novel") + assert any(path.startswith("/books") for path in server.seen), server.seen + assert not any(path.startswith("/text/") for path in server.seen), server.seen + assert "library" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_voice_reads_from_the_local_library(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + saved = save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) + _action, _engine, speech = run_voice(url, output_dir, "read pride and prejudice") + assert server.seen == [], f"the catalog must not be contacted: {server.seen}" + assert len(speech.reads) == 1, speech.reads + assert speech.reads[0]["path"] == str(saved), speech.reads + assert "library" in _action.action_log, _action.action_log + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_reads_aloud_over_a_voice_messenger_too(): + # The read-aloud path is not voice-gateway-specific: any front end the + # scheduler reports as streamable (here the LXMF voice gateway) gets it. + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) + action, _engine, speech = run_voice( + url, output_dir, "read pride and prejudice", source="lxmf:ab" * 1 + ) + assert len(speech.reads) == 1, speech.reads + assert speech.reads[0]["source"].startswith("lxmf:"), speech.reads + assert "Reading" in action.action_log, action.action_log + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + def main(): test_reads_a_named_book() test_reads_by_gutenberg_id() @@ -256,6 +484,16 @@ def main(): test_missing_plain_text_format_is_reported() test_sends_an_identifying_user_agent() test_download_failure_is_reported_honestly() + test_voice_reads_aloud_and_records_a_start() + test_voice_resumes_from_a_bookmark() + test_voice_finished_book_starts_over() + test_non_voice_source_does_not_read_aloud() + test_uses_the_local_library_by_name_without_network() + test_uses_the_local_library_by_id_without_network() + test_ambiguous_local_match_falls_back_to_the_catalog() + test_reuses_a_saved_book_resolved_from_the_catalog() + test_voice_reads_from_the_local_library() + test_reads_aloud_over_a_voice_messenger_too() print("ok")