o
    hx                     @  s  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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% d dl&m'Z'm(Z( d dl)m*Z* d dl+m,Z,m-Z- d dl.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8m9Z9 d dl:m;Z; erd dl<m=Z= d dl)m*Z* d dl>m?Z? ee@ZAdeBd< G dd de	ZC	 d*ddZDG d d! d!ZEd+d$d%ZFd,d(d)ZGdS )-    )annotationsN)contextmanager)Enum)default_timer)TYPE_CHECKINGCallableFinalLiteralcast)Signal)configruntimeutil)FragmentStorageKeyError)
get_logger)ClientState)
ForwardMsg)create_page_profile_messageto_microseconds)PagesManager)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)page_sort_key)FragmentStorage)UploadedFileManagerr   _LOGGERc                   @  s(   e Zd 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FRAGMENT_STOPPED_WITH_SUCCESSSHUTDOWNENQUEUE_FORWARD_MSGN)
__name__
__module____qualname__r)   r*   r+   r,   r-   r.   r/    r3   r3   `/var/www/vscode/kcb/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.pyr(   H   s    r(   main_script_pathstrc           
        s   ddl m} ddlm}m} ddlm ||  }|jd   	d}t
dd |D td	}|d
d}|g fdd|D  }tddu rKdnd}|td||dd}	|	j|jkrd|	  t d S )Nr   )Path)PageType_navigation)StreamlitPagepagesz*.pyc                 S  s   g | ]
}|j d r|qS )z.py)nameendswith.0pager3   r3   r4   
<listcomp>   s    z_mpa_v1.<locals>.<listcomp>)keyT)defaultc                   s   g | ]	} |j  qS r3   )r<   r>   PAGES_FOLDERr:   r3   r4   rA      s    zclient.showSidebarNavigationFhiddensidebarzlist[PageType])positionexpanded)pathlibr7   streamlit.commands.navigationr8   r9   streamlit.navigation.pager:   resolveparentglobsortedr$   r   
get_optionr
   _pagerunr   )
r5   r7   r8   r9   MAIN_SCRIPT_PATHr;   	main_page	all_pagesrH   r@   r3   rD   r4   _mpa_v1|   s4   

rW   c                   @  s   e 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>d#d$Z	dAd%d&Z
dBd)d*Zd>d+d,Zed-d. ZdCd/d0ZdDd5d6ZdEd9d:Zd;S )FScriptRunner
session_idr6   r5   session_stater#   uploaded_file_mgrr&   script_cacher   initial_rerun_datar   	user_infodict[str, str | bool | None]fragment_storager%   pages_managerr   c
           
      C  sj   || _ || _t|| jd| _|| _|| _|| _|| _|	| _	t
 | _| j| tdd| _d| _d| _dS )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)
selfrY   r5   rZ   r[   r\   r]   r^   r`   ra   r3   r3   r4   __init__   s"   2
zScriptRunner.__init__returnc                 C  s
   t | S N)r   repr_rr   r3   r3   r4   __repr__  s   
zScriptRunner.__repr__Nonec                 C  s   | 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)rm   request_stoprw   r3   r3   r4   rz     s   zScriptRunner.request_stop
rerun_databoolc                 C  s   | 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.
        )rm   rn   )rr   r{   r3   r3   r4   rn     s   zScriptRunner.request_rerunc                 C  s2   | j dur	tdtj| jd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)targetr<   )rq   	Exception	threadingThread_run_script_threadstartrw   r3   r3   r4   r   "  s   
