o
    h}U                     @  s  U d Z ddlm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 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!m"Z"m#Z# dd
l$m%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+ e!,e-Z.de/d< dZ0de/d< dZ1de/d< dZ2de/d< dZ3de/d< e4ee5e6e f eegef f Z7de/d< dZ8de/d< G dd de%Z9		d?d@d(d)Z:G d*d+ d+Z;G d,d- d-Z<e< Z=dAd1d2Z>dBd5d6Z?dCd9d:Z@G d;d< d<ZAG d=d> d>ZBdS )Dz0Hashing for st.cache_data and st.cache_resource.    )annotationsN)Enum)Pattern)MappingProxyType)AnyCallableFinalUnioncast)	TypeAlias)logger	type_utilutil)StreamlitAPIException)UnhashableTypeError)	CacheType)UploadedFiler   _LOGGERiP  _PANDAS_ROWS_LARGEi'  _PANDAS_SAMPLE_SIZEi  _NP_SIZE_LARGEi _NP_SAMPLE_SIZEr   HashFuncsDicts<   streamlit-57R34ML17-hesamagicalponyflyingthroughthesky-CYCLE_CYCLE_PLACEHOLDERc                      s4   e Zd Z	dd fddZdd ZdddZ  ZS )UserHashErrorN
cache_typeCacheType | Nonec                   s@   t |j| _|| _|| _| ||}t | | |j	 d S N)
type__name__alternate_name	hash_funcr   _get_message_from_funcsuper__init__with_traceback__traceback__)selforig_excobject_to_hashr!   r   msg	__class__ U/var/www/vscode/kcb/lib/python3.10/site-packages/streamlit/runtime/caching/hashing.pyr$   C   s   zUserHashError.__init__c                 C  s   |  ||}d| dS )Nad  
%(orig_exception_desc)s

This error is likely due to a bug in %(hash_func_name)s, which is a
user-defined hash function that was passed into the `%(cache_primitive)s` decorator of
%(object_desc)s.

%(hash_func_name)s failed when hashing an object of type
`%(failed_obj_type_str)s`.  If you don't know where that object is coming from,
try looking at the hash chain below for an object that you do recognize, then
pass that to `hash_funcs` instead:

```
%(hash_stack)s
```

If you think this is actually a Streamlit bug, please
[file a bug report here](https://github.com/streamlit/streamlit/issues/new/choose).

)_get_error_message_argsstrip)r'   r(   cached_funcargsr-   r-   r.   r"   S   s   z$UserHashError._get_message_from_funcr(   BaseException
failed_objr   returndict[str, Any]c                 C  s   t jj}t|}|d u rd}nt|drd|j d}nd}d}| jtj	u r*d}n| jtj
u r2d}t| jdrAd| jj d}nd}t||t j |||d	S )
N	somethingr   `z()`z
a function z@st.cache_resourcez@st.cache_data)orig_exception_descfailed_obj_type_str
hash_stackobject_desccache_primitivehash_func_name)hash_stackscurrenthash_sourcer   get_fqn_typehasattrr   r   r   RESOURCEDATAr!   strpretty_print)r'   r(   r5   rC   r<   r>   decorator_namer@   r-   r-   r.   r0   m   s,   

z%UserHashError._get_error_message_argsr   )r   r   )r(   r4   r5   r   r6   r7   )r   
__module____qualname__r$   r"   r0   __classcell__r-   r-   r+   r.   r   B   s
    r   valr   r   r   rC   Callable[..., Any] | None
hash_funcsHashFuncsDict | Noner6   Nonec                 C  s"   |t j_t||}|||  dS )zcUpdates a hashlib hasher with the hash of val.

    This is the main entrypoint to hashing.py.
    N)rA   rB   rC   _CacheFuncHasherupdate)rN   hasherr   rC   rP   chr-   r-   r.   update_hash   s   
rW   c                   @  sH   e Zd ZdZdd ZdddZdd
dZdd ZdddZdddZ	dS )
_HashStacka  Stack of what has been hashed, for debug and circular reference detection.

    This internally keeps 1 stack per thread.

    Internally, this stores the ID of pushed objects rather than the objects
    themselves because otherwise the "in" operator inside __contains__ would
    fail for objects that don't return a boolean for "==" operator. For
    example, arr == 10 where arr is a NumPy array returns another NumPy array.
    This causes the "in" to crash since it expects a boolean.
    c                 C  s   t  | _d | _d S r   )collectionsOrderedDict_stackrC   r'   r-   r-   r.   r$      s   

z_HashStack.__init__r6   rH   c                 C  
   t | S r   r   repr_r\   r-   r-   r.   __repr__      
