
    BeG                       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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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,m-Z-m.Z. d dl/m0Z0m1Z1 ddl2m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z>m?Z? ddl@m@Z@ de7_A        dejB        d<   	 d dl/m8ZC dZDn# eE$ r dZDY nw xY w	 d dlFZF eFjG                     n# eE$ r dZFY nw xY w	 d dlHZIn# eE$ r Y nw xY wd e	jJ        v r/ejK        L                    d!          rdXd"ZMeMej3        jN        _-        eF_d dlOZOd# ZPeOjQ        ZR ejS        eOjQ                  d$             ZTeTeO_Q        eOjU        ZV ejS        eOjU                  d%             ZWeWeO_U        dYd(ZXeXejY        _Z        dXdZd-Z[d[d3Z\i fd4Z]d\d7Z^ej_        `                    d8          Zad]d<Zbd^d_dAZcd`dCZddD ZedadbdGZfefejN        _g        efej3        jN        _g        dH ZhdcdJZidK ZjdddLZkdedMZldfdNZmdddOZndP ZodXdgdRZpdhdWZqdS )i    )annotationsN)AnyCallableListTuple)__version__)Buffer
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)stateCDNcdnBOKEH_RESOURCESdocumentFTpyolite/drive/assets/sampledatac                    dS )Nr-    creates    0lib/python3.11/site-packages/panel/io/pyodide.py_sampledata_dirr3   I   s    ))    c                 0   | rGt          | d                   r2t          j                            | d                   f| dd          z   } nJt          |                    d                    r(t          j                            |d                   |d<   | |fS )Nr   r   filepath_or_buffer)r   pyodidehttpopen_urlgetargskwargss     r2   
_read_filer>   P   s     	_E$q'NN 	_L))$q'224T!""X=DD6::23344 	_+2<+@+@H\A]+^+^F'(V|r4   c                 8    t          | i |\  } }t          | i |S N)r>   _read_csv_originalr;   s     r2   	_read_csvrB   Y   s+    !42622f!426222r4   c                 8    t          | i |\  } }t          | i |S r@   )r>   _read_json_originalr;   s     r2   
_read_jsonrE   a   s+    !42622f"D3F333r4   funcr   c                    t          j                    }|                                rt          j         |                        n|                     |                        d S r@   )asyncioget_running_loop
is_runningcreate_taskrun_until_complete)rF   
event_loops     r2   async_executerN   g   s]    )++J .DDFF####%%ddff---
Fr4   docr   returnTuple[str, str, str]c                   t          | j        d          \  }}d |D             }d | j        D             }|rOt          d |D                       }|d                             d t	          ||          D             |d           t          j        |          t          j        |          t          j        |          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suppress_callback_warningc                6    g | ]}|                                 S r/   )to_json).0items     r2   
<listcomp>z_doc_json.<locals>.<listcomp>   s     AAADAAAr4   c                    g | ]	}|j         
S r/   )id)rW   ms     r2   rY   z_doc_json.<locals>.<listcomp>   s    ((((((r4   c                F    g | ]}|                     d           |j        fS )zdata-root-id)getAttributer[   )rW   els     r2   rY   z_doc_json.<locals>.<listcomp>   s+    XXXR__^<<beDXXXr4   r   c                     i | ]\  \  }}}||S r/   r/   )rW   _elidmodel_ids       r2   
<dictcomp>z_doc_json.<locals>.<dictcomp>   s#    YYY)<!THhYYYr4   )rootsroot_ids)r   re   sortedupdatezipjsondumps)rO   root_els	docs_jsonrender_itemsrender_items_jsonrf   	root_datas          r2   	_doc_jsonrq   q   s    & D	T  I| BALAAA((ci(((H XXxXXXYY	!##YYIx@X@XYYY %
 %
 	 	 	 :i  $*->"?"?HAUAUUUr4   modelr   targetstrTuple[Document, str]c           	     r   t                      }|                                 |                     |           |j        d         } t	          | gd          \  }}t          |                                          d         }|t          j        t          || j
        d         |t                              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.
    rO   r   TrS   r[   )	target_idroot_idrO   version)r   hold
server_docre   r   listvaluesrj   rk   dictrefr   )rr   rs   rO   rm   ra   doc_jsons         r2   _model_jsonr      s    & **CHHJJJ	IaLE8	4  LIq I$$&&''*H
4IdO	      r4   c                   t          | t                    r fd|                                 D             S t          | t                    rfd| D             S t          | t                    rt	          fd| D                       S t          | t
                    r$| j        v r| 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                :    i | ]\  }}|t          |           S buffers_serialize_buffers)rW   keyor   s      r2   rd   z&_serialize_buffers.<locals>.<dictcomp>   s:     
 
 
