
    &elH                       d dl m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	m
Z
mZmZ d dlmZ d dlmZmZ d dlZd dlmZmZ d dlmZ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# d dl$m%Z%m&Z& d dl'm(Z( d dl)m*Z* e	rd dl+m,Z,  ee-          Z.e G d de                      Z/ ed           G d d                      Z0 ed           G d d                      Z1 ed           G d d                      Z2 ed           G d d                      Z3ee2e3f         Z4	 e G d d                      Z5e G d  d!                      Z6	  G d" d#ej7                  Z8d0d+Z9d1d/Z:dS )2    )annotationsN)	dataclass)TYPE_CHECKINGAnyIteratorUnion)Message)Protocolruntime_checkable)runtimeutil)NONWIDGET_ELEMENTSWIDGETS)
get_logger)Block)CachedStFunctionWarningCacheReplayClosureError)	CacheType)update_hash)ScriptRunContextget_script_run_ctx)WidgetMetadata)HASHLIB_KWARGSDeltaGeneratorc                      e Zd ZU ded<   dS )WidgetstridN__name__
__module____qualname____annotations__     Olib/python3.11/site-packages/streamlit/runtime/caching/cached_message_replay.pyr   r   3   s         GGGGGr&   r   T)frozenc                  2    e Zd ZU dZded<   ded<   ded<   dS )	WidgetMsgMetadatazEverything needed for replaying a widget and treating it as an implicit
    argument to a cached function, beyond what is stored for all elements.
    r   	widget_idr   widget_valueWidgetMetadata[Any]metadataNr!   r"   r#   __doc__r$   r%   r&   r'   r*   r*   8   s?           NNN!!!!!!r&   r*   c                  .    e Zd ZU ded<   ded<   ded<   dS )MediaMsgDatabytes | strmediar   mimetypemedia_idNr    r%   r&   r'   r2   r2   C   s.         MMMMMMMMr&   r2   c                  X    e Zd ZU dZded<   ded<   ded<   ded<   dZd	ed
<   dZded<   dS )ElementMsgDatazAn element's message and related metadata for
    replaying that element's function call.

    widget_metadata is filled in if and only if this element is a widget.
    media_data is filled in iff this is a media element (image, audio, video).
    r   
delta_typer	   messageid_of_dg_called_onreturned_dgs_idNzWidgetMsgMetadata | Nonewidget_metadatazlist[MediaMsgData] | None
media_data)r!   r"   r#   r0   r$   r=   r>   r%   r&   r'   r8   r8   J   sm           OOO04O4444,0J000000r&   r8   c                  .    e Zd ZU ded<   ded<   ded<   dS )BlockMsgDatar   r:   r   r;   r<   Nr    r%   r&   r'   r@   r@   [   s3         NNNr&   r@   c                  <    e Zd ZU dZded<   ded<   ded<   ded<   d	S )
CachedResultz}The full results of calling a cache-decorated function, enough to
    replay the st functions called while executing it.
    r   valuezlist[MsgData]messagesr   main_id
sidebar_idNr/   r%   r&   r'   rB   rB      sC           JJJLLLOOOOOr&   rB   c                  0    e Zd ZU dZded<   ded<   ddZdS )MultiCacheResultszWidgets called by a cache-decorated function, and a mapping of the
    widget-derived cache key to the final results of executing the function.
    zset[str]
widget_idszdict[str, CachedResult]resultsctxr   
cache_typer   returnr   c                v    |j         fdt          | j                  D             }t          ||          }|S )Nc                ,    g | ]}|v ||         fS r%   r%   ).0widstates     r'   
<listcomp>z<MultiCacheResults.get_current_widget_key.<locals>.<listcomp>   s.     
 
 
"%C5LLS%*LLLr&   )session_statesortedrI   _make_widget_key)selfrK   rL   widget_values
widget_keyrR   s        @r'   get_current_widget_keyz(MultiCacheResults.get_current_widget_key   sV     !
 
 
 
)/)@)@
 
 
 &mZ@@
