#!/usr/bin/env python3
"""Generate an llms.txt file for any website, with the Ujeebu Crawl API.
Crawls the site as plain HTML (no JavaScript: the cheapest page), takes each page's title and meta
description (or its first paragraph), groups the pages by their first path segment and writes
llms.txt in the llmstxt.org format: the site name as an H1, a one-line summary, then one
"## Section" list of links per group.
pip install requests
UJEEBU_API_KEY=your-key python3 generate_llms_txt.py
"""
import collections
import os
import time
from html.parser import HTMLParser
from urllib.parse import urlparse
import requests
API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY")
API = "https://api.ujeebu.com"
SITE = "https://ujeebu.com/"
CRAWL = {
"urls": [SITE],
"scope": {"max_depth": 1, "max_pages": 60,
"exclude": ["/signin", "/signup", "/forgot", "/privacy", "/terms"]}, # pages no reader needs
"format": "html",
"page": {"js": False},
}
http = requests.Session()
http.headers["ApiKey"] = API_KEY
def api(method, path, **kwargs):
"""Call the Crawl API. A GET is tried again after a network error or a timeout."""
for attempt in range(1, 4):
try:
response = http.request(method, API + path, timeout=300, **kwargs)
break
except (requests.ConnectionError, requests.Timeout):
if method != "GET" or attempt == 3:
raise
time.sleep(5 * attempt)
if response.status_code >= 400:
raise SystemExit(f"{method} {path}: {response.status_code} {response.text}")
return response.json()
class HeadParser(HTMLParser):
"""The <title>, the <meta> name/property values and the first real paragraph of a page."""
def __init__(self):
super().__init__()
self.title, self.meta, self.paragraph = "", {}, ""
self._in, self._text = None, ""
def handle_starttag(self, tag, attrs):
a = dict(attrs)
if tag == "meta" and (a.get("name") or a.get("property")):
self.meta[(a.get("name") or a.get("property")).lower()] = a.get("content") or ""
elif tag in ("title", "p"):
self._in, self._text = tag, ""
def handle_endtag(self, tag):
if tag == self._in:
text = " ".join(self._text.split())
if tag == "title" and not self.title:
self.title = text
elif tag == "p" and not self.paragraph and len(text) >= 40:
self.paragraph = text
self._in = None
def handle_data(self, data):
if self._in:
self._text += data
def describe(html):
page = HeadParser()
page.feed(html)
summary = page.meta.get("description") or page.meta.get("og:description") or page.paragraph
return page.title, " ".join(summary.split()), page.meta.get("og:site_name", "")
def section(url):
"""The group of a page: its first path segment when it has two or more, else "Pages"."""
parts = urlparse(url).path.strip("/").split("/")
return parts[0].replace("-", " ").capitalize() if len(parts) > 1 else "Pages"
# 1. Price the crawl, cap it at the quote, and wait for it.
quote = api("POST", "/crawl/quote", json=CRAWL)
job = api("POST", "/crawl", json={**CRAWL, "max_credits": quote["credits_ceiling"]})
while not job.get("finished"):
time.sleep(5)
job = api("GET", f"/crawl/{job['job_id']}")
# 2. Read every page with its HTML, 5 at a time (whole HTML pages make large answers).
pages, after = [], 0
while True:
batch = api("GET", f"/crawl/{job['job_id']}/pages", params={"after": after, "limit": 5, "content": "true"})
pages += [p for p in batch["pages"] if p["state"] == "done" and p.get("html")]
if not batch["has_more"]:
break
after = batch["next_after"]
# 3. One line per page, grouped by section, in the llms.txt format.
home_title, home_summary, site_name = describe(pages[0]["html"])
site_name = site_name or urlparse(SITE).netloc
groups = collections.defaultdict(list)
for page in pages[1:]:
title, summary, _ = describe(page["html"])
title = title.rsplit(" | ", 1)[0] or page["url"] # "Pricing | Ujeebu" -> "Pricing"
groups[section(page["url"])].append(f"- [{title}]({page['url']})" + (f": {summary}" if summary else ""))
lines = [f"# {site_name}", "", f"> {home_summary}", ""]
for name in sorted(groups, key=lambda g: (g != "Pages", g)):
lines += [f"## {name}", "", *groups[name], ""]
with open("llms.txt", "w", encoding="utf-8") as f:
f.write("\n".join(lines))
print(f"llms.txt: {len(pages)} pages in {len(groups)} sections; job {job['stop_reason']}, {job['credits_used']} credits")
#!/usr/bin/env node
/**
* Generate an llms.txt file for any website, with the Ujeebu Crawl API.
*
* Crawls the site as plain HTML (no JavaScript: the cheapest page), takes each page's title and meta
* description (or its first paragraph), groups the pages by their first path segment and writes
* llms.txt in the llmstxt.org format: the site name as an H1, a one-line summary, then one
* "## Section" list of links per group.
*
* UJEEBU_API_KEY=your-key node generate-llms-txt.js (Node.js 18 or later, no dependencies)
*/
const fs = require('fs');
const API_KEY = process.env.UJEEBU_API_KEY || 'YOUR_API_KEY';
const API = 'https://api.ujeebu.com';
const SITE = 'https://ujeebu.com/';
const CRAWL = {
urls: [SITE],
scope: { max_depth: 1, max_pages: 60,
exclude: ['/signin', '/signup', '/forgot', '/privacy', '/terms'] }, // pages no reader needs
format: 'html',
page: { js: false },
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** Call the Crawl API. A GET is tried again after a network error or a timeout. */
async function api(method, path, body) {
for (let attempt = 1; ; attempt += 1) {
let response;
try {
response = await fetch(API + path, {
method,
headers: { ApiKey: API_KEY, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(300000),
});
} catch (err) {
if (method !== 'GET' || attempt === 3) throw err;
await sleep(5000 * attempt);
continue;
}
if (!response.ok) throw new Error(`${method} ${path}: ${response.status} ${await response.text()}`);
return response.json();
}
}
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', rsquo: '’', lsquo: '‘',
rdquo: '”', ldquo: '“', hellip: '…', middot: '·', copy: '©', mdash: String.fromCodePoint(0x2014), ndash: String.fromCodePoint(0x2013) };
/** Entities decoded, whitespace collapsed (an attribute value). */
function clean(value) {
return value
.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
.replace(/&([a-z]+);/gi, (m, name) => ENTITIES[name.toLowerCase()] ?? m)
.replace(/\s+/g, ' ').trim();
}
/** The text of an HTML fragment: tags out, then clean(). */
const text = (html) => clean(html.replace(/<[^>]*>/g, ' '));
/** The <title>, the meta description (or the first real paragraph) and og:site_name of a page. */
function describe(html) {
const meta = {};
for (const tag of html.match(/<meta\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi) || []) { // a quoted value may hold a ">"
const attr = (name) => {
const m = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i'));
return m ? clean(m[1] ?? m[2]) : '';
};
const key = (attr('name') || attr('property')).toLowerCase();
if (key) meta[key] = attr('content');
}
const title = text((html.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || '');
const paragraph = [...html.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/gi)].map((m) => text(m[1])).find((t) => t.length >= 40) || '';
return { title, summary: meta.description || meta['og:description'] || paragraph, siteName: meta['og:site_name'] || '' };
}
/** The group of a page: its first path segment when it has two or more, else "Pages". */
function section(url) {
const parts = new URL(url).pathname.replace(/^\/|\/$/g, '').split('/');
if (parts.length < 2) return 'Pages';
const name = parts[0].replace(/-/g, ' ');
return name.charAt(0).toUpperCase() + name.slice(1);
}
async function main() {
// 1. Price the crawl, cap it at the quote, and wait for it.
const quote = await api('POST', '/crawl/quote', CRAWL);
let job = await api('POST', '/crawl', { ...CRAWL, max_credits: quote.credits_ceiling });
while (!job.finished) {
await sleep(5000);
job = await api('GET', `/crawl/${job.job_id}`);
}
// 2. Read every page with its HTML, 5 at a time (whole HTML pages make large answers).
const pages = [];
for (let after = 0; ;) {
const batch = await api('GET', `/crawl/${job.job_id}/pages?after=${after}&limit=5&content=true`);
pages.push(...batch.pages.filter((p) => p.state === 'done' && p.html));
if (!batch.has_more) break;
after = batch.next_after;
}
// 3. One line per page, grouped by section, in the llms.txt format.
const home = describe(pages[0].html);
const siteName = home.siteName || new URL(SITE).host;
const groups = new Map();
for (const page of pages.slice(1)) {
const { title, summary } = describe(page.html);
const name = title.split(' | ').slice(0, -1).join(' | ') || title || page.url; // "Pricing | Ujeebu" -> "Pricing"
const group = section(page.url);
if (!groups.has(group)) groups.set(group, []);
groups.get(group).push(`- [${name}](${page.url})` + (summary ? `: ${summary}` : ''));
}
const names = [...groups.keys()].sort((a, b) => (a !== 'Pages') - (b !== 'Pages') || a.localeCompare(b));
const lines = [`# ${siteName}`, '', `> ${home.summary}`, ''];
for (const name of names) lines.push(`## ${name}`, '', ...groups.get(name), '');
fs.writeFileSync('llms.txt', lines.join('\n'));
console.log(`llms.txt: ${pages.length} pages in ${groups.size} sections; job ${job.stop_reason}, ${job.credits_used} credits`);
}
main().catch((err) => { console.error(err.message); process.exit(1); });