
    gp\                       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mZm	Z	m
Z
mZmZmZmZ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m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& ddl'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8 erddl9m:Z: ddl;m<Z<  ee=      Z>de?d<    e#ej                        ZAeed   df   ZBde?d<    G d de       ZC G d de5      ZD eD       ZEd#dZF G d d       ZG G d! d"e      ZHy)$z$@st.cache_data: pickle-based caching    )annotationsN)	TYPE_CHECKINGAnyCallableFinalLiteralTypeVarUnioncastoverload)	TypeAlias)runtime)StreamlitAPIException)
get_logger)
CacheErrorCacheKeyNotFoundError)	CacheType)CacheCachedFuncInfomake_cached_func_wrapper)CachedMessageReplayContextCachedResultMsgDatashow_widget_replay_deprecation)CacheStorageCacheStorageContextCacheStorageErrorCacheStorageKeyNotFoundErrorCacheStorageManager)InvalidCacheStorageContext)MemoryCacheStorageManager)gather_metrics)	CacheStatCacheStatsProvidergroup_stats)time_to_seconds)	timedelta)HashFuncsDictr   _LOGGERdiskr   CachePersistTypec                       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	ddZ
 xZS )CachedDataFuncInfoz:Implements the CachedFuncInfo interface for @st.cache_datac                t    t         |   |||       || _        || _        || _        | j                          y )N)show_spinner
hash_funcs)super__init__persistmax_entriesttlvalidate_params)selffuncr/   r3   r4   r5   r0   	__class__s          ]/var/www/openai/venv/lib/python3.12/site-packages/streamlit/runtime/caching/cache_data_api.pyr2   zCachedDataFuncInfo.__init__V   sD     	%! 	 	

 &    c                "    t         j                  S N)r   DATAr7   s    r:   
