
    iD                        d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	 d dl
mZmZmZ d dlmZ d dlmZ ded	ed
efdZ	 	 	 	 d#dedededededed
efdZded
efdZded
efdZdee   d
efdZde	eee   f   dee	eee   f      ded   d
ee	eee   f   ee	eee   f      f   fdZ	 	 	 	 d#dede	eee   f   dedededed
efdZ	 	 	 	 	 	 d$de	eee   f   dee	eee   f      ded   dededededeee      d
ee   fd Z	 	 	 	 	 	 d%de	eee   f   dee	eee   f      ded   d!ededededed
e	eeeef   f   fd"Zy)&    N)Sequence)inf)ListOptionalUnion)Tensorstacktensor)Literal)_validate_inputs
preds_wordtarget_wordreturnc                     t        | |k7        S )a.  Distance measure used for substitutions/identity operation.

    Code adapted from https://github.com/rwth-i6/ExtendedEditDistance/blob/master/EED.py.

    Args:
        preds_word: hypothesis word string
        target_word: reference word string

    Return:
        0 for match, 1 for no match

    )int)r   r   s     u/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/functional/text/eed.py_distance_between_wordsr   e   s     z[())    hyprefalpharhodeletion	insertionc                    dgt        |       dz   z  }dgt        |       dz   z  }d|d<   t        gt        |       dz   z  }t        dt        |      dz         D ]  }	t        t        |       dz         D ]Q  }
|
dkD  r?t        ||
dz
     |z   ||
dz
     t	        | |
dz
     ||	dz
           z   ||
   |z         ||
<   G||
   dz   ||
<   S |j                  t        |            }||xx   dz  cc<   ||	dz
     dk(  r!|||   z   }|D cg c]  }t        ||       }}|}t        gt        |       dz   z  } |t        d |D              z  }t        d|d   |z   t        t        |            |z   z        S c c}w )a8  Compute extended edit distance score for two lists of strings: hyp and ref.

    Code adapted from: https://github.com/rwth-i6/ExtendedEditDistance/blob/master/EED.py.

    Args:
        hyp: A hypothesis string
        ref: A reference string
        alpha: optimal jump penalty, penalty for jumps between characters
        rho: coverage cost, penalty for repetition of characters
        deletion: penalty for deletion of character
        insertion: penalty for insertion or substitution of character

    Return:
        Extended edit distance score as float
             ?        r    c              3   .   K   | ]  }|d k\  r|nd  yw)r   r   N ).0xs     r   	<genexpr>z _eed_function.<locals>.<genexpr>   s     F5Ea1f!+5Es   )lenr   rangeminr   indexsumfloat)r   r   r   r   r   r   number_of_visitsrownext_rowwi	min_indexjumpr$   coverages                  r   _eed_functionr4   u   s   . ts3x!|, %3s8a<
 CCFuC1%H1c#hl#s3x!|$A1u!QUOh.AJ!8QUSQZ!PPFY& "!fsl % NN3x=1	#q(# q1u:8I..D.67hAthH75CHqL)) $, SF5EFFFHq3r7X%%C/H*DEFF 8s   E2sentencec                 L   t        | t              st        dt        |        d      | j	                         } g d}|D ]  \  }}| j                  ||      }  g d}|D ]  \  }}t        j                  |||       }  g d}|D ]  \  }}| j                  ||      }  d| z   dz   S )zPreprocess english sentences.

    Copied from https://github.com/rwth-i6/ExtendedEditDistance/blob/master/util.py.

    Raises:
        ValueError: If input sentence is not of a type `str`.

    6Only strings allowed during preprocessing step, found  instead)).z .)!z !)?z ?),z ,))z\s+r    )z(\d) ([.,]) (\d)z\1\2\3)z#(Dr|Jr|Prof|Rev|Gen|Mr|Mt|Mrs|Ms) .z\1.))ze . g .ze.g.)zi . e .zi.e.)zU . S .zU.S.r    )
isinstancestr
ValueErrortyperstripreplaceresub)r5   rules_interpunctionpatternreplacementrules_res        r   _preprocess_enrI      s     h$QRVW_R`Qaaijkk H !4##G[9 !4H
 !)66';9 !)
 !4##G[9 !4 >Cr   c                     t        | t              st        dt        |        d      | j	                         } t        j                  d|       S )zPreprocess japanese sentences.

    Copy from https://github.com/rwth-i6/ExtendedEditDistance/blob/master/util.py.

    Raises:
        ValueError: If input sentence is not of a type `str`.

    r7   r8   NFKC)r=   r>   r?   r@   rA   unicodedata	normalize)r5   s    r   _preprocess_jarN      sK     h$QRVW_R`Qaaijkk H  22r   sentence_level_scoresc                 t    t        |       dk(  rt        d      S t        |       t        t        |             z  S )zReduction for extended edit distance.

    Args:
        sentence_level_scores: list of sentence-level scores as floats

    Return:
        average of scores as a tensor

    r   r   )r&   r
   r*   )rO   s    r   _eed_computerQ      s8      !Q&c{$%s3H/I(JJJr   predstargetlanguage)enjac           
      
   t        | |      \  }} |dk(  rt        }n|dk(  rt        }nt        d|       | D cg c]
  } ||       } }|D cg c]  }|D cg c]
  } ||       c} }}}| |fS c c}w c c}w c c}}w )au  Preprocess strings according to language requirements.

    Args:
        preds: An iterable of hypothesis corpus.
        target: An iterable of iterables of reference corpus.
        language: Language used in sentences. Only supports English (en) and Japanese (ja) for now. Defaults to en

    Return:
        Tuple of lists that contain the cleaned strings for target and preds

    Raises:
        ValueError: If a different language than ``'en'`` or ``'ja'`` is used
        ValueError: If length of target not equal to length of preds
        ValueError: If objects in reference and hypothesis corpus are not strings

    )hypothesis_corpus
