#!/usr/bin/env python3
"""Convert an entire website (here, a docs site) to Markdown for LLMs and RAG, with the Ujeebu Crawl API.
One crawl job reads the docs as Markdown, main content only, capped at the free quote's ceiling.
This script reads the pages as they arrive, skips duplicates, flags oversized pages and writes:
llms-full.txt every page in one Markdown file, with its source URL
docs.jsonl the same pages cut into chunks at their headings, one JSON line each, for embeddings
Stop it at any time: the next run resumes from the saved cursor.
pip install requests
UJEEBU_API_KEY=your-key python3 website_to_markdown.py
"""
import json
import os
import re
import time
import requests
API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY")
API = "https://api.ujeebu.com"
CRAWL = {
"urls": ["https://ujeebu.com/docs"],
"scope": {
"include": ["/docs/**"],
"exclude": [
"/docs/changelog/**", "/docs/*/changelog/**", # release notes: noise for retrieval
"/docs/fr/**", "/docs/de/**", "/docs/es/**", "/docs/ja/**", # translated copies of the same pages
],
"max_pages": 20,
},
"use_sitemap": True,
"format": "markdown",
"markdown": {"filter": "fit"}, # main content only: no menus, footers or cookie banners
}
STATE_FILE = "crawl-state.json" # job id, cursor and hashes written, so a stopped run can resume
MAX_CHARS = 1500 # target chunk size
OVERSIZED = 50_000 # flag pages longer than this for review
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: polling runs for minutes."""
for attempt in range(1, 4):
try:
response = http.request(method, API + path, timeout=120, **kwargs)
break
except requests.ConnectionError:
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()
def chunk(markdown, max_chars=MAX_CHARS):
"""Split Markdown into (section, text) chunks: a new chunk at every heading, and at a blank
line once the chunk has max_chars. Code (fenced blocks and code spans) is never cut in two."""
chunks, trail, lines, in_code = [], [], [], False
def flush():
text = "\n".join(lines).strip()
if text:
chunks.append((" > ".join(trail), text))
lines.clear()
for line in markdown.splitlines():
heading = None if in_code else re.match(r"(#{1,4})\s+(.+)", line)
if heading:
flush()
trail[len(heading.group(1)) - 1:] = [heading.group(2).strip()]
continue
if line.count("`") % 2: # a code block or a code span opens or closes on this line
in_code = not in_code
if not in_code and not line.strip() and sum(len(x) + 1 for x in lines) >= max_chars:
flush()
lines.append(line)
flush()
return chunks
def load_state():
if os.path.exists(STATE_FILE):
with open(STATE_FILE) as f:
return json.load(f)
quote = api("POST", "/crawl/quote", json=CRAWL)
print(f"Quote: {quote['sitemap']['in_scope_urls']} sitemap URLs in scope, {quote['credits_per_page']} "
f"credits a page, at most {quote['credits_ceiling']} credits")
job = api("POST", "/crawl", json={**CRAWL, "max_credits": quote["credits_ceiling"]})
print(f"Started {job['job_id']}")
return {"job_id": job["job_id"], "after": 0, "written": []}
def save_state(state):
with open(STATE_FILE, "w") as f:
json.dump(state, f)
state = load_state()
written = set(state["written"]) # sha256 of the pages already written
pages = chunks = 0
oversized = []
with open("llms-full.txt", "a", encoding="utf-8") as full, open("docs.jsonl", "a", encoding="utf-8") as out:
while True:
batch = api("GET", f"/crawl/{state['job_id']}/pages",
params={"after": state["after"], "limit": 10, "content": "true"})
for page in batch["pages"]: # finished pages only, in a stable order
if page["state"] != "done":
print(f" skipped {page['url']} ({page.get('error_class')})") # duplicate, blocked, ...
continue
if page["sha256"] in written:
print(f" skipped {page['url']} (same content as a page already written)")
continue
markdown = page.get("markdown")
if markdown is None and page.get("content_url"): # pages over 2 MB come as a link
markdown = requests.get(page["content_url"], timeout=120).text
markdown = (markdown or "").strip()
if len(markdown) > OVERSIZED:
oversized.append(page["url"])
print(f" oversized {page['url']} ({len(markdown):,} characters): review it")
full.write(f"Source: {page['url']}\n\n{markdown}\n\n---\n\n")
parts = chunk(markdown)
for n, (section, text) in enumerate(parts):
out.write(json.dumps({
"id": f"{page['url']}#{n}", # stable: an upsert by id makes a replay harmless
"url": page["url"],
"title": page.get("title", ""),
"section": section,
"text": text,
"page_sha256": page["sha256"],
}, ensure_ascii=False) + "\n")
written.add(page["sha256"])
pages += 1
chunks += len(parts)
print(f" {len(parts):>3} chunks {page['url']}")
full.flush()
out.flush()
state["after"] = batch["next_after"]
state["written"] = sorted(written)
save_state(state)
if batch["has_more"]:
continue # more finished pages are ready now
if batch["finished"]:
break # the job is over and every page has been read
time.sleep(5) # everything final so far is read: ask again in a moment
job = api("GET", f"/crawl/{state['job_id']}")
print(f"{pages} pages, {chunks} chunks; {len(oversized)} oversized; job {job['status']} "
f"({job['stop_reason']}), {job['credits_used']} credits")
#!/usr/bin/env node
/**
* Convert an entire website (here, a docs site) to Markdown for LLMs and RAG, with the Ujeebu Crawl API.
*
* One crawl job reads the docs as Markdown, main content only, capped at the free quote's ceiling.
* This script reads the pages as they arrive, skips duplicates, flags oversized pages and writes:
* llms-full.txt every page in one Markdown file, with its source URL
* docs.jsonl the same pages cut into chunks at their headings, one JSON line each, for embeddings
* Stop it at any time: the next run resumes from the saved cursor.
*
* UJEEBU_API_KEY=your-key node website-to-markdown.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 CRAWL = {
urls: ['https://ujeebu.com/docs'],
scope: {
include: ['/docs/**'],
exclude: [
'/docs/changelog/**', '/docs/*/changelog/**', // release notes: noise for retrieval
'/docs/fr/**', '/docs/de/**', '/docs/es/**', '/docs/ja/**', // translated copies of the same pages
],
max_pages: 20,
},
use_sitemap: true,
format: 'markdown',
markdown: { filter: 'fit' }, // main content only: no menus, footers or cookie banners
};
const STATE_FILE = 'crawl-state.json'; // job id, cursor and hashes written, so a stopped run can resume
const MAX_CHARS = 1500; // target chunk size
const OVERSIZED = 50000; // flag pages longer than this for review
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** Call the Crawl API. A GET is tried again after a network error: polling runs for minutes. */
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),
});
} 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();
}
}
/**
* Split Markdown into {section, text} chunks: a new chunk at every heading, and at a blank line
* once the chunk has maxChars. Code (fenced blocks and code spans) is never cut in two.
*/
function chunk(markdown, maxChars = MAX_CHARS) {
const chunks = [];
const trail = [];
let lines = [];
let inCode = false;
const flush = () => {
const text = lines.join('\n').trim();
if (text) chunks.push({ section: trail.join(' > '), text });
lines = [];
};
for (const line of markdown.split('\n')) {
const heading = inCode ? null : line.match(/^(#{1,4})\s+(.+)/);
if (heading) {
flush();
trail.splice(heading[1].length - 1);
trail.push(heading[2].trim());
continue;
}
if ((line.split('`').length - 1) % 2) inCode = !inCode; // a code block or span opens or closes here
const size = lines.reduce((n, l) => n + l.length + 1, 0);
if (!inCode && !line.trim() && size >= maxChars) flush();
lines.push(line);
}
flush();
return chunks;
}
async function loadState() {
if (fs.existsSync(STATE_FILE)) return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
const quote = await api('POST', '/crawl/quote', CRAWL);
console.log(`Quote: ${quote.sitemap.in_scope_urls} sitemap URLs in scope, ${quote.credits_per_page} ` +
`credits a page, at most ${quote.credits_ceiling} credits`);
const job = await api('POST', '/crawl', { ...CRAWL, max_credits: quote.credits_ceiling });
console.log(`Started ${job.job_id}`);
return { job_id: job.job_id, after: 0, written: [] };
}
async function main() {
const state = await loadState();
const written = new Set(state.written); // sha256 of the pages already written
const full = fs.openSync('llms-full.txt', 'a');
const out = fs.openSync('docs.jsonl', 'a');
let pages = 0;
let chunks = 0;
const oversized = [];
for (;;) {
const batch = await api('GET', `/crawl/${state.job_id}/pages?after=${state.after}&limit=10&content=true`);
for (const page of batch.pages) { // finished pages only, in a stable order
if (page.state !== 'done') {
console.log(` skipped ${page.url} (${page.error_class})`); // duplicate, blocked, ...
continue;
}
if (written.has(page.sha256)) {
console.log(` skipped ${page.url} (same content as a page already written)`);
continue;
}
let markdown = page.markdown;
if (markdown == null && page.content_url) { // pages over 2 MB come as a link
markdown = await (await fetch(page.content_url)).text();
}
markdown = (markdown || '').trim();
if (markdown.length > OVERSIZED) {
oversized.push(page.url);
console.log(` oversized ${page.url} (${markdown.length.toLocaleString('en-US')} characters): review it`);
}
fs.writeSync(full, `Source: ${page.url}\n\n${markdown}\n\n---\n\n`);
const parts = chunk(markdown);
parts.forEach(({ section, text }, n) => {
fs.writeSync(out, JSON.stringify({
id: `${page.url}#${n}`, // stable: an upsert by id makes a replay harmless
url: page.url,
title: page.title || '',
section,
text,
page_sha256: page.sha256,
}) + '\n');
});
written.add(page.sha256);
pages += 1;
chunks += parts.length;
console.log(` ${String(parts.length).padStart(3)} chunks ${page.url}`);
}
state.after = batch.next_after;
state.written = [...written].sort();
fs.writeFileSync(STATE_FILE, JSON.stringify(state));
if (batch.has_more) continue; // more finished pages are ready now
if (batch.finished) break; // the job is over and every page has been read
await sleep(5000); // everything final so far is read: ask again in a moment
}
fs.closeSync(full);
fs.closeSync(out);
const job = await api('GET', `/crawl/${state.job_id}`);
console.log(`${pages} pages, ${chunks} chunks; ${oversized.length} oversized; job ${job.status} ` +
`(${job.stop_reason}), ${job.credits_used} credits`);
}
main().catch((err) => { console.error(err.message); process.exit(1); });