
    -Phl3                     *   d 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 ddl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dZ'dS )zQParser for Jupyter notebooks.

Class that holds the Jupyter notebook information
    N)defaultdict)partial)count)Path)ExtensionError   )split_code_and_text_blockszsphinx-galleryc                     t           j        } g dt          | d                   z   ddt          | d                   z   dd| d         ddddddt          | d                   z    d	j        t           j        d
d          ddddd}|S )z=Returns a dictionary with the elements of a Jupyter notebook.zPython r   python)display_namelanguagenameipython)r   versionz.pyztext/x-pythonz{}.{}.{}N   )codemirror_modefile_extensionmimetyper   nbconvert_exporterpygments_lexerr   )
kernelspeclanguage_info   )cellsmetadatanbformatnbformat_minor)sysversion_infostrformat)
py_versionnotebook_skeletons     W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sphinx_gallery/notebook.pyjupyter_notebook_skeletonr%      s    !J !*C
1,>,> >$ 3z!}#5#55  -6*Q-#P#P"'+ &."+c*Q-.@.@"@,:,c.>rr.BC 
 
  ' *     c                     t          dd          }d                    ||         |                                |                     d                                                    S )zHelper to fill in directives.infodanger)notewarningz6<div class="alert alert-{}"><h4>{}</h4><p>{}</p></div>r   )dictr!   
capitalizegroupstrip)match	directivedirective_to_alerts      r$   directive_funr3   :   s[    68<<<CJJ9%y';';'='=u{{1~~?S?S?U?U  r&   c                    d}	 t          j        ||           }|sn+|                    d          }|                                d         t	          |          z
  }t          j        dt          j        |           dt           j                  }|                    | |          }|r|                                nt	          |           }t          j
        | ||                                                   }d|                    d           d| d	}	| d
