
    gq                       U 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	 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 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! d dl"m#Z#m$Z$ d dl%m&Z& d dl'm(Z(m)Z) d dl*m+Z+m,Z,m-Z- d dl.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5 erd dl6m7Z7 d dl8m9Z9 d dl%m&Z& d dl:m;Z;  ee<      Z=de>d<    G d de	      Z?	  G d d      Z@ddZAd dZBy)!    )annotationsN)contextmanager)Enum)default_timer)TYPE_CHECKINGCallableFinal)Signal)configruntimeutil)FragmentStorageKeyError)
get_logger)ClientState)
ForwardMsg)create_page_profile_messageto_microseconds)exec_func_with_error_handlingmodified_sys_path)ScriptCache)RerunExceptionStopException)	RerunDataScriptRequestsScriptRequestType)ScriptRunContextadd_script_run_ctxget_script_run_ctx)SCRIPT_RUN_WITHOUT_ERRORS_KEYSafeSessionStateSessionState)FragmentStorage)PagesManager)UploadedFileManagerr	   _LOGGERc                  (    e Zd ZdZdZdZdZdZdZdZ	y)	ScriptRunnerEventSCRIPT_STARTED!SCRIPT_STOPPED_WITH_COMPILE_ERRORSCRIPT_STOPPED_WITH_SUCCESSSCRIPT_STOPPED_FOR_RERUNFRAGMENT_STOPPED_WITH_SUCCESSSHUTDOWNENQUEUE_FORWARD_MSGN)
__name__
__module____qualname__r(   r)   r*   r+   r,   r-   r.        a/var/www/openai/venv/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/script_runner.pyr'   r'   G   s;     &N )L% #@  : %D! H 0r3   r'   c                      e Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZddZddZddZddZddZ	ddZ
dd	Zdd
Zed        ZddZ	 	 	 	 	 	 	 	 ddZddZy)ScriptRunnerc
                0   || _         || _        t        || j                        | _        || _        || _        || _        || _        |	| _	        t               | _        | j                  j                  |       t        d      | _        d| _        d| _        y)a1  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.

        session_state
            The AppSession's SessionState instance.

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

        script_cache
            A ScriptCache instance.

        initial_rerun_data
            RerunData to initialize this ScriptRunner with.

        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.

        fragment_storage
            The AppSession's FragmentStorage instance.
        )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_pathr    '_maybe_handle_execution_control_request_session_state_uploaded_file_mgr_script_cache
_user_info_fragment_storage_pages_managerr   	_requestsrequest_rerunr
   on_event_execing_script_thread)
self
session_idmain_script_pathsession_stateuploaded_file_mgrscript_cacheinitial_rerun_data	user_infofragment_storagepages_managers
             r4   __init__zScriptRunner.__init__x   s    d &!1.$*V*V
 #4)#!1+')$$%78
<  8<r3   c                ,    t        j                  |       S N)r   repr_rH   s    r4   __repr__zScriptRunner.__repr__   s    zz$r3   c                8    | j                   j                          y)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)rC   request_stoprV   s    r4   rY   zScriptRunner.request_stop   s     	##%r3   c                8    | j                   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.
        )rC   rD   )rH   
rerun_datas     r4   rD   zScriptRunner.request_rerun   s     ~~++J77r3   c                    | j                   t        d      t        j                  | j                  d      | _         | j                   j                          y)zeStart a new thread to process the ScriptEventQueue.

        This must be called only once.

        Nz ScriptRunner was already startedzScriptRunner.scriptThread)targetname)rG   	Exception	threadingThread_run_script_threadstartrV   s    r4   rc   zScriptRunner.start   sO     *>??'..**,
 	!!#r3   c                X    | j                         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.

        zOScriptRunner thread has a null ScriptRunContext. Something has gone very wrong!)_is_in_script_threadr   RuntimeError)rH   ctxs     r4   _get_script_run_ctxz ScriptRunner._get_script_run_ctx  s<      ((*** ";1  
r3   c                   | j                         sJ t        j                  d       t        | j                  | j
                  | j                  d| j                  | j                  | j                  | j                  t        t        j                  d            | j                  | j                        }t!        t#        j$                         |       | j                  j'                         }|j(                  t*        j,                  k(  rS| j/                  |j0                         | j                  j'                         }|j(                  t*        j,                  k(  rS|j(                  t*        j2                  k(  sJ t5               }|j6                  |_        |j8                  |_        | j:                  j=                  | t>        j@                  |       y)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)rI   _enqueuescript_requestsquery_stringrK   rL   rJ   rO   gather_usage_statsrP   rQ   )eventclient_stateN)!re   r%   debugr   r:   _enqueue_forward_msgrC   r=   r>   r;   r@   boolr   
get_optionrA   rB   r   r`   current_threadon_scriptrunner_readytyper   RERUN_run_scriptr[   STOPr   rm   page_script_hashrE   sendr'   r-   )rH   rg   requestrp   s       r4   rb   zScriptRunner._run_script_thread  so    ((***/0 ''.. NN--"55!33oo#F$5$56P$QR!33--
 	9335s;..668ll/555
 W//0nn::<G ll/555 ||055555 #}$'$4$4!(+(<(<%)22 	 	
r3   c                D    | j                   t        j                         k(  S )z<True if the calling function is running in the script thread)rG   r`   ru   rV   s    r4   re   z!ScriptRunner._is_in_script_threadP  s    ""i&>&>&@@@r3   c                |    | j                          | j                  j                  | t        j                  |       y)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.
        )ro   forward_msgN)r<   rE   r|   r'   r.   )rH   msgs     r4   rr   z!ScriptRunner._enqueue_forward_msgT  s7     	446 	)==3 	 	
