o
    2wig                     @  s  U d Z ddlmZ ddlZddlZddlZddl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ZddlmZ ddlmZmZ ddlmZmZmZmZmZ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, d
dl*m-Z- d
dl.m/Z/ zddl0m1Z1 W n e2y   dZ1Y nw zddl3m4Z5 ddl3m6Z7 dZ8W n e2y   dZ8Y nw dZ9dd Z:e	; Z<da=de>d< dd Z?e:e_@e?e_AG dd de,ZBG d d! d!eBZ+dS )"z!The IPython kernel implementation    )annotationsN)contextmanager)partial)release)line_at_cursortoken_at_cursor)	AnyBool	HasTraitsInstanceListTypedefaultobserveobserve_compat)	ZMQStream   BaseComm)CommManager)XCachingCompiler)_use_appnope)Kernel)_accepts_parameters)ZMQInteractiveShell)_asyncio_runner)provisionalcompleter)rectify_completionsTF_jupyter_types_experimentalc                  O  s   t | i |S )zCreate a new Comm.r   argskwargs r"   O/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/ipykernel/ipkernel.py_create_comm/   s   r$   zCommManager | None_comm_managerc                  O  sX   t du r*t t du rt| i |a W d   t S W d   t S 1 s%w   Y  t S )zCreate a new CommManager.N)r%   
_comm_lockr   r   r"   r"   r#   _get_comm_manager9   s   

r'   c                
      sR  e Zd ZdZedddZeeZedZ	ee
ZedddjddZeeddZe Zed	ed
d ZedddZeddd Zededd Ze Ze Z fddZeddejdd  dddddddddddd dd!d"dd#d$dgjddZ d%Z!e"j#Z$d&ej#% d' d(d%ejd' d)d*d+ d&d,d-Z&d.d/ Z'e(d0d1 Z)d2d3 Z* fd4d5Z+da fd7d8	Z, fd9d:Z-d;d< Z.dbd>d?Z/d@dA Z0e(dBdC Z1e1j2dDdC Z1e3dEdF Z4e3dGdH Z5 fdIdJZ6			=dcdddKdLdMZ7dNdO Z8dPdQ Z9dRdS Z:dddUdVZ;	'	'				=dedWdXZ<dYdZ Z=d[d\ Z>d]d^ Z?d_d` Z@  ZAS )fIPythonKernelzThe IPython Kernel class.z1IPython.core.interactiveshell.InteractiveShellABCT)
allow_nonezipykernel.debugger.DebuggerzUSet this flag to False to deactivate the use of experimental IPython completion APIs.)help)configuser_modulec                 C  s   | j d ur|d | j _d S d S Nnew)shellr,   selfchanger"   r"   r#   _user_module_changed\   s   
z"IPythonKernel._user_module_changedzcollections.abc.Mappinguser_nsc                 C  s   t  S N)dictr1   r"   r"   r#   _default_user_nsd   s   zIPythonKernel._default_user_nsc                 C  s(   | j d ur|d | j _| j   d S d S r-   )r/   r4   init_user_nsr0   r"   r"   r#   _user_ns_changedh   s   
zIPythonKernel._user_ns_changedc              
     sV  t  jdi | ddlm} dd tj D | _|r1| | j	| j
| j| j| j| j| j| j| _| jj| | j| j| j| | jd| _| j| jj_tjd}|rV|| jjd< | j| jj_| d| jj_| j| jj_| j| jj_t ! | _"t#| j"t$s}J | jj%&| j" g d	}|D ]}t'| j"|| j(|< qt) r| j*rd
dl+}|,  dS dS dS )zInitialize the kernel.r   _is_debugpy_availablec                 S  s"   g | ]}t |d r|jr|jqS )__file__)hasattrr=   ).0mr"   r"   r#   
<listcomp>z   s    
z*IPythonKernel.__init__.<locals>.<listcomp>)parentprofile_dirr,   r4   kernelcompiler_classJPY_SESSION_NAME__session__execute_result)	comm_opencomm_msg
comm_closer   Nr"   )-super__init__debuggerr<   sysmodulesvalues_kernel_modulesdebugger_classlogdebugpy_stream_publish_debug_eventdebug_shell_socketsessiondebug_just_my_codefilter_internal_framesshell_classinstancerC   r,   r4   rE   r/   displayhookosenvirongetiopub_socket
pub_socket_topictopicdisplay_pubcommget_comm_managercomm_manager
isinstancer
   configurablesappendgetattrshell_handlersr   _darwin_app_napappnopenope)r1   r!   r<   jupyter_session_namecomm_msg_typesmsg_typero   	__class__r"   r#   rM   t   sT   
