a
    Df[                     @  s.  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
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 d dl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$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/m0Z0 ddl1m1Z1 e2dZ3g Z4edd Z5edddddZ6edd Z7dd Z8d d! Z9d>d#d$d%d&d'd(Z:d)d* Z;d+d, Z<d?d-d.Z=d@d/d0d1d2d3Z>G d4d5 d5eZ?G d6d7 d7eZ@e@jAe_AG d8d9 d9e@ZBeBejCjDjE_BG d:d; d;e@ZFG d<d= d=e@ZGeGejCjDjE_GdS )A    )annotationsN)contextmanager)
ModuleType)IOAnyCallable)CodeHandler)
CodeRunner)Handlerhandle_exception)PathLike)Document)curdocpatch_curdoc
set_curdoc)import_required   config   )MIME_RENDERERS)profile_ctx)record_modulesstatezpanel.io.handlersc                  c  sX   zdd l } | j}t| j_W n ty,   Y n0 d V  z|| j_W n tyR   Y n0 d S Nr   )IPythondisplay	Exception)r   Z_orig_display r   ^/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/panel/io/handlers.py_patch_ipython_display'   s    r!   zdict[str, Callable[..., None]]zdict[str, Any])loggersreturnc                 c  s^   dd l m} i }tjD ]"}t||||< t||| |  qd V  |D ]}t||||  qDd S r   )Zbokeh.ioior   _io_functionsgetattrsetattr)r"   r$   oldfr   r   r    _monkeypatch_io5   s    
r*   c                  k  sR   dd | D }t j|  d V  | D ]$\}}|d u rBt j|= q(|t j|< q(d S )Nc                 S  s   i | ]}|t j|qS r   )osenvironget).0varr   r   r    
<dictcomp>B       z set_env_vars.<locals>.<dictcomp>)r+   r,   updateitems)Zenv_varsr(   r/   valuer   r   r    set_env_vars@   s    
r5   c                  C  s2   dt jvrd S dd lm}  |  }| r.|S d S )Nzmatplotlib.pyplotr   )sysmodulesZmatplotlib.pyplotZpyplotZgcfZget_axes)ZpltZfigr   r   r    
get_figureK   s    
r8   c                  O  sb   | drT| D ]B}|D ].}|tv rt| || i |}t|  qqt| qn
t|  d S )Nraw)r-   r   CELL_DISPLAYappendextend)argskwargsargZ	mime_typeoutr   r   r    r   S   s    

r   z	{pyodide}pythonr   ztuple[str, ...]str)
filehandlesupported_syntaxr#   c                 C  sl  d}d}d}g }g }|   }|s"q| }|rJ||r>d}q|| q|drt|t|d }	d|	 }| |	d }
|
|v r|rd|}|  tdd |D r|d|d	 d
}q|| q|dr|dd  }q|| q|r4d|}tdd |D r4|d|d	 |rbtdd |D rb|d|  d|S )z?
    Extracts Panel application code from a Markdown file.
    FNz```` c                 s  s   | ]}d |v V  qdS pn.extensionNr   r.   or   r   r    	<genexpr>   r1   zextract_code.<locals>.<genexpr>zpn.pane.Markdown(z).servable()
