
    i-                        d dl mZ d dl mZ ddlZddlmZ ddlmZ ddlm	Z	  ej                  e      Zej                  Zej                  Zd Zej$                  ej$                  ej&                  ej&                  ej(                  ej(                  ej*                  ej*                  ej,                  ej,                  ej.                  ej.                  ej                  ej                  ej0                  ej0                  ej2                  ej                  ej4                  ej0                  i
Zd Zd	 Zeedfd
ZeedfdZeeddfdZ eedfdZ!dej(                  fdZ"y)   )fuzz)utils    N)process)partialc           	          |t         j                  t         j                  t         j                  t         j                  t         j
                  t         j                  t         j                  t         j                  fvr S |t         j                  t         j                  fv}t        t        j                  |       r t        j                  k(  rS  fd}|S )z
    thefuzz runs both the default preprocessing of the function and the preprocessing
    function passed into process.* while rapidfuzz only runs the one passed into
    process.*. This function wraps the processor to mimic this behavior
    )force_asciic                        |             S N )spre_processor	processors    `/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/thefuzz/process.pywrapperz_get_processor.<locals>.wrapper!   s    Yq\**    )r   WRatioQRatiotoken_set_ratiotoken_sort_ratiopartial_token_set_ratiopartial_token_sort_ratioUWRatioUQRatior   r   full_process)r   scorerr	   r   r   s   `   @r   _get_processorr      s     dkk4;;**D,A,A22D4Q4QllDLL2 2 t|| <<KE..KHM	U%7%77+ Nr   c                 <     d fd	}t         j                   |      S )z~
    rapidfuzz scorers require the score_cutoff argument to be available
    This generates a compatible wrapper function
    c                      | |      S r   r   )s1s2score_cutoffr   s      r   r   z_get_scorer.<locals>.wrapper@   s    b"~r   )r   )_scorer_loweringget)r   r   s   ` r   _get_scorerr%   ;   s    
 00r   c                 l    |r ||       n| }t        |      dk(  rt        j                  d|  d       |S )Nr   zcApplied processor reduces input query to empty string, all comparisons will have score 0. [Query: 'z'])len_loggerwarning)queryr   processed_querys      r   _preprocess_queryr,   F   sB    *3i&O
?q  %%*G30 	1 r   c              #     K   t        |d      }|t        v }t        | |      } t        j                  | |t        ||      t        |      |      }|D ])  \  }}	}
|rt        t        |	            }	|r||	|
fn||	f + y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 thefuzz.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')
    itemsr   r   r"   N)	hasattrr#   r,   rprocessextract_iterr   r%   intround)r*   choicesr   r   r"   
is_mapping
is_lowereditchoicescorekeys              r   extractWithoutOrderr<   P   s     ^ '*J++JeY/E			w F36"!	
B ! Fse%E&0vuc"vuoE	Fs   A=A?   c                 "    t        | ||||      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 thefuzz.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')]
    )r   r   limit)extractBests)r*   r5   r   r   r?   s        r   extractrA      s    \ w)FRWXXr   c                    t        |d      }|t        v }t        | |      } t        j                  | |t        ||      t        |      ||      }t        |      D ]-  \  }	\  }
}}|rt        t        |            }|r|
||fn|
|f||	<   / |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.
    r.   )r   r   r"   r?   )
r0   r#   r,   r1   rA   r   r%   	enumerater3   r4   )r*   r5   r   r   r"   r?   r6   r7   resultsir9   r:   r;   s                r   r@   r@      s    ( '*J++JeY/Ew F36"!G $-W#5 MFE3e%E-7feS)fe_
	M Nr   c                     t        |d      }|t        v }t        | |      } t        j                  | |t        ||      t        |      |      }||S |\  }}	}
|rt        t        |	            }	|r||	|
fS ||	fS )ad  
    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.
    r.   r/   )	r0   r#   r,   r1   
extractOner   r%   r3   r4   )r*   r5   r   r   r"   r6   r7   resr9   r:   r;   s              r   rG   rG      s    , '*J++JeY/E


w F36"!	C {
FE3E%L!#-FE3BFE?Br   F   c                     t               }| D ]2  }t        || ||d      }|j                  t        |d       d          4 t	        |      t	        |       k7  rt        |      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 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 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: dedupe(contains_dupes)
            Out: ['Frodo Baggins', 'Samwise G.', 'Bilbo Baggins', 'Gandalf']
    N)r   r"   r?   c                 (    t        | d         | d   fS )Nr   )r'   )xs    r   <lambda>zdedupe.<locals>.<lambda>7  s    AaD	1Q4/@ r   )r;   r   )setr@   addmaxr'   list)contains_dupes	thresholdr   dedupeditemmatchess         r   deduperW     sj    : eG Ft^FQZbfgC%@A!DEF  LC,??4=S^Sr   )# r   r   logging	rapidfuzzrfuzzr   r1   	functoolsr   	getLogger__name__r(   r   default_scorerr   default_processorr   ratiopartial_ratior   r   r   r   r   r   r   r#   r%   r,   r<   rA   r@   rG   rW   r   r   r   <module>rc      sG      # ) 
'

H
%&& > 	JJ++%//511  %"?"?!!5#A#AKKKKLL%,,LL%,, 1 3DNij >FB '8VW .Yb ,=^bckl &R *;>`a )CX &(0D0D "Tr   