o
    7wiV                     @   sh   d Z ddlZddlZddlmZmZmZ ddlmZ eG dd dej	j
Zdd Zd	d
 Zdd ZdS )zI
Alignment code

Authors
 * Elena Rastorgueva 2020
 * Loren Lugosch 2020
    N)mark_as_loadermark_as_saverregister_checkpoint_hooks)undo_paddingc                       s   e Zd ZdZ							d1 fdd		Zd
d Zd2ddZdd Zdd Zdd Z	dd Z
dd Zdd Z	d3ddZdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd3d)d*Zd+d, Zed-d. Zed4d/d0Z  ZS )5
HMMAligneras  This class calculates Viterbi alignments in the forward method.

    It also records alignments and creates batches of them for use
    in Viterbi training.

    Arguments
    ---------
    states_per_phoneme : int
        Number of hidden states to use per phoneme.
    output_folder : str
        It is the folder that the alignments will be stored in when
        saved to disk. Not yet implemented.
    neg_inf : float
        The float used to represent a negative infinite log probability.
        Using `-float("Inf")` tends to give numerical instability.
        A number more negative than -1e5 also sometimes gave errors when
        the `genbmm` library was used (currently not in use). (default: -1e5)
    batch_reduction : string
        One of "none", "sum" or "mean".
        What kind of batch-level reduction to apply to the loss calculated
        in the forward method.
    input_len_norm : bool
        Whether to normalize the loss in the forward method by the length of
        the inputs.
    target_len_norm : bool
        Whether to normalize the loss in the forward method by the length of
        the targets.
    lexicon_path : string
        The location of the lexicon.

    Example
    -------
    >>> log_posteriors = torch.tensor([[[ -1., -10., -10.],
    ...                                 [-10.,  -1., -10.],
    ...                                 [-10., -10.,  -1.]],
    ...
    ...                                [[ -1., -10., -10.],
    ...                                 [-10.,  -1., -10.],
    ...                                 [-10., -10., -10.]]])
    >>> lens = torch.tensor([1., 0.66])
    >>> phns = torch.tensor([[0, 1, 2],
    ...                      [0, 1, 0]])
    >>> phn_lens = torch.tensor([1., 0.66])
    >>> aligner = HMMAligner()
    >>> forward_scores = aligner(
    ...        log_posteriors, lens, phns, phn_lens, 'forward'
    ... )
    >>> forward_scores.shape
    torch.Size([2])
    >>> viterbi_scores, alignments = aligner(
    ...        log_posteriors, lens, phns, phn_lens, 'viterbi'
    ... )
    >>> alignments
    [[0, 1, 2], [0, 1]]
    >>> viterbi_scores.shape
    torch.Size([2])
             jnoneFNc                    s  t    || _|| _|| _|| _|| _|| _i | _|| _	| j	d urt
| j	ddd}| }	W d    n1 s9w   Y  t|	D ]\}
}|d dkrP|
} nqBi }t }t|t|	D ]L}
|	|
 }| d }|dd }dd	d
 |D }|dD ]}|| qd|v r|dd }||v rt|| }||| |< q]d|i||< q]|| _t|}|  dd t|D | _dd t|D | _d| jd< d| jd< d S d S )Nrzutf-8)encodingr   ;/r   r   c                 S   s   g | ]}|  s|qS  )isdigit).0pr   r   Z/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/speechbrain/alignment/aligner.py
<listcomp>w   s    z'HMMAligner.__init__.<locals>.<listcomp> ~c                 S   s   i | ]	\}}||d  qS r   r   r   ir   r   r   r   
<dictcomp>       z'HMMAligner.__init__.<locals>.<dictcomp>c                 S   s   i | ]	\}}|d  |qS r   r   r   r   r   r   r      r   sil)super__init__states_per_phonemeoutput_folderneg_infbatch_reductioninput_len_normtarget_len_norm
align_dictlexicon_pathopen	readlines	enumeratesetrangelensplitjoinaddlexiconlistsortlex_lab2indlex_ind2lab)selfr   r    r!   r"   r#   r$   r&   flinesr   linestart_indexr0   lexicon_phoneswordphonesr   !number_of_existing_pronunciations	__class__r   r   r   Q   sR   




