o
    %ݫi                     @   sL   d Z ddlZddlZddlmZ ddlmZ ddlmZ G dd deZ	dS )a\   Specifies the inference interfaces for Voice Activity Detection (VAD) 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
 * Adel Moumen 2023
 * Pradnya Kandarkar 2023
    N)
Pretrained)
split_path)fetchc                       s   e Zd ZdZg dZg dZ fddZ			d5d	d
Zdd Zd6ddZ		d7ddZ
d8ddZd9ddZd9ddZ	d:ddZ			d;d d!Zd<d#d$Zd%d& Zd=d(d)Zd*d+ Z	d>d,d-Z	.d?d/d0Z												d@d1d2Zd6d3d4Z  ZS )AVADa  A ready-to-use class for Voice Activity Detection (VAD) using a
    pre-trained model.

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

    Example
    -------
    >>> import torchaudio
    >>> from speechbrain.inference.VAD import VAD
    >>> # Model is downloaded from the speechbrain HuggingFace repo
    >>> tmpdir = getfixture("tmpdir")
    >>> VAD = VAD.from_hparams(
    ...     source="speechbrain/vad-crdnn-libriparty",
    ...     savedir=tmpdir,
    ... )

    >>> # Perform VAD
    >>> boundaries = VAD.get_speech_segments("tests/samples/single-mic/example1.wav")
    )sample_ratetime_resolutiondevice)compute_featuresmean_var_normmodelc                    s*   t  j|i | | jj| _| jj| _d S N)super__init__hparamsr   r   )selfargskwargs	__class__ M/home/ubuntu/.local/lib/python3.10/site-packages/speechbrain/inference/VAD.pyr   6   s   
zVAD.__init__   
   Fc                 C   s  |  |\}}|| jkrtdt|| }t|| }|}	|r$|d }	t||	 }
g }d}d}	 || |kr9d}tjt|||d\}}|| j}|sT|j	d |k rft
jd||jd	}t
j||gdd
}t
jjj|ddd|fd|
fd}|ddd}| |}|ddddddf }|r| |}|ddd}t|j	d || j  }t|| j }t|	| j }t
jjj|d|fd|fd|fd}|ddd}|| |rn|| }q1t
j|dd
}t|| j|  }|ddd|ddf }|S )a_  Outputs the frame-level speech probability of the input audio file
        using the neural model specified in the hparam file. To make this code
        both parallelizable and scalable to long sequences, it uses a
        double-windowing approach.  First, we sequentially read non-overlapping
        large chunks of the input signal.  We then split the large chunks into
        smaller chunks and we process them in parallel.

        Arguments
        ---------
        audio_file: path
            Path of the audio file containing the recording. The file is read
            with torchaudio.
        large_chunk_size: float
            Size (in seconds) of the large chunks that are read sequentially
            from the input audio file.
        small_chunk_size: float
            Size (in seconds) of the small chunks extracted from the large ones.
            The audio signal is processed in parallel within the small chunks.
            Note that large_chunk_size/small_chunk_size must be an integer.
        overlap_small_chunk: bool
            True, creates overlapped small chunks. The probabilities of the
            overlapped chunks are combined using hamming windows.

        Returns
        -------
        prob_vad: torch.Tensor
            torch.Tensor containing the frame-level speech probabilities for the
            input audio file.
        FThe detected sample rate is different from that set in the hparam file   Fr   Tframe_offset
num_frames   r   dim)kernel_sizestrideN)output_sizer#   r$   )_get_audio_infor   
ValueErrorint
torchaudioloadstrtor   shapetorchzeroscatnn
functionalunfold	unsqueezesqueeze	transposeget_speech_prob_chunk_manage_overlapped_chunkspermuter   foldappend)r   
audio_filelarge_chunk_sizesmall_chunk_sizeoverlap_small_chunkr   	audio_lenlong_chunk_lensmall_chunk_lensmall_chunk_stepsmall_chunk_len_stepprob_chunks
last_chunkbegin_samplelarge_chunkfspaddingsmall_chunkssmall_chunks_probout_len
kernel_lenstep_lenprob_vad	last_elemr   r   r   get_speech_prob_file;   s|   %



