
    &e
e                        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 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 d d
lmZ d dlmZ d dlmZ d dl m!Z!m"Z"m#Z# d dl$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/  ee0          Z1 G d de          Z2	  G d d          Z3 G d de4          Z5 G d de5          Z6 G d de5          Z7d"dZ8de9dej:        fdZ;d eg df         ddfd!Z<dS )#    N)contextmanager)Enum)default_timer)CallableDictOptional)Signal)configruntimesource_utilutil)handle_uncaught_app_exception)
get_logger)ClientState)
ForwardMsg)ScriptCache)	RerunDataScriptRequestsScriptRequestType)ScriptRunContextadd_script_run_ctxget_script_run_ctx)SCRIPT_RUN_WITHOUT_ERRORS_KEYSafeSessionStateSessionState)UploadedFileManager)modified_sys_pathc                   &    e Zd ZdZdZdZdZdZdZdS )ScriptRunnerEventSCRIPT_STARTED!SCRIPT_STOPPED_WITH_COMPILE_ERRORSCRIPT_STOPPED_WITH_SUCCESSSCRIPT_STOPPED_FOR_RERUNSHUTDOWNENQUEUE_FORWARD_MSGN)	__name__
__module____qualname__r    r!   r"   r#   r$   r%        Llib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.pyr   r   5   s@         &N )L% #@  : H 0r*   r   c                       e Zd Zdededededededeee	e         f         fdZ
d	efd
ZddZded	efdZddZd	efdZddZd	efdZded	dfdZddZddZed             Zded	dfdZdededed	dfdZdS )ScriptRunner
session_idmain_script_pathsession_stateuploaded_file_mgrscript_cacheinitial_rerun_data	user_infoc                 "   || _         || _        || _        || _        || _        t          || j                  | _        t                      | _	        | j	        
                    |           t          d          | _        d| _        d| _        dS )a>  Initialize the ScriptRunner.

        (The ScriptRunner won't start executing until start() is called.)

        Parameters
        ----------
        session_id
            The AppSession's id.

        main_script_path
            Path to our main app script.

        uploaded_file_mgr
            The File manager to store the data uploaded by the file_uploader widget.

        script_cache
            A ScriptCache instance.

        user_info
            A dict that contains information about the current user. For now,
            it only contains the user's email address.

            {
                "email": "example@example.com"
            }

            Information about the current user is optionally provided when a
            websocket connection is initialized via the "X-Streamlit-User" header.

        )yield_callbacka  Emitted when a ScriptRunnerEvent occurs.

            This signal is generally emitted on the ScriptRunner's script
            thread (which is *not* the same thread that the ScriptRunner was
            created on).

            Parameters
            ----------
            sender: ScriptRunner
                The sender of the event (this ScriptRunner).

            event : ScriptRunnerEvent

            forward_msg : ForwardMsg | None
                The ForwardMsg to send to the frontend. Set only for the
                ENQUEUE_FORWARD_MSG event.

            exception : BaseException | None
                Our compile error. Set only for the
                SCRIPT_STOPPED_WITH_COMPILE_ERROR event.

            widget_states : streamlit.proto.WidgetStates_pb2.WidgetStates | None
                The ScriptRunner's final WidgetStates. Set only for the
                SHUTDOWN event.
            )docFN)_session_id_main_script_path_uploaded_file_mgr_script_cache
_user_infor   '_maybe_handle_execution_control_request_session_stater   	_requestsrequest_rerunr	   on_event_execing_script_thread)selfr.   r/   r0   r1   r2   r3   r4   s           r+   __init__zScriptRunner.__init__b   s    P &!1"3)#.$*V
 
 
 ())$$%7888
 
 
<  ;?r*   returnc                 *    t          j        |           S Nr   repr_rD   s    r+   __repr__zScriptRunner.__repr__       z$r*   Nc                 8    | j                                          dS )zRequest that the ScriptRunner stop running its script and
        shut down. The ScriptRunner will handle this request when it reaches
        an interrupt point.

        Safe to call from any thread.
        N)r?   request_stoprK   s    r+   rO   zScriptRunner.request_stop   s     	##%%%%%r*   
