a
    Df4N                     @  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mZmZ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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( d dl)m*Z+ d dl,m-Z.m/Z/m0Z0m1Z1 d dlm2Z2m3Z3 ddl4m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z?m@Z@mAZA ddlBmBZB de9_CdejDd< zZd dlm:ZE z,d dlFmGZH eHrd dlFmIZI eIe_Id ZJW n eKy   d!ZHd!ZJY n0 W nd eKyn   z2d dlFmGZH eHrJd d"lFm:Z:mIZI e:e_:eIe_IW n eKyd   d!ZHY n0 d ZJY n0 eJrd#ejDd$< zd dlLZLeLM  W n eKy   dZLY n0 zd dlNZOW n eKy   Y n0 d%e	jPv rejQRd&rdtd'd(ZSeSej5jT_0eLdu rXd dlUZUd)d* ZVeUjWZXeYeUjWd+d, ZZeZeU_WeUj[Z\eYeUj[d-d. Z]e]eU_[e^ Z_d/d0d1d2Z`e`eja_bdud3d4d5d6d7Zcd8d9d:d;d<d=Zdi fd>d?Zed3d@dAdBdCZfejghdDZig Zjd!akdEdF ZldGdH Zmd3d/dIdJdKdLZndvd3d/dMdMdNdOdPZod9d3dIdQdRdSZpdTdU ZqdwdVdIdWdXdYZrerejT_serej5jT_sdZd[ Ztd/d9d9d\d]d^Zud_d` ZvdIdadbdcZwd/d9dId\dddeZxd9d/dIdfdgdhZydIdadidjZzdkdl Z{dxdmd4d5dndoZ|d9dpdpd9dqdrdsZ}dS )y    )annotationsN)AnyCallableListTuple)__version__)Buffer
Serialized
Serializer)Document)	PatchJson)script_for_render_items)%standalone_docs_json_and_render_items)wrap_in_script_tag)DocumentReady)
set_curdoc)Model)settings)__file___download_fileexternal_data_dirsplitext)JSONXMLHttpRequest   )config)edit_readonlyisurl   )	resourcesMockSessionContext)LOADING_INDICATOR_CSS_CLASS)WriteCallbackStreamexec_with_returnformat_mime)stateZCDNZcdnZBOKEH_RESOURCESdocument)RUNNING_IN_WORKER)windowTF)r(   r*   ZaggZ
MPLBACKENDZpyolite/drive/assets/sampledatac                 C  s   dS )Nr+    creater,   r,   ]/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/panel/io/pyodide.py_sampledata_dir`   s    r0   c                  O  sZ   | r0t | d r0tj| d f| dd   } n"t |drRtj|d |d< | |fS )Nr   r   Zfilepath_or_buffer)r   pyodidehttpZopen_urlgetargskwargsr,   r,   r/   
_read_fileg   s
     r7   c                  O  s    t | i |\} }t| i |S N)r7   _read_csv_originalr4   r,   r,   r/   	_read_csvp   s    r:   c                  O  s    t | i |\} }t| i |S r8   )r7   _read_json_originalr4   r,   r,   r/   
_read_jsonx   s    r<   r   )funcc                 C  sD   t  }| r4t |  }t| |tj n||   d S r8   )	asyncioZget_running_loopZ
is_runningcreate_task_tasksaddadd_done_callbackdiscardZrun_until_complete)r=   Z
event_looptaskr,   r,   r/   async_execute   s    
rE   r   zTuple[str, str, str])docreturnc                 C  s   t | jdd\}}dd |D }dd | jD }|rjtdd |D }|d dd	 t||D |d
 t|t|t|fS )a  
    Serializes a Bokeh Document into JSON representations of the entire
    Document, the individual render_items and the ids of DOM nodes to
    render each item into.

    Arguments
    ---------
    doc: bokeh.document.Document
        The Bokeh document to serialize to JSON.
    root_els:
        A list of DOM nodes to render each root of the Document into.

    Returns
    -------
    docs_json: str
    render_items: str
    root_ids: str
    TZsuppress_callback_warningc                 S  s   g | ]}|  qS r,   )to_json).0itemr,   r,   r/   
<listcomp>       z_doc_json.<locals>.<listcomp>c                 S  s   g | ]
}|j qS r,   )id)rJ   mr,   r,   r/   rL      rM   c                 S  s   g | ]}| d |jfqS )zdata-root-id)getAttributerN   )rJ   elr,   r,   r/   rL      rM   r   c                 S  s   i | ]\\}}}||qS r,   r,   )rJ   _ZelidZmodel_idr,   r,   r/   
<dictcomp>   rM   z_doc_json.<locals>.<dictcomp>)rootsroot_ids)r   rT   sortedupdatezipjsondumps)rF   root_els	docs_jsonrender_itemsZrender_items_jsonrU   Z	root_datar,   r,   r/   	_doc_json   s    
r^   r   strzTuple[Document, str])modeltargetrG   c              	   C  sf   t  }|  | j|d |jd } t| gdd\}}t| d }|tt	|| j
d |tdfS )a  
    Renders a Bokeh Model to JSON representation given a particular
    DOM target and returns the Document and the serialized JSON string.

    Arguments
    ---------
    model: bokeh.model.Model
        The bokeh model to render.
    target: str
        The id of the DOM node to render to.

    Returns
    -------
    document: Document
        The bokeh Document containing the rendered Bokeh Model.
    model_json: str
        The serialized JSON representation of the Bokeh Model.
    rF   r   TrH   rN   )Z	target_idZroot_idrF   version)r   hold
server_docrT   r   listvaluesrY   rZ   dictrefr   )r`   ra   rF   r\   rR   Zdoc_jsonr,   r,   r/   _model_json   s    