zHMMAligner.__init__c              	      sl  dg d}g }|D ]}|dks|du r@|fddt jD gdg |fddt jD 7 }j7 |d7 }|g dg|rXtj| dkrXtj|  t tj| D ]E}j| | }| }	d g  |	D ]*|fddt jD 7 }d |  fd	dt jD 7  < j7 qw|r nqa |d7 }q
|fd
dt jD gdg |fddt jD 7 }j7 |d7 }dt	 }
g }D ]d }d }|td k }fddt td D }d D ]}t t|d D ]}|| }||d  }d|
||f< qq|rd|s6|s;|d  n|d   fddt t  d D }|D ]}|D ]	}d|
||f< qWqSn||7 }|s|d }| d d d }|D ]	}d|
||f< q{q|

 d}d d d d g}|fddt td d D 7 }t|}||||fS )a  Do processing using the lexicon to return a sequence of the possible
        phonemes, the transition/pi probabilities, and the possible final states.
        Inputs correspond to a single utterance, not a whole batch.

        Arguments
        ---------
        words : list
            List of the words in the transcript.
        interword_sils : bool
            If True, optional silences will be inserted between every word.
            If False, optional silences will only be placed at the beginning
            and end of each utterance.
        sample_pron : bool
            If True, it will sample a single possible sequence of phonemes.
            If False, it will return statistics for all possible sequences of
            phonemes.

        Returns
        -------
        poss_phns : torch.Tensor (phoneme)
            The phonemes that are thought to be in each utterance.
        log_transition_matrix : torch.Tensor (batch, from, to)
            Tensor containing transition (log) probabilities.
        start_states : list of ints
            A list of the possible starting states in each utterance.
        final_states : list of ints
            A list of the possible final states for each utterance.
        r   Tc                       g | ]} | qS r   r   r   r   number_of_statesr   r   r          z+HMMAligner._use_lexicon.<locals>.<listcomp>c                       g | ]
} j  j | qS r   silence_indexr   rA   r5   r   r   r          r   Fc                    s    g | ]}j   j | qS r   )r3   r   rA   )r   r5   r   r   r          c                    r@   r   r   rA   rB   r   r   r      rD   c                    r@   r   r   rA   rB   r   r   r          c                    rE   r   rF   rA   rH   r   r   r      rI   g      ?   c                    s   g | ]
} d  | d qS )r   rL   r   rA   )
word_primer   r   r      s    c                    s    g | ]}  d  | d qS r   r   r   rA   )next_word_idxwords_primer   r   r     rJ   c                    s    g | ]} d  d  | d qS rO   r   rA   )rQ   r   r   r   #  s    )r+   r   appendr,   r0   randomshuffler-   torcheyeloglog_softmaxtensor)r5   wordsinterword_silssample_pron
word_indexphoneme_indicesr;   pron_idxpronunciationphonemestransition_matrixfinal_statesword_idxis_optional_silencenext_word_existsthis_word_last_states	state_idxstate
next_statenext_word_starting_statesthis_word_last_statenext_word_starting_statenext_silence_idxnext_silence_starting_statelog_transition_matrixstart_states	poss_phnsr   )rP   rC   r   r5   rN   rQ   r   _use_lexicon   s   













zHMMAligner._use_lexiconTc                 C   sn  | j d | _g }g }g }g }|D ]!}| |||\}	}
}}||	 ||
 || || qdd |D }t|}t|}t|D ]-}|t||  }tjj	j
|| d|fdd||< tjj	j
|| d|d|f| jd||< qEt|}t|}| j||td k< | jt||g }|D ]
}d|dd|f< qtjj	j|dd	}t| | }|||||fS )
a  Do processing using the lexicon to return a sequence of the possible
        phonemes, the transition/pi probabilities, and the possible final
        states.
        Does processing on an utterance-by-utterance basis. Each utterance
        in the batch is processed by a helper method `_use_lexicon`.

        Arguments
        ---------
        words : list
            List of the words in the transcript
        interword_sils : bool
            If True, optional silences will be inserted between every word.
            If False, optional silences will only be placed at the beginning
            and end of each utterance.
        sample_pron: bool
            If True, it will sample a single possible sequence of phonemes.
            If False, it will return statistics for all possible sequences of
            phonemes.

        Returns
        -------
        poss_phns: torch.Tensor (batch, phoneme in possible phn sequence)
            The phonemes that are thought to be in each utterance.
        poss_phn_lens: torch.Tensor (batch)
            The relative length of each possible phoneme sequence in the batch.
        trans_prob: torch.Tensor (batch, from, to)
            Tensor containing transition (log) probabilities.
        pi_prob: torch.Tensor (batch, state)
            Tensor containing initial (log) probabilities.
        final_state: list of lists of ints
            A list of lists of possible final states for each utterance.

        Example
        -------
        >>> aligner = HMMAligner()
        >>> aligner.lexicon = {
        ...                     "a": {0: "a"},
        ...                     "b": {0: "b", 1: "c"}
        ...                   }
        >>> words = [["a", "b"]]
        >>> aligner.lex_lab2ind = {
        ...                   "sil": 0,
        ...                   "a":  1,
        ...                   "b":  2,
        ...                   "c":  3,
        ...                 }
        >>> poss_phns, poss_phn_lens, trans_prob, pi_prob, final_states = aligner.use_lexicon(
        ...     words,
        ...     interword_sils = True
        ... )
        >>> poss_phns
        tensor([[0, 1, 0, 2, 3, 0]])
        >>> poss_phn_lens
        tensor([1.])
        >>> trans_prob
        tensor([[[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05,
                  -1.0000e+05],
                 [-1.0000e+05, -1.3863e+00, -1.3863e+00, -1.3863e+00, -1.3863e+00,
                  -1.0000e+05],
                 [-1.0000e+05, -1.0000e+05, -1.0986e+00, -1.0986e+00, -1.0986e+00,
                  -1.0000e+05],
                 [-1.0000e+05, -1.0000e+05, -1.0000e+05, -6.9315e-01, -1.0000e+05,
                  -6.9315e-01],
                 [-1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05, -6.9315e-01,
                  -6.9315e-01],
                 [-1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05,
                   0.0000e+00]]])
        >>> pi_prob
        tensor([[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05,
                 -1.0000e+05]])
        >>> final_states
        [[3, 4, 5]]
        >>> # With no optional silences between words
        >>> poss_phns_, _, trans_prob_, pi_prob_, final_states_ = aligner.use_lexicon(
        ...     words,
        ...     interword_sils = False
        ... )
        >>> poss_phns_
        tensor([[0, 1, 2, 3, 0]])
        >>> trans_prob_
        tensor([[[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05],
                 [-1.0000e+05, -1.0986e+00, -1.0986e+00, -1.0986e+00, -1.0000e+05],
                 [-1.0000e+05, -1.0000e+05, -6.9315e-01, -1.0000e+05, -6.9315e-01],
                 [-1.0000e+05, -1.0000e+05, -1.0000e+05, -6.9315e-01, -6.9315e-01],
                 [-1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05,  0.0000e+00]]])
        >>> pi_prob_
        tensor([[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05]])
        >>> final_states_
        [[2, 3, 4]]
        >>> # With sampling of a single possible pronunciation
        >>> import random
        >>> random.seed(0)
        >>> poss_phns_, _, trans_prob_, pi_prob_, final_states_ = aligner.use_lexicon(
        ...     words,
        ...     sample_pron = True
        ... )
        >>> poss_phns_
        tensor([[0, 1, 0, 2, 0]])
        >>> trans_prob_
        tensor([[[-6.9315e-01, -6.9315e-01, -1.0000e+05, -1.0000e+05, -1.0000e+05],
                 [-1.0000e+05, -1.0986e+00, -1.0986e+00, -1.0986e+00, -1.0000e+05],
                 [-1.0000e+05, -1.0000e+05, -6.9315e-01, -6.9315e-01, -1.0000e+05],
                 [-1.0000e+05, -1.0000e+05, -1.0000e+05, -6.9315e-01, -6.9315e-01],
                 [-1.0000e+05, -1.0000e+05, -1.0000e+05, -1.0000e+05,  0.0000e+00]]])
        r   c                 S      g | ]}t |qS r   r,   )r   