cache_typezCachedDataFuncInfo.cache_typej   s    ~~r;   c                    t         S r=   )CACHE_DATA_MESSAGE_REPLAY_CTXr?   s    r:   cached_message_replay_ctxz,CachedDataFuncInfo.cached_message_replay_ctxn   s    ,,r;   c                `    | j                   j                   d| j                   j                   S )z-A human-readable name for the cached function.)r8   
__module____qualname__r?   s    r:   display_namezCachedDataFuncInfo.display_namer   s+     ))&&'q)?)?(@AAr;   c                    t         j                  || j                  | j                  | j                  | j
                        S )N)keyr3   r4   r5   rH   )_data_caches	get_cacher3   r4   r5   rH   )r7   function_keys     r:   get_function_cachez%CachedDataFuncInfo.get_function_cachew   s=    %%LL((** & 
 	
r;   c                    t         j                  | j                  j                  | j                  | j
                  | j                         y)z
        Validate the params passed to @st.cache_data are compatible with cache storage

        When called, this method could log warnings if cache params are invalid
        for current storage.
        )function_namer3   r4   r5   N)rK   validate_cache_paramsr8   __name__r3   r4   r5   r?   s    r:   r6   z"CachedDataFuncInfo.validate_params   s;     	**)),,LL((	 	+ 	
r;   r=   )r8   ztypes.FunctionTyper/   
bool | strr3   r+   r4   
int | Noner5   float | timedelta | str | Noner0   HashFuncsDict | None)returnr   )rW   r   )rW   str)rM   rX   rW   r   rW   None)rR   rF   rG   __doc__r2   propertyr@   rC   rH   rN   r6   __classcell__r9   s   @r:   r-   r-   S   s    D ,0  ! "	
   , )(   - - B B

r;   r-   c                      e Zd ZdZd Z	 	 	 	 	 	 	 	 	 	 	 	 d
dZddZddZ	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 	 	 ddZ	ddZ
y	)
DataCacheszManages all DataCache instancesc                D    t        j                         | _        i | _        y r=   )	threadingLock_caches_lock_function_cachesr?   s    r:   r2   zDataCaches.__init__   s    %NN,68r;   c           	     X   t        |d      }| j                  5  | j                  j                  |      }|8|j                  |k(  r)|j
                  |k(  r|j                  |k(  r|cddd       S |3t        j                  d||||       |j                  j                          t        j                  d||||       | j                  |||||      }| j                         }	|	j                  |      }
t        ||
||||      }|| j                  |<   |cddd       S # 1 sw Y   yxY w)zvReturn the mem cache for the given key.

        If it doesn't exist, create a new one with the given params.
        Fcoerce_none_to_infNz}Closing existing DataCache storage (key=%s, persist=%s, max_entries=%s, ttl=%s) before creating new one with different paramszCCreating new DataCache (key=%s, persist=%s, max_entries=%s, ttl=%s)rM   rP   ttl_secondsr4   r3   )rJ   storager3   r4   rj   rH   )r&   rd   re   getrj   r4   r3   r)   debugrk   closecreate_cache_storage_contextget_storage_managercreate	DataCache)r7   rJ   r3   r4   r5   rH   rj   cachecache_contextcache_storage_managerrk   s              r:   rL   zDataCaches.get_cache   sF    &ceD ))--c2E!%%4%%4MMW,   D  ##% MMU !== *'' > M %)$<$<$>!+22=AG'')E */D!!#&g s   AD 0B&D  D)c                B   | j                   5  	 | j                         j                          i | _        ddd       y# t        $ rL | j                  j                         D ],  }|j                          |j                  j                          . Y dw xY w# 1 sw Y   yxY w)z'Clear all in-memory and on-disk caches.N)	rd   rp   	clear_allNotImplementedErrorre   valuesclearrk   rn   )r7   
data_caches     r:   rw   zDataCaches.clear_all   s    	/
 ((*446
 %'D!  ' /"&"7"7">">"@J$$&&&,,. #A/ s,   B=BABBBBBc                    | j                   5  | j                  j                         }d d d        g }j                         D ]!  }|j	                  |j                                # t        |      S # 1 sw Y   JxY wr=   )rd   re   copyry   extend	get_statsr%   )r7   function_cachesstatsrs   s       r:   r   zDataCaches.get_stats   sg     #3388:O 
 "$$++-ELL*+ .5!! s   A11A:c                    t        |d      }| j                  d||||      }	 | j                         j                  |       y# t        $ r}t
        j                  d||        d}~ww xY w)zValidate that the cache params are valid for given storage.

        Raises
        ------
        InvalidCacheStorageContext
            Raised if the cache storage manager is not able to work with provided
            CacheStorageContext.
        Frg   	DUMMY_KEYri   zQCache params for function %s are incompatible with current cache storage manager.)exc_infoN)r&   ro   rp   check_contextr    r)   error)r7   rP   r3   r4   r5   rj   rt   es           r:   rQ   z DataCaches.validate_cache_params   s      &ceD99$'## : 
		$$&44]C) 	MM)	   	s   A 	A,A''A,c                "    t        |||||      S )N)rM   function_display_namerj   r4   r3   )r   )r7   rM   rP   r3   rj   r4   s         r:   ro   z'DataCaches.create_cache_storage_context  s      #%"/##
 	
r;   c                    t        j                         rt        j                         j                  S t        j                  d       t               S )Nz1No runtime found, using MemoryCacheStorageManager)r   existsget_instanceru   r)   warningr!   r?   s    r:   rp   zDataCaches.get_storage_manager*  s9    >>'')??? OOOP,..r;   N)rJ   rX   r3   r+   r4   rT   r5   $int | float | timedelta | str | NonerH   rX   rW   rr   rY   rW   zlist[CacheStat])
rP   rX   r3   r+   r4   rT   r5   r   rW   rZ   )rM   rX   rP   rX   r3   r+   rj   float | Noner4   rT   rW   r   )rW   r   )rR   rF   rG   r[   r2   rL   rw   r   rQ   ro   rp    r;   r:   r`   r`      s    )9DD "D  	D
 2D D 
DL'	""" ""  	"
 2" 
"H

 
 "	

 "
  
 

 /r;   r`   c                     t         S )z:Return the StatsProvider for all @st.cache_data functions.)rK   r   r;   r:   get_data_cache_stats_providerr   8  s    r;   c                     e Zd ZdZ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dZ ed      dd       Zy)CacheDataAPIzjImplements the public st.cache_data API: the @st.cache_data decorator, and
    st.cache_data.clear().
    c                :    t        || j                        | _        y)zCreate a CacheDataAPI instance.

        Parameters
        ----------
        decorator_metric_name
            The metric name to record for decorator usage.
        N)r"   
