chiron-data / code /build_evaluation.py
henry-yeh's picture
Withhold PsihoRo source files and public evaluation records
3803283 verified
Raw History Blame Contribute Delete
14.1 kB
#!/usr/bin/env python3
"""Build evaluation JSONL files from local sources; no inference or API calls.
Inputs:
prediction: data/raw/prediction/<domain>/qa_jsonl/test.jsonl and adapters.
measurement: data/raw/measurement/human_gold/{samples.jsonl,scoring.json},
or <domain>/samples.jsonl when the combined snapshot is absent;
construct_vocab.json, test_filter.json and the human-label row builder.
population: data/raw/population/{test_studies.jsonl,split.json}.
Output: data/eval/{prediction,measurement,population}.jsonl, with domain on each row.
python code/build_evaluation.py
python code/build_evaluation.py --type measurement
python code/build_evaluation.py --public-only
Python 3.10+ and the workspace modules are sufficient. Paths resolve from this
script. All selected signals are validated before replacing their output files.
Prediction exports the paper's 4,767 cases across 29 domains, using the original
source-row index for observation and question sampling. Frozen identities and
question-text spans are restored from data/eval/sources/record_layout.json. Measurement
exports the five-source final test set (2,855 people, 6,852 construct targets),
including the reviewed PANDORA disclosure removals. The default requires every
source. --public-only excludes restricted sources and rebuilds the distributed
subset. Training and raw source files are unchanged. Other signals retain source order.
"""
from __future__ import annotations
import argparse
from collections import defaultdict
import copy
import hashlib
import json
from pathlib import Path
import random
import re
import sys
import tempfile
from types import SimpleNamespace
sys.dont_write_bytecode = True
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "code"))
from domain_adapter import Sample, get_adapter
from measurement import build_human_gold
from utils import evaluation_inputs as evaluation
SIGNALS = ("prediction", "measurement", "population")
RESTRICTED_PREDICTION_DOMAINS = {"pandora", "wvs", "grit_tweet", "twitter_stmhd"}
RESTRICTED_MEASUREMENT_DOMAINS = {"pandora", "student_sadd_phq9", "psihoro_romanian_phq9_gad7"}
# Final prediction benchmark: one view per person, at most 200 per domain.
PREDICTION_COUNTS = {
"blog": 200, "essays_big5": 123, "grit_tweet": 21,
"openpsych_16pf": 200, "openpsych_as_sc_ad_do": 50,
"openpsych_big5": 200, "openpsych_cfcs": 200, "openpsych_dass": 200,
"openpsych_ecr": 200, "openpsych_fti": 200, "openpsych_hbds": 200,
"openpsych_hexaco": 200, "openpsych_hsns_dd": 200, "openpsych_hsq": 54,
"openpsych_ipip_ffm": 200, "openpsych_mach": 200, "openpsych_npas": 200,
"openpsych_npi": 200, "openpsych_nr6": 111, "openpsych_osri44": 200,
"openpsych_pwe": 67, "openpsych_riasec": 200, "openpsych_rse": 200,
"openpsych_sd3": 200, "pandora": 71, "sapa_2022": 200,
"self_esteem": 162, "twitter_stmhd": 108, "wvs": 200,
}
# Final convergent-validity test: (people, construct targets).
MEASUREMENT_COUNTS = {
"covid19_real_world_worry_rw3d": (1133, 2266),
"empathic_reactions_buechel2018": (842, 842),
"pandora": (693, 3465),
"psihoro_romanian_phq9_gad7": (92, 184),
"student_sadd_phq9": (95, 95),
}
def record_key(row, signal):
payload = {key: row[key] for key in ("domain", "messages")}
field = "ground_truths" if signal == "prediction" else "measurement"
payload[field] = row[field]
encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
def load_record_layout(root, signal):
return json.loads((root / "data/eval/sources/record_layout.json").read_text(encoding="utf-8"))[signal]
def selected_layout(layout, row, signal):
entries = layout.get(record_key(row, signal))
if not entries:
raise ValueError(f"Rebuilt {signal} input does not match the frozen evaluation layout")
return entries.pop(0)
def checked_name(name):
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]*", name):
raise ValueError(f"Invalid domain/study name: {name!r}")
return name
def prediction_rows(root, public_only=False):
raw = root / "data/raw/prediction"
layout = load_record_layout(root, "prediction")
args = SimpleNamespace(seed=42, min_questions=5, max_questions=10)
for name, expected_count in sorted(PREDICTION_COUNTS.items()):
if public_only and name in RESTRICTED_PREDICTION_DOMAINS:
continue
directory = raw / name
adapter = get_adapter(name)
if adapter.name != name:
raise ValueError(f"Use the canonical adapter name: {adapter.name}")
rows = list(evaluation.read_records(directory / "qa_jsonl/test.jsonl"))
identities = [str(adapter.get_sample_id(Sample.from_dict(row))) for row in rows]
if len(identities) != len(set(identities)):
raise ValueError(f"{name}: duplicate identities in the test pool")
order = list(range(len(rows)))
random.Random(42).shuffle(order)
selected = order[:200]
if len(selected) != expected_count:
raise ValueError(f"{name}: expected {expected_count} cases, got {len(selected)}; "
f"rebuild the source pool following data/raw/prediction/{name}/SOURCE.md")
for index in selected:
row = rows[index]
if row.get("domain", name) != name:
raise ValueError(f"{name}: conflicting domain field")
sample = Sample.from_dict(row)
if sample.split != "test":
raise ValueError(f"{name}: row {index + 1} is not a test record")
case = evaluation.prepare_case(sample, index, adapter, args)
selected = selected_layout(layout, case, "prediction")
user = case["messages"][1]["content"]
spans = selected["question_spans"]
if len(spans) != case["n_questions"] or any(not 0 <= start < end <= len(user) for start, end in spans):
raise ValueError("Invalid frozen question spans")
yield {
"sample_id": selected["sample_id"], "domain": name, "split": case["split"],
"messages": case["messages"], "questions": [user[start:end] for start, end in spans],
"ground_truths": case["ground_truths"], "n_questions": case["n_questions"],
"n_observations": case["n_observations"],
}
def clean_pandora_test(row, removals):
"""Apply reviewed comment removals to one test row, retaining its labels."""
user_index = next(i for i, m in enumerate(row["messages"]) if m["role"] == "user")
user = row["messages"][user_index]["content"]
match = re.search(r"(<person_records>\s*\n)(.*?)(\n\s*</person_records>)", user, re.S)
if match is None:
raise ValueError("PANDORA test row has no person_records block")
records = match.group(2).splitlines()
dropped = set()
for removal in removals:
index = removal["index"]
if (type(index) is not int or not 0 <= index < len(records) or index in dropped
or not records[index].startswith("- I posted on Reddit:")):
raise ValueError("PANDORA test filter does not match the source record order")
text = records[index][2:]
if hashlib.sha256(text.encode("utf-8")).hexdigest() != removal["sha256"]:
raise ValueError("PANDORA test filter does not match the source comment")
dropped.add(index)
retained = [text for i, text in enumerate(records) if i not in dropped]
if not any(text.startswith("- I posted on Reddit:") for text in retained):
return None
cleaned = dict(row)
cleaned["messages"] = [dict(message) for message in row["messages"]]
cleaned["messages"][user_index]["content"] = (
user[:match.start(2)] + "\n".join(retained) + user[match.end(2):])
return cleaned
def measurement_rows(root, public_only=False):
raw = root / "data/raw/measurement"
layout = load_record_layout(root, "measurement")
vocab = json.loads((raw / "construct_vocab.json").read_text(encoding="utf-8"))
scoring = build_human_gold.validate_scoring(
json.loads((raw / "human_gold/scoring.json").read_text(encoding="utf-8")), vocab)
expected_counts = {name: counts for name, counts in MEASUREMENT_COUNTS.items()
if not public_only or name not in RESTRICTED_MEASUREMENT_DOMAINS}
samples = build_human_gold.load_source_samples(raw / "human_gold")
if public_only:
samples = [row for row in samples if row["domain"] in expected_counts]
rows = build_human_gold.build_rows(
samples, scoring, vocab,
require_contiguous_ids=not public_only and (raw / "human_gold/samples.jsonl").is_file())["test"]
missing = set(expected_counts) - {row["domain"] for row in rows}
if missing:
raise ValueError("Missing measurement test sources: " + ", ".join(sorted(missing))
+ "; see data/raw/measurement/human_gold/SOURCE.md")
removals = (json.loads((raw / "human_gold/test_filter.json").read_text(encoding="utf-8"))["pandora"]
if "pandora" in expected_counts else {})
applied = set()
grouped = defaultdict(list)
for row in rows:
if row["domain"] not in expected_counts:
continue
if row["domain"] == "pandora" and row["sample_id"] in removals:
applied.add(row["sample_id"])
row = clean_pandora_test(row, removals[row["sample_id"]])
if row is None:
continue
grouped[checked_name(row["domain"])].append(row)
if applied != set(removals):
raise ValueError("PANDORA test filter IDs do not match the prepared source samples")
for name, expected in sorted(expected_counts.items()):
counts = (len(grouped[name]), sum(len(r["measurement"]["targets"]) for r in grouped[name]))
if counts != expected:
raise ValueError(f"{name}: expected {expected} people/targets, got {counts}")
for index, row in enumerate(grouped[name]):
evaluation.prepare_measurement_case(row, index, vocab)
selected = selected_layout(layout, row, "measurement")
yield {"sample_id": selected["sample_id"], "domain": name,
"messages": row["messages"], "measurement": row["measurement"]}
def population_rows(root, public_only=False):
raw = root / "data/raw/population"
split = json.loads((raw / "split.json").read_text(encoding="utf-8"))
for key in ("train_studies", "test_studies"):
names = split[key]
if not isinstance(names, list) or not names or len(names) != len(set(names)):
raise ValueError(f"Invalid {key} in population split")
for name in names:
checked_name(name)
if set(split["test_studies"]) & set(split["train_studies"]):
raise ValueError("Population train/test study overlap")
studies = list(evaluation.read_records(raw / "test_studies.jsonl"))
for study in studies:
study["domain"] = checked_name(study.pop("study"))
evaluation.validate_population_studies(copy.deepcopy(studies))
if {s["domain"] for s in studies} != set(split["test_studies"]):
raise ValueError("Population test snapshot must match every test study in split.json")
for study in sorted(studies, key=lambda s: s["domain"]):
if any(p.get("split") != "test" for p in study["prompts"]):
raise ValueError(f"{study['domain']}: expected a test condition")
yield study
def build(root=ROOT, signal=None, public_only=False, output_dir=None):
if signal is not None and signal not in SIGNALS:
raise ValueError(f"Unknown signal: {signal}")
builders = {"prediction": prediction_rows, "measurement": measurement_rows,
"population": population_rows}
output = Path(output_dir) if output_dir is not None else root / "data/eval"
counts = {}
with tempfile.TemporaryDirectory(prefix=".eval-build-", dir=root / "data") as temporary:
stage = Path(temporary)
for name in ([signal] if signal else SIGNALS):
domains = defaultdict(int)
prepared = list(builders[name](root, public_only=public_only))
if name in {"prediction", "measurement"}:
order = {entry["sample_id"]: entry["order"]
for entries in load_record_layout(root, name).values() for entry in entries}
prepared.sort(key=lambda row: order[row["sample_id"]])
with (stage / f"{name}.jsonl").open("w", encoding="utf-8") as handle:
for row in prepared:
domains[row["domain"]] += 1
handle.write(json.dumps(row, ensure_ascii=False, allow_nan=False,
separators=(",", ":")) + "\n")
if not domains:
raise ValueError(f"{name}: test data is empty")
counts[name] = sum(domains.values())
print(f"{name}: {counts[name]:,} rows, {len(domains)} domains", flush=True)
output.mkdir(parents=True, exist_ok=True)
for name in counts:
(stage / f"{name}.jsonl").replace(output / f"{name}.jsonl")
return counts
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--type", choices=SIGNALS, help="Omit to build all three complete signal files")
parser.add_argument("--public-only", action="store_true", help="Build only the distributed evaluation domains")
parser.add_argument("--output-dir", type=Path, help="Write to a separate evaluation directory")
args = parser.parse_args(argv)
try:
build(signal=args.type, public_only=args.public_only, output_dir=args.output_dir)
except (ValueError, KeyError, TypeError, OSError) as exc:
parser.exit(1, f"Build failed: {exc}\n")
if __name__ == "__main__":
main()