
    Bel#                       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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 Z e            Zd	d
dZddgZddgZd6dZ G d dej                  Zd7dZg Z d Z!	 	 	 d8d9d!Z"d"d#d$d%d&d'd(d)d*d+d&d#d,Z#d- Z$d. Z%d/ Z&d0 Z'd1 Z(d2 Z)e%e%e)e)e&e(e)e'e)d3	Z*d4 Z+d5 Z,dS ):a  
Utilities for executing Python code and rendering the resulting output
using a similar MIME-type based rendering system as implemented by
IPython.

Attempts to limit the actual MIME types that have to be rendered on
to a minimum simplifying frontend implementation:

    - application/bokeh: Model JSON representation
    - text/plain: HTML escaped string output
    - text/html: HTML code to insert into the DOM
    )annotationsN)redirect_stderrredirect_stdout)escape)dedent)AnyDictListc                 `   t          t          j        t          j                  j        j                  } t          t          j                  }t          j	                    D ]K}t          |j        dd          }|                    |           rd|vr|                    |j                   L|S )Npath zsite-packages)strpathlibPathsys
executableparentlistbuiltin_module_namespkgutiliter_modulesgetattrmodule_finder
startswithappendname)env_dirmodulesmmpaths       4lib/python3.11/site-packages/panel/io/mime_render.py_stdlibsr"   $   s    ',s~..5<==G3+,,G!## # #44G$$ 	#)E)ENN16"""N    zscikit-learnztransformers-js-py)sklearntransformers_jsjspyodidezbokeh.sampledataas_framecoder   return	List[str]c                h    t                      t          j                   }t                      }t          j        |          D ]}t          |t          j                  r@|j        D ]7}|j        }|	                    |
                    d          d                    8\t          |t          j                  r8|j        }||	                    |
                    d          d                    g }t          |          D ]g}t                              ||          }|t           v r't          |t"                    r|                    |           R|                    |           ht)           fdt*          D                       rd|vr|                    d           d |D             S )a  
    Finds the packages required in a string of code.

    Parameters
    ----------
    code : str
       the Python code to run.

    Returns
    -------
    ``List[str]``
        A list of package names that are to be installed for the code to be able to run.

    Examples
    --------
    >>> code = "import numpy as np; import scipy.stats"
    >>> find_imports(code)
    ['numpy', 'scipy']
    .r   Nc              3      K   | ]}|v V  	d S N ).0pddr)   s     r!   	<genexpr>z$find_requirements.<locals>.<genexpr>b   s'      
5
533$;
5
5
5
5
5
5r#   pandasc                $    g | ]}|t           v|S r0   )_IGNORED_PKGS)r1   pkgs     r!   
<listcomp>z%find_requirements.<locals>.<listcomp>d   s"    @@@Cs-'?'?C'?'?'?r#   )r   astparsesetwalk
isinstanceImportnamesr   addsplit
ImportFrommodulesorted_PACKAGE_MAPget_STDLIBSr   extendr   any_PANDAS_AUTODETECT)	r)   modimportsnoder   	node_namemodule_namepackagesr7   s	   `        r!   find_requirementsrQ   5   s   * $<<D
)D//CeeG 	3 	3dCJ'' 	3
 5 5 I	IOOC00344445 cn-- 	3+K"KK))#..q1222Hg ! !sC(((??T"" 	!OOC    OOC    

5
5
5
5"4
5
5
555 "((:R:R!!!@@8@@@@r#   c                  *     e Zd Zd fd	Z fdZ xZS )WriteCallbackStreamNTc                d    || _         || _        t                                                       d S r/   )_onwrite_escapesuper__init__)selfon_writer   	__class__s      r!   rX   zWriteCallbackStream.__init__l   s-     r#   c                    | j         r+|                      | j        rt          |          n|           t                                          |           d S r/   )rU   rV   r   rW   write)rY   sr[   s     r!   r]   zWriteCallbackStream.writeq   sL    = 	<MMt|:&)));;;ar#   )NT)__name__
__module____qualname__rX   r]   __classcell__)r[   s   @r!   rS   rS   j   sV             
        r#   rS   exprast.Exprast.Expressionc                V    d| _         d| _        t          j        | j        dd          S )zY
    Converts an ast.Expr to and ast.Expression that can be compiled
    and evaled.
    r   )lineno
