Spaces:
Running
Running
Download questionnaires.py from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 60.8 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/questionnaires.py
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/questionnaires.py
-
curl -L -o questionnaires.py https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/questionnaires.py
60.8 kB
"""
Questionnaire stages for the Prosocial Effort task (task_pe-cu-nicewebrl).
Wording ported from the Qualtrics source. Built as NiceWebRL FeedbackStages so
each one collects a dict of responses that gets logged like any other stage.
* Fatigue (pre & post): single 0-100 slider, "How tired do you feel right now?"
* Comprehension: two multiple-choice checks (loops until both correct).
* NASA-TLX effort: how effortful was harvesting the easiest vs hardest amount.
* Effort-impact: how did you feel earning credits for YOU vs the OTHER player.
* Self-esteem: Rosenberg items (0-100 agreement sliders).
"""
import asyncio
import json
import random
import zlib
from contextlib import nullcontext
from nicegui import app, ui
import nicewebrl
from nicewebrl import FeedbackStage
import screens
import effort_design as D
import themes as TH
def _go_back_one_stage():
"""Call when 'Back' is clicked on a cross-stage-rewindable stage. The
experiment framework's own advance_stage() always adds +1 right after
this stage's display_fn returns, so setting stage_idx to (current - 2)
here nets out to exactly one stage back overall.
Precondition: stage_idx must be >= 2. This primitive only correctly nets
to "one stage back" when idx >= 2; at idx == 1 it doesn't move, and at
idx == 0 it would move forward (clamped to 0 via max()). The plan's own
stage ordering excludes Back from the first stages (Fatigue_pre, etc.),
so all callers implicitly satisfy this precondition."""
idx = app.storage.user.get("stage_idx", 0)
app.storage.user["stage_idx"] = max(0, idx - 2)
async def _confirm_skip():
"""Qualtrics-style 'are you sure' dialog for an incomplete page. Returns True if the
participant chooses to continue anyway. Ported from sl-cu-nicewebrl's questionnaires.py."""
confirmed = {"v": False}
ev = asyncio.Event()
# persistent: a Quasar dialog is dismissable by ESC or a backdrop click by
# default, and dismissing this one set neither button's event, so the
# awaiting Continue handler never returned. The dialog vanished, Continue
# looked like it had done nothing, and each further click left another
# stranded dialog and coroutine behind.
with ui.dialog().props("persistent") as dialog, ui.card():
ui.markdown(
"You haven't answered everything on this page. Are you sure you want to "
"continue without answering?"
)
with ui.row():
ui.button("Go back and answer",
on_click=lambda: (dialog.close(), ev.set())).props("outline")
ui.button("Continue anyway",
on_click=lambda: (confirmed.update(v=True), dialog.close(), ev.set()))
dialog.open()
await ev.wait()
# Built fresh on every call, so without this each skipped page leaves one
# behind for the rest of the session.
try:
dialog.delete()
except Exception:
pass
return confirmed["v"]
async def _ignore_keys(e, container):
return
def _kind_for(name):
"""Which bucket a stage's screen record goes in, from its name."""
n = name.lower()
if n.startswith("harvest"):
return "harvest"
if n.startswith("night"):
return "night"
if "quiz" in n or "comprehension" in n or "comp" == n[:4]:
return "quiz"
return "questionnaire"
def _fb(name, display_fn):
"""A FeedbackStage whose screen is timed. Every stage in this file goes through here,
so one wrapper covers all of them: enter, exit, dwell, clicks and the time to the
first click land in the participant's timing CSV (see screens.py)."""
async def _timed(stage, container):
# No `log=` and no import of web_app. web_app calls screens.set_logger(log_event)
# as it loads, and `from web_app import log_event` HERE would not find that module:
# the container runs `python web_app.py`, so web_app is __main__ and the import
# builds a second copy and re-runs its body, which calls app.on_startup() after
# NiceGUI has started and 500s the page. Cost a participant their session on
# 2026-11-03.
async with screens.watch(name, _kind_for(name)):
return await display_fn(stage, container)
return FeedbackStage(name=name, display_fn=_timed, custom_key_press_fn=_ignore_keys)
# ----------------------------------------------------------------------------
# Generic slider battery
# ----------------------------------------------------------------------------
async def _slider_battery(container, title, intro, items, lo_label=None, hi_label=None,
lo=0, hi=100, start=50, allow_back=False, faces=None):
"""items: list of (key, prompt) sharing lo_label/hi_label, or
(key, prompt, item_lo_label, item_hi_label) to override the anchors for
that one item (e.g. mixing motivation- and effort-worded items in one
battery). Returns (values_dict, went_back_bool).
An empty `title` renders no heading. The post-task pages carried a short
label of their own ("Effort", "Motivation", "About the task") and then the
real instruction underneath it, which is two things to read before the
first item; they open on the instruction now, the way the TriPM does.
`faces` is one (row, canvas_prefix) per item, or None. With it each item
gets that person's picture to its left: the liking question names an id,
and an id is not somebody the participant can recognise. Without it the
page is laid out exactly as it was, because a dozen other batteries use
this function and none of them is about a person."""
nicewebrl.clear_element(container)
ev = asyncio.Event()
result = {"went_back": False}
sliders = {}
touched = {item[0]: False for item in items}
with container.style("align-items:center; max-width:680px;"):
if title:
ui.markdown(f"## {title}")
if intro:
ui.markdown(intro)
for i, item in enumerate(items):
key, prompt = item[0], item[1]
item_lo = item[2] if len(item) > 2 else lo_label
item_hi = item[3] if len(item) > 3 else hi_label
face = faces[i] if faces and i < len(faces) else None
with (ui.row().style("align-items:center; gap:14px; width:100%; "
"max-width:630px; flex-wrap:nowrap;")
if face else nullcontext()):
if face:
_face_canvas(face[0], face[1])
with ui.column().style("width:100%; max-width:560px; "
"margin-bottom:10px; min-width:0;"):
ui.markdown(f"**{prompt}**")
s = ui.slider(min=lo, max=hi, value=start).props("label-always")
s.on_value_change(lambda e, k=key: touched.update({k: True}))
with ui.row().style("width:100%; justify-content:space-between;"):
ui.label(item_lo).style("font-size:12px; color:#666;")
ui.label(item_hi).style("font-size:12px; color:#666;")
sliders[key] = s
async def on_continue():
if not all(touched.values()):
if not await _confirm_skip():
return
ev.set()
with ui.row():
if allow_back:
ui.button("Back", on_click=lambda: (result.update(went_back=True), ev.set())).props("outline")
ui.button("Continue", on_click=on_continue)
if faces:
import effort_stages as E
await E._paint_last(await _partner_faces([f[0] for f in faces],
faces[0][1]))
await ev.wait()
# Every slider starts at 50 and "Continue anyway" records that as an
# answer, so a 50 in the data could be a considered midpoint or a page
# nobody touched. Record which, otherwise the two are indistinguishable
# afterwards and the midpoint is the value a skipped page contributes.
out = {k: int(s.value) for k, s in sliders.items()}
out.update({f"{k}_touched": bool(v) for k, v in touched.items()})
return out, result["went_back"]
# ----------------------------------------------------------------------------
# Fatigue
# ----------------------------------------------------------------------------
#: Stage-name suffix and on-screen framing per block. A day-only session must
#: keep the names it was registered with, so "day" adds nothing.
BLOCK_SUFFIX = {"day": "", "night": "Night_"}
def _block_frame(block):
"""How to name the block on screen."""
return "the Night Harvest" if block == "night" else "the daytime harvest"
def fatigue_stage(when):
"""`when` is "pre", "post" (after the day task) or "night"."""
async def _display(stage, container):
# "post" no longer repeats "the task has finished" -- the dedicated
# QuestionnaireTransition screen right before this one already says that.
intro = ("Before we begin, one quick question." if when == "pre"
else "One quick question first.")
res, _went_back = await _slider_battery(
# The heading was the question, and then the question again
# underneath it.
container, "How tired are you?", intro,
[("fatigue", "How tired do you feel right now?")],
"Not at all tired", "Extremely tired", allow_back=False)
return dict(measure="fatigue", when=when, **res)
return _fb(f"Fatigue_{when}", _display)
# ----------------------------------------------------------------------------
# NASA-TLX style effort ratings (uses the participant's calibrated levels)
# ----------------------------------------------------------------------------
def nasa_tlx_stage(block="day"):
async def _display(stage, container):
th = TH.current_theme()
v, t = th["verb"], th["target"]
levels = D.effort_levels(app.storage.user.get("max_boxes", D.MAX_BOXES_FALLBACK))
res, went_back = await _slider_battery(
container, "",
f"Think back to {v}ing {t} during {_block_frame(block)}.\n\n"
f"Please indicate how effortful each of these was.",
# easiest and hardest levels by rank, not by name -- the names change
# if the effort fractions are ever retuned, the ranks do not.
[(f"effort_lvl{i + 1}",
f"How effortful did you find {v}ing {levels[nm]} {t}?")
for i, nm in enumerate(D.EFFORT_NAMES)],
"Required no effort", "Required a lot of effort", allow_back=True)
if went_back:
_go_back_one_stage()
return dict(measure="nasa_tlx_effort", block=block,
went_back=True, **res)
return dict(measure="nasa_tlx_effort", block=block, levels=levels, **res)
return _fb(BLOCK_SUFFIX[block] + "NASA_TLX", _display)
# ----------------------------------------------------------------------------
# Effort impact (self vs other)
# ----------------------------------------------------------------------------
def effort_impact_stage(block="day"):
async def _display(stage, container):
import effort_stages as E
if block == "night":
# Nothing was earned FOR this partner, so the day task's wording
# describes a game that was not played here.
nid = (app.storage.user.get("random_id_night")
or E.night_partner_id())
items = [("impact_night_take",
f"How did you feel when you walked home with credits and "
f"your partner ({nid}) lost the larger amount?"),
("impact_night_work",
f"How did you feel when you harvested their field and "
f"your partner ({nid}) lost far less?")]
else:
rid = app.storage.user.get("random_id", "the other player")
items = [("impact_self",
"How did you feel when you earned credits for YOU?"),
("impact_other",
f"How did you feel when you earned credits for your "
f"partner ({rid}), the OTHER player?")]
res, went_back = await _slider_battery(
container, "",
"Please indicate how you felt in each case.", items,
"Very bad", "Very good", allow_back=True)
if went_back:
_go_back_one_stage()
return dict(measure="effort_impact", block=block, went_back=True, **res)
return dict(measure="effort_impact", block=block, **res)
return _fb(BLOCK_SUFFIX[block] + "Effort_impact", _display)
# ----------------------------------------------------------------------------
# Post-task motivation / effort / task-rating / belief / strategy battery.
# "Partner" below = the real, age-matched in-game partner. The separate
# hypothetical battery (further down) asks child participants to imagine their
# parent playing, and parent participants to imagine their child playing.
# ----------------------------------------------------------------------------
def _partner_label():
rid = app.storage.user.get("random_id", "Player 2")
return f"your partner ({rid})"
def _choice_items(prefix, phrasing, block="day"):
"""One item per CHOICE the participant actually faced.
Split by choice type (work / rest / raid) crossed with who was paid, rather
than the old win-vs-avoid split. Work and rest are the two options on every
day trial and they are what the model contrasts, so asking about them
separately is what makes these ratings comparable to the fitted parameters;
"avoid losing" only ever applied to the night blocks.
Raid items are included only for the night blocks this participant actually
saw -- asking someone about raiding a sleeping partner they never met would
be confusing at best and suggestive at worst.
"""
import effort_stages as E
p = _partner_label()
rid = app.storage.user.get("random_id", "Player 2")
items = [
(f"{prefix}_work_self", phrasing("WORK to earn credits for YOURSELF")),
(f"{prefix}_work_other", phrasing(f"WORK to earn credits for {p}")),
(f"{prefix}_rest_self", phrasing("REST instead of working when the credits were for YOURSELF")),
(f"{prefix}_rest_other", phrasing(f"REST instead of working when the credits were for {p}")),
]
try:
nights = set(E.night_conditions())
except Exception:
nights = set()
if 1 in nights:
items.append((f"{prefix}_raid_self",
phrasing(f"RAID the field of {p} at night, taking credits "
f"from them for YOURSELF")))
items.append((f"{prefix}_raid_rest",
phrasing("STAY ASLEEP at night instead of raiding")))
if 2 in nights:
items.append((f"{prefix}_raid_keep",
phrasing("keep the night harvest in YOUR OWN pocket")))
items.append((f"{prefix}_raid_leave",
phrasing(f"leave the night harvest in the pocket of {p}")))
return items
def _night_choice_items(prefix, phrasing):
"""The night harvest's own items, asked in its own battery after it.
Separate from the day task's rather than appended to them: the two blocks
are about different people and are now asked about at different points in
the session, so putting both sets on one page asked about a block the
participant had not reached yet.
"""
import effort_stages as E
pn = E.partner_label_plain("night")
return [
(f"{prefix}_field_rest",
phrasing(f"REST and walk home with credits, knowing {pn} would lose "
f"the larger amount")),
(f"{prefix}_field_work",
phrasing(f"WORK on the field of {pn} for one credit less than "
f"resting")),
(f"{prefix}_field_vague",
phrasing(f"WORK on their field on the nights when you were shown a "
f"RANGE instead of an amount")),
]
def motivation_stage(block="day"):
async def _display(stage, container):
picker = _night_choice_items if block == "night" else _choice_items
res, went_back = await _slider_battery(
container, "",
f"Think back to {_block_frame(block)}.\n\n"
f"Please indicate how motivated you were to do each of the "
f"following.",
picker("motiv", lambda what: f"How motivated were you to {what}?"),
"Not at all motivated", "Extremely motivated", allow_back=True)
if went_back:
_go_back_one_stage()
return dict(measure="post_motivation", block=block, went_back=True, **res)
return dict(measure="post_motivation", block=block, **res)
return _fb(BLOCK_SUFFIX[block] + "PostTask_Motivation", _display)
def effort_exerted_stage(block="day"):
async def _display(stage, container):
picker = _night_choice_items if block == "night" else _choice_items
res, went_back = await _slider_battery(
container, "",
f"During {_block_frame(block)}.\n\n"
f"Please indicate how much effort each of these took.",
picker("effort", lambda what: f"How much effort did it take to {what}?"),
"Required no effort", "Required a lot of effort", allow_back=True)
if went_back:
_go_back_one_stage()
return dict(measure="post_effort", block=block, went_back=True, **res)
return dict(measure="post_effort", block=block, **res)
return _fb(BLOCK_SUFFIX[block] + "PostTask_Effort2", _display)
def task_rating_stage(block="day"):
async def _display(stage, container):
where = _block_frame(block)
res, went_back = await _slider_battery(
container, "",
f"Please indicate how you found {where}.",
[("task_difficulty", f"How easy or difficult was {where}?",
"Very easy", "Very difficult"),
("task_interest", f"How boring or interesting was {where}?",
"Very boring", "Very interesting")], allow_back=True)
if went_back:
_go_back_one_stage()
return dict(measure="post_task_rating", block=block, went_back=True, **res)
return dict(measure="post_task_rating", block=block, **res)
return _fb(BLOCK_SUFFIX[block] + "PostTask_TaskRating", _display)
#: Legacy column names, kept so the export and the analysis keep reading what
#: they always read. One question per person now, asked after the block that
#: introduced them, but the day one and the night one still mean what they
#: meant.
_LEGACY_BELIEF_KEY = {"day": "believed_partner_paid",
"night": "believed_night_partner_lost"}
async def _partner_faces(rows, prefix):
"""Paint the canvas faces in one round trip, once the page is built.
Returns the drawing call for effort_stages._paint_last, so the Continue
button is on screen before the pictures land rather than a round trip
after them. Only the "own" rows are here: the other task's partner is an
<img> and needs no drawing call.
"""
faces = [{"id": f"{prefix}_{r['position']}", "idx": int(r["avatar"])}
for r in rows
if r.get("face") == "own" and r.get("avatar") is not None]
if not faces:
return None
return ("(function(a){if(!window.Cornfield)return;a.forEach(function(x){"
"window.Cornfield.partnerAvatarPreview(x.id,x.idx);});})("
+ json.dumps(faces) + ")")
#: Both face slots are this size, so a row's text sits in the same place
#: whether the picture is drawn here or fetched from the other Space.
_FACE_STYLE = "width:58px;height:71px;border-radius:8px;flex:0 0 auto;"
def _face_canvas(row, prefix):
"""The picture that goes beside this person's question.
An id (P2-63540) is not a person. The participant met this one on a
matching screen that showed their face, and the questions about them used
to show only the id, so the last three screens of the study asked about
somebody the participant had no way to recognise.
This task's own partners are drawn on a canvas. The other task's are
fetched from the other Space, because an explorer redrawn as a farmer
would be a different-looking person from the one they met. A fetch that
fails leaves the same gap the row used to have, never a broken image.
"""
import effort_stages as E
if row.get("avatar") is None:
return _face_gap()
if row.get("face") == "own":
ui.html(f'<canvas id="{prefix}_{row["position"]}" width="72" '
f'height="88" style="{_FACE_STYLE}'
f'background:{TH.canvas_soil()};"></canvas>')
return
url = E.other_task_face_url(row.get("avatar"))
if not url:
return _face_gap()
ui.html(f'<img src="{url}" alt="" style="{_FACE_STYLE}'
f'object-fit:cover;background:{TH.canvas_soil()};" '
f'onerror="this.style.visibility=\'hidden\'">')
def _face_gap():
"""The same indent, with no picture, so the text still lines up."""
ui.html(f'<div style="{_FACE_STYLE}"></div>')
def partner_belief_stage():
"""Did they believe each partner was real, asked once about all of them.
Asked at the very end of the study, after every other question. Asking it
mid-battery tells the participant there is something to doubt, and
everything after it is then answered by someone who has just been invited
to suspect the study. Only the TriPM and the demographics follow, neither
of which is about the tasks.
About ALL the partners, including the other task's, because it is the
same question and splitting it across the two tasks asked it twice and
still missed a partner each time. Each row carries that person's face.
"""
async def _display(stage, container):
import effort_stages as E
rows = E.question_partner_rows()
if not rows:
return dict(measure="belief_check", skipped="no partners")
nicewebrl.clear_element(container)
done = asyncio.Event()
radios = {}
prefix = "pe_belief"
with container.style("align-items:center; max-width:680px;"):
ui.markdown("Please answer for each of the people you played with."
if len(rows) > 1 else
"One more question about the person you played with.")
warn = ui.markdown("")
for r in rows:
with ui.row().style("align-items:center; gap:14px; width:100%; "
"max-width:620px; margin-bottom:14px; "
"flex-wrap:nowrap;"):
_face_canvas(r, prefix)
with ui.column().style("align-items:flex-start; "
"flex:1 1 auto; min-width:0;"):
ui.markdown(r["question"]).style("text-align:left;")
radios[r["position"]] = (ui.radio({"Yes": "Yes", "No": "No"})
.props("inline color=primary"))
async def go():
blank = [p for p, w in radios.items() if w.value is None]
if blank:
warn.set_content(f"\u26a0\ufe0f **{len(blank)} of "
f"{len(rows)} still blank.**")
if not await _confirm_skip():
return
done.set()
ui.button("Continue", on_click=go).props("color=primary size=lg")
await E._paint_last(await _partner_faces(rows, prefix))
await done.wait()
out = {"measure": "belief_check", "partners": []}
for r in rows:
answer = radios[r["position"]].value
out[f"believed_p{r['position']}"] = answer
legacy = _LEGACY_BELIEF_KEY.get(r.get("kind"))
if legacy and legacy not in out:
out[legacy] = answer
out["partners"].append({"position": r["position"], "id": r["id"],
"kind": r.get("kind"),
"where": r.get("where")})
return out
return _fb("PostTask_Belief", _display)
def partner_liking_stage():
"""How much they liked each partner, one slider per person, with faces.
Next to the belief questions because both are about the people rather
than about either task, and both have to come after everything that asks
about the tasks themselves.
"""
async def _display(stage, container):
import effort_stages as E
rows = E.question_partner_rows()
if not rows:
return dict(measure="partner_liking", skipped="no partners")
# No ** around the id: _slider_battery already bolds the whole prompt,
# and bold inside bold renders the markers as literal asterisks in
# italics ("*P2-69469, the person ...*").
items = [(f"liking_p{r['position']}",
f"How much did you like {r['id']}, the person you "
f"played with in {r.get('where', 'this study')}?")
for r in rows]
prefix = "pe_liking"
res, _went_back = await _slider_battery(
container, "",
"Please indicate how much you liked each of the people you "
"played with." if len(rows) > 1 else
"Please indicate how much you liked the person you played with.",
items, "Not at all", "Very much", allow_back=False,
faces=[(r, prefix) for r in rows])
# `kind` as well as `where`, matching the belief record. Position
# depends on which task the participant happened to do first, so an
# analysis pooling liking_p1 across participants stacks two different
# questions. `kind` is the stable token that says which game the
# person belonged to, and `where` is prose that can be reworded.
return dict(measure="partner_liking",
partners=[{"position": r["position"], "id": r["id"],
"kind": r.get("kind"),
"where": r.get("where")} for r in rows],
**res)
return _fb("PostTask_Liking", _display)
# ----------------------------------------------------------------------------
# Hypothetical cross-role battery: children are asked to imagine their parent
# also played this game; parents are asked to imagine their child did. Each
# question is split self/other (the imagined player earning for themselves,
# vs. earning for the real participant), per the researcher's design note.
# ----------------------------------------------------------------------------
def _hypothetical_person(titlecase=False):
"""Who the participant is asked to imagine playing the same game.
The parent/child study asks each side to imagine the other. A parent
participant is asked about their child. Everybody else is asked about
their parent, which is the SONA sample as well: an undergraduate has a
parent to picture even though no parent is enrolled, and the researcher
asked on 2026-10-18 for the block to run there with that wording. It read
"another participant" before, which asks about a stranger.
"""
role = app.storage.user.get("role")
who = "your child" if role == "p" else "your parent"
return who[0].upper() + who[1:] if titlecase else who
def hypothetical_stage():
"""Asks the participant to rate somebody else playing the same game.
In the dyadic study that person really did play it, in the next room. On
SONA nobody did, so the question is put as a hypothetical and says so: the
sentence asks the participant to imagine it. The items are identical,
because both ask what that person WOULD do.
"""
async def _display(stage, container):
who = _hypothetical_person()
who_title = _hypothetical_person(titlecase=True)
# "played" in the dyadic study, where they did. "imagine ... also
# played" everywhere else, where nobody did and saying they had would
# be a claim about a person the participant knows.
intro = (
(f"In the meantime, {who} played the same game. "
"How do you think they did?"
if app.storage.user.get("dyad_mode") else
f"In the meantime, imagine that {who} also played the same game. "
"How do you think they would have done?")
+ "\n\nThere are no right or wrong answers here — just your "
"best guess."
)
res, went_back = await _slider_battery(
container, who_title, intro,
[("hyp_motiv_self", f"How motivated do you think {who} would be to win points for themselves?"),
("hyp_motiv_other", f"How motivated do you think {who} would be to win points for YOU?"),
("hyp_effort_self", f"How much effort do you think {who} would exert to win points for themselves?"),
("hyp_effort_other", f"How much effort do you think {who} would exert to win points for YOU?")],
"Not at all", "Extremely / a lot", allow_back=True)
if went_back:
_go_back_one_stage()
return dict(measure="hypothetical_cross_role", went_back=True, **res)
res2, _went_back2 = await _slider_battery(
container, who_title, "",
[("hyp_difficulty", f"How easy or difficult do you think {who} would find the task?",
"Very easy", "Very difficult"),
("hyp_interest", f"How boring or interesting do you think {who} would find the task?",
"Very boring", "Very interesting")], allow_back=False)
return dict(measure="hypothetical_cross_role", who=who, **res, **res2)
return _fb("PostTask_Hypothetical", _display)
def strategy_stage(block="day"):
"""Free-text: what strategy did the participant use?"""
async def _display(stage, container):
nicewebrl.clear_element(container)
done = asyncio.Event()
result = {"went_back": False}
th = TH.current_theme()
with container.style("align-items:center; max-width:640px;"):
# No heading of its own, like the TriPM and the slider pages:
# the instruction is the first thing to read.
ui.markdown(f"Please describe the strategy (or strategies) you "
f"used during {_block_frame(block)}.")
text = ui.textarea().props("outlined autogrow").style("width:100%;")
async def on_continue():
if not (text.value or "").strip():
if not await _confirm_skip():
return
done.set()
with ui.row():
ui.button("Back", on_click=lambda: (result.update(went_back=True), done.set())).props("outline")
ui.button("Continue", on_click=on_continue)
await done.wait()
if result["went_back"]:
_go_back_one_stage()
# text.value is live-bound (no separate "commit" step like a submit
# button), so whatever was already typed is safe to include here too.
return dict(measure="strategy", block=block, went_back=True,
strategy_text=(text.value or "").strip())
return dict(measure="strategy", block=block,
strategy_text=(text.value or "").strip())
return _fb(BLOCK_SUFFIX[block] + "PostTask_Strategy", _display)
# ----------------------------------------------------------------------------
# Self-esteem (Rosenberg subset)
# ----------------------------------------------------------------------------
ROSENBERG = [
("se1", "I feel that I have a number of good qualities."),
("se2", "All in all, I am inclined to feel that I am a failure."),
("se3", "I am able to do things as well as most other people."),
("se4", "I take a positive attitude toward myself."),
]
def self_esteem_stage():
async def _display(stage, container):
res, _went_back = await _slider_battery(
container, "About you", "Please rate how much you agree with each statement.",
ROSENBERG, "Strongly disagree", "Strongly agree")
return dict(measure="self_esteem", **res)
return _fb("Self_esteem", _display)
# ----------------------------------------------------------------------------
# Comprehension quiz (a.k.a. the "quiz"). Wording matches the Qualtrics survey,
# adapted to corn for DISPLAY; the EXPORT carries the canonical Qualtrics option
# text (with "boxes") so the Comp1_Q1/Q2 + Comp2_Q1/Q2 columns are byte-exact.
# Flow mirrors Qualtrics: Comp1 (both questions); if any wrong, Comp2 (retry).
# ----------------------------------------------------------------------------
COMP_INTRO = ("Please answer the following questions carefully to check your "
"understanding of the task.")
def comp2_intro():
th = TH.current_theme()
return ("**At least one of your answers was incorrect.**\n\n"
"Remember, on each round:\n\n"
"- The banner shows whether the credits are earned for **YOU** or your "
"**partner**.\n"
f"- You choose between two options — **Rest** for **{D.REST_CREDIT} credits**, or **Work** to "
f"earn more credits for **{th['verb']}ing {th['target']}**. If you choose to work, "
f"you must {th['verb']} **all** of the {th['target']} within **10 seconds**, "
"otherwise no credits are given for that round.\n\n"
"Please try one more time.")
# Each option is (display_text, qualtrics_export_text). display_text is themed
# (corn/jellyfish/fireflies/boxes); export_text is ALWAYS the canonical
# Qualtrics wording (with "boxes") so the Comp1_Q1/Q2 + Comp2_Q1/Q2 export
# columns stay byte-exact regardless of which theme was played.
def comp_items():
"""The comprehension items.
Display text is themed and is checked against the instruction screens; the
second string in each option is the canonical Qualtrics export text and is
deliberately left alone, so the exported columns stay comparable with the
original study. Full-sentence options end in a period, one-word ones do not.
The partner is always YOUR PARTNER, matching the round banner.
Written with the correct option first, and returned in a per-participant
order -- see _shuffle_options.
"""
th = TH.current_theme()
v, t = th["verb"], th["target"]
return _shuffle_options([
dict(key="comp_rest", qid="Q1",
prompt="What happens if you choose to REST?",
options=[
(f"I relax and earn {D.REST_CREDIT} credits.",
f"I relax and earn, but only {D.REST_CREDIT} credits"),
(f"I still have to {v} {t}.", "I still have to harvest corn"),
("I earn nothing at all.", "I earn nothing"),
], correct=0,
explain=f"Resting is easy. You relax and earn **{D.REST_CREDIT} credits**."),
dict(key="comp_work", qid="Q2",
prompt="What happens if you choose to WORK?",
options=[
(f"I have to {v} ALL of the {t} shown to earn the credits.",
"I have to click all of the boxes on the screen to earn the credits"),
(f"I have to {v} at least SOME of the {t} to earn the credits.",
"I have to click at least some of the boxes to earn the credits"),
(f"It doesn't matter whether I {v} any {t} or not.",
"It doesn't matter whether I click any boxes or not"),
], correct=0,
explain=f"To earn the credits you must {v} **all** of the {t} shown, "
f"**within 10 seconds**."),
# Social-comprehension items (extra columns appended to the export: Comp*_Q3/Q4/Q5).
dict(key="comp_who", qid="Q3",
prompt="On a YOUR PARTNER round, who gets the credits you earn?",
options=[
("YOUR PARTNER. It adds to their bonus, which is real money.",
"My partner - it adds to their bonus"),
("Me.", "Me"),
("Nobody.", "Nobody"),
], correct=0,
explain="On a YOUR PARTNER round the credits go to YOUR PARTNER, not to you. "
"That bonus is **real money** they will actually receive."),
dict(key="comp_who_self", qid="Q5",
prompt="On a YOU round, who gets the credits you earn?",
options=[
("Me. It adds to my bonus, which is real money.",
"Me - it adds to my bonus"),
("YOUR PARTNER.", "My partner"),
("Nobody.", "Nobody"),
], correct=0,
explain="On a YOU round the credits add to your own bonus. That is **real money** "
"you will actually receive."),
dict(key="comp_affect", qid="Q4",
prompt="Can YOUR PARTNER make choices that change how much YOU earn?",
options=[
("No. Only my choices matter. They just receive what I earn for them.",
"No - only my choices matter"),
("Yes. They also make choices that change my earnings.",
"Yes - they change my earnings"),
], correct=0,
explain="No. Only your choices matter. YOUR PARTNER never affects what you earn."),
])
async def _ask_mc(container, header, item, can_back=False):
"""SL-style: pick once -> see explanation feedback -> advance regardless.
Submit + options lock after the first choice. Returns (chosen_idx, went_back)."""
display_choices = [o[0] for o in item["options"]]
correct_idx = item["correct"]
nicewebrl.clear_element(container)
chosen = {"idx": None}
result = {"went_back": False}
done = asyncio.Event()
with container.style("align-items:center; max-width:680px;"):
th = TH.current_theme()
icon = th["item_emoji"] or "▫️"
ui.label(icon).style("font-size:40px; line-height:1;")
ui.markdown(f"### {header}")
ui.markdown(f"**{item['prompt']}**")
radio = (ui.radio({i: c for i, c in enumerate(display_choices)})
.props("color=primary")
.style("margin-left:0; padding-left:0;"))
fb = ui.markdown("")
back_btn = None
# One row, and the buttons take turns in it. Submit and Back used to
# stay on screen next to Continue once an answer was in, greyed out but
# still there. An RA read three buttons after every question and asked
# which one was live.
with ui.row():
if can_back:
back_btn = ui.button("Back", on_click=lambda: (result.update(went_back=True), done.set())).props("outline")
submit = ui.button("Submit")
cont = ui.button("Continue", on_click=lambda: done.set())
cont.set_visibility(False)
def do_submit():
if radio.value is None or chosen["idx"] is not None:
return
chosen["idx"] = radio.value
ok = (radio.value == correct_idx)
lead = "✅ **Correct!** " if ok else "❌ **Not quite.** "
# The question is still on screen above this, so the feedback does
# not repeat it; the revisit screen, where it is not, does.
fb.set_content(lead + item.get("explain", ""))
radio.disable() # lock the options
submit.set_visibility(False) # one choice per question, so it is done
# Back goes away for THIS question once its answer is submitted, so a
# participant can't see the correct-answer explanation and then click
# Back to re-attempt the same question with the answer already known.
# Back to a PREVIOUS already-answered question is unaffected -- that
# re-invokes _ask_mc fresh for that question with its own back_btn.
if back_btn is not None:
back_btn.set_visibility(False)
cont.set_visibility(True) # advance regardless of right/wrong
submit.on_click(do_submit)
await done.wait()
return chosen["idx"], result["went_back"]
def _shuffle_options(items):
"""The same items with their options in a per-participant order.
Every quiz item here was written with the correct answer first and nothing
ever reordered them, so the top choice was always right. A participant who
noticed could pass both quizzes without reading either, and the night
harvest's quiz is also the exclusion criterion, so it was inflating who
counts as having understood the block.
Seeded by the pid and the item id: fixed for a session, so the retry round
asks the question the same way round as the first attempt, and different
between participants, which is what removes the artifact. `correct` moves
with the options, and `options_order` records where they came from, since a
stored choice index now means something different for each participant.
"""
pid = str(app.storage.user.get("pid", "") or "anon")
out = []
for it in items:
rng = random.Random(zlib.crc32(f"quizopts|{pid}|{it['qid']}".encode()))
order = list(range(len(it["options"])))
rng.shuffle(order)
shuffled = dict(it)
shuffled["options"] = [it["options"][i] for i in order]
shuffled["correct"] = order.index(it["correct"])
shuffled["options_order"] = order
out.append(shuffled)
return out
async def _comp_round(container, rnd, items):
out = []
n = 0
while n < len(items):
it = items[n]
# Each question is its own screen record, with its own rt and its own corr,
# which is PsychoPy's <component>.corr. The stage wrapper around the whole
# round cannot see either.
# A wrong answer re-asks the question in a later round, so the round is in the
# name; without it the retries would all overwrite one component.
async with screens.watch(f"comp_{it['qid']}_r{rnd}", "quiz", index=n) as _s:
idx, went_back = await _ask_mc(
container, f"Quiz ({n + 1}/{len(items)})", it, can_back=(n > 0))
_s["action"] = "back" if went_back else "submit"
if not went_back:
_s["keys"] = ("" if idx is None
else it["options"][idx][1] if idx < len(it["options"]) else idx)
_s["corr"] = int(idx == it["correct"])
if went_back:
n -= 1
out.pop() # discard the answer we're about to re-ask
continue
out.append(dict(key=it["key"], qid=it["qid"], round=rnd, choice=idx,
export_text=it["options"][idx][1] if idx is not None else "",
correct=it["correct"], is_correct=(idx == it["correct"]),
# The options are in a per-participant order, so the
# two indices above are only readable against this.
# export_text and is_correct do not depend on it.
options_order=it.get("options_order")))
n += 1
return out
# ----------------------------------------------------------------------------
# The night harvest's own quiz. The main comprehension items are about the day
# task -- what resting pays and that working needs every box inside 10 seconds
# -- and neither asks the one belief this block depends on, which is that
# resting costs the partner. A participant who missed that produces choices
# that look like indifference, so the quiz doubles as the exclusion criterion.
# ----------------------------------------------------------------------------
def watch_comp_items():
"""Written with the correct option first, returned in a per-participant
order -- see _shuffle_options. This quiz is the exclusion criterion, so a
fixed order was inflating who counts as having understood the block."""
th = TH.current_theme()
big = max(D.WATCH_LOSS_REST)
return _shuffle_options([
dict(key="watch_comp_rest", qid="W1",
prompt="On a night when you choose REST, what happens?",
options=[
(f"I collect {D.WATCH_REST_PAY} credits, and my partner "
f"loses the larger amount.",
"I collect credits and my partner loses the larger amount"),
(f"I collect {D.WATCH_REST_PAY} credits, and my partner "
f"loses nothing.",
"I collect credits and my partner loses nothing"),
("I collect nothing, and my partner loses nothing.",
"I collect nothing and my partner loses nothing"),
], correct=0,
explain=f"Resting pays you **{D.WATCH_REST_PAY} credits** and "
f"leaves their field standing, so they lose the larger "
f"amount, up to **{big} credits**."),
dict(key="watch_comp_work", qid="W2",
prompt="On a night when you choose WORK, what happens?",
options=[
(f"I keep {D.WATCH_WORK_PAY} credit, and my partner loses "
f"only a little.",
"I keep one credit and my partner loses only a little"),
(f"I keep {D.WATCH_WORK_PAY} credit, and my partner still "
f"loses the larger amount.",
"I keep one credit and my partner still loses the larger amount"),
(f"I collect more than {D.WATCH_REST_PAY} credits, and my "
f"partner loses nothing.",
"I collect more credits and my partner loses nothing"),
], correct=0,
explain=f"{th['verb'].capitalize()}ing their field in pays you "
f"**{D.WATCH_WORK_PAY} credit**, which is less than "
f"resting, and holds their loss down to "
f"**{D.WATCH_LOSS_WORK} credits**."),
])
async def watch_comprehension_body(container):
"""The quiz itself, callable from another stage.
Out here rather than only inside a stage because the night harvest runs it at
the end of its practice stage: a separate stage for two questions would
add a row to STAGE_ORDER and to the analysis progress column for no gain.
"""
items = watch_comp_items()
responses = await _comp_round(container, 1, items)
attempts = 1
while any(not r["is_correct"] for r in responses[-len(items):]):
wrong = [items[i] for i, r in enumerate(responses[-len(items):])
if not r["is_correct"]]
nicewebrl.clear_element(container)
ev = asyncio.Event()
with container.style("align-items:center; max-width:680px;"):
ui.markdown("### Not quite. Let's go through that again.")
for it in wrong:
ui.markdown(f"**{it['prompt']}**")
ui.markdown(f"{it['explain']}")
ui.button("Try again", on_click=lambda: ev.set())
await ev.wait()
attempts += 1
responses += await _comp_round(container, attempts, wrong)
if attempts >= 4: # never trap anyone in the loop, since a
break # participant who cannot get it is data,
# not someone to hold at a screen
return dict(measure="watch_comprehension", attempts=attempts,
responses=responses)
def comprehension_stage():
async def _display(stage, container):
# intro (SL-style wording)
nicewebrl.clear_element(container)
ev = asyncio.Event()
with container.style("align-items:center; max-width:680px;"):
ui.markdown("## Let's check your understanding!")
ui.button("Start quiz", on_click=lambda: ev.set())
await ev.wait()
# Round 1, then the missed items again until every one is right. It
# used to re-ask once and move on, so a participant could start the
# task still believing resting pays nothing or that working needs only
# some of the boxes, which is the same wrong belief the night quiz
# excludes people for. The night quiz already looped; this is the same
# loop, with the same cap, because a participant who cannot get there
# is data rather than someone to hold at a screen.
items = comp_items()
responses = await _comp_round(container, 1, items)
wrong = [items[i] for i, r in enumerate(responses) if not r["is_correct"]]
attempts = 1
while wrong and attempts < 4:
nicewebrl.clear_element(container)
ev2 = asyncio.Event()
with container.style("align-items:center; max-width:680px;"):
ui.markdown("### Let's revisit the ones you got wrong!")
# The question with its answer. The answer alone reads as a
# statement out of nowhere when more than one item was missed,
# and the participant has to work out which question it is
# about before they can learn anything from it.
for it in wrong:
ui.markdown(f"**{it['prompt']}**")
ui.markdown(f"{it['explain']}")
ui.button("OK", on_click=lambda: ev2.set())
await ev2.wait()
attempts += 1
# Capped at Comp2 in the export: the template has Comp1 and Comp2
# columns, and a Comp3 would be dropped without a word. The raw
# record keeps every attempt either way.
round_out = await _comp_round(container, min(attempts, 2), wrong)
responses += round_out
wrong = [wrong[i] for i, r in enumerate(round_out)
if not r["is_correct"]]
nicewebrl.clear_element(container)
ev3 = asyncio.Event()
with container.style("align-items:center; max-width:600px;"):
ui.markdown("## You're all set! 🌽")
ui.button("Continue", on_click=lambda: ev3.set())
await ev3.wait()
return dict(measure="comprehension", responses=responses)
return _fb("Comprehension", _display)
# ----------------------------------------------------------------------------
# Study text supplied from content/ rather than hard-coded here: the consent
# form, a demographics block and the TriPM item bank. Each stage is skipped
# while its file is still a placeholder, so a half-filled content folder never
# blocks a pilot run and never shows a participant a placeholder.
# ----------------------------------------------------------------------------
import content_items as CI
async def consent_screen(container):
"""The consent form, before anything is collected. True if they agreed.
Returns True when there is no consent form on file, because the stage does
not exist yet in that case -- a missing file must not read as a refusal.
"""
# The order this session already resolved, so the form names the task they
# are about to start. Resolved before this screen runs, in the page
# handler, and None for a single-task session, which reads "decided at
# random" instead.
text = CI.consent_text(dyad=bool(app.storage.user.get("dyad_mode")),
first_task=app.storage.user.get("task_first"))
if not text:
return True
nicewebrl.clear_element(container)
done = asyncio.Event()
out = {"agreed": False}
with container.style("align-items:center; max-width:760px;"):
# extras="html" so the highlighted phrases render rather than showing
# their tags to the participant
ui.markdown(text, extras=["html"])
def agree():
out["agreed"] = True
done.set()
ui.markdown("---")
ui.markdown("**I consent to take part in this study.**")
with ui.row().style("gap:16px; margin-top:8px;"):
ui.button("Yes", on_click=agree).props("color=primary size=lg")
ui.button("No", on_click=done.set).props("outline size=lg")
await done.wait()
return out["agreed"]
def _demographic_widget(it):
"""The input for one demographics item.
Out of the page loop so each item can sit in its own left-aligned column
with its question above it, the way the TriPM reads.
"""
t = it["type"]
if t == "number":
return ui.number().props("outlined").style("width:100%;")
if t == "choice":
return (ui.radio(it["options"]).props("color=primary")
.style("margin:0 0 0 -10px; padding:0;"))
if t == "dropdown":
# A radio grid of 20-odd income bands is a wall; a select is the same
# question without the wall.
return ui.select(it["options"]).props("outlined").style("width:100%;")
if t == "multi":
# Select all that apply -- race/ethnicity is not a single choice, and
# forcing it into one loses people who are more than one thing.
return ui.select(it["options"], multiple=True).props(
"outlined use-chips").style("width:100%;")
if t == "scale":
return ui.slider(min=0, max=100, value=50).props("label-always")
return ui.input().props("outlined").style("width:100%;")
def demographics_stage():
"""Demographics, from content/demographics.txt."""
async def _display(stage, container):
items = CI.demographics_items()
if not items:
return dict(measure="demographics", skipped="no items supplied")
nicewebrl.clear_element(container)
done = asyncio.Event()
widgets = {}
widgets_opts = {it["key"]: it["options"] for it in items}
with container.style("align-items:center; max-width:640px;"):
# Same layout as the TriPM: one left-aligned column for the whole
# page, question above, the control under it at full width.
with ui.column().style("width:100%; max-width:560px; "
"align-items:flex-start; gap:0;"):
ui.markdown("Please answer the following questions about "
"yourself.")
ui.markdown("_You may leave any question blank._")
for it in items:
with ui.column().style("width:100%; "
"align-items:flex-start; "
"gap:2px; margin-bottom:18px;"):
ui.markdown(f"**{it['question']}**").style(
"text-align:left;")
widgets[it["key"]] = (_demographic_widget(it),
it["type"])
ui.button("Continue", on_click=done.set).props(
"color=primary size=lg")
await done.wait()
res = {}
for key, (w, t) in widgets.items():
val = w.value
if val is None or val == "" or val == []:
continue
if t in ("number", "scale"):
res[key] = float(val)
elif t == "multi":
# Kept as the joined selection AND as one flag per option, so
# the CSV can be analysed without re-parsing a string.
chosen = list(val)
res[key] = "; ".join(chosen)
for opt in widgets_opts.get(key, []):
res[f"{key}__{_slug(opt)}"] = 1 if opt in chosen else 0
else:
res[key] = str(val)
# Which questions were PUT, alongside which were answered. An empty
# answer is dropped above, so a page where somebody declined
# everything recorded nothing at all and read exactly like a page
# that never ran, or like a content file still on its placeholder.
# The TriPM already records n_items for the same reason.
return dict(measure="demographics", n_items=len(items),
asked=[it["key"] for it in items],
n_answered=len(res), **res)
return _fb("Demographics", _display)
#: TriPM's published response format. Four points, not a slider, because that is
#: how the instrument is scored.
TRIPM_SCALE = ["False", "Somewhat false", "Somewhat true", "True"]
def _slug(text):
"""A short, stable column suffix for one multi-select option."""
keep = [c.lower() if c.isalnum() else "_" for c in text]
out = "".join(keep)
while "__" in out:
out = out.replace("__", "_")
return out.strip("_")[:28]
def tripm_stage():
"""The TriPM on a single page.
Six pages with a counter made the block feel like six questionnaires rather
than one list, and the counter invited people to track progress instead of
reading. One scrolling page with the items in bold is less furniture and
reads faster.
"""
async def _display(stage, container):
# Asked in a per-participant order. One fixed order puts the same items
# last for everyone, where attention is lowest, and the three scales
# are interleaved in the published order, so that cost lands unevenly
# across Boldness, Meanness and Disinhibition. Each key travels with
# its own item, so tripm_key.csv scores exactly what it did before.
items = CI.tripm_items(order_seed=app.storage.user.get("pid") or "anon")
if not items:
return dict(measure="tripm", skipped="no items supplied")
nicewebrl.clear_element(container)
done = asyncio.Event()
widgets = {}
with container.style("align-items:center; max-width:720px;"):
# One left-aligned column holds the instruction, every statement
# and the button, so all of them start at the same x. Centring
# them put each statement over the middle of its own scale, which
# read as a different layout for every statement length.
with ui.column().style("width:100%; max-width:600px; "
"align-items:flex-start; gap:0;"):
ui.markdown("Please indicate how true each statement is of "
"you.")
warn = ui.markdown("")
for key, text in items:
# Statement on its own line, its scale on the next one.
# The scale is pulled back by the radio's own 10px of
# inner padding so the first circle sits flush under the
# statement's first letter.
with ui.column().style("width:100%; "
"align-items:flex-start; "
"gap:2px; margin-bottom:20px;"):
ui.markdown(f"**{text}**").style("text-align:left;")
widgets[key] = (ui.radio(TRIPM_SCALE)
.props("inline color=primary")
.style("margin:0 0 0 -10px; padding:0;"))
async def submit():
missing = [k for k, w in widgets.items()
if w.value not in TRIPM_SCALE]
if missing:
# Requested, not forced, like every other page here.
# The consent says a participant may skip any question
# they do not wish to answer, and this page was the one
# that held them at it.
warn.set_content(
f"\u26a0\ufe0f **{len(missing)} of {len(items)} "
f"statements are still blank.**")
if not await _confirm_skip():
return
done.set()
ui.button("Continue", on_click=submit).props(
"color=primary size=lg")
await done.wait()
answers = {k: TRIPM_SCALE.index(w.value) for k, w in widgets.items()
if w.value in TRIPM_SCALE}
# Which order they were asked in, since it is no longer the file's and
# an order effect cannot be checked afterwards without it.
return dict(measure="tripm", n_items=len(items),
item_order=[k for k, _ in items], **answers)
return _fb("TriPM", _display)
"""
Questionnaire stages for the Prosocial Effort task (task_pe-cu-nicewebrl).
Wording ported from the Qualtrics source. Built as NiceWebRL FeedbackStages so
each one collects a dict of responses that gets logged like any other stage.
* Fatigue (pre & post): single 0-100 slider, "How tired do you feel right now?"
* Comprehension: two multiple-choice checks (loops until both correct).
* NASA-TLX effort: how effortful was harvesting the easiest vs hardest amount.
* Effort-impact: how did you feel earning credits for YOU vs the OTHER player.
* Self-esteem: Rosenberg items (0-100 agreement sliders).
"""
import asyncio
import json
import random
import zlib
from contextlib import nullcontext
from nicegui import app, ui
import nicewebrl
from nicewebrl import FeedbackStage
import screens
import effort_design as D
import themes as TH
def _go_back_one_stage():
"""Call when 'Back' is clicked on a cross-stage-rewindable stage. The
experiment framework's own advance_stage() always adds +1 right after
this stage's display_fn returns, so setting stage_idx to (current - 2)
here nets out to exactly one stage back overall.
Precondition: stage_idx must be >= 2. This primitive only correctly nets
to "one stage back" when idx >= 2; at idx == 1 it doesn't move, and at
idx == 0 it would move forward (clamped to 0 via max()). The plan's own
stage ordering excludes Back from the first stages (Fatigue_pre, etc.),
so all callers implicitly satisfy this precondition."""
idx = app.storage.user.get("stage_idx", 0)
app.storage.user["stage_idx"] = max(0, idx - 2)
async def _confirm_skip():
"""Qualtrics-style 'are you sure' dialog for an incomplete page. Returns True if the
participant chooses to continue anyway. Ported from sl-cu-nicewebrl's questionnaires.py."""
confirmed = {"v": False}
ev = asyncio.Event()
# persistent: a Quasar dialog is dismissable by ESC or a backdrop click by
# default, and dismissing this one set neither button's event, so the
# awaiting Continue handler never returned. The dialog vanished, Continue
# looked like it had done nothing, and each further click left another
# stranded dialog and coroutine behind.
with ui.dialog().props("persistent") as dialog, ui.card():
ui.markdown(
"You haven't answered everything on this page. Are you sure you want to "
"continue without answering?"
)
with ui.row():
ui.button("Go back and answer",
on_click=lambda: (dialog.close(), ev.set())).props("outline")
ui.button("Continue anyway",
on_click=lambda: (confirmed.update(v=True), dialog.close(), ev.set()))
dialog.open()
await ev.wait()
# Built fresh on every call, so without this each skipped page leaves one
# behind for the rest of the session.
try:
dialog.delete()
except Exception:
pass
return confirmed["v"]
async def _ignore_keys(e, container):
return
def _kind_for(name):
"""Which bucket a stage's screen record goes in, from its name."""
n = name.lower()
if n.startswith("harvest"):
return "harvest"
if n.startswith("night"):
return "night"
if "quiz" in n or "comprehension" in n or "comp" == n[:4]:
return "quiz"
return "questionnaire"
def _fb(name, display_fn):
"""A FeedbackStage whose screen is timed. Every stage in this file goes through here,
so one wrapper covers all of them: enter, exit, dwell, clicks and the time to the
first click land in the participant's timing CSV (see screens.py)."""
async def _timed(stage, container):
# No `log=` and no import of web_app. web_app calls screens.set_logger(log_event)
# as it loads, and `from web_app import log_event` HERE would not find that module:
# the container runs `python web_app.py`, so web_app is __main__ and the import