DzVAD.get_speech_prob_filec                 C   s   t j|jd | jd}t|jd d }|d|df ||d d |d|df< |dd|f |d| d |dd|f< |dd |dd |dd< |S )zgThis support function manages overlapped the case in which the
        small chunks have a 50% overlap.r   r    r   r   Nr   )r/   hamming_windowr.   r   r)   r5   )r   rM   rT   
half_pointr   r   r   r9      s(   

zVAD._manage_overlapped_chunksNc                 C   s   t |jdkr|d}|du rtj|jd | jd}|| j|| j}}| }| j	|}| j
||}| j|}||jd |jd |jd |jd  }| j|\}}| j|}t|}|S )a3  Outputs the frame-level posterior probability for the input audio chunks
        Outputs close to zero refers to time steps with a low probability of speech
        activity, while outputs closer to one likely contain speech.

        Arguments
        ---------
        wavs : torch.Tensor
            Batch of waveforms [batch, time, channels] or [batch, time]
            depending on the model. Make sure the sample rate is fs=16000 Hz.
        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   Nr    r      )lenr.   r5   r/   onesr   r-   floatmodsr	   r
   cnnreshapernndnnsigmoid)r   wavswav_lensfeatsoutputshoutput_probr   r   r   r8      s$   

zVAD.get_speech_prob_chunk      ?      ?c                 C   s   ||k d}||k d}td|jd D ],}|dd|df  |dd|d df O  < |dd|df  |dd|df M  < q| |jS )a  Scans the frame-level speech probabilities and applies a threshold
        on them. Speech starts when a value larger than activation_th is
        detected, while it ends when observing a value lower than
        the deactivation_th.

        Arguments
        ---------
        vad_prob: torch.Tensor
            Frame-level speech probabilities.
        activation_th:  float
            Threshold for starting a speech segment.
        deactivation_th: float
            Threshold for ending a speech segment.

        Returns
        -------
        vad_th: torch.BoolTensor
            torch.Tensor containing 1 for speech regions and 0 for non-speech regions.
        cpur   N.)r-   ranger.   r   )r   vad_probactivation_thdeactivation_thframe_does_not_deactivatevad_thir   r   r   apply_threshold  s   ,*zVAD.apply_thresholdsecondsc                 C   sN  t j|ddd}d|dddddf< || }|dddddf dk |dddddf< |dddddf dk |dddddf< |dk jd d dkrkt j|t dgdd| j	fdd}|dk dddf 
dd}|dddf d |dddf< || j  }| j|   }|d	kr|}|S |}|S )
a	  Computes the time boundaries where speech activity is detected.
        It takes in input frame-level binary decisions
        (1 for speech, 0 for non-speech) and outputs the begin/end second
        (or sample) of each detected speech region.

        Arguments
        ---------
        prob_th: torch.Tensor
            Frame-level binary decisions (1 for speech frame, 0 for a
            non-speech one).  The tensor can be obtained from apply_threshold.
        output_value: 'seconds' or 'samples'
            When the option 'seconds' is set, the returned boundaries are in
            seconds, otherwise, it reports them in samples.

        Returns
        -------
        boundaries: torch.Tensor
            torch.Tensor containing the start second (or sample) of speech segments
            in even positions and their corresponding end in odd positions
            (e.g, [1.0, 1.5, 5,.0 6.0] means that we have two speech segment;
             one from 1.0 to 1.5 seconds and another from 5.0 to 6.0 seconds).
        r   )dimsshiftsr   Nr   r         ?r!   rq   )r/   rollr)   nonzeror.   r1   Tensorr5   r-   r   r\   r   rY   r   round)r   prob_thoutput_valueprob_th_shiftedindexesrq   samples
boundariesr   r   r   get_boundaries2  s0   00
  zVAD.get_boundariesc           	      C   s   g }|j d dkr|S |d  }|d  }td|j d D ]&}||df }|| }||kr6||df }q|||g |}||df }q|||g t||j}|S )a  Merges segments that are shorter than the given threshold.

        Arguments
        ---------
        boundaries : str
            torch.Tensor containing the speech boundaries. It can be derived using the
            get_boundaries method.
        close_th: float
            If the distance between boundaries is smaller than close_th, the
            segments will be merged.

        Returns
        -------
        new_boundaries
            The new boundaries with the merged segments.
        r   )r   r   )r   r   r   )r.   rY   ri   r<   r/   FloatTensorr-   r   )	r   r~   close_thnew_boundariesprev_beg_segprev_end_segro   beg_segsegment_distancer   r   r   merge_close_segmentsp  s    zVAD.merge_close_segmentsc                 C   sl   g }t |jd D ]!}||df ||df  }||kr*|||df ||df g q	t||j}|S )a  Removes segments that are too short.

        Arguments
        ---------
        boundaries : torch.Tensor
            torch.Tensor containing the speech boundaries. It can be derived using the
            get_boundaries method.
        len_th: float
            If the length of the segment is smaller than close_th, the segments
            will be merged.

        Returns
        -------
        new_boundaries
            The new boundaries without the short segments.
        r   r   )ri   r.   r<   r/   r   r-   r   )r   r~   len_thr   ro   seg_lenr   r   r   remove_short_segments  s   zVAD.remove_short_segmentsTc                 C   s  |durt |ddd}|dur| |\}}|| }|jtjkr#d}nd}d}	d}
