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.
381 lines
14 KiB
Python
381 lines
14 KiB
Python
"""Download the full text of a Project Gutenberg book (Gutendex).
|
|
|
|
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.
|
|
|
|
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`.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import urllib.error
|
|
import urllib.parse
|
|
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 = {
|
|
"service": "gutendex",
|
|
"transport": "http",
|
|
"config_vars": ["gutendex_base_url", "output_dir"],
|
|
}
|
|
|
|
CONTRACT = {
|
|
"gutendex_base_url": "Base URL of the Gutendex Project Gutenberg API, e.g. https://gutendex.com (no trailing slash needed).",
|
|
"output_dir": "Directory where the downloaded book's full text is saved as a .txt file, e.g. /home/me/books.",
|
|
}
|
|
|
|
# Gutendex's Cloudflare front blocks the default `Python-urllib/<ver>` agent
|
|
# with HTTP 403; a plain, identifying agent is accepted.
|
|
USER_AGENT = "semif-agent/1.0"
|
|
|
|
TIMEOUT_SECONDS = 60
|
|
MAX_CANDIDATES = 8
|
|
MAX_QUERY_CHARS = 80
|
|
|
|
# An explicit "book 1342" / "gutenberg #1342" names a Project Gutenberg id
|
|
# directly; a bare number is not treated as an id so a title like "1984" still
|
|
# searches by name.
|
|
_ID_RE = re.compile(
|
|
r"(?:gutenberg|book|ebook|e-book|id|number|no\.?)\s*#?\s*(\d{1,7})",
|
|
re.IGNORECASE,
|
|
)
|
|
_LEAD_STOPWORDS = {
|
|
"please", "pls", "hey", "can", "could", "would", "you", "i", "id", "i'd",
|
|
"want", "wanna", "like", "to", "help", "me", "find", "search", "look",
|
|
"show", "get", "list", "read", "fetch", "browse", "download", "pull", "up",
|
|
"recommend", "give", "some", "any", "a", "an", "the", "book", "books",
|
|
"work", "works", "novel", "novels", "title", "titles", "ebook", "ebooks",
|
|
"e-book", "e-books", "text", "texts", "full", "entire", "whole", "complete",
|
|
"by", "from", "about", "on", "in", "of", "written", "authored", "titled",
|
|
"called", "named", "for", "with", "regarding", "re",
|
|
}
|
|
_TRAILING_NOUNS = {
|
|
"book", "books", "work", "works", "novel", "novels", "title", "titles",
|
|
"text", "texts", "ebook", "ebooks",
|
|
}
|
|
|
|
|
|
def _search_terms(text):
|
|
"""The catalog search terms in a request, with command words stripped."""
|
|
words = re.findall(r"[A-Za-z0-9']+", (text or "").lower())
|
|
start = 0
|
|
while start < len(words) and words[start] in _LEAD_STOPWORDS:
|
|
start += 1
|
|
terms = words[start:]
|
|
while terms and terms[-1] in _TRAILING_NOUNS:
|
|
terms.pop()
|
|
return " ".join(terms)[:MAX_QUERY_CHARS]
|
|
|
|
|
|
def _authors(book):
|
|
names = [a.get("name") for a in (book.get("authors") or []) if a.get("name")]
|
|
return ", ".join(names) if names else "unknown author"
|
|
|
|
|
|
def _label(book):
|
|
return f"{book.get('title', 'Untitled')} — {_authors(book)} (ID {book.get('id')})"
|
|
|
|
|
|
def _plain_text_url(formats):
|
|
"""The best plain-text download URL from a book's formats map, or None."""
|
|
fallback = None
|
|
for mime, url in (formats or {}).items():
|
|
if mime.split(";")[0].strip().lower() != "text/plain":
|
|
continue
|
|
if "utf-8" in mime.lower():
|
|
return url
|
|
fallback = fallback or url
|
|
return fallback
|
|
|
|
|
|
def _slug(text):
|
|
slug = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")
|
|
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:
|
|
url += "?" + urllib.parse.urlencode(params)
|
|
http_request = urllib.request.Request(
|
|
url, headers={"Accept": "application/json", "User-Agent": USER_AGENT}
|
|
)
|
|
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
|
return json.loads(response.read().decode("utf-8"))
|
|
|
|
|
|
def _get_text(url):
|
|
http_request = urllib.request.Request(
|
|
url, headers={"Accept": "text/plain", "User-Agent": USER_AGENT}
|
|
)
|
|
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
|
return response.read().decode("utf-8", "replace")
|
|
|
|
|
|
def act(ctx, request):
|
|
source = request.user_input if request.user_input else request.text
|
|
base_url = str(ctx.config["gutendex_base_url"]).strip().rstrip("/")
|
|
output_dir = str(ctx.config["output_dir"]).strip()
|
|
if not output_dir:
|
|
return ActionResult(
|
|
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:
|
|
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)
|
|
if not query:
|
|
return ActionResult(
|
|
action_log="the request did not name a book",
|
|
new_state=request.text,
|
|
needs_input="Which book should I read?",
|
|
)
|
|
hit = _local_by_query(library, query)
|
|
if hit is not None:
|
|
book, local_path = _library_book(hit), hit[1]
|
|
else:
|
|
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}"
|
|
)
|
|
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
|
|
)
|
|
|
|
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"Using the saved copy of '{book.get('title', 'Untitled')}' "
|
|
f"({len(text):,} characters) already in your library: {path}."
|
|
)
|
|
else:
|
|
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)
|