
    -Ph?                         d 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	Z
ddlmZ ddlmZ ddlmZ e
j        j                            d	          Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!dS )a#  Binder and Jupyterlite utility functions.

Integration with Binder and Jupyterlite is on an experimental stage. Note that
this API may change in the future.

.. warning::

   Binder is still beta technology, so there may be instability in the
   experience of users who click Binder links.

    N)Path)quote)ConfigError   )glr_path_static)status_iteratorzsphinx-galleryc                 t   |d         }|d         }t           j                            | |d                   }t           j                            |t	          |                              d                    }|*d                    |                    d          |g          }|                    t           j        d          }d                    |d         dd	|d
         |d         t          |d                   g          }|d         du r|dt          |           z  }n|dt          |           z  }|S )a  Generate a Binder URL according to the configuration in conf.py.

    Parameters
    ----------
    fpath: str
        The path to the `.py` file for which a Binder badge will be generated.
    binder_conf: dict or None
        The Binder configuration dictionary. See `gen_binder_rst` for details.

    Returns
    -------
    binder_url : str
        A URL that can be used to direct the user to the live Binder
        environment.
    filepath_prefixnotebooks_dirsrc_dir.ipynbN/binderhub_urlv2ghorgrepobranchuse_jupyter_labTz?urlpath=lab/tree/z