poss_phns_r   r   r   r     rK   z*HMMAligner.use_lexicon.<locals>.<listcomp>r   valueInfr   Ndim)r3   rG   rs   rR   maxr,   r+   rU   nn
functionalpadr!   stackfloatonesrX   rY   )r5   rZ   r[   r\   rr   
trans_probrq   rc   words_rv   trans_prob_start_states_final_states_poss_phn_lensU_max
batch_sizeindexphn_pad_lengthpi_probstart_stater   r   r   use_lexicon+  sL   j






zHMMAligner.use_lexiconc                 C   s<   t |}t| }| jt||g }d|dddf< |S )aw  Creates tensor of initial (log) probabilities (known as 'pi').
        Assigns all probability mass to the first phoneme in the sequence.

        Arguments
        ---------
        phn_lens_abs : torch.Tensor (batch)
            The absolute length of each phoneme sequence in the batch.

        Returns
        -------
        pi_prob : torch.Tensor (batch, phn)
        r   N)r,   intr|   r!   rU   r   )r5   phn_lens_absr   r   r   r   r   r   _make_pi_prob  s
   zHMMAligner._make_pi_probc                 C   sR  t |}t| }|j}t|d }t|d dg}td|g}t||fd}t||fd}t|}|| }	|	d||	|dd
|}	tj||ddddf |dddf k }
|
d}
|
dd|}
|
ddd}|	|
|@   }	t|	dk|	tjtd |d}	tjjj|	dd}	| j|	|	|	k< | j|	|	td k< |	S )	a  Creates tensor of transition (log) probabilities.
        Only allows transitions to the same phoneme (self-loop) or the next
        phoneme in the phn sequence

        Arguments
        ---------
        phn_lens_abs : torch.Tensor (batch)
            The absolute length of each phoneme sequence in the batch.

        Returns
        -------
        trans_prob : torch.Tensor (batch, from, to)
        r   r   deviceNrM   rL   ry   rz   )r,   r   r|   r   rU   rV   zeroscatreshaperepeattoarange	unsqueezeexpandpermuter   whererY   r}   r~   rX   r!   )r5   r   r   r   r   trans_prob_off_diag	zero_sidezero_bottomtrans_prob_main_diagr   mask_amask_br   r   r   _make_trans_prob  s:   

