o
    ZhX                     @  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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rddl-mZ. ddl/Z0ddl1m2Z2 e"3e4Z5de6d< dZ7de6d< dZ8de6d< dZ9de6d< dZ:de6d< e;ee<e=e f eegef f Z>de6d< dZ?de6d< G dd de&Z@		dAdBd*d+ZAG d,d- d-ZBG d.d/ d/ZCeC ZDdCd3d4ZEdDd7d8ZFdEd;d<ZGG d=d> d>ZHG d?d@ d@ZIdS )Fz0Hashing for st.cache_data and st.cache_resource.    )annotationsN)Enum)Pattern)MappingProxyType)TYPE_CHECKINGAnyCallableFinalUnioncast)	TypeAlias)logger	type_utilutil)StreamlitAPIException)UnhashableTypeError)	CacheType)UploadedFile)Imager	   _LOGGERiP  _PANDAS_ROWS_LARGEi'  _PANDAS_SAMPLE_SIZEi  _NP_SIZE_LARGEi _NP_SAMPLE_SIZEr   HashFuncsDicts<   streamlit-57R34ML17-hesamagicalponyflyingthroughthesky-CYCLE_CYCLE_PLACEHOLDERc                      s6   e Zd Z	dd fddZdddZdddZ  ZS )UserHashErrorNorig_excBaseExceptionobject_to_hashr   	hash_funcCallable[[Any], Any]
cache_typeCacheType | NonereturnNonec                   s@   t |j| _|| _|| _| ||}t | | |j	 d S N)
type__name__alternate_namer    r"   _get_message_from_funcsuper__init__with_traceback__traceback__)selfr   r   r    r"   msg	__class__ b/var/www/html/Persson_Maskin/env/lib/python3.10/site-packages/streamlit/runtime/caching/hashing.pyr,   H   s   zUserHashError.__init__cached_funcstrc                 C  s^   |  ||}d|d  d|d  d|d  d|d  d	|d  d
|d  d|d  ddS )N
orig_exception_descz'

This error is likely due to a bug in hash_func_namezB, which is a
user-defined hash function that was passed into the `cache_primitivez` decorator of
object_descz.