z_HashStack.__repr__rN   r   c                 C  s   || j t|< d S r   )r[   idr'   rN   r-   r-   r.   push   s   z_HashStack.pushc                 C  s   | j   d S r   )r[   popitemr\   r-   r-   r.   pop      z_HashStack.popc                 C  s   t || jv S r   )rb   r[   rc   r-   r-   r.   __contains__   rg   z_HashStack.__contains__c                   s,   d
dd d  fdd	t| j D S )Nvr   r6   rH   c                 S  s2   zdt |  dt|  W S  ty   Y dS w )NzObject of type z: z"<Unable to convert item to string>)r   rD   rH   	Exception)ri   r-   r-   r.   to_str   s
   z'_HashStack.pretty_print.<locals>.to_strr/   c                 3  s    | ]} |V  qd S r   r-   ).0xrk   r-   r.   	<genexpr>   s    z*_HashStack.pretty_print.<locals>.<genexpr>)ri   r   r6   rH   )joinreversedr[   valuesr\   r-   rn   r.   rI      s   
"z_HashStack.pretty_printNr6   rH   )rN   r   )
r   rK   rL   __doc__r$   r`   rd   rf   rh   rI   r-   r-   r-   r.   rX      s    


rX   c                   @  s0   e Zd ZdZdd ZdddZedd	d
ZdS )_HashStacksz@Stacks of what has been hashed, with at most 1 stack per thread.c                 C  s   t  | _d S r   )weakrefWeakKeyDictionary_stacksr\   r-   r-   r.   r$      s   z_HashStacks.__init__r6   rH   c                 C  r]   r   r^   r\   r-   r-   r.   r`      ra   z_HashStacks.__repr__rX   c                 C  s2   t  }| j|d }|d u rt }|| j|< |S r   )	threadingcurrent_threadrx   getrX   )r'   rz   stackr-   r-   r.   rB      s   
z_HashStacks.currentNrs   )r6   rX   )r   rK   rL   rt   r$   r`   propertyrB   r-   r-   r-   r.   ru      s    
ru   iintbytesc                 C  s    |   d d }| j|dddS )N   littleT)signed)
bit_lengthto_bytes)r~   	num_bytesr-   r-   r.   _int_to_bytes   s   r   ffloatc                 C  s   dd l }|d| S )Nr   z<d)structpack)r   r   r-   r-   r.   _float_to_bytes   s   r   obj
Any | Nonec                 C  s   | du rdS dd }|| r| S t | trtt|| r| S t | tr0tt|| r0dt| fS t| s?t| s?t| rCt	| S t
S )zReturn key for memoization.Nc                 S  sP   t | tp't | tp't | tp't | tp't | tp't | tp't | tjp'| d u S r   )	
isinstancer   	bytearrayrH   r   r   booluuidUUID)r   r-   r-   r.   	is_simple   s   

z_key.<locals>.is_simple__l)r   tupleallmaplistinspect	isbuiltin	isroutineiscoderb   NoResult)r   r   r-   r-   r.   _key   s   

r   c                   @  sD   e Zd ZdZddddZdddZdddZdddZdddZdS )rS   z+A hasher that can hash objects with cycles.Nr   r   rP   rQ   c                 C  s:   |  |rdd |  D | _ni | _i | _d| _|| _d S )Nc                 S  s*   i | ]\}}t |tr|nt||qS r-   )r   rH   r   get_fqn)rl   kri   r-   r-   r.   
<dictcomp>%  s    z-_CacheFuncHasher.__init__.<locals>.<dictcomp>r   )items_hash_funcs_hashessizer   )r'   r   rP   r-   r-   r.   r$     s   

z_CacheFuncHasher.__init__r6   rH   c                 C  r]   r   r^   r\   r-   r-   r.   r`   2  ra   z_CacheFuncHasher.__repr__r   r   r   c                 C  s   t |j }|t|f}|d tur|| jv r| j| S |tjv r$tS tj	| z.d|| 
|f }|  jt|7  _|d turQ|| j|< W tj  |S W tj  |S tj  w )zKAdd memoization to _to_bytes and protect against cycles in data structures.   s   %s:%s)r   rL   encoder   r   r   rA   rB   r   rd   	_to_bytesr   sys	getsizeofrf   )r'   r   tnamekeybr-   r-   r.   r   5  s&   




z_CacheFuncHasher.to_bytesrR   c                 C  s   |  |}|| dS )z6Update the provided hasher with the hash of an object.N)r   rT   )r'   rU   r   r   r-   r-   r.   rT   W  s   
z_CacheFuncHasher.updatec              
   C  s  t jddd}t|dst|dr| t|S t|ts$t|tr&|S t	|| j
