o
    ei                     @   s  d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
Z
ddlZddlZddlmZ ddlZddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ G dd deZG dd deZeG dd dZG dd deZeG dd dZG dd deZdS )al   Specifies the inference interfaces for Automatic speech Recognition (ASR) modules.

Authors:
 * Aku Rouhe 2021
 * Peter Plantinga 2021
 * Loren Lugosch 2020
 * Mirco Ravanelli 2020
 * Titouan Parcollet 2021
 * Abdel Heba 2021
 * Andreas Nautsch 2022, 2023
 * Pooneh Mousavi 2023
 * Sylvain de Langen 2023, 2024
 * Adel Moumen 2023, 2024
 * Pradnya Kandarkar 2023
    N)	dataclass)AnyListOptionalTuple)tqdm)
Pretrained)
split_path)DynChunkTrainConfig)fetch)split_fixed_chunksc                       sN   e Zd ZdZdgZddgZ fddZdd Zd	d
 Zdd Z	dd Z
  ZS )EncoderDecoderASRaf  A ready-to-use Encoder-Decoder ASR model

    The class can be used either to run only the encoder (encode()) to extract
    features or to run the entire encoder-decoder model
    (transcribe()) to transcribe speech. The given YAML must contain the fields
    specified in the *_NEEDED[] lists.

    Arguments
    ---------
    *args : tuple
    **kwargs : dict
        Arguments are forwarded to ``Pretrained`` parent class.

    Example
    -------
    >>> from speechbrain.inference.ASR import EncoderDecoderASR
    >>> tmpdir = getfixture("tmpdir")
    >>> asr_model = EncoderDecoderASR.from_hparams(
    ...     source="speechbrain/asr-crdnn-rnnlm-librispeech",
    ...     savedir=tmpdir,
    ... )  # doctest: +SKIP
    >>> asr_model.transcribe_file("tests/samples/single-mic/example2.flac")  # doctest: +SKIP
    "MY FATHER HAS REVEALED THE CULPRIT'S NAME"
    	tokenizerencoderdecoderc                    s\   t  j|i | | jj| _d| _d| _t| jdr| jj| _t| jdr,| jj| _d S d S )NFtransducer_beam_searchtransformer_beam_search)super__init__hparamsr   r   r   hasattrselfargskwargs	__class__ W/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/speechbrain/inference/ASR.pyr   @   s   

zEncoderDecoderASR.__init__c                 K   s@   | j |fi |}|d}tdg}| ||\}}|d S ak  Transcribes the given audiofile into a sequence of words.

        Arguments
        ---------
        path : str
            Path to audio file which to transcribe.
        **kwargs : dict
            Arguments forwarded to ``load_audio``.

        Returns
        -------
        str
            The audiofile transcription produced by this ASR system.
        r         ?)
load_audio	unsqueezetorchtensortranscribe_batchr   pathr   waveformbatch
rel_lengthpredicted_wordspredicted_tokensr   r   r   transcribe_fileJ   s   
z!EncoderDecoderASR.transcribe_filec                 C   sJ   |  }|| j|| j}}| j||}| jr#| jj||}|S )aD  Encodes the input audio into a sequence of hidden states

        The waveforms should already be in the model's desired format.
        You can call:
        ``normalized = EncoderDecoderASR.normalizer(signal, sample_rate)``
        to get a correctly converted signal in most cases.

        Arguments
        ---------
        wavs : torch.Tensor
            Batch of waveforms [batch, time, channels] or [batch, time]
            depending on the model.
        wav_lens : torch.Tensor
            Lengths of the waveforms relative to the longest one in the
            batch, tensor of shape [batch]. The longest one should have
            relative length 1.0 and others len(waveform) / max_length.
            Used for ignoring padding.

        Returns
        -------
        torch.Tensor
            The encoded batch
        )floattodevicemodsr   r   transformerencoder   wavswav_lensencoder_outr   r   r   encode_batchb   s   zEncoderDecoderASR.encode_batchc                    s   t  5 | j} ||} jr|g}n||g} jj| \}}}} fdd|D }W d   ||fS 1 s<w   Y  ||fS )a  Transcribes the input audio into a sequence of words

        The waveforms should already be in the model's desired format.
        You can call:
        ``normalized = EncoderDecoderASR.normalizer(signal, sample_rate)``
        to get a correctly converted signal in most cases.

        Arguments
        ---------
        wavs : torch.Tensor
            Batch of waveforms [batch, time, channels] or [batch, time]
            depending on the model.
        wav_lens : torch.Tensor
            Lengths of the waveforms relative to the longest one in the
            batch, tensor of shape [batch]. The longest one should have
            relative length 1.0 and others len(waveform) / max_length.
            Used for ignoring padding.

        Returns
        -------
        list
            Each waveform in the batch transcribed.
        tensor
            Each predicted token id.
        c                       g | ]} j |qS r   r   
