treble_tsdk.collections.scene_collection

Classes

RenderPathsEntry

Shape of one entry in the render_paths column, matching _render_paths_dtype.

RenderResultEntry

Shape of one entry in the renders column, matching render_result_struct.

SceneCollection

class treble_tsdk.collections.scene_collection.RenderPathsEntry

Shape of one entry in the render_paths column, matching _render_paths_dtype.

total=False because render_to_disk() builds this incrementally — clean_audio_path/separated_track_audio_paths/snr are only present when the corresponding option (target_selection/output_separated_tracks/ calculate_snr) was requested.

__init__(*args, **kwargs)
clean_audio_path: str
noisy_audio_path: str
normalization_coefficient: float
output_path: str
render_mode: str
sampling_rate: float
separated_track_audio_paths: list[str]
snr: list[float]
target_render_mode: str
target_selection: str | None
class treble_tsdk.collections.scene_collection.RenderResultEntry

Shape of one entry in the renders column, matching render_result_struct.

__init__(*args, **kwargs)
clean_audio: bytes | None
noisy_audio: bytes
render_mode: str
sampling_rate: float
separated_track_audio: list[bytes] | None
snr: list[float] | None
target_render_mode: str
target_selection: str | None
class treble_tsdk.collections.scene_collection.SceneCollection
__init__(client: TSDKClient | None = None, data_loader: IRDataLoader = None, description: str = '')

Create a collection of AudioScene objects that can be rendered together.

Parameters:
  • client – TSDKClient used to resolve simulations/devices and to drive remote optimization.

  • data_loader – IRDataLoader used to load and cache IR data.

  • description – Free-text description stored in the collection metadata.

add_column(name: str, mapper: Callable[[T], Any], dtype: polars.DataType | None = None)

Add a column to the collection using a mapper function.

Parameters:
  • name (str) – Name of the column.

  • mapper (Callable[[T], Any]) – Mapper function to get a value. Called for each row in the collection with the item (e.g. Simulation or IRInfo) as a parameter.

  • dtype (pl.DataType) – Data type of the column. If not provided the mapper function will be used to determine the data type.

add_scene(scene: AudioScene)

Append a scene to the collection.

Parameters:

scene – The AudioScene to add.

add_scenes(scenes: list[AudioScene])

Append multiple scenes to the collection in a single batch.

Prefer this over repeated add_scene() calls when adding many scenes (e.g. during generation).

Parameters:

scenes – The AudioScene objects to add.

apply(func: Callable[[polars.DataFrame], polars.DataFrame]) _Self

Apply a DataFrame transformation and return a new collection of the same type.

The returned collection shares cached objects with the original but has an independent DataFrame. The transformation must preserve the required columns.

Parameters:

func (Callable[[pl.DataFrame], pl.DataFrame]) – A function that receives the underlying Polars DataFrame and returns a transformed DataFrame.

Returns:

A new collection of the same type with the transformed DataFrame.

Example:

filtered = coll.apply(lambda df: df.filter(pl.col("x") > 5).sort("y"))
as_remote_optimization_live_progress()

Display a live, auto-refreshing progress view for the remote optimization job.

cancel_remote_optimization()
copy_custom_columns(other_collection: CollectionBase, key_columns: list[str] | None = None, columns_to_copy: list[str] | None = None)
enrich_with_predicted_snr(target_selection: int | str | list[int])

Predict the SNR of each scene for a given target and append the result as a new entry in the predicted_snr column.

Each struct in predicted_snr is keyed by target_selection and holds the predicted SNR (in dB) for that target. Calling this again with the same target_selection skips the matching entry; a different target_selection accumulates as an additional list entry.

SNR prediction requires the IRs to carry per-band spl values (added via IRCollection.enrich_with_acoustic_parameters()) and the audio sources to carry SPL metadata (added via AudioDataset.enrich_with_spl()).

Parameters:

target_selection – Track index, source group name, or list of track indices designating the target.

filter_by_predicted_snr(min_db: float | None = None, max_db: float | None = None, target_selection: int | str | list[int] | None = None) SceneCollection

Return a new collection keeping only scenes whose predicted SNR falls within [min_db, max_db].