r3   c                .   | j                         sy| j                  sy| j                  j                         }|y|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)re   rF   rC   on_scriptrunner_yieldrw   r   rx   r   r[   rz   r   )rH   r}   s     r4   r<   z4ScriptRunner._maybe_handle_execution_control_requestd  s     ((*
 }}
 ..668?<<,222 !3!344||055555or3   c              #  x   K   | j                   rt        d      d| _         	 d d| _         y# d| _         w xY w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)rF   rf   rV   s    r4   _set_execing_flagzScriptRunner._set_execing_flag  s8      ===>>	"!DMEDMs   :. :	7:c           
          j                         sJ 	 t        j                  d|       t               }d}|j                  s,t        j                         j                  j                           j                  j                  |j                  |j                          j                  j                  |j                  |j                        } j                  j                         }||d   n|d   } j                         }|j                  }||k7  rtt!               }	|j"                  C|j"                  j$                  -|j"                  j$                  D 
ch c]  }
|
j&                   }	}
 j(                  j+                  |	       t-        |j                        }|j/                  |j0                  ||        j2                  j5                   t6        j8                  || j                  j;                                	 ||d   }n;|d   }t=               }|j                  |j>                  _        |jA                  |        jB                  jE                  |      } jM                  d      }|tN        jP                  d<   ||jR                  d<   ||||f fd	}t               |z
  }tU        ||      \  }}}}}| j(                  tH        <   |rt6        jV                  }n-|j                  rt6        jX                  }nt6        jZ                  }|j\                  r]	 |jA                  t_        |j`                  tc        t               |z
        tc        |      |rte        |      jf                  nd              ji                  |||       tk        tl               ||}nyc c}
w # tF        $ r`}t        j                  d|	       d
 j(                  tH        <    j2                  j5                   t6        jJ                  |       Y d}~yd}~ww xY w# tF        $ r!}t        j                  d|	       Y d}~d}~ww xY w)zRun our script.

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

        zRunning script %sr   Nr{   )rm   r{   fragment_ids_this_run)ro   r{   r   pagesscript_pathzFatal script error)exc_infoF)ro   	exception__main____file__c           	        t        j                        5  j                         5  |j                  %j                  j                  |j                         |j                          |j                  r5|j                  D ]%  }	 j                  j                  |      } |        ' n<t#        | |j$                         j                  j'                  |j(                         j                  j+                          j-                          d d d        d d d        y # t        $ r( |j                  st        j                  d| d       Y t        t        f$ r}|d }~wt         $ r Y w xY w# 1 sw Y   dxY w# 1 sw Y   y xY w)NzCouldn't find fragment with id z. This can happen if the fragment does not exist anymore when this request is processed, for example because a full app rerun happened that did not register the fragment. Usually this doesn't happen or no action is required, so its mainly for debugging.)new_fragment_ids)r   r;   r   widget_statesr=   on_script_will_rerunon_script_startfragment_id_queuerA   getr   is_auto_rerunr%   warningr   r   r_   exec__dict__clearr   maybe_check_serializabler<   )codemodulerg   r[   fragment_idwrapped_fragmenterH   s          r4   code_to_execz.ScriptRunner._run_script.<locals>.code_to_exec  sl   %d&<&<=**, "//;++@@&44 '')!33+5+G+GK$%373I3I3M3M$/4" 0 !1 2 ,HP T6??3..44-0-A-A 5  ''@@B@@Bu - >=& $; & (2'?'?$+OO*I+ WR )R%& %3M#B ( '(#, %
 !%%W -, >=s`   F AE4"D"(A)E4F ".E1	E4E1	 E"	"E1	.E40E1	1E44E=	9F  F	)commands	exec_time	prep_timeuncaught_exceptionzFailed to create page profile)7re   r%   rq   timerr   r   get_instancemedia_file_mgrclear_session_refsrB   set_script_intentr{   	page_nameget_initial_active_scriptget_main_pagerh   setr   widgetsidr=   on_script_finishedlistresetrm   rE   r|   r'   r(   	get_pagesr   page_not_foundenqueuer?   get_bytecoder_   r   r)   _new_modulesysmodulesr   r   r+   r,   r*   rn   r   tracked_commandsr   rw   r/   _on_script_finished_log_if_error_clean_problem_modules)rH   r[   
start_timer   active_scriptmain_page_infor{   rg   previous_page_script_hash
widget_idswr   r   r   r   exr   r   _run_without_errorsrerun_exception_datapremature_stopr   finished_events   `                       r4   ry   zScriptRunner._run_script  s    ((*** MM-z: %J I//
 $$&55HHJ11++Z-A-A !//II++Z-A-AM "00>>@N !, 01#$67  **,C ),(<(<%(,<< (+u
 ,,8"0088D0:0H0H0P0P!Q0P1!$$0PJ!Q##66zB$()E)E$F!II'44!1&;   MM'66!1&;))335   ,"/">K #1"?K %,C3=3G3GC&&0KK$))66{C& %%j1F '-CKK
# +6FOOJ'"&v3: =C~ *,I .lC@"$" BTD =># "3!K!K--!2!P!P!2!N!N%%PKK3%(%9%9&5eg
6J&K&5i&@ $6 !%%7 8 A A%)	  $$S..I 01#/1
O X "RT  	2R@EJ##$AB""+MM  # 
 	H ! P MM"ABMOOPs9   N$AN) AP )	P2APP	P?P::P?c                :   |s%| j                   j                  |j                         | j                  j	                  | |       t        j                         j                  j                          t        j                  d      rt        j                  d       yy)zCalled when our script finishes executing, even if it finished
        early with an exception. We perform post-run cleanup here.
        )ro   zrunner.postScriptGC   N)r=   r   widget_ids_this_runrE   r|   r   r   r   remove_orphaned_filesr   rt   gccollect)rH   rg   ro   r   s       r4   r   z ScriptRunner._on_script_finished  sx     2233J3JK 	4u- 	--CCE 23JJqM 4r3   c                ,    t        j                  |      S )z(Create a new module with the given name.)types