decode_ids.0	token_seqr   r   r   
<listcomp>       
z6EncoderDecoderASR.transcribe_batch.<locals>.<listcomp>N)r#   no_gradr/   r0   r8   r   r1   r   )r   r5   r6   r7   inputsr,   _r+   r   r?   r   r%      s   


z"EncoderDecoderASR.transcribe_batchc                 C      |  ||S z=Runs full transcription - note: no gradients through decodingr%   r   r5   r6   r   r   r   forward      zEncoderDecoderASR.forward)__name__
__module____qualname____doc__HPARAMS_NEEDEDMODULES_NEEDEDr   r-   r8   r%   rI   __classcell__r   r   r   r   r   #   s    
(r   c                       sV   e Zd ZdZddgZdgZ fddZdd Zd	d
 Zdd Z	dd Z
dd Z  ZS )
EncoderASRa'  A ready-to-use Encoder ASR model

    The class can be used either to run only the encoder (encode()) to extract
    features or to run the entire encoder + decoder function model
    (transcribe()) to transcribe speech. The given YAML must contain the fields
    specified in the *_NEEDED[] lists.

    Arguments
    ---------
    *args : tuple
    **kwargs : dict
        Arguments are forwarded to ``Pretrained`` parent class.

    Example
    -------
    >>> from speechbrain.inference.ASR import EncoderASR
    >>> tmpdir = getfixture("tmpdir")
    >>> asr_model = EncoderASR.from_hparams(
    ...     source="speechbrain/asr-wav2vec2-commonvoice-fr",
    ...     savedir=tmpdir,
    ... ) # doctest: +SKIP
    >>> asr_model.transcribe_file("samples/audio_samples/example_fr.wav") # doctest: +SKIP
    r   decoding_functionr   c                    s(   t  j|i | | jj| _|   d S N)r   r   r   r   set_decoding_functionr   r   r   r   r      s   
zEncoderASR.__init__c                    s  t jjtjrjj_d
S tjjtjjj	rt j
tjjjr4j
j  fddtt D }nt j
tjrJfddtj
 D }ntdtjdrtjj}d|v rst|d \}}tt||jjd}||d< ni }jjdi |d|i_d
S td	)ai  Set the decoding function based on the parameters defined in the hyperparameter file.

        The decoding function is determined by the `decoding_function` specified in the hyperparameter file.
        It can be either a functools.partial object representing a decoding function or an instance of
        `speechbrain.decoders.ctc.CTCBaseSearcher` for beam search decoding.

        Raises:
            ValueError: If the decoding function is neither a functools.partial nor an instance of
                        speechbrain.decoders.ctc.CTCBaseSearcher.

        Note:
            - For greedy decoding (functools.partial), the provided `decoding_function` is assigned directly.
            - For CTCBeamSearcher decoding, an instance of the specified `decoding_function` is created, and
            additional parameters are added based on the tokenizer type.
        c                    s   g | ]} | qS r   r   )r=   x)ind2labr   r   r@      s    z4EncoderASR.set_decoding_function.<locals>.<listcomp>c                    r9   r   )r   id_to_piecer=   ir?   r   r   r@      rA   z5The tokenizer must be sentencepiece or CTCTextEncodertest_beam_searchkenlm_model_path)sourcesavedir
vocab_listzQThe decoding function must be an instance of speechbrain.decoders.CTCBaseSearcherNr   )
isinstancer   rS   	functoolspartial
issubclassspeechbraindecodersctcCTCBaseSearcherr   dataior   CTCTextEncoderrW   rangelensentencepieceSentencePieceProcessor
vocab_size
ValueErrorr   r[   r	   strr   r^   )r   r_   opt_beam_search_paramsr]   flr\   r   )rW   r   r   rU      sV   


z EncoderASR.set_decoding_functionc                 K   sD   | j |fi |}|d}tdg}| ||\}}t|d S r   )r!   r"   r#   r$   r%   rp   r&   r   r   r   r-     s   
zEncoderASR.transcribe_filec                 C   s4   |  }|| j|| j}}| j||}|S )a=  Encodes the input audio into a sequence of hidden states

        The waveforms should already be in the model's desired format.
        You can call:
        ``normalized = EncoderASR.normalizer(signal, sample_rate)``
        to get a correctly converted signal in most cases.

        Arguments
        ---------
        wavs : torch.Tensor
            Batch of waveforms [batch, time, channels] or [batch, time]
            depending on the model.
        wav_lens : torch.Tensor
            Lengths of the waveforms relative to the longest one in the
            batch, tensor of shape [batch]. The longest one should have
            relative length 1.0 and others len(waveform) / max_length.
            Used for ignoring padding.

        Returns
        -------
        torch.Tensor
            The encoded batch
        )r.   r/   r0   r1   r   r4   r   r   r   r8   0  s   zEncoderASR.encode_batchc                    s   t  _ | j} ||} ||}t jtj	j
