a
    DfL                     @  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m	Z	 ddl
mZ ddlmZmZmZmZmZmZmZm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 ddl m!Z!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/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@mAZA ddlBmCZCmDZDmEZEmFZFmGZG ddlHmHZH erddlImJZJ ddlKmLZL ddlMmNZN ddlOmPZP ddlQmRZR dd lSmTZT d!ZUd"eVd#< d$ZWd"eVd%< d&ZXd"eVd'< d(d)d*d+ZYdd-d.d/d0d1d2d3d4ZZd.d0d5d6d7Z[d"d8d9d:Z\eE]d;Z^d<eVd=< eE]d>Z_d<eVd?< eE]d@Z`d<eVdA< dBdCdDdEdFZadi fdGdHZbddIdJdKdLdMdNdOZcddQdJd"dLdRdSdTZddUdV ZeddQdIdWdKdXd"dLdYdZd[Zfd\d"d]d^d_Zgd`da ZhG dbdc dce7ZiG ddde dee9ZjG dfdg dgZkdhd1didjdkZle	dld)dmdnZmdd/d/dpdqd1drdsdtZnddud"dqdvdwdxdyZodzd{dBd|d}dd,i fdqdqd/d"d"d~d/dd1d	ddZpdd ZqddududddZrze3d W n esy   Y n0 ze2dee W n ety   Y n0 dS )z`
Various utilities for loading JS dependencies and rendering plots
inside the Jupyter notebook.
    )annotationsN)contextmanager)partial)TYPE_CHECKINGAnyDictIteratorListLiteralOptionalTuple)serialize_json)MACROS)Document)server_document)div_for_render_itemscript_for_render_items)%standalone_docs_json_and_render_items)wrap_in_script_tag)Model)CDNINLINE)_Unsetsettings)make_id)register_display_accessorunregister_display_accessor)PYVIZ_PROXYCommJupyterCommJSJupyterCommManager
nb_mime_js   )escape   )embed_state)
add_to_docdiff)	PANEL_DIR	Resources_envbundle_resourcespatch_model_css)state)Server)Template)CommManager)Viewable)Widget)Locationz&application/vnd.holoviews_load.v0+jsonstr	LOAD_MIMEz&application/vnd.holoviews_exec.v0+json	EXEC_MIME	text/html	HTML_MIMEzList[Dict[str, str]])returnc                   C  s
   ddigS )Nmodulez!panel.io.jupyter_server_extension r;   r;   r;   ^/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/panel/io/notebook.py_jupyter_server_extension_pathsD   s    r=   Tr   r   boolanyNone)doccommbinarymsgr9   c              
   C  s   |du rt | |d}|du r dS |jszz.ddlm} | dtt| |||d W q tyv   t	j
dtdd Y q0 n
t|| dS )	zH
    Pushes events stored on the document across the provided comm.
    N)rC   r   )IOLoopg?)rD   zAttempted to send message over Jupyter Comm but it was not yet open and also could not be rescheduled to a later time. The update will not be sent.)
stacklevel)r'   Z_commZtornado.iolooprE   currentZ
call_laterr   push	ExceptionwarningswarnUserWarningsend)rA   rB   rC   rD   rE   r;   r;   r<   rH   G   s    "rH   )rB   rD   c                 C  s`   |  |j |  |j |  |j |jD ]0}t|j}| }|  | | j |gd q*dS )z:
    Sends a bokeh message across a pyviz_comms.Comm.
    )buffersN)	rM   Zheader_jsonZmetadata_jsonZcontent_jsonrN   jsondumpsrefto_bytes)rB   rD   bufferheaderpayloadr;   r;   r<   rM   \   s    

rM   )rQ   c                 C  s<   | t jvrd S t j|  \}}}}|r8d|jvr8t|| d S )NZembedded)r-   Z_viewstagsrH   )rQ   selfrootrA   rB   r;   r;   r<   push_on_rootl   s
    
rY   zdoc_nb_js.jsr/   	DOC_NB_JSzautoload_panel_js.jsAUTOLOAD_NB_JSznb_template.htmlNB_TEMPLATE_BASEF  )	reloadingload_timeoutc                 C  sV   i i i d}|D ]$}	|	  D ]\}
}||
 | qqtj| d|||||||tjd