ModuleType)rH   r^   s     r4   r   zScriptRunner._new_module  s    %%r3   N)rI   strrJ   r   rK   r!   rL   r$   rM   r   rN   r   rO   zdict[str, str | bool | None]rP   r"   rQ   r#   )returnr   r   None)r[   r   r   rs   )r   r   )r   rs   )r   r   r   r   )r[   r   r   r   )rg   r   ro   r'   r   rs   r   r   )r^   r   r   ztypes.ModuleType)r/   r0   r1   rR   rW   rY   rD   rc   rh   rb   re   rr   r<   r   r   ry   r   r   r2   r3   r4   r6   r6   w   s    a<a< a< $	a<
 /a< "a< &a< 0a< *a< $a<F &8$6/
bA
  D " "tl#,=OS	2&r3   r6   c                 0   dt         j                  v r.	 t         j                  d   } | j                  j                          dt         j                  v r&	 t         j                  d   }|j                  d       yy# t        $ r Y Dw xY w# t        $ r Y yw xY w)z;Some modules are stateful, so we have to clear their state.keraszmatplotlib.pyplotallN)r   r   backendclear_sessionr_   close)r   plts     r4   r   r     s     #++	KK(EMM'')
 ckk)	++12CIIe *	  		  		s#   -A: $B	 :	BB		BBc                j    	  |         y # t         $ r}t        j                  |       Y d }~y d }~ww xY wrT   )r_   r%   r   )fnr   s     r4   r   r     s+    
 s   
 	2-2r   )r   zCallable[[], None]r   r   )C
__future__r   r   r   r`   r   
contextlibr   enumr   timeitr   r   typingr   r   r	   blinkerr
   	streamlitr   r   r   streamlit.errorsr   streamlit.loggerr   streamlit.proto.ClientState_pb2r   streamlit.proto.ForwardMsg_pb2r   streamlit.runtime.metrics_utilr   r   (streamlit.runtime.scriptrunner.exec_coder   r   +streamlit.runtime.scriptrunner.script_cacher   /streamlit.runtime.scriptrunner_utils.exceptionsr   r   4streamlit.runtime.scriptrunner_utils.script_requestsr   r   r   7streamlit.runtime.scriptrunner_utils.script_run_contextr   r   r   streamlit.runtime.stater   r    r!   streamlit.runtime.fragmentr"   streamlit.runtime.pages_managerr#   'streamlit.runtime.uploaded_file_managerr$   r/   r%   __annotations__r'   r6   r   r   r2   r3   r4   <module>r      s    # 	 
   %  ) 1 1  + + 4 ' 7 5 D 
 
  :<GKH% %0 0>"o& o&d,r3   