Skip to content

sweetbean.stimulus_spec

Declarative stimulus + trial specs and jsPsych-backed compiler.

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,
    )

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),
        ]
    )

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}")

load_spec_library(path)

Load reusable trial-spec templates from JSON file.

Source code in sweetbean/stimulus_spec/io.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def load_spec_library(path: str | Path) -> dict[str, dict[str, Any]]:
    """Load reusable trial-spec templates from JSON file."""
    p = Path(path)
    payload = json.loads(p.read_text(encoding="utf-8"))
    raw_specs = payload.get("specs")
    if not isinstance(raw_specs, dict) or not raw_specs:
        raise ValueError("Spec file must contain a non-empty 'specs' object.")
    out: dict[str, dict[str, Any]] = {}
    for spec_id, raw in raw_specs.items():
        if not isinstance(spec_id, str) or not spec_id.strip():
            raise ValueError("All spec ids must be non-empty strings.")
        if not isinstance(raw, dict):
            raise ValueError(f"Spec '{spec_id}' must be a JSON object.")
        out[spec_id] = raw
    return out

load_timeline_rows(path)

Load timeline rows from CSV.

Required column: spec_id

Source code in sweetbean/stimulus_spec/io.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def load_timeline_rows(path: str | Path) -> list[dict[str, Any]]:
    """Load timeline rows from CSV.

    Required column: `spec_id`
    """
    p = Path(path)
    rows: list[dict[str, Any]] = []
    with p.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        if "spec_id" not in (reader.fieldnames or []):
            raise ValueError("Timeline CSV must contain a 'spec_id' column.")
        for row_idx, row in enumerate(reader, start=1):
            clean = {k: _decode_cell(v or "") for k, v in row.items() if k}
            sid = str(clean.get("spec_id", "")).strip()
            if not sid:
                raise ValueError(f"Missing spec_id at timeline row {row_idx}.")
            clean["spec_id"] = sid
            rows.append(clean)
    if not rows:
        raise ValueError("Timeline CSV is empty.")
    return rows

trial_specs_from_files(spec_json_path, timeline_csv_path)

Materialize validated TrialSpec list from JSON templates + timeline CSV.

Source code in sweetbean/stimulus_spec/io.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def trial_specs_from_files(
    spec_json_path: str | Path,
    timeline_csv_path: str | Path,
) -> list[TrialSpec]:
    """Materialize validated TrialSpec list from JSON templates + timeline CSV."""
    specs = load_spec_library(spec_json_path)
    timeline = load_timeline_rows(timeline_csv_path)

    out: list[TrialSpec] = []
    for row in timeline:
        sid = row["spec_id"]
        if sid not in specs:
            raise KeyError(f"Timeline references unknown spec_id '{sid}'.")
        resolved = _resolve_templates(specs[sid], row)
        out.append(TrialSpec.model_validate(resolved))
    return out

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