_decorator)r7   decorator_metric_names     r:   r2   zCacheDataAPI.__init__B  s     )!4??
r;   F.)boundc                     y r=   r   )r7   r8   s     r:   __call__zCacheDataAPI.__call__V  s    &)r;   NTF)r5   r4   r/   r3   experimental_allow_widgetsr0   c                    y r=   r   )r7   r5   r4   r/   r3   r   r0   s          r:   r   zCacheDataAPI.__call__Z  s     r;   c          	     2    | j                  |||||||      S )N)r5   r4   r3   r/   r   r0   )r   )r7   r8   r5   r4   r/   r3   r   r0   s           r:   r   zCacheDataAPI.__call__f  s/     #%'A!  
 	
r;   )r0   c          
        	 |du rd	n	|du rd	n|		dvrt        d| d      |rt        d       	fd	}||S t        t        t	        t
        j                  |      	
            S )a]  Decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).

        Cached objects are stored in "pickled" form, which means that the return
        value of a cached function must be pickleable. Each caller of the cached
        function gets its own copy of the cached data.

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

        A function's arguments must be hashable to cache it. If you have an
        unhashable argument (like a database connection) or an argument you
        want to exclude from caching, use an underscore prefix in the argument
        name. In this case, Streamlit will return a cached value when all other
        arguments match a previous function call. Alternatively, you can
        declare custom hashing functions with ``hash_funcs``.

        To cache global resources, use ``st.cache_resource`` instead. Learn more
        about caching at https://docs.streamlit.io/develop/concepts/architecture/caching.

        Parameters
        ----------
        func : callable
            The function to cache. 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)``.

            Note that ``ttl`` will be ignored if ``persist="disk"`` or ``persist=True``.

        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 data is being created. If string,
            value of show_spinner param will be used for spinner text.

        persist : "disk", bool, or None
            Optional location to persist cached data to. Passing "disk" (or True)
            will persist the cached data to the local disk. None (or False) will disable
            persistence. The default is None.

        experimental_allow_widgets : bool
            Allow widgets to be used in the cached function. Defaults to False.

        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.

        .. deprecated::
            The cached widget replay functionality was removed in 1.38. Please
            remove the ``experimental_allow_widgets`` parameter from your
            caching decorators. This parameter will be removed in a future
            version.

        Example
        -------
        >>> import streamlit as st
        >>>
        >>> @st.cache_data
        ... def fetch_and_clean_data(url):
        ...     # Fetch data from URL here, and then clean it up.
        ...     return data
        >>>
        >>> d1 = fetch_and_clean_data(DATA_URL_1)
        >>> # Actually executes the function, since this is the first time it was
        >>> # encountered.
        >>>
        >>> d2 = fetch_and_clean_data(DATA_URL_1)
        >>> # Does not execute the function. Instead, returns its previously computed
        >>> # value. This means that now the data in d1 is the same as in d2.
        >>>
        >>> d3 = fetch_and_clean_data(DATA_URL_2)
        >>> # This is a different URL, so the function executes.

        To set the ``persist`` parameter, use this command as follows:

        >>> import streamlit as st
        >>>
        >>> @st.cache_data(persist="disk")
        ... def fetch_and_clean_data(url):
        ...     # Fetch data from URL here, and then clean it up.
        ...     return data

        By default, all parameters to a cached 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_data
        ... def fetch_and_clean_data(_db_connection, num_rows):
        ...     # Fetch data from _db_connection here, and then clean it up.
        ...     return data
        >>>
        >>> connection = make_database_connection()
        >>> d1 = fetch_and_clean_data(connection, num_rows=10)
        >>> # Actually executes the function, since this is the first time it was
        >>> # encountered.
        >>>
        >>> another_connection = make_database_connection()
        >>> d2 = fetch_and_clean_data(another_connection, num_rows=10)
        >>> # Does not execute the function. Instead, returns its previously computed
        >>> # value - even though the _database_connection parameter was different
        >>> # in both calls.

        A cached function's cache can be procedurally cleared:

        >>> import streamlit as st
        >>>
        >>> @st.cache_data
        ... def fetch_and_clean_data(_db_connection, num_rows):
        ...     # Fetch data from _db_connection here, and then clean it up.
        ...     return data
        >>>
        >>> fetch_and_clean_data.clear(_db_connection, 50)
        >>> # Clear the cached entry for the arguments provided.
        >>>
        >>> fetch_and_clean_data.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. ``datetime.datetime``) to a hash
        function (``lambda dt: dt.isoformat()``) like this:

        >>> import streamlit as st
        >>> import datetime
        >>>
        >>> @st.cache_data(hash_funcs={datetime.datetime: lambda dt: dt.isoformat()})
        ... def convert_to_utc(dt: datetime.datetime):
        ...     return dt.astimezone(datetime.timezone.utc)

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

        >>> import streamlit as st
        >>> import datetime
        >>>
        >>> @st.cache_data(hash_funcs={"datetime.datetime": lambda dt: dt.isoformat()})
        ... def convert_to_utc(dt: datetime.datetime):
        ...     return dt.astimezone(datetime.timezone.utc)

        Tr*   FN)Nr*   zUnsupported persist option 'z#'. Valid values are 'disk' or None.