zIPythonKernel.__init__zPython Referencezhttps://docs.python.org/%i.%iN   )texturlzIPython Referencez&https://ipython.org/documentation.htmlzNumPy Referencez+https://docs.scipy.org/doc/numpy/reference/zSciPy Referencez+https://docs.scipy.org/doc/scipy/reference/zMatplotlib Referencez$https://matplotlib.org/contents.htmlzSymPy Referencez'http://docs.sympy.org/latest/index.htmlzpandas Referencez-https://pandas.pydata.org/pandas-docs/stable/ipythonpythonr   ztext/x-python)nameversionz	ipython%d   z.py)r{   r|   mimetypecodemirror_modepygments_lexernbconvert_exporterfile_extensionc                 C  sD   ddl m} |r |d jd}| jd| | j j| d S d S )Nr   r;   zutf-8zDebugpy received: %s)rN   r<   bytesdecoderT   debug
tcp_clientreceive_dap_frame)r1   msgr<   framer"   r"   r#   dispatch_debugpy   s   zIPythonKernel.dispatch_debugpyc                 C     | j r| j jS d S r5   )r/   bannerr7   r"   r"   r#   r         zIPythonKernel.bannerc                   s   	 | j  I dH  q)zPoll the stopped queue.TN)rN   handle_stopped_eventr7   r"   r"   r#   poll_stopped_queue   s   z IPythonKernel.poll_stopped_queuec                   sf   | j rd| j _| jdu r| jd n	| jj| jdd t   | jr1t	
|  | jjj dS dS )zStart the kernel.FNz7debugpy_stream undefined, debugging will not be enabledcopy)r/   exit_nowrU   rT   warningon_recvr   rL   startasynciorun_coroutine_threadsafer   control_threadio_loopasyncio_loopr7   rt   r"   r#   r      s   

zIPythonKernel.startr/   c                   s6   t  ||| |dkr| jr| j| dS dS dS )zmOverridden from parent to tell the display hook and output streams
        about the parent message.
        r/   N)rL   
set_parentr/   )r1   identrB   channelrt   r"   r#   r      s   zIPythonKernel.set_parentc                   s"   t  |}|d| jd |S )zVInitialize metadata.

        Run at the beginning of each execution request.
        T)dependencies_metengine)rL   init_metadataupdater   )r1   rB   mdrt   r"   r#   r     s   zIPythonKernel.init_metadatac                 C  s0   |d |d< |d dkr|d dkrd|d< |S )zXFinish populating metadata.

        Run after completing an execution request.
        statuserrorenameUnmetDependencyFr   r"   )r1   rB   metadatareply_contentr"   r"   r#   finish_metadata  s   zIPythonKernel.finish_metadataFc                 C  s*   || _ tj| _| jt_tj| _| jt_dS )zZForward raw_input and getpass to the current frontend.

        via input_request
        N)_allow_stdinbuiltinsinput_sys_raw_input	raw_inputgetpass_save_getpass)r1   allow_stdinr"   r"   r#   _forward_input"  s
   zIPythonKernel._forward_inputc                 C  s   | j t_| jt_dS )zRestore raw_input, getpassN)r   r   r   r   r   r7   r"   r"   r#   _restore_input/  s   zIPythonKernel._restore_inputc                 C  r   r5   )r/   execution_countr7   r"   r"   r#   r   5  r   zIPythonKernel.execution_countc                 C  s   d S r5   r"   )r1   valuer"   r"   r#   r   ;  s   c              
   #  sz    t  dd }t|| |t|  fdd}ttj|}zdV  W ttj| dS ttj| w )aP  ContextManager for capturing SIGINT and cancelling a future

        SIGINT raises in the event loop when running async code,
        but we want it to halt a coroutine.

        Ideally, it would raise KeyboardInterrupt,
        but this turns it into a CancelledError.
        At least it gets a decent traceback to the user.
        c                 S  s    |   s|  r