t|jd D ]b}||df }||df }|	|kri|
d }
d	| | d
 }|rYt||
|	|f  |duri|||
|	|f d  |
d }
d	| | d }|rt||
||f  |dur|||
||f d  |}	q0|dur|	|k r|
d }
d	| | d
 }|rt||
||f  |dur|||
||f d  |dur|	  dS dS )a  Saves the boundaries on a file (and/or prints them)  in a readable format.

        Arguments
        ---------
        boundaries: torch.Tensor
            torch.Tensor containing the speech boundaries. It can be derived using the
            get_boundaries method.
        save_path: path
            When to store the text file containing the speech/non-speech intervals.
        print_boundaries: Bool
            Prints the speech/non-speech intervals in the standard outputs.
        audio_file: path
            Path of the audio file containing the recording. The file is read
            with torchaudio. It is used here to detect the length of the
            signal.
        Nwzutf-8)modeencodingz% iz% .2f r   r   zsegment_%03d 
NON_SPEECH
SPEECH)
openr'   dtyper/   r)   ri   r.   printwriteclose)r   r~   	save_pathprint_boundariesr=   fr   rA   value_formatlast_endcnt_segro   begin_value	end_value	print_strr   r   r   save_boundaries  sP   zVAD.save_boundaries        ư>c                 C   sr  |  |\}}|| jkrtdt| j| }g }	t|jd D ]}
t||
df | }t||
df | }|| }tj|||d\}}|	| j
}| j|||d}| d| }| }||  d|   d }|dd}| j|||d	}| j|d
d}t|jd D ]!}||
df ||df  }||
df ||df  }|	||g qq t|		|j
}	|	S )a  Applies energy-based VAD within the detected speech segments.The neural
        network VAD often creates longer segments and tends to merge segments that
        are close with each other.

        The energy VAD post-processes can be useful for having a fine-grained voice
        activity detection.

        The energy VAD computes the energy within the small chunks. The energy is
        normalized within the segment to have mean 0.5 and +-0.5 of std.
        This helps to set the energy threshold.

        Arguments
        ---------
        audio_file: path
            Path of the audio file containing the recording. The file is read
            with torchaudio.
        boundaries: torch.Tensor
            torch.Tensor containing the speech boundaries. It can be derived using the
            get_boundaries method.
        activation_th: float
            A new speech segment is started it the energy is above activation_th.
        deactivation_th: float
            The segment is considered ended when the energy is <= deactivation_th.
        eps: float
            Small constant for numerical stability.

        Returns
        -------
        new_boundaries
            The new boundaries that are post-processed by the energy VAD.
        r   r   r   r   )
chunk_sizechunk_strider   r   rf   rk   rl   rq   rz   )r'   r   r(   r)   r   ri   r.   r*   r+   r-   r   create_chunksabssumlogmeanstdr5   rp   r   r<   r/   r   )r   r=   r~   rk   rl   epsr   rA   	chunk_lenr   ro   rH   
end_sampler   segment_segment_chunksenergy_chunks
energy_vadenergy_boundariesjstart_enend_endr   r   r   
energy_VAD	  sR   )



