#!/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")