
    /_i}                       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rd dl<m=Z=m>Z> d dl?m@Z@ d dl)m*Z* d dlAmBZB  eeC      ZDdeEd<    G d de	      ZF	 d"dZG G d d      ZHd#d ZId$d!ZJy)%    )annotationsN)contextmanager)Enum)default_timer)TYPE_CHECKINGAny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)Callable	Generator)FragmentStorage)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/   r0   r1   r2   r3        k/var/www/html/land_sniper/venv/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/script_runner.pyr,   r,   J   s;     &N )L% #@  : %D! H 0r8   r,   c                R   ddl m} ddlm}m} ddlm}  ||       j                         }|j                  dz  }t        |j                  d      D cg c]I  }|j                  j                  d      r,|j                  j                  d      s|j                  d	k7  r|K c}t        
      } ||d      }	|	g|D cg c]  } |||j                  z         c}z   }
t        j                   d      du rdnd} |t#        d|
      |d      }|j%                          y c c}w c c}w )Nr   )Path)PageType_navigation)StreamlitPagepagesz*.pyz.py.z__init__.py)keyT)defaultzclient.showSidebarNavigationFhiddensidebarzlist[PageType])positionexpanded)pathlibr;   streamlit.commands.navigationr<   r=   streamlit.navigation.pager>   resolveparentsortedglobnameendswith
startswithr%   r   
get_optionr   run)main_script_pathr;   r<   r=   r>   resolved_main_script_pathpages_folderpager?   	main_page	all_pagesrE   s               r9   _mpa_v1rY   ~   s'   C7 (,,<'='E'E'G3::WDL  %))&1	
yy!!%(II((-		]*	 	
 	E 7FI<A48lTYY./ I ;<E 	 
 y)D 	HHJ7	
s   AD=D$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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_idrS   session_stateuploaded_file_mgrscript_cacheinitial_rerun_data	user_infofragment_storagepages_managers
             r9   __init__zScriptRunner.__init__   s    d &!1.$*V*V
 #4)#!1+')$$%78
<  8<r8   c                ,    t        j                  |       S N)r   repr_rm   s    r9   __repr__zScriptRunner.__repr__  s    zz$r8   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)rh   request_stoprz   s    r9   r}   zScriptRunner.request_stop  s     	##%r8   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.
        )rh   ri   )rm   