S )N)packagespathsshimT)
bundleforcer^   timeoutconfigrequirementsexportsskip_imports	ipywidgetversion)itemsupdater[   renderbokeh__version__)rc   configsrg   rh   ri   rj   r^   r_   rf   confkeycr;   r;   r<   _autoload_jsw   s     ru   c              	   C  s   t  }tt| dd}t|d|}tt||}| }|td|| |tt	d t
|dkr~|d d |d	< |d	 j|d
< |d u rt}nt|trtd| }||S )NF)quotezapplication/json )titleZplot_scriptdocsbasemacrosr$   ry   r   rA   rootsz{% extends base %}
)r   r#   r   r   r   copyrm   dictr\   r   lenr|   
isinstancer4   r*   Zfrom_stringrn   )	docs_jsonrender_itemstemplatetemplate_variablesZjson_idrO   scriptcontextr;   r;   r<   html_for_render_items   s(    
r   z
'Document'zOptional['Comm']zOptional['CommManager']z0Tuple[Dict[str, str], Dict[str, Dict[str, str]]])documentrB   managerr9   c                 C  sx   | j d jd }t| dd\}}|rL|d }tt|j j d d |j _t||| j| j	d}d|t
dit
d|iifS )	Nr   idTZsuppress_callback_warning)r   r   r7   rw   )r|   rQ   r   r~   listZ_rootsrl   r   r   r   r6   )r   rB   r   rQ   r   r   itemhtmlr;   r;   r<   render_template   s     r   cdnz'Model')modelrB   	resourcesr9   c                   s  t | tstdddlm  | jd }tjsR|dkrRd}t| |d || j	j
d< t| gd	d
\}\}t|}| } fdd jD }	dtjv }
tjs|
dtjv M }
tjt|t|g|	|
d}|| }}dj||d}||d}dt|tditd|iifS )Nz0notebook_content expects a single Model instancer"   )panel_extensionr   serverz'/panel-preview/static/extensions/panel/)dist_urlr   Tr   c                   s    g | ]}| j v r j | qS r;   )Z_globals).0extZpnextr;   r<   
<listcomp>   s   
z render_model.<locals>.<listcomp>ipywidgets_bokehZPANEL_IPYWIDGET)r   r   rg   rj   z<div id='{id}'>{html}</div>)r   r   )r7   application/javascriptr7   rw   )r   r   
ValueErrorrf   r   rQ   r-   _is_pyodider,   r   Z_template_variablesr   r   to_jsonZ_loaded_extensionssysmodulesosenvironrZ   rn   r   formatmimebundle_to_htmlr6   )r   rB   r   targetr   r   Zrender_itemdivZrender_jsonrg   rj   r   Zbokeh_scriptZ	bokeh_divr   datar;   r   r<   render_model   s6    





r   c                   s    ddl m d fdd	}|S )z
    Generates a function that will render the supplied object as a
    mimebundle, e.g. to monkey-patch a _repr_mimebundle_ method onto
    an existing object.
    r"   panelNc                   s     | |S N)_repr_mimebundle_)includeexcludeobjr   r;   r<   r      s    z(mime_renderer.<locals>._repr_mimebundle_)NN)paner   )r   r   r;   r   r<   mime_renderer   s    r   z'Comm'zOptional['Location'])r   rA   rB   r   locationr   r9   c                   s   |r0|j tjv r0tj|j  }|js0 fdd|_t| tsBtdt| |d |dur`|| |dur|	|| |  }|| t
|  |S )zb
    Displays bokeh output inside a notebook using the PyViz display
    and comms machinery.
    c                   s      S r   )init)_rB   r;   r<   <lambda>       z#render_mimebundle.<locals>.<lambda>z&Can only render bokeh LayoutDOM modelsTN)Zclient_comm_id_JupyterCommManagerZ_commsZ_on_openr   r   r   r&   Zadd_rootZ
_get_modelr   )r   rA   rB   r   r   r   client_commlocr;   r   r<   render_mimebundle   s    


r   zDict[str, Any])rc   r9   c                 C  sH   t | tr| \}}n| }|dd}d|v rD|d }|dj|d7 }|S )z+
    Converts a MIME bundle into HTML.
    r7   rw   r   z4
<script type="application/javascript">{js}</script>)js)r   tuplegetr   )rc   r   metadatar   r   r;   r;   r<   r   	  s    

r   c                    s  ddl m }  g g i   }}}g }tj D ]\}}d|v r*|| q*ddlm} |tt	|
 7 }| j D ]L\}}	|	dd dddd	 }
