exp0-rationalist-dialect / fetch_lesswrong_all.py
rlundqvist's picture
Add files using upload-large-folder tool
ac1fe46 verified
Raw
History Blame Contribute Delete
4.43 kB
"""Fetch a sample of ALL LessWrong posts since START_DATE (no tag filter)
for use as a baseline corpus to compare against AI-tagged posts.
Pagination uses a `before` date cursor because the GraphQL endpoint caps
`offset` (skip) at ~2000.
Writes: data/lesswrong_all_posts.jsonl
Usage:
python fetch_lesswrong_all.py [--max N]
"""
import argparse
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 START_DATE
API = "https://www.lesswrong.com/graphql"
OUT = Path(PROJECT_DIR) / "data" / "lesswrong_all_posts.jsonl"
MIN_WORDS = 200
def strip_html(html):
text = re.sub(r"<[^>]+>", " ", html or "")
for esc, raw in [("&nbsp;", " "), ("&amp;", "&"), ("&lt;", "<"),
("&gt;", ">"), ("&quot;", '"'), ("&#39;", "'")]:
text = text.replace(esc, raw)
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"]
QUERY = """
query GetPosts($limit: Int, $before: String, $after: String) {
posts(input: {terms: {view: "new", limit: $limit, before: $before, after: $after}}) {
results {
_id title slug postedAt baseScore author wordCount
contents { html }
tags { name }
user { displayName }
}
}
}
"""
def fetch_all(max_posts=50000, batch=200):
"""Walk posts newest-first using a `before` cursor. Each batch sets
`before` to one second prior to the oldest postedAt of the previous batch
(to avoid re-fetching the boundary post)."""
out = []
seen = set()
before = None # first call: no upper bound -> get newest
while len(out) < max_posts:
variables = {"limit": batch, "after": START_DATE}
if before is not None:
variables["before"] = before
data = gql(QUERY, variables)
results = data.get("posts", {}).get("results", [])
if not results:
print(" no more results", flush=True)
break
new = [r for r in results if r.get("_id") and r["_id"] not in seen]
for r in new:
seen.add(r["_id"])
out.extend(new)
# Find the oldest postedAt in this batch to use as next cursor
dates = [r.get("postedAt") for r in results if r.get("postedAt")]
if not dates:
print(" batch had no postedAt, stopping", flush=True)
break
oldest = min(dates)
print(f" fetched {len(out)} (oldest in batch={oldest[:19]}, new={len(new)})",
flush=True)
# If oldest is at/before START_DATE, we're done
if oldest[:10] <= START_DATE:
print(f" reached START_DATE={START_DATE}", flush=True)
break
if len(new) == 0:
# Cursor didn't advance -> nothing new came back; bail
print(" no new posts in this batch, stopping", flush=True)
break
before = oldest # next page = strictly older than this
time.sleep(0.4)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--max", type=int, default=50000)
args = ap.parse_args()
OUT.parent.mkdir(parents=True, exist_ok=True)
posts = fetch_all(args.max)
kept = 0
with open(OUT, "w") as f:
for p in posts:
pid = p.get("_id")
body = strip_html((p.get("contents") or {}).get("html") or "")
wc = p.get("wordCount") or len(body.split())
if not pid or not body or wc < MIN_WORDS: 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")
kept += 1
print(f"=== done: {kept} posts >={MIN_WORDS} words -> {OUT} ===", flush=True)
if __name__ == "__main__":
main()