j}t jjtjr>|r4 fdd|D }n% fdd|D }ndd |D }W d   ||fS W d   ||fS W d   ||fS 1 sfw   Y  ||fS )a{  Transcribes the input audio into a sequence of words

        The waveforms should already be in the model's desired format.
        You can call:
        ``normalized = EncoderASR.normalizer(signal, sample_rate)``
        to get a correctly converted signal in most cases.

        Arguments
        ---------
        wavs : torch.Tensor
            Batch of waveforms [batch, time, channels] or [batch, time]
            depending on the model.
        wav_lens : torch.Tensor
            Lengths of the waveforms relative to the longest one in the
            batch, tensor of shape [batch]. The longest one should have
            relative length 1.0 and others len(waveform) / max_length.
            Used for ignoring padding.

        Returns
        -------
        list
            Each waveform in the batch transcribed.
        tensor
            Each predicted token id.
        c                    s   g | ]}d   j|qS ) )joinr   decode_ndimr<   r?   r   r   r@   p      z/EncoderASR.transcribe_batch.<locals>.<listcomp>c                    r9   r   r:   r<   r?   r   r   r@   u  rA   c                 S   s   g | ]}|d  j qS )r   )text)r=   hypr   r   r   r@   z  s    N)r#   rB   r/   r0   r8   rS   r`   r   rd   rh   r   ri   r   ra   rb   )r   r5   r6   r7   predictionsis_ctc_text_encoder_tokenizerr+   r   r?   r   r%   M  s4   





zEncoderASR.transcribe_batchc                 C   rE   )zRuns the encoder)r8   rH   r   r   r   rI   ~  rJ   zEncoderASR.forward)rK   rL   rM   rN   rO   rP   r   rU   r-   r8   r%   rI   rQ   r   r   r   r   rR      s    H1rR   c                   @   s   e Zd ZU dZeed< eed< ejed< dZe	e
 ed< dZe	e
 ed< dZe	ee
  ed< dZe	ee
  ed	< dZe	e ed
< dZe	e ed< dS )ASRWhisperSegmenta  A single chunk of audio for Whisper ASR streaming.

    This object is intended to be mutated as streaming progresses and passed across calls
    to the lower-level APIs such as `encode_chunk`, `decode_chunk`, etc.

    Attributes
    ----------
    start : float
        The start time of the audio chunk.
    end : float
        The end time of the audio chunk.
    chunk : torch.Tensor
        The audio chunk, shape [time, channels].
    lang_id : str
        The language identifier associated with the audio chunk.
    words : str
        The predicted words for the audio chunk.
    tokens : List[int]
        The predicted tokens for the audio chunk.
    prompt : List[str]
        The prompt associated with the audio chunk.
    avg_log_probs : float
        The average log probability associated with the prediction.
    no_speech_prob : float
        The probability of no speech in the audio chunk.
    startendchunkNlang_idwordstokenspromptavg_log_probsno_speech_prob)rK   rL   rM   rN   r.   __annotations__r#   Tensorr   r   rp   r   r   r   r   r   r   r   r   r   r   r{     s   
 
r{   c                       s\  e Zd ZdZddgZddgZg dZ fddZe	 d	e
fd
dZe	 dejfddZe	 dejde
fddZdddefddZe	 								d.d	e
dee
 dee
 dee ded ed!ed"ee fd#d$Z								d.d	e
dee
 dee
 dee ded ed!ed"ee d%ee fd&d'Zd(d) Ze	 d*d+ Zd,d- Z  ZS )/
WhisperASRaP  A ready-to-use Whisper ASR model.

    The class can be used to run the entire encoder-decoder whisper model.
    The set of tasks supported are: ``transcribe``, ``translate``, and ``lang_id``.
    The given YAML must contains the fields specified in the *_NEEDED[] lists.

    Arguments
    ---------
    *args : tuple
    **kwargs : dict
        Arguments are forwarded to ``Pretrained`` parent class.

    Example
    -------
    >>> from speechbrain.inference.ASR import WhisperASR
    >>> tmpdir = getfixture("tmpdir")
    >>> asr_model = WhisperASR.from_hparams(source="speechbrain/asr-whisper-medium-commonvoice-it", savedir=tmpdir,) # doctest: +SKIP
    >>> hyp = asr_model.transcribe_file("speechbrain/asr-whisper-medium-commonvoice-it/example-it.wav")  # doctest: +SKIP
    >>> hyp  # doctest: +SKIP
    buongiorno a tutti e benvenuti a bordo
    >>> _, probs = asr_model.detect_language_file("speechbrain/asr-whisper-medium-commonvoice-it/example-it.wav")  # doctest: +SKIP
    >>> print(f"Detected language: {max(probs[0], key=probs[0].get)}")  # doctest: +SKIP
    Detected language: it
    languagesample_ratewhisperr   )
