o
    f,                     @   s   d dl mZ d dl mZ ddlZddlZddlmZ ejZej	Z
e
edfddZe
edfd	d
Ze
eddfddZe
edfddZdejfddZdS )   )fuzz)utils    N)partialc              	   c   s   dd }z|du st |dkrW dS W n	 ty   Y nw |du r$|}|| }t |dkr6td|  |tjtjtjtj	tj
tjtjtjfv rQ|tjkrQ|}|tjtjfv rgttjdd}t|dd}n |tjtjtjtj	tj
tjfv rttjd	d}t|dd}n|}||}z!| D ]\}}	|||	}
|||
}||kr|	||fV  qW dS  ty   |D ]}	|||	}
|||
}||kr|	|fV  qY dS w )
a	  Select the best match in a list or dictionary of choices.

    Find best matches in a list or dictionary of choices, return a
    generator of tuples containing the match and its score. If a dictionary
    is used, also returns the key for each match.

    Arguments:
        query: An object representing the thing we want to find.
        choices: An iterable or dictionary-like object containing choices
            to be matched against the query. Dictionary arguments of
            {key: value} pairs will attempt to match the query against
            each value.
        processor: Optional function of the form f(a) -> b, where a is the query or
            individual choice and b is the choice to be used in matching.

            This can be used to match against, say, the first element of
            a list:

            lambda x: x[0]

            Defaults to fuzzywuzzy.utils.full_process().
        scorer: Optional function for scoring matches between the query and
            an individual processed choice. This should be a function
            of the form f(query, choice) -> int.

            By default, fuzz.WRatio() is used and expects both query and
            choice to be strings.
        score_cutoff: Optional argument for score threshold. No matches with
            a score less than this number will be returned. Defaults to 0.

    Returns:
        Generator of tuples containing the match and its score.

        If a list is used for choices, then the result will be 2-tuples.
        If a dictionary is used, then the result will be 3-tuples containing
        the key for each match.

        For example, searching for 'bird' in the dictionary

        {'bard': 'train', 'dog': 'man'}

        may return

        ('train', 22, 'bard'), ('man', 0, 'dog')
    c                 S   s   | S )N xr   r   K/home/ubuntu/webapp/venv/lib/python3.10/site-packages/fuzzywuzzy/process.py
no_process?   s   z'extractWithoutOrder.<locals>.no_processNr   zhApplied processor reduces input query to empty string, all comparisons will have score 0. [Query: '{0}']F)force_ascii)full_processT)len	TypeErrorloggingwarningformatr   WRatioQRatiotoken_set_ratiotoken_sort_ratiopartial_token_set_ratiopartial_token_sort_ratioUWRatioUQRatior   r   r   itemsAttributeError)querychoices	processorscorerscore_cutoffr
   processed_querypre_processorkeychoice	processedscorer   r   r	   extractWithoutOrder   sf   /