z( failed when hashing an object of type
`failed_obj_type_strz`.  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_stackz
```

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   r5   argsr3   r3   r4   r*   X   s$   z$UserHashError._get_message_from_func
failed_obj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r@d| jj dnd}t||t j |||d	S )
N	somethingr(   `z()`z
a function z@st.cache_resourcez@st.cache_data)r8   r<   r=   r;   r:   r9   )hash_stackscurrenthash_sourcer   get_fqn_typehasattrr(   r"   r   RESOURCEDATAr    r6   pretty_print)r/   r   rA   rH   r<   r;   decorator_namer9   r3   r3   r4   r>   u   s.   


z%UserHashError._get_error_message_argsr&   )
r   r   r   r   r    r!   r"   r#   r$   r%   )r   r   r5   r   r$   r6   )r   r   rA   r   r$   rB   )r(   
__module____qualname__r,   r*   r>   __classcell__r3   r3   r1   r4   r   G   s
    
r   valr   hasherr"   r   rH   Callable[..., Any] | None
hash_funcsHashFuncsDict | Noner$   r%   c                 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)rF   rG   rH   _CacheFuncHasherupdate)rR   rS   r"   rH   rU   chr3   r3   r4   update_hash   s   
rZ   c                   @  sL   e Zd ZdZdddZdddZdddZd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.
    r$   r%   c                 C  s   t  | _d | _d S r&   )collectionsOrderedDict_stackrH   r/   r3   r3   r4   r,      s   

z_HashStack.__init__r6   c                 C  
   t | S r&   r   repr_r_   r3   r3   r4   __repr__      
z_HashStack.__repr__rR   r   c                 C  s   || j t|< d S r&   )r^   idr/   rR   r3   r3   r4   push   s   z_HashStack.pushc                 C  s   | j   d S r&   )r^   popitemr_   r3   r3   r4   pop      z_HashStack.popboolc                 C  s   t || jv S r&   )re   r^   rf   r3   r3   r4   __contains__   rj   z_HashStack.__contains__c                   s,   d
dd d  fdd	t| j D S )Nvr   r$   r6   c                 S  s.   zdt |  d|  W S  ty   Y dS w )NzObject of type z: z"<Unable to convert item to string>)r   rI   	Exception)rm   r3   r3   r4   to_str   s
   z'_HashStack.pretty_print.<locals>.to_strr7   c                 3  s    | ]} |V  qd S r&   r3   ).0xro   r3   r4   	<genexpr>   s    z*_HashStack.pretty_print.<locals>.<genexpr>)rm   r   r$   r6   )joinreversedr^   valuesr_   r3   rr   r4   rM      s   
"z_HashStack.pretty_printNr$   r%   r$   r6   )rR   r   r$   r%   )rR   r   r$   rk   )
r(   rO   rP   __doc__r,   rc   rg   ri   rl   rM   r3   r3   r3   r4   r[      s    




r[   c                   @  s2   e Zd ZdZd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.r$   r%   c                 C  s   t  | _d S r&   )weakrefWeakKeyDictionary_stacksr_   r3   r3   r4   r,      s   z_HashStacks.__init__r6   c                 C  r`   r&   ra   r_   r3   r3   r4   rc      rd   z_HashStacks.__repr__r[   c                 C  s2   t  }| j|d }|d u rt }|| j|< |S r&   )	threadingcurrent_threadr}   getr[   )r/   r   stackr3   r3   r4   rG      s   
z_HashStacks.currentNrw   rx   )r$   r[   )r(   rO   rP   ry   r,   rc   propertyrG   r3   r3   r3   r4   rz      s    

rz   iintbytesc                 C  s    |   d d }| j|dddS )N   littleT)signed)
bit_lengthto_bytes)r   	num_bytesr3   r3   r4   _int_to_bytes   s   r   ffloatc                 C  s   dd l }|d| S )Nr   z<d)structpack)r   r   r3   r3   r4   _float_to_bytes   s   r   obj
Any | Nonec                 C  s   | du rdS d	dd}|| r| S t | trtt|| r| S t | tr1tt|| r1dt| fS t| s@t| s@t| rDt	| S t
S )
zReturn key for memoization.Nr   r   r$   rk   c              	   S  s"   t | tttttttjfp| d u S r&   )	
isinstancer   	bytearrayr6   r   r   rk   uuidUUID)r   r3   r3   r4   	is_simple  s   z_key.<locals>.is_simple__l)r   r   r$   rk   )r   tupleallmaplistinspect	isbuiltin	isroutineiscodere   NoResult)r   r   r3   r3   r4   _key   s   
r   c                   @  sF   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 )rW   z+A hasher that can hash objects with cycles.Nr"   r   rU   rV   r$   r%   c                 C  s:   |  |rdd |  D | _ni | _i | _d| _|| _d S )Nc                 S  s*   i | ]\}}t |tr|nt||qS r3   )r   r6   r   get_fqn)rp   krm   r3   r3   r4   
<dictcomp>'  s    z-_CacheFuncHasher.__init__.<locals>.<dictcomp>r   )items_hash_funcs_hashessizer"   )r/   r"   rU   r3   r3   r4   r,     s   