|
|	d
d i|
|id}|| qri }|D ]<}t|tst||r| sqt|dr||j t|dst|tsqt|tr0| n
t|j  di }t fdd|D sh|  t dg D ]}t|trt d  d<  d | d |d < t|tr|d n|f}|D ]0}||vr|| ||v r|| ||< qАqxq||||fS )zl
    Returns JS snippet to load the required dependencies in the classic
    notebook using REQUIRE JS.
    r"   rf   .)ReactiveHTML/r   z.minrw   N)ra   rh   __js_skip____js_require__rh   c                 3  s   | ]} |kV  qd S r   r;   )r   rf   Zmodel_requirer;   r<   	<genexpr>B  r   z%require_components.<locals>.<genexpr>ra   r   r$   )rf   r   Zmodel_class_reverse_maprl   appendZreactiver   r   paramZconcrete_descendentsvaluesZjs_filessplitreplacer   r~   
issubclass_loadedhasattrrm   r   r   popr?   r   r   )rf   rq   rg   rh   Zjs_requiresZ	qual_namer   r   exportr   namerr   Zskip_importZmodel_exportsreqreqsrr;   r   r<   require_components  sJ     





r   c                   @  s   e Zd ZdZedd ZdS )JupyterCommJSBinaryzZ
    Extends pyviz_comms.JupyterCommJS with support for repacking
    binary buffers.
    c                 C  s*   dd t |d D }t|d d |dS )Nc                 S  s   i | ]\}}||qS r;   r;   )r   ivr;   r;   r<   
<dictcomp>\  r   z.JupyterCommJSBinary.decode.<locals>.<dictcomp>rN   contentr   )_buffers)	enumerater~   )clsrD   rN   r;   r;   r<   decodeZ  s    zJupyterCommJSBinary.decodeN)__name__
__module____qualname____doc__classmethodr   r;   r;   r;   r<   r   T  s   r   c                   @  s   e Zd ZeZdS )JupyterCommManagerBinaryN)r   r   r   r   r   r;   r;   r;   r<   r   _  s   r   c                   @  s"   e Zd ZdZdd ZdddZdS )
Mimebundlez'
    Wraps a generated mimebundle.
    c                 C  s
   || _ d S r   Z_mimebundle)rW   Z
mimebundler;   r;   r<   __init__h  s    zMimebundle.__init__Nc                 C  s   | j S r   r   )rW   r   r   r;   r;   r<   r   k  s    zMimebundle._repr_mimebundle_)NN)r   r   r   r   r   r   r;   r;   r;   r<   r   d  s   r   r1   )objsr9   c                  G  s"   | D ]}|j D ]}t| qqdS )z
    A utility for pushing updates to the frontend given a Panel
    object.  This is required when modifying any Bokeh object directly
    in a notebook session.

    Arguments
    ---------
    objs: panel.viewable.Viewable
    N)Z_modelsrY   )r   r   rQ   r;   r;   r<   push_notebookr  s    

r   r   c                   c  s$   dt _zdV  W dt _ndt _0 dS )z8
    Context manager to temporarily block comm push
    TNF)r-   Z_holdr;   r;   r;   r<   
block_comm  s    r   autozbool | Literal['auto']int)inliner^   enable_mathjaxr_   r9   c              
   C  s4  ddl m} | rtjstnt}tjdd}tjjt	u}tj }t
j||d}z\td ||||d}	t \}
}}}dtjv }t|	|
||||||d}W |r|t_qtj  n|r|t_n
tj  0 |d	|t|i tjj   td
 d jdd}dttjtg}|t|d	|id |dd| did d S )Nr   publish_display_datar   )default)notebook)r   r^   r   r   )rc   rq   rg   rh   ri   rj   r^   r_   r   Z
_templateszjupyter.csszutf-8)encoding
)r   r7   z<style>z</style>)IPython.displayr   r-   r   r   r   r   r   Z_user_valuer   r)   Z
from_bokehr+   r   r   r   ru   unset_valuer5   ro   ior   ZcurstateZoutput_notebookr(   	read_textjoinr   r   Z
js_managerr!   )r   r^   r   r_   r   r   Zprev_resourcesZuser_resourcesZnb_endpointrc   rq   rg   rh   ri   rj   Zbokeh_jsZCSSZJSr;   r;   r<   load_notebook  sL    
r   r   z'Server')r   notebook_urlportr9   c                 C  s   ddl m} ddlm}m}m} t|r2|d}n||}t j	}|| ||dd|d}	t|rl||	j
}
n|||	j
}
t|
dd	}|t|td
itd|iid |	S )a  
    Displays a bokeh server inline in the notebook.

    Arguments
    ---------
    panel: Viewable
      Panel Viewable object to launch a server for
    notebook_url: str
      The URL of the running Jupyter notebook server
    port: int (optional, default=0)
      Allows specifying a specific port
    server_id: str
      Unique ID to identify the server with

    Returns
    -------
    server: bokeh.server.Server
    r   r   r$   )_origin_url_server_url
