Skip to content

sweetbean

AssetStimulusSpec

Bases: _BaseStimulusSpec

Rendered visual asset stimulus (image/gif/other browser image asset).

Source code in sweetbean/stimulus_spec/spec.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
class AssetStimulusSpec(_BaseStimulusSpec):
    """Rendered visual asset stimulus (image/gif/other browser image asset)."""

    kind: Literal["asset"] = "asset"
    asset_ref: str = Field(
        description=(
            "Asset URL/path, or a timeline placeholder like `{{asset_path_col}}` "
            "resolved from the current CSV row."
        )
    )
    object_fit: Literal["contain", "cover", "fill", "none", "scale-down"] | None = Field(
        default=None,
        description=(
            "Optional CSS object-fit. If omitted, defaults to contain."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )

Block

A block of stimuli (for example, an instruction, training, or test block)

Source code in sweetbean/block.py
 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
class Block:
    """
    A block of stimuli (for example, an instruction, training, or test block)
    """

    stimuli: List[Any] = []
    js = ""
    timeline = None
    extensions: Dict = {}

    def __init__(self, stimuli, timeline=None):
        """
        Arguments:
            stimuli: a list of stimuli
            timeline: a list of dictionaries with the name of the timeline variables
        """
        if timeline is None:
            timeline = []
        self.stimuli = stimuli
        self.timeline = timeline
        self.extensions["touch_layouts"] = []

    def to_js(self, template_timeline_token=None):
        """
        Build jsPsych trial source for this block.

        If ``template_timeline_token`` is set (see :meth:`Experiment.compile`), the
        timeline data is omitted here and injected later via
        :meth:`Experiment.to_js_string_from_template` for faster multi-condition builds.
        """
        self.js = "{timeline: ["
        for s in self.stimuli:
            self.extensions["touch_layouts"].append(s.create_touch_layout())
            s.to_js()
            self.js += s.js + ","
        self.js = self.js[:-1]
        if isinstance(self.timeline, CodeVariable):
            if template_timeline_token is not None:
                raise ValueError(
                    "template_timeline_token is not supported when timeline is a CodeVariable"
                )
            self.js += f"], timeline_variables: {self.timeline.name}" + "}"
        elif template_timeline_token is not None:
            self.js += f"], timeline_variables: {template_timeline_token}" + "}"
        else:
            self.js += f"], timeline_variables: {sb_to_js(self.timeline)}" + "}"

    def to_image(self, path, data, sequence=True, timeline_idx="random", zoom_factor=3):
        """
        Create an image of the stimuli sequence of the block
        Arguments:
            path: the path to save the image
            data: if needed data can be passed in for the stimuli
                (for example, correct if the sequence contains a feedback stimulus)
            sequence: if True, the images are combined into one image else they are
                stored separately
            timeline_idx: the index of the timeline element to use, if "random" a random
                timeline element is chosen, if none, the whole timeline is shown
            zoom_factor: the factor by which the images are zoomed (can be a list if
                different zoom factors for each stimulus are needed)

        """

        data_in = []
        shared_variables = {}
        for s in self.stimuli:
            _shared_variables = s.return_shared_variables()
            for s_key in _shared_variables:
                shared_variables[s_key] = _shared_variables[s_key].value
        if not self.timeline:
            timeline = [{}]
        else:
            timeline = self.timeline

        if timeline_idx == "random":
            timeline = [timeline[random.randint(0, len(timeline) - 1)]]
        elif timeline_idx is not None:
            timeline = [timeline[timeline_idx]]

        k = 0
        images = []
        durations = []
        for t in timeline:
            for s in self.stimuli:
                if s.arg["duration"] == 0:
                    continue
                html = HTML_PREAMBLE
                html += "jsPsych = initJsPsych();\n"
                html += "trials = [\n"
                s._prepare_args_l(t, data_in, shared_variables)
                s.to_js_for_image()
                html += s.js
                html += "];\n"
                html += "jsPsych.run(trials);"
                html += HTML_APPENDIX
                image = asyncio.run(render_html_to_image(html))
                duration = s.l_args["duration"] if "duration" in s.l_args else 0
                images.append(image)
                durations.append(duration)
                if data and k < len(data):
                    data_in.append(data[k])
                k += 1

        if not sequence:
            if path:
                for idx, i in enumerate(images):
                    i.save(f"{path}/stimulus_{idx}.png")
                return
            return images, durations
        result_image = create_stimulus_sequence(
            images, durations, zoom_factor=zoom_factor
        )
        if path:
            result_image.save(path)
            return
        return result_image

__init__(stimuli, timeline=None)

Parameters:

Name Type Description Default
stimuli

a list of stimuli

required
timeline

a list of dictionaries with the name of the timeline variables

None
Source code in sweetbean/block.py
46
47
48
49
50
51
52
53
54
55
56
def __init__(self, stimuli, timeline=None):
    """
    Arguments:
        stimuli: a list of stimuli
        timeline: a list of dictionaries with the name of the timeline variables
    """
    if timeline is None:
        timeline = []
    self.stimuli = stimuli
    self.timeline = timeline
    self.extensions["touch_layouts"] = []

to_image(path, data, sequence=True, timeline_idx='random', zoom_factor=3)

Create an image of the stimuli sequence of the block Arguments: path: the path to save the image data: if needed data can be passed in for the stimuli (for example, correct if the sequence contains a feedback stimulus) sequence: if True, the images are combined into one image else they are stored separately timeline_idx: the index of the timeline element to use, if "random" a random timeline element is chosen, if none, the whole timeline is shown zoom_factor: the factor by which the images are zoomed (can be a list if different zoom factors for each stimulus are needed)

Source code in sweetbean/block.py
 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
def to_image(self, path, data, sequence=True, timeline_idx="random", zoom_factor=3):
    """
    Create an image of the stimuli sequence of the block
    Arguments:
        path: the path to save the image
        data: if needed data can be passed in for the stimuli
            (for example, correct if the sequence contains a feedback stimulus)
        sequence: if True, the images are combined into one image else they are
            stored separately
        timeline_idx: the index of the timeline element to use, if "random" a random
            timeline element is chosen, if none, the whole timeline is shown
        zoom_factor: the factor by which the images are zoomed (can be a list if
            different zoom factors for each stimulus are needed)

    """

    data_in = []
    shared_variables = {}
    for s in self.stimuli:
        _shared_variables = s.return_shared_variables()
        for s_key in _shared_variables:
            shared_variables[s_key] = _shared_variables[s_key].value
    if not self.timeline:
        timeline = [{}]
    else:
        timeline = self.timeline

    if timeline_idx == "random":
        timeline = [timeline[random.randint(0, len(timeline) - 1)]]
    elif timeline_idx is not None:
        timeline = [timeline[timeline_idx]]

    k = 0
    images = []
    durations = []
    for t in timeline:
        for s in self.stimuli:
            if s.arg["duration"] == 0:
                continue
            html = HTML_PREAMBLE
            html += "jsPsych = initJsPsych();\n"
            html += "trials = [\n"
            s._prepare_args_l(t, data_in, shared_variables)
            s.to_js_for_image()
            html += s.js
            html += "];\n"
            html += "jsPsych.run(trials);"
            html += HTML_APPENDIX
            image = asyncio.run(render_html_to_image(html))
            duration = s.l_args["duration"] if "duration" in s.l_args else 0
            images.append(image)
            durations.append(duration)
            if data and k < len(data):
                data_in.append(data[k])
            k += 1

    if not sequence:
        if path:
            for idx, i in enumerate(images):
                i.save(f"{path}/stimulus_{idx}.png")
            return
        return images, durations
    result_image = create_stimulus_sequence(
        images, durations, zoom_factor=zoom_factor
    )
    if path:
        result_image.save(path)
        return
    return result_image

to_js(template_timeline_token=None)

Build jsPsych trial source for this block.

If template_timeline_token is set (see :meth:Experiment.compile), the timeline data is omitted here and injected later via :meth:Experiment.to_js_string_from_template for faster multi-condition builds.

Source code in sweetbean/block.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def to_js(self, template_timeline_token=None):
    """
    Build jsPsych trial source for this block.

    If ``template_timeline_token`` is set (see :meth:`Experiment.compile`), the
    timeline data is omitted here and injected later via
    :meth:`Experiment.to_js_string_from_template` for faster multi-condition builds.
    """
    self.js = "{timeline: ["
    for s in self.stimuli:
        self.extensions["touch_layouts"].append(s.create_touch_layout())
        s.to_js()
        self.js += s.js + ","
    self.js = self.js[:-1]
    if isinstance(self.timeline, CodeVariable):
        if template_timeline_token is not None:
            raise ValueError(
                "template_timeline_token is not supported when timeline is a CodeVariable"
            )
        self.js += f"], timeline_variables: {self.timeline.name}" + "}"
    elif template_timeline_token is not None:
        self.js += f"], timeline_variables: {template_timeline_token}" + "}"
    else:
        self.js += f"], timeline_variables: {sb_to_js(self.timeline)}" + "}"

BotDetection

Bases: Protection

Bot/agent detection layer.

Source code in sweetbean/protection/bot_detection.py
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
class BotDetection(Protection):
    """Bot/agent detection layer."""

    name = "bot_detection"

    def __init__(
        self,
        enable_countermeasures: bool = True,
        track_sliders: bool = True,
    ):
        """
        Arguments:
            enable_countermeasures: when False, only passive logging runs —
                no honeypot DOM, no clipboard/devtools blocking, no inline
                traps. Useful for pilots / debugging.
            track_sliders: when True, install a document-level ``input``
                listener that calls ``BotDetection.recordSliderMove()`` for
                every range slider, so per-trial slider stats are captured
                without modifying any stimulus class.
        """
        self.enable_countermeasures = enable_countermeasures
        self.track_sliders = track_sliders

    def runtime_js(self) -> str:
        return _ASSET_PATH.read_text(encoding="utf-8")

    def init_js(self) -> str:
        cm = "true" if self.enable_countermeasures else "false"
        js = f"BotDetection.initialize({cm});"
        if self.track_sliders:
            js += (
                "document.addEventListener('input',function(e){"
                "if(e.target&&e.target.type==='range'){"
                "if(window.BotDetection){BotDetection.recordSliderMove();}}"
                "},true);"
            )
        return js

    def summary_js(self) -> str:
        return "BotDetection.getSummary()"

    def on_load_for_stimulus(self, stimulus) -> str:
        return "if(window.BotDetection){BotDetection.resetTrialTracking();}"

    def on_finish_for_stimulus(self, stimulus) -> str:
        return (
            "if(window.BotDetection){"
            "if(typeof data.rt==='number'){BotDetection.addRT(data.rt);}"
            "Object.assign(data,BotDetection.getTrialInteractionData());"
            "Object.assign(data,BotDetection.getTrialLevelSummary());"
            "}"
        )

__init__(enable_countermeasures=True, track_sliders=True)

Parameters:

Name Type Description Default
enable_countermeasures bool

when False, only passive logging runs — no honeypot DOM, no clipboard/devtools blocking, no inline traps. Useful for pilots / debugging.

True
track_sliders bool

when True, install a document-level input listener that calls BotDetection.recordSliderMove() for every range slider, so per-trial slider stats are captured without modifying any stimulus class.

True
Source code in sweetbean/protection/bot_detection.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def __init__(
    self,
    enable_countermeasures: bool = True,
    track_sliders: bool = True,
):
    """
    Arguments:
        enable_countermeasures: when False, only passive logging runs —
            no honeypot DOM, no clipboard/devtools blocking, no inline
            traps. Useful for pilots / debugging.
        track_sliders: when True, install a document-level ``input``
            listener that calls ``BotDetection.recordSliderMove()`` for
            every range slider, so per-trial slider stats are captured
            without modifying any stimulus class.
    """
    self.enable_countermeasures = enable_countermeasures
    self.track_sliders = track_sliders

Experiment

An experiment consisting of blocks

Source code in sweetbean/experiment.py
 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
class Experiment:
    """
    An experiment consisting of blocks
    """

    blocks: List[Block] = []
    js = ""

    def __init__(self, blocks: List[Block], protections=None):
        """
        Arguments:
            blocks: a list of blocks
            protections: optional list of :class:`sweetbean.protection.Protection`
                instances. Each protection embeds its own JS into the compiled
                experiment at well-defined hook points (head, runtime, init,
                per-trial on_load/on_finish, summary). See
                :mod:`sweetbean.protection` for the contract.
        """
        self.blocks = blocks
        self.protections = list(protections) if protections else []

    def _protection_head_assets(self) -> str:
        return "".join(p.head_assets() for p in self.protections if p.head_assets())

    def _protection_runtime_js(self) -> str:
        parts = [p.runtime_js() for p in self.protections]
        return "\n".join(part for part in parts if part)

    def _protection_init_js(self) -> str:
        parts = [p.init_js() for p in self.protections]
        return "\n".join(part for part in parts if part)

    def _protection_summary_js(self) -> str:
        """JS statement that adds each protection's summary onto every saved
        trial row via ``jsPsych.data.addProperties``. Empty if no protection
        emits a summary."""
        entries = []
        for p in self.protections:
            expr = p.summary_js()
            if expr:
                entries.append(f"{p.name}:{expr}")
        if not entries:
            return ""
        return "jsPsych.data.addProperties({" + ",".join(entries) + "});"

    def to_js(self, path_local_download=None):
        from sweetbean.protection._context import set_active_protections

        self.js = ""
        shared_variables = {}
        extensions = ""
        # Protection runtime libs go FIRST so window.<Lib> is in scope by the
        # time anything else runs. Active-protections context is set BEFORE
        # block.to_js so per-trial hooks (on_load/on_finish) are emitted.
        runtime = self._protection_runtime_js()
        if runtime:
            self.js += runtime + "\n"
        set_active_protections(self.protections)
        try:
            for b in self.blocks:
                b.to_js()
                extensions += _initialize_extensions(b.extensions)
                for s in b.stimuli:
                    shared_variables.update(s.return_shared_variables())
            for s_key in shared_variables:
                self.js += f"{shared_variables[s_key].set()}\n"
            summary = self._protection_summary_js()
            init = self._protection_init_js()
            if path_local_download:
                if path_local_download.endswith(".json"):
                    save_call = (
                        f"jsPsych.data.get().localSave('json',"
                        f"'{path_local_download}')"
                    )
                elif path_local_download.endswith(".csv"):
                    save_call = (
                        f"jsPsych.data.get().localSave('csv',"
                        f"'{path_local_download}')"
                    )
                else:
                    raise Exception(
                        "Unknown file format for local download. "
                        "Only .json or .csv are supported."
                    )
                on_finish_body = f"{summary}{save_call}"
                opts = f"{{on_finish:()=>{{{on_finish_body}}}}}"
                if extensions == "":
                    self.js += f"jsPsych = initJsPsych({opts});\n"
                else:
                    self.js += f"jsPsych = initJsPsych({extensions}{opts});\n"
            elif summary:
                opts = f"{{on_finish:()=>{{{summary}}}}}"
                if extensions == "":
                    self.js += f"jsPsych = initJsPsych({opts});\n"
                else:
                    self.js += f"jsPsych = initJsPsych({extensions}{opts});\n"
            else:
                self.js += f"jsPsych = initJsPsych({extensions});\n"
            if init:
                self.js += init + "\n"
            self.js += "trials = [\n"
            for b in self.blocks:
                self.js += b.js
                self.js += ","
            self.js = self.js[:-1] + "]\n"
            self.js += ";jsPsych.run(trials)"
        finally:
            set_active_protections([])

    def to_html(self, path, path_local_download=None):
        """
        Save the experiment to an HTML file
        """
        self.to_js(path_local_download)
        # Protection head_assets() (extra <link>/<script> tags) are emitted
        # right after the preamble's opening <script>; runtime_js (e.g. the
        # inlined BotDetection IIFE) is already part of self.js, prepended
        # in to_js so it executes before initJsPsych.
        head_assets = self._protection_head_assets()
        html = HTML_PREAMBLE
        if head_assets:
            html += "</script>\n" + head_assets + "<script>\n"
        html += f"{self.js}" + HTML_APPENDIX

        with open(path, "w") as f:
            f.write(html)

    def to_js_string(self, as_function=True, is_async=True):
        """
        Return the experiment as a JavaScript string
        """
        from sweetbean.protection._context import set_active_protections

        text = FUNCTION_PREAMBLE(is_async) if as_function else ""
        runtime = self._protection_runtime_js()
        if runtime:
            text += runtime + "\n"
        extensions = ""
        set_active_protections(self.protections)
        try:
            for b in self.blocks:
                b.to_js()
                extensions += _initialize_extensions(b.extensions)
                for s in b.stimuli:
                    shared_variables = s.return_shared_variables()
                    for s_key in shared_variables:
                        text += f"{shared_variables[s_key].set()}\n"
            text += f"const jsPsych = initJsPsych({extensions})\n"
            init = self._protection_init_js()
            if init:
                text += init + "\n"
            text += "const trials = [\n"
            for b in self.blocks:
                text += b.js
                text += ","
            text = text[:-1] + "]\n"
        finally:
            set_active_protections([])
        # Summary lands on every saved row by running addProperties AFTER
        # jsPsych.run completes — that's why it goes into post_run_js, not
        # initJsPsych's on_finish (which would race with the run loop in
        # the function-style output).
        post_run = self._protection_summary_js()
        if as_function:
            text += FUNCTION_APPENDIX(is_async, post_run)
        else:
            text += TEXT_APPENDIX(is_async, post_run)
        return text

    def compile(self, as_function=True, is_async=True):
        """
        Build JavaScript once: stimulus graphs and ``jsPsych`` setup are emitted;
        each block's ``timeline_variables`` is a placeholder string that
        :meth:`to_js_string_from_template` replaces with per-condition data.

        Use when multiple conditions share the same stimulus structure (e.g. Firebase
        payloads) so timelines are "injected" without re-running Transcrypt per condition.
        """
        from sweetbean.protection._context import set_active_protections

        text = FUNCTION_PREAMBLE(is_async) if as_function else ""
        runtime = self._protection_runtime_js()
        if runtime:
            text += runtime + "\n"
        extensions = ""
        set_active_protections(self.protections)
        try:
            for bi, b in enumerate(self.blocks):
                if isinstance(b.timeline, CodeVariable):
                    b.to_js()
                else:
                    b.to_js(template_timeline_token=_timeline_placeholder(bi))
                extensions += _initialize_extensions(b.extensions)
                for s in b.stimuli:
                    shared_variables = s.return_shared_variables()
                    for s_key in shared_variables:
                        text += f"{shared_variables[s_key].set()}\n"
            text += f"const jsPsych = initJsPsych({extensions})\n"
            init = self._protection_init_js()
            if init:
                text += init + "\n"
            text += "const trials = [\n"
            for b in self.blocks:
                text += b.js
                text += ","
            text = text[:-1] + "]\n"
        finally:
            set_active_protections([])
        post_run = self._protection_summary_js()
        if as_function:
            text += FUNCTION_APPENDIX(is_async, post_run)
        else:
            text += TEXT_APPENDIX(is_async, post_run)
        return text

    @staticmethod
    def to_js_string_from_template(template: str, timelines: List[Any]) -> str:
        """
        Replace each ``__SB_TIMELINE_PLACEHOLDER_i__`` in *template* with the JS literal
        for ``timelines[i]`` (from :func:`sweetbean.util.parse.to_js`).

        *timelines* must have one entry per block that used a placeholder in
        :meth:`compile` (same order as ``Experiment.blocks``). Blocks compiled with
        :class:`~sweetbean.variable.CodeVariable` timelines embed real JS and are not
        listed here — pass the full list of block timelines, including those unchanged.
        """
        from sweetbean.util.parse import to_js as sb_to_js

        def _repl(m: re.Match) -> str:
            idx = int(m.group(1))
            if idx < 0 or idx >= len(timelines):
                raise ValueError(
                    f"Template references timeline placeholder {idx}; "
                    f"got {len(timelines)} timeline(s)"
                )
            return sb_to_js(timelines[idx])

        return _TIMELINE_PLACEHOLDER_RE.sub(_repl, template)

    def run_on_language(
        self,
        get_input=input,
        multi_turn=False,
        preamble="",
        data=None,
        response_open_token="<<",
        response_close_token=">>",
    ):
        """
        Run the experiment in a language

        Arguments:
            get_input: a function to get input from the response
                (for example, a function that prompts language model and returns the response)
            multi_turn: a boolean to allow multi-turn input.
                If True, the prompts are not concatenated.
            preamble: a string to be added before the prompts
            data: a list of dictionaries with the data.
                This will rerun the experiment with the data as input.
                If the data is not provided for the full experiment,
                the rest of it will be simulated with the get_input function.
            response_open_token: token used in prompt templates for "answer starts here".
            response_close_token: token appended after model/user answer in stored prompts.
        """
        out_data = []
        prompts = []
        shared_variables = {}
        for b in self.blocks:
            for s in b.stimuli:
                _shared_variables = s.return_shared_variables()
                for s_key in _shared_variables:
                    shared_variables[s_key] = _shared_variables[s_key].value
        datum_index = 0
        for b in self.blocks:
            timeline = b.timeline
            stimuli = b.stimuli
            if not timeline:
                timeline = [{}]
            for timeline_element in timeline:
                out_data, prompts, shared_variables, datum_index = run_stimuli(
                    stimuli,
                    timeline_element,
                    out_data,
                    shared_variables,
                    prompts,
                    get_input,
                    multi_turn,
                    datum_index,
                    data,
                    preamble,
                    response_open_token,
                    response_close_token,
                )
        return out_data, prompts

__init__(blocks, protections=None)

Parameters:

Name Type Description Default
blocks List[Block]

a list of blocks

required
protections

optional list of :class:sweetbean.protection.Protection instances. Each protection embeds its own JS into the compiled experiment at well-defined hook points (head, runtime, init, per-trial on_load/on_finish, summary). See :mod:sweetbean.protection for the contract.

None
Source code in sweetbean/experiment.py
30
31
32
33
34
35
36
37
38
39
40
41
def __init__(self, blocks: List[Block], protections=None):
    """
    Arguments:
        blocks: a list of blocks
        protections: optional list of :class:`sweetbean.protection.Protection`
            instances. Each protection embeds its own JS into the compiled
            experiment at well-defined hook points (head, runtime, init,
            per-trial on_load/on_finish, summary). See
            :mod:`sweetbean.protection` for the contract.
    """
    self.blocks = blocks
    self.protections = list(protections) if protections else []

compile(as_function=True, is_async=True)

Build JavaScript once: stimulus graphs and jsPsych setup are emitted; each block's timeline_variables is a placeholder string that :meth:to_js_string_from_template replaces with per-condition data.

Use when multiple conditions share the same stimulus structure (e.g. Firebase payloads) so timelines are "injected" without re-running Transcrypt per condition.

Source code in sweetbean/experiment.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def compile(self, as_function=True, is_async=True):
    """
    Build JavaScript once: stimulus graphs and ``jsPsych`` setup are emitted;
    each block's ``timeline_variables`` is a placeholder string that
    :meth:`to_js_string_from_template` replaces with per-condition data.

    Use when multiple conditions share the same stimulus structure (e.g. Firebase
    payloads) so timelines are "injected" without re-running Transcrypt per condition.
    """
    from sweetbean.protection._context import set_active_protections

    text = FUNCTION_PREAMBLE(is_async) if as_function else ""
    runtime = self._protection_runtime_js()
    if runtime:
        text += runtime + "\n"
    extensions = ""
    set_active_protections(self.protections)
    try:
        for bi, b in enumerate(self.blocks):
            if isinstance(b.timeline, CodeVariable):
                b.to_js()
            else:
                b.to_js(template_timeline_token=_timeline_placeholder(bi))
            extensions += _initialize_extensions(b.extensions)
            for s in b.stimuli:
                shared_variables = s.return_shared_variables()
                for s_key in shared_variables:
                    text += f"{shared_variables[s_key].set()}\n"
        text += f"const jsPsych = initJsPsych({extensions})\n"
        init = self._protection_init_js()
        if init:
            text += init + "\n"
        text += "const trials = [\n"
        for b in self.blocks:
            text += b.js
            text += ","
        text = text[:-1] + "]\n"
    finally:
        set_active_protections([])
    post_run = self._protection_summary_js()
    if as_function:
        text += FUNCTION_APPENDIX(is_async, post_run)
    else:
        text += TEXT_APPENDIX(is_async, post_run)
    return text

run_on_language(get_input=input, multi_turn=False, preamble='', data=None, response_open_token='<<', response_close_token='>>')

Run the experiment in a language

Parameters:

Name Type Description Default
get_input

a function to get input from the response (for example, a function that prompts language model and returns the response)

input
multi_turn

a boolean to allow multi-turn input. If True, the prompts are not concatenated.

False
preamble

a string to be added before the prompts

''
data

a list of dictionaries with the data. This will rerun the experiment with the data as input. If the data is not provided for the full experiment, the rest of it will be simulated with the get_input function.

None
response_open_token

token used in prompt templates for "answer starts here".

'<<'
response_close_token

token appended after model/user answer in stored prompts.

'>>'
Source code in sweetbean/experiment.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def run_on_language(
    self,
    get_input=input,
    multi_turn=False,
    preamble="",
    data=None,
    response_open_token="<<",
    response_close_token=">>",
):
    """
    Run the experiment in a language

    Arguments:
        get_input: a function to get input from the response
            (for example, a function that prompts language model and returns the response)
        multi_turn: a boolean to allow multi-turn input.
            If True, the prompts are not concatenated.
        preamble: a string to be added before the prompts
        data: a list of dictionaries with the data.
            This will rerun the experiment with the data as input.
            If the data is not provided for the full experiment,
            the rest of it will be simulated with the get_input function.
        response_open_token: token used in prompt templates for "answer starts here".
        response_close_token: token appended after model/user answer in stored prompts.
    """
    out_data = []
    prompts = []
    shared_variables = {}
    for b in self.blocks:
        for s in b.stimuli:
            _shared_variables = s.return_shared_variables()
            for s_key in _shared_variables:
                shared_variables[s_key] = _shared_variables[s_key].value
    datum_index = 0
    for b in self.blocks:
        timeline = b.timeline
        stimuli = b.stimuli
        if not timeline:
            timeline = [{}]
        for timeline_element in timeline:
            out_data, prompts, shared_variables, datum_index = run_stimuli(
                stimuli,
                timeline_element,
                out_data,
                shared_variables,
                prompts,
                get_input,
                multi_turn,
                datum_index,
                data,
                preamble,
                response_open_token,
                response_close_token,
            )
    return out_data, prompts

to_html(path, path_local_download=None)

Save the experiment to an HTML file

Source code in sweetbean/experiment.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def to_html(self, path, path_local_download=None):
    """
    Save the experiment to an HTML file
    """
    self.to_js(path_local_download)
    # Protection head_assets() (extra <link>/<script> tags) are emitted
    # right after the preamble's opening <script>; runtime_js (e.g. the
    # inlined BotDetection IIFE) is already part of self.js, prepended
    # in to_js so it executes before initJsPsych.
    head_assets = self._protection_head_assets()
    html = HTML_PREAMBLE
    if head_assets:
        html += "</script>\n" + head_assets + "<script>\n"
    html += f"{self.js}" + HTML_APPENDIX

    with open(path, "w") as f:
        f.write(html)

to_js_string(as_function=True, is_async=True)

Return the experiment as a JavaScript string

Source code in sweetbean/experiment.py
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
185
186
187
188
189
def to_js_string(self, as_function=True, is_async=True):
    """
    Return the experiment as a JavaScript string
    """
    from sweetbean.protection._context import set_active_protections

    text = FUNCTION_PREAMBLE(is_async) if as_function else ""
    runtime = self._protection_runtime_js()
    if runtime:
        text += runtime + "\n"
    extensions = ""
    set_active_protections(self.protections)
    try:
        for b in self.blocks:
            b.to_js()
            extensions += _initialize_extensions(b.extensions)
            for s in b.stimuli:
                shared_variables = s.return_shared_variables()
                for s_key in shared_variables:
                    text += f"{shared_variables[s_key].set()}\n"
        text += f"const jsPsych = initJsPsych({extensions})\n"
        init = self._protection_init_js()
        if init:
            text += init + "\n"
        text += "const trials = [\n"
        for b in self.blocks:
            text += b.js
            text += ","
        text = text[:-1] + "]\n"
    finally:
        set_active_protections([])
    # Summary lands on every saved row by running addProperties AFTER
    # jsPsych.run completes — that's why it goes into post_run_js, not
    # initJsPsych's on_finish (which would race with the run loop in
    # the function-style output).
    post_run = self._protection_summary_js()
    if as_function:
        text += FUNCTION_APPENDIX(is_async, post_run)
    else:
        text += TEXT_APPENDIX(is_async, post_run)
    return text

to_js_string_from_template(template, timelines) staticmethod

Replace each __SB_TIMELINE_PLACEHOLDER_i__ in template with the JS literal for timelines[i] (from :func:sweetbean.util.parse.to_js).

timelines must have one entry per block that used a placeholder in :meth:compile (same order as Experiment.blocks). Blocks compiled with :class:~sweetbean.variable.CodeVariable timelines embed real JS and are not listed here — pass the full list of block timelines, including those unchanged.

Source code in sweetbean/experiment.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
@staticmethod
def to_js_string_from_template(template: str, timelines: List[Any]) -> str:
    """
    Replace each ``__SB_TIMELINE_PLACEHOLDER_i__`` in *template* with the JS literal
    for ``timelines[i]`` (from :func:`sweetbean.util.parse.to_js`).

    *timelines* must have one entry per block that used a placeholder in
    :meth:`compile` (same order as ``Experiment.blocks``). Blocks compiled with
    :class:`~sweetbean.variable.CodeVariable` timelines embed real JS and are not
    listed here — pass the full list of block timelines, including those unchanged.
    """
    from sweetbean.util.parse import to_js as sb_to_js

    def _repl(m: re.Match) -> str:
        idx = int(m.group(1))
        if idx < 0 or idx >= len(timelines):
            raise ValueError(
                f"Template references timeline placeholder {idx}; "
                f"got {len(timelines)} timeline(s)"
            )
        return sb_to_js(timelines[idx])

    return _TIMELINE_PLACEHOLDER_RE.sub(_repl, template)

KeyboardPressResponseSpec

Bases: _SpecBaseModel

Keyboard response definition.

Source code in sweetbean/response_spec/spec.py
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
class KeyboardPressResponseSpec(_SpecBaseModel):
    """Keyboard response definition."""

    kind: Literal["keyboard_press"] = "keyboard_press"
    allowed_keys: tuple[str, ...] = Field(
        default_factory=tuple,
        description=(
            "Allowed keyboard keys. When empty, any keypress is accepted "
            "(equivalent to jsPsych ALL_KEYS)."
        ),
    )
    correct_keys: tuple[str, ...] | None = Field(
        default=None,
        description=(
            "Optional key(s) considered correct for feedback/scoring. "
            "When omitted, correctness is not evaluated for this response."
        ),
    )
    max_responses: int | None = Field(
        default=1,
        description=(
            "Maximum number of responses to capture. Default 1. "
            "Use null for no limit (as many responses as occur before the trial ends)."
        ),
    )
    response_ends_trial: bool = Field(
        default=True,
        description="Whether a valid response ends the trial.",
        json_schema_extra=_PROMPT_SILENT,
    )

    @field_validator("max_responses")
    @classmethod
    def _keyboard_max_responses(cls, v: int | None) -> int | None:
        if v is None:
            return None
        if v < 1:
            raise ValueError("max_responses must be >= 1 or null")
        return v

MouseClickResponseSpec

Bases: _SpecBaseModel

Mouse click response definition.

Source code in sweetbean/response_spec/spec.py
 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
class MouseClickResponseSpec(_SpecBaseModel):
    """Mouse click response definition."""

    kind: Literal["mouse_click"] = "mouse_click"
    target_ids: tuple[str, ...] = Field(
        default_factory=tuple,
        description=(
            "Clickable stimulus ids. When empty, the full scene is clickable: "
            "every rendered stimulus layer counts as a target (full-screen hit "
            "testing over stacked regions)."
        ),
    )
    correct_target_ids: tuple[str, ...] | None = Field(
        default=None,
        description=(
            "Optional target ids considered correct for feedback/scoring. "
            "When omitted, correctness is not evaluated for this response."
        ),
    )
    record_click_x: bool = Field(
        default=True,
        description=(
            "Whether to record click X (viewport/client) in trial data when the "
            "runtime supports it. Default: true."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )
    record_click_y: bool = Field(
        default=True,
        description=(
            "Whether to record click Y (viewport/client) in trial data when the "
            "runtime supports it. Default: true."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )
    max_responses: int | None = Field(
        default=1,
        description=(
            "Maximum number of responses to capture. Default 1. "
            "Use null for no limit (as many responses as occur before the trial ends)."
        ),
    )
    response_ends_trial: bool = Field(
        default=True,
        description="Whether a valid response ends the trial.",
        json_schema_extra=_PROMPT_SILENT,
    )

    @field_validator("max_responses")
    @classmethod
    def _mouse_max_responses(cls, v: int | None) -> int | None:
        if v is None:
            return None
        if v < 1:
            raise ValueError("max_responses must be >= 1 or null")
        return v

Protection

Base class — see module docstring for the hook contract.

Source code in sweetbean/protection/protection.py
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
class Protection:
    """Base class — see module docstring for the hook contract."""

    name: str = "protection"

    def head_assets(self) -> str:
        """Extra HTML injected into ``<head>``. Used by ``Experiment.to_html``."""
        return ""

    def runtime_js(self) -> str:
        """JS source emitted before ``initJsPsych``. Typically the protection
        library (IIFE) being inlined into the page."""
        return ""

    def init_js(self) -> str:
        """JS source run after ``initJsPsych`` but before trials run. Typical
        use: call the library's ``initialize`` and register global handlers."""
        return ""

    def summary_js(self) -> str:
        """JS expression that evaluates to a summary object. Empty disables.
        Wired into the experiment's ``on_finish`` so it lands on every row of
        saved data via ``jsPsych.data.addProperties``."""
        return ""

    def on_load_for_stimulus(self, stimulus) -> str:
        """Per-trial JS injected into the stimulus's ``on_load`` callback.

        Return ``""`` to no-op for this stimulus type. Implementations may
        inspect ``stimulus`` (e.g. ``isinstance``) to specialize.
        """
        return ""

    def on_finish_for_stimulus(self, stimulus) -> str:
        """Per-trial JS injected into the stimulus's ``on_finish`` callback.

        ``data`` is in scope and refers to the trial's data row — mutate it
        directly to attach per-trial signals.
        """
        return ""

head_assets()

Extra HTML injected into <head>. Used by Experiment.to_html.

Source code in sweetbean/protection/protection.py
36
37
38
def head_assets(self) -> str:
    """Extra HTML injected into ``<head>``. Used by ``Experiment.to_html``."""
    return ""

init_js()

JS source run after initJsPsych but before trials run. Typical use: call the library's initialize and register global handlers.

Source code in sweetbean/protection/protection.py
45
46
47
48
def init_js(self) -> str:
    """JS source run after ``initJsPsych`` but before trials run. Typical
    use: call the library's ``initialize`` and register global handlers."""
    return ""

on_finish_for_stimulus(stimulus)

Per-trial JS injected into the stimulus's on_finish callback.

data is in scope and refers to the trial's data row — mutate it directly to attach per-trial signals.

Source code in sweetbean/protection/protection.py
64
65
66
67
68
69
70
def on_finish_for_stimulus(self, stimulus) -> str:
    """Per-trial JS injected into the stimulus's ``on_finish`` callback.

    ``data`` is in scope and refers to the trial's data row — mutate it
    directly to attach per-trial signals.
    """
    return ""

on_load_for_stimulus(stimulus)

Per-trial JS injected into the stimulus's on_load callback.

Return "" to no-op for this stimulus type. Implementations may inspect stimulus (e.g. isinstance) to specialize.

Source code in sweetbean/protection/protection.py
56
57
58
59
60
61
62
def on_load_for_stimulus(self, stimulus) -> str:
    """Per-trial JS injected into the stimulus's ``on_load`` callback.

    Return ``""`` to no-op for this stimulus type. Implementations may
    inspect ``stimulus`` (e.g. ``isinstance``) to specialize.
    """
    return ""

runtime_js()

JS source emitted before initJsPsych. Typically the protection library (IIFE) being inlined into the page.

Source code in sweetbean/protection/protection.py
40
41
42
43
def runtime_js(self) -> str:
    """JS source emitted before ``initJsPsych``. Typically the protection
    library (IIFE) being inlined into the page."""
    return ""

summary_js()

JS expression that evaluates to a summary object. Empty disables. Wired into the experiment's on_finish so it lands on every row of saved data via jsPsych.data.addProperties.

Source code in sweetbean/protection/protection.py
50
51
52
53
54
def summary_js(self) -> str:
    """JS expression that evaluates to a summary object. Empty disables.
    Wired into the experiment's ``on_finish`` so it lands on every row of
    saved data via ``jsPsych.data.addProperties``."""
    return ""

RectangleSpec

Bases: _SpecBaseModel

Normalized rectangular placement in viewport coordinates.

Source code in sweetbean/stimulus_spec/spec.py
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
class RectangleSpec(_SpecBaseModel):
    """Normalized rectangular placement in viewport coordinates."""

    x: float = Field(
        default=0.5,
        ge=0.0,
        le=1.0,
        description="Horizontal center position in normalized viewport coordinates.",
    )
    y: float = Field(
        default=0.5,
        ge=0.0,
        le=1.0,
        description="Vertical center position in normalized viewport coordinates.",
    )
    width: float = Field(
        default=1.0,
        gt=0.0,
        le=1.0,
        description="Normalized width relative to viewport width.",
    )
    height: float = Field(
        default=1.0,
        gt=0.0,
        le=1.0,
        description="Normalized height relative to viewport height.",
    )

SymbolStimulusSpec

Bases: _BaseStimulusSpec

Rendered geometric symbol stimulus.

Source code in sweetbean/stimulus_spec/spec.py
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
class SymbolStimulusSpec(_BaseStimulusSpec):
    """Rendered geometric symbol stimulus."""

    kind: Literal["symbol"] = "symbol"
    shape: Literal["circle", "ring", "rectangle", "triangle", "cross"] = Field(
        description="Symbol geometry to render.",
    )
    color: str = Field(
        default="#111111",
        description="Primary CSS color used for symbol fill/stroke.",
        json_schema_extra=_PROMPT_SILENT,
    )
    size_px: int | None = Field(
        default=None,
        ge=1,
        description=(
            "Optional symbol size in pixels. If omitted, defaults to 160."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )
    stroke_color: str | None = Field(
        default=None,
        description=(
            "Optional outline color for symbol variants that support stroke."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )
    stroke_width_px: int | None = Field(
        default=None,
        ge=0,
        description=(
            "Optional outline width in pixels. If omitted, renderer picks a "
            "shape-specific default when needed."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )
    rotation_deg: float | None = Field(
        default=None,
        description=(
            "Optional clockwise symbol rotation in degrees. If omitted, defaults to 0."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )

TextStimulusSpec

Bases: _BaseStimulusSpec

Rendered text stimulus.

Source code in sweetbean/stimulus_spec/spec.py
 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
class TextStimulusSpec(_BaseStimulusSpec):
    """Rendered text stimulus."""

    kind: Literal["text"] = "text"
    text: str = Field(description="Text content to render.")
    color: str = Field(
        default="white",
        description="CSS text color. Default: white.",
        json_schema_extra=_PROMPT_SILENT,
    )
    font_size_px: int | None = Field(
        default=None,
        ge=1,
        description=(
            "Optional font size in pixels. If omitted, defaults to 32."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )
    font_family: str | None = Field(
        default=None,
        description=(
            "Optional CSS font-family. If omitted, defaults to sans-serif."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )
    align: Literal["left", "center", "right"] | None = Field(
        default=None,
        description=(
            "Optional text alignment inside the placement rectangle. "
            "If omitted, defaults to center."
        ),
        json_schema_extra=_PROMPT_SILENT,
    )

TrialSpec

Bases: _SpecBaseModel

One rendered trial containing layered stimuli and response handlers.

Source code in sweetbean/stimulus_spec/spec.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
class TrialSpec(_SpecBaseModel):
    """One rendered trial containing layered stimuli and response handlers."""

    stimuli: tuple[StimulusSpecUnion, ...] = Field(
        default_factory=tuple,
        min_length=1,
        description="Layered visual stimuli rendered in one trial frame.",
    )
    responses: tuple[ResponseSpecUnion, ...] = Field(
        default_factory=tuple,
        description="Response handlers active for this trial frame.",
    )
    trial_duration_ms: int | None = Field(
        default=None,
        ge=1,
        description="Optional hard cap for total trial duration.",
        json_schema_extra=_PROMPT_SILENT,
    )
    background_color: str = Field(
        default="black",
        description="CSS background color for the trial frame. Default: black.",
        json_schema_extra=_PROMPT_SILENT,
    )

    @model_validator(mode="after")
    def _validate_unique_ids_and_stimulus_defaults(self) -> "TrialSpec":
        ids = [s.id for s in self.stimuli if s.id]
        if len(ids) != len(set(ids)):
            raise ValueError("Stimulus ids must be unique when provided.")

        resolved: list[StimulusSpecUnion] = []
        for i, s in enumerate(self.stimuli):
            updates: dict[str, object] = {}
            if s.z_index is None:
                updates["z_index"] = i
            if s.rect is None:
                updates["rect"] = RectangleSpec()
            if s.opacity is None:
                updates["opacity"] = 1.0
            if isinstance(s, TextStimulusSpec):
                if s.font_size_px is None:
                    updates["font_size_px"] = 32
                if s.font_family is None:
                    updates["font_family"] = "sans-serif"
                if s.align is None:
                    updates["align"] = "center"
            if isinstance(s, SymbolStimulusSpec):
                if s.size_px is None:
                    updates["size_px"] = 160
                if s.rotation_deg is None:
                    updates["rotation_deg"] = 0.0
            if isinstance(s, AssetStimulusSpec):
                if s.object_fit is None:
                    updates["object_fit"] = "contain"
            if updates:
                s = s.model_copy(update=updates)
            resolved.append(s)

        return self.model_copy(update={"stimuli": tuple(resolved)})

build_html_from_files(spec_json_path, timeline_csv_path, out_html_path)

Compile and write a runnable jsPsych HTML from declarative files.

Source code in sweetbean/stimulus_spec/io.py
108
109
110
111
112
113
114
115
116
117
118
119
def build_html_from_files(
    spec_json_path: str | Path,
    timeline_csv_path: str | Path,
    out_html_path: str | Path,
) -> Path:
    """Compile and write a runnable jsPsych HTML from declarative files."""
    trials = trial_specs_from_files(spec_json_path, timeline_csv_path)
    compiled = [compile_trial(t) for t in trials]
    exp = Experiment([Block(compiled)])
    out = Path(out_html_path)
    exp.to_html(str(out))
    return out

build_prompt_schema_markdown(*, verbosity=1)

Return markdown documentation for SweetBean trial-spec models.

verbosity is passed to auto_prompt.build_prompt when available; higher values include fields marked with prompt_verbosity_min.

Source code in sweetbean/stimulus_spec/prompt_schema.py
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
def build_prompt_schema_markdown(*, verbosity: int = 1) -> str:
    """Return markdown documentation for SweetBean trial-spec models.

    *verbosity* is passed to ``auto_prompt.build_prompt`` when available;
    higher values include fields marked with ``prompt_verbosity_min``.
    """
    try:
        from auto_prompt import build_prompt  # type: ignore
    except Exception:
        payload = {
            "TrialSpec": TrialSpec.model_json_schema(),
            "StimulusSpecUnion": TypeAdapter(StimulusSpecUnion).json_schema(),
            "ResponseSpecUnion": TypeAdapter(ResponseSpecUnion).json_schema(),
        }
        return "```json\n" + json.dumps(payload, indent=2, default=str) + "\n```"
    interpolation_guide = (
        "# TIMELINE PLACEHOLDER GUIDE\n\n"
        "- Any string field may use `{{column_name}}` placeholders.\n"
        "- Placeholders are resolved from the current timeline CSV row before validation/rendering.\n"
        "- Use literal values (direct strings/numbers) when no per-row substitution is needed.\n"
        "- Example: `asset_ref: \"{{asset_ref}}\"`, `text: \"{{prompt_text}}\"`.\n"
        "\n"
        "# RUNTIME FEEDBACK NOTES\n\n"
        "- Response handlers emit normalized fields in jsPsych data when available:\n"
        "  `bean_response`, `bean_rt`, `bean_correct`, and plugin-specific values like `bean_value`.\n"
        "- These can be consumed by dynamic SweetBean/JS logic in later trials "
        "(e.g. feedback screens based on previous correctness).\n"
    )
    return "\n\n".join(
        [
            interpolation_guide,
            "# SCHEMA - TrialSpec",
            build_prompt(TrialSpec, verbosity=verbosity),
            "# SCHEMA - StimulusSpecUnion",
            build_prompt(StimulusSpecUnion, verbosity=verbosity),
            "# SCHEMA - ResponseSpecUnion",
            build_prompt(ResponseSpecUnion, verbosity=verbosity),
        ]
    )

check_java()

Ensure that Java is installed.

Source code in sweetbean/__init__.py
27
28
29
30
31
32
33
34
35
def check_java():
    """Ensure that Java is installed."""
    java_path = shutil.which("java")
    if java_path is None:
        sys.stderr.write(
            "\nError: Java is required but not found.\n"
            "   Please install Java using one of the following.\n"
        )
        sys.exit(1)

compile_trial(spec)

Compile one declarative trial spec into a SweetBean stimulus object.

Source code in sweetbean/stimulus_spec/render.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def compile_trial(
    spec: TrialSpec,
) -> HtmlKeyboardResponse | HtmlChoice | HtmlSliderResponse:
    """Compile one declarative trial spec into a SweetBean stimulus object."""
    scene_html, rendered = _build_scene_html(spec)
    if not spec.responses:
        return HtmlKeyboardResponse(
            duration=_max_duration_ms(spec),
            stimulus=scene_html,
            choices=[],
            correct_key="",
        )
    if len(spec.responses) != 1:
        raise ValueError(
            "Current renderer supports exactly one response spec per trial."
        )

    response = spec.responses[0]
    if response.kind == "keyboard_press":
        if response.max_responses is not None and response.max_responses > 1:
            raise ValueError(
                "Keyboard response: max_responses > 1 is not supported by the "
                "renderer yet; use 1 or null (unlimited)."
            )
        correct_key = ""
        if response.correct_keys:
            if len(response.correct_keys) > 1:
                raise ValueError(
                    "Keyboard response currently supports at most one `correct_keys` "
                    "entry for built-in correctness tracking."
                )
            correct_key = response.correct_keys[0]
        keys = list(response.allowed_keys)
        choices: list[str] | _JsPsychAllKeys = (
            keys if keys else _JS_PSYCH_ALL_KEYS
        )
        return HtmlKeyboardResponse(
            duration=_max_duration_ms(spec),
            stimulus=scene_html,
            choices=choices,
            correct_key=correct_key,
        )

    if response.kind == "mouse_click":
        if response.max_responses is not None and response.max_responses > 1:
            raise ValueError(
                "Mouse click response: max_responses > 1 is not supported by the "
                "renderer yet; use 1 or null (unlimited)."
            )
        target_set = set(response.target_ids)
        html_array: list[str] = []
        values: list[str] = []
        for stim_id, stim_html in rendered:
            if target_set and stim_id not in target_set:
                continue
            html_array.append(stim_html)
            values.append(stim_id)
        if not html_array:
            raise ValueError(
                "Mouse click response has no clickable targets after filtering."
            )
        return HtmlChoice(
            duration=_max_duration_ms(spec),
            html_array=html_array,
            values=values,
            correct_values=list(response.correct_target_ids or ()),
            time_after_response=0,
        )

    if response.kind == "slider":
        if response.max_responses is not None and response.max_responses > 1:
            raise ValueError(
                "Slider response: max_responses > 1 is not supported by the "
                "renderer yet; use 1 or null (unlimited)."
            )
        start = (
            response.start_value
            if response.start_value is not None
            else (response.min_value + response.max_value) / 2.0
        )
        return HtmlSliderResponse(
            duration=_max_duration_ms(spec),
            stimulus=scene_html,
            min=response.min_value,
            max=response.max_value,
            slider_start=start,
            step=response.step,
            labels=list(response.tick_labels),
            button_label=response.button_label,
            require_movement=response.require_movement,
            response_ends_trial=response.response_ends_trial,
            correct_values=list(response.correct_values or ()),
            correct_min=response.correct_min_value,
            correct_max=response.correct_max_value,
        )

    raise ValueError(f"Unsupported response kind: {response.kind}")

write_prompt_schema_markdown(out_path, *, verbosity=1)

Generate and write markdown docs for Trial/Stimulus/Response specs.

Source code in sweetbean/stimulus_spec/io.py
122
123
124
125
126
127
128
129
130
131
def write_prompt_schema_markdown(
    out_path: str | Path, *, verbosity: int = 1
) -> Path:
    """Generate and write markdown docs for Trial/Stimulus/Response specs."""
    out = Path(out_path)
    out.write_text(
        build_prompt_schema_markdown(verbosity=verbosity) + "\n",
        encoding="utf-8",
    )
    return out