(
zHMMAligner._make_trans_probc                 C   s  t |  }t |  }|j}t||dddf |dddf k }t|dddddf |tjdg|d}	||}|	d
d|d}
t|	d|
}t||dddf |dddf k }t|dddddf |tj| jg|d}|ddd}|S )aE  Creates a 'useful' form of the posterior probabilities, rearranged
        into the order of phoneme appearance in phns.

        Arguments
        ---------
        emission_pred : torch.Tensor (batch, time, phoneme in vocabulary)
            posterior probabilities from our acoustic model
        lens_abs : torch.Tensor (batch)
            The absolute length of each input to the acoustic model,
            i.e., the number of frames.
        phn_lens_abs : torch.Tensor (batch)
            The absolute length of each phoneme sequence in the batch.
        phns : torch.Tensor (batch, phoneme in phn sequence)
            The phonemes that are known/thought to be in each utterance.

        Returns
        -------
        emiss_pred_useful : torch.Tensor
            Tensor shape (batch, phoneme in phn sequence, time).
        N        r   r   rL   rM   r   )r   r|   itemr   rU   r   r   r   rY   r   r   gatherr!   r   )r5   emission_predlens_absr   phnsr   fb_max_lengthr   	mask_lensemiss_pred_acc_lensphns_copiedemiss_pred_usefulmask_phn_lensr   r   r   _make_emiss_pred_useful  s,   *
*z"HMMAligner._make_emiss_pred_usefulc                 C   s`  t |}| }| }	|j}
||
}||
}| jtj|||	g|
d }||dddddf  |dddddf< td|	D ][}||k }d|v rq| }| jt||| }d|ddt	|t	|f< ||
}|||< t
|ddd|dddd|d f }||dddd|f  |dddd|f< qAtj|t	|dddf dd	}|S )
a  Does forward dynamic programming algorithm.

        Arguments
        ---------
        pi_prob : torch.Tensor (batch, phn)
            Tensor containing initial (log) probabilities.
        trans_prob : torch.Tensor (batch, from, to)
            Tensor containing transition (log) probabilities.
        emiss_pred_useful : torch.Tensor (batch, phoneme in phn sequence, time)
            A 'useful' form of the posterior probabilities, rearranged
            into the order of phoneme appearance in phns.
        lens_abs : torch.Tensor (batch)
            The absolute length of each input to the acoustic model,
            i.e., the number of frames.
        phn_lens_abs : torch.Tensor (batch)
            The absolute length of each phoneme sequence in the batch.
        phns : torch.Tensor (batch, phoneme in phn sequence)
            The phonemes that are known/thought to be in each utterance.

        Returns
        -------
        sum_alpha_T : torch.Tensor (batch)
            The (log) likelihood of each utterance in the batch.
        r   Nr   r   Tr   rM   rL   rz   )r,   r|   r   r   r!   rU   r   r+   sumr   batch_log_matvecmulr   	logsumexp)r5   r   r   r   r   r   r   r   r   r   r   alpha_matrixtutt_lens_passedn_passedI_tensoralpha_times_transsum_alpha_Tr   r   r   _dp_forwardY  s6   "


,
$zHMMAligner._dp_forwardc                  C   s6  t |}| }	| }
|j}||}||}| jtj||	|
g|d }dtj||	|
g|d }||dddddf  |dddddf< td|
D ]>}t|	ddd|dddd|d f \}}||dddd|f  |dddd|f< |
tj|dddd|f< qMg }g }t|D ]s}|| }|dur|| }||||d f }t| }|| }n
||   d }|g}|||d f  g}t|ddD ]'}|d }||||d f   }|||f  }|d| |d| q|| || q|t||d |d f }|||fS )a  Calculates Viterbi alignment using dynamic programming.

        Arguments
        ---------
        pi_prob : torch.Tensor (batch, phn)
            Tensor containing initial (log) probabilities.
        trans_prob : torch.Tensor (batch, from, to)
            Tensor containing transition (log) probabilities.
        emiss_pred_useful : torch.Tensor (batch, phoneme in phn sequence, time)
            A 'useful' form of the posterior probabilities, rearranged
            into the order of phoneme appearance in phns.
        lens_abs : torch.Tensor (batch)
            The absolute length of each input to the acoustic model,
            i.e., the number of frames.
        phn_lens_abs : torch.Tensor (batch)
            The absolute length of each phoneme sequence in the batch.
        phns : torch.Tensor (batch, phoneme in phn sequence)
            The phonemes that are known/thought to be in each utterance.
        final_states : list
            List of final states

        Returns
        -------
        z_stars : list of lists of int
            Viterbi alignments for the files in the batch.
        z_stars_loc : list of lists of int
            The locations of the Viterbi alignments for the files in the batch.
            e.g., for a batch with a single utterance with 5 phonemes,
            `z_stars_loc` will look like:
            [[0, 0, 0, 1, 1, 2, 3, 3, 3, 4, 4]].
        viterbi_scores : torch.Tensor (batch)
            The (log) likelihood of the Viterbi path for each utterance.
        r   iNr   r   rM   rL   )r,   r|   r   r   r!   rU   r   r+   batch_log_maxvecmulr   typeFloatTensorargmaxr   longinsertrR   r   ) r5   r   r   r   r   r   r   rc   r   r   r   r   v_matrixbackpointersr   xr   z_starsz_stars_locutterance_in_batchlen_absfinal_states_utterviterbi_finalsfinal_state_chosenUz_star_i_locz_star_i	time_stepcurrent_best_locearlier_best_locearlier_z_starviterbi_scoresr   r   r   _dp_viterbi  sl   -



