gutendex: add Project Gutenberg pack (find books, read full text)
This commit is contained in:
commit
9a41f66fd6
11 files changed
+885
No files matched your search
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"gutendex_base_url": "Base URL of the Gutendex Project Gutenberg API, e.g. https://gutendex.com (no trailing slash needed)."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Find public-domain books in the Project Gutenberg catalog by author, title, or genre, listing the most popular matches."
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
"""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)]
|
||||
)
|
||||
@@ -0,0 +1,188 @@
|
||||
"""Hermetic mechanics test for gutendex.find_books.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the public Gutendex `/books` route and asserts the query the
|
||||
body built. This proves the body reads its base URL from config, extracts search
|
||||
terms, picks the search/topic parameter via a SemIf decision, and reports real
|
||||
failures and empty results honestly. It does NOT prove the live integration —
|
||||
only a real run against Gutendex does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import DecisionResult, Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Test-only stand-in that always selects one declared option."""
|
||||
|
||||
def __init__(self, selected):
|
||||
self.selected = selected
|
||||
self.calls = []
|
||||
|
||||
def call(self, decision):
|
||||
self.calls.append(decision)
|
||||
ids = [option.id for option in decision.options]
|
||||
return DecisionResult(
|
||||
request=decision,
|
||||
option_ids=ids,
|
||||
probabilities=[1.0 if oid == self.selected else 0.0 for oid in ids],
|
||||
)
|
||||
|
||||
|
||||
FIXTURE_BOOKS = [
|
||||
{
|
||||
"id": 98,
|
||||
"title": "A Tale of Two Cities",
|
||||
"authors": [{"name": "Charles Dickens", "birth_year": 1812, "death_year": 1870}],
|
||||
"subjects": ["France -- History -- Revolution, 1789-1799 -- Fiction"],
|
||||
"formats": {"text/plain; charset=utf-8": "https://example.org/98.txt"},
|
||||
},
|
||||
{
|
||||
"id": 1400,
|
||||
"title": "Great Expectations",
|
||||
"authors": [{"name": "Charles Dickens", "birth_year": 1812, "death_year": 1870}],
|
||||
"subjects": ["England -- Fiction"],
|
||||
"formats": {"text/plain; charset=utf-8": "https://example.org/1400.txt"},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def _send(self, payload, status):
|
||||
raw = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def do_GET(self):
|
||||
self.server.seen.append(self.path)
|
||||
if self.server.status != 200:
|
||||
self._send({"detail": "boom"}, self.server.status)
|
||||
return
|
||||
if self.path.startswith("/books"):
|
||||
self._send(
|
||||
{
|
||||
"count": self.server.count,
|
||||
"next": None,
|
||||
"previous": None,
|
||||
"results": self.server.results,
|
||||
},
|
||||
200,
|
||||
)
|
||||
return
|
||||
self._send({"detail": "not found"}, 404)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(status=200, results=None, count=None):
|
||||
handler = type("Handler", (Handler,), {"status": status, "seen": []})
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
server.seen = handler.seen
|
||||
server.status = status
|
||||
server.results = FIXTURE_BOOKS if results is None else results
|
||||
server.count = len(server.results) if count is None else count
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def run(url, text, selected="search"):
|
||||
engine = FakeEngine(selected)
|
||||
ctx = ActionContext(engine=engine, config={"gutendex_base_url": url})
|
||||
return skill.act(ctx, Request(text)), engine
|
||||
|
||||
|
||||
def test_searches_by_author_or_title():
|
||||
server, url = start_server()
|
||||
try:
|
||||
action, engine = run(url, "find books by charles dickens", selected="search")
|
||||
assert len(engine.calls) == 1, "one mode decision"
|
||||
assert any(
|
||||
path.startswith("/books?") and "search=charles+dickens" in path
|
||||
for path in server.seen
|
||||
), server.seen
|
||||
assert "A Tale of Two Cities" in action.action_log, action.action_log
|
||||
assert action.new_state == action.action_log
|
||||
assert action.decisions and action.decisions[0][1].selected == "search"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_searches_by_genre_via_topic():
|
||||
server, url = start_server()
|
||||
try:
|
||||
action, _engine = run(url, "find science fiction books", selected="topic")
|
||||
assert any(
|
||||
path.startswith("/books?") and "topic=science+fiction" in path
|
||||
for path in server.seen
|
||||
), server.seen
|
||||
assert "Found 2" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_empty_result_is_reported_plainly():
|
||||
server, url = start_server(results=[], count=0)
|
||||
try:
|
||||
action, _engine = run(url, "find books by nobody at all")
|
||||
assert "No Project Gutenberg books matched" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_http_failure_is_reported_honestly():
|
||||
server, url = start_server(status=503)
|
||||
try:
|
||||
action, _engine = run(url, "find books by charles dickens")
|
||||
assert "503" in action.action_log, action.action_log
|
||||
assert action.new_state == "find books by charles dickens"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_missing_query_asks_for_one():
|
||||
server, url = start_server()
|
||||
try:
|
||||
action, engine = run(url, "find books")
|
||||
assert action.needs_input, "a nameless request must ask for search terms"
|
||||
assert not engine.calls, "no decision without a query"
|
||||
assert server.seen == [], "no request without a query"
|
||||
print(action.needs_input)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
test_searches_by_author_or_title()
|
||||
test_searches_by_genre_via_topic()
|
||||
test_empty_result_is_reported_plainly()
|
||||
test_http_failure_is_reported_honestly()
|
||||
test_missing_query_asks_for_one()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
Reference in new issue
Block a user