|                                d                  |	z   | |d
         z   } D| S )a+  Rewrite code blocks to use Markdown's preferred backtick notation.

    Backtick notation preserves syntax highlighting.

    Parameters
    ----------
    text: str
        A mostly converted string of markdown text. May contain zero, one,
        or multiple code blocks in code-block format.
    z4[ \t]*\.\. code-block::[ \t]*(\S*)\n[ \t]*\n([ \t]+)T   r   z^(?!z
)[ \t]*\S+z```
z
```
Nr   )researchr.   spanlencompileescape	MULTILINEstarttextwrapdedentrstrip)
text
code_regex
code_blockindentstart_indexendcode_end_match	end_indexcontentsnew_codes
             r$   convert_code_to_mdrL   B   sG    IJJYz400
 	!!!$$ oo''*S[[8 j>6!2!2>>>MMD+66.<KN((***#d))	?4I(=#>??FFHHA))!,,AAAAA*joo''**+h6ijj9IIJ Kr&   c                 ~   d}t          j        d                    |          t           j                  }t          j        |fd|           } t          j        dt           j                  }t          j        |d |           } t          j        dt           j                  }t          j        |d|           } d	}|D ]O}	t          j        d
|	z  t           j                  }
t          j        |
t          t          |	          |           } Pt          j        dt           j                  }t          j        |d|           } t          j        d          }t          j        |d|           } t          j        d          }t          j        |d|           } t          j        dt           j                  }t          j        |d|           } t          j        dt           j                  }t          j        dt           j                  t          j        |fd|           } t          |           } | S )a  Converts reST from docstrings and text blocks to markdown for Jupyter notebooks.

    Parameters
    ----------
    text: str
        reST input to be converted to MD
    gallery_conf : dict
        The sphinx-gallery configuration dictionary.
    target_dir : str
        Path that notebook is intended for. Used where relative paths
        may be required.
    heading_levels: dict
        Mapping of heading style ``(over_char, under_char)`` to heading level.
        Note that ``over_char`` is `None` when only underline is present.
    z=`:.'"~^_*+#<>-z(?P<pre>\A|^[ \t]*\n)(?:(?P<over>[{0}])(?P=over)*\n[ \t]*)?(?P<heading>\S[^\n]*)\n(?P<under>(?(over)(?P=over)|[{0}]))(?P=under)*$)flagsc                      dj         d|                     dd                   z  g|                     dd          R  S )Nz
{1}{0} {2}#overunderpreheading)r!   r.   )r0   heading_levelss    r$   <lambda>zrst2md.<locals>.<lambda>   sM    )l).VW!=!=>>
[[	**
 
 
 r&   z"^\.\. math::((?:.+)?(?:\n+^  .+)*)c                 v    d                     |                     d                                                    S )Nz\begin{{align}}{0}\end{{align}}r   )r!   r.   r/   )r0   s    r$   rV   zrst2md.<locals>.<lambda>   s+    8??A@T@T@V@VWW r&   z:math:`(.+?)`z$\1$)r+   r*   z ^\.\. %s::((?:.+)?(?:\n+^  .+)*))r1   z^ *\.\. _.*:.*$\n z`([^`]*?)\s*<([^`]*)>`_z[\1](\2)z:ref:``z'^\s*\.\. contents::.*$(\n +:\S+: *$)*\nz'^\.\. image::(.*$)((?:\n +:\S+:.*$)*)\nz\n +:(\S+): +(.*)$c           
          d                     t          |                     d                                                    t	          j        d|                     d          pd                    S )Nz<img src="{}"{}>
r   z \1="\2"r5   rX   )r!   generate_image_srcr.   r/   r7   sub)r0   gallery_conf
image_opts
target_dirs    r$   rV   zrst2md.<locals>.<lambda>   s]    *11u{{1~~3355|ZPPF:{EKKNN,@bAA
 
 r&   )	r7   r;   r!   Mr\   DOTALLr   r3   rL   )rB   r]   r_   rU   adornment_charactersheadingsmath_eqinline_math
directivesr1   directive_refootnote_linksembedded_urisrefsrJ   imagesr^   s    ```            @r$   rst2mdrl   `   s;   $ .z	 F'((d  H 6	
 	
 	
 	
 	 D j>bdKKKG6WW D
 *-ry99K6+w--D$J W W	z/);24
 
 
 vlGMY$O$O$OQUVVZ 4BDAAAN6."d++DJ9::M6-d33D:i  D6$T""DzDBDQQQH6(B%%DZB"$OOOF1>>>J6	
 	
 	
 	
 	
 	
 	 D d##DKr&   c                 t   t          j        d|           r| S |d         sd|                     d          z   S |                     d          r|d         }|                     d          } t          j                            ||                     dt          j                            }t          |d         t                    rQ|d         }t          j                            ||d                   }||                    t          j        d          z   S 	 t          |d          5 }t          j        |                                          }ddd           n# 1 swxY w Y   n!# t           $ r t#          d| d	          w xY wt%          j        |          }d
|d          d|                    d           S )aF  Modify image path for notebook, according to "notebook_images" config.

    URLs are unchanged.
    If "notebook_images" config is a str, it is used as a prefix to image path, relative
    to "src_dir". If "notebook_images" is `True`, image is embedded as URI. If
    "notebook_images" is `False`, "file://" is prepended.
    z	https?://notebook_imageszfile:///src_dirrbNzUnable to open z to generate notebook data URIzdata:r   z;base64,ascii)r7   r0   lstrip
startswithospathjoinreplacesep
isinstancer    relpathopenbase64	b64encodereadOSErrorr   	mimetypes
guess_typedecode)	
image_pathr]   r_   	full_pathprefixrel_path
image_filedata	mime_types	            r$   r[   r[      s    
xj)) )* 2:,,S1111 S!! ,!),
&&s++
Z););C)H)HIII,01377 D/07??9l9.EFF((5555	i&& ;*'
(9(9::; ; ; ; ; ; ; ; ; ; ; ; ; ; ; 	 	 	 K)KKK  	 (33	Cy|CCT[[-A-ACCCs0   E$ %'EE$ EE$ E E$ $Fc                     |d         }|d         }t                      }|t          ||           t          || ||           |t          ||           |S )aL  Generate a Jupyter notebook file cell-by-cell.

    Parameters
    ----------
    script_blocks : list
        Script execution cells.
    gallery_conf : dict
        The sphinx-gallery configuration dictionary.
    target_dir : str
        Path that notebook is intended for. Used where relative paths
        may be required.
    first_notebook_celllast_notebook_cell)r%   add_code_cellfill_notebook)script_blocksr]   r_   
first_cell	last_cellwork_notebooks         r$   jupyter_notebookr      sk     34J12I-//MmZ000-jIIImY///r&   c                 v    ddddig |                                 gd}| d                             |           dS )zhAdd a code cell to the notebook.

    Parameters
    ----------
    code : str
        Cell content
    codeN	collapsedF)	cell_typeexecution_countr   outputssourcer   )r/   append)r   r   	code_cells      r$   r   r      sO      %(::<<. I '!!),,,,,r&   c                 J    di |gd}| d                              |           dS )zzAdd a markdown cell to the notebook.

    Parameters
    ----------
    markdown : str
        Markdown cell content.
    markdown)r   r   r   r   N)r   )r   r   markdown_cells      r$   add_markdown_cellr     s4     #-"
SSM'!!-00000r&   c                 \   d}d}t          j        ||          D ]}|||                                d                  }|r$|                                st	          | |           |                                d         }|                    d          }t          | |           ||d         S )a  Promote Jupyter cell magic in text blocks to code block in notebooks.

    Parses a block of markdown text looking for code blocks starting with a
    Jupyter cell magic (e.g. %%bash). Whenever one is found, the text before it
    and the code (as a runnable code block) are added to work_notebook. Any
    remaining text is returned.

    Parameters
    ----------
    markdown : str
        Markdown cell content.
    z*\n?```\s*[a-z]*\n(%%(?:[\s\S]*?))\n?```\n?r   r   N)r7   finditerr9   isspacer   r.   r   )r   r   cell_magic_regextext_cell_start
magic_cell
text_blockrD   s          r$   promote_jupyter_cell_magicr     s     EOk"2H== 1 1
o
0A0A!0DDE
 	9j0022 	9mZ888$//++A.%%a((
mZ0000 O$$%%r&   c                    t          d          t          fd          }|D ]\  }}}|dk    rt          | |           |d         du rt          |dz   |||          }ndd	l}	 |	j        |fd
dd|d         }|d         r7t          | |          }
|
r$|
                                st          | |
           t          | |           d	S )zWrites the Jupyter notebook cells.

    If available, uses pypandoc to convert rst to markdown.

    Parameters
    ----------
    script_blocks : list
        Each list element should be a tuple of (label, content, lineno).
    r   )r>   c                  "    t                     S )N)next)heading_level_counters   r$   rV   zfill_notebook.<locals>.<lambda>=  s    .C)D)D r&   r   pypandocFr6   r   Nmdrst)tor!   promote_jupyter_magic)	r   r   r   rl   r   convert_textr   r   r   )r   r   r]   r_   rU   blabelbcontentlinenor   r   	remainingr   s              @r$   r   r   2  s6    "NNN !D!D!D!DEEN$1 ; ; &V-2222J'500!tO\:~    180!%e 7CJ7O  34 ;6}hOO	 @Y%6%6%8%8 @%mY???!-::::+; ;r&   c                     t          |d          5 }t          j        | |d           ddd           dS # 1 swxY w Y   dS )z.Saves the Jupyter work_notebook to write_file.wr5   )rE   N)r|   jsondump)r   
write_fileout_nbs      r$   save_notebookr   V  s    	j#		 3&	-22223 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3s   6::c                 8   ddl m} t          j        d          }|                    ddd           |                    | |          } t          j        |j                  }||	                    |           | j
        D ]}t          |          \  }}t          d
|            t          j                            |          }	t!          |t          j        |          |	          }
t#          |
t%          |                              d                     d	S )zExposes the jupyter notebook renderer to the command line.

    Takes the same arguments as ArgumentParser.parse_args.
    `sphinx_gallery_conf` functions same as in `conf.py`.
    r   )gen_galleryz!Sphinx-Gallery Notebook converter)descriptionpython_src_file+z\Input Python file script to convert. Supports multiple files and shell wildcards (e.g. *.py))nargshelpNzConverting z.ipynb)rX   r   argparseArgumentParseradd_argument
parse_argscopydeepcopyDEFAULT_GALLERY_CONFupdater   r	   printru   rv   dirnamer   r   r   with_suffix)args	namespacesphinx_gallery_confr   parserr]   src_file	file_confblocksr_   
example_nbs              r$   python_to_jupyter_clir   `  s8    $1TUUUF
     T9--D =!ABBL&/000 ( H H6x@@	6&H&&'''W__X..
%fdmL.I.I:VV
j$x.."<"<X"F"FGGGGH Hr&   )NNN)(__doc__r   r}   r   r   r   ru   r7   r   r?   collectionsr   	functoolsr   	itertoolsr   pathlibr   sphinx.utilsphinxsphinx.errorsr   py_source_parserr	   utillogging	getLoggerloggerr%   r3   rL   rl   r[   r   r   r   r   r   r   r    r&   r$   <module>r      s            				 				 



  # # # # # #                       ( ( ( ( ( ( 8 8 8 8 8 8			&	&'7	8	8  6    <R R Rj$D $D $DN  2- - -$	1 	1 	1& & &>!; !; !;H3 3 3H H H H H Hr&   