rerun_datas     r9   ri   zScriptRunner.request_rerun  s     ~~++J77r8   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)targetrN   )rl   RuntimeError	threadingThread_run_script_threadstartrz   s    r9   r   zScriptRunner.start&  sO     *ABB'..**,
 	!!#r8   c                j    | j                         st        d      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.

        zGScriptRunner._get_script_run_ctx must be called from the script thread.zOScriptRunner thread has a null ScriptRunContext. Something has gone very wrong!)_is_in_script_threadr   r!   )rm   ctxs     r9   _get_script_run_ctxz ScriptRunner._get_script_run_ctx5  sH      ((*Y  !";1  
r8   c                L   | j                         st        d      t        j                  d       t	        | j
                  | j                  | j                  d| j                  | j                  | j                  | j                  t        t        j                  d            | j                  | j                   d      }t#        t%        j&                         |       | j                  j)                         }|j*                  t,        j.                  k(  rS| j1                  |j2                         | j                  j)                         }|j*                  t,        j.                  k(  rS|j*                  t,        j4                  k7  rt        d|j*                   d      t7               }|j8                  |_        |j:                  |_        |j<                  r%|j<                  j?                  |j<                         | j@                  jC                  | tD        jF                  |	       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.
        zFScriptRunner._run_script_thread must be called from the script thread.zBeginning script thread zbrowser.gatherUsageStatsN)rn   _enqueuescript_requestsquery_stringro   rp   rS   rs   gather_usage_statsrt   ru   context_info Unrecognized ScriptRequestType: . This should never happen.)eventclient_state)$r   r   r*   debugr   r_   _enqueue_forward_msgrh   rb   rc   r`   re   boolr   rQ   rf   rg   r    r   current_threadon_scriptrunner_readytyper   RERUN_run_scriptr   STOPr   r   page_script_hashr   CopyFromrj   sendr,   r2   )rm   r   requestr   s       r9   r   zScriptRunner._run_script_threadS  s    ((*X  	/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 <<,11127<<.@[\  #}$'$4$4!(+(<(<%%%..s/?/?@)22 	 	
r8   c                D    | j                   t        j                         k(  S )z=True if the calling function is running in the script thread.)rl   r   r   rz   s    r9   r   z!ScriptRunner._is_in_script_thread  s    ""i&>&>&@@@r8   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.
        )r   forward_msgN)ra   rj   r   r,   r3   )rm   msgs     r9   r   z!ScriptRunner._enqueue_forward_msg  s7     	446 	)==3 	 	
r8   c                \   | j                         sy| j                  sy| j                  j                         }|y|j                  t
        j                  k(  rt        |j                        |j                  t
        j                  k7  rt        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   rk   rh   on_scriptrunner_yieldr   r   r   r   r   r   r   r   )rm   r   s     r9   ra   z4ScriptRunner._maybe_handle_execution_control_request  s     ((*
 }}
 ..668?<<,222 !3!344<<,11127<<.@[\  or8   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)rk   r   rz   s    r9   _set_execing_flagzScriptRunner._set_execing_flag  s8      ===>>	"!DMEDMs   :. :	7:c           
          j                         st        d      	 t        j                  d|       t	               }d}|j
                  s,t        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-                  |	       |j
                  xs d}|j/                  |j0                  |||j2                  |j4                          j6                  j9                   t:        j<                  || j                  j?                                	 ||d   }n;|d   }tA               }|j                  |jB                  _        |jE                  |        jF                  jI                  |      } jS                  d      }|tT        jV                  d<   ||jX                  d<   ||||f	 	 	 	 	 	 	 	 	 d fd}t	               |z
  }t[        ||      \  }}}}}| j*                  tN        <   |rt:        j\                  }n-|j
                  rt:        j^                  }nt:        j`                  }|jb                  r]	 |jE                  te        |jf                  ti        t	               |z
        ti        |      |rtk        |      jl                  nd              jo                  |||       tq        tr               ||}nyc c}
w # tJ        $ r`}t        jM                  d	|
       d j*                  tN        <    j6                  j9                   t:        jP                  |       Y d}~yd}~ww xY w# tJ        $ r!}t        j                  d|
       Y d}~d}~ww xY w)zRun our script.

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

        z?ScriptRunner._run_script must be called from the script thread.zRunning script %sr   Nr   )r   r   fragment_ids_this_runcached_message_hashesr   )r   r   r   r?   script_pathzScript compilation error)exc_infoF)r   	exception__main____file__c                V   t        j                        5  j                         5  |j                  %j                  j                  |j                         |j                          |j                  r5|j                  D ]%  }	 j                  j                  |      } |        ' nbt"        j$                  rt'        j                         nt)        | |j*                         j                  j-                  |j.                         j                  j1                          j3                          d d d        d d d        y # t        $ r% |j                  st        j                  d|       Y t        t        f$ r  t         $ r Y w xY w# 1 sw Y   ]xY w# 1 sw Y   y xY w)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   r`   r   widget_statesrb   on_script_will_rerunon_script_startfragment_id_queuerf   getr   is_auto_rerunr*   warningr   r   	Exceptionr   uses_pages_directoryrY   exec__dict__clearr   maybe_check_serializablera   )codemoduler   r   fragment_idwrapped_fragmentrm   s         r9   code_to_execz.ScriptRunner._run_script.<locals>.code_to_exec`  s    &d&<&<=@C**,@C
 "//;++@@&44 '')!33+5+G+G &%K%%373I3I3M3M$/4" 0 !1 2&%R (<<#D$:$:; v7..44-0-A-A 5  ''@@B@@BA@C @C @C( $; & (2'?'?$+OO)R )4	%& %3M#B & !&#, %
 !%%]@C @C @C @CsT   FAF"E(BF7F+F	3F5F	FF	FF	FF()commands	exec_time	prep_timeuncaught_exceptionzFailed to create page profile)
