senselab.audio.tasks.speech_to_text.huggingface

This module provides a factory for managing Hugging Face ASR pipelines.

To ensure correct functionality, call transcribe_audios_with_transformers serially or, if you need to process multiple audios in parallel, pass the entire list of audios to the function at once, rather than calling the function with one audio at a time.

  1"""This module provides a factory for managing Hugging Face ASR pipelines.
  2
  3To ensure correct functionality, call `transcribe_audios_with_transformers` serially or,
  4if you need to process multiple audios in parallel, pass the entire list of audios to the
  5function at once, rather than calling the function with one audio at a time.
  6"""
  7
  8import time
  9from typing import Any, Dict, List, Optional, cast
 10
 11from transformers import Pipeline, pipeline
 12
 13from senselab.audio.data_structures import Audio
 14from senselab.utils.data_structures import DeviceType, HFModel, Language, ScriptLine, _select_device_and_dtype
 15from senselab.utils.data_structures.logging import logger
 16
 17
 18class HuggingFaceASR:
 19    """Factory for creating and caching Hugging Face ASR pipelines.
 20
 21    Pipelines are cached per *(model, revision, timestamps level, generation limits,
 22    chunk length, batch size, device)* so repeated calls with the same settings reuse
 23    the initialized pipeline.
 24    """
 25
 26    _pipelines: Dict[str, Pipeline] = {}
 27
 28    @classmethod
 29    def _get_hf_asr_pipeline(
 30        cls,
 31        model: HFModel,
 32        return_timestamps: Optional[str],
 33        max_new_tokens: int,
 34        chunk_length_s: int,
 35        batch_size: int,
 36        device: Optional[DeviceType] = None,
 37    ) -> Pipeline:
 38        """Get or create a Hugging Face ASR pipeline.
 39
 40        Args:
 41            model (HFModel): The Hugging Face model.
 42            return_timestamps (Optional[str]): The level of timestamp details.
 43            max_new_tokens (int): The maximum number of new tokens.
 44            chunk_length_s (int): The length of audio chunks in seconds.
 45            batch_size (int): The batch size for processing.
 46            device (Optional[DeviceType]): The device to run the model on.
 47
 48        Returns:
 49            Pipeline: The ASR pipeline.
 50        """
 51        device, _ = _select_device_and_dtype(
 52            user_preference=device, compatible_devices=[DeviceType.CUDA, DeviceType.CPU]
 53        )
 54        key = (
 55            f"{model.path_or_uri}-{model.revision}-{return_timestamps}-"
 56            f"{max_new_tokens}-{chunk_length_s}-{batch_size}-{device.value}"
 57        )
 58        if key not in cls._pipelines:
 59            cls._pipelines[key] = cast(
 60                Pipeline,
 61                pipeline(  # type: ignore[call-overload]
 62                    task="automatic-speech-recognition",
 63                    model=model.path_or_uri,
 64                    revision=model.revision,
 65                    return_timestamps=return_timestamps,
 66                    max_new_tokens=max_new_tokens,
 67                    chunk_length_s=chunk_length_s,
 68                    batch_size=batch_size,
 69                    device=device.value,
 70                ),
 71            )
 72        return cls._pipelines[key]
 73
 74    @classmethod
 75    def transcribe_audios_with_transformers(
 76        cls,
 77        audios: List[Audio],
 78        model: Optional[HFModel] = None,
 79        language: Optional[Language] = None,
 80        return_timestamps: Optional[str] = "word",
 81        max_new_tokens: int = 128,
 82        chunk_length_s: int = 30,
 83        batch_size: int = 1,
 84        device: Optional[DeviceType] = None,
 85    ) -> List[ScriptLine]:
 86        """Transcribe a list of `Audio` objects with a cached HF ASR pipeline.
 87
 88        Initializes (or reuses) a Transformers ASR pipeline and decodes all inputs
 89        in one call. Output keys are normalized (``"timestamp"`` → ``"timestamps"``)
 90        before converting to `ScriptLine`.
 91
 92        Requirements:
 93            - **Mono** input (shape `[1, T]`). Stereo is rejected.
 94            - Sampling rate must match the model’s **expected sampling rate**
 95              (read from the pipeline’s `feature_extractor.sampling_rate`).
 96
 97        Args:
 98            audios (list[Audio]):
 99                Audio objects to transcribe (mono, correct sampling rate).
100            model (HFModel, optional):
101                HF model to use. Defaults to ``HFModel("openai/whisper-tiny")``.
102            language (Language, optional):
103                Language hint (lowercased and passed via `generate_kwargs` when supported).
104            return_timestamps (str | None, optional):
105                Timestamp granularity. Defaults to ``"word"``.
106            max_new_tokens (int, optional):
107                Decoder limit per chunk. Defaults to ``128``.
108            chunk_length_s (int, optional):
109                Chunk length (seconds). Defaults to ``30``.
110            batch_size (int, optional):
111                Pipeline batch size. Defaults to ``1``.
112                Note: large values can degrade timestamp quality for long audios
113                (see HF issue discussions).
114            device (DeviceType, optional):
115                Inference device; supports ``CPU`` and ``CUDA`` here. If ``None``,
116                the backend will choose ``CUDA`` if available, otherwise ``CPU``.
117
118        Returns:
119            list[ScriptLine]: One transcript per input audio (order-preserving).
120
121        Raises:
122            ValueError:
123                If inputs are not mono or their sampling rate mismatches the model.
124            RuntimeError | OSError:
125                Any underlying HF/Transformers loading or runtime error.
126
127        Example (default model, CPU):
128            >>> from pathlib import Path
129            >>> from senselab.audio.data_structures import Audio
130            >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
131            >>> lines = HuggingFaceASR.transcribe_audios_with_transformers([a1])
132            >>> lines[0].text
133
134        Example (small Whisper, CUDA, word timestamps):
135            >>> from pathlib import Path
136            >>> from senselab.audio.data_structures import Audio
137            >>> from senselab.utils.data_structures import HFModel, DeviceType, Language
138            >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
139            >>> mdl = HFModel(path_or_uri="openai/whisper-small", revision="main")
140            >>> lines = HuggingFaceASR.transcribe_audios_with_transformers(
141            ...     [a1],
142            ...     model=mdl,
143            ...     language=Language.EN,
144            ...     return_timestamps="word",
145            ...     chunk_length_s=30,
146            ...     batch_size=1,
147            ...     device=DeviceType.CUDA,
148            ... )
149            >>> lines[0].timestamps
150        """
151        if model is None:
152            model = HFModel(path_or_uri="openai/whisper-tiny")
153
154        def _audio_to_huggingface_dict(audio: Audio) -> Dict:
155            """Convert an Audio object to a dictionary that can be used by the transformers pipeline.
156
157            Args:
158                audio (Audio): The audio object.
159
160            Returns:
161                Dict: The dictionary representation of the audio object.
162            """
163            return {
164                "array": audio.waveform.squeeze().numpy(),
165                "sampling_rate": audio.sampling_rate,
166            }
167
168        def _rename_key_recursive(obj: Dict[str, Any], old_key: str, new_key: str) -> Dict[str, Any]:
169            """Recursively rename keys in a dictionary."""
170            if isinstance(obj, dict):
171                for key in list(obj.keys()):
172                    if key == old_key:
173                        obj[new_key] = obj.pop(old_key)
174                    elif isinstance(obj[key], (dict, list)):
175                        obj[key] = _rename_key_recursive(obj[key], old_key, new_key)
176            elif isinstance(obj, list):
177                obj = [_rename_key_recursive(item, old_key, new_key) for item in obj]
178            return obj
179
180        # Take the start time of the pipeline initialization
181        start_time_pipeline = time.time()
182        # Get the Hugging Face pipeline
183        pipe = HuggingFaceASR._get_hf_asr_pipeline(
184            model=model,
185            return_timestamps=return_timestamps,
186            max_new_tokens=max_new_tokens,
187            chunk_length_s=chunk_length_s,
188            batch_size=batch_size,
189            device=device,
190        )
191
192        # Take the end time of the pipeline initialization
193        end_time_pipeline = time.time()
194        # Print the time taken for initialize the hugging face ASR pipeline
195        elapsed_time_pipeline = end_time_pipeline - start_time_pipeline
196        logger.info(f"Time taken to initialize the hugging face ASR pipeline: {elapsed_time_pipeline:.2f} seconds")
197
198        feature_extractor = getattr(pipe, "feature_extractor", None)
199        if feature_extractor is None:
200            raise ValueError("Internal error: The Hugging Face pipeline does not have a feature extractor.")
201
202        # Retrieve the expected sampling rate from the Hugging Face model
203        expected_sampling_rate = cast(int, getattr(feature_extractor, "sampling_rate", None))
204        if expected_sampling_rate is None:
205            raise ValueError("Internal error: The Hugging Face model does not specify an expected sampling rate.")
206
207        # Check that all audio objects are mono
208        for audio in audios:
209            if audio.waveform.shape[0] != 1:
210                raise ValueError(f"Stereo audio is not supported. Got {audio.waveform.shape[0]} channels")
211            if audio.sampling_rate != expected_sampling_rate:
212                raise ValueError(
213                    f"Incorrect sampling rate. Expected {expected_sampling_rate}" f", got {audio.sampling_rate}"
214                )
215
216        # Convert the audio objects to dictionaries that can be used by the pipeline
217        formatted_audios = [_audio_to_huggingface_dict(audio) for audio in audios]
218
219        # Take the start time of the transcription
220        start_time_transcription = time.time()
221        # Run the pipeline
222        transcriptions = pipe(
223            formatted_audios,
224            generate_kwargs={"language": f"{language.name.lower()}", "num_beams": 1} if language else {"num_beams": 1},
225        )
226
227        # Take the end time of the transcription
228        end_time_transcription = time.time()
229        # Print the time taken for transcribing the audios
230        elapsed_time_transcription = end_time_transcription - start_time_transcription
231        logger.info(f"Time taken for transcribing the audios: {elapsed_time_transcription:.2f} seconds")
232
233        # Rename the "timestamp" key to "timestamps"
234        transcriptions = _rename_key_recursive(transcriptions, "timestamp", "timestamps")
235
236        # Convert the pipeline output to ScriptLine objects
237        return [ScriptLine.from_dict(cast(Dict[str, Any], t)) for t in transcriptions]
class HuggingFaceASR:
 19class HuggingFaceASR:
 20    """Factory for creating and caching Hugging Face ASR pipelines.
 21
 22    Pipelines are cached per *(model, revision, timestamps level, generation limits,
 23    chunk length, batch size, device)* so repeated calls with the same settings reuse
 24    the initialized pipeline.
 25    """
 26
 27    _pipelines: Dict[str, Pipeline] = {}
 28
 29    @classmethod
 30    def _get_hf_asr_pipeline(
 31        cls,
 32        model: HFModel,
 33        return_timestamps: Optional[str],
 34        max_new_tokens: int,
 35        chunk_length_s: int,
 36        batch_size: int,
 37        device: Optional[DeviceType] = None,
 38    ) -> Pipeline:
 39        """Get or create a Hugging Face ASR pipeline.
 40
 41        Args:
 42            model (HFModel): The Hugging Face model.
 43            return_timestamps (Optional[str]): The level of timestamp details.
 44            max_new_tokens (int): The maximum number of new tokens.
 45            chunk_length_s (int): The length of audio chunks in seconds.
 46            batch_size (int): The batch size for processing.
 47            device (Optional[DeviceType]): The device to run the model on.
 48
 49        Returns:
 50            Pipeline: The ASR pipeline.
 51        """
 52        device, _ = _select_device_and_dtype(
 53            user_preference=device, compatible_devices=[DeviceType.CUDA, DeviceType.CPU]
 54        )
 55        key = (
 56            f"{model.path_or_uri}-{model.revision}-{return_timestamps}-"
 57            f"{max_new_tokens}-{chunk_length_s}-{batch_size}-{device.value}"
 58        )
 59        if key not in cls._pipelines:
 60            cls._pipelines[key] = cast(
 61                Pipeline,
 62                pipeline(  # type: ignore[call-overload]
 63                    task="automatic-speech-recognition",
 64                    model=model.path_or_uri,
 65                    revision=model.revision,
 66                    return_timestamps=return_timestamps,
 67                    max_new_tokens=max_new_tokens,
 68                    chunk_length_s=chunk_length_s,
 69                    batch_size=batch_size,
 70                    device=device.value,
 71                ),
 72            )
 73        return cls._pipelines[key]
 74
 75    @classmethod
 76    def transcribe_audios_with_transformers(
 77        cls,
 78        audios: List[Audio],
 79        model: Optional[HFModel] = None,
 80        language: Optional[Language] = None,
 81        return_timestamps: Optional[str] = "word",
 82        max_new_tokens: int = 128,
 83        chunk_length_s: int = 30,
 84        batch_size: int = 1,
 85        device: Optional[DeviceType] = None,
 86    ) -> List[ScriptLine]:
 87        """Transcribe a list of `Audio` objects with a cached HF ASR pipeline.
 88
 89        Initializes (or reuses) a Transformers ASR pipeline and decodes all inputs
 90        in one call. Output keys are normalized (``"timestamp"`` → ``"timestamps"``)
 91        before converting to `ScriptLine`.
 92
 93        Requirements:
 94            - **Mono** input (shape `[1, T]`). Stereo is rejected.
 95            - Sampling rate must match the model’s **expected sampling rate**
 96              (read from the pipeline’s `feature_extractor.sampling_rate`).
 97
 98        Args:
 99            audios (list[Audio]):
100                Audio objects to transcribe (mono, correct sampling rate).
101            model (HFModel, optional):
102                HF model to use. Defaults to ``HFModel("openai/whisper-tiny")``.
103            language (Language, optional):
104                Language hint (lowercased and passed via `generate_kwargs` when supported).
105            return_timestamps (str | None, optional):
106                Timestamp granularity. Defaults to ``"word"``.
107            max_new_tokens (int, optional):
108                Decoder limit per chunk. Defaults to ``128``.
109            chunk_length_s (int, optional):
110                Chunk length (seconds). Defaults to ``30``.
111            batch_size (int, optional):
112                Pipeline batch size. Defaults to ``1``.
113                Note: large values can degrade timestamp quality for long audios
114                (see HF issue discussions).
115            device (DeviceType, optional):
116                Inference device; supports ``CPU`` and ``CUDA`` here. If ``None``,
117                the backend will choose ``CUDA`` if available, otherwise ``CPU``.
118
119        Returns:
120            list[ScriptLine]: One transcript per input audio (order-preserving).
121
122        Raises:
123            ValueError:
124                If inputs are not mono or their sampling rate mismatches the model.
125            RuntimeError | OSError:
126                Any underlying HF/Transformers loading or runtime error.
127
128        Example (default model, CPU):
129            >>> from pathlib import Path
130            >>> from senselab.audio.data_structures import Audio
131            >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
132            >>> lines = HuggingFaceASR.transcribe_audios_with_transformers([a1])
133            >>> lines[0].text
134
135        Example (small Whisper, CUDA, word timestamps):
136            >>> from pathlib import Path
137            >>> from senselab.audio.data_structures import Audio
138            >>> from senselab.utils.data_structures import HFModel, DeviceType, Language
139            >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
140            >>> mdl = HFModel(path_or_uri="openai/whisper-small", revision="main")
141            >>> lines = HuggingFaceASR.transcribe_audios_with_transformers(
142            ...     [a1],
143            ...     model=mdl,
144            ...     language=Language.EN,
145            ...     return_timestamps="word",
146            ...     chunk_length_s=30,
147            ...     batch_size=1,
148            ...     device=DeviceType.CUDA,
149            ... )
150            >>> lines[0].timestamps
151        """
152        if model is None:
153            model = HFModel(path_or_uri="openai/whisper-tiny")
154
155        def _audio_to_huggingface_dict(audio: Audio) -> Dict:
156            """Convert an Audio object to a dictionary that can be used by the transformers pipeline.
157
158            Args:
159                audio (Audio): The audio object.
160
161            Returns:
162                Dict: The dictionary representation of the audio object.
163            """
164            return {
165                "array": audio.waveform.squeeze().numpy(),
166                "sampling_rate": audio.sampling_rate,
167            }
168
169        def _rename_key_recursive(obj: Dict[str, Any], old_key: str, new_key: str) -> Dict[str, Any]:
170            """Recursively rename keys in a dictionary."""
171            if isinstance(obj, dict):
172                for key in list(obj.keys()):
173                    if key == old_key:
174                        obj[new_key] = obj.pop(old_key)
175                    elif isinstance(obj[key], (dict, list)):
176                        obj[key] = _rename_key_recursive(obj[key], old_key, new_key)
177            elif isinstance(obj, list):
178                obj = [_rename_key_recursive(item, old_key, new_key) for item in obj]
179            return obj
180
181        # Take the start time of the pipeline initialization
182        start_time_pipeline = time.time()
183        # Get the Hugging Face pipeline
184        pipe = HuggingFaceASR._get_hf_asr_pipeline(
185            model=model,
186            return_timestamps=return_timestamps,
187            max_new_tokens=max_new_tokens,
188            chunk_length_s=chunk_length_s,
189            batch_size=batch_size,
190            device=device,
191        )
192
193        # Take the end time of the pipeline initialization
194        end_time_pipeline = time.time()
195        # Print the time taken for initialize the hugging face ASR pipeline
196        elapsed_time_pipeline = end_time_pipeline - start_time_pipeline
197        logger.info(f"Time taken to initialize the hugging face ASR pipeline: {elapsed_time_pipeline:.2f} seconds")
198
199        feature_extractor = getattr(pipe, "feature_extractor", None)
200        if feature_extractor is None:
201            raise ValueError("Internal error: The Hugging Face pipeline does not have a feature extractor.")
202
203        # Retrieve the expected sampling rate from the Hugging Face model
204        expected_sampling_rate = cast(int, getattr(feature_extractor, "sampling_rate", None))
205        if expected_sampling_rate is None:
206            raise ValueError("Internal error: The Hugging Face model does not specify an expected sampling rate.")
207
208        # Check that all audio objects are mono
209        for audio in audios:
210            if audio.waveform.shape[0] != 1:
211                raise ValueError(f"Stereo audio is not supported. Got {audio.waveform.shape[0]} channels")
212            if audio.sampling_rate != expected_sampling_rate:
213                raise ValueError(
214                    f"Incorrect sampling rate. Expected {expected_sampling_rate}" f", got {audio.sampling_rate}"
215                )
216
217        # Convert the audio objects to dictionaries that can be used by the pipeline
218        formatted_audios = [_audio_to_huggingface_dict(audio) for audio in audios]
219
220        # Take the start time of the transcription
221        start_time_transcription = time.time()
222        # Run the pipeline
223        transcriptions = pipe(
224            formatted_audios,
225            generate_kwargs={"language": f"{language.name.lower()}", "num_beams": 1} if language else {"num_beams": 1},
226        )
227
228        # Take the end time of the transcription
229        end_time_transcription = time.time()
230        # Print the time taken for transcribing the audios
231        elapsed_time_transcription = end_time_transcription - start_time_transcription
232        logger.info(f"Time taken for transcribing the audios: {elapsed_time_transcription:.2f} seconds")
233
234        # Rename the "timestamp" key to "timestamps"
235        transcriptions = _rename_key_recursive(transcriptions, "timestamp", "timestamps")
236
237        # Convert the pipeline output to ScriptLine objects
238        return [ScriptLine.from_dict(cast(Dict[str, Any], t)) for t in transcriptions]