cache_datac           
     8    t        t        |             S )Nr8   r3   r/   r4   r5   r0   )r   r-   )fr0   r4   persist_stringr/   r5   s    r:   wrapperz(CacheDataAPI._decorator.<locals>.wrapper7  s*    +"*!- +)	 	r;   r   )r   r   r   r-   r   typesFunctionType)
r7   r8   r5   r4   r/   r3   r   r0   r   r   s
     ```  ` @r:   r   zCacheDataAPI._decorator{  s    X d?#N!N$N/'.wi7Z[  &*<8
	 
	 <N'%,,d3&)'%	
 		
r;   clear_data_cachesc                ,    t         j                          y)z,Clear all in-memory and on-disk data caches.N)rK   rw   r?   s    r:   rz   zCacheDataAPI.clearQ  s     	 r;   )r   rX   )r8   r   rW   r   )r5   rU   r4   rT   r/   rS   r3   CachePersistType | boolr   boolr0   rV   rW   zCallable[[F], F]r=   )r8   zF | Noner5   rU   r4   rT   r/   rS   r3   r   r   r   r0   rV   rY   )rR   rF   rG   r[   r2   r	   r   r   r   r   r   r   r"   rz   r   r;   r:   r   r   =  s   
" 	8CH-.A ) )  /3"&#'+/+0+/	 ,	  		
 !	 )	 %)	 )	 
	 	 
 /3"&#'+/+0+/

 ,	

  
 !
 )
 %)
 )
. T
 ,0T
T
 ,	T

  T
 !T
 )T
 %)T
 )T