z_CacheFuncHasher.__init__r6   c                 C  r`   r&   ra   r_   r3   r3   r4   rc   4  rd   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'   rP   encoder   r   r   rF   rG   r   rg   	_to_bytesr   sys	getsizeofri   )r/   r   tnamekeybr3   r3   r4   r   7  s$   



z_CacheFuncHasher.to_bytesrS   c                 C  s   |  |}|| dS )z6Update the provided hasher with the hash of an object.N)r   rX   )r/   rS   r   r   r3   r3   r4   rX   X  s   
z_CacheFuncHasher.updatec              
   C  sJ  t jddd}t|dst|dr| t|S t|ttfr#|S t	|| j
v rU| j
t	| }z||}W n tyO } z
t|||| jd|d}~ww | |S t|tr^| S t|trgt|S t|trpt|S t|tjry|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#m$} t%d|}| ||j& | ||j'j( t)|t*kr|j+t,dd}z| |||- .  | W S  t/y:   t0j1dd	d dt23|t2j4  Y S w t|drddl#m$} t%d|}	| ||	j5 t)|	t*krb|	j+t,dd}	z | ||	j6}
| ||
 | ||	}| || | W S  t/y   t0j1dd	d dt23|	t2j4  Y S w t|drddl7}t%d|}| |t|j'  | ||j5 t)|t*kr|j+t,dd}z| ||j8dd9 :   | W S  t/y   t0j1dd	d dt23|t2j4  Y S w t|druddl7}t%d|}| ||j5 t)|t*kr"|j+t,dd}z8|j; D ]\}}| ||  | |t|  q(|j<ddj8dd9 :  }| || | W S  t/yt   t0j1dd	d dt23|t2j4  Y S w t|drt%d|}| ||j5 | |t|j' |j&t=krddl>}|j?@d}|jA|jBtCd }| ||.  | S t|d!rddl>}t%d"|}|jD|. d#d$}| |S tEF|rt|jG S t|tHtIjJjKfr| t|S t|d%rt|jL S t|tMr | ||j( | ||N  | ||O  | S tP|d&rRt|tQjRtSjTfrRtU|d&d'}| || | |tVjWX| | ||N  | S t|tYra| |jZ|j[gS t|tQj\tQj]fr| ||N  | ||O  | S t|d(rt|jG S tE^|r| |jGS tE_|r| |jGS t|t`jar| ||jb | ||jc | ||jd | S te|rzt%d)|}tP|d*r|f }n|g }| || | W S  ty } zthd+|d}~ww z|i }W n ty } zth |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   )hash_pandas_objectz	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npt.NDArray[Any])r   zPIL.Image.Imager   uint8)dtypezbuiltins.getset_descriptorname
wonthappenznumpy.ufuncr   model_dump_jsonze
                    Pydantic object contains unhashable members, such as functions.
                )jhashlibnewr   is_typer   re   r   r   r   rI   r   rn   r   r"   r6   r   r   r   r   r   r   r   datetime	isoformatr   r   rX   digestdictr   r'   dataclassesis_dataclassasdictr   pandas.utilr   r   r   r   r   lenr   sampler   to_numpytobytes	TypeErrorr   warningpickledumpsHIGHEST_PROTOCOLshapedtypespolarshashto_arrow	to_stringschema	hash_rowsr   numpyrandomRandomStatechoiceflatr   
frombufferr   r   r(   r   r\   abc	ItemsViewrP   r   tellgetvaluerJ   ioIOBasetempfile_TemporaryFileWrappergetattrospathgetmtimer   patternflagsStringIOBytesIOismoduleisclass	functoolspartialr@   funckeywordsis_pydantic_modelr   jsonr   
__reduce__)r/   r   hr    outputexitemr   
series_objdf_objcolumn_hash_bytesvalues_hash_bytesplctnp_objnpstatepil_objnp_arrayobj_nameany_obj	json_datareduce_datar3   r3   r4   r   ]  s  













 











z_CacheFuncHasher._to_bytesr&   )r"   r   rU   rV   r$   r%   rx   )r   r   r$   r   )rS   r   r   r   r$   r%   )	r(   rO   rP   ry   r,   rc   r   rX   r   r3   r3   r3   r4   rW     s    


!rW   c                   @  s   e Zd ZdZdS )r   z<Placeholder class for return values when None is meaningful.N)r(   rO   rP   ry   r3   r3   r3   r4   r     s    r   )NN)rR   r   rS   r   r"   r   rH   rT   rU   rV   r$   r%   )r   r   r$   r   )r   r   r$   r   )r   r   r$   r   )Jry   
__future__r   r\   collections.abcr   r   r   r   r   r   r   r   r   r   r~   r   r{   enumr   rer   typesr   typingr   r   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   numpy.typingnptpandaspd	PIL.Imager   
get_loggerr(   r   __annotations__r   r   r   r   r   r6   r'   r   r   r   rZ   r[   rz   rF   r   r   r   rW   r   r3   r3   r3   r4   <module>   sj    *
X(


  y