llmstxt-corpus / code /crawl.py
jacobezra93's picture
Mirror the Zenodo deposit
708b108 verified
Raw History Blame Contribute Delete
5.82 kB
#!/usr/bin/env python3
"""llms.txt ecosystem audit — phase A: fetch all llms.txt files; phase B: validate links."""
import concurrent.futures as cf
import json, os, random, re, ssl, sys, urllib.request, urllib.error
OUT = "/tmp/llmsaudit"
UA = "Mozilla/5.0 (compatible; SEMPITE-research/1.0; +https://sempite.com/research/)"
CTX = ssl.create_default_context()
CTX.check_hostname = False
CTX.verify_mode = ssl.CERT_NONE
NOTABLE = { # recognizable brands: full link check (cap 400)
"docs.stripe.com","stripe.com","claude.com","docs.anthropic.com","docs.perplexity.ai",
"docs.docker.com","python.langchain.com","ai-sdk.dev","vercel.com","supabase.com",
"docs.cloudflare.com","developers.cloudflare.com","zapier.com","docs.zapier.com",
"mintlify.com","docs.cursor.com","cursor.com","elevenlabs.io","docs.elevenlabs.io",
"resend.com","svelte.dev","nextjs.org","bun.sh","hono.dev","docs.github.com",
"shopify.dev","fly.io","turbo.build","expo.dev","docs.expo.dev","pydantic.dev",
"modelcontextprotocol.io","openrouter.ai","huggingface.co","docs.x.ai","x.ai",
"platform.openai.com","cohere.com","docs.cohere.com","groq.com","console.groq.com",
"mistral.ai","docs.mistral.ai","together.ai","docs.together.ai","replicate.com",
"fireworks.ai","docs.fireworks.ai","deepgram.com","developers.deepgram.com",
"assemblyai.com","www.assemblyai.com","docs.pinecone.io","weaviate.io","qdrant.tech",
"trychroma.com","docs.trychroma.com","neon.tech","planetscale.com","railway.app",
"docs.railway.app","render.com","netlify.com","docs.netlify.com","astro.build",
"tailwindcss.com","daisyui.com","drizzle.team","orm.drizzle.team","prisma.io",
"www.prisma.io","trigger.dev","inngest.com","clerk.com","workos.com","auth0.com",
"plaid.com","twilio.com","www.twilio.com","sendgrid.com","postmarkapp.com",
"linear.app","raycast.com","warp.dev","zed.dev","sourcegraph.com","gitbook.com",
"readme.com","algolia.com","meilisearch.com","typesense.org","posthog.com",
"june.so","amplitude.com","segment.com","rudderstack.com","langfuse.com",
"braintrust.dev","helicone.ai","portkey.ai","litellm.ai","docs.litellm.ai",
}
SAMPLE_N = 15 # long-tail sample per site
NOTABLE_CAP = 400 # notable full-check cap
TIMEOUT = 15
def fetch(url, method="GET", maxbytes=1_500_000):
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "*/*"}, method=method)
redirects = 0
try:
with urllib.request.urlopen(req, timeout=TIMEOUT, context=CTX) as r:
body = r.read(maxbytes) if method == "GET" else b""
final = r.geturl()
redirects = 1 if final.rstrip("/") != url.rstrip("/") else 0
return r.status, redirects, final, body
except urllib.error.HTTPError as e:
return e.code, redirects, url, b""
except Exception:
return 0, 0, url, b"" # network/timeout/dns
def check_link(url):
code, red, final, _ = fetch(url, "HEAD")
if code in (405, 403, 406, 501, 0):
code, red, final, _ = fetch(url, "GET", maxbytes=2048)
return code, red, final
LINK_RE = re.compile(r'\((https?://[^)\s]+)\)|^(?:[-*]\s*)?(https?://\S+)$', re.M)
def phase_a(src):
code, red, final, body = fetch(src)
txt = body.decode("utf-8", "replace")
is_html = txt.lstrip()[:200].lower().find("<html") >= 0 or txt.lstrip().startswith("<!doctype")
links = []
if code == 200 and not is_html:
for m in LINK_RE.finditer(txt):
u = (m.group(1) or m.group(2) or "").rstrip(".,;:")
if u and len(u) < 500:
links.append(u)
seen, ordered = set(), []
for u in links:
if u not in seen:
seen.add(u); ordered.append(u)
return {"src": src, "status": code, "redirected": red, "final": final,
"is_html": is_html, "bytes": len(body), "n_links": len(ordered), "links": ordered}
def main():
urls = [l.strip() for l in open("/tmp/llms-urls-all.txt") if l.strip()]
print(f"Phase A: fetching {len(urls)} llms.txt files", flush=True)
results = []
with cf.ThreadPoolExecutor(64) as ex:
for i, r in enumerate(ex.map(phase_a, urls)):
results.append(r)
if (i+1) % 200 == 0: print(f" {i+1}/{len(urls)}", flush=True)
with open(f"{OUT}/phase_a.jsonl", "w") as f:
for r in results:
f.write(json.dumps({k: v for k, v in r.items() if k != "links"}) + "\n")
rng = random.Random(20260805)
jobs = [] # (site, url, tier)
capped_sites = 0
for r in results:
if r["status"] != 200 or r["is_html"] or not r["n_links"]: continue
host = re.sub(r'^https?://([^/]+).*', r'\1', r["src"]).lower().removeprefix("www.")
notable = host in NOTABLE or re.sub(r'^https?://([^/]+).*', r'\1', r["src"]).lower() in NOTABLE
pool = r["links"]
if notable:
if len(pool) > NOTABLE_CAP: capped_sites += 1
chosen = pool[:NOTABLE_CAP]
tier = "notable"
else:
chosen = pool if len(pool) <= SAMPLE_N else rng.sample(pool, SAMPLE_N)
tier = "sample"
for u in chosen: jobs.append((r["src"], u, tier))
print(f"Phase B: validating {len(jobs)} links ({capped_sites} notable sites capped at {NOTABLE_CAP})", flush=True)
def work(j):
site, url, tier = j
code, red, final = check_link(url)
return f"{site}\t{tier}\t{code}\t{red}\t{url}\t{final}"
with open(f"{OUT}/phase_b.tsv", "w") as f:
with cf.ThreadPoolExecutor(64) as ex:
for i, line in enumerate(ex.map(work, jobs)):
f.write(line + "\n")
if (i+1) % 2000 == 0:
f.flush(); print(f" {i+1}/{len(jobs)}", flush=True)
print("DONE", flush=True)
if __name__ == "__main__":
main()