zVAD.energy_VAD @  c                 C   s.   | d||}||jd |jd  d}|S )a
  Splits the input into smaller chunks of size chunk_size with
        an overlap chunk_stride. The chunks are concatenated over
        the batch axis.

        Arguments
        ---------
        x: torch.Tensor
            Signal to split into chunks.
        chunk_size : int
            The size of each chunk.
        chunk_stride: int
            The stride (hop) of each chunk.

        Returns
        -------
        x: torch.Tensor
            A new tensors with the chunks derived from the input signal.
        r   r   r   )r4   r\   r.   )r   xr   r   r   r   r   r   n  s   zVAD.create_chunksc                 C   s"   t t|}|j}|j}||fS )z>Returns the sample rate and the length of the input audio file)r*   infor,   r   r   )r   r=   metadatar   rA   r   r   r   r'     s   zVAD._get_audio_info{Gz?c                 C   s   |  |\}}|| jkrtdd}t|| }|}d}	tjd||jd}
||k rF|d|	df |
d||f< |	d }	|| }|| }||k s)|
S )a  Upsamples the output of the vad to help visualization. It creates a
        signal that is 1 when there is speech and 0 when there is no speech.
        The vad signal has the same resolution as the input one and can be
        opened with it (e.g, using audacity) to visually figure out VAD regions.

        Arguments
        ---------
        vad_out: torch.Tensor
            torch.Tensor containing 1 for each frame of speech and 0 for each non-speech
            frame.
        audio_file: path
            The original audio file used to compute vad_out
        time_resolution : float
            Time resolution of the vad_out signal.

        Returns
        -------
        vad_signal
            The upsampled version of the vad_out tensor.
        r   r   r   r    )r'   r   r(   r)   r/   r0   r   )r   vad_outr=   r   r   sig_lenbeg_samp	step_sizeend_sampindex
vad_signalr   r   r   upsample_VAD  s"   
zVAD.upsample_VADc           	      C   s   |  |\}}|| jkrtdtjd||jd}t|jd D ]}t||df | }t||df | }d|d||f< q |S )a  Based on the input boundaries, this method creates a signal that is 1
        when there is speech and 0 when there is no speech.
        The vad signal has the same resolution as the input one and can be
        opened with it (e.g, using audacity) to visually figure out VAD regions.

        Arguments
        ---------
        boundaries: torch.Tensor
            torch.Tensor containing the boundaries of the speech segments.
        audio_file: path
            The original audio file used to compute vad_out

        Returns
        -------
        vad_signal
            The output vad signal with the same resolution of the input one.
        r   r   r    r   rt   )	r'   r   r(   r/   r0   r   ri   r.   r)   )	r   r~   r=   r   r   r   ro   
beg_sampler   r   r   r   upsample_boundaries  s   
zVAD.upsample_boundariesc                 C   s   |  |\}}g }t|jd D ]@}t||df | }t||df | }	|	| }
tjt|||
d\}}| |}| |krP|	||df ||df g qt
||j}|S )a  Takes in input the boundaries of the detected speech segments and
        double checks (using the neural VAD) that they actually contain speech.

        Arguments
        ---------
        boundaries: torch.Tensor
            torch.Tensor containing the boundaries of the speech segments.
        audio_file: path
            The original audio file used to compute vad_out.
        speech_th: float
            Threshold on the mean posterior probability over which speech is
            confirmed. Below that threshold, the segment is re-assigned to a
            non-speech region.

        Returns
        -------
        new_boundaries
            The boundaries of the segments where speech activity is confirmed.
        r   r   r   )r'   ri   r.   r)   r*   r+   r,   r8   r   r<   r/   r   r-   r   )r   r~   r=   	speech_thr   r   r   ro   r   r   len_segr   rJ   speech_probr   r   r   double_check_speech_segments  s   


z VAD.double_check_speech_segments皙?c                 C   s   |  |\}}|| jkrtdg }t|jd D ];}||df | }	||df | }
ttd|	||  }	tt||
||  }
|
|	 }tj	||	|d\}}|
| q|S )aq  Returns a list containing all the detected speech segments.

        Arguments
        ---------
        boundaries: torch.Tensor
            torch.Tensor containing the boundaries of the speech segments.
        audio_file: path
            The original audio file used to compute vad_out.
        before_margin: float
            Used to cut the segments samples a bit before the detected margin.
        after_margin: float
            Use to cut the segments samples a bit after the detected margin.

        Returns
        -------
        segments: list
            List containing the detected speech segments
        r   r   r   r   )r'   r   r(   ri   r.   r)   maxminr*   r+   r<   )r   r~   r=   before_marginafter_marginr   r   segmentsro   r   r   r   vad_segmentrJ   r   r   r   get_segments  s&   