transcribe	translater   c                    s"   t  j|i | | jjj| _d S rT   )r   r   r   r   r   r   r   r   r   r     s   zWhisperASR.__init__r'   c                 C   sD   |  | | jd}| jj|}| jj|\}}||fS )a  Detects the language of the given audiofile.
        This method only works on input_file of 30 seconds or less.

        Arguments
        ---------
        path : str
            Path to audio file which to transcribe.

        Returns
        -------
        language_tokens : torch.Tensor
            The detected language tokens.
        language_probs : dict
            The probabilities of the detected language tokens.

        Raises
        ------
        ValueError
            If the model doesn't have language tokens.
        r   )	r!   r.   r/   r0   r"   r1   r   _get_meldetect_language)r   r'   r5   mellanguage_tokenslanguage_probsr   r   r   detect_language_file  s   zWhisperASR.detect_language_filewavc                 C   s(   | j j|}| j j|\}}||fS )a  Detects the language of the given wav Tensor.
        This method only works on wav files of 30 seconds or less.

        Arguments
        ---------
        wav : torch.tensor
            Batch of waveforms [batch, time, channels].

        Returns
        -------
        language_tokens : torch.Tensor of shape (batch_size,)
            ids of the most probable language tokens, which appears after the startoftranscript token.
        language_probs : List[Dict[str, float]]
            list of dictionaries containing the probability distribution over all languages.

        Raises
        ------
        ValueError
            If the model doesn't have language tokens.

        Example
        -------
        >>> from speechbrain.inference.ASR import WhisperASR
        >>> import torchaudio
        >>> tmpdir = getfixture("tmpdir")
        >>> asr_model = WhisperASR.from_hparams(
        ...     source="speechbrain/asr-whisper-medium-commonvoice-it",
        ...     savedir=tmpdir,
        ... ) # doctest: +SKIP
        >>> wav, _ = torchaudio.load("your_audio") # doctest: +SKIP
        >>> language_tokens, language_probs = asr_model.detect_language(wav) # doctest: +SKIP
        )r1   r   r   r   )r   r   r   r   r   r   r   r   detect_language_batch  s   "z WhisperASR.detect_language_batchr   taskc                 C   sf   | j jjg|jd  }d}| j jjdu s|dkr/| j j|\}}dd |D }| j j| ||fS )aJ  Detects the language of the given mel spectrogram.

        Arguments
        ---------
        mel : torch.tensor
            Batch of mel spectrograms [batch, time, channels].
        task : str
            The task to perform.

        Returns
        -------
        language_tokens : Tensor, shape = (n_audio,)
            ids of the most probable language tokens, which appears after the startoftranscript token.
        language_probs : List[Dict[str, float]], length = n_audio
            list of dictionaries containing the probability distribution over all languages.
        r   Nr   c                 S   s   g | ]	}t ||jd qS ))key)maxget)r=   probsr   r   r   r@   %  s    z/WhisperASR._detect_language.<locals>.<listcomp>)r1   r   r   shaper   r   set_lang_tokens)r   r   r   	languages
lang_probslang_tokensr   r   r   _detect_language  s   zWhisperASR._detect_languagestreamertorchaudio.io.StreamReaderframes_per_chunkc                 #        fddt  jD }dd t|D }t|dkr)tdt| d| d|d d } j||| jjd	dd
   D ]\}|	d}|
d}|V  q?dS )R  From a :class:`torchaudio.io.StreamReader`, identifies the audio
        stream and returns an iterable stream of chunks (after resampling and
        downmixing to mono).

        Arguments
        ---------
        streamer : torchaudio.io.StreamReader
            The stream object. Must hold exactly one source stream of an
            audio type.
        frames_per_chunk : int
            The number of frames per chunk. For a streaming model, this should
            be determined from the DynChunkTrain configuration.

        Yields
        ------
        chunks from streamer
        c                       g | ]}  |qS r   get_src_stream_inforY   r   r   r   r@   >      z0WhisperASR._get_audio_stream.<locals>.<listcomp>c                 S   "   g | ]\}}|j d kr||fqS audio
media_typer=   rZ   stream_infor   r   r   r@   C  
    
   IExpected stream to have only 1 stream (with any number of channels), got  (with streams: )r   fltpr   stream_indexr   formatnum_channelsNrj   num_src_streams	enumeraterk   ro   add_basic_audio_streamaudio_normalizerr   streamsqueezer"   r   r   r   stream_infosaudio_stream_infosaudio_stream_indexr~   r   r   r   _get_audio_stream)  0   