zScriptRunner.startr   c                 C  s&   |   sJ t }|du r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)rr   ctxr3   r3   r4   _get_script_run_ctx1  s   z ScriptRunner._get_script_run_ctxc                 C  s   |   sJ td t| j| j| jd| j| j| j	| j
ttd| j| jdd}tt | | j }|jtjkrL| |j | j }|jtjks;|jtjksTJ t }|j|_|j|_| jj| tj |d 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.gatherUsageStatsN)rY   _enqueuescript_requestsquery_stringrZ   r[   r5   r^   gather_usage_statsr`   ra   context_info)eventclient_state)!r   r'   debugr   rd   _enqueue_forward_msgrm   rg   rh   re   rj   r|   r   rQ   rk   rl   r   r   current_threadon_scriptrunner_readytyper   RERUN_run_scriptr{   STOPr   r   page_script_hashro   sendr(   r.   )rr   r   requestr   r3   r3   r4   r   L  s:   	



zScriptRunner._run_script_threadc                 C  s   | j t kS )z=True if the calling function is running in the script thread.)rq   r   r   rw   r3   r3   r4   r   ~  s   z!ScriptRunner._is_in_script_threadmsgr   c                 C  s    |    | jj| tj|d 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.
        )r   forward_msgN)rf   ro   r   r(   r/   )rr   r   r3   r3   r4   r     s   	
z!ScriptRunner._enqueue_forward_msgc                 C  sX   |   sdS | jsdS | j }|du r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   rp   rm   on_scriptrunner_yieldr   r   r   r   r{   r   r   )rr   r   r3   r3   r4   rf     s   	

z4ScriptRunner._maybe_handle_execution_control_requestc                 c  s2    | j rtdd| _ z	dV  W d| _ dS d| _ 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)rp   r   rw   r3   r3   r4   _set_execing_flag  s   zScriptRunner._set_execing_flagc              
     s     sJ 	 td| t }d}|jst j   j	
|j|j  j	|j|j} j	 }|dur;|d n|d }  }|j}||krgt }	|jdura|jjduradd |jjD }	 j|	 t|j}
|j|j||
|jd  jj tj||
 j	 d	 z"|dur|d
 }n|d
 }t }|j|j_| |  j!"|}W n) t#y } ztj$d|d d jt%<  jj tj&|d W Y d}~dS d}~ww  'd}|t(j)d< ||j*d< ||||f fdd	}t | }t+||\}}}}}| jt%< |rtj,}n|jrtj-}ntj.}|j/rNz| t0|j1t2t | t2||r-t3|j4ndd W n t#yM } ztjd|d W Y d}~nd}~ww  5||| t6t7 |dura|}ndS q)zRun our script.

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

        TzRunning script %sr   Nr   c                 S  s   h | ]}|j qS r3   )id)r?   wr3   r3   r4   	<setcomp>  s    z+ScriptRunner._run_script.<locals>.<setcomp>)r   r   fragment_ids_this_runr   )r   r   r   r;   script_pathzScript compilation error)exc_infoF)r   	exception__main____file__c                   sH  t  j   x |jd ur j|j |  |jr\|jD ]9}z j	|}|  W q! t
yC   |jsAtd| d Y q! ttfyR } z|d }~w tyZ   Y q!w ntjrdt j t| |j  jj|jd  j     W d    n1 sw   Y  W d    d S W d    d S 1 sw   Y  d S )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   re   r   widget_statesrg   on_script_will_rerunon_script_startfragment_id_queuerk   getr   is_auto_rerunr'   warningr   r   r~   r   uses_pages_directoryrW   exec__dict__clearr   maybe_check_serializablerf   )codemoduler   r{   fragment_idwrapped_fragmenterw   r3   r4   code_to_execH  sL   




	(


Pz.ScriptRunner._run_script.<locals>.code_to_exec)commands	exec_time	prep_timeuncaught_exceptionzFailed to create page profile)8r   r'   r   timerr   r   get_instancemedia_file_mgrclear_session_refsrl   set_script_intentr   	page_nameget_initial_active_scriptget_main_pager   setr   widgetsrg   on_script_finishedlistresetr   r   ro   r   r(   r)   	get_pagesr   page_not_foundenqueueri   get_bytecoder~   r   r!   r*   _new_modulesysmodulesr   r   r,   r-   r+   r   r   tracked_commandsr   r   r0   _on_script_finished_log_if_error_clean_problem_modules)rr   r{   
start_timer   active_scriptmain_page_infor   r   previous_page_script_hash
widget_idsr   r   r   r   exr   r   _run_without_errorsrerun_exception_datapremature_stopr   finished_eventr3   rw   r4   r     s   




	






A

 zScriptRunner._run_scriptr   r   r(   r   c                 C  sL   |s	| j |j | jj| |d t j  t	
dr$t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.
        )r   zrunner.postScriptGC   N)rg   r   widget_ids_this_runro   r   r   r   r   remove_orphaned_filesr   rQ   gccollect)rr   r   r   r   r3   r3   r4   r     s   
z ScriptRunner._on_script_finishedr<   types.ModuleTypec                 C  s
   t |S )z(Create a new module with the given name.)types
ModuleType)rr   r<   r3   r3   r4   r     s   
zScriptRunner._new_moduleN)rY   r6   r5   r6   rZ   r#   r[   r&   r\   r   r]   r   r^   r_   r`   r%   ra   r   )rt   r6   rt   ry   )r{   r   rt   r|   )rt   r   )rt   r|   )r   r   rt   ry   )r{   r   rt   ry   )r   r   r   r(   r   r|   rt   ry   )r<   r6   rt   r   )r0   r1   r2   rs   rx   rz   rn   r   r   r   r   r   rf   r   r   r   r   r   r3   r3   r3   r4   rX      s"    

c

	



2

"

 
zrX   rt   ry   c                  C  st   dt jv rzt jd } | j  W n	 ty   Y nw dt jv r8zt jd }|d W dS  ty7   Y dS w dS )z;Some modules are stateful, so we have to clear their state.keraszmatplotlib.pyplotallN)r   r   backendclear_sessionr~   close)r   pltr3   r3   r4   r     s   



r   fnCallable[[], None]c              
   C  s>   z|   W d S  t y } zt| W Y d }~d S d }~ww ru   )r~   r'   r   )r   r   r3   r3   r4   r     s   r   )r5   r6   r   )r   r   rt   ry   )H
__future__r   r   r   r   r   
contextlibr   enumr   timeitr   r   typingr   r   r   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.pages_managerr   (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.source_utilr$   streamlit.runtime.fragmentr%   'streamlit.runtime.uploaded_file_managerr&   r0   r'   __annotations__r(   rW   rX   r   r   r3   r3   r3   r4   <module>   sN   
(    
: