""" Export a participant's NiceWebRL data (task_ole-cu-nicewebrl, "ReactorRoom") into ONE long-format CSV: one row per trial and one row per survey item, sharing a single union column set (cells empty where not applicable). Filter by the `row_type` column. Union columns cover the three record schemas from CONTRACT.md: * learning trial (row_type="trial", phase="learning") * baseline / generalization (row_type="trial", phase="baseline"|"generalization") * survey items (row_type="survey", measure=…) Robust to missing fields — every column defaults to "". Usage: python export_csv.py # data/user_data_*.msgpack -> *_data.csv python export_csv.py path/file.msgpack python export_csv.py path/file.msgpack out.csv 1007 """ import csv import glob import sys from nicewebrl.utils import read_all_records_sync COLUMNS = [ "row_type", "pid", "group", "ts", # ---- trial (learning + baseline + generalization; union) ---- "phase", "block", "trial", "clip_id", "recipient", "severity", "mishap", "intensity", "coviewer", "coviewer_level", "predicted_demo", "demo_rating", "prediction_error", "self_rating", "rt_predict_ms", "rt_self_ms", # ---- survey (one row per item) ---- "measure", "when", "item", "response", "is_correct", "correct_answer", "survey_round", "survey_extra", ] # scalar types we treat as an item response when exploding a survey record _SCALAR = (int, float, str, bool) # keys that are survey-level metadata, NOT individual item responses _SURVEY_META = { "row_type", "measure", "when", "pid", "group", "ts", "responses", "ratings", "coviewer_names", "reverse_keyed", "n_items", "n_correct_first_try", "target", "name", } # trial fields we copy straight through when present _TRIAL_FIELDS = [ "phase", "block", "trial", "clip_id", "recipient", "severity", "mishap", "intensity", "coviewer", "coviewer_level", "predicted_demo", "demo_rating", "prediction_error", "self_rating", "rt_predict_ms", "rt_self_ms", ] def _data_of(rec): """Return the payload dict for a record, whether it's a nicewebrl-wrapped record (has a 'data' key) or a bare dict already carrying row_type.""" if isinstance(rec, dict): d = rec.get("data") if isinstance(d, dict) and ("row_type" in d or not rec.get("row_type")): # prefer the wrapped payload when it looks like ours if isinstance(d, dict) and d: return d if "row_type" in rec: return rec if isinstance(d, dict): return d return rec if isinstance(rec, dict) else {} def _trial_row(base, d): row = {**base, "row_type": "trial", "pid": d.get("pid", ""), "group": d.get("group", ""), "ts": d.get("ts", "")} for k in _TRIAL_FIELDS: if k in d and d[k] is not None: row[k] = d[k] return row def _survey_rows(base, d): """One row per survey item. Handles battery dicts (scalar fields), comprehension `responses` lists, and impression `ratings` name->value maps.""" common = {"row_type": "survey", "pid": d.get("pid", ""), "group": d.get("group", ""), "ts": d.get("ts", ""), "measure": d.get("measure", ""), "when": d.get("when", "")} out = [] # 1) comprehension-style list of item responses for r in d.get("responses", []) or []: if not isinstance(r, dict): continue out.append({**base, **common, "item": r.get("key", r.get("qid", "")), "response": r.get("export_text", r.get("choice", "")), "is_correct": r.get("is_correct", ""), "correct_answer": r.get("correct", ""), "survey_round": r.get("round", "")}) # 2) impression-style name->value ratings map ratings = d.get("ratings") if isinstance(ratings, dict): for name, val in ratings.items(): out.append({**base, **common, "item": name, "response": val}) # 3) flat scalar item responses (IRI, willingness, attention_check, …) # skip keys already represented via ratings above skip_scalars = set(ratings.keys()) if isinstance(ratings, dict) else set() scalar_meta = {} for k, v in d.items(): if k in ("is_correct", "target", "answer"): scalar_meta[k] = v continue if k in _SURVEY_META or k in skip_scalars: continue if isinstance(v, _SCALAR): row = {**base, **common, "item": k, "response": v} out.append(row) # attention-check / single pass-fail measures: emit a dedicated row carrying the # correctness metadata even if no plain scalar item was produced above if scalar_meta: out.append({**base, **common, "item": d.get("measure", ""), "response": scalar_meta.get("answer", ""), "is_correct": scalar_meta.get("is_correct", ""), "correct_answer": scalar_meta.get("target", "")}) # nothing itemizable -> still emit a marker row so the survey isn't lost if not out: out.append({**base, **common, "item": d.get("measure", ""), "response": ""}) return out def export(msgpack_path, out_path=None, pid=None): records = read_all_records_sync(msgpack_path) base = dict.fromkeys(COLUMNS, "") rows = [] for rec in records: d = _data_of(rec) rt = d.get("row_type") if rt == "trial": row = _trial_row(base, d) if pid and not row.get("pid"): row["pid"] = pid rows.append(row) elif rt == "survey": srows = _survey_rows(base, d) if pid: for r in srows: if not r.get("pid"): r["pid"] = pid rows.extend(srows) # everything else (Events, EnvStage, etc.) is ignored for this long format if out_path is None: out_path = msgpack_path.rsplit(".", 1)[0] + "_data.csv" with open(out_path, "w", newline="") as f: w = csv.DictWriter(f, fieldnames=COLUMNS) w.writeheader() w.writerows(rows) n_tr = sum(1 for r in rows if r["row_type"] == "trial") n_sv = sum(1 for r in rows if r["row_type"] == "survey") print(f" wrote {out_path} ({n_tr} trial rows, {n_sv} survey rows, " f"{len(rows)} total, {len(COLUMNS)} cols)") return out_path if __name__ == "__main__": args = sys.argv[1:] if args: path = args[0] out = args[1] if len(args) > 1 else None pid = args[2] if len(args) > 2 else None export(path, out, pid) else: paths = sorted(glob.glob("data/user_data_*.msgpack")) if not paths: print("No data files found (data/user_data_*.msgpack).") for p in paths: export(p)