Factory for creating and caching Hugging Face ASR pipelines.

Pipelines are cached per (model, revision, timestamps level, generation limits, chunk length, batch size, device) so repeated calls with the same settings reuse the initialized pipeline.

@classmethod
def transcribe_audios_with_transformers( cls, audios: List[senselab.audio.data_structures.audio.Audio], model: Optional[senselab.utils.data_structures.model.HFModel] = None, language: Optional[senselab.utils.data_structures.language.Language] = None, return_timestamps: Optional[str] = 'word', max_new_tokens: int = 128, chunk_length_s: int = 30, batch_size: int = 1, device: Optional[senselab.utils.data_structures.device.DeviceType] = None) -> List[senselab.utils.data_structures.script_line.ScriptLine]:
 75    @classmethod
 76    def transcribe_audios_with_transformers(
 77        cls,
 78        audios: List[Audio],
 79        model: Optional[HFModel] = None,
 80        language: Optional[Language] = None,
 81        return_timestamps: Optional[str] = "word",
 82        max_new_tokens: int = 128,
 83        chunk_length_s: int = 30,
 84        batch_size: int = 1,
 85        device: Optional[DeviceType] = None,
 86    ) -> List[ScriptLine]:
 87        """Transcribe a list of `Audio` objects with a cached HF ASR pipeline.
 88
 89        Initializes (or reuses) a Transformers ASR pipeline and decodes all inputs
 90        in one call. Output keys are normalized (``"timestamp"`` → ``"timestamps"``)
 91        before converting to `ScriptLine`.
 92
 93        Requirements:
 94            - **Mono** input (shape `[1, T]`). Stereo is rejected.
 95            - Sampling rate must match the model’s **expected sampling rate**
 96              (read from the pipeline’s `feature_extractor.sampling_rate`).
 97
 98        Args:
 99            audios (list[Audio]):
100                Audio objects to transcribe (mono, correct sampling rate).
101            model (HFModel, optional):
102                HF model to use. Defaults to ``HFModel("openai/whisper-tiny")``.
103            language (Language, optional):
104                Language hint (lowercased and passed via `generate_kwargs` when supported).
105            return_timestamps (str | None, optional):
106                Timestamp granularity. Defaults to ``"word"``.
107            max_new_tokens (int, optional):
108                Decoder limit per chunk. Defaults to ``128``.
109            chunk_length_s (int, optional):
110                Chunk length (seconds). Defaults to ``30``.
111            batch_size (int, optional):
112                Pipeline batch size. Defaults to ``1``.
113                Note: large values can degrade timestamp quality for long audios
114                (see HF issue discussions).
115            device (DeviceType, optional):
116                Inference device; supports ``CPU`` and ``CUDA`` here. If ``None``,
117                the backend will choose ``CUDA`` if available, otherwise ``CPU``.
118
119        Returns:
120            list[ScriptLine]: One transcript per input audio (order-preserving).
121
122        Raises:
123            ValueError:
124                If inputs are not mono or their sampling rate mismatches the model.
125            RuntimeError | OSError:
126                Any underlying HF/Transformers loading or runtime error.
127
128        Example (default model, CPU):
129            >>> from pathlib import Path
130            >>> from senselab.audio.data_structures import Audio
131            >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
132            >>> lines = HuggingFaceASR.transcribe_audios_with_transformers([a1])
133            >>> lines[0].text
134
135        Example (small Whisper, CUDA, word timestamps):
136            >>> from pathlib import Path
137            >>> from senselab.audio.data_structures import Audio
138            >>> from senselab.utils.data_structures import HFModel, DeviceType, Language
139            >>> a1 = Audio(filepath=Path("sample1.wav").resolve())
140            >>> mdl = HFModel(path_or_uri="openai/whisper-small", revision="main")
141            >>> lines = HuggingFaceASR.transcribe_audios_with_transformers(
142            ...     [a1],
143            ...     model=mdl,
144            ...     language=Language.EN,
145            ...     return_timestamps="word",
146            ...     chunk_length_s=30,
147            ...     batch_size=1,
148            ...     device=DeviceType.CUDA,
149            ... )
150            >>> lines[0].timestamps
151        """
152        if model is None:
153            model = HFModel(path_or_uri="openai/whisper-tiny")
154
155        def _audio_to_huggingface_dict(audio: Audio) -> Dict:
156            """Convert an Audio object to a dictionary that can be used by the transformers pipeline.
157
158            Args:
159                audio (Audio): The audio object.
160
161            Returns:
162                Dict: The dictionary representation of the audio object.
163            """
164            return {
165                "array": audio.waveform.squeeze().numpy(),
166                "sampling_rate": audio.sampling_rate,
167            }
168
169        def _rename_key_recursive(obj: Dict[str, Any], old_key: str, new_key: str) -> Dict[str, Any]:
170            """Recursively rename keys in a dictionary."""
171            if isinstance(obj, dict):
172                for key in list(obj.keys()):
173                    if key == old_key:
174                        obj[new_key] = obj.pop(old_key)
175                    elif isinstance(obj[key], (dict, list)):
176                        obj[key] = _rename_key_recursive(obj[key], old_key, new_key)
177            elif isinstance(obj, list):
178                obj = [_rename_key_recursive(item, old_key, new_key) for item in obj]
179            return obj
180
181        # Take the start time of the pipeline initialization
182        start_time_pipeline = time.time()
183        # Get the Hugging Face pipeline
184        pipe = HuggingFaceASR._get_hf_asr_pipeline(
185            model=model,
186            return_timestamps=return_timestamps,
187            max_new_tokens=max_new_tokens,
188            chunk_length_s=chunk_length_s,
189            batch_size=batch_size,
190            device=device,
191        )
192
193        # Take the end time of the pipeline initialization
194        end_time_pipeline = time.time()
195        # Print the time taken for initialize the hugging face ASR pipeline
196        elapsed_time_pipeline = end_time_pipeline - start_time_pipeline
197        logger.info(f"Time taken to initialize the hugging face ASR pipeline: {elapsed_time_pipeline:.2f} seconds")
198
199        feature_extractor = getattr(pipe, "feature_extractor", None)
200        if feature_extractor is None:
201            raise ValueError("Internal error: The Hugging Face pipeline does not have a feature extractor.")
202
203        # Retrieve the expected sampling rate from the Hugging Face model
204        expected_sampling_rate = cast(int, getattr(feature_extractor, "sampling_rate", None))
205        if expected_sampling_rate is None:
206            raise ValueError("Internal error: The Hugging Face model does not specify an expected sampling rate.")
207
208        # Check that all audio objects are mono
209        for audio in audios:
210            if audio.waveform.shape[0] != 1:
211                raise ValueError(f"Stereo audio is not supported. Got {audio.waveform.shape[0]} channels")
212            if audio.sampling_rate != expected_sampling_rate:
213                raise ValueError(
214                    f"Incorrect sampling rate. Expected {expected_sampling_rate}" f", got {audio.sampling_rate}"
215                )
216
217        # Convert the audio objects to dictionaries that can be used by the pipeline
218        formatted_audios = [_audio_to_huggingface_dict(audio) for audio in audios]
219
220        # Take the start time of the transcription
221        start_time_transcription = time.time()
222        # Run the pipeline
223        transcriptions = pipe(
224            formatted_audios,
225            generate_kwargs={"language": f"{language.name.lower()}", "num_beams": 1} if language else {"num_beams": 1},
226        )
227
228        # Take the end time of the transcription
229        end_time_transcription = time.time()
230        # Print the time taken for transcribing the audios
231        elapsed_time_transcription = end_time_transcription - start_time_transcription
232        logger.info(f"Time taken for transcribing the audios: {elapsed_time_transcription:.2f} seconds")
233
234        # Rename the "timestamp" key to "timestamps"
235        transcriptions = _rename_key_recursive(transcriptions, "timestamp", "timestamps")
236
237        # Convert the pipeline output to ScriptLine objects
238        return [ScriptLine.from_dict(cast(Dict[str, Any], t)) for t in transcriptions]