r&   N)rK   r   rL   r   rM   r   )r!   r"   r#   r0   r$   rZ   r%   r&   r'   rH   rH      sN           $$$$     r&   rH   c                      e Zd ZdZd,dZd-dZej        d.d            Zd/dZ	d0dZ
d1dZd2dZd3d#Zej        d4d$            Zd5d(Zd6d*Zd+S )7CachedMessageReplayContextzA utility for storing messages generated by `st` commands called inside
    a cached function.

    Data is stored in a thread-local object, so it's safe to use an instance
    of this class across multiple threads.
    rL   r   c                    g | _         d| _        g | _        g | _        g | _        d | _        g | _        || _        d| _        d S )Nr   )	_cached_func_stack_suppress_st_function_warning_cached_message_stack_seen_dg_stack_most_recent_messages_registered_metadata_media_data_cache_type_allow_widgets)rW   rL   s     r'   __init__z#CachedMessageReplayContext.__init__   sP    <>-.*:<".046"@D!/1%#$r&   rM   r   c                *    t          j        |           S N)r   repr_rW   s    r'   __repr__z#CachedMessageReplayContext.__repr__   s    z$r&   functypes.FunctionTypeallow_widgetsboolIterator[None]c              #    K   | j                             |           | j                            g            | j                            t	                                 |r| xj        dz  c_        	 dV  | j                                          | j                                        | _        | j                                         |r| xj        dz  c_        dS dS # | j                                          | j                                        | _        | j                                         |r| xj        dz  c_        w xY w)zContext manager that should wrap the invocation of a cached function.
        It allows us to track any `st.foo` messages that are generated from inside the function
        for playback during cache retrieval.
           N)r^   appendr`   ra   setrf   poprb   )rW   rm   ro   s      r'   calling_cached_functionz2CachedMessageReplayContext.calling_cached_function   sT      	&&t,,,"))"---""355))) 	%1$	)EEE#''))))-)C)G)G)I)ID&##%%% )##q(####) ) #''))))-)C)G)G)I)ID&##%%% )##q(######s   0C A$D>r9   element_protor	   invoked_dg_id
used_dg_idreturned_dg_idNonec                6   t          j                    sdS t          | j                  dk    r|                     ||          }t          |t                    rN|j        rG|j        }| j        s!t          
                    d           t          t          |d| j                  }nd}| j        }	t          ||||||	          }
| j        D ] }| j        s||                    |
           !g | _        d| _        | j        D ]}|                    |           dS )zRecord the element protobuf as having been produced during any currently
        executing cached functions, so they can be replayed any time the function's
        execution is skipped because they're in the cache.
        Nrs   zRTrying to save widget message that wasn't registered. This should not be possible.)r.   )r   existslenr`   select_dg_to_save
