o
    ,&]ixQ                     @  s  U d Z ddlm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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mZmZm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z, erddl-m.Z. ddl/m0Z0 ee1Z2de3d< e"ej4Z5ee	ge6f Z7de3d< d+ddZ8G dd de)Z9e9 Z:d,d!d"Z;ed#Z<ed$Z=G d%d& d&ee<e=f Z>G d'd( d(Z?G d)d* d*ee= Z@dS )-z"@st.cache_resource implementation.    )annotationsN)Callable)TYPE_CHECKINGAnyFinal	TypeAliasTypeVaroverload)TTLCache)	ParamSpec)
get_logger)cache_utils)CacheKeyNotFoundError)	CacheType)Cache
CachedFuncCachedFuncInfomake_cached_func_wrapper)CachedMessageReplayContextCachedResultMsgData)gather_metrics)	CacheStatCacheStatsProvidergroup_stats)time_to_seconds)	timedelta)HashFuncsDictr   _LOGGERr   ValidateFuncaValidateFunc | Nonebreturnboolc                 C  s    | 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"   r%   r%   j/var/www/html/IGF-ODF-V3/venv/lib/python3.10/site-packages/streamlit/runtime/caching/cache_resource_api.py_equal_validate_funcsD   s    r'   c                   @  s8   e Zd ZdZdddZdddZdddZdddZdS )ResourceCachesz$Manages all ResourceCache instances.r#   Nonec                 C  s   t  | _i | _d S N)	threadingLock_caches_lock_function_cachesselfr%   r%   r&   __init__P   s   

zResourceCaches.__init__keystrdisplay_namemax_entriesint | float | Nonettlfloat | timedelta | str | Nonevalidater!   ResourceCache[Any]c                 C  s   |du rt j}t|}| jA | j|}|dur2|j|kr2|j|kr2t|j	|r2|W  d   S t
d| t|||||d}|| j|< |W  d   S 1 sRw   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))r2   r4   r5   ttl_secondsr9   )mathinfr   r-   r.   getr;   r5   r'   r9   r   debugResourceCache)r0   r2   r4   r5   r7   r9   r;   cacher%   r%   r&   	get_cacheT   s.   



$zResourceCaches.get_cachec                 C  s2   | j  i | _W d   dS 1 sw   Y  dS )zClear all resource caches.N)r-   r.   r/   r%   r%   r&   	clear_all}   s   "zResourceCaches.clear_alllist[CacheStat]c                 C  sX   | j  | j }W d    n1 sw   Y  g }| D ]	}||  qt|S r*   )r-   r.   copyvaluesextend	get_statsr   )r0   function_cachesstatsrA   r%   r%   r&   rH      s   zResourceCaches.get_statsNr#   r)   )r2   r3   r4   r3   r5   r6   r7   r8   r9   r!   r#   r:   r#   rD   )__name__
__module____qualname____doc__r1   rB   rC   rH   r%   r%   r%   r&   r(   M   s    


)r(   r   c                   C     t S )z>Return the StatsProvider for all @st.cache_resource functions.)_resource_cachesr%   r%   r%   r&   !get_resource_cache_stats_provider      rS   PRc                      s\   e Zd ZdZ		d#d$ fddZed%ddZed&ddZed'ddZd(d!d"Z	  Z
S ))CachedResourceFuncInfoz?Implements the CachedFuncInfo interface for @st.cache_resource.NFfuncCallable[P, R]show_spinner
bool | strr5   
int | Noner7   r8   r9   r!   
hash_funcsHashFuncsDict | None	show_timer$   r#   r)   c                   s*   t  j||||d || _|| _|| _d S )N)r]   rZ   r_   )superr1   r5   r7   r9   )r0   rX   rZ   r5   r7   r9   r]   r_   	__class__r%   r&   r1      s   

