
    .Ph\                         d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlmZ ddlmZmZmZ ddlmZmZmZmZmZ ddlmZmZmZ dZ d	 Z! G d
 de"          Z#deiZ$d Z%ddZ&d Z' ej(                    Z) G d de          Z* G d de+          Z, G d de+          Z- G d de-          Z. G d de          Z/ G d de/          Z0 G d de          Z1	 d dZ2dS )!zo
A context object for caching a function's return value each time it
is called with the same input arguments.

    N   )hashing)CacheWarningFileSystemStoreBackendStoreBackendBase)filter_argsformat_callformat_signatureget_func_codeget_func_name)Loggerformat_timepformatz# first line:c                    |                      t                    rb|                     d          } t          | d         t	          t                    d                   }d                    | dd                   } nd}| |fS )zUExtract the first line information from the function code
    text if available.
    
r   Nr   )
startswithFIRST_LINE_TEXTsplitintlenjoin)	func_code
first_lines     M/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/joblib/memory.pyextract_first_liner   9   sz     O,, OOD))	1c/&:&:&<&<=>>
IIim,,		
j      c                       e Zd ZdZdS )JobLibCollisionWarningz@Warn that there might be a collision between names of functions.N)__name__
__module____qualname____doc__ r   r   r   r   F   s        JJJJr   r   localc                     t          | t                    s"t          d                    |                     |t	          |t
                    s"t          d                    |                    |t          | <   dS )a  Extend available store backends.

    The Memory, MemorizeResult and MemorizeFunc objects are designed to be
    agnostic to the type of store used behind. By default, the local file
    system is used but this function gives the possibility to extend joblib's
    memory pattern with other types of storage such as cloud storage (S3, GCS,
    OpenStack, HadoopFS, etc) or blob DBs.

    Parameters
    ----------
    backend_name: str
        The name identifying the store backend being registered. For example,
        'local' is used with FileSystemStoreBackend.
    backend: StoreBackendBase subclass
        The name of a class that implements the StoreBackendBase interface.

    z3Store backend name should be a string, '{0}' given.Nz;Store backend should inherit StoreBackendBase, '{0}' given.)
isinstancestr
ValueErrorformat
issubclassr   _STORE_BACKENDS)backend_namebackends     r   register_store_backendr/   M   s    $ lC(( 
AHHVV
 
 	
 j2BCCIPP 
 
 	
 %,OL!!!r   c                 H   |i }t          |t          j                  rt          |          }t          |t                    r|S t          |t                    rd}t
          j                            |          }t          	                                D ]\  }}| |k    r
 |            }|#t          d                    ||                     |                    |||           |S |7t          j        d                    |j        j                  t"                     dS )z7Return the correct store object for the given location.Nz#Unknown location {0} or backend {1}verbosebackend_optionszdInstantiating a backend using a {} as a location is not supported by joblib. Returning None instead.)r'   pathlibPathr(   r   ospath
