senselab.audio.tasks.speech_to_text.api

This module represents the API for the speech-to-text task within the senselab package.

Currently, it supports only Hugging Face models, with plans to include more in the future. Users can specify the audio clips to transcribe, the ASR model, the language, the preferred device, and the model-specific parameters, and senselab handles the rest.

 1"""This module represents the API for the speech-to-text task within the senselab package.
 2
 3Currently, it supports only Hugging Face models, with plans to include more in the future.
 4Users can specify the audio clips to transcribe, the ASR model, the language,
 5the preferred device, and the model-specific parameters, and senselab handles the rest.
 6"""
 7
 8from typing import Any, List, Optional
 9
10from senselab.audio.data_structures import Audio
11from senselab.audio.tasks.speech_to_text.huggingface import HuggingFaceASR
12from senselab.utils.data_structures import DeviceType, HFModel, Language, ScriptLine, SenselabModel
13
14
15def transcribe_audios(
16    audios: List[Audio],
17    model: SenselabModel,
18    language: Optional[Language] = None,
19    device: Optional[DeviceType] = None,
20    **kwargs: Any,  # noqa: ANN401
21) -> List[ScriptLine]:
22    """Transcribe a batch of `Audio` objects using an ASR model.
23
24    Currently supports **Hugging Face** models (via Transformers). For best throughput,
25    pass the **entire list** of audios in one call so that a single ASR pipeline is
26    initialized and reused internally.
27
28    Args:
29        audios (list[Audio]):
30            Audio objects to transcribe. Typical ASR models expect **mono, fixed
31            sampling rate** (e.g., Whisper expects mono 16 kHz). Validate upstream.
32        model (SenselabModel):
33            The ASR model to use. **Only `HFModel` is supported** at present.
34        language (Language, optional):
35            Spoken language hint for decoding (passed to the HF pipeline when supported).
36        device (DeviceType, optional):
37            Preferred device for inference. For HF ASR we currently support
38            ``DeviceType.CPU`` and ``DeviceType.CUDA``. If None, the backend will choose
39            ``CUDA`` if available, otherwise ``CPU``.
40        **kwargs:
41            Model-specific options forwarded to the HF ASR helper, e.g.:
42              * ``return_timestamps``: ``"word"`` | ``"segment"`` | ``None``
43              * ``max_new_tokens``: ``int`` (default 128)
44              * ``chunk_length_s``: ``int`` seconds (default 30)
45              * ``batch_size``: ``int`` (default 1)
46
47    Returns:
48        list[ScriptLine]: One transcript object per input audio, preserving order.
49
50    Raises:
51        NotImplementedError: If `model` is not an instance of `HFModel`.
52        TypeError: If invalid keyword arguments are provided downstream.
53
54    Todo:
55        - Include more models (e.g., speechbrain, nvidia)
56
57    Example (default settings on CPU):
58        >>> from pathlib import Path
59        >>> from senselab.audio.data_structures import Audio
60        >>> from senselab.utils.data_structures import HFModel, DeviceType, Language
61        >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
62        >>> a2 = Audio(filepath=Path("sample2.wav").resolve())
63        >>> model = HFModel(path_or_uri="openai/whisper-tiny")
64        >>> lines = transcribe_audios([a1, a2], model, language=Language.EN, device=DeviceType.CPU)
65        >>> lines[0].text
66
67    Example (timestamps, longer chunks, CUDA):
68        >>> from pathlib import Path
69        >>> from senselab.audio.data_structures import Audio
70        >>> from senselab.utils.data_structures import HFModel, DeviceType, Language
71        >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
72        >>> model = HFModel(path_or_uri="openai/whisper-small", revision="main")
73        >>> lines = transcribe_audios(
74        ...     [a1],
75        ...     model,
76        ...     language=Language.EN,
77        ...     device=DeviceType.CUDA,
78        ...     return_timestamps="word",
79        ...     chunk_length_s=30,
80        ...     batch_size=1,
81        ... )
82        >>> lines[0].timestamps
83    """
84    try:
85        if isinstance(model, HFModel):
86            return HuggingFaceASR.transcribe_audios_with_transformers(
87                audios=audios, model=model, language=language, device=device, **kwargs
88            )
89        else:
90            raise NotImplementedError(
91                "Only Hugging Face models are supported for now. We aim to support more models in the future."
92            )
93    except TypeError as e:
94        raise TypeError(e)
16def transcribe_audios(
17    audios: List[Audio],
18    model: SenselabModel,
19    language: Optional[Language] = None,
20    device: Optional[DeviceType] = None,
21    **kwargs: Any,  # noqa: ANN401
22) -> List[ScriptLine]:
23    """Transcribe a batch of `Audio` objects using an ASR model.
24
25    Currently supports **Hugging Face** models (via Transformers). For best throughput,
26    pass the **entire list** of audios in one call so that a single ASR pipeline is
27    initialized and reused internally.
28
29    Args:
30        audios (list[Audio]):
31            Audio objects to transcribe. Typical ASR models expect **mono, fixed
32            sampling rate** (e.g., Whisper expects mono 16 kHz). Validate upstream.
33        model (SenselabModel):
34            The ASR model to use. **Only `HFModel` is supported** at present.
35        language (Language, optional):
36            Spoken language hint for decoding (passed to the HF pipeline when supported).
37        device (DeviceType, optional):
38            Preferred device for inference. For HF ASR we currently support
39            ``DeviceType.CPU`` and ``DeviceType.CUDA``. If None, the backend will choose
40            ``CUDA`` if available, otherwise ``CPU``.
41        **kwargs:
42            Model-specific options forwarded to the HF ASR helper, e.g.:
43              * ``return_timestamps``: ``"word"`` | ``"segment"`` | ``None``
44              * ``max_new_tokens``: ``int`` (default 128)
45              * ``chunk_length_s``: ``int`` seconds (default 30)
46              * ``batch_size``: ``int`` (default 1)
47
48    Returns:
49        list[ScriptLine]: One transcript object per input audio, preserving order.
50
51    Raises:
52        NotImplementedError: If `model` is not an instance of `HFModel`.
53        TypeError: If invalid keyword arguments are provided downstream.
54
55    Todo:
56        - Include more models (e.g., speechbrain, nvidia)
57
58    Example (default settings on CPU):
59        >>> from pathlib import Path
60        >>> from senselab.audio.data_structures import Audio
61        >>> from senselab.utils.data_structures import HFModel, DeviceType, Language
62        >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
63        >>> a2 = Audio(filepath=Path("sample2.wav").resolve())
64        >>> model = HFModel(path_or_uri="openai/whisper-tiny")
65        >>> lines = transcribe_audios([a1, a2], model, language=Language.EN, device=DeviceType.CPU)
66        >>> lines[0].text
67
68    Example (timestamps, longer chunks, CUDA):
69        >>> from pathlib import Path
70        >>> from senselab.audio.data_structures import Audio
71        >>> from senselab.utils.data_structures import HFModel, DeviceType, Language
72        >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
73        >>> model = HFModel(path_or_uri="openai/whisper-small", revision="main")
74        >>> lines = transcribe_audios(
75        ...     [a1],
76        ...     model,
77        ...     language=Language.EN,
78        ...     device=DeviceType.CUDA,
79        ...     return_timestamps="word",
80        ...     chunk_length_s=30,
81        ...     batch_size=1,
82        ... )
83        >>> lines[0].timestamps
84    """
85    try:
86        if isinstance(model, HFModel):
87            return HuggingFaceASR.transcribe_audios_with_transformers(
88                audios=audios, model=model, language=language, device=device, **kwargs
89            )
90        else:
91            raise NotImplementedError(
92                "Only Hugging Face models are supported for now. We aim to support more models in the future."
93            )
94    except TypeError as e:
95        raise TypeError(e)