Tz# r   c                 s  s   | ]}d |v V  qdS rH   r   rJ   r   r   r    rL      r1   c                 s  s   | ]}d |v rd|v V  qdS )rI   z	template=Nr   rJ   r   r   r    rL      r1   zpn.state.template.title = 
)	readlinelstrip
startswithr;   lenstripjoinclearany)rD   rE   ZinblockZblock_openertitlemarkdownr@   lineZlslineZnum_leading_backticksZsyntaxmdr   r   r    extract_code`   sF    




rZ   c                 C  s  g }t | d s|S | d d}|dd D ]"}|dddd}|| q.|d }d}|sz| sptt| d	}W q^ ty   |sY q|  d| }Y q^0 q^|st	
d
| d   |S | dr|| |S d|v r<|ds<z(|d|d  }t| |}W n ty:   Y n0 ztj|dd W n" typ   || | Y S 0 | d }|d|d| d|d|d	 |S )z
    Parses a code cell and generates wrapper code to capture the
    return value of the cell and any other outputs published inside
    the cell.
    sourcerM   Nzget_ipython().run_line_magicrG   zget_ipython().magicFTzIThe following cell did not contain valid Python syntax and was skipped:

;#eval)modeid_pn__state._cell_outputs[z
].append((zB))
for _cell__out in _CELL__DISPLAY:
    _pn__state._cell_outputs[zr].append(_cell__out)
_CELL__DISPLAY.clear()
_fig__out = _get__figure()
if _fig__out:
    _pn__state._cell_outputs[z].append(_fig__out)
)rQ   splitreplacer;   rR   SyntaxErrorastparsepoplogwarnrstripendswithcountindex)cellcoder[   rX   Zcell_outZparsesZcell_tmpcell_idr   r   r    capture_code_cell   sd    




	rr   c                 C  s   t jst| | d S ddlm} tj|j= ztj	jj
| W n tyP   Y n0 t|dddd}tt dddd}|dt|j d| d| d	d
ddd  d S )Nr   )Alertz[1mz<b>z[0mz</b>z</b>: z
<pre style="overflow-y: auto">z</pre>Zdanger   stretch_width)Z
alert_typemarginsizing_mode)r   
autoreloadr   paners   r6   r7   __name__r   r   _modulesremove
ValueErrorrC   rd   htmlescape	traceback
format_exctypeservable)handlermoduleers   Ze_msgtbr   r   r    autoreload_handle_exception   s    

r   c                   s  z
t  }W n ty(   d }t  Y n0 g } fdd}z>tj  tj t | t	t
jR}td( j|| |r|  W d    n1 s0    Y  W d    n1 s0    Y  W d    n1 s0    Y  W d    n1 s0    Y  W t
jr^z2 jjj}tj|t
jf  |7  < tjd W n ty\   Y n0 tj  |d urt| npt
jrz2 jjj}tj|t
jf  |7  < tjd W n ty   Y n0 tj  |d urt| 0 d S )Nc                    s6   t  } tjrg | j_|  ur2tdjjjf d S )Nz'%s at '%s' replaced the output document)	r   r   rx   r7   r{   RuntimeError_origin_runnerpath)Znewdocdocr   r   r    
post_check   s
    zrun_app.<locals>.post_check)r   	_profiles)r   r   bk_set_curdocr   Z
_launchingr;   r*   _loggersr   r   r   Zprofilerr   r   runZsession_contextrequestr   r   paramtriggerr   r|   )r   r   r   post_runZold_docsessionsr   r   r   r   r    run_app   sH    






r   zstr | os.PathLike | IOzlist[str] | None)filenamepreamblec                 C  s&  t dd}t dd}G dd d|jj}| g}|| |j}| }|D ]}|| qJ||\}	}
||	d}|j	
|}i }t|pg }|d D ]x}|d	 }|d
 di ||< |d dkrt|}||7 }q|d dkrd|d dd}|d|d| d qd|}|||fS )a  
    Parses a notebook on disk and returns a script.

    Arguments
    ---------
    filename: str | os.PathLike
      The notebook file to parse.
    preamble: list[str]
      Any lines of code to prepend to the parsed code output.

    Returns
    -------
    nb: nbformat.NotebookNode
      nbformat dictionary-like representation of the notebook
    code: str
      The parsed and converted script
    cell_layouts: dict
      Dictionary containing the layout and positioning of cells.
    	nbconvertzJThe Panel notebook application handler requires nbconvert to be installed.nbformatzQThe Panel notebook application handler requires Jupyter Notebook to be installed.c                   @  s:   e Zd ZdZedZdddddZdd Zd	d
 Z	dS )z,parse_notebook.<locals>.StripMagicsProcessorz
        Preprocessor to convert notebooks to Python source while stripping
        out all magics (i.e IPython specific syntax).
        z^\s*(?P<magic>%%\w\w+)($|(\s+))rC   )r[   r#   c                 S  s`   g }|  D ]H}| j|}|du r0|| qd}|j| j|dd}t| qd	|S )zZ
            Given the source of a cell, filter out all cell and line magics.
            Nz7Stripping out IPython magic {magic} in code cell {cell}magic)ro   r   rM   )