rerun_datac                 6    | j                             |          S )a  Request that the ScriptRunner interrupt its currently-running
        script and restart it.

        If the ScriptRunner has been stopped, this request can't be honored:
        return False.

        Otherwise, record the request and return True. The ScriptRunner will
        handle the rerun request as soon as it reaches an interrupt point.

        Safe to call from any thread.
        )r?   r@   rD   rP   s     r+   r@   zScriptRunner.request_rerun   s     ~++J777r*   c                     | j         t          d          t          j        | j        d          | _         | j                                          dS )zeStart a new thread to process the ScriptEventQueue.

        This must be called only once.

        Nz ScriptRunner was already startedzScriptRunner.scriptThread)targetname)rC   	Exception	threadingThread_run_script_threadstartrK   s    r+   rZ   zScriptRunner.start   s\     *>???'.*,
 
 
 	!!#####r*   c                 p    |                                  sJ t                      }|t          d          |S )at  Get the ScriptRunContext for the current thread.

        Returns
        -------
        ScriptRunContext
            The ScriptRunContext for the current thread.

        Raises
        ------
        AssertionError
            If called outside of a ScriptRunner thread.
        RuntimeError
            If there is no ScriptRunContext for the current thread.

        NzOScriptRunner thread has a null ScriptRunContext. Something has gone very wrong!)_is_in_script_threadr   RuntimeError)rD   ctxs     r+   _get_script_run_ctxz ScriptRunner._get_script_run_ctx   sH      ((***** "";a   
r*   c                    |                                  sJ t                              d           t          | j        | j        | j        d| j        | j        | j	        d| j
        t          t          j        d                    
  
        }t          t          j                    |           | j                                        }|j        t&          j        k    rH|                     |j                   | j                                        }|j        t&          j        k    H|j        t&          j        k    sJ t1                      }|j        |_        |j        |_        | j                            | t:          j        |           dS )aN  The entry point for the script thread.

        Processes the ScriptRequestQueue, which will at least contain the RERUN
        request that will trigger the first script-run.

        When the ScriptRequestQueue is empty, or when a SHUTDOWN request is
        dequeued, this function will exit and its thread will terminate.
        zBeginning script thread zbrowser.gatherUsageStats)
r.   _enqueuescript_requestsquery_stringr0   r1   r/   page_script_hashr4   gather_usage_stats)eventclient_stateN)r\   _LOGGERdebugr   r8   _enqueue_forward_msgr?   r>   r:   r9   r<   boolr
   
get_optionr   rW   current_threadon_scriptrunner_readytyper   RERUN_run_scriptrP   STOPr   rd   re   rA   sendr   r$   )rD   r^   requestrh   s       r+   rY   zScriptRunner._run_script_thread   sv    ((*****/000 '. N-"5!3o#F$56P$Q$QRR
 
 
 	9355s;;;.6688l/555
 W/000n::<<G l/555 |055555 #}}$'$4!(+(<%)2 	 	
 	
 	
 	
 	
r*   c                 :    | j         t          j                    k    S )z<True if the calling function is running in the script thread)rC   rW   rn   rK   s    r+   r\   z!ScriptRunner._is_in_script_thread-  s    "i&>&@&@@@r*   msgc                     t          j        d          s|                                  | j                            | t
          j        |           dS )zEnqueue a ForwardMsg to our browser queue.
        This private function is called by ScriptRunContext only.

        It may be called from the script thread OR the main thread.
        runner.installTracer)rg   forward_msgN)r
   rm   r=   rA   rt   r   r%   )rD   rw   s     r+   rk   z!ScriptRunner._enqueue_forward_msg1  s`      !788 	;88::: 	)=3 	 	
 	
 	
 	
 	
r*   c                    |                                  sdS | j        sdS | j                                        }|dS |j        t
          j        k    rt          |j                  |j        t
          j	        k    sJ t                      )as  Check our current ScriptRequestState to see if we have a
        pending STOP or RERUN request.

        This function is called every time the app script enqueues a
        ForwardMsg, which means that most `st.foo` commands - which generally
        involve sending a ForwardMsg to the frontend - act as implicit
        yield points in the script's execution.
        N)r\   rB   r?   on_scriptrunner_yieldrp   r   rq   RerunExceptionrP   rs   StopException)rD   ru   s     r+   r=   z4ScriptRunner._maybe_handle_execution_control_requestF  s     ((** 	
 F} 	
 F.6688?F<,222 !3444|055555oor*   c                 l      fdt          t          d          rt          j                   dS dS )z:Install function that runs before each line of the script.c                 0                                      S rH   )r=   )framerg   argrD   trace_callss      r+   r   z1ScriptRunner._install_tracer.<locals>.trace_callsk  s    88:::r*   settraceN)hasattrsysr   )rD   r   s   `@r+   _install_tracerzScriptRunner._install_tracerh  sV    	 	 	 	 	 	
 3
