Skip to content

bioamla.viz

bioamla.viz

bioamla.viz — audio visualization domain.

Spectrogram and waveform rendering built on matplotlib and librosa. matplotlib (with the Agg backend) is imported lazily inside the functions that need it, so importing this package stays fast.

Example

from bioamla.viz import generate_spectrogram generate_spectrogram("recording.wav", "out.png", viz_type="mel")

batch_generate_spectrograms

batch_generate_spectrograms(
    input_dir: str,
    output_dir: str,
    viz_type: VisualizationType = "mel",
    sample_rate: int = 16000,
    n_mels: int = 128,
    n_mfcc: int = 40,
    hop_length: int = 512,
    n_fft: int = 2048,
    window: WindowType = "hann",
    figsize: tuple[int, int] = (10, 4),
    cmap: str = "magma",
    db_min: float | None = None,
    db_max: float | None = None,
    dpi: int = 150,
    format: str = "png",
    recursive: bool = True,
    verbose: bool = True,
    on_progress: Callable[[int, int], None] | None = None,
) -> dict

Generate spectrograms for all audio files in a directory.

Parameters:

Name Type Description Default
input_dir str

Directory containing audio files.

required
output_dir str

Directory for output images.

required
viz_type VisualizationType

Type of visualization ('stft', 'mel', 'mfcc', or 'waveform').

'mel'
sample_rate int

Target sample rate for processing.

16000
n_mels int

Number of mel bands (for mel spectrogram).

128
n_mfcc int

Number of MFCCs to compute (for mfcc visualization).

40
hop_length int

Number of samples between successive frames.

512
n_fft int

FFT window size (256-8192 recommended).

2048
window WindowType

Window function name.

'hann'
figsize tuple[int, int]

Figure size as (width, height) in inches.

(10, 4)
cmap str

Colormap for spectrogram visualizations.

'magma'
db_min float | None

Minimum dB value for scaling.

None
db_max float | None

Maximum dB value for scaling.

None
dpi int

Resolution for output images.

150
format str

Output format ('png' or 'jpg').

'png'
recursive bool

Whether to search subdirectories.

True
verbose bool

Whether to print progress messages.

True
on_progress Callable[[int, int], None] | None

Optional (completed, total) progress callback.

None

Returns:

Type Description
dict

Statistics dict with files_processed, files_failed, output_dir.

Raises:

Type Description
NotFoundError

If the input directory does not exist.

compute_mel_spectrogram

compute_mel_spectrogram(
    audio: ndarray,
    sample_rate: int,
    n_fft: int = 2048,
    hop_length: int = 512,
    n_mels: int = 128,
    window: WindowType = "hann",
    fmin: float = 0.0,
    fmax: float | None = None,
    backend: str = "auto",
) -> tuple[np.ndarray, np.ndarray]

Compute a mel spectrogram from an audio signal.

Parameters:

Name Type Description Default
audio ndarray

Audio samples as numpy array.

required
sample_rate int

Sample rate of the audio.

required
n_fft int

FFT window size (256-8192 recommended).

2048
hop_length int

Number of samples between successive frames.

512
n_mels int

Number of mel bands.

128
window WindowType

Window function name.

'hann'
fmin float

Minimum frequency for the mel filterbank.

0.0
fmax float | None

Maximum frequency for the mel filterbank (default: sample_rate/2).

None
backend str

Compute backend — 'auto' (GPU/torch if available, else librosa), 'librosa' (CPU), or 'torch' (force GPU/torch).

'auto'

Returns:

Type Description
tuple[ndarray, ndarray]

Tuple of (times, mel_spectrogram).

compute_stft

compute_stft(
    audio: ndarray,
    sample_rate: int,
    n_fft: int = 2048,
    hop_length: int = 512,
    window: WindowType = "hann",
    backend: str = "auto",
) -> tuple[np.ndarray, np.ndarray, np.ndarray]

Compute the Short-Time Fourier Transform of an audio signal.

Parameters:

Name Type Description Default
audio ndarray

Audio samples as numpy array.

required
sample_rate int

Sample rate of the audio.

required
n_fft int

FFT window size (256-8192 recommended).

2048
hop_length int

Number of samples between successive frames.

512
window WindowType

Window function name.

'hann'
backend str

Compute backend — 'auto' (GPU/torch if available, else librosa), 'librosa' (CPU), or 'torch' (force GPU/torch).

'auto'

Returns:

Type Description
tuple[ndarray, ndarray, ndarray]

