exp0-rationalist-dialect / fetch_alignmentforum_comments.py
rlundqvist's picture
Add files using upload-large-folder tool
ac1fe46 verified
Raw
History Blame Contribute Delete
4.63 kB
"""Fetch ALL comments on every AF post.
Strategy: read alignmentforum_posts.jsonl (must already exist), then for each
post issue `comments(view: "commentsByPost", postId: ...)`. Comments are
written incrementally so partial runs can be resumed.
NO start-date filter.
Writes: data/alignmentforum_comments.jsonl
Usage:
python fetch_alignmentforum_comments.py [--max-per-post 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)
API = "https://www.lesswrong.com/graphql"
POSTS_IN = Path(PROJECT_DIR) / "data" / "alignmentforum_posts.jsonl"
OUT = Path(PROJECT_DIR) / "data" / "alignmentforum_comments.jsonl"
MIN_WORDS = 20
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, retries=3):
for attempt in range(retries):
try:
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"]
except Exception as e:
if attempt == retries - 1: raise
print(f" retry {attempt+1}/{retries}: {e}", flush=True)
time.sleep(5 * (attempt + 1))
QUERY = """
query GetCommentsForPost($pid: String!, $limit: Int) {
comments(input: {terms: {view: "commentsByPost", postId: $pid, limit: $limit}}) {
results {
_id postId postedAt baseScore af
contents { html }
user { displayName }
}
}
}
"""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--max-per-post", type=int, default=1000)
args = ap.parse_args()
if not POSTS_IN.exists():
print(f"FATAL: {POSTS_IN} not found. Run fetch_alignmentforum.py first.")
sys.exit(1)
# Load post IDs
post_ids = []
with open(POSTS_IN) as f:
for line in f:
post_ids.append(json.loads(line)["id"])
print(f"have {len(post_ids)} AF posts to scan for comments", flush=True)
# Resume: skip post IDs we've already pulled comments for
done_posts = set()
if OUT.exists():
with open(OUT) as f:
for line in f:
try: done_posts.add(json.loads(line)["post_id"])
except: pass
print(f"resume: {len(done_posts)} posts already pulled", flush=True)
todo = [p for p in post_ids if p not in done_posts]
print(f"to fetch: {len(todo)}", flush=True)
n_comments = 0
t0 = time.time()
with open(OUT, "a") as f:
for i, pid in enumerate(todo):
try:
data = gql(QUERY, {"pid": pid, "limit": args.max_per_post})
except Exception as e:
print(f" ERR post {pid}: {e}", flush=True)
continue
results = data.get("comments", {}).get("results", []) or []
for c in results:
# Only keep AF comments (since LW posts cross-post can have non-AF replies)
if not c.get("af"): continue
cid = c.get("_id")
body = strip_html((c.get("contents") or {}).get("html") or "")
wc = len(body.split())
if not cid or not body or wc < MIN_WORDS: continue
f.write(json.dumps({
"id": cid,
"post_id": c.get("postId"),
"posted_at": c.get("postedAt"),
"body": body,
"word_count": wc,
"base_score": c.get("baseScore"),
"author": (c.get("user") or {}).get("displayName"),
"doc_type": "comment",
}) + "\n")
n_comments += 1
if (i + 1) % 50 == 0:
f.flush()
elapsed = time.time() - t0
rate = (i + 1) / max(1, elapsed)
eta = (len(todo) - i - 1) / max(0.01, rate) / 60
print(f" scanned {i+1}/{len(todo)} posts, "
f"{n_comments} comments kept, ETA {eta:.1f}min", flush=True)
time.sleep(0.2)
print(f"=== done: {n_comments} AF comments >={MIN_WORDS} words -> {OUT} ===", flush=True)
if __name__ == "__main__":
main()