o
    ZhK}                     @  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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/m0Z0m1Z1m2Z2 d dl3m4Z4m5Z5m6Z6 d dl7m8Z8m9Z9m:Z: d dl;m<Z< erd dl=m>Z> d dl?m@Z@ d dl*m+Z+ d dlAmBZB eeCZDdeEd< G dd de	ZF	 d+d!d"ZGG d#d$ d$ZHd,d%d&ZId-d)d*ZJdS ).    )annotationsN)contextmanager)Enum)default_timer)TYPE_CHECKINGAny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)	Generator)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/   r0   r1    r5   r5   m/var/www/html/Persson_Maskin/env/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.pyr*   J   s    r*   main_script_pathstrreturnNonec           
        s   ddl m} ddlm}m} ddlm  ||  }|jd t	dd 
dD td	} |d
d}|g fdd|D  }tddu rIdnd}|td||dd}	|	  d S )Nr   )Path)PageType_navigation)StreamlitPagepagesc                 S  s2   g | ]}|j d r|j ds|j dkr|qS )z.py.z__init__.py)nameendswith
startswith.0pager5   r5   r6   
<listcomp>   s    


z_mpa_v1.<locals>.<listcomp>z*.py)keyT)defaultc                   s   g | ]	} |j  qS r5   )rA   rD   r>   pages_folderr5   r6   rG      s    zclient.showSidebarNavigationFhiddensidebarzlist[PageType])positionexpanded)pathlibr;   streamlit.commands.navigationr<   r=   streamlit.navigation.pager>   resolveparentsortedglobr%   r   
get_optionr   run)
r7   r;   r<   r=   resolved_main_script_pathr?   	main_page	all_pagesrN   rF   r5   rJ   r6   _mpa_v1~   s2   
r\   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dAd!d"Zd?d#d$Z	dBd%d&Z
dCd)d*Zd?d+d,ZedDd.d/ZdEd0d1ZdFd6d7ZdGd:d;Zd<S )HScriptRunner
session_idr8   r7   session_stater$   uploaded_file_mgrr(   script_cacher   initial_rerun_datar   	user_infodict[str, str | bool | None]fragment_storager'   pages_managerr   r9   r:   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)
selfr^   r7   r_   r`   ra   rb   rc   re   rf   r5   r5   r6   __init__   s"   2
zScriptRunner.__init__c                 C  s
   t | S N)r   repr_rw   r5   r5   r6   __repr__  s   
zScriptRunner.__repr__c                 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)rr   request_stopr{   r5   r5   r6   r}     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.
        )rr   rs   )rw   r~   r5   r5   r6   rs     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)targetrA   )rv   RuntimeError	threadingThread_run_script_threadstartr{   r5   r5   r6   r   &  s   
zScriptRunner.startr   c                 C  s*   |   std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.

        zGScriptRunner._get_script_run_ctx must be called from the script thread.NzOScriptRunner thread has a null ScriptRunContext. Something has gone very wrong!)_is_in_script_threadr   r!   )rw   ctxr5   r5   r6   _get_script_run_ctx5  s   z ScriptRunner._get_script_run_ctxc                 C  s   |   std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rN| |j | j }|jtjks=|jtjkr]td|j dt }|j|_|j|_|jrr|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.
        zFScriptRunner._run_script_thread must be called from the script thread.zBeginning script thread zbrowser.gatherUsageStatsN)r^   _enqueuescript_requestsquery_stringr_   r`   r7   rc   gather_usage_statsre   rf   context_info Unrecognized ScriptRequestType: . This should never happen.)eventclient_state)$r   r   r)   debugr   ri   _enqueue_forward_msgrr   rl   rm   rj   ro   r   r   rW   rp   rq   r    r   current_threadon_scriptrunner_readytyper   RERUN_run_scriptr~   STOPr   r   page_script_hashr   CopyFromrt   sendr*   r0   )rw   r   requestr   r5   r5   r6   r   S  sJ   	



zScriptRunner._run_script_threadc                 C  s   | j t kS )z=True if the calling function is running in the script thread.)rv   r   r   r{   r5   r5   r6   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)rk   rt   r   r*   r1   )rw   r   r5   r5   r6   r     s   	
z!ScriptRunner._enqueue_forward_msgc                 C  sf   |   sdS | jsdS | j }|du rdS |jtjkr!t|j|jtj	kr0t
d|j d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.
        Nr   r   )r   ru   rr   on_scriptrunner_yieldr   r   r   r   r~   r   r   r   )rw   r   r5   r5   r6   rk     s   	

