
    &eR                       U d Z ddlm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mZmZ 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 ddlmZ ddlmZ ddlmZm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3  ee4          Z5 e$ej6                  Z7e
e	ge8f         Z9de:d<   d&dZ; G d de1          Z< e<            Z=d'dZ> G d  d!e           Z? G d" d#          Z@ G d$ d%e          ZAdS )(z!@st.cache_resource implementation    )annotationsN)	timedelta)AnyCallableTypeVarcastoverload)TTLCache)	TypeAlias)show_deprecation_warning)
get_logger)cache_utils)CacheKeyNotFoundError)	CacheType)CacheCachedFuncInfomake_cached_func_wrapperttl_to_seconds)CachedMessageReplayContextCachedResultElementMsgDataMsgDataMultiCacheResults)HashFuncsDict)gather_metrics)get_script_run_ctx)	CacheStatCacheStatsProvider)asizeofr   ValidateFuncaValidateFunc | Nonebreturnboolc                "    | du r|du p| duo|duS )zTrue if the two validate functions are equal for the purposes of
    determining whether a given function cache needs to be recreated.
    N )r!   r#   s     Llib/python3.11/site-packages/streamlit/runtime/caching/cache_resource_api.py_equal_validate_funcsr)   =   s)     I#!t)I$)H1D=I    c                  0    e Zd ZdZd ZddZddZddZdS )ResourceCachesz#Manages all ResourceCache instancesc                D    t          j                    | _        i | _        d S N)	threadingLock_caches_lock_function_cachesselfs    r(   __init__zResourceCaches.__init__I   s     %N,,:<r*   keystrdisplay_namemax_entriesint | float | Nonettlfloat | timedelta | str | Nonevalidater"   allow_widgetsr%   r$   ResourceCachec           	        |t           j        }t          |          }| j        5  | j                            |          }|9|j        |k    r.|j        |k    r#t          |j	        |          r|cddd           S t                              d|           t          ||||||          }|| j        |<   |cddd           S # 1 swxY w Y   dS )zvReturn the mem cache for the given key.

        If it doesn't exist, create a new one with the given params.
        Nz#Creating new ResourceCache (key=%s))r6   r8   r9   ttl_secondsr=   r>   )mathinfr   r1   r2   getrA   r9   r)   r=   _LOGGERdebugr?   )	r4   r6   r8   r9   r;   r=   r>   rA   caches	            r(   	get_cachezResourceCaches.get_cacheM   sU    (K$S))  	 	)--c22E!%44%44)%.(CC 5 	 	 	 	 	 	 	 	 MM?EEE!)''!+  E */D!#&+	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   A	C;;CC
CNonec                T    | j         5  i | _        ddd           dS # 1 swxY w Y   dS )zClear all resource caches.N)r1   r2   r3   s    r(   	clear_allzResourceCaches.clear_allx   sw     	' 	'$&D!	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	's   !!list[CacheStat]c                    | j         5  | j                                        }d d d            n# 1 swxY w Y   g }|                                D ])}|                    |                                           *|S r.   )r1   r2   copyvaluesextend	get_stats)r4   function_cachesstatsrG   s       r(   rQ   zResourceCaches.get_stats}   s     	; 	; #388::O	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;
 "$$++-- 	, 	,ELL**++++s   .22N)r6   r7   r8   r7   r9   r:   r;   r<   r=   r"   r>   r%   r$   r?   r$   rI   r$   rL   )__name__
__module____qualname____doc__r5   rH   rK   rQ   r'   r*   r(   r,   r,   F   sf        --= = =) ) ) )V' ' ' '
	 	 	 	 	 	r*   r,   r   c                     t           S )z>Return the StatsProvider for all @st.cache_resource functions.)_resource_cachesr'   r*   r(   !get_resource_cache_stats_providerr\      s    r*   c                  x     e Zd ZdZ	 dd fdZedd            Zedd            Zed d            Zd!dZ	 xZ