zWhisperASR._get_audio_streamN      333333?F   initial_promptlogprob_thresholdcondition_on_previous_textverboseuse_torchaudio_streaming
chunk_sizec
           "      +   s   |dur!| j v r|dkr jj| ntd| d j  |	 jj }|r6tj	|} 
||}n j|fi |
}|d}t||}tdg}g }d}|durh jjd|  }|| ng }tt||dD ]\}}| j} jj|}||	 }|d	 |	 } jj|} ||\}}|dkrt||||d d
V  qr||d } jj|  j||\}}}}| t|d d	  }|dur jjj d |k} |dur||krd} | rt||||d dg ||!  jjj d d	V  qr fdd|D }!t||||d |!d |d ||!  jjj d d	V  ||d  |r9 jjj"dkr=t|}qrdS )at  Transcribes the given audiofile into a sequence of words.
        This method supports the following tasks: ``transcribe``, ``translate``, and ``lang_id``.
        It can process an input audio file longer than 30 seconds by splitting it into chunk_size-second segments.

        Arguments
        ---------
        path : str
            URI/path to the audio to transcribe. When
            ``use_torchaudio_streaming`` is ``False``, uses SB fetching to allow
            fetching from HF or a local file. When ``True``, resolves the URI
            through ffmpeg, as documented in
            :class:`torchaudio.io.StreamReader`.
        task : Optional[str]
            The task to perform. If None, the default task is the one passed in the Whisper model.
        initial_prompt : Optional[str]
            The initial prompt to condition the model on.
        logprob_threshold : Optional[float]
            The log probability threshold to continue decoding the current segment.
        no_speech_threshold : float
            The threshold to skip decoding segment if the no_speech_prob is higher than this value.
        condition_on_previous_text : bool
            If True, the model will be condition on the last 224 tokens.
        verbose : bool
            If True, print the transcription of each segment.
        use_torchaudio_streaming : bool
            Whether the audio file can be loaded in a streaming fashion. If not,
            transcription is still performed through chunks of audio, but the
            entire audio file is fetched and loaded at once.
            This skips the usual fetching method and instead resolves the URI
            using torchaudio (via ffmpeg).
        chunk_size : Optional[int]
            The size of the chunks to split the audio into. The default
            chunk size is 30 seconds which corresponds to the maximal length
            that the model can process in one go.
        **kwargs : dict
            Arguments forwarded to ``load_audio``

        Yields
        ------
        ASRWhisperSegment
            A new ASRWhisperSegment instance initialized with the provided parameters.
        Nr   zTask z$ not supported. Supported tasks are r   r     )disabler   )r|   r}   r~   r   Frs   )	r|   r}   r~   r   r   r   r   r   r   c                        g | ]} j j|d d qS T)skip_special_tokensr   decodestripr=   tr?   r   r   r@         z8WhisperASR.transcribe_file_streaming.<locals>.<listcomp>g      ?)#TASKSr1   r   set_taskro   r   r   
torchaudioioStreamReaderr   r!   r"   r   r#   r$   r   r   r3   r   extendr   r   r/   r0   r   forward_encoderr   r{   
set_promptsumrk   no_speech_probsitemtemperature)"r   r'   r   r   r   no_speech_thresholdr   r   r   r   r   num_frames_per_chunkr   segmentsr(   r)   r*   
all_tokensprompt_reset_sinceinitial_prompt_tokensrZ   segmentmel_segmentr|   r}   r7   r   rD   r   r,   scoresr   should_skipr+   r   r?   r   transcribe_file_streaming_  s   8





z$WhisperASR.transcribe_file_streamingreturnc
                 K   sr   g }| j |f||||||||	d|
D ]"}|| |r6|dkr$|jn|j}td|j d|j d|  q|S )a	  Run the Whisper model using the specified task on the given audio file and return the ``ASRWhisperSegment`` objects
        for each segment.

        This method supports the following tasks: ``transcribe``, ``translate``, and ``lang_id``.
        It can process an input audio file longer than 30 seconds by splitting it into chunk_size-second segments.

        Arguments
        ---------
        path : str
            URI/path to the audio to transcribe. When
            ``use_torchaudio_streaming`` is ``False``, uses SB fetching to allow
            fetching from HF or a local file. When ``True``, resolves the URI
            through ffmpeg, as documented in
            :class:`torchaudio.io.StreamReader`.
        task : Optional[str]
            The task to perform. If None, the default task is the one passed in the Whisper model.
            It can be one of the following: ``transcribe``, ``translate``, ``lang_id``.
        initial_prompt : Optional[str]
            The initial prompt to condition the model on.
        logprob_threshold : Optional[float]
            The log probability threshold to continue decoding the current segment.
        no_speech_threshold : float
            The threshold to skip decoding segment if the no_speech_prob is higher than this value.
        condition_on_previous_text : bool
            If True, the model will be condition on the last 224 tokens.
        verbose : bool
            If True, print the details of each segment.
        use_torchaudio_streaming : bool
            Whether the audio file can be loaded in a streaming fashion. If not,
            transcription is still performed through chunks of audio, but the
            entire audio file is fetched and loaded at once.
            This skips the usual fetching method and instead resolves the URI
            using torchaudio (via ffmpeg).
        chunk_size : Optional[int]
            The size of the chunks to split the audio into. The default
            chunk size is 30 seconds which corresponds to the maximal length
            that the model can process in one go.
        **kwargs : dict
            Arguments forwarded to ``load_audio``

        Returns
        -------
        results : list
            A list of ``WhisperASRChunk`` objects, each containing the task result.
        )r   r   r   r   r   r   r   r   r   [zs --> zs] )r   appendr   r   printr|   r}   )r   r'   r   r   r   r   r   r   r   r   r   resultswhisper_segmentpredr   r   r   r-     s4   :