Parameters:
  • min_db – Lower bound on predicted SNR in dB. If None, no lower bound is applied.

  • max_db – Upper bound on predicted SNR in dB. If None, no upper bound is applied.

  • target_selection – The target used during enrich_with_predicted_snr(). Required when scenes carry more than one predicted-SNR entry; may be omitted when each scene has a single entry, in which case that entry is used.

Returns:

A new SceneCollection with the matching scenes.

filter_collection(*args, **kwargs) _Self

Filter the collection and return a new collection with matching rows.

Accepts the same arguments as polars.DataFrame.filter().

Returns:

A new collection of the same type containing only the matching rows.

Example:

nearby = coll.filter_collection(pl.col("source_receiver_dist") < 5.0)
get_predicted_snr(scene_id: str, target_selection: int | str | list[int] | None = None) float | None

Retrieve a predicted SNR value for the scene with id scene_id.

When the scene has only one predicted-SNR entry, target_selection may be omitted. When multiple entries exist, supply target_selection to select the matching one.

Parameters:
  • scene_id – The id of the scene in the collection.

  • target_selection – The target selection used during enrich_with_predicted_snr(). Required when the scene has more than one predicted-SNR entry.

Returns:

The predicted SNR in dB, or None when it could not be estimated.

get_remote_optimization_progress() OneOffTaskBundleProgress | None

Fetch a point-in-time progress snapshot for the remote optimization job.

Returns:

The OneOffTaskBundleProgress, or None when no eligible remote render has been started.

get_remote_optimization_token_cost() Decimal

Estimate the token cost of running the remote optimization for this collection.

get_render(scene_id: str, sampling_rate: float | None = None, render_mode: RenderMode | None = None, target_selection: int | str | list[int] | None = None, target_render_mode: TargetRenderMode | WetMonoWindowed | WetDeviceWindowed | None = None) dict

Retrieve a rendered audio entry for the scene with id scene_id.

When the scene has only one render entry, no recipe arguments are needed. When multiple entries exist, narrow the result by supplying one or more recipe arguments.

Parameters:
  • scene_id – The id of the scene in the collection.

  • sampling_rate – Filter by output sampling rate in Hz.

  • render_mode – Filter by render mode.

  • target_selection – Filter by target selection. Required when the scene has more than one render entry.

  • target_render_mode – Filter by target render mode.

Returns:

A dict with keys noisy_audio (AudioSignal), clean_audio (AudioSignal or None), separated_track_audio (list of AudioSignal or None), and snr (float or None).

get_render_paths(scene_id: str, output_path: str | Path | None = None) RenderPathsEntry

Retrieve a render_to_disk() result entry for the scene with id scene_id.

Each output_path holds at most one render_paths entry (see render_to_disk()), so output_path alone always disambiguates. When the scene has only one render_paths entry, output_path may be omitted.

Parameters:
  • scene_id – The id of the scene in the collection.

  • output_path – The output_path used in the render_to_disk() call. Required when the scene has more than one render_paths entry.

Returns:

The matching render_paths entry, with file paths relative to that entry’s output_path.

head(n: int = 5) _Self

Return a new collection with the first n rows.

Parameters:

n (int) – Number of rows, defaults to 5.

Returns:

A new collection of the same type.

plot()

Plot the collection using an interactive widget.

Extends CollectionBase.plot() so the SNR columns become plottable:

  • predicted_snr — one numeric column per distinct target_selection (e.g. predicted_snr ["target"]).

  • renders — one per-channel snr column per distinct render recipe (e.g. renders snr [mono, 0, wet_mono]).

  • render_paths — one per-channel snr column per distinct render recipe across every render_to_disk() call (e.g. SNR [mono, 0, wet_mono]), regardless of how many different output_path values were used. If renders already has a column for that same recipe (from a matching render() call), render_paths reuses it instead of adding a duplicate.

preload_rendered_irs()

Preload the rendered IR data into the data loader.

print_remote_optimization_token_cost()

Print the token cost of running the remote optimization for this collection.

remove_column(name: str)

Remove a column from the collection.

render(sampling_rate: float = 32000, render_mode: RenderMode = RenderMode.AUTO, target_selection: int | str | list[int] | None = None, target_render_mode: TargetRenderMode | WetMonoWindowed | WetDeviceWindowed = TargetRenderMode.WET_MONO, calculate_snr: bool = False, output_separated_tracks: bool = False, show_progress: bool = True, minutes_to_wait: int = 720, max_workers: int | None = None)