## 	&L%%%%%	& 	&r*   c              #   t   K   | j         rt          d          d| _         	 dV  d| _         dS # d| _         w xY w)zA context for setting the ScriptRunner._execing flag.

        Used by _maybe_handle_execution_control_request to ensure that
        we only handle requests while we're inside an exec() call
        zNested set_execing_flag callTNF)rB   r]   rK   s    r+   _set_execing_flagzScriptRunner._set_execing_flags  sT       = 	?=>>>	"EEE!DMMMEDM!!!!s   . 	7c                 z   |                                  sJ t                              d           t                      }d}t	          j                    j                                         | j        }t          j
        |          }t          |                                          d         }d}d}j        r|                    j        d          }nDj        s;j        r4t!          t#          fd|                                          d          }n|}||d         n|d         }	|                                 }
|
                    j        |	           | j                            | t.          j        |	           	 |r	|d         }n6|}t3                      }j        |j        _        |
                    |           | j                            |          }ni# t<          $ r\}t                              d	|           d
| j        t@          <   | j                            | t.          j!        |           Y d}~dS d}~ww xY wtE          j#        d          r| $                                 d}d
}	 tK          d          }|tL          j'        d<   ||j(        d<   tS          | j                  5  | *                                5  j+        | j        ,                    j+                   |
-                                 t                      |z
  }t]          ||j(                   | j        /                                 d| j        t@          <   ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   na# t`          $ r}|j1        }d
}Y d}~nId}~wtd          $ r d}Y n8t<          $ r,}d
| j        t@          <   |}tg          |           d}Y d}~nd}~ww xY w|rt.          j4        }nt.          j5        }|
j6        r	 ddl7m8}m9} |
                     ||
j:         |t                      |z
             ||          |rtw          |          j<        nd                     n3# t<          $ r&}t                              d|           Y d}~nd}~ww xY w| =                    |
||           n# |rt.          j4        }nt.          j5        }|
j6        r	 ddl7m8}m9} |
                     ||
j:         |t                      |z
             ||          |rtw          |          j<        nd                     n3# t<          $ r&}t                              d|           Y d}~nd}~ww xY w| =                    |
||           w xY wt}          t~                     || @                    |           dS dS )zRun our script.

        Parameters
        ----------
        rerun_data: RerunData
            The RerunData to use.

        zRunning script %sr   Nc                 *    | o| d         j         k    S )N	page_name)r   )prP   s    r+   <lambda>z*ScriptRunner._run_script.<locals>.<lambda>  s    aLQ{^z7K%K r*   re   )rd   re   )rg   re   script_pathzFatal script error: %sF)rg   	exceptionry   __main____file__T)create_page_profile_messageto_microseconds)	exec_time	prep_timeuncaught_exceptionzFailed to create page profile)exc_info)Ar\   ri   rj   timerr   get_instancemedia_file_mgrclear_session_refsr9   r   	get_pageslistvaluesre   getr   nextfilterr_   resetrd   rA   rt   r   r    r   page_not_foundenqueuer;   get_bytecoderV   r>   r   r!   r
   rm   r   _new_moduler   modules__dict__r   r   widget_stateson_script_will_rerunon_script_startexecmaybe_check_serializabler}   rP   r~   r   r#   r"   rf   streamlit.runtime.metrics_utilr   r   tracked_commandsrp   r&   _on_script_finished_log_if_error_clean_problem_modulesrr   )rD   rP   
start_timer   r/   pagesmain_page_infocurrent_page_infor   re   r^   r   rw   codeexrerun_exception_datapremature_stopmoduleefinished_eventr   r   s    `                    r+   rr   zScriptRunner._run_script  s    ((*****):666!GG
	 	-@@BBB1%&677ellnn--a0 !& 	/ %		**Et L L, 	/1E 	/
 !%
 MLLLLLNN  
! 
! !/ !, 011 23 	 &&((		#0- 	 	
 	
 	

 	#2- 	 	
 	
 	
	  !/>. !ll/9/C",C   %22;??DD 		 		 		MM2B777AFD =>M'I    
 FFFFF		 344 	#  """ 59  %U	J !,,F '-CK
# +6FOJ'"4#9:: 	J 	JD<R<R<T<T 	J 	J+7'<<Z=UVVV##%%%!GGj0	T6?+++#<<>>>EI#$AB	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J  	# 	# 	##$< 
 #NNNNNN 	" 	" 	" "NNN 	" 	" 	"AFD =>!#)*<===!NNNNNN		" $ O!2!K!2!N% PP        KK330&5oegg
6J&K&K&5oi&@&@10&t4F/G/G/P/P!%  	 	 	 	 ! P P P MM"ABMOOOOOOOOP $$S..IIII9 $ O!2!K!2!N% PP        KK330&5oegg
6J&K&K&5oi&@&@10&t4F/G/G/P/P!%  	 	 	 	 ! P P P MM"ABMOOOOOOOOP $$S..IIII 	,---+122222 ,+s   AG   
I*AII6<M? 2M3B	MM3M 	 M3#M 	$M3'M? 3M77M? :M7;M? >R5 ?
O		NR5 O&R5 (	O1"OR5 OR5 A&Q* *
R4RR5#VA&U ?V 
U0
U+&V+U00Vr^   rg   r   c                 (   |s| j                             |j                   | j                            | |           t          j                    j                                         t          j
        d          rt          j        d           dS dS )zCalled when our script finishes executing, even if it finished
        early with an exception. We perform post-run cleanup here.
        )rg   zrunner.postScriptGC   N)r>   on_script_finishedwidget_ids_this_runrA   rt   r   r   r   remove_orphaned_filesr
   rm   gccollect)rD   r^   rg   r   s       r+   r   z ScriptRunner._on_script_finishedS  s      	L2233JKKK 	4u--- 	-CCEEE 233 	JqMMMMM	 	r*   rF   N)r&   r'   r(   strr   r   r   r   r   r   rE   rL   rO   rl   r@   rZ   r   r_   rY   r\   r   rk   r=   r   r   r   rr   r   r   r)   r*   r+   r-   r-   a   s       V?V? V? $	V?
 /V? "V? &V? Xc]*+V? V? V? V?p #        & & & &8	 8d 8 8 8 8$ $ $ $%5    4.
 .
 .
 .
`Ad A A A A

 
t 
 
 
 