zCachedResourceFuncInfo.__init__r   c                 C  s   t jS r*   )r   RESOURCEr/   r%   r%   r&   
cache_type   s   z!CachedResourceFuncInfo.cache_typer   c                 C  rQ   r*   )!CACHE_RESOURCE_MESSAGE_REPLAY_CTXr/   r%   r%   r&   cached_message_replay_ctx   rT   z0CachedResourceFuncInfo.cached_message_replay_ctxr3   c                 C  s   | j j d| j j S )z.A human-readable name for the cached function..)rX   rN   rO   r/   r%   r%   r&   r4      s   z#CachedResourceFuncInfo.display_namefunction_keyCache[R]c                 C  s   t j|| j| j| j| jdS )N)r2   r4   r5   r7   r9   )rR   rB   r4   r5   r7   r9   )r0   rh   r%   r%   r&   get_function_cache   s   z)CachedResourceFuncInfo.get_function_cache)NF)rX   rY   rZ   r[   r5   r\   r7   r8   r9   r!   r]   r^   r_   r$   r#   r)   )r#   r   )r#   r   )r#   r3   )rh   r3   r#   ri   )rM   rN   rO   rP   r1   propertyrd   rf   r4   rj   __classcell__r%   r%   ra   r&   rW      s    	rW   c                   @  s   e Zd ZdZd(ddZed)ddZedddddddd*ddZ	d+dddddddd,d!dZddd"d,d#d$Zed%d-d&d'Z	dS ).CacheResourceAPIzvImplements the public st.cache_resource API: the @st.cache_resource decorator,
    and st.cache_resource.clear().
    decorator_metric_namer3   r#   r)   c                 C  s   t || j| _dS )zCreate a CacheResourceAPI instance.

        Parameters
        ----------
        decorator_metric_name
            The metric name to record for decorator usage.
        N)r   
_decorator)r0   rn   r%   r%   r&   r1      s   zCacheResourceAPI.__init__rX   rY   CachedFunc[P, R]c                 C     d S r*   r%   )r0   rX   r%   r%   r&   __call__   s   zCacheResourceAPI.__call__NTFr7   r5   rZ   r_   r9   r]   r7   r8   r5   r\   rZ   r[   r_   r$   r9   r!   r]   r^   ,Callable[[Callable[P, R]], CachedFunc[P, R]]c                C  rq   r*   r%   )r0   r7   r5   rZ   r_   r9   r]   r%   r%   r&   rr      s   
Callable[P, R] | None?CachedFunc[P, R] | Callable[[Callable[P, R]], CachedFunc[P, R]]c             	   C  s   | j |||||||dS )Nrs   )ro   r0   rX   r7   r5   rZ   r_   r9   r]   r%   r%   r&   rr      s   )r_   r]   c             
     s8   |du r fddS t t| d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()``.

        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``.

        Cached values are available to all users of your app. If you need to
        save results that should only be accessible within a session, use
        `Session State
        <https://docs.streamlit.io/develop/concepts/architecture/session-state>`_
        instead. Within each user session, an ``@st.cache_resource``-decorated
        function returns the cached instance of the return value (if the value
        is already cached). Therefore, objects cached by ``st.cache_resource``
        act like singletons and can mutate. To cache data and return copies,
        use ``st.cache_data`` instead. To learn more about caching, see
        `Caching overview
        <https://docs.streamlit.io/develop/concepts/architecture/caching>`_.

        .. warning::
            Async objects are not officially supported in Streamlit. Caching
            async objects or objects that reference async objects may have
            unintended consequences. For example, Streamlit may close event
            loops in its normal operation and make the cached object raise an
            ``Event loop closed`` error.

            To upvote official ``asyncio`` support, see GitHub issue `#8488
            <https://github.com/streamlit/streamlit/issues/8488>`_. To upvote
            support for caching async functions, see GitHub issue `#8308
            <https://github.com/streamlit/streamlit/issues/8308>`_.

        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.

        show_time : bool
            Whether to show the elapsed time next to the spinner text. If this is
            ``False`` (default), no time is displayed. If this is ``True``,
            elapsed time is displayed with a precision of 0.1 seconds. The time
            format is not configurable.

        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.

        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
        >>>
        >>> fetch_and_clean_data.clear(_sessionmaker, "https://streamlit.io/")
        >>> # Clear the cached entry for the arguments provided.
        >>>
        >>> 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              
     s   t t|  dS )NrX   rZ   r_   r5   r7   r9   r]   r   rW   )fr]   r5   rZ   r_   r7   r9   r%   r&   <lambda>  s    z-CacheResourceAPI._decorator.<locals>.<lambda>rx   ry   rw   r%   r{   r&   ro     s    <zCacheResourceAPI._decoratorclear_resource_cachesc                 C  s   t   dS )z Clear all cache_resource caches.N)rR   rC   r/   r%   r%   r&   clear  s   zCacheResourceAPI.clear)rn   r3   r#   r)   )rX   rY   r#   rp   )r7   r8   r5   r\   rZ   r[   r_   r$   r9   r!   r]   r^   r#   rt   r*   )rX   ru   r7   r8   r5   r\   rZ   r[   r_   r$   r9   r!   r]   r^   r#   rv   rK   )