rj   c                   s   t | tr  fdd|  D S t | tr< fdd| D S t | tr\t fdd| D S t | tr~| j v rv| jS |  S | S )at  
    Recursively iterates over a JSON patch and converts Buffer objects
    to a reference or base64 serialized representation.

    Arguments
    ---------
    obj: dict
        Dictionary containing events to patch the JS Document with.
    buffers: dict
        Binary array buffers.

    Returns
    --------
    Serialization safe version of the original object.
    c                   s   i | ]\}}|t | d qS buffers_serialize_buffers)rJ   keyorl   r,   r/   rS      s   z&_serialize_buffers.<locals>.<dictcomp>c                   s   g | ]}t | d qS rk   rn   rJ   rq   rl   r,   r/   rL      s   z&_serialize_buffers.<locals>.<listcomp>c                 3  s   | ]}t | d V  qdS )rl   Nrn   rr   rl   r,   r/   	<genexpr>   s   z%_serialize_buffers.<locals>.<genexpr>)	
isinstancerh   itemsrf   tupler   rN   ri   Z	to_base64)objrm   r,   rl   r/   ro      s"    






ro   z	List[Any])rF   eventsc                 C  sd   t | jjd}t||d}| j  i }|jD ]}tj	|
 j||j< q2t||d}||fS )N)Z
references)rx   rl   )r
   modelsZsynced_referencesr   encodeZflush_syncedrm   r1   ffito_jsto_bytesbufferrN   ro   )rF   rx   
serializerZ
patch_json
buffer_mapr~   r,   r,   r/   _process_document_events   s    

r   z
((entries) => {
  for (let entry of entries) {
    if (entry[1] === undefined) {
      entry[1] = null;
    }
  }
  return Object.fromEntries(entries);
})
c                 C  sF   t | ds| S t|  } t j}tt|| d 	 d d|iS )Nr~   )rN   datarN   )
hasattrrh   Zobject_entriesuuiduuid4hex_current_buffersappendr   r}   )value	converterotheruidr,   r,   r/   _bytes_converter  s    