z4ScriptRunner._maybe_handle_execution_control_requestGenerator[None, None, None]c                 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)ru   r   r{   r5   r5   r6   _set_execing_flag  s   zScriptRunner._set_execing_flagc              
     s     std	 td| t }d}|jst 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|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d  fdd}t | }t-||\}}}}}| jt'< |r
tj.}n|jrtj/}ntj0}|j1rQz|"t2|j3t4t | t4||r0t5|j6ndd W n t%yP } ztjd|d W Y d}~nd}~ww  7||| t8t9 |durd|}ndS q	)!zRun our script.

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

        z?ScriptRunner._run_script must be called from the script thread.TzRunning script %sr   Nr   c                 S  s   h | ]}|j qS r5   )id)rE   wr5   r5   r6   	<setcomp>  s    z+ScriptRunner._run_script.<locals>.<setcomp>)r   r   fragment_ids_this_runcached_message_hashesr   )r   r   r   r?   script_pathzScript compilation error)exc_infoF)r   	exception__main____file__coder8   moduletypes.ModuleTyper   r   r~   r   r9   r:   c                   s8  t  j   p |jd ur j|j |  |jrS|jD ]0}z j	|}|  W q! t
y@   |js>td| Y q! ttfyI     tyQ   Y q!w ntjr\t j nt| |j  jj|jd  j     W d    n1 s}w   Y  W d    d S W d    d S 1 sw   Y  d S )Na  Couldn't find fragment with id %s. 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   rj   r   widget_statesrl   on_script_will_rerunon_script_startfragment_id_queuerp   getr   is_auto_rerunr)   warningr   r   	Exceptionr   uses_pages_directoryr\   exec__dict__clearr   maybe_check_serializablerk   )r   r   r   r~   fragment_idwrapped_fragmentr{   r5   r6   code_to_exec^  sL   




)

Pz.ScriptRunner._run_script.<locals>.code_to_exec)commands	exec_time	prep_timeuncaught_exceptionzFailed to create page profile)
r   r8   r   r   r   r   r~   r   r9   r:   ):r   r   r)   r   timerr   r   get_instancemedia_file_mgrclear_session_refsrq   set_script_intentr   	page_nameget_initial_active_scriptget_main_pager   setr   widgetsrl   on_script_finishedlistresetr   r   r   rt   r   r*   r+   	get_pagesr   page_not_foundenqueuern   get_bytecoder   r   r"   r,   _new_modulesysmodulesr   r   r.   r/   r-   r   r   tracked_commandsr   r   r2   _on_script_finished_log_if_error_clean_problem_modules)rw   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_eventr5   r{   r6   r     s   




	






H

 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)rl   r   widget_ids_this_runrt   r   r   r   r   remove_orphaned_filesr   rW   gccollect)rw   r   r   r   r5   r5   r6   r     s   
z ScriptRunner._on_script_finishedrA   r   c                 C  s
   t |S )z(Create a new module with the given name.)types
ModuleType)rw   rA   r5   r5   r6   r     s   
zScriptRunner._new_moduleN)r^   r8   r7   r8   r_   r$   r`   r(   ra   r   rb   r   rc   rd   re   r'   rf   r   r9   r:   )r9   r8   r9   r:   )r~   r   r9   r   )r9   r   )r9   r   )r   r   r9   r:   )r9   r   )r~   r   r9   r:   )r   r   r   r*   r   r   r9   r:   )rA   r8   r9   r   )r2   r3   r4   rx   r|   r}   rs   r   r   r   r   r   rk   r   r   r   r   r   r5   r5   r5   r6   r]      s$    

c

	



:

%
  
r]   c                  C  s   dt jv rzt jd } td| j  W n	 ty   Y nw dt jv r>zt jd }td|d W dS  ty=   Y dS w dS )z;Some modules are stateful, so we have to clear their state.kerasr   zmatplotlib.pyplotallN)r   r   r   backendclear_sessionr   close)r   pltr5   r5   r6   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 ry   )r   r)   r   )r   er5   r5   r6   r     s   r   )r7   r8   r9   r:   r   )r   r   r9   r:   )K
__future__r   r   r   r   r   
contextlibr   enumr   timeitr   r   typingr   r   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%   collections.abcr&   streamlit.runtime.fragmentr'   'streamlit.runtime.uploaded_file_managerr(   r2   r)   __annotations__r*   r\   r]   r   r   r5   r5   r5   r6   <module>   sP    
*    
S