"""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. 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.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/` 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" 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 = [] book = 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 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?", ) 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], ) 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") 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)