"""Fetch LessWrong posts via GraphQL. Two-step approach: 1. Resolve tag IDs for the names we care about. 2. Fetch posts by tagId using filterSettings. Writes: data/lesswrong_posts.jsonl """ import json import os import re import sys import time from pathlib import Path import requests PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, PROJECT_DIR) from config import LW_TAGS, START_DATE API = "https://www.lesswrong.com/graphql" OUT = Path(PROJECT_DIR) / "data" / "lesswrong_posts.jsonl" MIN_WORDS = 200 def strip_html(html): text = re.sub(r"<[^>]+>", " ", html or "") text = re.sub(r" ", " ", text) text = re.sub(r"&", "&", text) text = re.sub(r"<", "<", text) text = re.sub(r">", ">", text) text = re.sub(r""", '"', text) text = re.sub(r"'", "'", text) text = re.sub(r"\s+", " ", text) return text.strip() def gql(query, variables=None): r = requests.post(API, json={"query": query, "variables": variables or {}}, timeout=60) r.raise_for_status() j = r.json() if "errors" in j: raise RuntimeError(f"GraphQL errors: {j['errors']}") return j["data"] def resolve_tag_ids(names): """Walk the alphabetical tag list and pick out the ones matching names.""" print("Resolving tag IDs...", flush=True) name_set = {n.lower().strip() for n in names} found = {} offset = 0 while offset < 10000 and len(found) < len(name_set): data = gql(""" query GetTags($limit: Int, $offset: Int) { tags(input: {terms: {view: "allTagsAlphabetical", limit: $limit, offset: $offset}}) { results { _id name slug } } } """, {"limit": 500, "offset": offset}) results = data.get("tags", {}).get("results", []) if not results: break for t in results: if t["name"].lower().strip() in name_set: found[t["name"]] = t["_id"] print(f" found {t['name']} -> {t['_id']}", flush=True) offset += len(results) time.sleep(0.3) missing = name_set - {n.lower().strip() for n in found.keys()} if missing: print(f" MISSING: {missing}", flush=True) return found def fetch_posts_for_tag(tag_id, tag_name, max_posts=5000, batch=200): """Fetch posts requiring a given tag, paginated by offset.""" all_posts = [] offset = 0 while offset < max_posts: data = gql(""" query GetPosts($tagId: String!, $limit: Int, $offset: Int) { posts(input: {terms: { view: "new", filterSettings: {tags: [{tagId: $tagId, filterMode: "Required"}]}, limit: $limit, offset: $offset, after: "%s" }}) { results { _id title slug postedAt baseScore author wordCount contents { html } tags { name } user { displayName } } } } """ % START_DATE, {"tagId": tag_id, "limit": batch, "offset": offset}) results = data.get("posts", {}).get("results", []) if not results: break all_posts.extend(results) print(f" '{tag_name}': {len(all_posts)} fetched (offset {offset})", flush=True) if len(results) < batch: break offset += batch time.sleep(0.4) return all_posts def main(): OUT.parent.mkdir(parents=True, exist_ok=True) tag_ids = resolve_tag_ids(LW_TAGS) if not tag_ids: print("No tags resolved; abort.") return seen = set() kept = 0 with open(OUT, "w") as f: for tag_name, tag_id in tag_ids.items(): print(f"\n=== {tag_name} ===", flush=True) try: posts = fetch_posts_for_tag(tag_id, tag_name) except Exception as e: print(f" FAIL: {e}", flush=True) continue for p in posts: pid = p.get("_id") if not pid or pid in seen: continue body = strip_html((p.get("contents") or {}).get("html") or "") wc = p.get("wordCount") or len(body.split()) if wc < MIN_WORDS or not body: continue f.write(json.dumps({ "id": pid, "title": p.get("title"), "slug": p.get("slug"), "posted_at": p.get("postedAt"), "body": body, "word_count": wc, "tags": [t["name"] for t in (p.get("tags") or [])], "base_score": p.get("baseScore"), "author": (p.get("user") or {}).get("displayName") or p.get("author"), }) + "\n") seen.add(pid) kept += 1 print(f"\n=== done: {kept} unique posts ≥{MIN_WORDS} words → {OUT} ===", flush=True) if __name__ == "__main__": main()