gutendex: read a book aloud over a voice front end
read_book now checks the local library 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 re-downloaded. When the request arrives from a front end that can stream a read-aloud (the local voice gateway, or an LXMF/Sideband voice chat), the saved text is handed to the scheduler's speech channel (ctx.speech) instead of being summarised: the gateway streams it through Piper a chunk at a time until the user stops it, and the position is kept in a bookmarks.json beside the saved books so a later request resumes where the listener stopped. A text front end keeps the saved-file summary, and the skill reports honestly when a book has no plain text to read. The skill asks ctx.speech.supports(source) on both the saved-library and the fresh-download paths; the manifest/README describe the read-aloud and the library-first behaviour.
This commit is contained in:
1 parent
52346baf52
commit
530e9968a4
4 files changed
+477
-58
No files matched your search
@@ -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-<id>-<slug>.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)
|
||||
Reference in new issue
Block a user