Render the Scene Collection and append the results as a new entry in the renders column (a list of render-result structs, one per render call).

Each struct in renders is keyed by the render parameters (sampling_rate, render_mode, target_selection, target_render_mode) and contains the resulting audio bytes plus optional separated_track_audio and snr fields.

Calling render() again with the same key parameters updates the matching entry in place — e.g. re-rendering with calculate_snr=True fills in the snr field of the existing entry rather than adding a new one. Different key parameters accumulate as additional list entries. A matching entry that already has everything requested (SNR/separated tracks) is skipped entirely.

When the collection has scenes eligible for remote optimization and that work has not yet been kicked off, this method will start it and block until completion.

Parameters:
  • sampling_rate – Output sampling rate in Hz.

  • render_mode – Rendering mode for the mixed audio.

  • target_selection – Track index, source group name, or list of indices to isolate as the clean target. If None, no target/clean output is produced.

  • target_render_mode – How the isolated target is rendered.

  • calculate_snr – If True, compute the per-device channel SNR between the rendered target and the noise.

  • output_separated_tracks – If True, also store each separated track.

  • show_progress – If True, show progress bars/live views during remote rendering and scene rendering.

  • minutes_to_wait – Number of minutes to wait for remote optimization to finish. By default this allows for up to 12 hours of waiting before giving up.

  • max_workers – Number of scenes to render concurrently, using a thread pool. Defaults to os.cpu_count().

render_to_disk(output_path: str | Path, sampling_rate: float = 32000, render_mode: RenderMode = RenderMode.AUTO, target_selection: int | str | list[int] | None = None, target_render_mode: TargetRenderMode | WetMonoWindowed | WetDeviceWindowed = TargetRenderMode.WET_MONO, calculate_snr: bool = False, output_separated_tracks: bool = False, collate_fn: Callable[..., None] | None = None, collate_fn_kwargs: dict = {}, show_progress: bool = True, minutes_to_wait: int = 720, max_workers: int | None = None)

Render the Scene Collection to .wav files on disk instead of keeping the rendered audio in memory, and append the result as a new entry in the render_paths column (a list of render-path structs, one per render_to_disk call with a distinct output_path).

Noisy audio is written to output_path/noisy, clean (target) audio to output_path/clean, and separated tracks (if requested) to output_path/separated, each as {scene.id}.wav (separated tracks are suffixed with the track index). Before writing, the noisy and clean audio of a scene are normalized together by their shared peak amplitude.

Each struct in render_paths is keyed by output_path alone — every output_path holds at most one render, since .wav filenames are derived only from scene.id and would otherwise collide on disk. Calling render_to_disk() again with the same output_path overwrites the matching entry (and the .wav files on disk) in place, even if the render recipe (sampling_rate, render_mode, target_selection, target_render_mode) has changed — e.g. re-rendering with calculate_snr=True fills in the snr field and rewrites the audio. A different output_path accumulates as an additional list entry, so the same collection can be rendered to disk multiple times with different settings, each under its own directory.

When the collection has scenes eligible for remote optimization and that work has not yet been kicked off, this method will start it and block until completion.

Parameters:
  • output_path – Directory under which noisy/clean/separated subdirectories are created and populated with .wav files. Also part of the identity of the render_paths entry — reusing the same output_path overwrites the matching entry and its files.

  • sampling_rate – Output sampling rate in Hz.

  • render_mode – Rendering mode for the mixed audio.

  • target_selection – Track index, source group name, or list of indices to isolate as the clean target. If None, no target/clean output is produced.

  • target_render_mode – How the isolated target is rendered.

  • calculate_snr – If True, compute the per-device channel SNR between the rendered target and the noise.

  • output_separated_tracks – If True, also write each separated track to disk.

  • collate_fn – Optional callable invoked once per scene, after that scene’s audio has been written to disk. Called as collate_fn(row, output_path, entry, scene, **collate_fn_kwargs), where row is the scene’s dataframe row, output_path is the render output directory, entry is the render metadata computed for this scene (e.g. normalization_coefficient, noisy_audio_path, clean_audio_path, snr), and scene is the rendered AudioScene itself. Use this to write out anything else derived from the collection, such as transcripts, alongside the rendered audio.

  • collate_fn_kwargs – Optional dict of extra keyword arguments forwarded to every collate_fn call, for passing in custom context (e.g. a model, config, or logger) that isn’t derivable from the row/entry/scene alone.

  • show_progress – If True, show progress bars/live views during remote rendering and scene rendering.

  • minutes_to_wait – Number of minutes to wait for remote optimization to finish. By default this allows for up to 12 hours of waiting before giving up.

  • max_workers – Number of scenes to render concurrently, using a thread pool. Defaults to os.cpu_count(). collate_fn is always called sequentially, once per scene in completion order, on the main thread.

