o
    ,&]iX                     @  s2  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 ddlmZ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& ddl'm(Z( ddl)m*Z* erddl+mZ, ddl-Z.ddl/m0Z0 e 1e2Z3de4d< dZ5de4d< dZ6de4d< dZ7de4d< dZ8de4d< e9e:e;e B eegef f Z<de4d< dZ=de4d< G dd de$Z>		dAdBd*d+Z?G d,d- d-Z@G d.d/ d/ZAeA ZBdCd3d4ZCdDd7d8ZDdEd;d<ZEG d=d> d>ZFG d?d@ d@ZGdS )Fz0Hashing for st.cache_data and st.cache_resource.    )annotationsN)Callable)Enum)Pattern)MappingProxyType)TYPE_CHECKINGAnyFinal	TypeAliascast)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__ _/var/www/html/IGF-ODF-V3/venv/lib/python3.10/site-packages/streamlit/runtime/caching/hashing.pyr+   G   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   r4   argsr2   r2   r3   r)   W   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)r7   r;   r<   r:   r9   r8   )hash_stackscurrenthash_sourcer   get_fqn_typehasattrr'   r!   r   RESOURCEDATAr   r5   pretty_print)r.   r   r@   rG   r;   r:   decorator_namer8   r2   r2   r3   r=   t   s.   


z%UserHashError._get_error_message_argsr%   )
r   r   r   r   r   r    r!   r"   r#   r$   )r   r   r4   r   r#   r5   )r   r   r@   r   r#   rA   )r'   
__module____qualname__r+   r)   r=   __classcell__r2   r2   r0   r3   r   F   s
    
r   valr   hasherr!   r   rG   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)rE   rF   rG   _CacheFuncHasherupdate)rQ   rR   r!   rG   rT   chr2   r2   r3   update_hash   s   
rY   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_stackrG   r.   r2   r2   r3   r+      s   

z_HashStack.__init__r5   c                 C  
   t | S r%   r   repr_r^   r2   r2   r3   __repr__      
z_HashStack.__repr__rQ   r   c                 C  s   || j t|< d S r%   )r]   idr.   rQ   r2   r2   r3   push   s   z_HashStack.pushc                 C  s   | j   d S r%   )r]   popitemr^   r2   r2   r3   pop      z_HashStack.popboolc                 C  s   t || jv S r%   )rd   r]   re   r2   r2   r3   __contains__   ri   z_HashStack.__contains__c                   s,   d
dd d  fdd	t| j D S )Nvr   r#   r5   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   rH   	Exception)rl   r2   r2   r3   to_str   s
   z'_HashStack.pretty_print.<locals>.to_strr6   c                 3  s    | ]} |V  qd S r%   r2   ).0xrn   r2   r3   	<genexpr>   s    z*_HashStack.pretty_print.<locals>.<genexpr>)rl   r   r#   r5   )joinreversedr]   valuesr^   r2   rq   r3   rL      s   
"z_HashStack.pretty_printNr#   r$   r#   r5   )rQ   r   r#   r$   )rQ   r   r#   rj   )
r'   rN   rO   __doc__r+   rb   rf   rh   rk   rL   r2   r2   r2   r3   rZ      s    




rZ   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^   r2   r2   r3   r+      s   z_HashStacks.__init__r5   c                 C  r_   r%   r`   r^   r2   r2   r3   rb      rc   z_HashStacks.__repr__rZ   c                 C  s2   t  }| j|d }|d u rt }|| j|< |S r%   )	threadingcurrent_threadr|   getrZ   )r.   r~   stackr2   r2   r3   rF      s   
z_HashStacks.currentNrv   rw   )r#   rZ   )r'   rN   rO   rx   r+   rb   propertyrF   r2   r2   r2   r3   ry      s    

ry   iintbytesc                 C  s    |   d d }| j|dddS )N   littleT)signed)
bit_lengthto_bytes)r   	num_bytesr2   r2   r3   _int_to_bytes   s   r   ffloatc                 C  s   dd l }|d| S )Nr   z<d)structpack)r   r   r2   r2   r3   _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#   rj   c              	   S  s"   t | tttttttjfp| d u S r%   )	
isinstancer   	bytearrayr5   r   r   rj   uuidUUID)r   r2   r2   r3   	is_simple  s   z_key.<locals>.is_simple__l)r   r   r#   rj   )r   tupleallmaplistinspect	isbuiltin	isroutineiscoderd   NoResult)r   r   r2   r2   r3   _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 )rV   z+A hasher that can hash objects with cycles.Nr!   r   rT   rU   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 r2   )r   r5   r   get_fqn)ro   krl   r2   r2   r3   
<dictcomp>&  s    z-_CacheFuncHasher.__init__.<locals>.<dictcomp>r   )items_hash_funcs_hashessizer!   )r.   r!   rT   r2   r2   r3   r+     s   


z_CacheFuncHasher.__init__r5   c                 C  r_   r%   r`   r^   r2   r2   r3   rb   3  rc   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&   rO   encoder   r   r   rE   rF   r   rf   	_to_bytesr   sys	getsizeofrh   )r.   r   tnamekeybr2   r2   r3   r   6  s$   



z_CacheFuncHasher.to_bytesrR   c                 C  s   |  |}|| dS )z6Update the provided hasher with the hash of an object.N)r   rW   )r.   rR   r   r   r2   r2   r3   rW   W  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[Any])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   rd   r   r   r   rH   r   rm   r   r!   r5   r   r   r   r   r   r   r   datetime	isoformatr   r   rW   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	ItemsViewrO   r   tellgetvaluerI   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_datar2   r2   r3   r   \  s  













 











z_CacheFuncHasher._to_bytesr%   )r!   r   rT   rU   r#   r$   rw   )r   r   r#   r   )rR   r   r   r   r#   r$   )	r'   rN   rO   rx   r+   rb   r   rW   r   r2   r2   r2   r3   rV     s    


!rV   c                   @  s   e Zd ZdZdS )r   z<Placeholder class for return values when None is meaningful.N)r'   rN   rO   rx   r2   r2   r2   r3   r     s    r   )NN)rQ   r   rR   r   r!   r   rG   rS   rT   rU   r#   r$   )r   r   r#   r   )r   r   r#   r   )r   r   r#   r   )Hrx   
__future__r   r[   collections.abcr   r   r   r   r   r   r   r   r   r   r}   r   rz   r   enumr   rer   typesr   typingr   r   r	   r
   r   	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   r5   r&   r   r   r   rY   rZ   ry   rE   r   r   r   rV   r   r2   r2   r2   r3   <module>   sj   &
X(


  y