rM   rN   rO   rP   r1   r	   rr   ro   r   r~   r%   r%   r%   r&   rm      s8    
 Urm   c                      sp   e Zd ZdZd# fddZed$ddZed$ddZd%ddZe	dd&ddZ
d'd(ddZd)d!d"Z  ZS )*r@   z>Manages cached values for a single st.cache_resource function.r2   r3   r5   floatr;   r9   r!   r4   r#   r)   c                   s<   t    || _|| _t||tjd| _t	 | _
|| _d S )N)maxsizer7   timer)r`   r1   r2   r4   r
   r   TTLCACHE_TIMER
_mem_cacher+   r,   _mem_cache_lockr9   )r0   r2   r5   r;   r9   r4   ra   r%   r&   r1     s   


zResourceCache.__init__c                 C     | j jS r*   )r   r   r/   r%   r%   r&   r5        zResourceCache.max_entriesc                 C  r   r*   )r   r7   r/   r%   r%   r&   r;     r   zResourceCache.ttl_secondsCachedResult[R]c                 C  sl   | j ) || jvrt | j| }| jdur#| |js#| j|= t |W  d   S 1 s/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   r9   value)r0   r2   resultr%   r%   r&   read_result  s   

$zResourceCache.read_result_cache_resource_objectr   rV   messageslist[MsgData]c                 C  sP   t jj}t jj}| j t||||| j|< W d   dS 1 s!w   Y  dS )z3Write a value and associated messages to the cache.N)st_mainidsidebarr   r   r   )r0   r2   r   r   main_id
sidebar_idr%   r%   r&   write_result  s
   "zResourceCache.write_resultN
str | Nonec                 C  sr   | j , |d u r| j  n|| jv r| j|= W d    d S W d    d S W d    d S 1 s2w   Y  d S r*   )r   r   r~   )r0   r2   r%   r%   r&   _clear  s   

"zResourceCache._clearrD   c                   sT   j  tj }W d    n1 sw   Y  ddlm   fdd|D S )Nr   )asizeofc                   s    g | ]}t d j |dqS )st_cache_resource)category_name
cache_namebyte_length)r   r4   ).0entryr   r0   r%   r&   
<listcomp>&  s    z+ResourceCache.get_stats.<locals>.<listcomp>)r   listr   rF    streamlit.vendor.pympler.asizeofr   )r0   cache_entriesr%   r   r&   rH     s   zResourceCache.get_stats)r2   r3   r5   r   r;   r   r9   r!   r4   r3   r#   r)   )r#   r   )r2   r3   r#   r   )r2   r3   r   rV   r   r   r#   r)   r*   )r2   r   r#   r)   rL   )rM   rN   rO   rP   r1   rk   r5   r;   r   r   r   r   rH   rl   r%   r%   ra   r&   r@     s    
r@   )r    r!   r"   r!   r#   r$   )r#   r   )ArP   
__future__r   r<   r+   collections.abcr   typingr   r   r   r   r   r	   
cachetoolsr
   typing_extensionsr   	streamlitr   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   streamlit.runtime.metrics_utilr   streamlit.runtime.statsr   r   r   streamlit.time_utilr   datetimer   !streamlit.runtime.caching.hashingr   rM   r   __annotations__rc   re   r$   r   r'   r(   rR   rS   rU   rV   rW   rm   r@   r%   r%   r%   r&   <module>   sF    	

	B
.  