zWhisperASR.transcribe_filec                 C   s2   |j | jtjd}| jj|}| jj|}|S )a  Encodes the input audio into a sequence of hidden states

        The waveforms should already be in the model's desired format.
        You can call:
        ``normalized = EncoderDecoderASR.normalizer(signal, sample_rate)``
        to get a correctly converted signal in most cases.

        Arguments
        ---------
        wavs : torch.tensor
            Batch of waveforms [batch, time, channels].
        wav_lens : torch.tensor
            Lengths of the waveforms relative to the longest one in the
            batch, tensor of shape [batch]. The longest one should have
            relative length 1.0 and others len(waveform) / max_length.
            Used for ignoring padding.

        Returns
        -------
        torch.tensor
            The encoded batch
        )r0   dtype)r/   r0   r#   float32r1   r   r   r   )r   r5   r6   r   r7   r   r   r   r8   Y  s   zWhisperASR.encode_batchc                    sf   |   j} ||} j||\}}}} fdd|D } jjr/ fdd|D }||fS )aN  Transcribes the input audio into a sequence of words

        The waveforms should already be in the model's desired format.
        You can call:
        ``normalized = EncoderDecoderASR.normalizer(signal, sample_rate)``
        to get a correctly converted signal in most cases.

        Arguments
        ---------
        wavs : torch.tensor
            Batch of waveforms [batch, time, channels].
        wav_lens : torch.tensor
            Lengths of the waveforms relative to the longest one in the
            batch, tensor of shape [batch]. The longest one should have
            relative length 1.0 and others len(waveform) / max_length.
            Used for ignoring padding.

        Returns
        -------
        list
            Each waveform in the batch transcribed.
        tensor
            Each predicted token id.
        c                    r   r   r   r   r?   r   r   r@     r   z/WhisperASR.transcribe_batch.<locals>.<listcomp>c                    s   g | ]} j |d qS )r   )r   	normalizesplit)r=   rw   r?   r   r   r@     rv   )r.   r/   r0   r8   r1   r   r   normalized_transcripts)r   r5   r6   r7   r,   rD   r+   r   r?   r   r%   u  s   

zWhisperASR.transcribe_batchc                 C   rE   rF   rG   rH   r   r   r   rI     rJ   zWhisperASR.forward)NNr   r   FFFr   )rK   rL   rM   rN   rO   rP   r   r   r#   rB   rp   r   r   r   r   intr   r   r.   boolr   r   r{   r-   r8   r%   rI   rQ   r   r   r   r   r     s    %
6	
 *	

S
(r   c                   @   sJ   e Zd ZU dZeed< 	 eed< 	 eed< 	 eed< 	 eee  ed< dS )ASRStreamingContexta  Streaming metadata, initialized by
    :meth:`~StreamingASR.make_streaming_context` (see there for details on
    initialization of fields here).

    This object is intended to be mutate: the same object should be passed
    across calls as streaming progresses (namely when using the lower-level
    :meth:`~StreamingASR.encode_chunk`, etc. APIs).

    Holds some references to opaque streaming contexts, so the context is
    model-agnostic to an extent.configfea_extractor_contextencoder_contextdecoder_contexttokenizer_contextN)	rK   rL   rM   rN   r
   r   r   r   r   r   r   r   r   r    s   
 r  c                       s  e Zd ZdZg dZddgZ fddZddd	efd