zVAD.get_segmentsc                 C   s   t |\}}t||d}| j||||d}| j||	|
d }| j|dd}|r1| j||||d}| j||d}| j||d}|rI| j	|||d}|S )	a'  Detects speech segments within the input file. The input signal can
        be both a short or a long recording. The function computes the
        posterior probabilities on large chunks (e.g, 30 sec), that are read
        sequentially (to avoid storing big signals in memory).
        Each large chunk is, in turn, split into smaller chunks (e.g, 10 seconds)
        that are processed in parallel. The pipeline for detecting the speech
        segments is the following:
            1- Compute posteriors probabilities at the frame level.
            2- Apply a threshold on the posterior probability.
            3- Derive candidate speech segments on top of that.
            4- Apply energy VAD within each candidate segment (optional).
            5- Merge segments that are too close.
            6- Remove segments that are too short.
            7- Double check speech segments (optional).

        Arguments
        ---------
        audio_file : str
            Path to audio file.
        large_chunk_size: float
            Size (in seconds) of the large chunks that are read sequentially
            from the input audio file.
        small_chunk_size: float
            Size (in seconds) of the small chunks extracted from the large ones.
            The audio signal is processed in parallel within the small chunks.
            Note that large_chunk_size/small_chunk_size must be an integer.
        overlap_small_chunk: bool
            If True, it creates overlapped small chunks (with 50% overlap).
            The probabilities of the overlapped chunks are combined using
            hamming windows.
        apply_energy_VAD: bool
            If True, a energy-based VAD is used on the detected speech segments.
            The neural network VAD often creates longer segments and tends to
            merge close segments together. The energy VAD post-processes can be
            useful for having a fine-grained voice activity detection.
            The energy thresholds is  managed by activation_th and
            deactivation_th (see below).
        double_check: bool
            If True, double checks (using the neural VAD) that the candidate
            speech segments actually contain speech. A threshold on the mean
            posterior probabilities provided by the neural network is applied
            based on the speech_th parameter (see below).
        close_th: float
            If the distance between boundaries is smaller than close_th, the
            segments will be merged.
        len_th: float
            If the length of the segment is smaller than close_th, the segments
            will be merged.
        activation_th:  float
            Threshold of the neural posteriors above which starting a speech segment.
        deactivation_th: float
            Threshold of the neural posteriors below which ending a speech segment.
        en_activation_th: float
            A new speech segment is started it the energy is above activation_th.
            This is active only if apply_energy_VAD is True.
        en_deactivation_th: float
            The segment is considered ended when the energy is <= deactivation_th.
            This is active only if apply_energy_VAD is True.
        speech_th: float
            Threshold on the mean posterior probability within the candidate
            speech segment. Below that threshold, the segment is re-assigned to
            a non-speech region. This is active only if double_check is True.

        Returns
        -------
        boundaries: torch.Tensor
            torch.Tensor containing the start second of speech segments in even
            positions and their corresponding end in odd positions
            (e.g, [1.0, 1.5, 5,.0 6.0] means that we have two speech segment;
             one from 1.0 to 1.5 seconds and another from 5.0 to 6.0 seconds).
        )source)r>   r?   r@   r   rq   r   )r   )r   )r   )
r   r   rS   rp   rY   r   r   r   r   r   )r   r=   r>   r?   r@   apply_energy_VADdouble_checkr   r   rk   rl   en_activation_then_deactivation_thr   r   flrF   ry   r~   r   r   r   get_speech_segments<  s<   YzVAD.get_speech_segmentsc                 C   s   |  ||S )z,Gets frame-level speech-activity predictions)r8   )r   r`   ra   r   r   r   forward  s   zVAD.forward)r   r   Fr   )rf   rg   )rq   )rg   )NTN)rf   r   r   )r   r   )r   )rf   )r   r   )r   r   FFTrg   rg   rf   rg   rf   r   rf   )__name__
__module____qualname____doc__HPARAMS_NEEDEDMODULES_NEEDEDr   rS   r9   r8   rp   r   r   r   r   r   r   r'   r   r   r   r   r   r   __classcell__r   r   r   r   r      s\    
 
3

%
>
/ 
O

e
	.&
/
0
 r   )
r   r/   r*    speechbrain.inference.interfacesr   speechbrain.utils.data_utilsr   speechbrain.utils.fetchingr   r   r   r   r   r   <module>   s    