splitlines_magic_patternmatchr;   format_cell_countergroupri   warningrS   )selfr[   filteredrX   r   msgmessager   r   r    strip_magics;  s    z9parse_notebook.<locals>.StripMagicsProcessor.strip_magicsc                 S  s4   |d dkr,|  j d7  _ | |d |d< ||fS )N	cell_typerp   r   r[   )r   r   )r   ro   	resourcesrn   r   r   r    preprocess_cellJ  s    z<parse_notebook.<locals>.StripMagicsProcessor.preprocess_cellc                 S  s   d| _ | ||S r   )r   
preprocess)r   nbr   r   r   r    __call__P  s    z5parse_notebook.<locals>.StripMagicsProcessor.__call__N)
rz   
__module____qualname____doc__recompiler   r   r   r   r   r   r   r    StripMagicsProcessor3  s
   
r      cellsra   metadatazpanel-layoutr   rp   rW   rG   r[   "z\"rb   z].append("""z""")rM   )r   preprocessorsZPreprocessorread
NO_CONVERTZNotebookExporterZregister_preprocessorZfrom_notebook_nodeZreadsZv4upgradelistr-   rr   rS   rd   r;   )r   r   r   r   r   r   r   ZexporterpreprocessorZ	nb_string_cell_layoutsrp   ro   rq   Z	cell_coderY   r   r   r    parse_notebook  s0    

!

r   c                   @  s    e Zd ZdddddddZdS )	PanelCodeRunnerNr   zCallable[[], None] | NoneNone)r   r   r#   c              
   C  s   t  }ttj}ttj}tjdt j| j t j	| jg| j
t_| jdusZJ znzt| j|j |rv|  W n0 ty } zt| || W Y d}~n
d}~0 0 W t | |t_|t_d| _nt | |t_|t_d| _0 dS )z
        Execute the configured source code in a module and run any post
        checks.

        See bokeh.application.handlers.code_runner for original implementation.
        r   NT)r+   getcwdr   r6   r   argvinsertdirname_pathbasename_argv_codeexec__dict__r   r   chdirZran)r   r   r   Z_cwdZ	_sys_pathZ	_sys_argvr   r   r   r    r   t  s(    


$

zPanelCodeRunner.run)N)rz   r   r   r   r   r   r   r    r   r  s   r   c                   @  s<   e Zd ZdZg dddddddd	d
dZddddZdS )PanelCodeHandlera  Modify Bokeh documents by creating Dashboard from code.

    Additionally this subclass adds support for the ability to:

    - Log session launch, load and destruction
    - Capture document_ready events to track when app is loaded.
    - Add profiling support
    - Ensure that state.curdoc is set
    - Reload the application module if autoreload is enabled
    - Track modules loaded during app execution to enable autoreloading
    Nr   packagerC   r   	list[str]ModuleType | Noner   )r[   r   r   r   r#   c                C  sB   t |  t||||d| _i | _tjD ]}| || j|< q(d S )N)r   )r
   __init__r   r   r   r   r%   Z_make_io_logger)r   r[   r   r   r   r)   r   r   r    r     s
    

zPanelCodeHandler.__init__z
'Document')r   c                 C  s`   t jr.| jj}| jj}t| ||d}|j| _| j }|d u rDd S |j| t	| || d S )N)r   r   )
r   rx   r   r   r   r   
new_moduler7   addr   )r   r   r   r   r   r   r   r   r    modify_document  s    
z PanelCodeHandler.modify_document)rz   r   r   r   r   r   r   r   r   r    r     s   	r   c                      s<   e Zd ZdZdZdZg dddddd	d
 fddZ  ZS )ScriptHandlerzGModify Bokeh documents by creating Dashboard from a Python script.
    zG%s: call to %s() ignored when running scripts with the 'bokeh' command.ZScriptNr   r   r   r   r   r   r   r   r#   c                  sL   t |dd}| }W d   n1 s*0    Y  t j||||d dS )za

        Keywords:
            filename (str) : a path to a Python source (".py") file

        utf-8encodingN)r[   r   r   r   )openr   superr   )r   r   r   r   r)   r[   	__class__r   r    r     s    &zScriptHandler.__init__rz   r   r   r   _logger_textr   r   __classcell__r   r   r   r    r     s   r   c                      s(   e Zd ZdZdZdZ fddZ  ZS )MarkdownHandlerzGModify Bokeh documents by creating Dashboard from a Markdown file.
    zN%s: call to %s() ignored when running Markdown files with the 'panel' command.ZMarkdownc                   sr   d|vrt dtj|d }t|dd}t|}W d   n1 sJ0    Y  ||d< t j|i | dS )z\

        Keywords:
            filename (str) : a path to a Markdown (".md") file

        r   zMust pass a filename to Handlerr   r   Nr[   )r}   r+   r   abspathr   rZ   r   r   )r   r=   r>   r   r)   rp   r   r   r    r     s    &zMarkdownHandler.__init__r   r   r   r   r    r     s   r   c                      s|   e Zd ZdZddgZdZdZg dddd	d
dd fddZdd Zdd Z	dd Z
dd ZdddddZdd Z  ZS )NotebookHandlerzGModify Bokeh documents by creating Dashboard from a notebook file.
    z%from panel import state as _pn__statezbfrom panel.io.handlers import CELL_DISPLAY as _CELL__DISPLAY, display, get_figure as _get__figure
zI%s: call to %s() ignored when running notebooks with the 'panel' command.ZNotebookNr   r   r   r   r   r   c                  s*   |  | t j| ||d d| _dS )zg

        Keywords:
            filename (str) : a path to a Jupyter notebook (".ipynb") file

        )r[   r   FN)_load_layoutr   r   _parse_stale)r   r   r   r   r   r   r    r     s    
zNotebookHandler.__init__c                 C  sR   t || jd\}}}|tj| < | jdi  D ]\}}|tj|  |< q0|| _|S )N)r   r   )r   _importsr   _cell_layouts_layoutr-   r3   _nb)r   r   r   rp   r   rq   layoutr   r   r    r   
  s    
zNotebookHandler._parsec                 C  sh   t |}|jd|j d }| r\t|}t|| _W d    qb1 sP0    Y  ni | _| jS )N..layout)	pathlibPathparentnameis_filer   jsonloadr   )r   r   nb_pathZlayout_pathr)   r   r   r    r     s    

,zNotebookHandler._load_layoutc                 C  sX   ddl m} i }d|v r*d|v r*d|d< n*d|d< t|dkrTt|d	 |rTd
|d< |S )Nr   )PlotlywidthheightZstretch_bothrw   ru   r   r   i,  Z
min_height)ry   r   rQ   
isinstance)r   specpanelsr   paramsr   r   r    _compute_layout  s    
zNotebookHandler._compute_layoutc                   s  ddl m } ddlm} ddlm  ddlm d|_j}djv }djv }|s`|s`d	j_	t
jt
j|d
 dd j_i i i   }}	}
j D ]\}}|ri }n4|| jdi v r| jd | }nj|  |i } fdd|D }||i | ||}|D ]}|j|_q||	|< ||t|< t||
|< |  qd
dl}|| jj|j}d| jv r| jd }n|d dg }i }|D ]}||
vs|rq|
| }|| ||< | jdg D ](}||
vrq|
| }|| ||< q| D ]\}}||vr|||< qqjjj|t j d |r\fdd}!| |rtjj"| j#d |	j$|< dS )a  Renders template containing cell outputs.

        Creates an EditableTemplate containing all cell outputs
        found in the notebook and lays them out according to the
        cell metadata (if present).

        Arguments
        ----------
        doc (Document)
            A ``Document`` to render the template into
        path (str):
            The path to the application code.
        r   r   )Columnpanelr   r   editableresetFr   r    r   c                   s   g | ]}|d ur |qS Nr   )r.   objr  r   r    
<listcomp>J  r1   z4NotebookHandler._render_template.<locals>.<listcomp>Norderr   zpanel-cell-order)r   Z
local_savec                    s8    j j} | dd  t| }|r,d| nd j _d S )Nr  ?rG   )locationZquery_paramsrh   urlparse	urlencodesearch)queryr  r   r   r    unset_reseto  s    
z5NotebookHandler._render_template.<locals>.unset_resetr   )%r   r   r  ry   r  r   templateZ_jupyter_kernel_contextZsession_argsr  r+   r   splitextr   rd   rV   _cell_outputsr3   r   r-   r   r  rw   ra   r   r   r   r   r   r   r   r2   boolZonloadZwatch_update_position_metadata_session_outputs)r   r   r   r   r  Zpersistr  r  Zlayoutsoutputsr   rq   Zobjectsr   r   ZpoutZpor   r   Z
cell_orderZorderedobj_idr  r   )r  r   r    _render_template'  sn    

(




z NotebookHandler._render_templater   )r   r#   c              	     s   j jjstjrT }t|t	
}t|dddj _d_j  }|du rjdS  j|  fdd}t H tdd	 t| | W d   n1 s0    Y  W d   n1 s0    Y  dS )
zRun Bokeh application code to update a ``Document``

        Arguments
        ----------
        doc (Document) : a ``Document`` to update
        r   T)r   r`   dont_inheritFNc                     s2    j s$ tjv s$jjs$  tj  d S r	  )rootsr   Z
_templatesr   errorr  r  rT   r   r   r   r   r   r    r     s    z1NotebookHandler.modify_document.<locals>.post_runZagg)Z
MPLBACKEND)r   r   r   r   rx   r   r   rf   rg   r+   fspathr   r   r   r7   r   r!   r5   r   )r   r   r[   nodesr   r   r   r   r    r   y  s    


zNotebookHandler.modify_documentc                   s   | j }|jjd }tj| }i i  } |d D ]P}|d |v r.||d  }|d  t|< t|jt| }|d= |||d < q. fdd|jD }	||	d}
t	| j
j}|jd|j d }t|d	}t|
| W d
   n1 s0    Y  d| _d
S )z
        Maps EditableTemplate update events to cells in the original
        notebook and then overwrites notebook metadata with updated
        layout information.
        r\   r   ra   c                   s   g | ]} | qS r   r   )r.   r  Zcell_idsr   r    r    r1   z=NotebookHandler._update_position_metadata.<locals>.<listcomp>)r   r  r   r   wNT)r   r
  Z
_documentsr   r  ra   dictnewr   r   r   r   r   r   r   r   dumpr   )r   eventr   r   r  Z	cell_dataro   r@   r   r  Z	nb_layoutr   r   r)   r   r#  r    r    s(    

*z)NotebookHandler._update_position_metadata)rz   r   r   r   r   r   r   r   r   r   r  r  r   r  r   r   r   r   r    r     s    
R%r   )rA   )N)N)H
__future__r   rf   r~   r   loggingr+   r   r   r6   r   urllib.parserg   r  
contextlibr   typesr   typingr   r   r   Zbokeh.command.utilZbokehZbokeh.application.handlers.coder   Z&bokeh.application.handlers.code_runnerr	   Z"bokeh.application.handlers.handlerr
   r   Zbokeh.core.typesr   Zbokeh.documentr   Zbokeh.io.docr   r   r   r   Zbokeh.util.dependenciesr   r   Zmime_renderr   Zprofiler   reloadr   r   	getLoggerri   r:   r!   r*   r5   r8   r   rZ   rr   r   r   r   r   r   r   r   Zapplicationhandlers	directoryr   r   r   r   r   r    <module>   sf   




 1K
*V!, I