B
    `B                 @   s   d dl mZ d dlmZ d dlmZmZ ejfddZ	dd Z
dd	 Ze fd
dZe fddZefddZefddZe efddZe efddZdd Zeje edddfddZeje edddfddZdS )     )PorterStemmer)wordnet)chainproductc             C   s0   t t||  }t t|| }||fS )a  
    Takes in string inputs for hypothesis and reference and returns
    enumerated word lists for each of them

    :param hypothesis: hypothesis string
    :type hypothesis: str
    :param reference: reference string
    :type reference: str
    :preprocess: preprocessing method (default str.lower)
    :type preprocess: method
    :return: enumerated words list
    :rtype: list of 2D tuples, list of 2D tuples
    )list	enumeratesplit)
hypothesis	reference
preprocesshypothesis_listreference_list r   J/home/dcms/DCMS/lib/python3.7/site-packages/nltk/translate/meteor_score.py_generate_enums   s    r   c             C   s   t | |\}}t||S )a  
    matches exact words in hypothesis and reference
    and returns a word mapping based on the enumerated
    word id between hypothesis and reference

    :param hypothesis: hypothesis string
    :type hypothesis: str
    :param reference: reference string
    :type reference: str
    :return: enumerated matched tuples, enumerated unmatched hypothesis tuples,
             enumerated unmatched reference tuples
    :rtype: list of 2D tuples, list of 2D tuples,  list of 2D tuples
    )r   _match_enums)r	   r
   r   r   r   r   r   exact_match"   s    r   c             C   s   g }xt t| ddd D ]x}xrt t|ddd D ]X}| | d || d kr8|| | d || d f | |d ||d f P q8W qW || |fS )aQ  
    matches exact words in hypothesis and reference and returns
    a word mapping between enum_hypothesis_list and enum_reference_list
    based on the enumerated word id.

    :param enum_hypothesis_list: enumerated hypothesis list
    :type enum_hypothesis_list: list of tuples
    :param enum_reference_list: enumerated reference list
    :type enum_reference_list: list of 2D tuples
    :return: enumerated matched tuples, enumerated unmatched hypothesis tuples,
             enumerated unmatched reference tuples
    :rtype: list of 2D tuples, list of 2D tuples,  list of 2D tuples
    N   r   )rangelenappendpop)enum_hypothesis_listenum_reference_list
word_matchijr   r   r   r   4   s    
r   c                s   fdd| D }fdd|D }t ||\} t dkrLtt  ng  tdkrhtt ng tt fdd| } ttfdd|}|| |fS )a
  
    Stems each word and matches them in hypothesis and reference
    and returns a word mapping between enum_hypothesis_list and
    enum_reference_list based on the enumerated word id. The function also
    returns a enumerated list of unmatched words for hypothesis and reference.

    :param enum_hypothesis_list:
    :type enum_hypothesis_list:
    :param enum_reference_list:
    :type enum_reference_list:
    :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
    :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
    :return: enumerated matched tuples, enumerated unmatched hypothesis tuples,
             enumerated unmatched reference tuples
    :rtype: list of 2D tuples, list of 2D tuples,  list of 2D tuples
    c                s"   g | ]}|d    |d fqS )r   r   )stem).0	word_pair)stemmerr   r   
<listcomp>b   s    z$_enum_stem_match.<locals>.<listcomp>c                s"   g | ]}|d    |d fqS )r   r   )r   )r   r    )r!   r   r   r"   f   s    r   c                s   | d  kS )Nr   r   )x)enum_unmat_hypo_listr   r   <lambda>v       z"_enum_stem_match.<locals>.<lambda>c                s   | d  kS )Nr   r   )r#   )enum_unmat_ref_listr   r   r%   z   r&   )r   r   r   zipfilter)r   r   r!   Zstemmed_enum_list1Zstemmed_enum_list2r   r   )r$   r'   r!   r   _enum_stem_matchN   s    r*   c             C   s   t | |\}}t|||dS )a[  
    Stems each word and matches them in hypothesis and reference
    and returns a word mapping between hypothesis and reference

    :param hypothesis:
    :type hypothesis:
    :param reference:
    :type reference:
    :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
    :type stemmer: nltk.stem.api.StemmerI or any class that
                   implements a stem method
    :return: enumerated matched tuples, enumerated unmatched hypothesis tuples,
             enumerated unmatched reference tuples
    :rtype: list of 2D tuples, list of 2D tuples,  list of 2D tuples
    )r!   )r   r*   )r	   r
   r!   r   r   r   r   r   
stem_match   s    r+   c             C   s   g }xt t| ddd D ]}ttdd || | d D  | | d h}xbt t|ddd D ]H}|| d |krl|| | d || d f | |||f P qlW qW || |fS )a  
    Matches each word in reference to a word in hypothesis
    if any synonym of a hypothesis word is the exact match
    to the reference word.

    :param enum_hypothesis_list: enumerated hypothesis list
    :param enum_reference_list: enumerated reference list
    :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
    :type wordnet: WordNetCorpusReader
    :return: list of matched tuples, unmatched hypothesis list, unmatched reference list
    :rtype:  list of tuples, list of tuples, list of tuples

    Nr   c             S   s   g | ]}d d |  D qS )c             S   s&   g | ]}|  d dk r|  qS )_r   )namefind)r   Zlemmar   r   r   r"      s   z5_enum_wordnetsyn_match.<locals>.<listcomp>.<listcomp>)Zlemmas)r   Zsynsetr   r   r   r"      s   z*_enum_wordnetsyn_match.<locals>.<listcomp>r   r   )r   r   setr   Zsynsetsunionr   r   )r   r   r   r   r   Zhypothesis_synsr   r   r   r   _enum_wordnetsyn_match   s    
r1   c             C   s   t | |\}}t|||dS )a  
    Matches each word in reference to a word in hypothesis if any synonym
    of a hypothesis word is the exact match to the reference word.

    :param hypothesis: hypothesis string
    :param reference: reference string
    :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
    :type wordnet: WordNetCorpusReader
    :return: list of mapped tuples
    :rtype: list of tuples
    )r   )r   r1   )r	   r
   r   r   r   r   r   r   wordnetsyn_match   s    r2   c             C   sV   t | |\}} }t| ||d\}} }t| ||d\}} }t|| | dd d| |fS )ap  
    Aligns/matches words in the hypothesis to reference by sequentially
    applying exact match, stemmed match and wordnet based synonym match.
    in case there are multiple matches the match which has the least number
    of crossing is chosen. Takes enumerated list as input instead of
    string input

    :param enum_hypothesis_list: enumerated hypothesis list
    :param enum_reference_list: enumerated reference list
    :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
    :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
    :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
    :type wordnet: WordNetCorpusReader
    :return: sorted list of matched tuples, unmatched hypothesis list,
             unmatched reference list
    :rtype: list of tuples, list of tuples, list of tuples
    )r!   )r   c             S   s   | d S )Nr   r   )Zwordpairr   r   r   r%      r&   z$_enum_allign_words.<locals>.<lambda>)key)r   r*   r1   sorted)r   r   r!   r   Zexact_matchesZstem_matchesZwns_matchesr   r   r   _enum_allign_words   s    r5   c             C   s   t | |\}}t||||dS )a  
    Aligns/matches words in the hypothesis to reference by sequentially
    applying exact match, stemmed match and wordnet based synonym match.
    In case there are multiple matches the match which has the least number
    of crossing is chosen.

    :param hypothesis: hypothesis string
    :param reference: reference string
    :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
    :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
    :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
    :type wordnet: WordNetCorpusReader
    :return: sorted list of matched tuples, unmatched hypothesis list, unmatched reference list
    :rtype: list of tuples, list of tuples, list of tuples
    )r!   r   )r   r5   )r	   r
   r!   r   r   r   r   r   r   allign_words   s    r6   c             C   s|   d}d}xn|t | d k rv| |d  d | | d d krd| |d  d | | d d krd|d7 }q
|d7 }|d7 }q
W |S )at  
    Counts the fewest possible number of chunks such that matched unigrams
    of each chunk are adjacent to each other. This is used to caluclate the
    fragmentation part of the metric.

    :param matches: list containing a mapping of matched words (output of allign_words)
    :return: Number of chunks a sentence is divided into post allignment
    :rtype: int
    r   r   )r   )matchesr   chunksr   r   r   _count_chunks  s    
  r9   g?   g      ?c             C   s   t || |d\}}	t|}
t|	}t||	|d\}}}t|}yLt||
 }t|| }|| || d| |   }tt|}|| }W n tk
r   dS X |||  }d| | S )aT  
    Calculates METEOR score for single hypothesis and reference as per
    "Meteor: An Automatic Metric for MT Evaluation with HighLevels of
    Correlation with Human Judgments" by Alon Lavie and Abhaya Agarwal,
    in Proceedings of ACL.
    http://www.cs.cmu.edu/~alavie/METEOR/pdf/Lavie-Agarwal-2007-METEOR.pdf


    >>> hypothesis1 = 'It is a guide to action which ensures that the military always obeys the commands of the party'

    >>> reference1 = 'It is a guide to action that ensures that the military will forever heed Party commands'


    >>> round(single_meteor_score(reference1, hypothesis1),4)
    0.7398

        If there is no words match during the alignment the method returns the
        score as 0. We can safely  return a zero instead of raising a
        division by zero error as no match usually implies a bad translation.

    >>> round(meteor_score('this is a cat', 'non matching hypothesis'),4)
    0.0

    :param references: reference sentences
    :type references: list(str)
    :param hypothesis: a hypothesis sentence
    :type hypothesis: str
    :param preprocess: preprocessing function (default str.lower)
    :type preprocess: method
    :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
    :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
    :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
    :type wordnet: WordNetCorpusReader
    :param alpha: parameter for controlling relative weights of precision and recall.
    :type alpha: float
    :param beta: parameter for controlling shape of penalty as a
                 function of as a function of fragmentation.
    :type beta: float
    :param gamma: relative weight assigned to fragmentation penality.
    :type gamma: float
    :return: The sentence-level METEOR score.
    :rtype: float
    )r   )r!   r   g        )r   r   r5   floatr9   ZeroDivisionError)r
   r	   r   r!   r   alphabetagammaZenum_hypothesisZenum_referenceZtranslation_lengthZreference_lengthr7   r,   Zmatches_countZ	precisionZrecallZfmeanZchunk_countZ	frag_fracZpenaltyr   r   r   single_meteor_score"  s     5r@   c                s    t  fdd| D S )a	  
    Calculates METEOR score for hypothesis with multiple references as
    described in "Meteor: An Automatic Metric for MT Evaluation with
    HighLevels of Correlation with Human Judgments" by Alon Lavie and
    Abhaya Agarwal, in Proceedings of ACL.
    http://www.cs.cmu.edu/~alavie/METEOR/pdf/Lavie-Agarwal-2007-METEOR.pdf


    In case of multiple references the best score is chosen. This method
    iterates over single_meteor_score and picks the best pair among all
    the references for a given hypothesis

    >>> hypothesis1 = 'It is a guide to action which ensures that the military always obeys the commands of the party'
    >>> hypothesis2 = 'It is to insure the troops forever hearing the activity guidebook that party direct'

    >>> reference1 = 'It is a guide to action that ensures that the military will forever heed Party commands'
    >>> reference2 = 'It is the guiding principle which guarantees the military forces always being under the command of the Party'
    >>> reference3 = 'It is the practical guide for the army always to heed the directions of the party'

    >>> round(meteor_score([reference1, reference2, reference3], hypothesis1),4)
    0.7398

        If there is no words match during the alignment the method returns the
        score as 0. We can safely  return a zero instead of raising a
        division by zero error as no match usually implies a bad translation.

    >>> round(meteor_score(['this is a cat'], 'non matching hypothesis'),4)
    0.0

    :param references: reference sentences
    :type references: list(str)
    :param hypothesis: a hypothesis sentence
    :type hypothesis: str
    :param preprocess: preprocessing function (default str.lower)
    :type preprocess: method
    :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
    :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
    :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
    :type wordnet: WordNetCorpusReader
    :param alpha: parameter for controlling relative weights of precision and recall.
    :type alpha: float
    :param beta: parameter for controlling shape of penalty as a function
                 of as a function of fragmentation.
    :type beta: float
    :param gamma: relative weight assigned to fragmentation penality.
    :type gamma: float
    :return: The sentence-level METEOR score.
    :rtype: float
    c                s"   g | ]}t | d qS ))r!   r   r=   r>   r?   )r@   )r   r
   )r=   r>   r?   r	   r!   r   r   r   r"     s   	z meteor_score.<locals>.<listcomp>)max)Z
referencesr	   r   r!   r   r=   r>   r?   r   )r=   r>   r?   r	   r!   r   r   meteor_scorej  s    ;	rB   N)Znltk.stem.porterr   Znltk.corpusr   	itertoolsr   r   strlowerr   r   r   r*   r+   r1   r2   r5   r6   r9   r@   rB   r   r   r   r   <module>
   s0   1&(C