r   c                 C  s8   z(| j td}t|ttd}W t  n
t  0 |S )N)Zdefault_converter)contentrm   )to_pyr   r	   rf   r   clear)
json_patchpatchZ
serializedr,   r,   r/   _convert_json_patch  s
    r   None)pydocjsdocrG   c              
     s    fdd}  tj|tjd  fdd} | z  jt  W n2 t	y } zt
d|  W Y d}~n
d}~0 0 dS )a1  
    Links Python and JS documents in Pyodide ensuring that messages
    are passed between them.

    Arguments
    ---------
    pydoc: bokeh.document.Document
        The Python Bokeh Document instance to sync.
    jsdoc: Javascript Document
        The Javascript Bokeh Document instance to sync.
    c                   sR   t | dd }|d ur|dks tr$d S  tj| g}t|}j|dd d S )N	setter_idpythonjs)setter)getattr	_patchingZcreate_json_patchr1   r{   r|   r   apply_json_patch)eventr   r   r   r   r   r,   r/   jssync+  s    z_link_docs.<locals>.jssyncFc                   sp   t | dd }|d ur |dkr d S t| g\}}tjj|td}tj|}daz || W danda0 d S )Nr   r   Zdict_converterTF)r   r   r1   r{   r|   _dict_converterr   r   )r   r   r   r   r   r,   r/   pysync5  s    z_link_docs.<locals>.pysyncz/Error raised while processing Document events: N)	on_changer1   r{   Zcreate_proxyr|   unhold	callbackstrigger_eventr   	Exceptionprint)r   r   r   r   er,   r   r/   
_link_docs  s    
r   z
str | None)rF   dispatch_fnmsg_idr   c                   s6    fdd} |   jt  dS )a  
    Links the Python document to a dispatch_fn which can be used to
    sync messages between a WebWorker and the main thread in the
    browser.

    Arguments
    ---------
    doc: bokeh.document.Document
        The document to dispatch messages from.
    dispatch_fn: JS function
        The Javascript function to dispatch messages to.
    setter: str
        Setter ID used for suppressing events.
    msg_id: str | None
        An optional message ID to pass through to the dispatch_fn.
    c                   sT   d urt | dd krd S t| g\}}tjj|td} |tj| d S )Nr   r   )r   r   r1   r{   r|   r   )r   r   r   r   rF   r   r   r,   r/   r   \  s
    z!_link_docs_worker.<locals>.pysyncN)r   r   r   r   r   )rF   r   r   r   r   r,   r   r/   _link_docs_workerK  s    