r   strr   types.ModuleTyper   r   r   r   returnNone):r   r   r*   r   timerr   r   get_instancemedia_file_mgrclear_session_refsrg   set_script_intentr   	page_nameget_initial_active_scriptget_main_pager   setr   widgetsidrb   on_script_finishedresetr   r   r   rj   r   r,   r-   	get_pagesr   page_not_foundenqueuerd   get_bytecoder   r   r"   r.   _new_modulesysmodulesr   r   r0   r1   r/   r   r   tracked_commandsr   r   r4   _on_script_finished_log_if_error_clean_problem_modules)rm   r   
start_timer   active_scriptmain_page_infor   r   previous_page_script_hash
widget_idswr   r   r   r   exr   r   _run_without_errorsrerun_exception_datapremature_stopr   finished_events   `                       r9   r   zScriptRunner._run_script  sf    ((*Q 
 MM-z: %J I//
 $$&55HHJ11++Z-A-A !//II++M "00>>@N !, 01#$67  **,C ),(<(<%(,<< (+u
 ,,8"0088D0:0H0H0P0P!Q1!$$!QJ!Q##66zB ,,4 " II'44!1&;&0&F&F'44   MM'66!1&;))335   ,"/">K #1"?K %,C3=3G3GC&&0KK$))66{C& %%j1F '-CKK
# +6FOOJ' !+1(+(2	FCFC(FC &FC &	FC
 FCP *,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
i X "R\  	!!"<r!JEJ##$AB""+MM  # 
 	Z ! P MM"ABMOOPs9   N=AO 7AP. 	P+AP&&P+.	Q7QQ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.
        )r   zrunner.postScriptGC   N)rb   r   widget_ids_this_runrj   r   r   r   r   remove_orphaned_filesr   rQ   gccollect)rm   r   r   r   s       r9   r   z ScriptRunner._on_script_finished  sx     2233J3JK 	4u- 	--CCE 23JJqM 4r8   c                ,    t        j                  |      S )z(Create a new module with the given name.)types
ModuleType)rm   rN   s     r9   r   zScriptRunner._new_module  s    %%r8   N)rn   r   rS   r   ro   r$   rp   r)   rq   r   rr   r   rs   zdict[str, str | bool | None]rt   r(   ru   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   )r   r   )r   r   r   r   )r   zGenerator[None, None, None])r   r   r   r   )r   r   r   r,   r   r   r   r   )rN   r   r   r   )r4   r5   r6   rv   r{   r}   ri   r   r   r   r   r   ra   r   r   r   r   r   r7   r8   r9   r[   r[      s    a<a< a< $	a<
 /a< "a< &a< 0a< *a< $a< 
a<F &8$<8
tA
 #J " "DL#,=OS	2&r8   r[   c                 X   dt         j                  v r8	 t         j                  d   } t        d|       j                  j	                          dt         j                  v r0	 t         j                  d   }t        d|      j                  d       yy# t
        $ r Y Nw xY w# t
        $ r Y yw xY w)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   plts     r9   r   r     s     #++	KK(E&&446
 ckk)	++12C""5) *	  		  		s#   7B .B 	BB	B)(B)c                j    	  |         y # t         $ r}t        j                  |       Y d }~y d }~ww xY wrx   )r   r*   r   )fnes     r9   r   r     s+    
 s   
 	2-2)rS   r   r   r   r   )r  zCallable[[], None]r   r   )K
__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%   collections.abcr&   r'   streamlit.runtime.fragmentr(   'streamlit.runtime.uploaded_file_managerr)   r4   r*   __annotations__r,   rY   r[   r   r   r7   r8   r9   <module>r     s    # 	 
   %  ) ; ;  + + 4 ' 7 5 9 D 
 
 
 03:GKH% %0 0>*'TN	& N	&b,r8   