d S |   d S r5   )	cancelleddonecancel)f_ignoredr"   r"   r#   cancel_unless_doneP  s   z;IPythonKernel._cancel_on_sigint.<locals>.cancel_unless_donec                    s   fdd} j | d S )Nc                     s"      s  r
d S  d d S )Nr   )r   r   
set_resultr"   )sigint_futurer"   r#   set_sigint_result]  s   zQIPythonKernel._cancel_on_sigint.<locals>.handle_sigint.<locals>.set_sigint_result)r   add_callback)r    r   r1   r   r"   r#   handle_sigint\  s   z6IPythonKernel._cancel_on_sigint.<locals>.handle_sigintN)r   Futureadd_done_callbackr   signalSIGINT)r1   futurer   r   save_sigintr"   r   r#   _cancel_on_sigintA  s   
"zIPythonKernel._cancel_on_sigintc                 g  s    d V  d S r5   r"   )r1   r    r"   r"   r#   _dummy_context_managerm  s   
z$IPythonKernel._dummy_context_managerc                   s   t  |||I dH  dS )z/Override for cell output - cell reconciliation.N)rL   execute_request)r1   streamr   rB   rt   r"   r#   r   r  s   zIPythonKernel.execute_request)	cell_metacell_idc                  s  | j   dus
J | | i }t dr(t dr( j}	 j}
t|	dg}ndd }
 fdd}	t jdg}zd}z |}W n tyR   |}t	
 }Y nw trш jtu rt  r|
|||d	r|d rv|	||||||d
}n	|	|||||d}t|}t | jjkr| jn| j}||2 d}z|I dH }W  jd |s jd| n jd |s jd| w w W d   n1 sw   Y  n|d r߈ j||||d}n j|||d}W |   n|   w |jdur|jn|j}|jrd|d< n%d|d< | jpg tt |j!t|d t"| j#| j$dd}||d<  j%d |d< d|v rC| j&'dd(|d  |d dkrU )|pPi |d< ni |d<  j*+ |d<  j*,  |S )zHandle code execution.Nrun_cell_asyncshould_run_asyncr   c                 S  s   dS )NFr"   )cellr"   r"   r#   <lambda>  s    z*IPythonKernel.do_execute.<locals>.<lambda>c                    s    j | i |S r5   )run_cellr   r/   r"   r#   r     s   z*IPythonKernel.do_execute.<locals>.run_cell)transformed_cellpreprocessing_exc_tuple)store_historysilentr   r   r   )r   r   r   r   post_executepost_run_cell)r   r   r   )r   r   okr   r   	tracebackr   evalueexecuteengine_uuid	engine_idmethodengine_infor   r   r   z Exception in execute request:
%s
user_expressionspayload)-r/   r   r>   r   r   r   r   transform_cell	ExceptionrO   exc_infor   loop_runnerr   get_event_loop
is_runningensure_future	threadingcurrent_threadshell_channel_threadparent_threadr   r   eventstriggerr   error_before_execerror_in_execsuccessr   _last_tracebackstrtype__name__r6   r   int_idr   rT   infojoinr   payload_managerread_payloadclear_payload)r1   coder   r   r   r   r   r   r   r   r   accepts_paramsr   r   corocoro_futurecmreserre_infor"   r   r#   
do_executev  s   


	



	

zIPythonKernel.do_executec                 C  sv   t r| jr| ||S |du rt|}t||\}}|| }| jdus%J | jd||\}}|||t| i ddS )zHandle code completion.N r   matches
cursor_endcursor_startr   r   )_use_experimental_60_completionuse_experimental_completions_experimental_do_completelenr   r/   complete)r1   r  
cursor_poslineoffsetline_cursortxtr  r"   r"   r#   do_complete	  s   

zIPythonKernel.do_completec                   s(   ddl m} |r| j |I dH S dS )zHandle a debug request.r   r;   N)rN   r<   process_request)r1   r   r<   r"   r"   r#   do_debug_request  s
   zIPythonKernel.do_debug_requestc           
      C  s   |du rt |}t 6 | jdusJ | jj||}tt||}g }|D ]}|t|j	|j
|j|j|jd q&W d   n1 sDw   Y  |r]|d j	}|d j
}dd |D }	n|}|}g }	|	||t|iddS )zD
        Experimental completions from IPython, using Jedi.
        N)r   endrw   r   	signaturer   c                 S  s   g | ]}|j qS r"   )rw   )r?   cr"   r"   r#   rA   A  s    z;IPythonKernel._experimental_do_complete.<locals>.<listcomp>r   r  )r  _provisionalcompleterr/   	Completercompletionslist_rectify_completionsrk   r6   r   r  rw   r   r  _EXPERIMENTAL_KEY_NAME)
r1   r  r  raw_completionsr!  compscompser  r"   r"   r#   r  '  s@   

z'IPythonKernel._experimental_do_completer"   c                 C  s   t ||}ddi}i |d< i |d< | jdusJ z0tjdkr(| jj|||d}n| jj||d}|d | | jjsB|d d	 d
|d< W |S  tyV   d|d< Y |S w )zHandle code inspection.r   r   datar   N)   )detail_levelomit_sections)r,  z	text/htmlTfoundF)	r   r/   r   version_infoobject_inspect_mimer   enable_html_pagerpopKeyError)r1   r  r  r,  r-  r{   r   bundler"   r"   r#   
do_inspectO  s,   



zIPythonKernel.do_inspectc
                 C  s   | j dusJ |dkr| j jj|||dd}