r   )ri   rF   rG   c                   sh   t jjj }| |vr:tdI dH  t| |I dH  dS t jjj }||	|  }t
||jj dS )a  
    Links a rendered Bokeh model on the frontend to a Python Document
    in Python.

    Arguments
    ---------
    ref: str
        The ID of the rendered bokeh Model
    doc: bokeh.document.Document
        The bokeh Document to sync the rendered Model with.
    g?N)r   r*   BokehindexZobject_keysr>   sleep_link_modelZobject_valuesindexOfr   r`   r(   )ri   rF   renderedviewsviewr,   r,   r/   r   g  s    r   c                   C  sL   dt jv r(tt jd dr(t jd  S tt jdr<t jjS tsHtdd S )N__main__get_current_display_target_outz,Could not determine target node to write to.)sysmodulesr   r   stdoutr   
_IN_WORKER
ValueErrorr,   r,   r,   r/   _get_pyscript_target|  s    r   bool)progressrG   c              	   C  s   t dd}d}tttjd }t|}W d   n1 sB0    Y  |D ]\}}t|\}}|dkrt|d s|d7 }n||7 }|| }	|		 rt|	d	}
|

 }W d   n1 s0    Y  t| }||krqPt|||| d
 qPdS )z#
    Download bokeh sampledata
    Tr-   zhttps://sampledata.bokeh.orgzsampledata.jsonNz.zipr   z.csvrb)r   )r   openpathlibPath_bk_util_dirparentrY   loadr   existsreadhashlibmd5	hexdigestr   )r   data_dirZs3ffilesfilenamer   Z	real_nameext	real_pathfiler   Z	local_md5r,   r,   r/   _download_sampledata  s$    
(
&r   c                 C  sD   t stdt }d|_|d| d |  t|j	
  S )Nz6Cannot make synchronous binary request in main thread.Zarraybufferr3   F)r   RuntimeErrorr   newZresponseTyper   sendioBytesIOresponser   tobytes)urlZxhrr,   r,   r/   fetch_binary  s    r   )rw   ra   rG   c           
      C  s   ddl m} ddlm} t }|| j|dd t|jdd\}\}|jD ]}||jj|< qJ|	|j
d	 t||g}tt|jd jd
 |}	t|	 |	tj t|S )z
    Generates a script to render the supplied object to the target.

    Arguments
    ---------
    obj: Viewable
        Object to render into the DOM node
    target: str
        Target ID of the DOM node to render the object into.
    r   r'   r   panelF)locationTrH   zbk-rootrN   )r   r(   paner   r   re   r   rT   Z_rootsZgetElementById	classListrA   r   r>   r?   r   ri   r@   rB   rC   r   )
rw   ra   r(   as_panelrF   r\   Zrender_itemrootscriptrD   r,   r,   r/   render_script  s    

r   c                  O  s   t ddS )z7
    Stub to replace Tornado based serve function.
    z,Cannot serve application in pyodide context.N)r   r4   r,   r,   r/   serve  s    r   )rG   c                     s:   t jd t  t      fdd _ t_dS )zP
    Creates a Document mocking a server context for embedded Pyodide apps.
    Fc                     s
   t  dS )Nr'   r    r,   rb   r,   r/   <lambda>  rM   zinit_doc.<locals>.<lambda>N)	bk_settingsZ
simple_ids	set_valuer   r   rd   _session_contextr&   curdocr,   r,   rb   r/   init_doc  s    r   c                   s*   ddl m} |d t|| I dH  dS )z
    Renders the object into a DOM node specified by the target.

    Arguments
    ---------
    obj: Viewable
        Object to render into the DOM node
    target: str
        Target ID of the DOM node to render the object into.
    r   )consolezFpanel.io.pyodide.show is deprecated in favor of panel.io.pyodide.writeN)r   r   logwrite)rw   ra   r   r,   r,   r/   show  s    
r   )ra   rw   rG   c                   sf   ddl m} ||}t|| \}}tjjjt	|I dH }t
|jd jj}t|| |  dS )z
    Renders the object into a DOM node specified by the target.

    Arguments
    ---------
    target: str
        Target ID of the DOM node to render the object into.
    obj: Viewable
        Object to render into the DOM node
    r   r   Nr   )r   r   rj   r   r*   r   embedZ
embed_itemr   parserf   rT   r`   r(   r   r   )ra   rw   r   r   
model_jsonr   r   r,   r,   r/   r     s    
r   c                  C  s4   ddl m}  | dd }|jtdtj  dS )z+
    Hides the global loading spinner.
    r   r'   bodyzpn-N)r   r(   ZgetElementsByTagNamer   remover"   r   Zloading_spinner)r(   r   r,   r,   r/   hide_loader  s    r   c                  C  s   t js
dS zttjj} W n ty0   Y dS 0 t| }t	t j, t jj
dd | D  W d   n1 sx0    Y  dS )zI
    Syncs the JS window.location with the Panel Location component.
    Nc                 S  s"   i | ]\}}|t jjv r||qS r,   )r&   r   param)rJ   kvr,   r,   r/   rS     s   z!sync_location.<locals>.<dictcomp>)r&   r   r   Z	stringifyr   r*   r   rY   loadsr   r   rW   ru   )Z