Usage:

def write_transcripts_and_store_irs(row, output_path, entry, scene):
    path = output_path / "transcripts" / f"{row['id']}.txt"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(str(row["track_transcripts"]))

scene_collection.render_to_disk(
    output_path = "rendered_scenes",
    sampling_rate = 32000,
    render_mode = treble.scene.RenderMode.DEVICE,
    target_selection = "speech",
    target_render_mode = treble.scene.TargetRenderMode.DRY_MONO,
    collate_fn=write_transcripts
)
sample_with_distribution(column: str, n_samples: int, distribution: Gaussian | Uniform | LogNormal | Exponential | Bimodal | Beta | ScaledBeta) _Self

Sample rows where the specified column follows a target distribution.

Returns a new collection of the same type containing only the sampled rows.

Parameters:
  • column (str) – The column to sample from.

  • n_samples (int) – The number of rows to sample.

  • distribution (Distribution) – Distribution to sample from.

Returns:

A new collection containing the sampled rows.

sample_with_gaussian_distribution(column: str, n_samples: int, target_mean: float, target_std: float, seed: int = 42)

Sample rows where the specified column follows a target Gaussian distribution.

This is a convenience wrapper around sample_with_distribution.

Parameters:
  • column (str) – The column to sample from.

  • n_samples (int) – The number of rows to sample.

  • target_mean (float) – The target mean for the distribution.

  • target_std (float) – The target standard deviation for the distribution.

  • seed (int) – The random seed for reproducibility.

start_remote_optimization(show_progress: bool = True)

Start the remote optimization for this scene collection.

Parameters:

show_progress – If True, display a live progress view for the processing tasks.

tail(n: int = 5) _Self

Return a new collection with the last n rows.

Parameters:

n (int) – Number of rows, defaults to 5.

Returns:

A new collection of the same type.

wait_for_remote_optimization_processing(minutes_to_wait: int = 720) str | None

Waits until the remote optimization has been completed and then returns the status.

Parameters:

minutes_to_wait – Number of minutes to wait before stopping, defaults to 720 minutes (12 hours).

Returns:

The status of the remote optimization.

write_parquet(path: str | Path, **kwargs)

Write the dataframe to a parquet file.

Parameters:
  • path (str | Path) – Path to the parquet file.

  • kwargs – Additional keyword arguments passed to polars.DataFrame.write_parquet.

property columns: list[str]

List of columns in the DataFrame

property compact_columns: dict[str, int]

Columns to truncate when printing, mapped to their max display length in characters.

property dataframe: polars.DataFrame

Get the collection data as a Polars DataFrame.

Returns pl.DataFrame:

DataFrame containing all collection items and computed columns.

property editable_dataframe: polars.DataFrame

DataFrame with only the user-modifiable (non-locked) columns. The key column is always included in the editable dataframe although it is locked.

property lazy_df: polars.LazyFrame

Lazy access to underlying Polars DataFrame

property locked_columns: list[str]

List of locked columns for the collection. Columns in this list are read-only and cannot be modified by the user.

property remote_optimization_status: SolveTaskStatus | None

Return the aggregate status of the remote optimization job.

Returns:

The SolveTaskStatus, or None when no eligible remote render has been started.

property required_columns: list[str]

List of required columns for the collection.

property scenes: list[AudioScene]

The scenes held by this collection, reconstructed from the dataframe.

Returns:

A list of AudioScene, empty when the collection holds no scenes.