Download questionnaires.py from princessamygdala/TreasureHuntForTwo: direct link, hf CLI and curl.
- Browser
- Download file 36.8 kB
-
https://huggingface.co/spaces/princessamygdala/TreasureHuntForTwo/resolve/main/questionnaires.py
- Command line
-
hf download hf://spaces/princessamygdala/TreasureHuntForTwo/questionnaires.py
-
curl -L -o questionnaires.py https://huggingface.co/spaces/princessamygdala/TreasureHuntForTwo/resolve/main/questionnaires.py
36.8 kB
| """ | |
| Post-game questionnaire for TreasureHuntForTwo, appended after the main "Explore" stage. | |
| Built as ONE NiceWebRL FeedbackStage whose display_fn pages through several screens with | |
| Back/Next, exactly like the intro flow (web_app._intro_page/run_intro), so every screen | |
| supports going back to change an earlier answer. All responses land in one dict, logged like | |
| any other stage. | |
| Sections: | |
| * Strategy (free text). | |
| * Motivation / effort: self vs. the REAL in-game partner (win points / avoid losing points). | |
| * Task rating: difficulty, interest. | |
| * Belief check: did they believe the partner's payout was real? | |
| * Hypothetical (DYAD MODE ONLY): children imagine their parent playing this game; parents | |
| imagine their child playing it (app.storage.user["role"], set at ID entry, see | |
| web_app.pid_screen). Motivation/effort here cover 3 targets (themselves / their own | |
| partner / you), each for both winning points and avoiding losing points. These pages are | |
| SKIPPED unless the session is in dyad mode (?dyad_mode=yes), because a single-participant | |
| sample (e.g. the SONA pilot) has no parent/child counterpart to imagine. | |
| """ | |
| import asyncio | |
| import base64 | |
| import io | |
| import random | |
| import zlib | |
| from nicegui import app, ui | |
| import nicewebrl | |
| from nicewebrl import FeedbackStage | |
| import orders | |
| import screens | |
| import sprites | |
| def _png_src(img): | |
| """Base64 PNG data URL for a PIL image -- same technique as web_app._png_src, duplicated | |
| rather than imported to avoid a questionnaires<->web_app circular import.""" | |
| buf = io.BytesIO() | |
| img.save(buf, format="PNG") | |
| return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii") | |
| async def _ignore_keys(e, container): | |
| return | |
| def _fb(name, display_fn): | |
| return FeedbackStage(name=name, display_fn=display_fn, custom_key_press_fn=_ignore_keys) | |
| def _partner_label(caps=False): | |
| pid = app.storage.user.get("partner_id") or orders.partner_id_for( | |
| *orders.partner_seed_args(app.storage.user)) | |
| return f"YOUR PARTNER (#{pid})" if caps else f"your partner (#{pid})" | |
| def dyad_mode(): | |
| """True when this session pairs a parent with a child (?dyad_mode=yes). Off by default: | |
| a single-participant sample has no counterpart, so the hypothetical pages are skipped.""" | |
| return bool(app.storage.user.get("dyad_mode")) | |
| def _hypothetical_person(titlecase=False): | |
| who = "your child" if app.storage.user.get("role") == "p" else "your parent" | |
| return ("Your child" if app.storage.user.get("role") == "p" else "Your parent") if titlecase else who | |
| # ---------------------------------------------------------------------------- | |
| # Page primitives. Each factory returns an async render(container, answers, can_back) -> | |
| # (action, {key: value}); action is "back" or "next". `answers` (everything collected on | |
| # earlier pages this pass) is used to prefill values when the participant comes Back to a | |
| # page they've already answered. | |
| # ---------------------------------------------------------------------------- | |
| async def _confirm_skip(): | |
| """Qualtrics-style 'are you sure' dialog for an incomplete page. Returns True if the | |
| participant chooses to continue anyway.""" | |
| 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. Found and fixed on | |
| # task_pe-cu-nicewebrl's ported copy of this function; mirrored back here. | |
| 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"] | |
| def _nav_row(result, ev, can_back, is_complete=None): | |
| """Continue is always visible/clickable; if `is_complete` is given and returns False, | |
| clicking Continue asks for confirmation before proceeding (rather than blocking it).""" | |
| async def on_continue(): | |
| if is_complete is not None and not is_complete(): | |
| if not await _confirm_skip(): | |
| return | |
| result.update(action="next") | |
| ev.set() | |
| with ui.row(): | |
| if can_back: | |
| ui.button("Back", on_click=lambda: (result.update(action="back"), ev.set())).props("outline") | |
| cont = ui.button("Continue", on_click=on_continue) | |
| return cont | |
| def _slider_page(title, intro, items, lo_label=None, hi_label=None, lo=0, hi=100, start=50): | |
| """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. | |
| Continue is always clickable; if a slider hasn't been touched (and wasn't already | |
| answered on an earlier pass, e.g. after Back), clicking it asks for confirmation.""" | |
| async def render(container, answers, can_back): | |
| nicewebrl.clear_element(container) | |
| result = {"action": None} | |
| ev = asyncio.Event() | |
| sliders = {} | |
| touched = {item[0]: (item[0] in answers) 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 item in 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 | |
| with ui.column().style("width:100%; max-width:560px; margin-bottom:10px;"): | |
| ui.markdown(f"**{prompt}**") | |
| s = ui.slider(min=lo, max=hi, value=answers.get(key, start)).props("label-always") | |
| 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;") | |
| s.on_value_change(lambda e, k=key: touched.update({k: True})) | |
| sliders[key] = s | |
| _nav_row(result, ev, can_back, is_complete=lambda: all(touched.values())) | |
| await ev.wait() | |
| return result["action"], {k: int(s.value) for k, s in sliders.items()} | |
| return render | |
| def _text_page(title, prompt, key): | |
| """Continue is always clickable; if the textarea is blank, clicking it asks for | |
| confirmation before proceeding.""" | |
| async def render(container, answers, can_back): | |
| nicewebrl.clear_element(container) | |
| result = {"action": None} | |
| ev = asyncio.Event() | |
| with container.style("align-items:center; max-width:640px;"): | |
| if title: | |
| ui.markdown(f"## {title}") | |
| ui.markdown(prompt) | |
| area = ui.textarea(value=answers.get(key, "")).props("outlined autogrow").style("width:100%;") | |
| _nav_row(result, ev, can_back, is_complete=lambda: bool((area.value or "").strip())) | |
| await ev.wait() | |
| return result["action"], {key: (area.value or "").strip()} | |
| return render | |
| LIKERT5 = ["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"] | |
| def _likert_page(title, intro, items, options=LIKERT5): | |
| """items: list of (key, prompt). One radio group per item. Continue is always clickable; | |
| if any item is unanswered, clicking it asks for confirmation before proceeding.""" | |
| async def render(container, answers, can_back): | |
| nicewebrl.clear_element(container) | |
| result = {"action": None} | |
| ev = asyncio.Event() | |
| radios = {} | |
| with container.style("align-items:center; max-width:680px;"): | |
| if title: | |
| ui.markdown(f"## {title}") | |
| if intro: | |
| ui.markdown(intro) | |
| for key, prompt in items: | |
| with ui.column().style("width:100%; max-width:600px; margin-bottom:16px;"): | |
| ui.markdown(f"**{prompt}**") | |
| radios[key] = ui.radio( | |
| {o: o for o in options}, value=answers.get(key) | |
| ).props("inline color=primary") | |
| _nav_row(result, ev, can_back, | |
| is_complete=lambda: all(r.value is not None for r in radios.values())) | |
| await ev.wait() | |
| return result["action"], {k: r.value for k, r in radios.items()} | |
| return render | |
| def _to_money(points): | |
| """10-coin scale -> $1 per 100 points, capped at $6 -- same formula as web_app's own | |
| to_money, duplicated rather than imported (this module has no other dependency on | |
| web_app, and the formula is fixed to this task's point scale, not something the two | |
| copies could drift apart on by accident).""" | |
| return max(0.0, min(6.0, int(points) / 100.0)) | |
| def _belief_verb(row): | |
| """"receive" or "lose" -- which the belief-check question for this partner should ask | |
| about. By `kind` when one arrived (task_pe-cu-nicewebrl's night harvest sends "night" for | |
| a partner who only ever loses; everything else, including this task's own "hunt", is | |
| earned-for). Falls back to comparing earned/lost when `kind` is missing or empty -- an | |
| older deploy on either side that predates this field, or one the signer chose not to set.""" | |
| kind = (row.get("kind") or "").lower() | |
| if kind == "night": | |
| return "lose" | |
| if kind: | |
| return "receive" | |
| return "lose" if (row.get("lost") or 0) > (row.get("earned") or 0) else "receive" | |
| #: What each partner's game is called on screen, keyed by the `kind` the handoff carries | |
| #: (order_link.encode_partner_rows). The deferred end-of-study screen names several partners | |
| #: from BOTH tasks on one page, so "that game" would leave the participant guessing which of | |
| #: three or four games a given person belonged to. task_pe-cu-nicewebrl names its own two the | |
| #: same way on its own copy of this screen (effort_stages.question_partner_rows), so a | |
| #: participant who finishes there reads the same labels as one who finishes here. | |
| _WHERE_BY_KIND = { | |
| "hunt": "the treasure hunt", | |
| "day": "the daytime harvest", | |
| "night": "the Night Harvest", | |
| } | |
| def _row_where(row): | |
| """What to call the game this partner belonged to. An unknown/missing `kind` (an older | |
| deploy on the other side) falls back to the vague wording, which is still true.""" | |
| return (row.get("where") | |
| or _WHERE_BY_KIND.get((row.get("kind") or "").lower()) | |
| or "that game") | |
| def _belief_question(row): | |
| """The belief question for one partner, worded for the kind of partner they were. | |
| A partner you earned for is asked whether they would really receive it. The other task's | |
| night harvest partner could only ever LOSE credits, so "receive the credits you earned | |
| for them" describes a game nobody played with them. Same two sentences as | |
| task_pe-cu-nicewebrl's _belief_question, so the question does not change wording | |
| depending on which task the participant happened to finish second.""" | |
| where = _row_where(row) | |
| if _belief_verb(row) == "lose": | |
| return (f"During {where}, did you believe that **{row['id']}** would really lose " | |
| f"the credits shown on screen?") | |
| return (f"During {where}, did you believe that **{row['id']}** would really receive " | |
| f"the credits you earned for them?") | |
| def _row_avatar_image(row, size=96): | |
| """Render `row["avatar_url"]` (resolved by the caller -- a local data: URL for this | |
| task's own partner, or an https URL into the OTHER task's own /static/partner_face_<idx> | |
| route for one of theirs, see order_link.PARTNER_FACE_PATH) if there is one, else nothing. | |
| Neither task can draw the other's partner itself -- an explorer redrawn as a farmer is a | |
| different-looking person from the one the participant actually met -- so the picture is | |
| always fetched from whichever app actually owns that avatar.""" | |
| url = row.get("avatar_url") | |
| if not url: | |
| return | |
| ui.image(url).style(f"width:{size}px; height:{size}px;") | |
| def _belief_multi_page(rows): | |
| """One Yes/No belief question per partner in `rows` (met order), with that partner's | |
| picture shown beside it when row["avatar_url"] is set. Continue enables once every one is | |
| answered; no Back (matches the single-partner original's locked-once-answered behaviour, | |
| generalised to N partners). | |
| Wording matches task_pe-cu-nicewebrl's phrasing (agreed 2026-10-18) so the combined study | |
| asks the same question on both sides.""" | |
| async def render(container, answers, can_back): | |
| nicewebrl.clear_element(container) | |
| result = {"action": None} | |
| ev = asyncio.Event() | |
| radios = {} | |
| with container.style("align-items:center; max-width:680px;"): | |
| for idx, row in enumerate(rows, start=1): | |
| key = f"belief_p{idx}" | |
| with ui.column().style("align-items:center; margin-bottom:14px;"): | |
| _row_avatar_image(row) | |
| ui.markdown(_belief_question(row)) | |
| radios[key] = ui.radio( | |
| {"Yes": "Yes", "No": "No"}, value=answers.get(key) | |
| ).props("inline color=primary") | |
| _nav_row(result, ev, can_back, | |
| is_complete=lambda: all(r.value is not None for r in radios.values())) | |
| await ev.wait() | |
| return result["action"], {k: r.value for k, r in radios.items()} | |
| return render | |
| def _liking_multi_page(rows): | |
| """One 0-100 liking slider per partner in `rows`, with that partner's picture shown | |
| beside it when row["avatar_url"] is set -- same pairing/wording agreement as | |
| _belief_multi_page.""" | |
| async def render(container, answers, can_back): | |
| nicewebrl.clear_element(container) | |
| result = {"action": None} | |
| ev = asyncio.Event() | |
| sliders = {} | |
| touched = {} | |
| with container.style("align-items:center; max-width:680px;"): | |
| for idx, row in enumerate(rows, start=1): | |
| key = f"liking_p{idx}" | |
| touched[key] = key in answers | |
| with ui.column().style("align-items:center; margin-bottom:14px;"): | |
| _row_avatar_image(row) | |
| ui.markdown(f"How much did you like **{row['id']}**, the person you " | |
| f"played with in {_row_where(row)}?") | |
| with ui.column().style("width:100%; max-width:400px; align-items:center;"): | |
| s = ui.slider(min=0, max=100, | |
| value=answers.get(key, 50)).props("label-always") | |
| with ui.row().style("width:100%; justify-content:space-between;"): | |
| ui.label("Not at all").style("font-size:12px; color:#666;") | |
| ui.label("Very much").style("font-size:12px; color:#666;") | |
| s.on_value_change(lambda e, k=key: touched.update({k: True})) | |
| sliders[key] = s | |
| _nav_row(result, ev, can_back, is_complete=lambda: all(touched.values())) | |
| await ev.wait() | |
| return result["action"], {k: int(s.value) for k, s in sliders.items()} | |
| return render | |
| async def partner_checks_screen(container, rows): | |
| async with screens.watch("partner_checks", "partner_check"): | |
| return await _partner_checks_screen(container, rows) | |
| async def _partner_checks_screen(container, rows): | |
| """Belief (Yes/No) then liking (0-100 slider), one of each per partner in `rows` (met | |
| order), each with that partner's own picture -- the belief/suspicion manipulation check, | |
| covering every partner across both tasks. Returns a flat dict: belief_p#/liking_p# per | |
| position, plus partner_order (the raw ids, so a position can be traced back to who it | |
| was). {} if `rows` is empty (nothing to ask). | |
| Asked ONCE, at the very end, for whichever task the participant finishes second (see | |
| web_app.finish_experiment) -- the researcher's own instruction (2026-10-18), after briefly | |
| trying it per-task-per-game: "the belief questions should come after all games are | |
| finished even after all points are shown... it should still come with pics." `rows` is | |
| expected to carry `avatar_url` per entry (this task's own partner: a local render; the | |
| other task's partner: a URL into THAT app's own /static/partner_face_<idx> route) -- see | |
| finish_experiment and order_link.PARTNER_FACE_PATH. | |
| """ | |
| if not rows: | |
| return {} | |
| pages = [_belief_multi_page(rows), _liking_multi_page(rows)] | |
| answers = {} | |
| idx = 0 | |
| while idx < len(pages): | |
| action, vals = await pages[idx](container, answers, can_back=(idx > 0)) | |
| answers.update(vals) | |
| idx = max(0, idx - 1) if action == "back" else idx + 1 | |
| answers["partner_order"] = [r.get("id") for r in rows] | |
| return answers | |
| def post_game_questionnaire_stage(): | |
| async def _display(stage, container): | |
| p = _partner_label(caps=True) | |
| who = _hypothetical_person() | |
| who_title = _hypothetical_person(titlecase=True) | |
| hyp_intro = ( | |
| f"In the meantime, {who} played the same game. How do you think they did?\n\n" | |
| "There are no right or wrong answers here, just your best guess." | |
| ) | |
| hypothetical_pages = [ | |
| _slider_page( | |
| who_title, hyp_intro, | |
| [("hyp_motiv_win_self", f"How motivated do you think {who} would be to win points for themselves?"), | |
| ("hyp_motiv_win_partner", f"How motivated do you think {who} would be to win points for their partner?"), | |
| ("hyp_motiv_win_you", f"How motivated do you think {who} would be to win points for YOU?"), | |
| ("hyp_motiv_avoid_self", f"How motivated do you think {who} would be to avoid losing points for themselves?"), | |
| ("hyp_motiv_avoid_partner", f"How motivated do you think {who} would be to avoid losing points for their partner?"), | |
| ("hyp_motiv_avoid_you", f"How motivated do you think {who} would be to avoid losing points for YOU?")], | |
| "Not at all", "Extremely / a lot"), | |
| _slider_page( | |
| who_title, "", | |
| [("hyp_effort_win_self", f"How much effort do you think {who} would exert to win points for themselves?"), | |
| ("hyp_effort_win_partner", f"How much effort do you think {who} would exert to win points for their partner?"), | |
| ("hyp_effort_win_you", f"How much effort do you think {who} would exert to win points for YOU?"), | |
| ("hyp_effort_avoid_self", f"How much effort do you think {who} would exert to avoid losing points for themselves?"), | |
| ("hyp_effort_avoid_partner", f"How much effort do you think {who} would exert to avoid losing points for their partner?"), | |
| ("hyp_effort_avoid_you", f"How much effort do you think {who} would exert to avoid losing points for YOU?")], | |
| "Not at all", "Extremely / a lot"), | |
| _slider_page( | |
| 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")]), | |
| ] | |
| # Shuffled per participant, same reason and construction as the TriPM fix: a fixed | |
| # order puts the same item last for everyone, and the key travels with its own item, | |
| # so the three future_* columns still score what they always did. | |
| future_items = [ | |
| ("future_clear_goal", "When I think about my future, I can see clearly what " | |
| "I want to achieve."), | |
| ("future_imagine", "I can imagine what my future will be like."), | |
| ("future_unclear", "I can't get a clear picture of my future even when I try."), | |
| ] | |
| rng = random.Random(zlib.crc32(f"future|{app.storage.user.get('pid') or 'anon'}".encode())) | |
| rng.shuffle(future_items) | |
| pages = [ | |
| _text_page(None, "What strategy (or strategies) did you use during " | |
| "the learning task?", "strategy_text"), | |
| _slider_page( | |
| None, "Think back to the task you just completed. Please indicate how " | |
| "motivated you were, for each statement below.", | |
| [("motiv_win_self", "How motivated were you to win points for YOURSELF?"), | |
| ("motiv_win_partner", f"How motivated were you to win points for {p}?"), | |
| ("motiv_avoid_self", "How motivated were you to avoid losing points for YOURSELF?"), | |
| ("motiv_avoid_partner", f"How motivated were you to avoid losing points for {p}?")], | |
| "Not at all motivated", "Extremely motivated"), | |
| _slider_page( | |
| None, "Please indicate how much effort each statement below required.", | |
| [("effort_win_self", "How much effort did you exert to win points for YOURSELF?"), | |
| ("effort_win_partner", f"How much effort did you exert to win points for {p}?"), | |
| ("effort_avoid_self", "How much effort did you exert to avoid losing points for YOURSELF?"), | |
| ("effort_avoid_partner", f"How much effort did you exert to avoid losing points for {p}?")], | |
| "Required no effort", "Required a lot of effort"), | |
| _slider_page( | |
| None, "Please indicate how each statement below applies to the task you just " | |
| "completed.", | |
| [("task_difficulty", "How easy or difficult was the task?", | |
| "Very easy", "Very difficult"), | |
| ("task_interest", "How boring or interesting was the task?", | |
| "Very boring", "Very interesting")]), | |
| *(hypothetical_pages if dyad_mode() else []), | |
| _likert_page( | |
| None, "Please indicate how much you agree with each statement below.", | |
| future_items), | |
| ] | |
| answers = {} | |
| idx = 0 | |
| visits = {} | |
| while idx < len(pages): | |
| # A page can be revisited with Back, so each visit is its own screen record and | |
| # the name carries the visit number. Without that a revisit would look like one | |
| # very long page. | |
| visits[idx] = visits.get(idx, 0) + 1 | |
| name = f"post_q_p{idx:02d}" + ("" if visits[idx] == 1 else f"_v{visits[idx]}") | |
| async with screens.watch(name, "questionnaire", index=idx) as _s: | |
| action, vals = await pages[idx](container, answers, can_back=(idx > 0)) | |
| _s["action"] = action | |
| answers.update(vals) | |
| idx = max(0, idx - 1) if action == "back" else idx + 1 | |
| # Belief/liking check for THIS task's own partner: deferred to the very end of the | |
| # study for a combined-study participant (see web_app.finish_experiment, which asks | |
| # it there alongside the other task's partner), asked right here for a | |
| # standalone/single-task session. Briefly moved to run right after each task's own | |
| # game instead (avatar shown there), then reverted the same day on the researcher's | |
| # own instruction (2026-10-18): "the belief questions should come after all games are | |
| # finished even after all points are shown... it should still come with pics." -- | |
| # so the picture moved to the deferred screen with it (partner_checks_screen). | |
| if app.storage.user.get("task_position") in (1, 2): | |
| app.storage.user["_belief_check_deferred"] = True | |
| else: | |
| partner_idx = app.storage.user.get("partner_avatar_idx") | |
| own_row = { | |
| "id": str(app.storage.user.get("partner_id") or | |
| orders.partner_id_for(*orders.partner_seed_args(app.storage.user))), | |
| "earned": _to_money(app.storage.user.get("partner_points", 0)), | |
| "lost": 0.0, "kind": "hunt", | |
| "where": "the treasure hunt", | |
| "avatar_url": (_png_src(sprites.draw_partner_avatar_framed(partner_idx)) | |
| if partner_idx is not None else None), | |
| } | |
| answers.update(await partner_checks_screen(container, [own_row])) | |
| return dict(measure="post_game_questionnaire", | |
| dyad_mode=int(dyad_mode()), | |
| who=(who if dyad_mode() else ""), | |
| future_item_order=[k for k, _ in future_items], **answers) | |
| return _fb("PostTask_Questionnaire", _display) | |
| # ---------------------------------------------------------------------------- | |
| # Combined-SONA-study screens only (?study=sona; see order_link.py and web_app.py's | |
| # finish_experiment()). Ported from task_pe-cu-nicewebrl/questionnaires.py: consent runs once, | |
| # at the very start, for whichever task the participant lands on first; demographics + TriPM | |
| # run once, at the very end, for whichever task the participant finishes second -- general | |
| # self-report measures that belong to the combined study, not to either task specifically. | |
| # Plain async functions (not _fb-wrapped Stages) so they can be awaited directly from wherever | |
| # each app's own flow decides "am I first / am I second", rather than living in the fixed | |
| # per-task stage list. | |
| # ---------------------------------------------------------------------------- | |
| import content_items as CI | |
| #: 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] | |
| async def consent_screen(container): | |
| async with screens.watch("consent", "consent"): | |
| return await _consent_screen(container) | |
| async def _consent_screen(container): | |
| """The combined-study consent form, before anything else. 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(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;"): | |
| 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"] | |
| async def demographics_screen(container): | |
| async with screens.watch("demographics", "demographics"): | |
| return await _demographics_screen(container) | |
| async def _demographics_screen(container): | |
| """Demographics, from content/demographics.txt. Returns a flat dict of answers, or | |
| {"skipped": ...} if no items are supplied.""" | |
| items = CI.demographics_items() | |
| if not items: | |
| return dict(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 above: 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("## A few questions about you") | |
| 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;") | |
| t = it["type"] | |
| if t == "number": | |
| w = ui.number().props("outlined").style("width:100%;") | |
| elif t == "choice": | |
| # The one control with its own inner padding, like the TriPM scale. | |
| w = (ui.radio(it["options"]).props("color=primary") | |
| .style("margin:0 0 0 -10px; padding:0;")) | |
| elif t == "dropdown": | |
| w = ui.select(it["options"]).props("outlined").style("width:100%;") | |
| elif t == "multi": | |
| w = ui.select(it["options"], multiple=True).props( | |
| "outlined use-chips").style("width:100%;") | |
| elif t == "scale": | |
| w = ui.slider(min=0, max=100, value=50).props("label-always") | |
| else: | |
| w = ui.input().props("outlined").style("width:100%;") | |
| widgets[it["key"]] = (w, t) | |
| 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": | |
| 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) | |
| return res | |
| async def tripm_screen(container): | |
| async with screens.watch("tripm", "tripm"): | |
| return await _tripm_screen(container) | |
| async def _tripm_screen(container): | |
| """The Triarchic Psychopathy Measure on a single scrolling page. Returns a dict of | |
| {tripm_key: 0..3, item_order: [...]}, or {"skipped": ...} if no items are supplied.""" | |
| # 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(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, and a short statement ended up on the same line as the scale | |
| # above it, so the list read as a different layout for every statement length. | |
| # Matches task_pe-cu-nicewebrl's copy of this page. | |
| 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"⚠️ **{len(missing)} of {len(items)} 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(item_order=[k for k, _ in items], **answers) | |
| _PAYMENT_METHODS = ["Venmo", "Amazon Gift Card", "PayPal"] | |
| async def payment_screen(container, total_bonus_usd): | |
| async with screens.watch("payment", "payment"): | |
| return await _payment_screen(container, total_bonus_usd) | |
| async def _payment_screen(container, total_bonus_usd): | |
| """Collect where to send the combined-study real-money bonus -- email + payment method -- | |
| shown once, at the very end, on whichever task the participant finishes SECOND (matches the | |
| consent form's payment-mechanism sentence). Returns {"email": str, "method": str}. | |
| This screen only collects and validates the answers; it does not decide the amount (the | |
| caller computes `total_bonus_usd` from both tasks' coin totals) and does not write anywhere | |
| -- the caller is responsible for pushing the result to the separate payment store | |
| (gitlab_save.submit_payment), keyed by a payment-only pseudonym, never alongside research | |
| data or this task's own pid. | |
| """ | |
| nicewebrl.clear_element(container) | |
| done = asyncio.Event() | |
| with container.style("align-items:center; max-width:520px;"): | |
| ui.markdown("## One last thing: how should we send your bonus?") | |
| ui.markdown( | |
| f"Your total bonus across both tasks is **${total_bonus_usd:.2f}**. We need an " | |
| "email address and a payment method to send it. This is stored separately from " | |
| "your survey/game responses, linked to them only by a code your research team " | |
| "cannot reverse without a second, separate key -- matching what the consent form " | |
| "promised about your SONA ID." | |
| ) | |
| email_w = ui.input("Email address").props("outlined type=email").style("width:100%;") | |
| method_w = ui.radio(_PAYMENT_METHODS).props("color=primary") | |
| warn = ui.markdown("") | |
| def submit(): | |
| email = (email_w.value or "").strip() | |
| if "@" not in email or "." not in email.split("@")[-1]: | |
| warn.set_content("⚠️ **Please enter a valid email address.**") | |
| return | |
| if method_w.value not in _PAYMENT_METHODS: | |
| warn.set_content("⚠️ **Please choose a payment method.**") | |
| return | |
| done.set() | |
| ui.button("Submit", on_click=submit).props("color=primary size=lg") | |
| await done.wait() | |
| return {"email": (email_w.value or "").strip(), "method": method_w.value} | |