isinstancer   r   rc   _LOGGERerrorAttributeErrorr*   rd   r8   rf   rt   ra   add)rW   r9   rx   ry   rz   r{   
id_to_saverQ   widget_metar>   element_msg_datamsgsss                r'   save_element_messagez/CachedMessageReplayContext.save_element_message  sb    ~ 	Ft)**a////zJJJ -00 #]5E ##&0 )MMl   )(/(A   #)J-    2 2 2& 2+*=KK 0111 $(!$ 	" 	"AEE.!!!!	" 	"r&   block_protor   c                    |                      ||          }| j        D ]&}|                    t          |||                     '| j        D ]}|                    |           d S ri   )r   r`   rt   r@   ra   r   )rW   r   ry   rz   r{   r   r   r   s           r'   save_block_messagez-CachedMessageReplayContext.save_block_messageE  s     ++M:FF
. 	O 	ODKK[*nMMNNNN$ 	" 	"AEE.!!!!	" 	"r&   
invoked_idacting_on_idc                X    t          | j                  dk    r|| j        d         v r|S |S )a  Select the id of the DG that this message should be invoked on
        during message replay.

        See Note [DeltaGenerator method invocation]

        invoked_id is the DG the st function was called on, usually `st._main`.
        acting_on_id is the DG the st function ultimately runs on, which may be different
        if the invoked DG delegated to another one because it was in a `with` block.
        r   )r   ra   )rW   r   r   s      r'   r   z,CachedMessageReplayContext.select_dg_to_saveR  s9     t"##a''LD<OPR<S,S,Sr&   r.   r-   c                    || _         d S ri   )rc   )rW   r.   s     r'   save_widget_metadataz/CachedMessageReplayContext.save_widget_metadataa  s    $,!!!r&   
image_datar3   r5   image_idc                X    | j                             t          |||                     d S ri   )rd   rt   r2   )rW   r   r5   r   s       r'   save_image_dataz*CachedMessageReplayContext.save_image_datad  s-     	Z8 L LMMMMMr&   c              #     K   | xj         dz  c_         	 d V  | xj         dz  c_         | j         dk    sJ d S # | xj         dz  c_         | j         dk    sJ w xY w)Nrs   r   )r_   rk   s    r'   #suppress_cached_st_function_warningz>CachedMessageReplayContext.suppress_cached_st_function_warningi  s      **a/**	;EEE..!3..5:::::: ..!3..5::::::::s	   7 Adg'DeltaGenerator'st_func_namec                    |t           v rdS |t          v r| j        dk    rdS t          | j                  dk    r1| j        dk    r(| j        d         }|                     |||           dS dS dS )a  If appropriate, warn about calling st.foo inside @memo.

        DeltaGenerator's @_with_element and @_widget wrappers use this to warn
        the user when they're calling st.foo() from within a function that is
        wrapped in @st.cache.

        Parameters
        ----------
        dg : DeltaGenerator
            The DeltaGenerator to publish the warning to.

        st_func_name : str
            The name of the Streamlit function that was called.

        Nr   r   )r   r   rf   r   r^   r_    _show_cached_st_function_warning)rW   r   r   cached_funcs       r'   %maybe_show_cached_st_function_warningz@CachedMessageReplayContext.maybe_show_cached_st_function_warningr  s    . ---F7""t':Q'>'>Ft&''!++0RVW0W0W1"5K11"lKPPPPP ,+0W0Wr&   r   c                    |                                  5  t          | j        ||          }|                    |           d d d            d S # 1 swxY w Y   d S ri   )r   r   re   	exception)rW   r   r   r   es        r'   r   z;CachedMessageReplayContext._show_cached_st_function_warning  s     5577 	 	'(8,TTALLOOO	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   ,AAAN)rL   r   )rM   r   )rm   rn   ro   rp   rM   rq   )r9   r   rx   r	   ry   r   rz   r   r{   r   rM   r|   )
r   r   ry   r   rz   r   r{   r   rM   r|   )r   r   r   r   rM   r   )r.   r-   rM   r|   )r   r3   r5   r   r   r   rM   r|   )rM   rq   )r   r   r   r   rM   r|   )r   r   r   r   r   rn   rM   r|   )r!   r"   r#   r0   rg   rl   
contextlibcontextmanagerrw   r   r   r   r   r   r   r   r   r%   r&   r'   r\   r\      s$        	% 	% 	% 	%        ) ) ) )*5" 5" 5" 5"n" " " "   - - - -N N N N
 ; ; ; ;Q Q Q Q@
 
 
 
 
 
r&   r\   resultrL   r   r   rn   rM   r|   c                   ddl m} ddlm} i }t          j        || j        <   t          j        || j        <   t                      }	 | j
        D ]}t          |t                    r|j         ||j        j        |d|j                   |j        F|j        D ]>}t#          j                    j                            |j        |j        |j                   ?||j                 }	|	                    |j        |j                  }
t          |
|          r
|
||j        <   t          |t8                    r1||j                 }	|	                    |j                  }|||j        <   dS # t<          $ r t?          ||          w xY w)a  Replay the st element function calls that happened when executing a
    cache-decorated function.

    When a cache function is executed, we record the element and block messages
    produced, and use those to reproduce the DeltaGenerator calls, so the elements
    will appear in the web app even when execution of the function is skipped
    because the result was cached.

    To make this work, for each st function call we record an identifier for the
    DG it was effectively called on (see Note [DeltaGenerator method invocation]).
    We also record the identifier for each DG returned by an st function call, if
    it returns one. Then, for each recorded message, we get the current DG instance
    corresponding to the DG the message was originally called on, and enqueue the
    message using that, recording any new DGs produced in case a later st function
    call is on one of them.
    r   r   )register_widget_from_metadataN) streamlit.delta_generatorr   streamlit.runtime.state.widgetsr   st_mainrE   sidebarrF   r   rD   r   r8   r=   r.   r9   r>   r   get_instancemedia_file_mgrr   r4   r5   r6   r;   _enqueuer:   r<   r@   _blockKeyErrorr   )r   rL   r   r   r   returned_dgsrK   msgdatar   maybe_dgnew_dgs               r'   replay_cached_messagesr     s   & 988888MMMMMM /1L#%8L &(jL"#


C?? 	; 	;C#~.. ;&211+4	   >- #  ,..=AA Jt}    "#"89;;s~s{CCh77 A8@L!45C.. ;!#"893;//4:S01+	; 	;,  ? ? ?%j+>>>?s   D E( (Fwidgetslist[tuple[str, Any]]r   c                    t          j        di t          }| D ]}t          |||           |                                S )zGenerate a key for the given list of widgets used in a cache-decorated function.

    Keys are generated by hashing the IDs and values of the widgets in the given list.
    md5)r   )hashlibnewr   r   	hexdigest)r   rL   func_hasherwidget_id_vals       r'   rV   rV     sO    
 +66~66K  < <M;
;;;;  """r&   )r   rB   rL   r   r   rn   rM   r|   )r   r   rL   r   rM   r   );
__future__r   r   r   	threadingtypesdataclassesr   typingr   r   r   r   google.protobuf.messager	   typing_extensionsr
   r   	streamlitr   r   r   streamlit.elementsr   r   streamlit.loggerr   streamlit.proto.Block_pb2r   &streamlit.runtime.caching.cache_errorsr   r   $streamlit.runtime.caching.cache_typer   !streamlit.runtime.caching.hashingr   1streamlit.runtime.scriptrunner.script_run_contextr   r   streamlit.runtime.state.commonr   streamlit.utilr   r   r   r!   r   r   r*   r2   r8   r@   MsgDatarB   rH   localr\   r   rV   r%   r&   r'   <module>r      s   # " " " " "           ! ! ! ! ! ! 6 6 6 6 6 6 6 6 6 6 6 6 + + + + + + 9 9 9 9 9 9 9 9     # # # # # # # # : : : : : : : : ' ' ' ' ' ' + + + + + +        ; : : : : : 9 9 9 9 9 9        : 9 9 9 9 9 ) ) ) ) ) ) 9888888
*X

     X    $" " " " " " " " $        $1 1 1 1 1 1 1 1  $        ,
-6r                2>z z z z z z z zz4? 4? 4? 4?n	# 	# 	# 	# 	# 	#r&   