ref_corpusrU   rV   z?Expected argument `language` to either be `en` or `ja` but got )r   rI   rN   r?   )rR   rS   rT   preprocess_functionpred	referencer   s          r   _preprocess_sentencesr]      s    , %uPMFE 4,	T	,Z[cZdeff38954 &5E9OUVv)9=9C"3'9=vFV&= :=Vs   A5	A?A:)A?:A?target_wordsc           	      b    t         }|D ]  }t        | |||||      }||k  s|} t        |      S )a  Compute scores for ExtendedEditDistance.

    Args:
        target_words: An iterable of reference words
        preds_word: A hypothesis word
        alpha: An optimal jump penalty, penalty for jumps between characters
        rho: coverage cost, penalty for repetition of characters
        deletion: penalty for deletion of character
        insertion: penalty for insertion or substitution of character

    Return:
        best_score: best (lowest) sentence-level score as a Tensor

    )r   r4   r
   )	r   r^   r   r   r   r   
best_scorer\   scores	            r   _compute_sentence_statisticsrb   #  sA    , J!	j)UC9U:J "
 *r   sentence_eedc           	          t        | ||      \  } }|g }dt        |       t        |d         fv r|S t        | |      D ]&  \  }}	t        ||	||||      }
|j	                  |
       ( |S )a  Compute scores for ExtendedEditDistance.

    Args:
        preds: An iterable of hypothesis corpus
        target: An iterable of iterables of reference corpus
        language: Language used in sentences. Only supports English (en) and Japanese (ja) for now. Defaults to en
        alpha: optimal jump penalty, penalty for jumps between characters
        rho: coverage cost, penalty for repetition of characters
        deletion: penalty for deletion of character
        insertion: penalty for insertion or substitution of character
        sentence_eed: list of sentence-level scores

    Return:
        individual sentence scores as a list of Tensors

    r   )r]   r&   ziprb   append)rR   rS   rT   r   r   r   r   rc   
hypothesisr^   ra   s              r   _eed_updaterh   C  s    4 *%BME6 	SZVAY(($'v$6 
L,ZucS[]fgE" %7 r   return_sentence_level_scorec           	          t        g d||||g      D ]:  \  }}	t        |	t              rt        |	t              s'|	dk  s-t        d| d       t	        | ||||||      }
t        |
      }|r|t        |
      fS |S )uX  Compute extended edit distance score (`ExtendedEditDistance`_) [1] for strings or list of strings.

    The metric utilises the Levenshtein distance and extends it by adding a jump operation.

    Args:
        preds: An iterable of hypothesis corpus.
        target: An iterable of iterables of reference corpus.
        language: Language used in sentences. Only supports English (en) and Japanese (ja) for now. Defaults to en
        return_sentence_level_score: An indication of whether sentence-level EED score is to be returned.
        alpha: optimal jump penalty, penalty for jumps between characters
        rho: coverage cost, penalty for repetition of characters
        deletion: penalty for deletion of character
        insertion: penalty for insertion or substitution of character

    Return:
        Extended edit distance score as a tensor

    Example:
        >>> from torchmetrics.functional.text import extended_edit_distance
        >>> preds = ["this is the prediction", "here is an other sample"]
        >>> target = ["this is the reference", "here is another one"]
        >>> extended_edit_distance(preds=preds, target=target)
        tensor(0.3078)

    References:
        [1] P. Stanchev, W. Wang, and H. Ney, “EED: Extended Edit Distance Measure for Machine Translation”,
        submitted to WMT 2019. `ExtendedEditDistance`_

    )r   r   r   r   r   zParameter `z)` is expected to be a non-negative float.)re   r=   r+   r?   rh   rQ   r	   )rR   rS   rT   ri   r   r   r   r   
param_nameparamrO   averages               r   extended_edit_distancern   m  s    P !!JUTWYaclLmn
E%'Jue,DQR{:,6_`aa o (vxXW`a01G"3444Nr   )       @333333?皙?r   )rU   ro   rp   rq   r   N)rU   Fro   rp   rq   r   ) rC   rL   collections.abcr   mathr   typingr   r   r   torchr   r	   r
   typing_extensionsr   #torchmetrics.functional.text.helperr   r>   r   r   r+   r4   rI   rN   rQ   tupler]   rb   rh   boolrn   r"   r   r   <module>rz      s	  r 
  $  ( ( ' ' % @* *# *# *& 7G	7G	7G 7G 
	7G
 7G 7G 7Gt* S * S * Z3S 3S 3"KV K K #hsm#$#U3-./# j!# 5hsm#$huS(3-5G/H&IIJ	#R Xc]*+  
	
   F %)+/'hsm#$'U3-./' j!' 	'
 
' ' ' 4<(' 
&\'Z %)(-2hsm#$2U3-./2 j!2 "&	2
 2 
2 2 2 65(()2r   