fineweb-edu-misinfo / code /annotate_llm.py
ratishsp's picture
Upload code/annotate_llm.py with huggingface_hub
d20549e verified
Raw
History Blame Contribute Delete
21.7 kB
"""
Annotate documents using Together AI or Claude Sonnet APIs.
===========================================================
Actions: run, submit-claude, collect-claude, compare.
Usage:
# Run annotations via Together AI (sync, with optional concurrency)
python annotate_openrouter.py run \
--documents ../audit_output/flagged_documents.csv.gz \
--sample 100000 \
--model meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8 \
--output ../audit_output/annotations_llama_100k.csv \
--label-prefix llama --concurrency 64
# Submit/collect Claude batch
python annotate_openrouter.py submit-claude \
--documents ../audit_output/flagged_documents.csv.gz --sample 300
python annotate_openrouter.py collect-claude \
--documents ../audit_output/flagged_documents.csv.gz --sample 300 \
--batch-id <batch_id> --output ../audit_output/annotations_claude.csv
# Compare two annotation files
python annotate_openrouter.py compare \
--file-a annotations_a.csv --file-b annotations_b.csv
Note: run/collect must use the same --documents, --sample, and seed
to produce matching rows. Uses reservoir sampling for memory efficiency.
"""
import csv
import gzip
import os
import re
import random
import argparse
from collections import Counter
csv.field_size_limit(10_000_000)
# ── Config ────────────────────────────────────────────────────────────────────
LLAMA_MODEL = "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8"
CLAUDE_MODEL = "claude-sonnet-4-6"
MAX_TEXT_CHARS = 10000
RANDOM_SEED = 42
CLASSES = [
"climate_denial",
"health_misinfo",
"pseudoscience",
"hate_extremism",
"conspiracy_propaganda",
"benign",
]
SYSTEM_PROMPT = """You are an expert in misinformation research and content analysis.
Classify whether the following web document contains misinformation, propaganda, or other problematic content. The text may be truncated.
Use exactly one of these labels:
- climate_denial: denies or misrepresents climate change science
- health_misinfo: health or medical misinformation (antivax, COVID denial, quack remedies, unproven supplement claims, alternative medicine promoted as replacement for evidence-based treatment)
- pseudoscience: promotes non-medical unscientific claims (creationism, flat earth, ancient aliens, astrology, etc.)
- hate_extremism: hate speech, Holocaust denial, white nationalism, racist pseudoscience, far-right extremism, or religiously-motivated content that incites hatred or violence against specific groups
- conspiracy_propaganda: conspiracy theories (QAnon, chemtrails, etc.) or state-sponsored propaganda and disinformation
- benign: legitimate content that is not misinformation, propaganda, or pseudoscience
Important: only flag content that actively promotes or endorses misinformation. Use benign for:
- low-quality, politically biased, or opinionated content that is not clearly misinformation
- satirical, humorous, or fictional content
- articles that discuss or critically examine a questionable topic without endorsing it
- content with minor factual errors that is otherwise informational
- speculative or futuristic science and engineering discussions
- historical or archival documents that reflect outdated views or language
Respond in exactly this format:
LABEL: <label>
CONFIDENCE: high | medium | low
REASON: <one sentence explaining your verdict>"""
# ── Data loading ──────────────────────────────────────────────────────────────
def load_documents(documents_path, sample_size, seed=RANDOM_SEED):
"""Load documents from gzipped or plain CSV, optionally sampling.
Uses reservoir sampling to avoid loading all rows into memory when
sample_size is set (important for large files like 490K docs).
"""
is_gz = str(documents_path).endswith(".gz")
opener = gzip.open if is_gz else open
mode = "rt" if is_gz else "r"
def parse_row(row):
url = row.get("url", "")
domain = row.get("domain", "")
if not domain and url:
try:
from urllib.parse import urlparse
domain = urlparse(url).netloc
if domain.startswith("www."):
domain = domain[4:]
except Exception:
pass
return {
"url": url,
"domain": domain,
"category": row.get("category", "unknown"),
"score": row.get("score", ""),
"text": row.get(text_field, "")[:MAX_TEXT_CHARS],
}
with opener(documents_path, mode) as f:
reader = csv.DictReader(f)
fields = reader.fieldnames
text_field = "full_text" if "full_text" in fields else "text_preview"
if not sample_size:
rows = [parse_row(row) for row in reader]
print(f" Loaded {len(rows)} documents")
return rows
# Reservoir sampling: keeps only sample_size rows in memory
rng = random.Random(seed)
reservoir = []
total = 0
for i, row in enumerate(reader):
total = i + 1
if i < sample_size:
reservoir.append(parse_row(row))
else:
j = rng.randint(0, i)
if j < sample_size:
reservoir[j] = parse_row(row)
print(f" Sampled {len(reservoir)} from {total:,} total (reservoir sampling)")
return reservoir
# ── Prompt ────────────────────────────────────────────────────────────────────
def make_prompt(row):
return f"""Document text:
{row['text']}
Classify this document."""
def strip_thinking(text):
"""Remove <think>...</think> blocks that some models may produce."""
return re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
def parse_response(text):
"""Extract label, confidence, reason from model response."""
text = strip_thinking(text)
label = confidence = reason = ""
for line in text.strip().splitlines():
line = line.strip()
if line.upper().startswith("LABEL:"):
label = line.split(":", 1)[1].strip().lower()
elif line.upper().startswith("CONFIDENCE:"):
confidence = line.split(":", 1)[1].strip().lower()
elif line.upper().startswith("REASON:"):
reason = line.split(":", 1)[1].strip()
if label not in CLASSES:
label = "unknown"
return label, confidence, reason
# ── Claude batch ──────────────────────────────────────────────────────────────
def submit_claude_batch(rows):
import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
requests = [
Request(
custom_id=f"item-{i}",
params=MessageCreateParamsNonStreaming(
model=CLAUDE_MODEL,
max_tokens=128,
temperature=0.1,
system=SYSTEM_PROMPT,
messages=[{"role": "user", "content": make_prompt(row)}],
)
)
for i, row in enumerate(rows)
]
batch = client.messages.batches.create(requests=requests)
print(f" Batch submitted: {batch.id} ({len(requests)} requests)")
return batch.id
def collect_claude_batch(batch_id, n_rows):
import anthropic
client = anthropic.Anthropic()
batch = client.messages.batches.retrieve(batch_id)
print(f" Batch status: {batch.processing_status}")
if batch.processing_status != "ended":
print(f" ERROR: batch not complete")
return None
results = [""] * n_rows
for result in client.messages.batches.results(batch_id):
idx = int(result.custom_id.split("-")[1])
if result.result.type == "succeeded":
msg = result.result.message
results[idx] = next((b.text for b in msg.content if b.type == "text"), "")
else:
results[idx] = f"ERROR: {result.result.type}"
succeeded = sum(1 for r in results if r and not r.startswith("ERROR"))
print(f" Collected {succeeded}/{n_rows} results")
return results
# ── Synchronous / Concurrent Together AI ─────────────────────────────────────
def run_together_sync(rows, model, output_path, label_prefix="llm", concurrency=1):
"""Run Together AI requests, optionally with concurrency. Saves incrementally."""
checkpoint_path = output_path + ".checkpoint"
p = f"{label_prefix}_" if label_prefix else ""
fieldnames = ["url", "domain", "category", "score",
f"{p}label", f"{p}confidence", f"{p}reason"]
# Resume from checkpoint if exists
completed = {}
if os.path.exists(checkpoint_path):
with open(checkpoint_path) as f:
reader = csv.DictReader(f)
for row in reader:
completed[row["url"]] = row
print(f" Resuming from checkpoint: {len(completed):,} already done")
# Filter out already-completed rows
remaining_indices = [i for i, row in enumerate(rows) if row["url"] not in completed]
print(f" {len(remaining_indices):,} remaining to annotate")
if remaining_indices:
if concurrency > 1:
responses = _run_concurrent_incremental(
rows, remaining_indices, model, concurrency,
checkpoint_path, fieldnames, p)
else:
responses = [""] * len(rows)
# Run remaining
from together import Together
client = Together()
for idx in remaining_indices:
row = rows[idx]
try:
resp = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": make_prompt(row)},
],
max_tokens=256, temperature=0.1,
)
responses[idx] = resp.choices[0].message.content
except Exception as e:
responses[idx] = f"ERROR: {e}"
# Append to checkpoint
label, conf, reason = parse_response(responses[idx])
with open(checkpoint_path, "a", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
if f.tell() == 0:
writer.writeheader()
writer.writerow({
"url": row["url"], "domain": row["domain"],
"category": row["category"], "score": row["score"],
f"{p}label": label, f"{p}confidence": conf, f"{p}reason": reason,
})
# Fill in already-completed responses from checkpoint
for i, row in enumerate(rows):
if row["url"] in completed:
c = completed[row["url"]]
responses[i] = f"LABEL: {c[f'{p}label']}\nCONFIDENCE: {c[f'{p}confidence']}\nREASON: {c[f'{p}reason']}"
save_annotations(rows, responses, output_path, label_prefix=label_prefix)
return
# Build full responses from checkpoint + new results for final save
all_responses = [""] * len(rows)
for i, row in enumerate(rows):
if row["url"] in completed:
c = completed[row["url"]]
all_responses[i] = f"LABEL: {c[f'{p}label']}\nCONFIDENCE: {c[f'{p}confidence']}\nREASON: {c[f'{p}reason']}"
save_annotations(rows, all_responses, output_path, label_prefix=label_prefix)
def _run_concurrent_incremental(rows, indices, model, concurrency,
checkpoint_path=None, fieldnames=None, prefix=""):
"""Run requests with asyncio concurrency, saving to checkpoint incrementally."""
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(
api_key=os.environ["TOGETHER_API_KEY"],
base_url="https://api.together.xyz/v1",
)
responses = [""] * len(rows)
done_count = 0
lock = asyncio.Lock() if checkpoint_path else None
# Open checkpoint file for appending
cp_file = None
cp_writer = None
if checkpoint_path:
needs_header = not os.path.exists(checkpoint_path) or os.path.getsize(checkpoint_path) == 0
cp_file = open(checkpoint_path, "a", newline="")
cp_writer = csv.DictWriter(cp_file, fieldnames=fieldnames)
if needs_header:
cp_writer.writeheader()
cp_file.flush()
async def process(i, row, sem):
nonlocal done_count
async with sem:
try:
resp = await client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": make_prompt(row)},
],
max_tokens=256,
temperature=0.1,
)
responses[i] = resp.choices[0].message.content
except Exception as e:
responses[i] = f"ERROR: {e}"
# Write to checkpoint
if cp_writer and lock:
label, conf, reason = parse_response(responses[i])
async with lock:
cp_writer.writerow({
"url": row["url"], "domain": row["domain"],
"category": row["category"], "score": row["score"],
f"{prefix}label": label, f"{prefix}confidence": conf,
f"{prefix}reason": reason,
})
done_count += 1
if done_count % 1000 == 0:
cp_file.flush()
print(f" {done_count}/{len(indices)} done (checkpoint saved)", flush=True)
elif done_count % 100 == 0 or done_count == len(indices):
print(f" {done_count}/{len(indices)} done", flush=True)
else:
done_count += 1
if done_count % 100 == 0 or done_count == len(indices):
print(f" {done_count}/{len(indices)} done", flush=True)
async def run_all():
sem = asyncio.Semaphore(concurrency)
tasks = [process(idx, rows[idx], sem) for idx in indices]
await asyncio.gather(*tasks)
asyncio.run(run_all())
if cp_file:
cp_file.flush()
cp_file.close()
return responses
# ── Save results ──────────────────────────────────────────────────────────────
def save_annotations(rows, responses, output_path, label_prefix=""):
"""Save annotations to CSV."""
p = f"{label_prefix}_" if label_prefix else ""
fieldnames = ["url", "domain", "category", "score",
f"{p}label", f"{p}confidence", f"{p}reason"]
with open(output_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for i, row in enumerate(rows):
label, conf, reason = parse_response(responses[i])
writer.writerow({
"url": row["url"],
"domain": row["domain"],
"category": row["category"],
"score": row["score"],
f"{p}label": label,
f"{p}confidence": conf,
f"{p}reason": reason,
})
print(f"\nSaved {len(rows)} annotations to {output_path}")
# Summary
labels = [parse_response(r)[0] for r in responses]
print(f"\nLabel distribution:")
for label, n in Counter(labels).most_common():
print(f" {label:<25}: {n:4d} ({n/len(rows)*100:.1f}%)")
# ── Compare ───────────────────────────────────────────────────────────────────
def compare_annotations(file_a, file_b, name_a="A", name_b="B"):
"""Compare two annotation files and print agreement stats."""
rows_a = list(csv.DictReader(open(file_a)))
rows_b = list(csv.DictReader(open(file_b)))
# Detect label column names
def find_label_col(fieldnames):
for f in fieldnames:
if f.endswith("label"):
return f
return None
label_col_a = find_label_col(rows_a[0].keys()) if rows_a else None
label_col_b = find_label_col(rows_b[0].keys()) if rows_b else None
if not label_col_a or not label_col_b:
print("ERROR: could not find label columns")
return
# Build URL→label maps
map_a = {r["url"]: r[label_col_a] for r in rows_a}
map_b = {r["url"]: r[label_col_b] for r in rows_b}
common_urls = set(map_a.keys()) & set(map_b.keys())
print(f"\n{name_a}: {len(rows_a)} docs ({label_col_a})")
print(f"{name_b}: {len(rows_b)} docs ({label_col_b})")
print(f"Common URLs: {len(common_urls)}")
if not common_urls:
print("ERROR: no common URLs to compare")
return
agreements = sum(1 for u in common_urls if map_a[u] == map_b[u])
print(f"\nAgreement: {agreements}/{len(common_urls)} ({agreements/len(common_urls)*100:.1f}%)")
# Disagreements
disagree = [(map_a[u], map_b[u]) for u in common_urls if map_a[u] != map_b[u]]
if disagree:
print(f"\nDisagreements ({name_a}{name_b}):")
for pair, count in Counter(disagree).most_common(15):
print(f" {pair[0]:<25}{pair[1]:<25} ({count})")
# Per-class agreement
print(f"\nPer-class agreement:")
for cls in CLASSES + ["unknown"]:
in_a = [u for u in common_urls if map_a[u] == cls]
if in_a:
agree = sum(1 for u in in_a if map_b[u] == cls)
print(f" {cls:<25}: {agree}/{len(in_a)} ({agree/len(in_a)*100:.0f}%)")
# ── Main ──────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="action", required=True)
# ── run (Together AI, sync or concurrent)
p_run = subparsers.add_parser("run", help="Run Together AI annotations (sync or concurrent)")
p_run.add_argument("--documents", required=True)
p_run.add_argument("--sample", type=int, default=300)
p_run.add_argument("--model", default=LLAMA_MODEL, help=f"Model name (default: {LLAMA_MODEL})")
p_run.add_argument("--output", required=True)
p_run.add_argument("--label-prefix", default="llm", help="Column prefix (default: llm)")
p_run.add_argument("--concurrency", type=int, default=1, help="Number of concurrent requests (default: 1)")
# ── submit-claude
p_submit_c = subparsers.add_parser("submit-claude", help="Submit Claude batch")
p_submit_c.add_argument("--documents", required=True)
p_submit_c.add_argument("--sample", type=int, default=300)
# ── collect-claude
p_collect_c = subparsers.add_parser("collect-claude", help="Collect Claude results")
p_collect_c.add_argument("--documents", required=True)
p_collect_c.add_argument("--sample", type=int, default=300)
p_collect_c.add_argument("--batch-id", required=True)
p_collect_c.add_argument("--output", required=True)
# ── compare
p_compare = subparsers.add_parser("compare", help="Compare two annotation files")
p_compare.add_argument("--file-a", required=True)
p_compare.add_argument("--file-b", required=True)
p_compare.add_argument("--name-a", default="A")
p_compare.add_argument("--name-b", default="B")
args = parser.parse_args()
if args.action == "run":
print(f"Loading documents...")
rows = load_documents(args.documents, args.sample)
print(f"\nRunning {len(rows)} requests (model: {args.model}, concurrency: {args.concurrency})...")
run_together_sync(rows, args.model, args.output, label_prefix=args.label_prefix, concurrency=args.concurrency)
elif args.action == "submit-claude":
print("Loading documents...")
rows = load_documents(args.documents, args.sample)
print(f"\nSubmitting Claude batch...")
submit_claude_batch(rows)
elif args.action == "collect-claude":
print("Loading documents...")
rows = load_documents(args.documents, args.sample)
print(f"\nCollecting Claude batch {args.batch_id}...")
responses = collect_claude_batch(args.batch_id, len(rows))
if responses:
save_annotations(rows, responses, args.output, label_prefix="claude")
elif args.action == "compare":
compare_annotations(args.file_a, args.file_b, args.name_a, args.name_b)