r'      c                 C   s<   t | |||}|durtj||dd dS t|dd ddS )a  Select the best match in a list or dictionary of choices.

    Find best matches in a list or dictionary of choices, return a
    list of tuples containing the match and its score. If a dictionary
    is used, also returns the key for each match.

    Arguments:
        query: An object representing the thing we want to find.
        choices: An iterable or dictionary-like object containing choices
            to be matched against the query. Dictionary arguments of
            {key: value} pairs will attempt to match the query against
            each value.
        processor: Optional function of the form f(a) -> b, where a is the query or
            individual choice and b is the choice to be used in matching.

            This can be used to match against, say, the first element of
            a list:

            lambda x: x[0]

            Defaults to fuzzywuzzy.utils.full_process().
        scorer: Optional function for scoring matches between the query and
            an individual processed choice. This should be a function
            of the form f(query, choice) -> int.
            By default, fuzz.WRatio() is used and expects both query and
            choice to be strings.
        limit: Optional maximum for the number of elements returned. Defaults
            to 5.

    Returns:
        List of tuples containing the match and its score.

        If a list is used for choices, then the result will be 2-tuples.
        If a dictionary is used, then the result will be 3-tuples containing
        the key for each match.

        For example, searching for 'bird' in the dictionary

        {'bard': 'train', 'dog': 'man'}

        may return

        [('train', 22, 'bard'), ('man', 0, 'dog')]
    Nc                 S      | d S Nr   r   ir   r   r	   <lambda>       zextract.<locals>.<lambda>r#   c                 S   r)   r*   r   r+   r   r   r	   r-      r.   Tr#   reverser'   heapqnlargestsorted)r   r   r   r   limitslr   r   r	   extractz   s   -r8   c                 C   s>   t | ||||}|durtj||dd dS t|dd ddS )a  Get a list of the best matches to a collection of choices.

    Convenience function for getting the choices with best scores.

    Args:
        query: A string to match against
        choices: A list or dictionary of choices, suitable for use with
            extract().
        processor: Optional function for transforming choices before matching.
            See extract().
        scorer: Scoring function for extract().
        score_cutoff: Optional argument for score threshold. No matches with
            a score less than this number will be returned. Defaults to 0.
        limit: Optional maximum for the number of elements returned. Defaults
            to 5.

    Returns: A a list of (match, score) tuples.
    Nc                 S   r)   r*   r   r+   r   r   r	   r-      r.   zextractBests.<locals>.<lambda>r/   c                 S   r)   r*   r   r+   r   r   r	   r-      r.   Tr0   r2   )r   r   r   r   r    r6   	best_listr   r   r	   extractBests   s   r:   c                 C   s8   t | ||||}z	t|dd dW S  ty   Y dS w )a_  Find the single best match above a score in a list of choices.

    This is a convenience method which returns the single best choice.
    See extract() for the full arguments list.

    Args:
        query: A string to match against
        choices: A list or dictionary of choices, suitable for use with
            extract().
        processor: Optional function for transforming choices before matching.
            See extract().
        scorer: Scoring function for extract().
        score_cutoff: Optional argument for score threshold. If the best
            match is found, but it is not greater than this number, then
            return None anyway ("not a good enough match").  Defaults to 0.

    Returns:
        A tuple containing a single match and its score, if a match
        was found that was above score_cutoff. Otherwise, returns None.
    c                 S   r)   r*   r   r+   r   r   r	   r-      r.   zextractOne.<locals>.<lambda>r/   N)r'   max
ValueError)r   r   r   r   r    r9   r   r   r	   
extractOne   s   r=   F   c           
         s   g }| D ]=}t || d|d} fdd|D }t|dkr'||d d  qt|dd d	}t|d
d dd}||d d  qi }|D ]}	d||	< qF| }t|t| kr[| S |S )a  This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify
    and remove duplicates. Specifically, it uses the process.extract to identify duplicates that
    score greater than a user defined threshold. Then, it looks for the longest item in the duplicate list
    since we assume this item contains the most entity information and returns that. It breaks string
    length ties on an alphabetical sort.

    Note: as the threshold DECREASES the number of duplicates that are found INCREASES. This means that the
        returned deduplicated list will likely be shorter. Raise the threshold for fuzzy_dedupe to be less
        sensitive.

    Args:
        contains_dupes: A list of strings that we would like to dedupe.
        threshold: the numerical value (0,100) point at which we expect to find duplicates.
            Defaults to 70 out of 100
        scorer: Optional function for scoring matches between the query and
            an individual processed choice. This should be a function
            of the form f(query, choice) -> int.
            By default, fuzz.token_set_ratio() is used and expects both query and
            choice to be strings.

    Returns:
        A deduplicated list. For example:

            In: contains_dupes = ['Frodo Baggin', 'Frodo Baggins', 'F. Baggins', 'Samwise G.', 'Gandalf', 'Bilbo Baggins']
            In: fuzzy_dedupe(contains_dupes)
            Out: ['Frodo Baggins', 'Samwise G.', 'Bilbo Baggins', 'Gandalf']
        N)r6   r   c                    s   g | ]
}|d   kr|qS )r   r   ).0r   	thresholdr   r	   
<listcomp>  s    zdedupe.<locals>.<listcomp>r   r   c                 S   r)   Nr   r   r   r   r   r	   r-     r.   zdedupe.<locals>.<lambda>r/   c                 S   s   t | d S rC   )r   r   r   r   r	   r-     s    Tr0   )r8   r   appendr5   keys)
contains_dupesrA   r   	extractoritemmatchesfilteredfilter_sortrE   er   r@   r	   dedupe   s    
rM   ) r   r   r3   r   	functoolsr   r   default_scorerr   default_processorr'   r8   r:   r=   r   rM   r   r   r   r	   <module>   s   j2