l '(! )!r;   r   c                  t     e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 d fdZd	dZd
dZ ed      dd       ZdddZ	 xZ
S )rr   z:Manages cached values for a single st.cache_data function.c                v    t         |           || _        || _        || _        || _        || _        || _        y r=   )r1   r2   rJ   rH   rk   rj   r4   r3   )r7   rJ   rk   r3   r4   rj   rH   r9   s          r:   r2   zDataCache.__init__Z  s=     	(&&r;   c                n    t        | j                  t              r| j                  j                         S g S r=   )
isinstancerk   r$   r   r?   s    r:   r   zDataCache.get_statsk  s)    dll$67<<))++	r;   c                   	 | j                   j                  |      }	 t        j                  |      }t        |t              s%| j                   j                  |       t               |S # t        $ r}t        t	        |            |d}~wt
        $ r}t        t	        |            |d}~ww xY w# t        j                  $ r}t        d|       |d}~ww xY w)zRead a value and messages from the cache. Raise `CacheKeyNotFoundError`
        if the value doesn't exist, and `CacheError` if the value exists but can't
        be unpickled.
        NzFailed to unpickle )rk   rl   r   r   rX   r   r   pickleloadsr   r   deleteUnpicklingError)r7   rJ   pickled_entryr   entryexcs         r:   read_resultzDataCache.read_resultp  s    
	, LL,,S1M		CLL/Ee\2 ##C(+--L , 	7'A/Q6  	,SV$!+	, %% 	C23%89sB	Cs;   A* AB1 *	B.3BB.B))B.1CCC_cache_data_objectc                L   	 t         j                  j                  }t         j                  j                  }t	        ||||      }t        j                  |      }| j                  j                  ||       y# t
        j                  t        f$ r}t        d|       |d}~ww xY w)zbWrite a value and associated messages to the cache.
        The value must be pickleable.
        zFailed to pickle N)st_mainidsidebarr   r   dumpsPicklingError	TypeErrorr   rk   set)	r7   rJ   valuemessagesmain_id
sidebar_idr   r   r   s	            r:   write_resultzDataCache.write_result  s    
	AhhkkGJ ':FE"LL/M 	m, $$i0 	A067S@	As   AA6 6B#BB#c                t    |s| j                   j                          y | j                   j                  |       y r=   )rk   rz   r   )r7   rJ   s     r:   _clearzDataCache._clear  s'    LL LL$r;   )rJ   rX   rk   r   r3   r+   r4   rT   rj   r   rH   rX   r   )rJ   rX   rW   r   )rJ   rX   r   r   r   zlist[MsgData]rW   rZ   r=   )rJ   z
str | NonerW   rZ   )rR   rF   rG   r[   r2   r   r   r"   r   r   r]   r^   s   @r:   rr   rr   W  st    D  "	
   " "
C. ()- *-% %r;   rr   )rW   r$   )Ir[   
__future__r   r   rb   r   typingr   r   r   r   r   r	   r
   r   r   typing_extensionsr   	streamlitr   r   streamlit.errorsr   streamlit.loggerr   &streamlit.runtime.caching.cache_errorsr   r   $streamlit.runtime.caching.cache_typer   %streamlit.runtime.caching.cache_utilsr   r   r   /streamlit.runtime.caching.cached_message_replayr   r   r   r   !streamlit.runtime.caching.storager   r   r   r   r   8streamlit.runtime.caching.storage.cache_storage_protocolr    5streamlit.runtime.caching.storage.dummy_cache_storager!   streamlit.runtime.metrics_utilr"   streamlit.runtime.statsr#   r$   r%   streamlit.time_utilr&   datetimer'   !streamlit.runtime.caching.hashingr(   rR   r)   __annotations__r>   rB   r+   r-   r`   rK   r   r   rr   r   r;   r:   <module>r      s    + "   
 
 
 (   2 ' T : 
   : N N /"?H% % :9>> J  $GFOT$9: ) :9
 9
xb/# b/L |
W! W!tB% B%r;   