Ë
    þÍ:j¡D  ã                   óˆ  — 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/home/mcse/projects/srt_converter/srt-converter-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   è ø€ ÒF°˜a 1šf™¨!Ó+ÑFùs   ‚)Ú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®  € ð. �tœs 3›x¨!™|Ñ,Ðð ˆ%”3�s“8˜a‘<Ñ
 €Cà€Cˆ�FÜˆuœ˜C› 1™Ñ%€Hä�1”c˜#“h ‘lÓ#ò *ˆÜ”s˜3“x !‘|Ó$ò 	+ˆAØ�1ŠuÜ!Ø˜Q ™U‘O hÑ.Ø˜˜A™‘JÔ!8¸¸QÀ¹U¹ÀSÈÈQÉÁZÓ!PÑPØ˜‘F˜YÑ&ó�˜’ð " !™f s™l�˜’ð	+ð —N‘N¤3 x£=Ó1ˆ	Ø˜Ó# qÑ(Ó#ð ˆq�1‰u‰:˜ÒØ˜8 IÑ.Ñ.ˆDØ.6Ö7¨œ˜A˜t�Ð7ˆHÐ7àˆÜ�5œC ›H q™LÑ)‰ð)*ð, ”SÑFÐ5EÔFÓFÑF€Häˆq�3�r‘7˜XÑ%¬%´°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 )zÄPreprocess 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¤Ô$ÜÐQÔRVÐW_ÓR`ÐQaÐaiÐjÓkÐkà�‰Ó €HòÐð !4ò :Ñˆ�Ø×#Ñ# G¨[Ó9‰ð:ò€Hð
 !)ò :Ñˆ�Ü—6‘6˜' ;°Ó9‰ð:òÐð
 !4ò :Ñˆ�Ø×#Ñ# G¨[Ó9‰ð:ð �‰>˜CÑÐr   c                 óž   — t        | t        «      st        dt        | «      › d�«      ‚| j	                  «       } t        j                  d| «      S )zÃPreprocess 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¤Ô$ÜÐQÔRVÐW_ÓR`ÐQaÐaiÐjÓkÐkà�‰Ó €Hä× Ñ  ¨Ó2Ð2r   Úsentence_level_scoresc                 ót   — t        | «      dk(  rt        d«      S t        | «      t        t        | «      «      z  S )z°Reduction 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‹{ÐäÐ$Ó%¬¬sÐ3HÓ/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ÈÔP�M€FˆEð �4ÒÜ,ÑØ	�TÒ	Ü,ÑäÐZÐ[cÐZdÐeÓfÐfà38Ö9¨4Ñ  Õ&Ð9€EÐ9ØOU×VÀ)°9Ö=¨CÑ" 3Õ'Ô=ÐV€FÑ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   #  sF   € ô, €Jà!ò ˆ	Ü˜j¨)°U¸CÀÈ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 *¨%°¸ÓB�M€Eˆ6àÐØˆð 	ŒS�‹Zœ˜V A™Y›Ð(Ñ(ØÐä$'¨¨vÓ$6ò #Ñ ˆ
�LÜ,¨Z¸ÀuÈcÐS[Ð]fÓgˆØ×Ñ˜EÕ"ð#ð Ð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 !Ò!JÈUÐTWÐYaÐclÐLmÓnò bÑˆ
�EÜ˜%¤Ô'¬J°u¼eÕ,DÈÐQRËÜ˜{¨:¨,Ð6_Ð`ÓaÐaðbô (¨¨v°xÀÈÈXÐW`ÓaÐäÐ0Ó1€Gá"ØœÐ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3˜Sð 3 Só 3ð"K¨¨V©ð K¸ó Kð #Ø��h˜s‘mÐ#Ñ$ð#à�U˜3 ¨¡Ð-Ñ.Ñ/ð#ð �jÑ!ð#ð ˆ5��h˜s‘mÐ#Ñ$ h¨u°S¸(À3¹-Ð5GÑ/HÑ&IÐIÑJó	#ðR ØØØñØðà˜˜X c™]Ð*Ñ+ðð ðð 
ð	ð
 ðð ðð óðF %)ØØØØØ+/ñ'Ø��h˜s‘mÐ#Ñ$ð'à�U˜3 ¨¡Ð-Ñ.Ñ/ð'ð �jÑ!ð'ð ð	'ð
 
ð'ð ð'ð ð'ð ˜4 ™<Ñ(ð'ð 
ˆ&�\ó'ðZ %)Ø(-ØØØØñ2Ø��h˜s‘mÐ#Ñ$ð2à�U˜3 ¨¡Ð-Ñ.Ñ/ð2ð �jÑ!ð2ð "&ð	2ð
 ð2ð 
ð2ð ð2ð ð2ð ˆ6�5˜ ˜Ñ(Ð(Ñ)ô2r   