loc_stringZloc_datar,   r,   r/   sync_location  s    
r   zDocument | Nonec           
        s   | pt j}|t jv r@|t j| jvr@t j| }|j|jd|d z tjd}|D ]
}d|_	qRW n t
yv   d}Y n0 t||\}}}d|_|durtjjjt|t|I dH }t|d jd jj}	t||	 t  t  |||fS )a%  
    Renders the contents of the Document into an existing template.
    Note that this assumes that the HTML file this function runs in
    was itself generated from the code being run. This function may
    be used in the main browser thread or from within a WebWorker.
    If invoked by a WebWorker the JSON return values can be sent
    to the main thread for rendering.

    Arguments
    ---------
    doc: Document
       The document to render to JSON.

    Returns
    -------
    docs_json: str
    render_items: str
    root_ids: str
    T)titler   rF   z[data-root-id] Nr   )r&   r   Z
_templatesZ
_documentsre   r   r   r(   ZquerySelectorAll	innerHTMLr   r^   r   r*   r   r   Zembed_itemsr   r   rf   rT   r`   r   r   r   )
rF   r   templater[   rQ   r\   r]   rU   r   r   r,   r,   r/   	write_doc  s&    


$
r  zCallable[[str], None] | None)codestdout_callbackstderr_callbackra   c                   s   ddl m}m}m} ddlm} ddlm}m}	 |||f}
i }|rNt	||d< |r^t	||d< t
| fi | i }t t||	fst fdd|
D rt| |\}}|tj|< |d	 |d
< |d< n durt \|d
< |d< tj|S )a1  
    Executes Python code and returns a MIME representation of the
    return value.

    Arguments
    ---------
    code: str
        Python code to execute
    stdout_callback: Callable[[str, str], None] | None
        Callback executed with output written to stdout.
    stderr_callback: Callable[[str, str], None] | None
        Callback executed with output written to stderr.
    target: str
        The ID of the DOM node to write the output into.

    Returns
    -------
    Returns an JS Map containing the content, mime_type, stdout and stderr.
    r   )	HoloViewsInteractiver   )ReactiveExpr)ViewableViewerr   stderrc                 3  s   | ]}|  V  qd S r8   )Zapplies)rJ   r   outr,   r/   rs   h  rM   zpyrender.<locals>.<genexpr>zapplication/bokehr   Z	mime_typeN)r   r  r  r   r   r	  Zviewabler
  r  r#   r$   rt   r   anyrj   r&   cacher%   r1   r{   r|   )r  r  r  ra   r  r  r   r	  r
  r  ZPANESr6   retrF   r   r,   r  r/   pyrenderD  s$    
&
r  )N)N)NN)F)N)~
__future__r   r>   	functoolsr   r   rY   osr   r   r   typingr   r   r   r   Zbokehr   r   r1   r   Zbokeh.core.serializationr   r	   r
   Zbokeh.documentr   Zbokeh.document.jsonr   Zbokeh.embed.elementsr   Zbokeh.embed.utilr   Zbokeh.embed.wrappersr   Zbokeh.eventsr   Zbokeh.io.docr   Zbokeh.modelr   Zbokeh.settingsr   r   Zbokeh.util.sampledatar   r   r   r   r   r   r   r   utilr   r   r   r   r(   r!   Zloadingr"   Zmime_renderr#   r$   r%   r&   ZRESOURCE_MODEenvironZjs_documentZpyscriptr)   Z_IN_PYSCRIPT_WORKERr*   r   r   Zpyodide_httpZ	patch_allZ fsspec.implementations.http_syncZfsspecr   pathr   r0   Z
sampledataZpandasr7   Zread_csvr9   wrapsr:   	read_jsonr;   r<   setr@   rE   ZparameterizedZasync_executorr^   rj   ro   r   r  Zrun_jsr   r   r   r   r   r   r   r   r   r   downloadr   r   r   r   r   r   r   r   r  r  r,   r,   r,   r/   <module>   s   













 ##
-

		,