Tuple of (frequencies, times, stft_magnitude).

generate_spectrogram

generate_spectrogram(
    audio_path: str,
    output_path: str,
    viz_type: VisualizationType = "mel",
    sample_rate: int = 16000,
    n_mels: int = 128,
    n_mfcc: int = 40,
    hop_length: int = 512,
    n_fft: int = 2048,
    window: WindowType = "hann",
    figsize: tuple[int, int] = (10, 4),
    cmap: str = "magma",
    title: str | None = None,
    db_min: float | None = None,
    db_max: float | None = None,
    dpi: int = 150,
    format: str | None = None,
    show_colorbar: bool = True,
    backend: str = "auto",
) -> str

Generate a spectrogram visualization from an audio file.

Parameters:

Name Type Description Default
audio_path str

Path to the input audio file.

required
output_path str

Path to save the output image.

required
viz_type VisualizationType

Type of visualization ('stft', 'mel', 'mfcc', or 'waveform').

'mel'
sample_rate int

Target sample rate for processing.

16000
n_mels int

Number of mel bands (for mel spectrogram).

128
n_mfcc int

Number of MFCCs to compute (for mfcc visualization).

40
hop_length int

Number of samples between successive frames.

512
n_fft int

FFT window size (256-8192 recommended).

2048
window WindowType

Window function name.

'hann'
figsize tuple[int, int]

Figure size as (width, height) in inches.

(10, 4)
cmap str

Colormap for spectrogram visualizations.

'magma'
title str | None

Optional title for the plot (defaults to filename).

None
db_min float | None

Minimum dB value for scaling.

None
db_max float | None

Maximum dB value for scaling.

None
dpi int

Resolution for output image (dots per inch).

150
format str | None

Output format ('png', 'jpg', 'jpeg'); inferred from extension if None.

None
show_colorbar bool

Whether to show axes/title/colorbar (default: True).

True
backend str

Spectrogram compute backend — 'auto' (GPU/torch if available, else librosa), 'librosa' (CPU), or 'torch' (force GPU/torch).

'auto'

Returns:

Type Description
str

Path to the saved output image (as a string).

Raises:

Type Description
NotFoundError

If the audio file does not exist.

ValueError

If an invalid visualization type or window is specified.

AudioLoadError

If the audio cannot be loaded.

ProcessingError

If the image cannot be written.

spectrogram_to_db

spectrogram_to_db(
    spectrogram: ndarray,
    ref: float | str = "max",
    amin: float = 1e-10,
    top_db: float | None = 80.0,
) -> np.ndarray

Convert a spectrogram to decibel (dB) scale.

Parameters:

Name Type Description Default
spectrogram ndarray

Power or amplitude spectrogram.

required
ref float | str

Reference value for dB computation ('max' or a float).

'max'
amin float

Minimum amplitude threshold (prevents log of zero).

1e-10
top_db float | None

Maximum dynamic range in dB (None disables clipping).

80.0

Returns:

Type Description
ndarray

Spectrogram in dB scale.

spectrogram_to_image

spectrogram_to_image(
    spectrogram: ndarray,
    output_path: str,
    cmap: str = "magma",
    figsize: tuple[int, int] = (10, 4),
    dpi: int = 150,
    format: str | None = None,
    title: str | None = None,
    xlabel: str = "Time",
    ylabel: str = "Frequency",
    colorbar: bool = True,
    colorbar_label: str | None = None,
    vmin: float | None = None,
    vmax: float | None = None,
) -> str

Export a spectrogram array to an image file.

Parameters:

Name Type Description Default
spectrogram ndarray

2D spectrogram array (frequency x time).

required
output_path str

Path to save the output image.

required
cmap str

Colormap for visualization.

'magma'
figsize tuple[int, int]

Figure size as (width, height) in inches.

(10, 4)
dpi int

Resolution for output image (dots per inch).

150
format str | None

Output format ('png', 'jpg', 'jpeg'); inferred from extension if None.

None
title str | None

Optional title for the plot.

None
xlabel str

Label for the x-axis.

'Time'
ylabel str

Label for the y-axis.

'Frequency'
colorbar bool

Whether to include a colorbar.

True
colorbar_label str | None

Label for the colorbar.

None
vmin float | None

Minimum value for color scaling.

None
vmax float | None

Maximum value for color scaling.

None

Returns:

Type Description
str

Path to the saved output image (as a string).

Raises:

Type Description
ProcessingError

If the image cannot be written.