?filepath=)
ospathrelpathjoinr   with_suffixstripreplacesepr   )fpathbinder_confgallery_conffpath_prefix	link_baserelative_link	path_link
binder_urls           b/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sphinx_gallery/interactive_example.pygen_binder_urlr'      s>   " 01LO,I GOOE<	+BCCMY](;(;(G(G(Q(QRRI HHl0055yABB	 !!"&#..I (+h'((	
	 	J $%--=5+;+;===

55#3#3555
    c                    t          | ||          }t          j                            t          j                            |           dd          }t          j        t          j                            |          d           t          j                            |          s?t          j        t          j                            t                      d          |           d
                    |          }|S )a  Generate the reST + link for the Binder badge.

    Parameters
    ----------
    fpath: str
        The path to the `.py` file for which a Binder badge will be generated.

    binder_conf: dict or None
        If a dictionary it must have the following keys:

        'binderhub_url'
            The URL of the BinderHub instance that's running a Binder service.
        'org'
            The GitHub organization to which the documentation will be pushed.
        'repo'
            The GitHub repository to which the documentation will be pushed.
        'branch'
            The Git branch on which the documentation exists (e.g., gh-pages).
        'dependencies'
            A list of paths to dependency files that match the Binderspec.

    gallery_conf : dict
        Sphinx-Gallery configuration dictionary.

    Returns
    -------
    rst : str
        The reStructuredText for the Binder badge that links to this file.
    imageszbinder_badge_logo.svgTexist_okz
  .. container:: binder-badge

    .. image:: images/binder_badge_logo.svg
      :target: {}
      :alt: Launch binder
      :width: 150 px
)r'   r   r   r   dirnamemakedirsisfileshutilcopyfiler   format)r   r   r    r%   physical_pathrsts         r&   gen_binder_rstr5   Q   s    <  {LAAJ GLL
*A M K..>>>>7>>-(( 
GLL**,CDDm	
 	
 	
	! fZ  Jr(   c                     |dS | j         j        dvrdS | j        j        }|d         }t	          |          dk    sdS t
                              dd           t          | |           t          |            dS )z1Copy all Binder requirements and notebooks files.Nhtmlreadthedocsbinderr   zcopying binder requirements...whitecolor)	buildernameconfigsphinx_gallery_conflenloggerinfo_copy_binder_reqs_copy_binder_notebooks)app	exceptionr    r   s       r&   copy_binder_filesrI      s    
{666:1Lx(K{a
KK0K@@@c;'''3r(   c                    |d         }|D ]f}t           j                            t           j                            | j        |                    s"t          d                    |                    gt           j                            | j        d          }t          j        |d           |D ]:}t          j
        t           j                            | j        |          |           ;dS )z@Copy Binder requirements files to a "binder" folder in the docs.dependencieszSCouldn't find the Binder requirements file: {}, did you specify the path correctly?r:   Tr+   N)r   r   existsr   srcdirr   r2   outdirr.   r0   copy)rG   r   	path_reqsr   binder_folders        r&   rE   rE      s    N+I  w~~bgll3:t<<== 	66<fTll  	 GLLX66MK----  C CBGLLT22MBBBBC Cr(   c                     g }|D ]q}|                     d          r|dk    r>t          j                            t          j                            | |                    r\|                    |           r|S )zRemove files with `.ipynb` and directories named `images` from list of files.

    `contents` should be a list of files, which is returned after file removal.
    Used with the `shutil` "ignore" keyword to filter out non-ipynb files.
    r   r*   )endswithr   r   isdirr   append)r   contentscontents_returnentrys       r&   _remove_ipynb_filesrY      s     O 	* 	*>>(## 	*xRW]]27<<e3L3L%M%M ""5))))r(   c                 ,   | j         j        }|d         }|d         }t          j                            | j        |d                   }t          j        |d           t          j        |d           t          |t          t          f          s|g}t          |dt          |                    }|D ]_}t          j        t          j                            | j        |          t          j                            ||          t           	           `d
S )zCopy Jupyter notebooks to the binder notebooks directory.

    Copy each output gallery directory structure but only including the
    Jupyter notebook files.
    gallery_dirsr:   r   Tignore_errorsr+   zcopying binder notebooks...lengthignoreN)r@   rA   r   r   r   rN   r0   rmtreer.   
isinstancelisttupler   rB   copytreerM   rY   )rG   r    r[   r   r   iteratori_folders          r&   rF   rF      s    :1L/Lx(KGLL[-IJJM
M-t4444K----lT5M22 &$~3C<M<M  H  
 
GLLX..GLL11&	
 	
 	
 	
 	

 
r(   c                 &     i n                                   t           t                    st          d          t	                     dk    r S g d}g d}g }|D ],}                     |          |                    |           -t	          |          dk    rt          d|                                            D ]}|||z   vrt          d|           t           fdd	D                       s(t          d
	                     d                             g d} d         }t          |t                    r	|g}| d<   nKt          |t          t          f          s/t          d	                    t          |                                                   d                                dd                                dd           d |D             t          fd|D                       st          d           S )z<Check to make sure that the Binder configuration is correct.Nz+`binder_conf` must be a dictionary or None.r   )r   r   r   r   rK   )r
   r   r   z#binder_conf is missing values for: zUnknown Binder config key: c              3   N   K   | ]}d                               |          V   dS )r   N)
startswith).0iir   s     r&   	<genexpr>z$check_binder_conf.<locals>.<genexpr>   sG        8:O$//33     r(   )zhttp://zhttps://z2did not supply a valid url, gave binderhub_url: {}r   )zrequirements.txtzenvironment.yml
DockerfilerK   z>`dependencies` value should be a list of strings. Got type {}.r
   r   	notebooksr   Fc                 L    g | ]!}t           j                            |          "S  )r   r   basename)rl   rm   s     r&   
<listcomp>z%check_binder_conf.<locals>.<listcomp>  s(    DDDB27++B//DDDr(   c              3       K   | ]}|v V  	d S )Nrr   )rl   rm   path_reqs_filenamess     r&   rn   z$check_binder_conf.<locals>.<genexpr>  s)      GGRr((GGGGGGr(   zDid not find one of `requirements.txt` or `environment.yml` in the "dependencies" section of the binder configuration for Sphinx-Gallery. A path to at least one of these files must exist in your Binder dependencies.)rO   rc   dictr   rB   getrU   keysanyr2   strrd   re   type
setdefault)	r   
req_valuesoptional_valuesmissing_valuesvalkeyrequired_reqs_filesrP   rv   s	   `       @r&   check_binder_confr      s    $+""1A1A1C1CKk4(( IGHHH
;1 LKKJMMMON ' '??3'!!#&&&
>QPPPQQQ!! C CzO344ACAABBB 5     >U     
 @GGO, 
 
 	
 POON+I)S!! 
K	&/N##	D%=11 
LSSY 
 
 	
 ,---?K888,e444DD)DDDGGGG3FGGGGG 
6
 
 	
 r(   c                 L    d| j         v o|j        d         du}|sdS d|_        dS )zoConfigure 'jupyterlite_bind_ipynb_suffix' if jupyterlite enabled.

    Connected to "config-inited" event.
    jupyterlite_sphinxjupyterliteNF)
extensionsrA   jupyterlite_bind_ipynb_suffix)rG   r@   is_jupyterlite_enableds      r&    pre_configure_jupyterlite_sphinxr     sH     	. 	B&}5TA  " 
 ,1F(((r(   c                     t          |j        d         |           |j        d<   |j        d         dS |j        g |_        |j                            |j        d         d                    dS )zCheck SG "jupyterlite" and update Jupyterlite config "jupyterlite_contents".

    Connected to "config-inited" event but lower priority so called after
    `pre_configure_jupyterlite_sphinx`.
    r   Njupyterlite_contents)check_jupyterlite_confrA   r   rU   )rG   r@   s     r&   !post_configure_jupyterlite_sphinxr   1  s     1G"=131 1F}- !-08"*&(# &&"=12HI    r(   c                    ddl m} |dS | j        j        dvrdS | j        j        }d| j        v o	|d         du}|sdS t                              dd	           |d
         }|d         d         }t          j
        |d           t          j        |           t          |t          t          f          s|g}t!          |dt#          |                    }|D ]_}t          j        t          j                            | j        |          t          j                            ||          t,                     `|d         d         }	|	dS  ||d          \  }	t          j                            |dd          }
t/          t1          j        |
d                    }t                              dd	           |D ]}t3          |          5 }t5          j        |          }ddd           n# 1 swxY w Y    |	||           t3          |d          5 }t5          j        ||d           ddd           n# 1 swxY w Y   dS )zECreate Jupyterlite contents according to "jupyterlite" configuration.r   )_get_callablesNr7   r   r   z copying Jupyterlite contents ...r;   r<   r[   r   Tr\   z Copying Jupyterlite contents ...r^   r`   notebook_modification_functionz**z*.ipynb)	recursivez#Modifying Jupyterlite notebooks ...w   )indent)gen_rstr   r>   r?   r@   rA   r   rC   rD   r0   rb   r   r.   rc   rd   re   r   rB   rf   r   r   rM   rY   sortedglobopenjsonloaddump)rG   rH   r   r    r   r[   contents_dirrg   rh   r   notebook_patternnotebook_filename_listnotebook_filenamefnotebook_contents                  r&   create_jupyterlite_contentsr   G  s    ''''''
{666:1L. 	4't3 
 " 
KK2'KBBB/L./EFL
M,d3333KlT5M22 &$~8\ARAR  H  
 
GLLX..GLLx00&	
 	
 	
 	
 	
 &2-%@(&" &-(6|](S(S%#w||L$	BB#DI.>$$O$O$OPP
KK5WKEEE3 5 5#$$ 	,#y||	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	'&'79JKKK#S)) 	5QI&!4444	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	55 5s$   G..G2	5G2	H99H=	 H=	c                    t           j                            | |d                   }|                    dd          }|                    t           j        d          }t           j                            t           j                            |d         d          t           j                            |                     }|                    t           j        d          }|d         d         r|dz  }n|d	z  }| d
| }t           j                            t           j                            |           d          }t          |           d                    |          }|S )a~  Generate the reST + link for the Binder badge.

    Parameters
    ----------
    fpath: str
        The path to the `.py` file for which a JupyterLite badge will be
        generated.

    gallery_conf : dict
        Sphinx-Gallery configuration dictionary.

    Returns
    -------
    rst : str
        The reStructuredText for the JupyterLite badge that links to this file.
    r   z.pyr   r   liter   r   z/labz
/notebooksz/index.html?path=r*   z
  .. container:: lite-badge

    .. image:: images/jupyterlite_badge_logo.svg
      :target: {}
      :alt: Launch JupyterLite
      :width: 150 px
)	r   r   r   r   r   r   r-   _add_jupyterlite_badge_logor2   )r   r    r#   notebook_locationlite_root_urllite_url	image_dirr4   s           r&   gen_jupyterlite_rstr     s2   " GOOE<	+BCCM%--eX>>)11"&#>>GOO
\),f55rwu7M7M M "))"&#66MM"#45 &%EE2CEEH RW__U33X>>I	***	! fX  Jr(   c                 2   t          j        | d           t           j                            | d          }t           j                            |          sAt          j        t           j                            t                      d          |           d S d S )NTr+   zjupyterlite_badge_logo.svg)r   r.   r   r   r/   r0   r1   r   )r   r3   s     r&   r   r     s    K	D))))GLL,HIIM7>>-(( 
GLL**,HII=	
 	
 	
 	
 	

 
r(   c                 
   |d}nd|j         vp| du }|rdS t          | t                    st          d          dddd}|                                 }t          |          t          |          z
  }|r/t          dt          |           dt          |                     |                                D ]\  }}|	                    ||           t          j                            |j        |d                   |d<   |S )	z4Return full JupyterLite configuration with defaults.NTr   z'`jupyterlite_conf` must be a dictionaryr   )r   r   r   z?Found some unknown keys in sphinx_gallery_conf['jupyterlite']: z. Allowed keys are: )r   rc   rw   r   rO   setr   rd   itemsr}   r   r   r   rM   )jupyterlite_confrG   is_jupyterlite_disabledconf_defaultsresultunknown_keysr   default_values           r&   r   r     sU    {"& !6R:Jd:R 	   t&-- ECDDD !7*. M ""$$Fv;;]!3!33L 
7l##7 7!%m!4!47 7
 
 	
 ,1133 . .]#}----%'W\\
F12& &F!" Mr(   )"__doc__r   r   r   r0   pathlibr   urllib.parser   sphinx.utilsphinxsphinx.errorsr    r   utilsr   utillogging	getLoggerrC   r'   r5   rI   rE   rY   rF   r   r   r   r   r   r   r   rr   r(   r&   <module>r      s  
 
   				                  % % % % % %       " " " " " "			&	&'7	8	8/ / /d8 8 8v     &C C C$  (
 
 
8; ; ;|1 1 1$  ,;5 ;5 ;5|/ / /d
 
 
% % % % %r(   