dZ	d#de	de
fddZ	d#de	de
fddZde	fddZde	defddZe 	d$dedejdeej fddZe dedejdeee eee  f fdd Z	d$dedejdeej fd!d"Z  ZS )%StreamingASRa  A ready-to-use, streaming-capable ASR model.

    Arguments
    ---------
    *args : tuple
    **kwargs : dict
        Arguments are forwarded to ``Pretrained`` parent class.

    Example
    -------
    >>> from speechbrain.inference.ASR import StreamingASR
    >>> from speechbrain.utils.dynamic_chunk_training import DynChunkTrainConfig
    >>> tmpdir = getfixture("tmpdir")
    >>> asr_model = StreamingASR.from_hparams(source="speechbrain/asr-conformer-streaming-librispeech", savedir=tmpdir,) # doctest: +SKIP
    >>> asr_model.transcribe_file("speechbrain/asr-conformer-streaming-librispeech/test-en.wav", DynChunkTrainConfig(24, 8)) # doctest: +SKIP
    )fea_streaming_extractormake_decoder_streaming_contextrS    make_tokenizer_streaming_contexttokenizer_decode_streamingencproj_encc                    s"   t  j|i | | jjj| _d S rT   )r   r   r   r	  
propertiesfilter_propsr   r   r   r   r     s   zStreamingASR.__init__r   r   r   c                 #   r   )r   c                    r   r   r   rY   r   r   r   r@     r   z2StreamingASR._get_audio_stream.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r   r@     r   r   r   r   r   r   r   r   r   Nr   r   r   r   r   r     r   zStreamingASR._get_audio_streamTdynchunktrain_configr   c                 k   s    |  |}|rtj|}| ||}n| j|fi |}|d}	t|	|}t	dg}
| 
|}tjd|f| jdg| jj| }t||D ]}| |||
}|d V  qKdS )a  Transcribes the given audio file into a sequence of words, in a
        streaming fashion, meaning that text is being yield from this
        generator, in the form of strings to concatenate.

        Arguments
        ---------
        path : str
            URI/path to the audio to transcribe. When
            ``use_torchaudio_streaming`` is ``False``, uses SB fetching to allow
            fetching from HF or a local file. When ``True``, resolves the URI
            through ffmpeg, as documented in
            :class:`torchaudio.io.StreamReader`.
        dynchunktrain_config : DynChunkTrainConfig
            Streaming configuration. Sane values and how much time chunks
            actually represent is model-dependent.
        use_torchaudio_streaming : bool
            Whether the audio file can be loaded in a streaming fashion. If not,
            transcription is still performed through chunks of audio, but the
            entire audio file is fetched and loaded at once.
            This skips the usual fetching method and instead resolves the URI
            using torchaudio (via ffmpeg).
        **kwargs : dict
            Arguments forwarded to ``load_audio``

        Yields
        ------
        generator of str
            An iterator yielding transcribed chunks (strings). There is a yield
            for every chunk, even if the transcribed string for that chunk is an
            empty string.
        r   r    r   )r0   N)get_chunk_size_framesr   r   r   r   r!   r"   r   r#   r$   make_streaming_contextzerosr0   r   r	  !get_recommended_final_chunk_count	itertoolschaintranscribe_chunk)r   r'   r  r   r   r   r   chunksr(   r)   r*   contextfinal_chunksr~   r+   r   r   r   r     s(   
'


z&StreamingASR.transcribe_file_streamingc                 C   s$   d}|  |||D ]}||7 }q	|S )aN  Transcribes the given audio file into a sequence of words.

        Arguments
        ---------
        path : str
            URI/path to the audio to transcribe. When
            ``use_torchaudio_streaming`` is ``False``, uses SB fetching to allow
            fetching from HF or a local file. When ``True``, resolves the URI
            through ffmpeg, as documented in
            :class:`torchaudio.io.StreamReader`.
        dynchunktrain_config : DynChunkTrainConfig
            Streaming configuration. Sane values and how much time chunks
            actually represent is model-dependent.
        use_torchaudio_streaming : bool
            Whether the audio file can be loaded in a streaming fashion. If not,
            transcription is still performed through chunks of audio, but the
            entire audio file is fetched and loaded at once.
            This skips the usual fetching method and instead resolves the URI
            using torchaudio (via ffmpeg).

        Returns
        -------
        str
            The audio file transcription produced by this ASR system.
        rs   )r   )r   r'   r  r   r   
text_chunkr   r   r   r-   V  s    
zStreamingASR.transcribe_filec                 C   s*   t || jj | jj|| j ddS )ay  Create a blank streaming context to be passed around for chunk
        encoding/transcription.

        Arguments
        ---------
        dynchunktrain_config : DynChunkTrainConfig
            Streaming configuration. Sane values and how much time chunks
            actually represent is model-dependent.

        Returns
        -------
        ASRStreamingContext
        N)r  r  r  r  r  )r  r   r	  r  r1   r  r
  r   r  r   r   r   r    s   