*       D	& 	& 	& 	& " " ^"O3i O3D O3 O3 O3 O3b#,=OS	     r*   r-   c                       e Zd ZdZdS )ScriptControlExceptionz Base exception for ScriptRunner.Nr&   r'   r(   __doc__r)   r*   r+   r   r   m  s        **Dr*   r   c                       e Zd ZdZdS )r~   z1Silently stop the execution of the user's script.Nr   r)   r*   r+   r~   r~   s  s        ;;Dr*   r~   c                   *    e Zd ZdZdefdZdefdZdS )r}   z*Silently stop and rerun the user's script.rP   c                     || _         dS )zConstruct a RerunException

        Parameters
        ----------
        rerun_data : RerunData
            The RerunData that should be used to rerun the script
        N)rP   rR   s     r+   rE   zRerunException.__init__|  s     %r*   rF   c                 *    t          j        |           S rH   rI   rK   s    r+   rL   zRerunException.__repr__  rM   r*   N)r&   r'   r(   r   r   rE   r   rL   r)   r*   r+   r}   r}   y  sP        44%9 % % % % #            r*   r}   rF   c                  .   dt           j        v r=	 t           j        d         } | j                                         n# t          $ r Y nw xY wdt           j        v r;	 t           j        d         }|                    d           dS # t          $ r Y dS w xY wdS )z;Some modules are stateful, so we have to clear their state.keraszmatplotlib.pyplotallN)r   r   backendclear_sessionrV   close)r   plts     r+   r   r     s     #+	K(EM'')))) 	 	 	D	 ck))	+12CIIe 	 	 	DD		 *)s!   +< 
A	A	'B 
BBrU   c                 *    t          j        |           S )z(Create a new module with the given name.)types
ModuleType)rU   s    r+   r   r     s    D!!!r*   fnc                     	  |              d S # t           $ r%}t                              |           Y d }~d S d }~ww xY wrH   )rV   ri   warning)r   r   s     r+   r   r     sY    
   s   
 
=8=r   )=r   r   rW   r   
contextlibr   enumr   timeitr   r   typingr   r   r   blinkerr	   	streamlitr
   r   r   r   streamlit.error_utilr   streamlit.loggerr   streamlit.proto.ClientState_pb2r   streamlit.proto.ForwardMsg_pb2r   +streamlit.runtime.scriptrunner.script_cacher   .streamlit.runtime.scriptrunner.script_requestsr   r   r   1streamlit.runtime.scriptrunner.script_run_contextr   r   r   streamlit.runtime.stater   r   r   'streamlit.runtime.uploaded_file_managerr   *streamlit.vendor.ipython.modified_sys_pathr   r&   ri   r   r-   BaseExceptionr   r~   r}   r   r   r   r   r   r)   r*   r+   <module>r      s,   
			 



      % % % % % %       ) ) ) ) ) ) + + + + + + + + + +       8 8 8 8 8 8 8 8 8 8 8 8 > > > > > > ' ' ' ' ' ' 7 7 7 7 7 7 5 5 5 5 5 5 C C C C C C         
         
         
 H G G G G G H H H H H H
*X

0 0 0 0 0 0 0 06"I I I I I I I IX	 	 	 	 	] 	 	 		 	 	 	 	* 	 	 	         +      "   ("c "e. " " " "hr4x( T      r*   