n$|dkr(| j jj|||||d}
n|dkr9| j jj|||||	d}
ng }
d	t|
d
S )zHandle code history.NtailT)rawoutputinclude_latestrange)r7  r8  search)r7  r8  nuniquer   )r   history)r/   history_managerget_tail	get_ranger;  r"  )r1   hist_access_typer8  r7  rX   r   stopr<  patternr=  histr"   r"   r#   
do_historyk  s"   

zIPythonKernel.do_historyc                 C  s   | j rd| j _td|dS )zHandle kernel shutdown.Tr   )r   restart)r/   r   r6   )r1   rG  r"   r"   r#   do_shutdown  s   zIPythonKernel.do_shutdownc                 C  sZ   t | jdd}|du r| jdusJ | jj}||\}}d|i}|dkr+d| |d< |S )zHandle an is_complete request.input_transformer_managerNr   
incomplete indent)rl   r/   input_splittercheck_complete)r1   r  transformer_managerr   indent_spacesrr"   r"   r#   do_is_complete  s   zIPythonKernel.do_is_completec              
   C  s  z
ddl m}m} W n ty   ddlm}m} Y nw | j}|dus%J z|j}dt|dd d }	|||dd	\}
}}t	|
d
d}|	d }|	d }|	d }|	d }||
|||||di}|
| | d| d| d| d}zt||j|j ||}W |D ]}|| qn|D ]}|| qw | jdusJ ||| jj| jjd}W nU ty } zI|  |jpg tt|jt|d}t| j| jdd}||d< | j| jd|| dd | jdd|d  g }d|d< W Y d}~||fS d}~ww ddi}||fS )zHandle an apply request.r   )serialize_objectunpack_apply_messager   N_-r
  Fr   r   r   r    r!   resultz = z(*z,**))buffer_thresholditem_thresholdr   applyr   r   r   )r   zException in apply request:
%sr   r   r   r   ) ipyparallel.serializerS  rT  ImportError	serializer/   r4   r   replacerl   r   execuser_global_nsr`   r2  rX   rY  rZ  BaseExceptionshowtracebackr   r   r   r6   r   r   send_responsera   rc   rT   r   r   )r1   contentbufsmsg_idreply_metadatarS  rT  r/   workingprefixr   r    r!   fnameargname	kwargname
resultnamensr  rW  key
result_bufr)  r   r  r"   r"   r#   do_apply  sn   


zIPythonKernel.do_applyc                 C  s   | j r	| j d tddS )zClear the kernel.Fr   )r   )r/   resetr6   r7   r"   r"   r#   do_clear  s   
zIPythonKernel.do_clearr   )F)TNF)r   r"   )r   r   NNNF)Br   
__module____qualname____doc__r   r/   r   r   r[   rS   r   rE   r	   tagr  r   rU   r   r,   r   r   r3   r4   r   r8   r:   r   _sys_eval_inputrM   r   rO   r/  
help_linksimplementationr   r|   implementation_versionsplitlanguage_infor   propertyr   r   r   r   r   r   r   r   r   setterr   r   r   r   r	  r  r  r  r5  rF  rH  rR  rr  rt  __classcell__r"   r"   rt   r#   r(   G   s    
9"
	




+
 
(!
$Br(   c                      s    e Zd ZdZ fddZ  ZS )r   z3DEPRECATED.  An alias for the IPython kernel class.c                   s.   ddl }|jdtdd t j|i | dS )zDEPRECATED.r   Nz@Kernel is a deprecated alias of ipykernel.ipkernel.IPythonKernelrv   )
stacklevel)warningswarnDeprecationWarningrL   rM   )r1   r    r!   r  rt   r"   r#   rM     s   zKernel.__init__)r   ru  rv  rw  rM   r  r"   r"   rt   r#   r     s    r   )Crw  
__future__r   r   r   r   r^   r   rO   r   typingt
contextlibr   	functoolsr   rf   IPython.corer   IPython.utils.tokenutilr   r   	traitletsr   r	   r
   r   r   r   r   r   r   zmq.eventloop.zmqstreamr   	comm.commr   comm.managerr   compilerr   
eventloopsr   
kernelbaser   
KernelBaser   zmqshellr   IPython.core.interactiveshellr   r]  IPython.core.completerr   r  r   r#  r  r$  r$   Lockr&   r%   __annotations__r'   create_commrg   r(   r"   r"   r"   r#   <module>   sd    ,
     ,