z#StreamingASR.make_streaming_contextr   c                 C   s   | j jd |j S )a  Returns the chunk size in actual audio samples, i.e. the exact
        expected length along the time dimension of an input chunk tensor (as
        passed to :meth:`~StreamingASR.encode_chunk` and similar low-level
        streaming functions).

        Arguments
        ---------
        dynchunktrain_config : DynChunkTrainConfig
            The streaming configuration to determine the chunk frame count of.

        Returns
        -------
        chunk size
        r   )r  strider   r  r   r   r   r    s   z"StreamingASR.get_chunk_size_framesNr  r~   	chunk_lenc                 C   s   |du rt |df}| }|| j|| j}}|jd | |jks+J | j	j
||j|d}| jj||j}| j|}|S )a3  Encoding of a batch of audio chunks into a batch of encoded
        sequences.
        For full speech-to-text offline transcription, use `transcribe_batch` or
        `transcribe_file`.
        Must be called over a given context in the correct order of chunks over
        time.

        Arguments
        ---------
        context : ASRStreamingContext
            Mutable streaming context object, which must be specified and reused
            across calls when streaming.
            You can obtain an initial context by calling
            `asr.make_streaming_context(config)`.

        chunk : torch.Tensor
            The tensor for an audio chunk of shape `[batch size, time]`.
            The time dimension must strictly match
            `asr.get_chunk_size_frames(config)`.
            The waveform is expected to be in the model's expected format (i.e.
            the sampling rate must be correct).

        chunk_len : torch.Tensor, optional
            The relative chunk length tensor of shape `[batch size]`. This is to
            be used when the audio in one of the chunks of the batch is ending
            within this chunk.
            If unspecified, equivalent to `torch.ones((batch_size,))`.

        Returns
        -------
        torch.Tensor
            Encoded output, of a model-dependent shape.Nr   r   )r  lengths)r#   onessizer.   r/   r0   r   r  r  r   r	  r  r1   r  forward_streamingr  r  )r   r  r~   r  rV   r   r   r   encode_chunk  s   (zStreamingASR.encode_chunkrV   c                    sV   j | j} jdu rfddtt|D  _ fddt|D }||fS )a  Decodes the output of the encoder into tokens and the associated
        transcription.
        Must be called over a given context in the correct order of chunks over
        time.

        Arguments
        ---------
        context : ASRStreamingContext
            Mutable streaming context object, which should be the same object
            that was passed to `encode_chunk`.

        x : torch.Tensor
            The output of `encode_chunk` for a given chunk.

        Returns
        -------
        list of str
            Decoded tokens of length `batch_size`. The decoded strings can be
            of 0-length.
        list of list of output token hypotheses
            List of length `batch_size`, each holding a list of tokens of any
            length `>=0`.
        Nc                    s   g | ]} j  qS r   )r   r  )r=   rD   r?   r   r   r@     r   z-StreamingASR.decode_chunk.<locals>.<listcomp>c                    s*   g | ]\}}j j j| j| qS r   )r   r  r   r  )r=   rZ   
cur_tokensr  r   r   r   r@     s    )r   rS   r  r  rj   rk   r   )r   r  rV   r   r   r   r&  r   decode_chunk  s   


zStreamingASR.decode_chunkc                 C   s^   |du rt |df}| }|| j|| j}}| |||}| ||\}}|S )a  Transcription of a batch of audio chunks into transcribed text.
        Must be called over a given context in the correct order of chunks over
        time.

        Arguments
        ---------
        context : ASRStreamingContext
            Mutable streaming context object, which must be specified and reused
            across calls when streaming.
            You can obtain an initial context by calling
            `asr.make_streaming_context(config)`.
        chunk : torch.Tensor
            The tensor for an audio chunk of shape `[batch size, time]`.
            The time dimension must strictly match
            `asr.get_chunk_size_frames(config)`.
            The waveform is expected to be in the model's expected format (i.e.
            the sampling rate must be correct).
        chunk_len : torch.Tensor, optional
            The relative chunk length tensor of shape `[batch size]`. This is to
            be used when the audio in one of the chunks of the batch is ending
            within this chunk.
            If unspecified, equivalent to `torch.ones((batch_size,))`.

        Returns
        -------
        str
            Transcribed string for this chunk, might be of length zero.
        Nr   )r#   r!  r"  r.   r/   r0   r$  r'  )r   r  r~   r  rV   r   rD   r   r   r   r    s   #zStreamingASR.transcribe_chunk)TrT   )rK   rL   rM   rN   rO   rP   r   r   r   r
   r  r   r-   r  r  r#   rB   r  r   r   r$  r   r   rp   r'  r  rQ   r   r   r   r   r    sj    
:
B
)
60r  )rN   ra   r  dataclassesr   typingr   r   r   r   rl   r#   r   r   rd    speechbrain.inference.interfacesr   speechbrain.utils.data_utilsr	   (speechbrain.utils.dynamic_chunk_trainingr
   speechbrain.utils.fetchingr   speechbrain.utils.streamingr   r   rR   r{   r   r  r  r   r   r   r   <module>   s8      V'   {