File size: 6,951 Bytes
63879a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""
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)