col_offset)rg   rh   r9   
Expressionvalue)rc   s    r!   _convert_exprrk   v   s+    
 DKDO>$*QQ????r#   c                 T    t                               t          |                      dS )z_
    IPython.display compatibility wrapper.

    Note: This only handles a single display.
    N)_OUT_BUFFERrH   r   )objskwargss     r!   _displayrp      s$     tDzz"""""r#   global_contextDict[str, Any]stdoutr   stderrc           
     p   |r|nt                      }t          |d<   t          j        |           }t	          j        |          }|j        dd         |_        t	          j        |          }|j        dd         |_        |pt          j        }|pt          j	        }t          |          5  t          |          5  	 t          t          |dd          |           |j        sd}nt          |j        d                   t          j        k    r8t!          t          t#          |j        d                   dd          |          }n!t          t          |dd          |           d}|                                                     d          rd}t(          r|t(          d         }n'# t*          $ r d}t-          j        |	           Y nw xY wt(                                           n# t(                                           w xY w	 ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |S )
a  
    Executes a code snippet and returns the resulting output of the
    last line.

    Arguments
    ---------
    code: str
        The code to execute
    global_context: Dict[str, Any]
        The globals to inject into the execution context.
    stdout: io.StringIO
        The stream to redirect stdout to.
    stderr: io.StringIO
        The stream to redirect stderr to.

    Returns
    -------

    The return value of the executed code.
    displayNz<ast>execr   eval;)file)globalsrp   r9   r:   copydeepcopybodyr   rs   rt   r   r   rx   compiletypeExprry   rk   stripendswithrm   	Exception	traceback	print_excclear)r)   rq   rs   rt   code_astinit_astlast_astouts           r!   exec_with_returnr      s   4 (6D^^799N (N9yH}X&&HM#2#&HM}X&&HM"##&HM!szF!szF		 	     /&"9"9    	 7F33^DDD= hmA&''38337=q1A#B#BGVTTVdeeWXw77HHHzz||$$S))  &s{!"o 	- 	- 	-CV,,,,,,	- K%                                                           & Jsm   ,H+<H>C)F('G)(!G	G)GG)H)HHH+H	H+H	H++H/2H/
text/plain	text/htmltext/markdownimage/svg+xml	image/pngapplication/pdf
image/jpegz
text/latexapplication/jsonapplication/javascript)__repr___repr_html__repr_markdown_
_repr_svg_
_repr_png_
_repr_pdf__repr_jpeg__repr_latex_repr_json__repr_javascript_savefigto_htmlc                
    | dfS )Nr   r0   rj   metamimes      r!   
render_svgr      s    +r#   c                    d| d|  }d                     d |                                D                       }d| d| ddfS )	Nzdata:z;charset=utf-8;base64, c                    g | ]\  }}d S )z	{k}="{v}"r0   )r1   kvs      r!   r8   z render_image.<locals>.<listcomp>   s    ;;;dak;;;r#   z
<img src="z" z</img>r   )joinitems)rj   r   r   dataattrss        r!   render_imager      s]    6466u66DHH;;djjll;;;<<E------{::r#   c                    d|  ddfS )Nz<script>z	</script>r   r0   r   s      r!   render_javascriptr      s    &e&&&33r#   c                8    t          j         | g dd          dfS )N)extrasmarty
codehilitehtml5)
extensionsoutput_formatr   )markdownr   s      r!   render_markdownr      s2    ;;;7   r#   c                    |                      d          }t          j        |                              d          }d| }d| ddfS )Nutf-8zdata:application/pdf;base64,z<embed src="z4" width="100%" height="100%" type="application/pdf">r   )encodebase64	b64encodedecode)rj   r   r   r   
base64_pdfsrcs         r!   
render_pdfr      sU    <<  D!$''..w77J
5
5
5CS#SSSU```r#   c                
    | |fS r/   r0   r   s      r!   identityr      s    $;r#   )	r   r   r   r   r   r   r   r   r   c                   |dk    rt          |           S t          | |          r|dk    rxt          j                    }|                     |d           |                    d           t          j        |                                          	                    d          S  t          | |                      S |dk    ri i fS dS )	z'
    Evaluates a formatter method.
    r   r   png)formatr   r   _repr_mimebundle_N)reprhasattrioBytesIOr   seekr   r   readr   r   )objprint_methodbufs      r!   eval_formatterr      s     z!!Cyy	l	#	# 9$$*,,CKKEK***HHQKKK#CHHJJ//66w???)wsL))+++	,	,	,2v4r#   c                   t          | t                    rt          |           dfS t          | d          }t          |t                    r|\  }}n|}dg }}t          t          t                                                              D ]b\  }}||v r	||         }n.t          | t                    r	|dk    rd}nt          | |          }|C|t          vr|                    |           b |t          |          }d}nt          |t                    r|\  }}ni }t          |         |||          \  }	}|dk    rt          |	          }	|	|fS )z0
    Formats object using _repr_x_ methods.
    r   r   Nr   )r=   r   r   r   tuplereversedr   MIME_METHODSr   r   MIME_RENDERERSr   r   )
r   
mimebundleformat_dict_outputnot_availablemethod	mime_typer   contents
             r!   format_mimer     s}    #s )c{{L((%899J*e$$ !#QQ  "MF%d<+=+=+?+?&@&@AA  	## +FFT"" 	1v';';FF#C00F>n,,  +++~f 			FE	"	" '	264KKGYL  //Ir#   )r)   r   r*   r+   )rc   rd   r*   re   )NNN)
r)   r   rq   rr   rs   r   rt   r   r*   r   )-__doc__
__future__r   r9   r   r}   r   r   r   r   r   
contextlibr   r   htmlr   textwrapr   typingr   r	   r
   r   r"   rG   rE   r6   rJ   rQ   StringIOrS   rk   rm   rp   r   r   r   r   r   r   r   r   r   r   r   r0   r#   r!   <module>r      s    # " " " " " 



   				   



     7 7 7 7 7 7 7 7             " " " " " " " " " "    8::+  y!(*5 /A /A /A /Aj
 
 
 
 
"+ 
 
 
@ @ @ @ # # # &*	9 9 9 9 9@ &!#%1 "  ; ; ;
4 4 4  
a a a    /!$
 
  "% % % % %r#   