psyflow package¶
Submodules¶
psyflow.BlockUnit module¶
- class psyflow.BlockUnit.BlockUnit(block_id, block_idx, settings, window=None, keyboard=None, seed=None, n_trials=None)[source]¶
Bases:
object
Block-level controller for trials.
This object generates trial conditions, executes each trial, and stores metadata. It exposes hooks for custom start/end logic and summary methods.
- block_id¶
Identifier for the block.
- Type:
str
- block_idx¶
Index of this block in the experiment.
- Type:
int
- n_trials¶
Number of trials to execute.
- Type:
int
- settings¶
Experiment settings container.
- Type:
dict
- win¶
PsychoPy window used for drawing.
- Type:
Any
- kb¶
PsychoPy keyboard used for responses.
- Type:
Any
- seed¶
Seed used for randomisation.
- Type:
int
- conditions¶
Ordered list of condition labels for each trial.
- Type:
list of Any or None
- results¶
Accumulated trial results after
run_trial()
.- Type:
list of dict
- meta¶
Additional block metadata such as start time and duration.
- Type:
dict
- add_condition(condition_list)[source]¶
Manually set the condition list.
- Parameters:
condition_list (list) – A list of trial condition labels.
- Returns:
The same instance for method chaining.
- Return type:
- generate_conditions(func=None, n_trials=None, condition_labels=None, weights=None, order='random', seed=None, **kwargs)[source]¶
Generate trial conditions for this block.
If func is provided, delegate generation to it. Otherwise, use the built-in weighted, balanced generator with optional sequential vs. random ordering.
- Parameters:
func (Callable, optional) – User-supplied generator with signature (n_trials, condition_labels, seed=…, **kwargs) -> array-like.
n_trials (int, optional) – Number of trials in this block. Defaults to self.n_trials.
condition_labels (list of Any, optional) – Labels for each condition. Defaults to self.settings.conditions.
weights (list of float, optional) – Relative weight for each label; defaults to equal weights.
order ({'random','sequential'}) – If ‘sequential’, interleave labels in the order given; if ‘random’, build the list then shuffle.
seed (int, optional) – Overrides self.seed for this generation call, without mutating the block’s stored seed.
**kwargs (dict) – Extra keyword arguments passed to func when used.
- Returns:
Returns self for chaining.
- Return type:
- get_all_data()[source]¶
Return trial results without modifying anything.
- Returns:
Trial result dictionaries.
- Return type:
list of dict
- get_trial_data(key, pattern, match_type='exact', negate=False)[source]¶
Filter trial data based on value of a key using matching rules.
- Parameters:
key (str) – The key in each trial dict to match against.
pattern (str or list of str) – One or more patterns to match.
match_type ({'exact', 'startswith', 'endswith', 'regex'}) – Type of string matching to use.
negate (bool) – If True, return trials that do NOT match the pattern(s).
- Returns:
Filtered list of trial dicts.
- Return type:
List[Dict]
- logging_block_info()[source]¶
Log block metadata including ID, index, seed, trial count, and condition distribution.
- on_end(func=None)[source]¶
Register a function to run at the end of the block.
- Parameters:
func (Callable, optional) – A function that takes the BlockUnit as input.
- on_start(func=None)[source]¶
Register a function to run at the start of the block.
- Parameters:
func (Callable, optional) – A function that takes the BlockUnit as input.
- run_trial(func, **kwargs)[source]¶
Run all trials using a specified trial function.
- Parameters:
func (Callable) – Function to run each trial. Must accept
(win, kb, settings, condition, **kwargs)
.**kwargs (dict) – Additional keyword arguments forwarded to
func
.
psyflow.StimBank module¶
- class psyflow.StimBank.StimBank(win, config=None)[source]¶
Bases:
object
A hybrid stimulus management system for PsychoPy experiments.
StimBank supports: - Manual registration of stimuli via decorators (@registry.define(“name”)) - Loading stimuli from YAML or Python dictionaries - Centralized retrieval, lazy instantiation, and batch preview
- add_from_dict(named_specs=None, **kwargs)[source]¶
Add stimuli from a dictionary or keyword-based specifications.
- Parameters:
named_specs (dict, optional) – Dictionary where keys are stimulus names and values are stimulus specs.
kwargs (dict) – Additional stimuli as keyword-based name=spec entries.
- add_voice(stim_label, text, overwrite=False, voice='zh-CN-XiaoxiaoNeural')[source]¶
Convert arbitrary text to speech (MP3) and register it as a new Sound stimulus.
- Parameters:
stim_label (str) – The name under which to register the new voice stimulus, and the base filename for the MP3 (e.g. ‘welcome_voice’ → ‘assets/welcome_voice.mp3’).
text (str) – The text to synthesize.
overwrite (bool) – If True, overwrite an existing MP3 file. Default is False.
voice (str) – The TTS voice to use (default “zh-CN-XiaoxiaoNeural”). edge-tts –list-voices
- convert_to_voice(keys, overwrite=False, voice='zh-CN-YunyangNeural')[source]¶
Convert specified TextStim/TextBox2 stimuli to speech (MP3) and register them as new Sound stimuli in this StimBank.
- Parameters:
keys (list[str]) – List of registered stimulus names to convert.
overwrite (bool) – If True, overwrite existing MP3 files (default False).
voice (str) – Name of the TTS voice to use (default ‘zh-CN-YunyangNeural’). edge-tts –list-voices
- define(name)[source]¶
Register a stimulus generator function using a decorator.
- Parameters:
name (str) – Name to register the stimulus under.
- Returns:
A decorator to wrap the stimulus function.
- Return type:
Callable
- describe(name)[source]¶
Print accepted arguments for a registered stimulus.
- Parameters:
name (str) – Name of the stimulus to describe.
- export_to_yaml(path)[source]¶
Export YAML-defined stimuli (but not decorator-defined) to file.
- Parameters:
path (str) – Path to save the YAML file.
- get(name)[source]¶
Get a stimulus by name, instantiating it if needed.
- Parameters:
name (str) – Registered stimulus name.
- Returns:
Instantiated PsychoPy stimulus object.
- Return type:
Any
- Raises:
KeyError – If the stimulus is not registered.
- get_and_format(name, **format_kwargs)[source]¶
Return a fresh TextStim or TextBox2 with formatted text, keeping other properties unchanged.
- Parameters:
name (str) – Name of the registered stimulus (TextStim or TextBox2).
**format_kwargs – Formatting variables to apply to the text field.
- Returns:
- TextStim or TextBox2
A new formatted visual text stimulus.
- Raises:
TypeError – If the stimulus is not a TextStim.
- get_group(prefix)[source]¶
Retrieve a dictionary of stimuli whose names start with a given prefix.
- Parameters:
prefix (str) – Common prefix to match.
- Returns:
A dictionary of {name: stimulus} pairs.
- Return type:
dict
- get_selected(keys)[source]¶
Retrieve a subset of named stimuli.
- Parameters:
keys (list of str) – List of stimulus names to retrieve.
- Returns:
A dictionary of {name: stimulus} pairs.
- Return type:
dict
- make_factory(cls, base_kwargs, name)[source]¶
Create a factory function for a given stimulus class.
- Parameters:
cls (type) – PsychoPy stimulus class (e.g., TextStim).
base_kwargs (dict) – Default keyword arguments.
name (str) – Stimulus name (used for error messages).
- Returns:
A factory function that accepts (win, **overrides)
- Return type:
Callable
- preload_all()[source]¶
Instantiate all registered stimuli.
- Returns:
The object itself for method chaining.
- Return type:
- preview_all(wait_keys=True)[source]¶
Preview all registered stimuli one by one.
- Parameters:
wait_keys (bool) – Wait for key press after last stimulus.
- preview_group(prefix, wait_keys=True)[source]¶
Preview all stimuli that match a name prefix.
- Parameters:
prefix (str) – Prefix string to filter stimuli.
wait_keys (bool) – Wait for key press after final stimulus.
- preview_selected(keys, wait_keys=True)[source]¶
Preview selected stimuli by name.
- Parameters:
keys (list of str) – Stimulus names to preview.
wait_keys (bool) – Wait for key press after final stimulus.
- rebuild(name, update_cache=False, **overrides)[source]¶
Rebuild a stimulus with optional updated parameters.
- Parameters:
name (str) – Registered stimulus name.
update_cache (bool) – Whether to overwrite the existing cached version.
**overrides (dict) – New keyword arguments to override the original parameters.
- Returns:
A fresh stimulus object.
- Return type:
Any
psyflow.SubInfo module¶
- class psyflow.SubInfo.SubInfo(config)[source]¶
Bases:
object
GUI-based participant information collector using a YAML-style config.
This class generates an input dialog based on a configurable field structure and provides basic localization and validation for different field types.
Supported field types: - string : Free text input - int : Integer input with optional constraints - choice : Dropdown with options
- subject_data¶
The result of .collect(), formatted with English field keys.
- Type:
dict or None
- collect(exit_on_cancel=True)[source]¶
Show a dialog to collect participant input. Loops until valid or cancelled.
- Parameters:
exit_on_cancel (bool) – If True, exit the program if the user cancels input.
- Returns:
Cleaned response dictionary with English field keys, or None if cancelled and exit_on_cancel is False.
- Return type:
dict or None
Examples
>>> cfg = {'subinfo_fields': [{'name': 'age', 'type': 'int'}]} >>> info = SubInfo(cfg) >>> info.collect(exit_on_cancel=False)
psyflow.TaskSettings module¶
- class psyflow.TaskSettings.TaskSettings(size=<factory>, units='deg', screen=1, bg_color='gray', fullscreen=True, total_blocks=1, total_trials=10, key_list=<factory>, conditions=<factory>, block_seed=None, seed_mode='same_across_sub', overall_seed=2025, log_file=None, res_file=None, json_file=None, save_path='./data', task_name=None)[source]¶
Bases:
object
Configuration container for PsychoPy-based tasks.
This dataclass holds core experimental parameters and provides utility methods to set per-subject seeds, construct output paths, and dynamically extend settings from external config dictionaries.
Features¶
Window display settings
Experimental structure (blocks, trials, conditions)
Response keys
Flexible seeding strategies
Auto-generated per-subject filenames
- add_subinfo(subinfo)[source]¶
Add subject-specific information and set seed/file names accordingly.
- Parameters:
subinfo (dict) – Dictionary that must contain at least ‘subject_id’. Also used to construct per-subject output file names.
- Raises:
ValueError – If ‘subject_id’ is missing from subinfo.
-
bg_color:
str
= 'gray'¶
-
block_seed:
Optional
[List
[int
]] = None¶
-
conditions:
List
[str
]¶
- classmethod from_dict(config)[source]¶
Create a TaskSettings instance from a flat dictionary.
Known fields are applied normally; unknown keys are attached as attributes.
- Parameters:
config (dict) – Dictionary of configuration options.
- Returns:
An initialized instance with config applied.
- Return type:
Examples
>>> cfg = {'total_blocks': 2, 'total_trials': 20} >>> TaskSettings.from_dict(cfg)
-
fullscreen:
bool
= True¶
-
json_file:
Optional
[str
] = None¶
-
key_list:
List
[str
]¶
-
log_file:
Optional
[str
] = None¶
-
overall_seed:
int
= 2025¶
-
res_file:
Optional
[str
] = None¶
-
save_path:
Optional
[str
] = './data'¶
-
screen:
int
= 1¶
-
seed_mode:
str
= 'same_across_sub'¶
- set_block_seed(seed_base)[source]¶
Generate a list of per-block seeds from a base seed.
- Parameters:
seed_base (int) – Base seed used to generate a list of integers for each block.
-
size:
List
[int
]¶
-
task_name:
Optional
[str
] = None¶
-
total_blocks:
int
= 1¶
-
total_trials:
int
= 10¶
-
trials_per_block:
int
¶
-
units:
str
= 'deg'¶
psyflow.StimUnit module¶
- class psyflow.StimUnit.StimUnit(unit_label, win, kb=None, triggersender=None)[source]¶
Bases:
object
A modular trial unit for PsychoPy-based experiments. Designed to encapsulate stimulus presentation, response handling, event triggers, and lifecycle hooks with flexible timing control.
Features¶
Add multiple visual stimuli and manage them as a group.
Register event hooks for start, response, timeout, and end stages.
Supports both time-based and frame-based control modes.
Triggers aligned to visual flips (e.g., for EEG/fMRI).
Logs detailed trial state to PsychoPy’s logging system.
- type win:
Window
- param win:
PsychoPy window where stimuli will be drawn.
- type win:
visual.Window
- type unit_label:
str
- param unit_label:
Identifier for the trial (used for logging/debugging).
- type unit_label:
str
- param trigger:
External trigger handler (default: a dummy TriggerSender instance).
- type trigger:
Trigger, optional
- param frame_time:
Duration of a single frame in seconds (default: 1/60 for 60Hz).
- type frame_time:
float
- add_stim(*stims)[source]¶
Add one or more visual or sound stimuli to the trial.
Supports calling patterns: .add_stim(stimA) .add_stim(stimA, stimB, stimC) .add_stim([stimA, stimB, stimC])
- Parameters:
*stims (visual.BaseVisualStim or sound.Sound or list of such) – One or more PsychoPy stimuli (visual or audio).
- Returns:
Returns self for chaining.
- Return type:
- capture_response(keys, duration, onset_trigger=None, response_trigger=None, timeout_trigger=None, terminate_on_response=True, correct_keys=None, highlight_stim=None, dynamic_highlight=False)[source]¶
Wait for a keypress or timeout. Supports both time-based and frame-based duration. Triggers and onset time synced to visual flip.
- Parameters:
keys (list[str]) – Keys to listen for.
duration (float) – Response window duration in seconds.
onset_trigger (int) – Trigger code sent at stimulus onset.
response_trigger (int | dict[str, int]) – Trigger code for response, can be per-key.
timeout_trigger (int) – Trigger code for timeout.
correct_keys (list[str] | None) – If provided, only keys in this list count as hits.
highlight_stim (VisualStim or dict) – If a single stim: draw it around whatever is chosen. If a dict: maps key names -> highlight stimuli.
dynamic_highlight (bool) – If True, allow multiple key presses and update the highlight each time.
- Return type:
- get_state(key, default=None, prefix=None)[source]¶
Retrieve a value from internal state.
Lookup order: 1. Try exact key. 2. If not found, try prefixed key using: - provided prefix (if given) - otherwise self.label
- Parameters:
key (str) – State variable name.
default (Any) – Value to return if key is not found.
prefix (str, optional) – Optional manual prefix to use (overrides self.label).
- Returns:
Stored value, or default if not found.
- Return type:
Any
- log_unit()[source]¶
Write the current trial state to PsychoPy logs.
All key-value pairs stored in
state
are emitted usinglogging.data
which allows post‑hoc reconstruction of each trial.- Return type:
None
Examples
>>> unit.set_state(response="space") >>> unit.log_unit()
- on_response(keys, func=None)[source]¶
Register or decorate a function to call when a valid response key is pressed.
- Parameters:
keys (list[str]) – Keys that trigger the callback.
func (Callable or None) – A function accepting (StimUnit, key, rt) or None to use as decorator.
- on_timeout(timeout, func=None)[source]¶
Register or decorate a function to call on timeout.
- Parameters:
timeout (float) – Time in seconds after which timeout is triggered.
func (Callable or None) – A function accepting (StimUnit) or None to use as decorator.
- run(terminate_on_response=True)[source]¶
Execute the full trial lifecycle.
This method draws all registered stimuli, handles response and timeout events, executes registered hooks and logs the final state.
- Parameters:
terminate_on_response (bool, optional) – If
True
the trial ends immediately once a response is registered. Defaults toTrue
.- Returns:
The instance itself for chaining.
- Return type:
Examples
>>> StimUnit("trial1", win).run()
- send_trigger(trigger_code)[source]¶
Send a trigger value via the connected trigger object.
- Parameters:
trigger_code (int) – The value to send.
- Return type:
- set_state(prefix=None, **kwargs)[source]¶
Update internal state with optional key prefixing.
- Parameters:
prefix (str, optional) – If None, use self.label. If “”, store keys as-is. Else use prefix + ‘_’.
kwargs (dict) – State variables to store.
- Return type:
- show(duration=None, onset_trigger=None, offset_trigger=None)[source]¶
Display the stimulus for a specified duration, using frame-based timing (recommended for EEG/fMRI). Audio playback is automatically started on stimulus onset.
If duration is None, the longest duration of any sound stimulus will be used. If duration is set explicitly, it will be respected even if shorter than any sound duration.
- Parameters:
duration (float | list | tuple | None) – Duration of stimulus presentation (in seconds). Can be: - A fixed number - A (min, max) range to sample from - None → automatically use max sound duration (if any)
onset_trigger (int) – Trigger code to send at stimulus onset.
offset_trigger (int) – Trigger code to send at stimulus offset.
- Return type:
- Returns:
StimUnit
Behavior Table
————–
| Condition | Behavior |
|——————————————|——————————————————|
| duration=None | Uses longest sound (or 0.0 if no sound) |
| duration=(1, 2) | Samples uniformly in [1, 2], regardless of sound |
| duration=1.0 + sound is 2.5 seconds | Screen ends at 1.0s, sound may be cut off early |
| duration=None + sound is 2.5 seconds | Screen and sound will both last full 2.5s |
- to_dict(target=None)[source]¶
Return the StimUnit
- Parameters:
target (dict, optional) – If provided, updates this dict in-place and returns it.
- Returns:
StimUnit for chaining.
- Return type:
- wait_and_continue(keys=['space'], min_wait=None, log_message=None, terminate=False)[source]¶
Display the current stimuli (visual and sound) and wait for a key press to continue or quit.
- Parameters:
keys (list[str]) – Keys that allow the trial to proceed (default: [“space”]).
min_wait (float or None) – Minimum time to wait before accepting key press. If None, and any sound stimuli are present, it is automatically set to the longest sound duration.
log_message (str, optional) – Optional log message (default: auto-generated).
terminate (bool) – If True, the experiment will quit after key press.
- Return type:
psyflow.TriggerSender module¶
- class psyflow.TriggerSender.TriggerSender(trigger_func=None, *, mock=False, post_delay=0.001, on_trigger_start=None, on_trigger_end=None)[source]¶
Bases:
object
A wrapper for sending EEG/MEG trigger codes with optional hooks and delays.
Can be initialized with a real sending function or used in mock mode for development/testing without hardware.
Examples
>>> sender = TriggerSender(lambda c: port.write(bytes([c]))) >>> sender.send(32)
>>> sender = TriggerSender(mock=True) >>> sender.send(99)
psyflow.LLM module¶
- exception psyflow.LLM.LLMAPIError(message, status_code=None, api_response=None)[source]¶
Bases:
Exception
Exception raised for errors returned by LLM providers.
- Parameters:
message (
str
) – Human-readable description of the error.status_code (
Optional
[int
]) – HTTP status code if applicable.api_response (
Optional
[Any
]) – Raw response from the provider or SDK error details.
- class psyflow.LLM.LLMClient(provider, api_key, model)[source]¶
Bases:
object
Unified client for multiple LLM backends, plus utilities for task-document conversion and translation.
- Supported providers:
gemini
: Google GenAI SDKopenai
: Official OpenAI SDKdeepseek
: OpenAI SDK with custom base_urlmoonshot
: OpenAI SDK with custom base_url
- provider¶
Lowercase provider name.
- api_key¶
API key for authentication.
- model¶
Model identifier to use.
- _sdk_client¶
Underlying SDK client instance.
- knowledge_base¶
Few-shot examples for generation context.
- add_knowledge(source)[source]¶
Bulk-load few-shot examples into memory from either:
A JSON file path containing a list of example-dicts, or
A list of example-dicts directly.
- Each example-dict maps keys to either:
List[str] of file paths or URLs → will be parsed via _parse_entry()
Raw text (str) → will be stripped and stored as-is
- Parameters:
source (
Union
[str
,List
[Dict
[str
,Union
[str
,List
[str
]]]]]) –If str, treated as path to a JSON file containing List[Dict[…]].
If list, treated as in-memory list of example dicts.
- Raises:
ValueError – on invalid JSON structure or unsupported source type.
- Return type:
None
- doc2task(doc_text, taps_root='.', prompt=None, deterministic=False, temperature=0.2, max_tokens=10000, file_names=None, return_raw=False)[source]¶
Reconstruct multiple interdependent source files from a task description, with utils.py treated as optional.
- Parameters:
doc_text (
str
) – Directory, README path, or raw description string.taps_root (
str
) – Root folder to write outputs under <task_name>/.prompt (
Optional
[str
]) – Custom instruction prompt (defaults shown below).deterministic (
bool
) – Force deterministic sampling.temperature (
float
) – Sampling temperature.max_tokens (
int
) – Max tokens to generate.file_names (
Optional
[List
[str
]]) – List of filenames to request. Defaults to [“run_trial.py”,”utils.py”,”main.py”,”config.yaml”].return_raw (
bool
) – If True, return raw LLM markdown; no files written.
- Return type:
Union
[str
,Dict
[str
,str
]]- Returns:
If return_raw: the raw markdown string from the LLM.
Otherwise: a dict mapping each filename → its saved path (excluding any empty utils.py).
- Raises:
ValueError – if any required section is missing (all except utils.py).
- generate(prompt, *, deterministic=False, **kwargs)[source]¶
Generate text completion from the configured model.
- Parameters:
prompt (
str
) – Input prompt for the LLM.deterministic (
bool
) – If True, zero out sampling randomness.kwargs – Additional generation parameters (e.g., temperature, stop).
- Return type:
str
- Returns:
Generated text response.
- Raises:
LLMAPIError – If the provider returns an error.
- list_models()[source]¶
Retrieve a list of available model IDs for the current provider.
- Return type:
List
[str
]- Returns:
List of model identifiers.
- Raises:
LLMAPIError – If no models are returned or listing fails.
- classmethod register_provider(name, handler)[source]¶
Register a custom provider handler.
- Parameters:
name (
str
) – Identifier for the custom provider.handler (
Callable
[[str
,Dict
[str
,Any
]],str
]) – Callable that takes (prompt, kwargs) and returns response string.
- save_knowledge(json_path)[source]¶
Write current knowledge_base (a list of dicts) to a JSON file.
- Return type:
None
- save_readme(*args)[source]¶
- Return type:
None
- Save a README to disk. Call as either:
save_readme(output_path) save_readme(content, output_path)
If only output_path is provided, uses self.last_response.
- task2doc(logic_paths=None, config_paths=None, prompt=None, deterministic=False, temperature=0.2, max_tokens=1500, output_path=None)[source]¶
Summarize a task into README.md. If prompt is None, loads the instruction template from psyflow/templates/task2doc_prompt.txt.
- Return type:
str
- test(ping='Hello', max_tokens=1)[source]¶
Smoke test connection and small completion.
Ensures the configured model exists.
Sends a small ping and returns its response.
- Parameters:
ping (
str
) – Prompt to send for testing.max_tokens (
int
) – Maximum tokens to request.
- Return type:
Optional
[str
]- Returns:
Ping response string.
- Raises:
LLMAPIError – On model not found or generation failure.
- translate(text, target_language, prompt=None, deterministic=False, temperature=0.2, max_tokens=800)[source]¶
Translate arbitrary text into the target language, preserving formatting and placeholders. Returns only the translated text—no explanations.
- Return type:
str
- translate_config(target_language, config=None, output_dir=None, output_name=None, prompt=None, deterministic=False, temperature=0.2, max_tokens=500)[source]¶
- Return type:
Dict
[str
,Any
]
- Translate selected fields of a YAML config:
subinfo_mapping values
any stimuli entries where type is ‘text’ or ‘textbox’
- If config is:
a file path (str) → loaded via load_config()
a dict returned from load_config()
None → defaults to “./config/config.yaml”
- If output_dir is provided, writes out a translated YAML:
filename is output_name if given, else original basename + “.translated.yaml”.
Returns the updated raw YAML dict.
psyflow.utils module¶
- psyflow.utils.count_down(win, seconds=3, **stim_kwargs)[source]¶
Display a frame-accurate countdown using TextStim.
- Parameters:
win (psychopy.visual.Window) – The PsychoPy window to display the countdown in.
seconds (int) – How many seconds to count down from.
**stim_kwargs (dict) – Additional keyword arguments for TextStim (e.g., font, height, color).
- Returns:
The countdown is shown on
win
for its side effect.- Return type:
None
- psyflow.utils.initialize_exp(settings, screen_id=1)[source]¶
Set up the PsychoPy window, keyboard and logging.
- Parameters:
settings (Any) – Configuration object with attributes describing window and logging settings.
screen_id (int, optional) – Monitor index to open the window on. Defaults to
1
.
- Returns:
The created PsychoPy
Window
andKeyboard
objects.- Return type:
tuple of (Window, Keyboard)
Examples
>>> win, kb = initialize_exp(my_settings)
- psyflow.utils.list_serial_ports()[source]¶
Alias for
show_ports()
.- Returns:
This function simply calls
show_ports()
and prints the ports.- Return type:
None
- psyflow.utils.list_supported_voices(filter_lang=None, human_readable=False)[source]¶
Query available edge-tts voices.
- Parameters:
filter_lang (str, optional) – Return only voices whose locale starts with this prefix.
human_readable (bool, optional) – If
True
print a formatted table; otherwise return the raw list.
- Returns:
The raw voice dictionaries if
human_readable
isFalse
, otherwiseNone
.- Return type:
list of dict or None
- psyflow.utils.load_config(config_file='config/config.yaml', extra_keys=None)[source]¶
Load a config.yaml file and return a structured dictionary.
- Parameters:
config_file (str) – Path to YAML config file.
extra_keys (list of str, optional) – Additional top-level keys to extract as ‘xxx_config’.
- Returns:
Dictionary with structured configs.
- Return type:
dict
Examples
>>> cfg = load_config('config/config.yaml') >>> cfg['task_config']['screen_width']
- psyflow.utils.show_ports()[source]¶
List all available serial ports.
The function prints a numbered list of connected serial ports with a short description. It is mainly intended for quick troubleshooting when choosing a port for trigger boxes or external devices.
- Returns:
This function is executed for its side effect of printing to
stdout
.- Return type:
None
- psyflow.utils.taps(task_name, template='cookiecutter-psyflow')[source]¶
Generate a task skeleton using the bundled template.
- Parameters:
task_name (str) – Name of the new task directory to create.
template (str, optional) – Name of the template folder inside the package. Defaults to
"cookiecutter-psyflow"
.
- Returns:
Path to the newly created project directory.
- Return type:
str
Examples
>>> taps("mytask") "mytask"
Module contents¶
psyflow: A utility package for modular PsychoPy experiment development.