expanduserr,   items	TypeErrorr*   	configurewarningswarn	__class__r    UserWarning)r.   locationr2   r3   objbackend_keybackend_objs          r   _store_backend_factoryrD   m   s7   (GL)) !x==(,-- 
	Hc	"	" 
7%%h// )8(=(=(?(? 	$ 	$$K+%%!kmm ;5<<XwOO   	hQQQ
		;;A6"+< < 	
 	
 	
 4r   c                 V    t          |           \  }}t          j        j        g ||R  S )z:Build a roughly unique identifier for the cached function.)r   r6   r7   r   )funcmodulesfuncnames      r   _build_func_identifierrI      s1    %d++GX7<++(++++r   c                   ~    e Zd ZdZ	 	 	 	 	 ddZed             Zed             Zed             Zd	 Z	d
 Z
d Zd ZdS )MemorizedResultal  Object representing a cached value.

    Attributes
    ----------
    location: str
        The location of joblib cache. Depends on the store backend used.

    func: function or str
        function whose output is cached. The string case is intended only for
        instantiation based on the output of repr() on another instance.
        (namely eval(repr(memorized_instance)) works).

    argument_hash: str
        hash of the function arguments.

    backend: str
        Type of store backend for reading/writing cache files.
        Default is 'local'.

    mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
        The memmapping mode used when loading from cache numpy arrays. See
        numpy.load for the meaning of the different values.

    verbose: int
        verbosity level (0 means no message).

    timestamp, metadata: string
        for internal use only.
    r%   Nr   c                 0   t          j        |            || _        t          |||          | _        || _        ||| _        n$| j                            | j                  | _        | j                            dd           | _	        || _
        || _        d S )Nr2   duration)r   __init___call_idrD   store_backend	mmap_modemetadataget_metadatagetrN   r2   	timestamp)selfr@   call_idr.   rR   r2   rV   rS   s           r   rO   zMemorizedResult.__init__   s     	3GXwWWW"$DMM .;;DMJJDM))*d;;"r   c                     | j         S N)func_idrW   s    r   rF   zMemorizedResult.func   s
    |r   c                     | j         d         S Nr   rP   r\   s    r   r[   zMemorizedResult.func_id       }Qr   c                     | j         d         S )Nr   r_   r\   s    r   args_idzMemorizedResult.args_id   r`   r   c           	         	 | j                             | j        | j        | j        | j                  S # t          $ rN}t          d                    t          j
        j        | j         j        g| j        R                      }||d}~ww xY w)z$Read value from cache and return it.)rV   rS   r2   zaError while trying to load a MemorizedResult's value. It seems that this folder is corrupted : {}N)rQ   	load_itemrP   rV   rS   r2   r)   KeyErrorr*   r6   r7   r   r@   )rW   excnew_excs      r   rU   zMemorizedResult.get   s    	#%//.	 0     	# 	# 	#>>DfGL!3!<Mt}MMM? ? G s"	#s   14 
BA	BBc                 D    | j                             | j                   dS )zClear value from cacheN)rQ   
clear_itemrP   r\   s    r   clearzMemorizedResult.clear   s!    %%dm44444r   c                 R     dj         | j        j        | j        j        g| j        R  S )Nz*{}(location="{}", func="{}", args_id="{}"))r*   r>   r    rQ   r@   rP   r\   s    r   __repr__zMemorizedResult.__repr__   s9    B;BN#T%7%@
CG=
 
 
 	
r   c                 B    | j                                         }d |d<   |S )NrV   __dict__copyrW   states     r   __getstate__zMemorizedResult.__getstate__  s$    ""$$!kr   )r%   Nr   NN)r    r!   r"   r#   rO   propertyrF   r[   rb   rU   rj   rl   rs   r$   r   r   rK   rK      s         D # # # #0   X     X      X # # #$5 5 5
 
 

    r   rK   c                   :    e Zd ZdZdZd Zd Zd Zd Zd Z	d Z
d	S )
NotMemorizedResultzxClass representing an arbitrary value.

    This class is a replacement for MemorizedResult when there is no cache.
    valuevalidc                 "    || _         d| _        d S )NTrw   )rW   rx   s     r   rO   zNotMemorizedResult.__init__      



r   c                 <    | j         r| j        S t          d          )NzNo value stored.)ry   rx   re   r\   s    r   rU   zNotMemorizedResult.get  s#    : 	/:-...r   c                 "    d| _         d | _        d S NFry   rx   r\   s    r   rj   zNotMemorizedResult.clear  r{   r   c                     | j         r3d                    | j        j        t	          | j                            S | j        j        dz   S )Nz{class_name}({value}))
class_namerx   z with no value)ry   r*   r>   r    r   rx   r\   s    r   rl   zNotMemorizedResult.__repr__!  sP    : 	>*11>2'$*:M:M 2    >*-===r   c                      | j         | j        dS )Nr   r   r\   s    r   rs   zNotMemorizedResult.__getstate__*  s    dj999r   c                 :    |d         | _         |d         | _        d S )Nry   rx   r   rq   s     r   __setstate__zNotMemorizedResult.__setstate__-  s    7^
7^


r   N)r    r!   r"   r#   	__slots__rO   rU   rj   rl   rs   r   r$   r   r   rv   rv     s         
 #I  / / /  > > >: : :$ $ $ $ $r   rv   c                   >    e Zd ZdZd Zd Zd Zd ZddZd Z	d	 Z
d
S )NotMemorizedFunca  No-op object decorating a function.

    This class replaces MemorizedFunc when there is no cache. It provides an
    identical API but does not write anything on disk.

    Attributes
    ----------
    func: callable
        Original undecorated function.
    c                     || _         d S rZ   rF   )rW   rF   s     r   rO   zNotMemorizedFunc.__init__B  s    			r   c                      | j         |i |S rZ   r   rW   argskwargss      r   __call__zNotMemorizedFunc.__call__E  s    ty$)&)))r   c                 6    t           | j        |i |          S rZ   rv   rF   r   s      r   call_and_shelvez NotMemorizedFunc.call_and_shelveH  s!    !)$)T"<V"<"<===r   c                 L    d                     | j        j        | j                  S )Nz{0}(func={1}))r*   r>   r    rF   r\   s    r   rl   zNotMemorizedFunc.__repr__K  s    %%dn&=tyIIIr   Tc                     d S rZ   r$   rW   r=   s     r   rj   zNotMemorizedFunc.clearN  s    r   c                       | j         |i |i fS rZ   r   r   s      r   callzNotMemorizedFunc.callR  s    ty$)&))2--r   c                     dS r~   r$   r   s      r   check_call_in_cachez$NotMemorizedFunc.check_call_in_cacheU  s    ur   NT)r    r!   r"   r#   rO   r   r   rl   rj   r   r   r$   r   r   r   r   5  s        	 	  * * *> > >J J J   . . .    r   r   c                       e Zd Zd ZdS )AsyncNotMemorizedFuncc                 F   K   t           | j        |i | d {V           S rZ   r   r   s      r   r   z%AsyncNotMemorizedFunc.call_and_shelve]  s7      !		4(B6(B(B"B"B"B"B"B"BCCCr   N)r    r!   r"   r   r$   r   r   r   r   \  s(        D D D D Dr   r   c                       e Zd ZdZ	 	 	 	 	 	 	 d dZd Zd Zed	             Zd
 Z	d Z
d Zd Zd Zd Zd Zd!dZd"dZd Zd#dZd Zd Zd$dZd%dZd%dZd&dZd ZdS )'MemorizedFuncaj  Callable object decorating a function for caching its return value
    each time it is called.

    Methods are provided to inspect the cache or clean it.

    Attributes
    ----------
    func: callable
        The original, undecorated, function.

    location: string
        The location of joblib cache. Depends on the store backend used.

    backend: str
        Type of store backend for reading/writing cache files.
        Default is 'local', in which case the location is the path to a
        disk storage.

    ignore: list or None
        List of variable names to ignore when choosing whether to
        recompute.

    mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
        The memmapping mode used when loading from cache
        numpy arrays. See numpy.load for the meaning of the different
        values.

    compress: boolean, or integer
        Whether to zip the stored data on disk. If an integer is
        given, it should be between 1 and 9, and sets the amount
        of compression. Note that compressed arrays cannot be
        read by memmapping.

    verbose: int, optional
        The verbosity flag, controls messages that are issued as
        the function is evaluated.

    cache_validation_callback: callable, optional
        Callable to check if a result in cache is valid or is to be recomputed.
        When the function is called with arguments for which a cache exists,
        the callback is called with the cache entry's metadata as its sole
        argument. If it returns True, the cached result is returned, else the
        cache for these arguments is cleared and the result is recomputed.
    r%   NFr   c
           	         t          j        |            || _        || _        || _        |	| _        t          |          | _        ||ng | _        || _	        t          |||t          ||                    | _        | j         | j                            | j        g           ||nt          j                    | _        	 t!          j        | |           n# t$          $ r Y nw xY wt'          j        |          rTt+          j                                        |          }
|
                    ddd          }
t3          j        dd|
          }
n|j        }
d|
z  | _        d | _        d | _        d S )	NcompressrR   r1   r   z

r   z. zMemoized version of %s)r   rO   rR   r   rF   cache_validation_callbackrI   r[   ignore_verboserD   dictrQ   store_cached_func_codetimerV   	functoolsupdate_wrapper	Exceptioninspect
isfunctionpydocTextDocdocumentreplaceresubr#   _func_code_info_func_code_id)rW   rF   r@   r.   r   rR   r   r2   rV   r   docs              r   rO   zMemorizedFunc.__init__  s    	" 	)B&-d33 & 2ff 4 (iHHH	
 
 
 )55t|nEEE&/&;	$T40000 	 	 	D	d## 	-//**400C++dFA..C&"c**CC ,C/#5#!s   C 
C%$C%c                    |                      d          sdS | j                            |          sdS | j                            |          }| j        1|                     |          s| j                            |           dS dS )a  Check if the function call is cached and valid for given arguments.

        - Compare the function code with the one from the cached function,
        asserting if it has changed.
        - Check if the function call is present in the cache.
        - Call `cache_validation_callback` for user define cache validation.

        Returns True if the function call is in cache and can be used, and
        returns False otherwise.
           
stacklevelFNT)_check_previous_func_coderQ   contains_itemrT   r   ri   rW   rX   rS   s      r   _is_in_cache_and_validz$MemorizedFunc._is_in_cache_and_valid  s     ---;; 	5 !//88 	5 %227;;*6228<< 7 ))'2225tr   c                      | j         |i |}| j        |f}t          | j                  \  }}| j                            | j        g          }|d         }	| j        dk    rkt          j        t          j	                   t          | j        g|R i |\  }}
|                     t          j        d| d|
 d| d|	 d	                     |                     |          r|r|                     |          i fS 	 t!          j                    }|                     |          }| j        d	k    r+|                     t!          j                    |z
  d
           |i fS # t&          $ rU t          | j        g|R i |\  }}
|                     d                    |
t-          j                                         Y nw xY w| j        dk    r|                     d| d| d|	            |                     ||||          S )a  Call wrapped function and cache result, or read cache if available.

        This function returns the wrapped function output or a reference to
        the cached result.

        Arguments:
        ----------

        args, kwargs: list and dict
            input arguments for wrapped function

        shelving: bool
            True when called via the call_and_shelve function.


        Returns
        -------
        output: Output of the wrapped function if shelving is false, or a
            MemorizedResult reference to the value if shelving is true.
        metadata: dict containing the metadata associated with the call.
        r@      )levelz"
                        Querying z( with signature
                        z*.

                        (argument hash z1)

                        The store location is z.
                        r   zcache loaded )contextz*Exception while loading results for {}
 {}
   zComputing func z, argument hash z in location )_get_args_idr[   r   rF   rQ   get_cached_func_infor   loggingbasicConfigINFOr
   infotextwrapdedentr   _get_memorized_resultr   
_load_item_print_durationr   r=   r*   	traceback
format_exc_call)rW   r   r   shelvingrb   rX   _	func_name	func_infor@   	signature
start_timeoutputs                r   _cached_callzMemorizedFunc._cached_call  s   , $$#T4V44<)$TY//9&;;T\NKK	Z(=Bgl3333+DIGGGGGGLAyII"+ "  )0	  08  	 	    &&w// 	 ?11'::B>>!Y[[
11=1$$((	j0/ )    rz!   /	KDKKKFKK9		AHH!9#7#9#9      =2II*) * *W * *'* *   zz'4:::s   ;A!E AF<;F<c                    t          | j        d          rO| j        t          | j        j                  | _        n)t          | j        j                  | j        k    rd | _        | j        t          | j                  | _        | j        S )N__code__)hasattrrF   r   idr   r   r   r\   s    r   func_code_infozMemorizedFunc.func_code_info4  s     49j)) 	,!)%'	(:%;%;""DI&''4+==='+$' $1#;#;D ##r   c                 >    |                      ||d          d         S )a\  Call wrapped function, cache result and return a reference.

        This method returns a reference to the cached result instead of the
        result itself. The reference object is small and picklable, allowing
        to send or store it easily. Call .get() on reference object to get
        result.

        Returns
        -------
        cached_result: MemorizedResult or NotMemorizedResult
            reference to the value returned by the wrapped function. The
            class "NotMemorizedResult" is used when there is no cache
            activated (e.g. location=None in Memory).
        Tr   r   r   r   s      r   r   zMemorizedFunc.call_and_shelveK  s$        v ==a@@r   c                 >    |                      ||d          d         S NFr   r   r   r   s      r   r   zMemorizedFunc.__call__]  s"      v >>qAAr   c                 Z    | j         }| j                                        }d |d<   d |d<   |S )NrV   r   )r   ro   rp   )rW   r   rr   s      r   rs   zMemorizedFunc.__getstate__a  s<      ""$$!k "&or   c                 T    | j          | j        |i |f}|                     |          S )aA  Check if the function call is cached and valid for given arguments.

        Does not call the function or do any work besides function inspection
        and argument hashing.

        - Compare the function code with the one from the cached function,
          asserting if it has changed.
        - Check if the function call is present in the cache.
        - Call `cache_validation_callback` for user define cache validation.

        Returns
        -------
        is_call_in_cache: bool
            Whether or not the function call is in cache and can be used.
        )r[   r   r   rW   r   r   rX   s       r   r   z!MemorizedFunc.check_call_in_cacheq  s7      <!2!2D!CF!C!CD**7333r   c                 p    t          j        t          | j        | j        ||          | j        du          S )z,Return the input parameter hash of a result.N)coerce_mmap)r   hashr   rF   r   rR   r   s      r   r   zMemorizedFunc._get_args_id  s:    |	4;f==d2
 
 
 	
r   c                     t          t          | j        dd                    }t          | j                  t          | j                  |fS )z'Hash a function to key the online cacher   N)r   getattrrF   r   )rW   func_code_hs     r   
_hash_funczMemorizedFunc._hash_func  s:    749j$??@@$)}}d49oo{::r   c                    dt           ||fz  }| j                            | j        g|           t	          | j        d          o| j        j        dk    }|r7|                                 }	 |t          | j        <   dS # t          $ r Y dS w xY wdS )z3Write the function code and the filename to a file.z%s %i
%sr    <lambda>N)
r   rQ   r   r[   r   rF   r    r   _FUNCTION_HASHESr:   )rW   r   r   is_named_callable	func_hashs        r   _write_func_codezMemorizedFunc._write_func_code  s      ?J	"JJ	114<.)LLL DIz**Oty/AZ/O 	  	 ))I.7 +++   	 	s   +A< <
B
	B
   c                    	 | j         t          v r,|                                 }|t          | j                  k    rdS n# t          $ r Y nw xY w| j        \  }}}	 t          | j                            | j        g                    \  }}n.# t          t          f$ r |                     ||           Y dS w xY w||k    rdS t          | j         dd          \  }}	||cxk    rdk    sn |	dk    rV|dk    sd                    |	||          }
n|	}
t          j        t!          d                    |
                    |           ||k    s4|1t"          j                            |          rt          | j         d
          \  }}	t)          |                    d                    }t-          j        |          5 }|                                |dz
  |dz
  |z   dz
           }d	d	d	           n# 1 swxY w Y   d                    |          }|                                |                                k    }n|                    d          }|r,t          j        t!          d|	|||	||fz            |           | j        dk    rGt          | j         d
          \  }}	|                     d                    |	| j                             |                     d           dS )zx
        stacklevel is the depth a which this function is called, to
        issue useful warnings to the user.
        TF)resolv_aliaswin_charactersr   r   z{0} ({1}:{2})z0Cannot detect name collisions for function '{0}'r   N)r   r   r   r   z	<doctest zHPossible name collisions between functions '%s' (%s:%i) and '%s' (%s:%i)r   z-Function {0} (identified by {1}) has changed.)r=   )rF   r   r   r:   r   r   rQ   get_cached_func_coder[   IOErrorOSErrorr   r   r*   r<   r=   r   r6   r7   existsr   r   tokenizeopen	readlinesr   rstripr   r   rj   )rW   r   r   r   source_filer   old_func_codeold_first_liner   r   func_description	num_linesfon_disk_func_codepossible_collisions                  r   r   z'MemorizedFunc._check_previous_func_code  s   
	y,,, !OO--	 0 ;;;4 	 	 	D	 .2-@*	;
	,>"77GG- -)M>> ! 	 	 	!!)Z88855	 I%%4 %IE%
 
 
9 Z----2----j1H1H###2#9#9{J$ $   $- M&FMM(  
 &    ++0Gw~~k** I,TYUKKK9	 5 566	];// 1()&*^a-?)-Ka-OO)%               %'GG,=$>$>!%,,..-2F2F2H2HH #" &1%;%;K%H%H"! *8 &'*%'&	   *   $ =2(GGGLAyII?FFt|   
 	


us3   8= 
A
	A
0B
 
'B54B5=)G22G69G6Tc                     | j         }| j        dk    r|r|                     d|z             | j                            |g           | j        \  }}}|                     ||           dS )zEmpty the function's cache.r   z(Clearing function cache identified by %sN)r[   r   r=   rQ   
clear_pathr   r   )rW   r=   r[   r   r   r   s         r   rj   zMemorizedFunc.clear  s    ,=1II@7JKKK%%	
 	
 	
 $(#6 	1ji44444r   c                 X    | j          | j        |i |f}|                     |||          S )a   Force the execution of the function with the given arguments.

        The output values will be persisted, i.e., the cache will be updated
        with any new values.

        Parameters
        ----------
        *args: arguments
            The arguments.
        **kwargs: keyword arguments
            Keyword arguments.

        Returns
        -------
        output : object
            The output of the function call.
        metadata : dict
            The metadata associated with the call.
        )r[   r   r   r   s       r   r   zMemorizedFunc.call#  s;    ( <!2!2D!CF!C!CD zz'4000r   c                     |                      ||           t          j                    } | j        |i |}|                     ||||||          S rZ   _before_callr   rF   _after_callrW   rX   r   r   r   r   r   s          r   r   zMemorizedFunc._call<  sW    $'''Y[[
D+F++vxTTTr   c                 f    | j         dk    r%t          t          | j        ||                     d S d S r^   )r   printr	   rF   r   s      r   r  zMemorizedFunc._before_callC  s9    =1+div6677777 r   c                 X   | j                             ||| j                   t          j                    |z
  }| j        dk    r|                     |           |                     ||||          }|r|                     ||          |fS | j        |                     ||          }||fS )NrM   r   )	rQ   	dump_itemr   r   r   _persist_inputr   rR   r   )	rW   rX   r   r   r   r   r   rN   rS   s	            r   r  zMemorizedFunc._after_callG  s    $$Wfdm$LLL9;;+=1  ***&&x$GG 	K--gx@@(JJ>% __Wh77Fxr         ?c                 f   t          j                     }t          | j        | j        ||          }t	          d |                                D                       }|||d}	| j                            ||	           t          j                     |z
  }
|
|k    rt          j	        d|
z  d           |	S )a  Save a small summary of the call using json format in the
        output directory.

        output_dir: string
            directory where to write metadata.

        duration: float
            time taken by hashing input arguments, calling the wrapped
            function and persisting its output.

        args, kwargs: list and dict
            input arguments for wrapped function

        this_duration_limit: float
            Max execution time for this function before issuing a warning.
        c              3   >   K   | ]\  }}|t          |          fV  d S rZ   )repr).0kvs      r   	<genexpr>z/MemorizedFunc._persist_input.<locals>.<genexpr>j  s0      II41a1d1gg,IIIIIIr   )rN   
input_argsr   zPersisting input arguments took %.2fs to run.If this happens often in your code, it can cause performance problems (results will be correct in all cases). The reason for this is probably some large input arguments for a wrapped function.   r   )
r   r   rF   r   r   r9   rQ   store_metadatar<   r=   )rW   rN   rX   r   r   this_duration_limitr   argument_dict
input_reprrS   this_durations              r   r  zMemorizedFunc._persist_inputV  s    " Y[[
#DIt{D&IIII=3F3F3H3HIIIII
 !$
 
 	))'8<<<	j0... M4
 7DD     r   c                 N    t          | j        ||| j        | j        dz
            S )Nr   rS   rV   r2   )rK   rQ   rV   r   r   s      r   r   z#MemorizedFunc._get_memorized_result  s4    nMA%
 
 
 	
r   c                 R    | j                             ||| j        | j                  S )Nr%  )rQ   rd   rV   r   r   s      r   r   zMemorizedFunc._load_item  s/    !++h$.$- , 
 
 	
r   r   c           	          t          | j                  \  }}| d| dt          |           }t          t	          ddt          |          z
            dz  |z              d S )N z- r   P   r   )r   rF   r   r  maxr   )rW   rN   r   r   namemsgs         r   r   zMemorizedFunc._print_duration  sj    	**4::::;x#8#8::c!b3s88m%%+c122222r   c                 d    d                     | j        j        | j        | j        j                  S )Nz.{class_name}(func={func}, location={location}))r   rF   r@   )r*   r>   r    rF   rQ   r@   r\   s    r   rl   zMemorizedFunc.__repr__  s6    ?FF~.'0 G 
 
 	
r   )r%   NNFr   NN)r   r   F)r  rZ   )r   )r    r!   r"   r#   rO   r   r   rt   r   r   r   rs   r   r   r   r   r   rj   r   r   r  r  r  r   r   r   rl   r$   r   r   r   r   d  s       + +j "&1" 1" 1" 1"f  <K; K; K;Z $ $ X$,A A A$B B B   4 4 4.
 
 
; ; ;
  0g g g gR5 5 5 51 1 12U U U U8 8 8     0 0 0 0d
 
 
 

 
 
 

3 3 3 3
 
 
 
 
r   r   c                   2     e Zd Zd Zd Z fdZddZ xZS )AsyncMemorizedFuncc                    K   |                      ||d          }t          j        |          r| d {V n|}|d         S r   r   asyncioiscoroutinerW   r   r   outs       r   r   zAsyncMemorizedFunc.__call__  sN      fu==".s33<Ciiiiiii1vr   c                    K   |                      ||d          }t          j        |          r| d {V n|}|d         S )NTr   r   r2  r5  s       r   r   z"AsyncMemorizedFunc.call_and_shelve  sN      ft<<".s33<Ciiiiiii1vr   c                 v   K    t                      j        |i |}t          j        |          r| d {V n|S rZ   )superr   r3  r4  )rW   r   r   r6  r>   s       r   r   zAsyncMemorizedFunc.call  sG      egglD+F++#/44=Syyyyyyy#=r   Fc                    K   |                      ||           t          j                    } | j        |i | d {V }|                     ||||||          S rZ   r  r  s          r   r   zAsyncMemorizedFunc._call  sm      $'''Y[[
 ty$1&11111111vxTTTr   r.  )r    r!   r"   r   r   r   r   __classcell__)r>   s   @r   r0  r0    sr          
  
> > > > >U U U U U U U Ur   r0  c                   Z    e Zd ZdZ	 	 	 	 	 	 ddZ	 	 	 	 	 ddZdd	Zdd
Zd Zd Z	d Z
dS )Memorya  A context object for caching a function's return value each time it
    is called with the same input arguments.

    All values are cached on the filesystem, in a deep directory
    structure.

    Read more in the :ref:`User Guide <memory>`.

    Parameters
    ----------
    location: str, pathlib.Path or None
        The path of the base directory to use as a data store
        or None. If None is given, no caching is done and
        the Memory object is completely transparent. This option
        replaces cachedir since version 0.12.

    backend: str, optional, default='local'
        Type of store backend for reading/writing cache files.
        The 'local' backend is using regular filesystem operations to
        manipulate data (open, mv, etc) in the backend.

    mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
        The memmapping mode used when loading from cache
        numpy arrays. See numpy.load for the meaning of the
        arguments.

    compress: boolean, or integer, optional
        Whether to zip the stored data on disk. If an integer is
        given, it should be between 1 and 9, and sets the amount
        of compression. Note that compressed arrays cannot be
        read by memmapping.

    verbose: int, optional
        Verbosity flag, controls the debug messages that are issued
        as functions are evaluated.

    backend_options: dict, optional
        Contains a dictionary of named parameters used to configure
        the store backend.
    Nr%   Fr   c                    t          j        |            || _        || _        t	          j                    | _        || _        || _        |i }|| _        |r|t          j
        dd           || _        t          |t                    r t          j                            |d          }t#          ||| j        t%          d||d|          | _        d S )Nz&Compressed results cannot be memmappedr   r   joblibr   r1   r$   )r   rO   r   rR   r   rV   r.   r   r3   r<   r=   r@   r'   r(   r6   r7   r   rD   r   rQ   )rW   r@   r.   rR   r   r2   r3   s          r   rO   zMemory.__init__  s     	" " O. 	R	-MBqQQQQ h$$ 	8w||Hh77H3M  !Y :I 	
 
 
r   c                    |"t          |          st          d| d          |t          j        | j        ||||          S | j        -t          j        |          rt          nt          } ||          S || j
        }|du r| j        }t          |t                    r|j        }t          j        |          rt          nt          } ||| j        | j        ||| j        || j        |	  	        S )a  Decorates the given function func to only compute its return
        value for input arguments not cached on disk.

        Parameters
        ----------
        func: callable, optional
            The function to be decorated
        ignore: list of strings
            A list of arguments name to ignore in the hashing
        verbose: integer, optional
            The verbosity mode of the function. By default that
            of the memory object is used.
        mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
            The memmapping mode used when loading from cache
            numpy arrays. See numpy.load for the meaning of the
            arguments. By default that of the memory object is used.
        cache_validation_callback: callable, optional
            Callable to validate whether or not the cache is valid. When
            the cached function is called with arguments for which a cache
            exists, this callable is called with the metadata of the cached
            result as its sole argument. If it returns True, then the
            cached result is returned, else the cache for these arguments
            is cleared and recomputed.

        Returns
        -------
        decorated_func: MemorizedFunc object
            The returned object is a MemorizedFunc object, that is
            callable (behaves like a function), but offers extra
            methods for cache lookup and management. See the
            documentation for :class:`joblib.memory.MemorizedFunc`.
        Nz4cache_validation_callback needs to be callable. Got .)r   rR   r2   r   F)r@   r.   r   rR   r   r2   rV   r   )callabler)   r   partialcacherQ   r3  iscoroutinefunctionr   r   r   rR   r'   r   rF   r0  r.   r   rV   )rW   rF   r   r2   rR   r   clss          r   rD  zMemory.cache  sI   P %0%:
 :
0 404 4 4   < $
#*C    % .t44&%%% 
 3t99?mGIdM** 	9D$+$?$E$EX  =s'L]n&?

 

 

 
	
r   Tc                     |r|                      d           | j        4| j                                         t                                           dS dS )z#Erase the complete cache directory.zFlushing completely the cacheN)r=   rQ   rj   r   r   s     r   rj   zMemory.clearg  s]     	7II5666)$$&&& ""$$$$$ *)r   c                 `    | j         dS |||dS | j                             |||           dS )aO  Remove cache elements to make the cache fit its limits.

        The limitation can impose that the cache size fits in ``bytes_limit``,
        that the number of cache items is no more than ``items_limit``, and
        that all files in cache are not older than ``age_limit``.

        Parameters
        ----------
        bytes_limit: int | str, optional
            Limit in bytes of the size of the cache. By default, the size of
            the cache is unlimited. When reducing the size of the cache,
            ``joblib`` keeps the most recently accessed items first. If a
            str is passed, it is converted to a number of bytes using units
            { K | M | G} for kilo, mega, giga.

        items_limit: int, optional
            Number of items to limit the cache to.  By default, the number of
            items in the cache is unlimited.  When reducing the size of the
            cache, ``joblib`` keeps the most recently accessed items first.

        age_limit: datetime.timedelta, optional
            Maximum age of items to limit the cache to.  When reducing the size
            of the cache, any items last accessed more than the given length of
            time ago are deleted. Example: to remove files older than 5 days,
            use datetime.timedelta(days=5). Negative timedelta are not
            accepted.
        N)rQ   enforce_store_limits)rW   bytes_limititems_limit	age_limits       r   reduce_sizezMemory.reduce_sizet  sJ    8 %F;#69;LF 	//[)TTTTTr   c                 V    | j          ||i |S  |                     |          |i |S )zEval function func with arguments `*args` and `**kwargs`,
        in the context of the memory.

        This method works similarly to the builtin `apply`, except
        that the function is called only if the cache is not
        up to date.

        )rQ   rD  )rW   rF   r   r   s       r   evalzMemory.eval  sC     %4((((tzz$0000r   c                 j    d                     | j        j        | j        d n| j        j                  S )Nz!{class_name}(location={location}))r   r@   )r*   r>   r    rQ   r@   r\   s    r   rl   zMemory.__repr__  s<    299~.*28J8S : 
 
 	
r   c                 B    | j                                         }d|d<   |S )zaWe don't store the timestamp when pickling, to avoid the hash
        depending from it.
        NrV   rn   rq   s     r   rs   zMemory.__getstate__  s&     ""$$!kr   )Nr%   NFr   N)NNNFNr   )NNN)r    r!   r"   r#   rO   rD  rj   rM  rO  rl   rs   r$   r   r   r=  r=    s        ' '^ !
 !
 !
 !