,$, 


zHMMAligner._dp_viterbic                 C   sp   | j du rt||}| jdu rt||}| jdkr	 |S | jdkr)| }|S | jdkr4| }|S td)a  Applies reduction to loss as specified during object initialization.

        Arguments
        ---------
        loss : torch.Tensor (batch)
            The loss tensor to be reduced.
        input_lens : torch.Tensor (batch)
            The absolute durations of the inputs.
        target_lens : torch.Tensor (batch)
            The absolute durations of the targets.

        Returns
        -------
        loss : torch.Tensor (batch, or scalar)
            The loss with reduction applied if it is specified.

        Tr
   r   meanzB`batch_reduction` parameter must be one of 'none', 'sum' or 'mean')r#   rU   divr$   r"   r   r   
ValueError)r5   loss
input_lenstarget_lensr   r   r   _loss_reduction  s    





zHMMAligner._loss_reductionc              	   C   s  t |jd |  }t |jd |  }| }|du r-| |}	| |}
d}nd|v rFd|v rFd|v rF|d }	|d }
|d }ntd | ||||}|dkri| |	|
||||}| 	|||}|S |dkr| 
|	|
|||||\}}}| 	|||}||fS td	)
a  Prepares relevant (log) probability tensors and does dynamic
        programming: either the forward or the Viterbi algorithm. Applies
        reduction as specified during object initialization.

        Arguments
        ---------
        emission_pred : torch.Tensor (batch, time, phoneme in vocabulary)
            Posterior probabilities from our acoustic model.
        lens : torch.Tensor (batch)
            The relative duration of each utterance sound file.
        phns : torch.Tensor (batch, phoneme in phn sequence)
            The phonemes that are known/thought to be in each utterance
        phn_lens : torch.Tensor (batch)
            The relative length of each phoneme sequence in the batch.
        dp_algorithm : string
            Either "forward" or "viterbi".
        prob_matrices : dict
            (Optional) Must contain keys 'trans_prob', 'pi_prob' and 'final_states'.
            Used to override the default forward and viterbi operations which
            force traversal over all of the states in the `phns` sequence.

        Returns
        -------
        tensor

            (1) if dp_algorithm == "forward".

                ``forward_scores`` : torch.Tensor (batch, or scalar)

                The (log) likelihood of each utterance in the batch, with reduction
                applied if specified. (OR)

            (2) if dp_algorithm == "viterbi".

                ``viterbi_scores`` : torch.Tensor (batch, or scalar)

                The (log) likelihood of the Viterbi path for each utterance, with
                reduction applied if specified.

                ``alignments`` : list of lists of int

                Viterbi alignments for the files in the batch.
        r   Nr   r   rc   z``prob_matrices` must contain the keys
                `pi_prob`, `trans_prob` and `final_states`forwardviterbiz8dp_algorithm input must be either 'forward' or 'viterbi')rU   roundshaper   r   r   r   r   r   r   r   )r5   r   lensr   phn_lensdp_algorithmprob_matricesr   r   r   r   rc   r   forward_scores
alignments_r   r   r   r   r   :  sb   5


	

zHMMAligner.forwardc                    s   t |jd |jd j }||j}t||}t|D ]'\}}g }|D ] | fddtjD 7 }q&t 	|||dt
|f< q|S )a"  Expands each phoneme in the phn sequence by the number of hidden
        states per phoneme defined in the HMM.

        Arguments
        ---------
        phns : torch.Tensor (batch, phoneme in phn sequence)
            The phonemes that are known/thought to be in each utterance.
        phn_lens : torch.Tensor (batch)
            The relative length of each phoneme sequence in the batch.

        Returns
        -------
        expanded_phns : torch.Tensor (batch, phoneme in expanded phn sequence)

        Example
        -------
        >>> phns = torch.tensor([[0., 3., 5., 0.],
        ...                      [0., 2., 0., 0.]])
        >>> phn_lens = torch.tensor([1., 0.75])
        >>> aligner = HMMAligner(states_per_phoneme = 3)
        >>> expanded_phns = aligner.expand_phns_by_states_per_phoneme(
        ...         phns, phn_lens
        ... )
        >>> expanded_phns
        tensor([[ 0.,  1.,  2.,  9., 10., 11., 15., 16., 17.,  0.,  1.,  2.],
                [ 0.,  1.,  2.,  6.,  7.,  8.,  0.,  1.,  2.,  0.,  0.,  0.]])
        r   r   c                    s   g | ]	}j   | qS r   r   )r   i_phoneme_indexr5   r   r   r     s    z@HMMAligner.expand_phns_by_states_per_phoneme.<locals>.<listcomp>N)rU   r   r   r   r   r   r   r)   r+   rY   r,   )r5   r   r   expanded_phnsr   phns_uttexpanded_phns_uttr   r   r   !expand_phns_by_states_per_phoneme  s   

z,HMMAligner.expand_phns_by_states_per_phonemec                 C   s<   t |D ]\}}|| }tj|tjd }|| j|< qdS )a  Records Viterbi alignments in `self.align_dict`.

        Arguments
        ---------
        ids : list of str
            IDs of the files in the batch.
        alignments : list of lists of int
            Viterbi alignments for the files in the batch.
            Without padding.

        Example
        -------
        >>> aligner = HMMAligner()
        >>> ids = ['id1', 'id2']
        >>> alignments = [[0, 2, 4], [1, 2, 3, 4]]
        >>> aligner.store_alignments(ids, alignments)
        >>> aligner.align_dict.keys()
        dict_keys(['id1', 'id2'])
        >>> aligner.align_dict['id1']
        tensor([0, 2, 4], dtype=torch.int16)
        )dtypeN)r)   rU   rY   int16cpur%   )r5   idsr   r   idalignment_ir   r   r   store_alignments  s
   zHMMAligner.store_alignmentsc           
      C   s   |  }t|}t|}tj|||jd  }t|D ]M}|| }|d||  }t||  t| }	|	dkr<d}	|	|	}|d||  }tj
jj|dt|| t| f|d d}|||dt|f< q|S )a  Prepares flat start alignments (with zero padding) for every utterance
        in the batch.
        Every phoneme will have an equal duration, except for the final phoneme
        potentially. E.g. if 104 frames and 10 phonemes, 9 phonemes will have
        duration of 10 frames, and one phoneme will have a duration of 14 frames.

        Arguments
        ---------
        lens_abs : torch.Tensor (batch)
            The absolute length of each input to the acoustic model,
            i.e., the number of frames.

        phn_lens_abs : torch.Tensor (batch)
            The absolute length of each phoneme sequence in the batch.

        phns : torch.Tensor (batch, phoneme in phn sequence)
            The phonemes that are known/thought to be in each utterance.

        Returns
        -------
        flat_start_batch : torch.Tensor (batch, time)
            Flat start alignments for utterances in the batch, with zero padding.
        r   Nr   r   rL   rw   )r   r,   rU   r|   r   r   r+   r   r   repeat_interleaver}   r~   r   )
r5   r   r   r   r   r   flat_start_batchr   
utter_phns
repeat_amtr   r   r   _get_flat_start_batch  s.   

z HMMAligner._get_flat_start_batchc                 C   sp   t |}t|}tj|||jd }t|D ]}| j||  }tjj	
|d|t | f}| ||< q|S )a1  Retrieves Viterbi alignments stored in `self.align_dict` and
        creates a batch of them, with zero padding.

        Arguments
        ---------
        ids : list of str
            IDs of the files in the batch.
        lens_abs : torch.Tensor (batch)
            The absolute length of each input to the acoustic model,
            i.e., the number of frames.

        Returns
        -------
        viterbi_batch : torch.Tensor (batch, time)
            The previously-recorded Viterbi alignments for the utterances
            in the batch.

        r   r   )r,   rU   r|   r   r   r   r+   r%   r}   r~   r   )r5   r   r   r   r   viterbi_batchr   viterbi_predsr   r   r   _get_viterbi_batch7  s   
zHMMAligner._get_viterbi_batchc                 C   sX   t |jd |  }t |jd |  }|d | jv r%| ||S | |||S )a  Fetches previously recorded Viterbi alignments if they are available.
        If not, fetches flat start alignments.
        Currently, assumes that if a Viterbi alignment is not available for the
        first utterance in the batch, it will not be available for the rest of
        the utterances.

        Arguments
        ---------
        ids : list of str
            IDs of the files in the batch.
        emission_pred : torch.Tensor (batch, time, phoneme in vocabulary)
            Posterior probabilities from our acoustic model. Used to infer the
            duration of the longest utterance in the batch.
        lens : torch.Tensor (batch)
            The relative duration of each utterance sound file.
        phns : torch.Tensor (batch, phoneme in phn sequence)
            The phonemes that are known/thought to be in each utterance.
        phn_lens : torch.Tensor (batch)
            The relative length of each phoneme sequence in the batch.

        Returns
        -------
        torch.Tensor (batch, time)
            Zero-padded alignments.

        Example
        -------
        >>> ids = ['id1', 'id2']
        >>> emission_pred = torch.tensor([[[ -1., -10., -10.],
        ...                                [-10.,  -1., -10.],
        ...                                [-10., -10.,  -1.]],
        ...
        ...                               [[ -1., -10., -10.],
        ...                                [-10.,  -1., -10.],
        ...                                [-10., -10., -10.]]])
        >>> lens = torch.tensor([1., 0.66])
        >>> phns = torch.tensor([[0, 1, 2],
        ...                      [0, 1, 0]])
        >>> phn_lens = torch.tensor([1., 0.66])
        >>> aligner = HMMAligner()
        >>> alignment_batch = aligner.get_prev_alignments(
        ...        ids, emission_pred, lens, phns, phn_lens
        ... )
        >>> alignment_batch
        tensor([[0, 1, 2],
                [0, 1, 0]])
        r   r   )rU   r   r   r   r%   r   r   )r5   r   r   r   r   r   r   r   r   r   r   get_prev_alignmentsZ  s
   1zHMMAligner.get_prev_alignmentsc           
         s   dgdd  D    fddt dt D }g }t t|D ]}||| g||  7 }q t|}tttt|t| }t|}||}|dt| }t|t|krmtjj	|dt|t| f}||k
   d }	|	S )a  Calculates the accuracy between predicted alignments and ground truth
        alignments for a single sentence/utterance.

        Arguments
        ---------
        alignments_ : list of ints
            The predicted alignments for the utterance.
        ends_ : list of ints
            A list of the sample indices where each ground truth phoneme
            ends, according to the transcription.
        phns_ : list of ints
            The unpadded list of ground truth phonemes in the utterance.

        Returns
        -------
        mean_acc : float
            The mean percentage of times that the upsampled predicted alignment
            matches the ground truth alignment.
        r   c                 S   rt   r   )r   )r   endr   r   r   r     rK   z2HMMAligner._calc_accuracy_sent.<locals>.<listcomp>c                    s    g | ]} |  |d    qS r   r   rA   ends_r   r   r     s     r   Nd   )r+   r,   rU   rY   r   r   r   r}   r~   r   r   r   r   )
r5   alignments_r  phns_true_durationstrue_alignmentsr   upsample_factoralignments_upsampledaccuracyr   r  r   _calc_accuracy_sent  s*   


zHMMAligner._calc_accuracy_sentc                    s   g } j dkr fdd|D }|durt|||\}}t|||D ]\}}} |||}	||	 q"t|}| }
|
dS )aq  Calculates mean accuracy between predicted alignments and ground truth
        alignments. Ground truth alignments are derived from ground truth phns
        and their ends in the audio sample.

        Arguments
        ---------
        alignments : list of lists of ints/floats
            The predicted alignments for each utterance in the batch.
        ends : list of lists of ints
            A list of lists of sample indices where each ground truth phoneme
            ends, according to the transcription.
            Note: current implementation assumes that 'ends' mark the index
            where the next phoneme begins.
        phns : list of lists of ints/floats
            The unpadded list of lists of ground truth phonemes in the batch.
        ind2labs : tuple
            (Optional)
            Contains the original index-to-label dicts for the first and second
            sequence of phonemes.

        Returns
        -------
        mean_acc : float
            The mean percentage of times that the upsampled predicted alignment
            matches the ground truth alignment.

        Example
        -------
        >>> aligner = HMMAligner()
        >>> alignments = [[0., 0., 0., 1.]]
        >>> phns = [[0., 1.]]
        >>> ends = [[2, 4]]
        >>> mean_acc = aligner.calc_accuracy(alignments, ends, phns)
        >>> mean_acc.item()
        75.0
        r   c                       g | ]} fd d|D qS )c                       g | ]}| j  qS r   r   rA   rH   r   r   r         z7HMMAligner.calc_accuracy.<locals>.<listcomp>.<listcomp>r   r   uttrH   r   r   r     s    z,HMMAligner.calc_accuracy.<locals>.<listcomp>Nr   )	r   map_inds_to_intersectzipr  rR   rU   rY   r   r   )r5   r   endsr   ind2labsacc_histr  r  r  accmean_accr   rH   r   calc_accuracy  s   %



zHMMAligner.calc_accuracyc                    s>    fddt  D }fdd|D }fdd|D }|S )aT  
        Converts alignments to 1 state per phoneme style.

        Arguments
        ---------
        alignments : list of ints
            Predicted alignments for a single utterance.

        Returns
        -------
        sequence : list of ints
            The predicted alignments converted to a 1 state per phoneme style.

        Example
        -------
        >>> aligner = HMMAligner(states_per_phoneme = 3)
        >>> alignments = [0, 1, 2, 3, 4, 5, 3, 4, 5, 0, 1, 2]
        >>> sequence = aligner.collapse_alignments(alignments)
        >>> sequence
        [0, 1, 1, 0]
        c                    s,   g | ]\}}|d ks| |d  kr|qS )r   r   r   )r   r   v)r   r   r   r     s
    z2HMMAligner.collapse_alignments.<locals>.<listcomp>c                    s   g | ]}| j  d kr|qS )r   r   r   r  rH   r   r   r   !      c                    r  r   r   r  rH   r   r   r   $  r  )r)   )r5   r   sequencer   )r   r5   r   collapse_alignments  s   
zHMMAligner.collapse_alignmentsc                 C   s   t | j| d S N)rU   saver%   )r5   pathr   r   r   _save(  s   zHMMAligner._savec                 C   s   ~t || _d S r  )rU   loadr%   )r5   r!  end_of_epochr   r   r   _load,  s   zHMMAligner._load)r   r   r	   r
   FFN)TFr  )F)__name__
__module____qualname____doc__r   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r"  r   r%  __classcell__r   r   r>   r   r      sD    <> 
 B:Ht,
w0:#9
4;&
r   c                    s   |\ t   t  }}||}||}||}dd t|D fddt|D  fddt|D   fdd| D }fdd|D }	fdd|D }
fd	d|	D }|
|fS )
a  Converts 2 lists containing indices for phonemes from different
    phoneme sets to a single phoneme so that comparing the equality
    of the indices of the resulting lists will yield the correct
    accuracy.

    Arguments
    ---------
    lists1 : list of lists of ints
        Contains the indices of the first sequence of phonemes.
    lists2 : list of lists of ints
        Contains the indices of the second sequence of phonemes.
    ind2labs : tuple (dict, dict)
        Contains the original index-to-label dicts for the first and second
        sequence of phonemes.

    Returns
    -------
    lists1_new : list of lists of ints
        Contains the indices of the first sequence of phonemes, mapped
        to the new phoneme set.
    lists2_new : list of lists of ints
        Contains the indices of the second sequence of phonemes, mapped
        to the new phoneme set.

    Example
    -------
    >>> lists1 = [[0, 1]]
    >>> lists2 = [[0, 1]]
    >>> ind2lab1 = {
    ...        0: "a",
    ...        1: "b",
    ...        }
    >>> ind2lab2 = {
    ...        0: "a",
    ...        1: "c",
    ...        }
    >>> ind2labs = (ind2lab1, ind2lab2)
    >>> out1, out2 = map_inds_to_intersect(lists1, lists2, ind2labs)
    >>> out1
    [[0, 1]]
    >>> out2
    [[0, 2]]
    c                 S   s   i | ]\}}||qS r   r   r   r   labr   r   r   r   j  r  z)map_inds_to_intersect.<locals>.<dictcomp>c                       i | ]\}}|t  | qS r   ru   r+  new_lab2indr   r   r   l  r  c                    r-  r   ru   r+  r.  r   r   r   o  r  c                    r  )c                       g | ]} | qS r   r   r   indind2lab1r   r   r   s  rK   4map_inds_to_intersect.<locals>.<listcomp>.<listcomp>r   r  r3  r   r   r   s  r  z)map_inds_to_intersect.<locals>.<listcomp>c                    r  )c                    r0  r   r   r1  ind2lab2r   r   r   t  rK   r5  r   r  r6  r   r   r   t  r  c                    r  )c                    r0  r   r   r   r,  r.  r   r   r   v  rK   r5  r   r  r.  r   r   r   v  r  c                    r  )c                    r0  r   r   r8  r.  r   r   r   w  rK   r5  r   r  r.  r   r   r   w  r  )r*   valuesintersection
differencer)   update)lists1lists2r  set1set2	intersect	set1_only	set2_only
lists1_lab
lists2_lab
lists1_new
lists2_newr   )r4  r7  r/  r   r  2  s"   ,


r  c                 C   s    | d}tj| | dd}|S )aK  For each 'matrix' and 'vector' pair in the batch, do matrix-vector
    multiplication in the log domain, i.e., logsumexp instead of add,
    add instead of multiply.

    Arguments
    ---------
    A : torch.Tensor (batch, dim1, dim2)
        Tensor
    b : torch.Tensor (batch, dim1)
        Tensor.

    Returns
    -------
    x : torch.Tensor (batch, dim1)

    Example
    -------
    >>> A = torch.tensor([[[   0., 0.],
    ...                    [ -1e5, 0.]]])
    >>> b = torch.tensor([[0., 0.,]])
    >>> x = batch_log_matvecmul(A, b)
    >>> x
    tensor([[0.6931, 0.0000]])
    >>>
    >>> # non-log domain equivalent without batching functionality
    >>> A_ = torch.tensor([[1., 1.],
    ...                    [0., 1.]])
    >>> b_ = torch.tensor([1., 1.,])
    >>> x_ = torch.matmul(A_, b_)
    >>> x_
    tensor([2., 1.])
    r   rM   rz   )r   rU   r   )Abr   r   r   r   r   |  s   
!r   c                 C   s(   | d}tj| | dd\}}||fS )a  Similar to batch_log_matvecmul, but takes a maximum instead of
    logsumexp. Returns both the max and the argmax.

    Arguments
    ---------
    A : torch.Tensor (batch, dim1, dim2)
        Tensor.
    b : torch.Tensor (batch, dim1)
        Tensor

    Returns
    -------
    x : torch.Tensor (batch, dim1)
        Tensor.
    argmax : torch.Tensor (batch, dim1)
        Tensor.

    Example
    -------
    >>> A = torch.tensor([[[   0., -1.],
    ...                    [ -1e5,  0.]]])
    >>> b = torch.tensor([[0., 0.,]])
    >>> x, argmax = batch_log_maxvecmul(A, b)
    >>> x
    tensor([[0., 0.]])
    >>> argmax
    tensor([[0, 1]])
    r   rM   rz   )r   rU   r|   )rH  rI  r   r   r   r   r   r     s   
r   )r)  rS   rU   speechbrain.utils.checkpointsr   r   r   speechbrain.utils.data_utilsr   r}   Moduler   r  r   r   r   r   r   r   <module>   s(              &J'