o
    ¡¿¯i«
  ã                   @   s(   d Z ddlZddlZG dd„ deƒZdS )zCommon functions for ST and MT.é    Nc                       s2   e Zd ZdZd	‡ fdd„	Zdd„ Zdd„ Z‡  ZS )
ÚErrorCalculatora>  Calculate BLEU for ST and MT models during training.

    :param y_hats: numpy array with predicted text
    :param y_pads: numpy array with true (target) text
    :param char_list: vocabulary list
    :param sym_space: space symbol
    :param sym_pad: pad symbol
    :param report_bleu: report BLUE score if True
    Fc                    sP   t t| ƒ ¡  || _|| _|| _|| _| j| jv r#| j | j¡| _dS d| _dS )z$Construct an ErrorCalculator object.N)	Úsuperr   Ú__init__Ú	char_listÚspaceÚpadÚreport_bleuÚindexÚ	idx_space)Úselfr   Ú	sym_spaceÚsym_padr   ©Ú	__class__© úM/home/ubuntu/.local/lib/python3.10/site-packages/espnet/nets/e2e_mt_common.pyr      s   
zErrorCalculator.__init__c                 C   s   d}| j s|S |  ||¡}|S )z÷Calculate corpus-level BLEU score.

        :param torch.Tensor ys_hat: prediction (batch, seqlen)
        :param torch.Tensor ys_pad: reference (batch, seqlen)
        :return: corpus-level BLEU score in a mini-batch
        :rtype float
        N)r   Úcalculate_corpus_bleu)r   Úys_hatÚys_padÚbleur   r   r   Ú__call__$   s
   zErrorCalculator.__call__c                    sè   g g }}t |ƒD ]Z\}}|| }t |dk¡d }t|ƒdkr$|d nt|ƒ}	‡ fdd„|d|	… D ƒ}
‡ fdd„|D ƒ}d |
¡ ˆ jd¡}| ˆ jd¡}d |¡ ˆ jd¡}| |¡ | |¡ q	t	j
 d	d„ |D ƒ|¡}|d
 S )züCalculate corpus-level BLEU score in a mini-batch.

        :param torch.Tensor seqs_hat: prediction (batch, seqlen)
        :param torch.Tensor seqs_true: reference (batch, seqlen)
        :return: corpus-level BLEU score
        :rtype float
        éÿÿÿÿr   c                    s   g | ]	}ˆ j t|ƒ ‘qS r   )r   Úint©Ú.0Úidx©r   r   r   Ú
<listcomp>B   s    z9ErrorCalculator.calculate_corpus_bleu.<locals>.<listcomp>Nc                    s&   g | ]}t |ƒd krˆ jt |ƒ ‘qS )r   )r   r   r   r   r   r   r   C   s   & Ú ú c                 S   s   g | ]}|g‘qS r   r   )r   Úrefr   r   r   r   I   s    éd   )Ú	enumerateÚnpÚwhereÚlenÚjoinÚreplacer   r   ÚappendÚnltkÚ
bleu_scoreÚcorpus_bleu)r   r   r   Úseqs_hatÚ	seqs_trueÚiÚy_hatÚy_trueÚeos_trueÚymaxÚseq_hatÚseq_trueÚseq_hat_textÚseq_true_textr   r   r   r   r   3   s   

z%ErrorCalculator.calculate_corpus_bleu)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   Ú__classcell__r   r   r   r   r      s
    
r   )r:   r)   Únumpyr#   Úobjectr   r   r   r   r   Ú<module>   s   