get_serverNTF)r  Zwebsocket_originstartshow	server_id)r   rw   r  )r   )r   r   r   r  r  r  callableuuiduuid4hexr  r   r8   r6   )r   r   r  r   r  r  r  originr  r   urlr   r;   r;   r<   show_server  s,    


r  i     rw   z./zOptional[str]zDict[Widget, List[Any]])	
max_statesmax_optsrO   json_prefix	save_path	load_pathprogressstatesr9   c	                 C  sx   ddl m }	 t }
t }|	jdd8 | |
|}t| ||
|||||||| W d   n1 sb0    Y  tt|S )ag  
    Renders a static version of a panel in a notebook by evaluating
    the set of states defined by the widgets in the model. Note
    this will only work well for simple apps with a relatively
    small state space.

    Arguments
    ---------
    max_states: int
      The maximum number of states to embed
    max_opts: int
      The maximum number of states for a single widget
    json: boolean (default=True)
      Whether to export the data to json files
    json_prefix: str (default='')
      Prefix for JSON filename
    save_path: str (default='./')
      The path to save json files to
    load_path: str (default=None)
      The path or URL the json files will be loaded from.
    progress: boolean (default=False)
      Whether to report progress
    states: dict (default={})
      A dictionary specifying the widget values to embed for each widget
    r"   r   T)embedN)rf   r   r   setget_rootr%   r   r   )r   r  r  rO   r  r  r  r  r  rf   rA   rB   r   r;   r;   r<   render_embed  s    
"r  c                 O  s&   ddl m} |t| g|R i |S )Nr   r   )r   r   r  )r   argskwargsr   r;   r;   r<   
show_embed  s    r  )r   r  c                   s   ddl m} ddlm} |r |nt }|fi |j|d | ddtdr|d_ gf fd	d
	}|d S )a  
    Returns an ipywidget model which renders the Panel object.

    Requires `jupyter_bokeh` to be installed.

    Arguments
    ---------
    obj: object
      Any Panel object or object which can be rendered with Panel
    doc: bokeh.Document
        Bokeh document the bokeh model will be attached to.
    **kwargs: dict
      Keyword arguments passed to the pn.panel utility function

    Returns
    -------
    Returns an ipywidget model which renders the Panel object.
    r   )
BokehModelr"   r   rA   T)Zcombine_events_view_countc                   s   d }| d dkrT| d dkrT|rTz |d  W n tyD   Y n0 g |d d < nx| d dkr| d dkr|r||d  ur|rz |d  W n ty   Y n0 jjd}| |g|d d < d S )Noldr   newr  )_cleanuprI   r  Z	_documentZupdate_from_model)ZchangerG   Z	new_modelr   r   Zwidgetr;   r<   view_count_changed4  s(    

z%ipywidget.<locals>.view_count_changed)	Zjupyter_bokeh.widgetsr  r   r   r   r  r   r   Zobserve)r   rA   r  r  r   r%  r;   r$  r<   rj     s    
rj   Z_ipython_display_r   )TN)NN)Nr   )NNr   )TFr   r]   )r   )N)ur   
__future__r   rO   r   r   r	  rJ   
contextlibr   	functoolsr   typingr   r   r   r   r	   r
   r   r   ro   Zbokeh.embed.notebookr   Zbokeh.core.json_encoderr   Zbokeh.core.templatesr   Zbokeh.documentr   Zbokeh.embedr   Zbokeh.embed.elementsr   r   Zbokeh.embed.utilr   Zbokeh.embed.wrappersr   Zbokeh.modelsr   Zbokeh.resourcesr   r   Zbokeh.settingsr   r   Zbokeh.util.serializationr   Zparam.displayr   r   Zpyviz_commsr   r   r   r    r   r!   utilr#   r  r%   r   r&   r'   r   r(   r)   r*   r+   r,   r-   Zbokeh.server.serverr.   Zjinja2r/   Zmodels.comm_managerr0   Zviewabler1   Zwidgets.baser2   r   r3   r5   __annotations__r6   r8   r=   rH   rM   rY   Zget_templaterZ   r[   r\   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  rj   KeyErrorrI   r;   r;   r;   r<   <module>   s   (  '   <    11 )1