"""Find public-domain books in the Project Gutenberg catalog (Gutendex). Real integration: the free public Gutendex JSON API over HTTP (`gutendex_base_url`); no account, credential, or bridge is involved. The request's search terms are taken from the user's query and the catalog is searched by author/title (`search`) or by genre/subject (`topic`) — which one is a SemIf decision over the real query. A real HTTP failure is reported honestly; book data is never invented. """ from __future__ import annotations import json import re import urllib.error import urllib.parse import urllib.request from semif_agent.decisions import DecisionRequest, Option from semif_agent.skills import ActionResult INTEGRATION = { "service": "gutendex", "transport": "http", "config_vars": ["gutendex_base_url"], } CONTRACT = { "gutendex_base_url": "Base URL of the Gutendex Project Gutenberg API, e.g. https://gutendex.com (no trailing slash needed).", } TIMEOUT_SECONDS = 20 MAX_RESULTS = 5 RESULT_CHARS = 300 MAX_QUERY_CHARS = 80 MODE_OPTIONS = [ Option( "search", "A specific author's name or a specific book title the user named, " "e.g. 'Charles Dickens' or 'Moby Dick'.", ), Option( "topic", "A genre, subject, or theme to browse rather than a specific author or " "title, e.g. 'science fiction', 'detective stories', or 'children'.", ), ] # Leading words that are command/plumbing rather than search terms; the query is # the request with these stripped from the front (see `_search_terms`). This is # deliberately mechanical: there is no candidate set to resolve against, and # stripping a known command vocabulary is deterministic and testable. _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 _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"}) with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: return json.loads(response.read().decode("utf-8")) def _format_results(query, books, total): lines = [f"Found {total} Project Gutenberg book(s) for '{query}':"] shown = 0 for book in books: line = ( f"• {book.get('title', 'Untitled')} — {_authors(book)} " f"(ID {book.get('id')})" ) if shown and sum(len(item) + 1 for item in lines) + len(line) > RESULT_CHARS: break lines.append(line) shown += 1 if shown >= MAX_RESULTS: break if total > shown: lines.append(f"… and {total - shown} more.") return "\n".join(lines) def act(ctx, request): query = _search_terms(request.text) if not query: return ActionResult( action_log="the request did not name an author, title, or genre", new_state=request.text, needs_input="What author, title, or genre should I look for?", ) base_url = str(ctx.config["gutendex_base_url"]).strip().rstrip("/") decision = DecisionRequest( state=request.text, question=( "Is the user looking for a specific author or book title by name, " "or browsing a genre, subject, or theme?" ), options=MODE_OPTIONS, ) result = ctx.engine.call(decision) params = {"search": query} if result.selected != "topic" else {"topic": query} try: payload = _get_json(base_url, "/books", params) 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, decisions=[(decision, result)], ) books = payload.get("results") or [] if not books: report = f"No Project Gutenberg books matched '{query}'." return ActionResult( action_log=report, new_state=report, decisions=[(decision, result)] ) total = payload.get("count") or len(books) report = _format_results(query, books, total) return ActionResult( action_log=report, new_state=report, decisions=[(decision, result)] )