<BCC#Aw777
 
 
r4   c                2    g | ]}t          |           S r   r   rW   r   r   s     r2   rY   z&_serialize_buffers.<locals>.<listcomp>   s4     
 
 
78q'222
 
 
r4   c              3  :   K   | ]}t          |           V  dS )r   Nr   r   s     r2   	<genexpr>z%_serialize_buffers.<locals>.<genexpr>   sB       
 
78q'222
 
 
 
 
 
r4   )	
isinstancer   itemsr}   tupler	   r[   r   	to_base64)objr   s    `r2   r   r      s     #t #
 
 
 
FIiikk
 
 
 	
 
C		 #
 
 
 
<?
 
 
 	
 
C		 # 
 
 
 
<?
 
 
 
 
 	
 
C	 	  #6W7N==??"Jr4   events	List[Any]c                l   t          | j        j                  }t          |                    |                    }| j                                         i }|j        D ]@}t          j        	                    |
                                          j        ||j        <   At          ||          }||fS )N)
references)r   r   )r
   modelssynced_referencesr   encodeflush_syncedr   r7   ffito_jsto_bytesbufferr[   r   )rO   r   
serializer
patch_json
buffer_mapr   s         r2   _process_document_eventsr      s    sz'CDDDJ*"3"3F";";<<<JJJ$ L L ' 1 1&//2C2C D D K
69#J
CCCJz!!r4   z
((entries) => {
  for (let entry of entries) {
    if (entry[1] === undefined) {
      entry[1] = null;
    }
  }
  return Object.fromEntries(entries);
})
pydocjsdocNonec                     fd}                     t          j                            |          t          j                            d                      fd}                      |           	                                    j                            t                                 dS # t          $ r}t          d|            Y d}~dS d}~ww xY w)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                    t          | dd           }||dk    rd S                     t          j                            | g                    }                    |                                d           d S )N	setter_idpythonjs)setter)getattrcreate_json_patchr7   r   r   apply_json_patchto_py)eventr   
json_patchr   r   s      r2   jssyncz_link_docs.<locals>.jssync   sy    E;55	!i8&;&;F,,W[->->w-G-GHH
z//11$?????r4   Fc                   t          | dd           }||dk    rd S t          | g          \  }}t          j                            |t
                    }t          j                            |          }                    ||           d S )Nr   r   dict_converter)r   r   r7   r   r   _dict_converterr   )r   r   r   r   r   r   s       r2   pysyncz_link_docs.<locals>.pysync  s    $//&D..F!9%%!I!I
J[&&z/&RR
[&&z22
z:66666r4   z/Error raised while processing Document events: N)	on_changer7   r   create_proxyr   unhold	callbackstrigger_eventr   	Exceptionprint)r   r   r   r   es   ``   r2   
_link_docsr      s   @ @ @ @ @ @ 
OOGK,,V44gk6G6G6N6NOOO7 7 7 7 7 7 
OOFE%%moo66666 E E ECCCDDDDDDDDDEs   5:B1 1
C;CCdispatch_fnmsg_id
str | Noner   c                      f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                   t          | dd           k    rd S t          | g          \  }}t          j                            |t
                    } |t          j                            |                     d S )Nr   r   )r   r   r7   r   r   r   )r   r   r   r   rO   r   r   s      r2   r   z!_link_docs_worker.<locals>.pysync%  s~    '%4"@"@F"J"JF!9#w!G!G
J[&&z/&RR
J 1 1* = =vFFFFFr4   N)r   r   r   r   r   )rO   r   r   r   r   s   ```` r2   _link_docs_workerr     sw    "G G G G G G G G MM&JJLLLM00000r4   r   c                P  K   ddl m} |j                                        }| |vr2t	          j        d           d{V  t          | |           d{V  dS |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.
    r   Bokehg?N)r   r   indexobject_keysrH   sleep_link_modelobject_valuesindexOfr   rr   r+   )r   rO   r   renderedviewsviews         r2   r   r   0  s       {&&((H
(mC         #s#########K%%''E!!#&&'DsDJ'(((((r4   c                 ,   dt           j        v rDt          t           j        d         d          r$t           j        d                                         S t          t           j        d          rt           j        j        S t          st          d          d S )N__main__get_current_display_target_outz,Could not determine target node to write to.)sysmoduleshasattrr   stdoutr   
_IN_WORKER
ValueErrorr/   r4   r2   _get_pyscript_targetr   F  s    S[  WS[-DFb%c%c {:&AACCC	V	$	$ Iz IGHHHI Ir4   progressboolc                   t          d          }d}t          t          j        t                    j        dz            5 }t          j        |          }ddd           n# 1 swxY w Y   |D ]\  }}t          |          \  }}|dk    rt          |          d         s|dz  }n||z  }||z  }	|		                                rit          |	d	          5 }
|

                                }ddd           n# 1 swxY w Y   t          j        |                                          }||k    rt          |||| 
           dS )z#
    Download bokeh sampledata
    Tr0   zhttps://sampledata.bokeh.orgzsampledata.jsonNz.zipr   z.csvrb)r   )r   openpathlibPath_bk_util_dirparentrj   loadr   existsreadhashlibmd5	hexdigestr   )r   data_dirs3ffilesfilenamer   	real_nameext	real_pathfiledata	local_md5s                r2   _download_sampledatar   P  s    !---H	'B	gl<((/2CC	D	D 	!               B B#!(++	3&==I&&q) $V#	Iy(	 	i&& #$yy{{# # # # # # # # # # # # # # #D))3355ICr8XAAAAAB Bs$   A""A&)A&C66C:	=C:	c                2   t           st          d          t          j                    }d|_        |                    d| d           |                                 t          j        |j	        
                                                                          S )Nz6Cannot make synchronous binary request in main thread.arraybufferr:   F)r   RuntimeErrorr   newresponseTyper   sendioBytesIOresponser   tobytes)urlxhrs     r2   fetch_binaryr  o  s}     USTTT



C$CHHUCHHJJJ:cl((**2244555r4   r   c                   ddl m} ddlm} t	                      } ||                               |d           t          |j        d          \  }\  }|j        D ]}||j        j        |<   |	                    |          j
                            d	           t          ||g          }t          j        t          |j        d         j        d
         |                     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)locationTrS   zbk-rootr[   )r   r+   paner
  r   r|   r   re   _rootsgetElementById	classListaddr   rH   rK   r   r   r   )	r   rs   r+   as_panelrO   rm   render_itemrootscripts	            r2   render_scriptr  x  s    ((((((
**CHSMMS5111 E	T! ! !I~ 	 0 0)/ &&F##-11)<<<$Y>>FCIaL$4T$:C@@AAAf%%%r4   c                      t          d          )z7
    Stub to replace Tornado based serve function.
    z,Cannot serve application in pyodide context.)r   r;   s     r2   server    s     E
F
FFr4   c                      t           j                            d           t                       t	                                                         fd _         t          _        dS )zP
    Creates a Document mocking a server context for embedded Pyodide apps.
    Fc                 $    t                     S )Nr*   r    rw   s   r2   <lambda>zinit_doc.<locals>.<lambda>  s    #5s#C#C#C r4   N)	bk_settings
simple_ids	set_valuer   r   r{   _session_contextr&   curdocrw   s   @r2   init_docr     sY     $$U+++
**CsOOOHHJJJCCCCCELLLr4   c                l   K   ddl m} |                    d           t          ||            d{V  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)r   rs   r"  s      r2   showr%    sU       KKXYYY


r4   c                R  K   ddl m} ddlm}  ||          }t	          ||           \  }}|j                            t          j        |                     d{V }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   r   r	  N)r   r   r  r
  r   embed
embed_itemr   parser}   re   rr   r+   r   r   )rs   r   r   r  r   
model_jsonr   r   s           r2   r$  r$    s       ((((((
(3--C#C00E:+((J)?)?@@@@@@@@Ea &/Eue	LLNNNNNr4   c                     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+   getElementsByTagNamer  remover"   r   loading_spinner)r+   r,  s     r2   hide_loaderr0    sY     ((003DN57UV=S7U7UVVVVVr4   c                 l   t           j        sdS ddlm}  t	          j        | j                  }t          j        |          }t          t           j                  5  t           j        j	        
                    d |                                D                        ddd           dS # 1 swxY w Y   dS )zI
    Syncs the JS window.location with the Panel Location component.
    Nr   )windowc                @    i | ]\  }}|t           j        j        v ||S r/   )r&   r  param)rW   kvs      r2   rd   z!sync_location.<locals>.<dictcomp>  s4     %
 %
 %
Qen6J1J1JAq1J1J1Jr4   )r&   r  r   r2  r   	stringifyrj   loadsr   r4  rh   r   )r2  
loc_stringloc_datas      r2   sync_locationr;    s     > 00Jz*%%H	u~	&	&  ## %
 %
%^^--%
 %
 %
 	 	 	                 s   AB))B-0B-Document | Nonec                  K   | pt           j        }|t           j        v rH|t           j        |         j        vr/t           j        |         }|                    |j        d|           	 ddlm}m} |	                    d          }|D ]	}d|_
        
n# t          $ r d}Y nw xY wt          ||          \  }}}	d|_        ||j                            t!          j        |          t!          j        |                     d{V }
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  rO   r   )r   r+   z[data-root-id] N)r&   r  
_templates
_documentsr|   r>  r   r   r+   querySelectorAll	innerHTMLr   rq   r  r'  embed_itemsr   r)  r}   re   rr   r   r;  r0  )rO   r   templater   r+   rl   r_   rm   rn   rf   r   r   s               r2   	write_docrF    s     ( )U\E   U%2B52I2T%T%T#E*(.4UKKK&&&&&&&&,,-=>> 	 	BBLL	   (1%(B(B%I|X!E k--dj.C.CTZP\E]E]^^^^^^^^U1X^$$Q'-65%   lH,,s   ()B B! B!codestdout_callbackCallable[[str], None] | Nonestderr_callbackc                   ddl m}m}m} ddlm}m} i }	|rt          |          |	d<   |rt          |          |	d<   t          | fi |	}
i }t          |
t          ||f          s*|                    |
          s|                    |
          r7t           ||
          |          \  }}|t          j        |<   |dc|d<   |d<   n|
t          |
          \  |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
  )ViewableViewerr   stderrzapplication/bokehcontent	mime_type)r  rL  rM  r
  viewablerN  rO  r#   r$   r   r   appliesr   r&   cacher%   r7   r   r   )rG  rH  rJ  rs   rL  rM  r  rN  rO  r=   outretrO   r*  s                 r2   pyrenderrX    sJ   2 A@@@@@@@@@++++++++F @.??x @.??x
4
*
*6
*
*C
C#x011 <Y5F5Fs5K5K <{ObObcfOgOg <%hhsmmV<<Z!F+57J(IK((	+6s+;+;(IK(;S!!!r4   r@   )rF   r   )rO   r   rP   rQ   )rr   r   rs   rt   rP   ru   )rO   r   r   r   )r   r   r   r   rP   r   )NN)rO   r   r   r   r   r   r   r   )r   rt   rO   r   rP   r   )F)r   r   rP   r   )r   r   rs   rt   rP   rt   )rP   r   )r   r   rs   rt   rP   r   )rs   rt   r   r   rP   r   )rO   r<  rP   rQ   )rG  rt   rH  rI  rJ  rI  rs   rt   )r
__future__r   rH   	functoolsr   r  rj   osr   r   typingr   r   r   r   bokehr4  r7   r   bokeh.core.serializationr	   r
   bokeh.documentr   bokeh.document.jsonr   bokeh.embed.elementsr   bokeh.embed.utilr   bokeh.embed.wrappersr   bokeh.eventsr   bokeh.io.docr   bokeh.modelr   bokeh.settingsr   r  bokeh.util.sampledatar   r   r   r   r   r   r   r   r   utilr   r   r?  r   r+   r!   loadingr"   mime_renderr#   r$   r%   r&   RESOURCE_MODEenvironjs_documentr   r   pyodide_http	patch_all fsspec.implementations.http_syncfsspecr   pathr   r3   
sampledatapandasr>   read_csvrA   wrapsrB   	read_jsonrD   rE   rN   parameterizedasync_executorrq   r   r   r   rG  run_jsr   r   r   r   r   r   downloadr  r  r  r   r%  r$  r0  r;  rF  rX  r/   r4   r2   <module>r}     s   " " " " " "       				  				  



                     7 7 7 7 7 7 7 7 # # # # # # ) ) ) ) ) ) 8 8 8 8 8 8 B B B B B B 3 3 3 3 3 3 & & & & & & # # # # # #       2 2 2 2 2 2            $ # # # # # # #       ' ' ' ' ' ' ' '       ( ( ( ( ( ( 0 0 0 0 0 0 K K K K K K K K K K      	  %
 ******JJ   JJJ	L 	 	 	LD		+++++ 	 	 	D	 /I J J* * * *.=EJ+MMM    Y_V_%%3 3 &%3  FO !*Y_V%&&4 4 '&4 "F    &3  "V V V V V@! ! ! !F %' ! ! ! !F	" 	" 	" 	" ,%% 	' 	 	$E $E $E $EL1 1 1 1 18) ) ) ),I I IB B B B B0 1  !5
  6 6 6& & & &6G G G	 	 	 	      .W W W W  +- +- +- +- +-Z(" (" (" (" (" ("s6   C" "C,+C,0D DDD DD