J "&Q
 Q
 Q
 Q
f% % % %%U %U %U %UN1 1 1"
 
 
    r   r=  c           	      H    t          j        | ||||||          fd}|S )zHelper cache_validation_callback to force recompute after a duration.

    Parameters
    ----------
    days, seconds, microseconds, milliseconds, minutes, hours, weeks: numbers
        argument passed to a timedelta.
    )dayssecondsmicrosecondsmillisecondsminuteshoursweeksc                 l    t          j                     | d         z
  }|                                k     S )Nr   )r   total_seconds)rS   computation_agedeltas     r   r   z0expires_after.<locals>.cache_validation_callback  s/    )++(88!4!4!6!666r   )datetime	timedelta)	rS  rT  rU  rV  rW  rX  rY  r   r]  s	           @r   expires_afterr`    sR     !!  E7 7 7 7 7 %$r   )r   N)r   r   r   r   r   r   r   )3r#   r3  r^  r   r   r   r6   r4   r   r   r   r   r   r   r<   weakrefr   r   _store_backendsr   r   r   func_inspectr   r	   r
   r   r   loggerr   r   r   r   r   r?   r   r,   r/   rD   rI   WeakKeyDictionaryr   rK   objectrv   r   r   r   r0  r=  r`  r$   r   r   <module>rg     s[            				   				                        
              1 0 0 0 0 0 0 0 0 0!
! 
! 
!K K K K K[ K K K 23, , ,@( ( ( (V, , , -7,.. a a a a af a a aH$$ $$ $$ $$ $$ $$ $$ $$T! ! ! ! !v ! ! !ND D D D D, D D D@	
 @	
 @	
 @	
 @	
F @	
 @	
 @	
LU U U U U U U U2w w w w wV w w w@ RS% % % % % %r   