S )"CachedResourceFuncInfoz>Implements the CachedFuncInfo interface for @st.cache_resourceNfunctypes.FunctionTypeshow_spinner
bool | strr9   
int | Noner;   r<   r=   r"   r>   r%   
hash_funcsHashFuncsDict | Nonec                |    t                                          ||||           || _        || _        || _        d S )N)ra   r>   rd   )superr5   r9   r;   r=   )	r4   r_   ra   r9   r;   r=   r>   rd   	__class__s	           r(   r5   zCachedResourceFuncInfo.__init__   sN     	%'!	 	 	
 	
 	
 ' r*   r$   r   c                    t           j        S r.   )r   RESOURCEr3   s    r(   
cache_typez!CachedResourceFuncInfo.cache_type   s    !!r*   r   c                    t           S r.   )!CACHE_RESOURCE_MESSAGE_REPLAY_CTXr3   s    r(   cached_message_replay_ctxz0CachedResourceFuncInfo.cached_message_replay_ctx   s    00r*   r7   c                8    | j         j         d| j         j         S )z-A human-readable name for the cached function.)r_   rW   rX   r3   s    r(   r8   z#CachedResourceFuncInfo.display_name   s"     )&AA)?AAAr*   function_keyr   c                t    t                               || j        | j        | j        | j        | j                  S )N)r6   r8   r9   r;   r=   r>   )r[   rH   r8   r9   r;   r=   r>   )r4   rq   s     r(   get_function_cachez)CachedResourceFuncInfo.get_function_cache   s>    ))*(], * 
 
 	
r*   r.   )r_   r`   ra   rb   r9   rc   r;   r<   r=   r"   r>   r%   rd   re   )r$   r   )r$   r   )r$   r7   )rq   r7   r$   r   )rV   rW   rX   rY   r5   propertyrk   rn   r8   rs   __classcell__rh   s   @r(   r^   r^      s        HH ,0! ! ! ! ! ! !( " " " X" 1 1 1 X1 B B B XB
 
 
 
 
 
 
 
r*   r^   c                      e Zd ZdZ	 d'd(dZ eded	ef         
          Ze	d)d            Z
e	dddddddd*d            Z
	 d'dddddddd+d Z
dd!d+d"Z ed#          d,d%            Zd& ZdS )-CacheResourceAPIzvImplements the public st.cache_resource API: the @st.cache_resource decorator,
    and st.cache_resource.clear().
    Ndecorator_metric_namer7   deprecation_warning
str | Nonec                H    t          || j                  | _        || _        dS )a  Create a CacheResourceAPI instance.

        Parameters
        ----------
        decorator_metric_name
            The metric name to record for decorator usage. `@st.experimental_singleton` is
            deprecated, but we're still supporting it and tracking its usage separately
            from `@st.cache_resource`.

        deprecation_warning
            An optional deprecation warning to show when the API is accessed.
        N)r   
_decorator_deprecation_warning)r4   ry   rz   s      r(   r5   zCacheResourceAPI.__init__   s&    $ ))>PP$7!!!r*   F.)boundr_   r$   c                    d S r.   r'   )r4   r_   s     r(   __call__zCacheResourceAPI.__call__   s    r*   TFr;   r9   ra   r=   experimental_allow_widgetsrd   r;   r<   r9   rc   ra   rb   r=   r"   r   r%   rd   re   Callable[[F], F]c                   d S r.   r'   )r4   r;   r9   ra   r=   r   rd   s          r(   r   zCacheResourceAPI.__call__   s	     	r*   F | Nonec          	     :    |                      |||||||          S )Nr   )r}   r4   r_   r;   r9   ra   r=   r   rd   s           r(   r   zCacheResourceAPI.__call__   s4     #%'A!  
 
 	
r*   )rd   c                   |                                   |
fdS t          t          t          t          j        |                              S )a  Decorator to cache functions that return global resources (e.g. database connections, ML models).

        Cached objects are shared across all users, sessions, and reruns. They
        must be thread-safe because they can be accessed from multiple threads
        concurrently. If thread safety is an issue, consider using ``st.session_state``
        to store resources per session instead.

        You can clear a function's cache with ``func.clear()`` or clear the entire
        cache with ``st.cache_resource.clear()``.

        To cache data, use ``st.cache_data`` instead. Learn more about caching at
        https://docs.streamlit.io/library/advanced-features/caching.

        Parameters
        ----------
        func : callable
            The function that creates the cached resource. Streamlit hashes the
            function's source code.

        ttl : float, timedelta, str, or None
            The maximum time to keep an entry in the cache. Can be one of:

            * ``None`` if cache entries should never expire (default).
            * A number specifying the time in seconds.
            * A string specifying the time in a format supported by `Pandas's
              Timedelta constructor <https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html>`_,
              e.g. ``"1d"``, ``"1.5 days"``, or ``"1h23s"``.
            * A ``timedelta`` object from `Python's built-in datetime library
              <https://docs.python.org/3/library/datetime.html#timedelta-objects>`_,
              e.g. ``timedelta(days=1)``.

        max_entries : int or None
            The maximum number of entries to keep in the cache, or None
            for an unbounded cache. When a new entry is added to a full cache,
            the oldest cached entry will be removed. Defaults to None.

        show_spinner : bool or str
            Enable the spinner. Default is True to show a spinner when there is
            a "cache miss" and the cached resource is being created. If string,
            value of show_spinner param will be used for spinner text.

        validate : callable or None
            An optional validation function for cached data. ``validate`` is called
            each time the cached value is accessed. It receives the cached value as
            its only parameter and it must return a boolean. If ``validate`` returns
            False, the current cached value is discarded, and the decorated function
            is called to compute a new value. This is useful e.g. to check the
            health of database connections.

        experimental_allow_widgets : bool
            Allow widgets to be used in the cached function. Defaults to False.
            Support for widgets in cached functions is currently experimental.
            Setting this parameter to True may lead to excessive memory use since the
            widget value is treated as an additional input parameter to the cache.
            We may remove support for this option at any time without notice.

        hash_funcs : dict or None
            Mapping of types or fully qualified names to hash functions.
            This is used to override the behavior of the hasher inside Streamlit's
            caching mechanism: when the hasher encounters an object, it will first
            check to see if its type matches a key in this dict and, if so, will use
            the provided function to generate a hash for it. See below for an example
            of how this can be used.

        Example
        -------
        >>> import streamlit as st
        >>>
        >>> @st.cache_resource
        ... def get_database_session(url):
        ...     # Create a database session object that points to the URL.
        ...     return session
        ...
        >>> s1 = get_database_session(SESSION_URL_1)
        >>> # Actually executes the function, since this is the first time it was
        >>> # encountered.
        >>>
        >>> s2 = get_database_session(SESSION_URL_1)
        >>> # Does not execute the function. Instead, returns its previously computed
        >>> # value. This means that now the connection object in s1 is the same as in s2.
        >>>
        >>> s3 = get_database_session(SESSION_URL_2)
        >>> # This is a different URL, so the function executes.

        By default, all parameters to a cache_resource function must be hashable.
        Any parameter whose name begins with ``_`` will not be hashed. You can use
        this as an "escape hatch" for parameters that are not hashable:

        >>> import streamlit as st
        >>>
        >>> @st.cache_resource
        ... def get_database_session(_sessionmaker, url):
        ...     # Create a database connection object that points to the URL.
        ...     return connection
        ...
        >>> s1 = get_database_session(create_sessionmaker(), DATA_URL_1)
        >>> # Actually executes the function, since this is the first time it was
        >>> # encountered.
        >>>
        >>> s2 = get_database_session(create_sessionmaker(), DATA_URL_1)
        >>> # Does not execute the function. Instead, returns its previously computed
        >>> # value - even though the _sessionmaker parameter was different
        >>> # in both calls.

        A cache_resource function's cache can be procedurally cleared:

        >>> import streamlit as st
        >>>
        >>> @st.cache_resource
        ... def get_database_session(_sessionmaker, url):
        ...     # Create a database connection object that points to the URL.
        ...     return connection
        ...
        >>> get_database_session.clear()
        >>> # Clear all cached entries for this function.

        To override the default hashing behavior, pass a custom hash function.
        You can do that by mapping a type (e.g. ``Person``) to a hash
        function (``str``) like this:

        >>> import streamlit as st
        >>> from pydantic import BaseModel
        >>>
        >>> class Person(BaseModel):
        ...     name: str
        >>>
        >>> @st.cache_resource(hash_funcs={Person: str})
        ... def get_person_name(person: Person):
        ...     return person.name

        Alternatively, you can map the type's fully-qualified name
        (e.g. ``"__main__.Person"``) to the hash function instead:

        >>> import streamlit as st
        >>> from pydantic import BaseModel
        >>>
        >>> class Person(BaseModel):
        ...     name: str
        >>>
        >>> @st.cache_resource(hash_funcs={"__main__.Person": str})
        ... def get_person_name(person: Person):
        ...     return person.name
        Nc                J    t          t          |                     S )Nr_   ra   r9   r;   r=   r>   rd   )r   r^   )fr   rd   r9   ra   r;   r=   s    r(   <lambda>z-CacheResourceAPI._decorator.<locals>.<lambda>  s9    5&!- +%"<)  
 
 r*   r   )_maybe_show_deprecation_warningr   r^   r   typesFunctionTyper   s     ``````r(   r}   zCacheResourceAPI._decorator  s    t 	,,... <
 
 
 
 
 
 
 
 
 
 ("%,d33)'!8%  

 

 
	
r*   clear_resource_cachesrI   c                `    |                                   t                                           dS )z Clear all cache_resource caches.N)r   r[   rK   r3   s    r(   clearzCacheResourceAPI.clear  s.     	,,...""$$$$$r*   c                @    | j         t          | j                    dS dS )zIf the API is being accessed with the deprecated `st.experimental_singleton` name,
        show a deprecation warning.
        N)r~   r   r3   s    r(   r   z0CacheResourceAPI._maybe_show_deprecation_warning  s,     $0$T%>????? 10r*   r.   )ry   r7   rz   r{   )r_   r   r$   r   )r;   r<   r9   rc   ra   rb   r=   r"   r   r%   rd   re   r$   r   )r_   r   r;   r<   r9   rc   ra   rb   r=   r"   r   r%   rd   re   rT   )rV   rW   rX   rY   r5   r   r   r   r   r	   r   r}   r   r   r   r'   r*   r(   rx   rx      sa        
 MQ8 8 8 8 80 	8CH-...A    X  /3"&#'(,+0+/
 
 
 
 
 X
 
 /3"&#'(,+0+/
 
 
 
 
 
< ,0u
 u
 u
 u
 u
 u
n ^+,,% % % -,%
@ @ @ @ @r*   rx   c                       e Zd ZdZd fdZedd            Zedd            ZddZ e	d          dd            Z
d dZd!dZ xZS )"r?   z>Manages cached values for a single st.cache_resource function.r6   r7   r9   floatrA   r=   r"   r8   r>   r%   c                    t                                                       || _        || _        t	          ||t
          j                  | _        t          j	                    | _
        || _        || _        d S )N)maxsizer;   timer)rg   r5   r6   r8   r
   r   TTLCACHE_TIMER
_mem_cacher/   r0   _mem_cache_lockr=   r>   )r4   r6   r9   rA   r=   r8   r>   rh   s          r(   r5   zResourceCache.__init__  sq     	(<D[8R=
 =
 =
  )~// *r*   r$   c                @    t          t          | j        j                  S r.   )r   r   r   r   r3   s    r(   r9   zResourceCache.max_entries  s    E4?2333r*   c                @    t          t          | j        j                  S r.   )r   r   r   r;   r3   s    r(   rA   zResourceCache.ttl_seconds  s    E4?.///r*   r   c                   | j         5  || j        vrt                      | j        |         }t                      }|st                      |                    |t
          j                  }||j        vrt                      |j        |         }| j        0|                     |j	                  s|j        |= t                      |cddd           S # 1 swxY w Y   dS )zRead a value and associated messages from the cache.
        Raise `CacheKeyNotFoundError` if the value doesn't exist.
        N)
r   r   r   r   get_current_widget_keyr   rj   resultsr=   value)r4   r6   multi_resultsctx
widget_keyresults         r(   read_resultzResourceCache.read_result  s+    ! 	 	$/))+---/3s/CM$&&C .+---&==c9CUVVJ!666 ,---"*:6F}(v|1L1L(!)*5+---3	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   B?CCC_cache_resource_objectr   r   messageslist[MsgData]rI   c                   t                      }|dS t          j        j        }t          j        j        }| j        rd |D             }nt                      }| j        5  	 | j        |         }n!# t          $ r t          |i           }Y nw xY w|j                            |           |                    |t          j                  }	t!          ||||          }
|
|j        |	<   || j        |<   ddd           dS # 1 swxY w Y   dS )z3Write a value and associated messages to the cache.Nc                ^    h | ]*}t          |t                    r|j        |j        j        +S r.   )
isinstancer   widget_metadata	widget_id).0msgs     r(   	<setcomp>z-ResourceCache.write_result.<locals>.<setcomp>  sE       c>22 8;7J7V #-7V7V7Vr*   )
widget_idsr   )r   st_mainidsidebarr>   setr   r   KeyErrorr   r   updater   r   rj   r   r   )r4   r6   r   r   r   main_id
sidebar_idwidgetsr   r   r   s              r(   write_resultzResourceCache.write_result
  st    !"";F(+Z]
 	 #  GG eeG! 	1 	1R $ 4 R R R 1Wb Q Q QR $++G444&==c9CUVVJ!%7JGGF06M!*-#0DOC 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1s7   C< A.-C<.B	C<BA#C<<D D c                x    | j         5  | j                                         d d d            d S # 1 swxY w Y   d S r.   )r   r   r   r3   s    r(   _clearzResourceCache._clear)  s    ! 	$ 	$O!!###	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$s   /33rL   c                      j         5  t           j                                                  }d d d            n# 1 swxY w Y    fd|D             S )Nc           	     X    g | ]&}t          d j        t          |                    'S )st_cache_resource)category_name
cache_namebyte_length)r   r8   r   )r   entryr4   s     r(   
<listcomp>z+ResourceCache.get_stats.<locals>.<listcomp>4  sL     
 
 
  1,#ENN  
 
 
r*   )r   listr   rO   )r4   cache_entriess   ` r(   rQ   zResourceCache.get_stats-  s     ! 	; 	; !7!7!9!9::M	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;
 
 
 
 '
 
 
 	
s   '<A A )r6   r7   r9   r   rA   r   r=   r"   r8   r7   r>   r%   )r$   r   )r6   r7   r$   r   )r6   r7   r   r   r   r   r$   rI   rT   rU   )rV   rW   rX   rY   r5   rt   r9   rA   r   r   r   r   rQ   ru   rv   s   @r(   r?   r?     s        HH+ + + + + +& 4 4 4 X4 0 0 0 X0   > ^,--1 1 1 .-1<$ $ $ $
 
 
 
 
 
 
 
r*   r?   )r!   r"   r#   r"   r$   r%   )r$   r   )BrY   
__future__r   rB   r/   r   datetimer   typingr   r   r   r   r	   
cachetoolsr
   typing_extensionsr   	streamlitr   streamlit.deprecation_utilr   streamlit.loggerr   streamlit.runtime.cachingr   &streamlit.runtime.caching.cache_errorsr   $streamlit.runtime.caching.cache_typer   %streamlit.runtime.caching.cache_utilsr   r   r   r   /streamlit.runtime.caching.cached_message_replayr   r   r   r   r   !streamlit.runtime.caching.hashingr   streamlit.runtime.metrics_utilr   1streamlit.runtime.scriptrunner.script_run_contextr   streamlit.runtime.statsr   r    streamlit.vendor.pympler.asizeofr   rV   rE   rj   rm   r%   r    __annotations__r)   r,   r[   r\   r^   rx   r?   r'   r*   r(   <module>r      s=   ( ' ' " " " " " "             9 9 9 9 9 9 9 9 9 9 9 9 9 9       ' ' ' ' ' '     ? ? ? ? ? ? ' ' ' ' ' ' 1 1 1 1 1 1 H H H H H H : : : : : :                         < ; ; ; ; ; 9 9 9 9 9 9 P P P P P P A A A A A A A A 4 4 4 4 4 4
*X

 %?$>y?Q$R$R !"C5$;/ / / / /J J J J@ @ @ @ @' @ @ @H ">##    
,
 ,
 ,
 ,
 ,
^ ,
 ,
 ,
^I@ I@ I@ I@ I@ I@ I@ I@Xn
 n
 n
 n
 n
E n
 n
 n
 n
 n
r*   