Transcribe a batch of Audio objects using an ASR model.

Currently supports Hugging Face models (via Transformers). For best throughput, pass the entire list of audios in one call so that a single ASR pipeline is initialized and reused internally.

Arguments:
  • audios (list[Audio]): Audio objects to transcribe. Typical ASR models expect mono, fixed sampling rate (e.g., Whisper expects mono 16 kHz). Validate upstream.
  • model (SenselabModel): The ASR model to use. Only HFModel is supported at present.
  • language (Language, optional): Spoken language hint for decoding (passed to the HF pipeline when supported).
  • device (DeviceType, optional): Preferred device for inference. For HF ASR we currently support DeviceType.CPU and DeviceType.CUDA. If None, the backend will choose CUDA if available, otherwise CPU.
  • **kwargs: Model-specific options forwarded to the HF ASR helper, e.g.:
    • return_timestamps: "word" | "segment" | None
    • max_new_tokens: int (default 128)
    • chunk_length_s: int seconds (default 30)
    • batch_size: int (default 1)
Returns:

list[ScriptLine]: One transcript object per input audio, preserving order.

Raises:
  • NotImplementedError: If model is not an instance of HFModel.
  • TypeError: If invalid keyword arguments are provided downstream.
Todo:
  • Include more models (e.g., speechbrain, nvidia)

Example (default settings on CPU):

from pathlib import Path from senselab.audio.data_structures import Audio from senselab.utils.data_structures import HFModel, DeviceType, Language a1 = Audio(filepath=Path("sample1.wav").resolve()) a2 = Audio(filepath=Path("sample2.wav").resolve()) model = HFModel(path_or_uri="openai/whisper-tiny") lines = transcribe_audios([a1, a2], model, language=Language.EN, device=DeviceType.CPU) lines[0].text

Example (timestamps, longer chunks, CUDA):

from pathlib import Path from senselab.audio.data_structures import Audio from senselab.utils.data_structures import HFModel, DeviceType, Language a1 = Audio(filepath=Path("sample1.wav").resolve()) model = HFModel(path_or_uri="openai/whisper-small", revision="main") lines = transcribe_audios( ... [a1], ... model, ... language=Language.EN, ... device=DeviceType.CUDA, ... return_timestamps="word", ... chunk_length_s=30, ... batch_size=1, ... ) lines[0].timestamps