Transcribe a list of Audio objects with a cached HF ASR pipeline.

Initializes (or reuses) a Transformers ASR pipeline and decodes all inputs in one call. Output keys are normalized ("timestamp" → "timestamps") before converting to ScriptLine.

Requirements:
  • Mono input (shape [1, T]). Stereo is rejected.
  • Sampling rate must match the model’s expected sampling rate (read from the pipeline’s feature_extractor.sampling_rate).
Arguments:
  • audios (list[Audio]): Audio objects to transcribe (mono, correct sampling rate).
  • model (HFModel, optional): HF model to use. Defaults to HFModel("openai/whisper-tiny").
  • language (Language, optional): Language hint (lowercased and passed via generate_kwargs when supported).
  • return_timestamps (str | None, optional): Timestamp granularity. Defaults to "word".
  • max_new_tokens (int, optional): Decoder limit per chunk. Defaults to 128.
  • chunk_length_s (int, optional): Chunk length (seconds). Defaults to 30.
  • batch_size (int, optional): Pipeline batch size. Defaults to 1. Note: large values can degrade timestamp quality for long audios (see HF issue discussions).
  • device (DeviceType, optional): Inference device; supports CPU and CUDA here. If None, the backend will choose CUDA if available, otherwise CPU.
Returns:

list[ScriptLine]: One transcript per input audio (order-preserving).

Raises:
  • ValueError: If inputs are not mono or their sampling rate mismatches the model.
  • RuntimeError | OSError: Any underlying HF/Transformers loading or runtime error.

Example (default model, CPU):

from pathlib import Path from senselab.audio.data_structures import Audio a1 = Audio(filepath=Path("sample1.wav").resolve()) lines = HuggingFaceASR.transcribe_audios_with_transformers([a1]) lines[0].text

Example (small Whisper, CUDA, word timestamps):

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()) mdl = HFModel(path_or_uri="openai/whisper-small", revision="main") lines = HuggingFaceASR.transcribe_audios_with_transformers( ... [a1], ... model=mdl, ... language=Language.EN, ... return_timestamps="word", ... chunk_length_s=30, ... batch_size=1, ... device=DeviceType.CUDA, ... ) lines[0].timestamps