v rX| j
t	| }z||}W n tyR } z
t|||| jd|d}~ww | |S t|tra| S t|trjt|S t|trst|S t|tjr||jS t|tjr|  S t|ttfr|D ]}| || q| S t|tr| D ]}| || q| S |du rdS |d	u rd
S |du rdS t|tst |r| t!|S t|t"rt| S t|dr>ddl#}t$d|}| ||j% | ||j&j' t(|t)kr|j*t+dd}z| ||j,-|. /  | W S  t0y=   t1j2dd	d dt34|t3j5  Y S w t|drddl#}t$d|}| ||j6 t(|t)krc|j*t+dd}z$| |j,-|j7}| || | |j,-|}	| ||	 | W S  t0y   t1j2dd	d dt34|t3j5  Y S w t|drddl8}
t$d|}| |t|j&  | ||j6 t(|t)kr|j*t+dd}z| ||j9dd: ;   | W S  t0y   t1j2dd	d dt34|t3j5  Y S w t|drzddl8}
t$d|}| ||j6 t(|t)kr'|j*t+dd}z8|j< D ]\}}| ||  | |t|  q-|j=ddj9dd: ;  }	| ||	 | W S  t0yy   t1j2dd	d dt34|t3j5  Y S w t|drddl>}t$d|}| ||j6 | |t|j& |j%t?krddl>}|j@Ad}|jB|jCtDd}| ||/  | S t|d rddl>}dd!lEmF} t$d"|}|jG|/ d#d$}| |S tHI|rt|jJ S t|tKst|tLjMjNr| t|S t|d%rt|jO S t|tPr3| ||j' | ||Q  | ||R  | S tS|d&rit|tTjUsGt|tVjWritX|d&d'}| || | |tYjZ[| | ||Q  | S t|t\rx| |j]|j^gS t|tTj_st|tTj`r| ||Q  | ||R  | S t|d(rt|jJ S tHa|r| |jJS tHb|r| |jJS t|tcjdr| ||je | ||jf | ||jg | S z|h }W n ty } zti |d}~ww |D ]	}| || q| S ))zHash objects to bytes, including code with dependencies.

        Python's built in `hash` does not produce consistent results across
        runs.
        md5F)usedforsecurityzunittest.mock.Mockzunittest.mock.MagicMock)r!   r   N   0T   1zpandas.core.series.Seriesr   z	pd.Series)nrandom_statez?Pandas Series hash failed. Falling back to pickling the object.)exc_infos   %szpandas.core.frame.DataFramezpd.DataFramezBPandas DataFrame hash failed. Falling back to pickling the object.zpolars.series.series.Seriesz	pl.Series)r   seed)r   z?Polars Series hash failed. Falling back to pickling the object.z polars.dataframe.frame.DataFramezpl.DataFramezBPolars DataFrame hash failed. Falling back to pickling the object.znumpy.ndarrayznp.ndarray[Any, Any])r   zPIL.Image.Image)Imager   uint8)dtypezbuiltins.getset_descriptorname
wonthappenznumpy.ufunc)jhashlibnewr   is_typer   rb   r   r   r   rD   r   rj   r   r   rH   r   r   r   r   r   r   r   datetime	isoformatr   r   rT   digestdictr   r   dataclassesis_dataclassasdictr   pandasr
   r   r   r   lenr   sampler   r   hash_pandas_objectto_numpytobytes	TypeErrorr   warningpickledumpsHIGHEST_PROTOCOLshapedtypespolarshashto_arrow	to_stringschema	hash_rowsnumpyr   randomRandomStatechoiceflatr   	PIL.Imager   
frombufferr   r   r   r   rY   abc	ItemsViewrL   r   tellgetvaluerE   ioIOBasetempfile_TemporaryFileWrappergetattrospathgetmtimer   patternflagsStringIOBytesIOismoduleisclass	functoolspartialr3   funckeywords
__reduce__r   )r'   r   hr!   outputexitempdcolumn_hash_bytesvalues_hash_bytesplctnpstater   np_arrayobj_namereduce_datar-   r-   r.   r   \  s|  













 
	

	





z_CacheFuncHasher._to_bytesr   )r   r   rP   rQ   rs   )r   r   r6   r   )r   r   r6   rR   )	r   rK   rL   rt   r$   r`   r   rT   r   r-   r-   r-   r.   rS     s    


"rS   c                   @  s   e Zd ZdZdS )r   z<Placeholder class for return values when None is meaningful.N)r   rK   rL   rt   r-   r-   r-   r.   r   z  s    r   )NN)
rN   r   r   r   rC   rO   rP   rQ   r6   rR   )r~   r   r6   r   )r   r   r6   r   )r   r   r6   r   )Crt   
__future__r   rY   collections.abcr   r   r   r   r   r   r   r   r   r   ry   r   rv   enumr   rer   typesr   typingr   r   r   r	   r
   typing_extensionsr   	streamlitr   r   r   streamlit.errorsr   &streamlit.runtime.caching.cache_errorsr   $streamlit.runtime.caching.cache_typer   'streamlit.runtime.uploaded_file_managerr   
get_loggerr   r   __annotations__r   r   r   r   r   rH   r   r   r   r   rW   rX   ru   rA   r   r   r   rS   r   r-   r-   r-   r.   <module>   sb   *
U(


#  d