| 1 | # POST an HTML page to /summarize to get its title and links. The summary is |
| 2 | # kept in KV under the page's SHA-256, and GET /summary/<sha256> reads it back. |
| 3 | import hashlib |
| 4 | import json |
| 5 | from urllib.parse import urlparse |
| 6 | |
| 7 | from bs4 import BeautifulSoup |
| 8 | from workers import Response, WorkerEntrypoint |
| 9 | |
| 10 | |
| 11 | def summarize(html): |
| 12 | soup = BeautifulSoup(html, "html.parser") |
| 13 | return { |
| 14 | "title": soup.title.get_text(strip=True) if soup.title else None, |
| 15 | "headings": [h.get_text(strip=True) for h in soup.select("h1, h2")], |
| 16 | "links": [a["href"] for a in soup.select("a[href]")], |
| 17 | } |
| 18 | |
| 19 | |
| 20 | class Default(WorkerEntrypoint): |
| 21 | async def fetch(self, request): |
| 22 | path = urlparse(request.url).path |
| 23 | if request.method == "POST" and path == "/summarize": |
| 24 | html = await request.text() |
| 25 | digest = hashlib.sha256(html.encode()).hexdigest() |
| 26 | summary = summarize(html) |
| 27 | await self.env.PAGES.put(digest, json.dumps(summary)) |
| 28 | return Response.json({"sha256": digest, **summary}) |
| 29 | if request.method == "GET" and path.startswith("/summary/"): |
| 30 | stored = await self.env.PAGES.get(path.removeprefix("/summary/")) |
| 31 | if stored is None: |
| 32 | return Response("not found", status=404) |
| 33 | return Response(stored, headers={"content-type": "application/json"}) |
| 34 | return Response("POST HTML to /summarize\n", status=404) |