Spaces:
Running

create-llms-txt / core.py
cyberandy's picture
new release
13fa0ad verified
Raw History Blame Contribute Delete
23.3 kB
"""WordLift llms.txt, OKF starter and graph-seed generation.
Bounded public-site discovery; no inference of undocumented claims. Do not run
this tool on private networks without an additional egress firewall.
"""
from __future__ import annotations
from collections import OrderedDict, defaultdict, deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from io import BytesIO
from pathlib import PurePosixPath
from urllib.parse import urljoin, urlsplit, urlunsplit, unquote
from urllib.robotparser import RobotFileParser
import ipaddress
import json
import re
import socket
import time
import zipfile
import requests
import yaml
from bs4 import BeautifulSoup
from defusedxml import ElementTree as ET
USER_AGENT = "WordLift-llms-generator/2.0 (+https://wordlift.io/generate-llms-txt/)"
MAX_BODY_BYTES = 1_500_000
MAX_SITEMAP_URLS = 250
MAX_PAGES = 30
MAX_REDIRECTS = 3
MAX_SITEMAPS = 6
EXCLUDE_PATH = re.compile(r"/(wp-admin|wp-login|cart|checkout|account|search|tag|feed)(/|$)", re.I)
EXCLUDE_SUFFIX = re.compile(r"\.(?:jpg|jpeg|png|gif|svg|webp|ico|woff2?|ttf|css|js|mp4|mov|zip|gz|xml|json|pdf|rss|atom)(?:$|\?)", re.I)
class SiteError(ValueError):
"""Invalid input, blocked URL or inaccessible content."""
@dataclass
class Page:
url: str
title: str
description: str = ""
summary: str = ""
links: list[str] = field(default_factory=list)
navigation_links: list[str] = field(default_factory=list)
def compact(s: str, limit: int = 180) -> str:
s = re.sub(r"\s+", " ", str(s or "")).strip()
return s[:limit].rstrip(" ,;:")
def md_escape(s: str) -> str:
"""Prevent untrusted page text from injecting headings or links."""
return re.sub(r"([\\\[\]()*_`])", r"\\\1", compact(s, 240)).replace("<", "&lt;").replace(">", "&gt;")
def normalize_url(value: str) -> str:
value = str(value or "").strip()
if not value:
raise SiteError("Please enter a public website URL.")
if not re.match(r"^https?://", value, re.I):
value = "https://" + value
parsed = urlsplit(value)
if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password:
raise SiteError("Use a public http(s) URL without credentials.")
if parsed.port and parsed.port not in {80, 443}:
raise SiteError("Only standard HTTP/HTTPS ports are supported.")
host = parsed.hostname.lower().rstrip(".")
if host == "localhost" or "." not in host or host.endswith((".local", ".internal", ".test", ".localhost")):
raise SiteError("Use a public domain, not a local or internal hostname.")
try:
ipaddress.ip_address(host)
raise SiteError("IP-address URLs aren't supported; use a public domain.")
except ValueError as e:
if isinstance(e, SiteError):
raise
path = parsed.path or "/"
if path.startswith("//"):
raise SiteError("Invalid website path.")
return urlunsplit((parsed.scheme, parsed.netloc.lower(), path, "", ""))
def host_alias(host: str) -> str:
return host[4:] if host.startswith("www.") else host
def allowed_site_url(url: str, base_url: str) -> bool:
try:
u, b = urlsplit(normalize_url(url)), urlsplit(normalize_url(base_url))
if host_alias(u.hostname) != host_alias(b.hostname):
return False
if EXCLUDE_PATH.search(u.path) or EXCLUDE_SUFFIX.search(u.path):
return False
return True
except (ValueError, TypeError):
return False
def public_dns_check(host: str) -> None:
"""Best-effort SSRF guard; production deployment should also block egress to private IPs."""
try:
infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
except OSError as exc:
raise SiteError("Cannot resolve that domain name.") from exc
if not infos:
raise SiteError("Domain has no DNS addresses.")
for item in infos:
try:
address = ipaddress.ip_address(item[4][0])
except ValueError:
raise SiteError("Unexpected DNS response.")
if not address.is_global:
raise SiteError("Private or reserved destination addresses are not supported.")
def fetch_text(url: str, base_url: str, *, allow_non_html: bool = False) -> tuple[str, str, int]:
"""Fetch small same-site public text/HTML/XML with manual redirect validation."""
current = normalize_url(url)
for _ in range(MAX_REDIRECTS + 1):
if not allowed_site_url(current, base_url) and not (
allow_non_html and host_alias(urlsplit(current).hostname or "") == host_alias(urlsplit(base_url).hostname or "")
):
raise SiteError("Cross-site, private or unsupported URL blocked.")
public_dns_check(urlsplit(current).hostname)
try:
response = requests.get(current, headers={"User-Agent": USER_AGENT, "Accept": "text/html,application/xml,text/xml,text/plain"},
timeout=(4, 9), allow_redirects=False, stream=True)
except requests.RequestException as exc:
raise SiteError("The website could not be reached.") from exc
try:
status = response.status_code
if status in {301, 302, 303, 307, 308}:
location = response.headers.get("Location", "")
if not location:
raise SiteError("Redirect response has no destination.")
current = normalize_url(urljoin(current, location))
continue
if status == 404:
return "", current, 404
if status >= 400:
raise SiteError(f"Website returned HTTP {status}.")
ctype = response.headers.get("Content-Type", "").split(";", 1)[0].lower()
if ctype and not (ctype.startswith("text/") or ctype in {"application/xml", "application/xhtml+xml", "application/rss+xml", "application/octet-stream"}):
raise SiteError("Unsupported content type from website.")
chunks: list[bytes] = []
total = 0
for chunk in response.iter_content(chunk_size=32768):
total += len(chunk)
if total > MAX_BODY_BYTES:
raise SiteError("Remote file exceeds the download limit.")
chunks.append(chunk)
return b"".join(chunks).decode(response.encoding or "utf-8", errors="replace"), current, status
finally:
response.close()
raise SiteError("Website redirected too many times.")
def parse_sitemap(xml: str) -> tuple[list[str], list[str]]:
"""Return (sub-sitemaps, page URLs); tolerate XML namespace variants."""
if not xml or len(xml) > MAX_BODY_BYTES:
return [], []
try:
root = ET.fromstring(xml)
except ET.ParseError:
return [], []
name = root.tag.split("}")[-1].lower()
locs = [compact(n.text or "", 400) for n in root.iter() if n.tag.split("}")[-1] == "loc"]
return (locs[:MAX_SITEMAP_URLS], []) if name == "sitemapindex" else ([], locs[:MAX_SITEMAP_URLS])
def extract_page(html: str, url: str) -> Page | None:
soup = BeautifulSoup(html, "html.parser")
robots = soup.find("meta", attrs={"name": re.compile("^robots$", re.I)})
if robots and "noindex" in str(robots.get("content", "")).lower():
return None
title_tag = soup.find("title")
title = compact(title_tag.get_text(" ") if title_tag else "", 100)
h1 = soup.find("h1")
if not title:
title = compact(h1.get_text(" ") if h1 else "", 100)
if not title:
title = compact(urlsplit(url).path.strip("/").replace("-", " ") or urlsplit(url).hostname, 100)
title = re.split(r"\s+[|–—]\s+", title)[0].strip() or title
desc_tag = soup.find("meta", attrs={"name": re.compile("^description$", re.I)})
description = compact(desc_tag.get("content", "") if desc_tag else "", 200)
links = []
seen = set()
for a in soup.find_all("a", href=True):
link = normalize_internal_link(a["href"], url)
if link and link not in seen:
seen.add(link)
links.append(link)
nav_links = []
seen_nav = set()
for container in soup.find_all(["nav", "header", "footer"]):
for a in container.find_all("a", href=True):
link = normalize_internal_link(a["href"], url)
if link and link not in seen_nav:
seen_nav.add(link)
nav_links.append(link)
main = soup.find("main") or soup.find("article") or soup.body or soup
for tag in main.find_all(["script", "style", "nav", "footer", "header", "noscript", "form"]):
tag.decompose()
paras = [compact(p.get_text(" "), 230) for p in main.find_all("p")]
paras = [p for p in paras if len(p) > 45]
summary = compact(" ".join(paras[:2]), 500)
if not description:
description = compact(summary, 175)
return Page(url=url, title=title, description=description, summary=summary, links=links, navigation_links=nav_links)
def normalize_internal_link(href: str, origin: str) -> str | None:
if not href or href.startswith(("#", "mailto:", "tel:", "javascript:", "data:")):
return None
full = urljoin(origin, href)
try:
return normalize_url(full) if allowed_site_url(full, origin) else None
except SiteError:
return None
def section_for(page: Page, home: str) -> str:
path = unquote(urlsplit(page.url).path).lower().strip("/")
if page.url.rstrip("/") == home.rstrip("/") or not path:
return "Main"
if re.search(r"(^|/)(docs?|developers?|api|reference|guides?|tutorials?|academy)(/|$)", path):
return "Documentation"
if re.search(r"(^|/)(products?|solutions?|services?|platform|features?|pricing)(/|$)", path):
return "Products & services"
if re.search(r"(^|/)(blog|news|insights|articles|resources|case-stud(?:y|ies))(/|$)", path):
return "Articles & resources"
if re.search(r"(^|/)(contact|about|company|team|press|legal|privacy|terms)(/|$)", path):
return "About & policies"
return "Other pages"
ORDER = ["Main", "Products & services", "Documentation", "Articles & resources", "About & policies", "Other pages"]
def rank_url(url: str, home: str, *, is_nav: bool = False) -> int:
path = urlsplit(url).path.lower().strip("/")
score = 10 if url.rstrip("/") == home.rstrip("/") else 0
score += 6 if is_nav else 0
score += 5 if re.search(r"(^|/)(about|products?|services?|docs?|platform|pricing|solutions?|contact)(/|$)", path) else 0
score -= 4 if re.search(r"(^|/)(blog|news|tags?|categories|author)(/|$)", path) else 0
score -= 4 if re.search(r"/20\d{2}/(?:0?[1-9]|1[0-2])", path) else 0
score -= 2 * max(0, path.count("/") - 1)
return score
def discover_site(raw_url: str, *, max_pages: int = 16, mode: str = "Recommended") -> tuple[str, list[Page], list[str]]:
home = normalize_url(raw_url)
started_at = time.monotonic()
count = max(2, min(int(max_pages), MAX_PAGES))
warnings: list[str] = []
html, actual, _ = fetch_text(home, home)
if not html:
raise SiteError("Homepage returned no HTML.")
home = actual
root = extract_page(html, home)
if root is None:
raise SiteError("Homepage declares noindex; can't build a public index.")
robots_url = urlunsplit((urlsplit(home).scheme, urlsplit(home).netloc, "/robots.txt", "", ""))
rp = RobotFileParser()
try:
robots_text, _, status = fetch_text(robots_url, home, allow_non_html=True)
if status == 200:
rp.parse(robots_text.splitlines())
elif status == 404:
rp.allow_all = True
except SiteError:
rp.allow_all = True
warnings.append("Robots rules unavailable; check permission before publishing.")
def can_fetch(url: str) -> bool:
return allowed_site_url(url, home) and rp.can_fetch(USER_AGENT, url)
if not can_fetch(home):
raise SiteError("robots.txt disallows crawling this URL.")
nav_links = [link for link in root.navigation_links if can_fetch(link)]
candidates = OrderedDict([(home, None)])
for link in nav_links if mode == "Homepage navigation" else root.links:
if can_fetch(link):
candidates.setdefault(link, None)
if mode != "Homepage navigation":
sitemap_roots = [urljoin(home, "/sitemap.xml"), urljoin(home, "/sitemap_index.xml"), urljoin(home, "/wp-sitemap.xml")]
for match in re.findall(r"(?im)^\s*Sitemap:\s*(\S+)", (robots_text if 'robots_text' in locals() else "")):
if allowed_site_url(match, home):
sitemap_roots.append(match)
pending = deque(dict.fromkeys(sitemap_roots))
visited: set[str] = set()
while pending and len(visited) < MAX_SITEMAPS and len(candidates) < MAX_SITEMAP_URLS and time.monotonic() - started_at < 45:
sitemap_url = pending.popleft()
if sitemap_url in visited:
continue
visited.add(sitemap_url)
try:
sm_body, _, status = fetch_text(sitemap_url, home, allow_non_html=True)
if status == 404:
continue
more, pages = parse_sitemap(sm_body)
for sub in more[:MAX_SITEMAPS]:
if allowed_site_url(sub, home):
pending.append(sub)
for page in pages:
if can_fetch(page):
candidates.setdefault(normalize_url(page), None)
except SiteError:
continue
if mode == "All discovered":
ordered = list(candidates)
else:
ordered = sorted(candidates, key=lambda link: (-rank_url(link, home, is_nav=link in nav_links), link))
pages = [root]
seen = {home.rstrip("/")}
attempted = 0
for url in ordered:
if len(pages) >= count or time.monotonic() - started_at > 50:
break
if url.rstrip("/") in seen or not can_fetch(url):
continue
attempted += 1
try:
page_html, final_url, status = fetch_text(url, home)
if status == 404 or not can_fetch(final_url):
continue
page = extract_page(page_html, final_url)
if page is None or final_url.rstrip("/") in seen:
continue
pages.append(page)
seen.add(final_url.rstrip("/"))
except SiteError:
continue
if time.monotonic() - started_at > 45:
warnings.append("Crawl time limit reached; some candidate pages were not inspected.")
if len(pages) == 1:
warnings.append("Only the homepage could be fetched. Consider checking the sitemap or robots.txt.")
if len(candidates) > count:
warnings.append(f"Sampled {len(pages)} public pages from {len(candidates)} discovered URLs; review before publishing.")
return home, pages, warnings
def build_llms_txt(home: str, pages: list[Page]) -> str:
if not pages:
raise SiteError("No pages were available.")
root = pages[0]
title = md_escape(root.title)
description = md_escape(root.description or root.summary)
lines = [f"# {title}", ""]
if description:
lines += [f"> {description}", ""]
groups = defaultdict(list)
for page in pages:
groups[section_for(page, home)].append(page)
for section in ORDER:
if section not in groups:
continue
lines += [f"## {section}", ""]
for page in groups[section]:
name = md_escape(page.title)
note = md_escape(page.description)
lines.append(f"- [{name}]({page.url})" + (f": {note}" if note else ""))
lines.append("")
return "\n".join(lines).strip() + "\n"
def validate_llms_txt(text: str) -> tuple[str, list[str]]:
errors = []
warnings = []
lines = (text or "").splitlines()
nonempty = [i for i, line in enumerate(lines) if line.strip()]
if not nonempty:
return "Needs fixes", ["Add at least one '# Site name' heading."]
first = lines[nonempty[0]].lstrip("\ufeff").strip()
if not first.startswith("# ") or first.startswith("## "):
errors.append("The first nonempty line should be an H1: '# Site name'.")
h1s = [line for line in lines if re.match(r"^# (?!#)", line)]
if len(h1s) != 1:
errors.append("The llms.txt proposal expects exactly one H1.")
if any(re.match(r"^###\s", line) for line in lines):
warnings.append("File-list sections should use H2 headings rather than an H3 per URL.")
links = re.findall(r"(?m)^\s*-\s*\[([^\]]+)\]\((https?://[^)]+)\)", text or "")
if not links:
warnings.append("No Markdown link-list entries were found (format: '- [Title](https://...)').")
if not any(line.startswith("## ") for line in lines):
warnings.append("Consider grouping your links into H2 sections.")
if len((text or "").encode("utf-8")) > 200_000:
warnings.append("This is a large index. Consider a shorter curated set of pages.")
return ("Needs fixes" if errors else "Valid structure"), errors + warnings + [f"Detected {len(links)} listed links."]
def make_graph_seed(home: str, pages: list[Page], mentions: dict[str, list[dict]] | None = None) -> dict:
"""Grounded WebSite/WebPage graph; only external identities actually resolved are included."""
mentions = mentions or {}
graph: list[dict] = [{"@id": home.rstrip("/") + "/#website", "@type": "WebSite", "url": home, "name": pages[0].title}]
seen_ids: set[str] = set()
for page in pages:
node: dict = {"@id": page.url + "#webpage", "@type": "WebPage", "name": page.title,
"url": page.url, "isPartOf": {"@id": home.rstrip("/") + "/#website"}}
if page.description:
node["description"] = page.description
resolved = []
for m in mentions.get(page.url, []):
if m.get("status") != "resolved":
continue
ent = m.get("entity") or {}
entity_id = ent.get("id", "")
if not isinstance(entity_id, str) or not re.fullmatch(r"Q[1-9]\d*", entity_id):
continue
wikidata = f"https://www.wikidata.org/wiki/{entity_id}"
resolved.append({"@id": wikidata})
if wikidata not in seen_ids:
seen_ids.add(wikidata)
graph.append({"@id": wikidata, "@type": "Thing", "name": compact(ent.get("label", ""), 100) or entity_id})
if resolved:
node["mentions"] = resolved
graph.append(node)
return {"@context": "https://schema.org", "@graph": graph}
def make_okf_bundle(home: str, pages: list[Page], mentions: dict | None = None, at: datetime | None = None) -> bytes:
"""OKF v0.2 starter with source provenance. All concepts are marked draft."""
if not pages:
raise SiteError("No pages available for bundle.")
at = at or datetime.now(timezone.utc)
timestamp = at.isoformat(timespec="seconds").replace("+00:00", "Z")
files: list[tuple[str, str]] = []
groups = defaultdict(list)
used: set[str] = set()
for i, page in enumerate(pages):
slug = re.sub(r"[^a-z0-9-]+", "-", unquote(urlsplit(page.url).path.lower()).strip("/").replace("/", "-"))
slug = slug.strip("-")[:80] or "home"
while slug in used:
slug += f"-{i}"
used.add(slug)
filename = f"pages/{slug}.md"
data: dict = {"type": "Web Page", "title": page.title, "resource": page.url,
"status": "draft", "generated": {"by": "wordlift-llms-generator/2.0", "at": timestamp},
"sources": [{"id": "source-page", "resource": page.url, "title": page.title}]}
if page.description:
data["description"] = page.description
body = f"# {page.title}\n\n"
if page.summary:
body += page.summary + "[^source-page]\n\n"
body += "[^source-page]: Public webpage captured during generation.\n\n"
else:
body += "Review this page's source before adding a knowledge summary.\n\n"
body += f"Source: [{page.url}]({page.url})\n"
yaml_txt = yaml.safe_dump(data, allow_unicode=True, sort_keys=False, default_flow_style=False)
files.append((filename, "---\n" + yaml_txt + "---\n\n" + body))
groups[section_for(page, home)].append((page, filename))
index = '---\nokf_version: "0.2"\n---\n\n# Site knowledge (draft)\n\n'
index += "Auto-extracted source pages. Concepts are drafts until reviewed.\n\n"
for section in ORDER:
if section not in groups:
continue
index += f"## {section}\n\n"
for page, filename in groups[section]:
index += f"- [{md_escape(page.title)}]({filename}): {md_escape(page.description)}\n"
index += "\n"
graph = make_graph_seed(home, pages, mentions)
with BytesIO() as b:
with zipfile.ZipFile(b, "w", zipfile.ZIP_DEFLATED) as z:
z.writestr("index.md", index)
for filename, data in files:
z.writestr(filename, data)
z.writestr("graph-seed.jsonld", json.dumps(graph, ensure_ascii=False, indent=2))
z.writestr("EXPORT-NOTES.txt", "OKF v0.2 starter bundle with WordLift graph-seed.jsonld extension.\n"
"Every concept is DRAFT and unverified. Pages are authoritative only for their own published content.\n"
"Graph contains WebSite/WebPage nodes and only externally resolved Wikidata mentions when configured.\n"
"Review titles, source links, summaries and entities before Knowledge Graph ingestion.\n"
"Specification: https://github.com/GoogleCloudPlatform/open-knowledge-format/blob/main/SPEC.md\n")
return b.getvalue()
def resolve_page_mentions(pages: list[Page], *, key: str, account_id: str) -> tuple[dict[str, list[dict]], str]:
"""Opt-in, server-side calls to WordLift. Never send credentials to the browser."""
if not key or not re.fullmatch(r"[A-Za-z0-9_-]{2,100}", account_id or ""):
return {}, "Entity grounding skipped: configure WL_KEY and WL_ACCOUNT_ID in Space Secrets."
output: dict[str, list[dict]] = {}
errors = 0
for page in pages[:5]: # cap API budget; site owner can review and opt in
text = compact(" ".join([page.title, page.description, page.summary]), 500)
if not text:
continue
try:
response = requests.post(
f"https://api.wordlift.io/accounts/{account_id}/resolve",
headers={"Authorization": f"Key {key}", "Content-Type": "application/json"},
json={"text": text, "language": "en"}, timeout=(5, 15),
)
response.raise_for_status()
data = response.json()
if isinstance(data, dict) and isinstance(data.get("mentions"), list):
output[page.url] = data["mentions"]
except (requests.RequestException, ValueError):
errors += 1
return output, (f"Entity grounding checked {len(output)} page(s)" + (f"; {errors} API error(s)" if errors else "") + ".")