
    -PhnK                        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mZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ g d	Zd
 Zd ZdZdZd Zd Z ee          Z G d d          ZdZd Zd Zd#dZd Zd ZdZ dZ!dZ"dZ#dZ$d Z%d  Z&e%e&d!Z'd" Z(dS )$aP  Scrapers for embedding images.

Collect images that have been produced by code blocks.

The only scraper we natively support is Matplotlib, others should
live in modules that will support them (e.g., PyVista, Plotly).  Scraped
images are injected as rst ``image-sg`` directives into the ``.rst``
file generated for each example script.
    N)PurePosixPath)indent)filterwarnings)ExtensionError   )optipng)save_figures
figure_rstImagePathIteratorclean_modulesmatplotlib_scraperc                     ddl } |                     d           |                                                                 }t	          dt
          d           |dk    r"t          d                    |                    ddlm	} | |fS )zImport matplotlib safely.r   NaggignorezMatplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.|(
|.)*is non-interactive, and thus cannot be shown)categorymessagea  Sphinx-Gallery relies on the matplotlib 'agg' backend to render figures and write them to files. You are currently using the {} backend. Sphinx-Gallery will terminate the build now, because changing backends is not well supported by matplotlib. We advise you to move sphinx_gallery imports before any matplotlib-dependent import. Moving sphinx_gallery imports at the top of your conf.py file should fix this issue)

matplotlibuseget_backendlowerr   UserWarningr   formatmatplotlib.pyplotpyplot)r   matplotlib_backendplts      W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sphinx_gallery/scrapers.py_import_matplotlibr   '   s     NN5#//117799    U""6 7=f=O6P6P	
 	
 		
 $#####s?    c                 (   g }t          | dd           }|'|                    |                                           g d}| j        D ]4}|D ]/}|                    |          }|r|                    |           05d                    |          }|S )N	_suptitle)leftcenterright)loc, )getattrappendget_textaxes	get_titlejoin)figtitlessuptitle
title_locsaxr%   text
fig_titless           r   _matplotlib_fig_titlesr4   J   s    FsK..Hh''))***,,,Jh $ $ 	$ 	$C<<C<((D $d###	$ 6""Jr   zC
.. container:: sphx-glr-animation

    .. raw:: html

        {0}
ze
.. video:: {video}
   :class: sphx-glr-single-img
   :height: {height}
   :width: {width}
{options}
c           	         ddl }ddlm} ddlm} |d         }g }|d         }	i }
|d         d         r7|d                                         D ]}t          ||          r
||
|j        <   t          |	                                |          D ]x\  }}t          |          }d|v r|                    d	|d         z             }|                    |          }|
                    |          x}r%|                    t          |||                     t!          |          }|j        j        j        }|                                }d
D ]N} t+          |d|z                         }|j        d|z            } ||           ||          k    r	||vr|||<   O	  |j        |fi | |j        d         }|dk    r|j        }|                    d|          }d|i}|	D ]c}|d                    d	d          }|j         d| d|j         }|j        t          |          z  }i |d||z  i} |j        |fi | |||<   d|g}n$# t:          $ r |                    d            w xY wd|d         v rct?          tA          |          |d                    |d         !                                D ]%}t?          tA          |          |d                    &|                    tE          |g|d         ||                     zd}|                    d          |d         dk    }n4|                    d          |d                             d          dk    }|                    d           d}tG          |          dk    r	|d         }nJtG          |          dk    r7|rd |D             }d  |D             }tH          d%                    |          z   }|S )!a  Scrape Matplotlib images.

    Parameters
    ----------
    block : sphinx_gallery.py_source_parser.Block
        The code block to be executed. Format (label, content, lineno).
    block_vars : dict
        Dict of block variables.
    gallery_conf : dict
        Contains the configuration of Sphinx-Gallery
    **kwargs : dict
        Additional keyword arguments to pass to
        :meth:`~matplotlib.figure.Figure.savefig`, e.g. ``format='svg'``. The
        ``format`` keyword argument in particular is used to set the file
        extension of the output file (currently only 'png', 'jpg', 'svg',
        'gif', and 'webp' are supported).

        This is not used internally, but intended for use when overriding the scraper.

    Returns
    -------
    rst : str
        The reStructuredText that will be rendered to HTML containing
        the images. This is often produced by :func:`figure_rst`.
    r   N)	Animationimage_path_iteratorimage_srcsetmatplotlib_animationsexample_globalsr   .)	facecolor	edgecolorget_zfigure.savefig.dpifiguredpiz.2f_xallimagescompress_imagescompress_images_argssrc_dir)srcsetpathsTmulti_imagesingle	file_conf r   c                 :    g | ]}t          j        d d|          S )z:class: sphx-glr-single-imgz:class: sphx-glr-multi-img)resub.0images     r   
<listcomp>z&matplotlib_scraper.<locals>.<listcomp>   s?         24PRW   r   c                 >    g | ]}t           t          |d           z   S )z      )HLIST_IMAGE_MATPLOTLIBr   rQ   s     r   rT   z&matplotlib_scraper.<locals>.<listcomp>   s5     
 
 
@E"VE7%;%;;
 
 
r   )&r   r   r   matplotlib.animationr6   values
isinstance_figzipget_fignumsr   with_suffixr@   getr(   	_anim_rstr4   colorscolorConverterto_rgbacopyr'   rcParamssavefigrA   replacestemsuffixparent	Exceptioncloser   stritemsr
   lenHLIST_HEADERr,   )block
block_varsgallery_confkwargsr   r   r6   r7   
image_rstssrcsetanimsanifig_num
image_pathr-   animr3   rb   these_kwargsattrfig_attrdefault_attrdpi0rI   multmultstnamehipathhikwargsconvert_to_multi_imagersts                                  r   r   r   k   s   6 ######......$%:;J.)F E+,Q/ &/07799 	& 	&C#y)) &"%ch"3??#4#46IJJ 8
 8
":..
v#//fX6F0FGGJjj!!99S>>!4 	ij,GGHHH+C00
#2: {{}}. 	. 	.D2wsFTM2244H%.y4/?@Lwx  GGL$9$999d&>P>P%-T"	CK
33l333&}5Dxw##E400Dj/K  + + ..sC88$/HHFHHZ5FHH#*]4-@-@@?l?E4$;??F//h///$*D!!&-KK 	 	 	IIe	 |$5666C
OO\2H%IJJJ%a...00 K KF\2H%IJJJJY''	  	
 	
 	
 	
 "~~m$$0!+M!:h!F		$	$	0!+K!8!<!<]!K!Kx!WIIe
C
:!m	Z1		! 	  (	  J
 
IS
 
 

 RWWZ000Js   B+I!I'c           	         ddl m} ddlm}m} | j        }|                    d          }|                                }|d         }t          t          d t          ||          D                                 }	|                                rd}
n|                                rd}
nd }
|                     t          |          |
|		           |d
         \  }}d }|+|                                 }||                                 }n5|dk    r|                                 }n|dk    r|                                 }|*t#          |d          }t$                              |          S |                    d|           }|                     |           dg}t)          | dd          r|                    d           |d         }|dk    r|j        }t/          t0          j                            ||d                             }t6                              d| t9          |d         |z            t9          |d         |z            d                    d |D                                 }|S )Nr   )rd   )FFMpegWriterImageMagickWriterz.gifthumbnail_sizec              3   &   K   | ]\  }}||z  V  d S )N )rR   t_sf_ss      r   	<genexpr>z_anim_rst.<locals>.<genexpr>   s*      LLhc3c	LLLLLLr   ffmpegimagemagick)writerrA   r9   html5jshtmlz     r;   autoplay_repeatFloopr?   r@   rH   /r   rM   c              3   "   K   | ]
}d | dV  dS )z   ::
Nr   )rR   opts     r   r   z_anim_rst.<locals>.<genexpr>  s*      ;;Cs;;;;;;r   )videowidthheightoptions)r   rd   rW   r   r   rZ   r]   get_size_inchesroundminr[   isAvailablesaverl   _repr_html_	to_jshtmlto_html5_videor   _ANIMATION_RSTr   r'   r(   rA   r   ospathrelpath_ANIMATION_VIDEO_RSTintr,   )rz   ry   rr   rd   r   r   r-   fig_size
thumb_sizeuse_dpir   rB   fmthtmlr   r   rA   	video_uris                     r   r_   r_      s   ######DDDDDDDD )C''//J""$$H./JCLL#j(2K2KLLLLLMMG!! 		&	&	(	( IIc*oof'I:::12FAsD
{!!<>>##D	""$$	~~dG$$$$T*** ""9s99--EIIelGtY&& v
=
!C
hg bgooe\)5LMMNNI&&)oo(1+#$$8A;$%%;;7;;;;;	 '  D Kr   )r   c                   0    e Zd ZdZd Zd Zd Zd Zd ZdS )r   zIterate over image paths for a given example.

    Parameters
    ----------
    image_path : str
        The template image path.
    c                 H    || _         t                      | _        d| _        d S )Ni@B )ry   listpaths_stop)selfry   s     r   __init__zImagePathIterator.__init__.  s    $VV



r   c                 *    t          | j                  S )zReturn the number of image paths used.

        Returns
        -------
        n_paths : int
            The number of paths.
        )rn   r   r   s    r   __len__zImagePathIterator.__len__3  s     4:r   c              #      K   t          | j                  D ]}|                                 V  t          d| j         d          )a[  Iterate over paths.

        Returns
        -------
        paths : iterable of str

        This enables the use of this Python pattern::

            >>> for epoch in epochs:  # doctest: +SKIP
            >>>     print(epoch)  # doctest: +SKIP

        Where ``epoch`` is given by successive outputs of
        :func:`mne.Epochs.next`.
        zGenerated over z images)ranger   nextr   )r   iis     r   __iter__zImagePathIterator.__iter__=  sV        
## 	H 	HB))++ !F4:!F!F!FGGGr   c                 *    |                                  S )z9Return the next image path, with numbering starting at 1.)__next__r   s    r   r   zImagePathIterator.nextR  s    }}r   c                     | j                             t          |           dz             }| j                            |           |S )Nr   )ry   r   rn   r   r(   )r   r   s     r   r   zImagePathIterator.__next__V  s<    %%c$ii!m44
$r   N)	__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   %  sl           
  H H H*      r   r   )pngsvgjpggifwebpc                     t           j                            |           d         } t          D ]*}|  d| }t           j                            |          r n+d}|  d| |fS )z5Find an image, tolerant of different file extensions.r   r;   r   )r   r   splitext_KNOWN_IMG_EXTSisfile)r   ext	this_paths      r   _find_image_extr   b  sv    7D!!!$D  OOcOO	7>>)$$ 	E	 OOcOOS!!r   c           	         ddl m} |d         }d}t          |          } ||d          D ]} || ||          }t          |t                    s%t          d|dt          |           d|          t          |          |z
  }	t          |	          D ]V}
t          |j	        ||
z                      \  }}t          j                            |          st          d	| d
|           W||z  }|S )a  Save all open figures of the example code-block.

    Parameters
    ----------
    block : sphinx_gallery.py_source_parser.Block
        The code block to be executed. Format (label, content, lineno).
    block_vars : dict
        Dict of block variables.
    gallery_conf : dict
        Contains the configuration of Sphinx-Gallery

    Returns
    -------
    images_rst : str
        rst code to embed the images in the document.
    r   _get_callablesr7   rM   image_scraperszrst from scraper z was not a string, got type r   zScraper z! did not produce expected image:
)gen_rstr   rn   rY   rl   r   typer   r   r   r   r   r   )rp   rq   rr   r   r7   all_rst
prev_countscraperr   n_newr   current_pathrB   s                r   r	   r	   n  sY   " ('''''$%:;G())J!>,0@AA  geZ66#s## 	 :G : :$(II: :25: :   '((:5,, 	 	B-#)*r/: OL! 7>>,// $XwXX,XX   	3Nr   rM   c                    |d | D             }fd| D             }d}|r|}nr| rpt           j                            | d                   d         }t           j                            |          d         dd         }t	          j        d	d
|          }|}t          |          }d}	t          |          dk    r.|d         }
|d         }t          |          }t          |
||fz  }	nWt          |          dk    rDt          }	t          |          D ]-\  }}
||         }t          |          }|	t          |
||fz  z  }	.|	S )a  Generate reST for a list of image filenames.

    Depending on whether we have one or more figures, we use a
    single rst call to 'image' or a horizontal list.

    Parameters
    ----------
    figure_list : list
        List of strings of the figures' absolute paths.
    sources_dir : str
        absolute path of Sphinx documentation sources
    fig_titles : str
        Titles of figures, empty string if no titles found. Currently
        only supported for matplotlib figures, default = ''.
    srcsetpaths : list or None
        List of dictionaries containing absolute paths.  If
        empty, then srcset field is populated with the figure path.
        (see ``image_srcset`` configuration option).  Otherwise,
        each dict is of the form
        {0: /images/image.png, 2.0: /images/image_2_00x.png}
        where the key is the multiplication factor and the contents
        the path to the image created above.

    Returns
    -------
    images_rst : str
        rst code to embed the images in the document

    The rst code will have a custom ``image-sg`` directive that allows
    multiple resolution images to be served e.g.:
    ``:srcset: /plot_types/imgs/img_001.png,
      /plot_types/imgs/img_2_00x.png 2.00x``

    Nc                     g | ]}d |iS )r   r   )rR   fls     r   rT   zfigure_rst.<locals>.<listcomp>  s    55522w555r   c                     g | ]S}t           j                            |                              t           j        d                               d           TS )r   )r   r   r   rf   seplstrip)rR   figure_pathsources_dirs     r   rT   zfigure_rst.<locals>.<listcomp>  sY        	[1199"&#FFMMcRR  r   rM   r   r   	   z[-,_] )r   r   splitr   rO   rP   _single_line_sanitizern   _get_srcset_stSG_IMAGEro   	enumerateHLIST_SG_TEMPLATE)figure_listr   r3   rI   figure_pathsalt	file_namefile_name_noextfile_name_final
images_rstfigure_namehinamesru   nns    `            r   r
   r
     s   F  65555   &  L C 	 GMM+a.11!4	'**955a82>&3@@

$
$CJ
<A"1oa.W55c6 ::

	\		Q		!
(66 	I 	IOB!"oG#K99F+{C.HHHJJr   c                 \   d}|                                 D ]w}t          j                            ||         |                               t          j        d                              d          }|d|z   z  }|dk    r|dz  }m|d|ddz  }x|dd	         dk    r
|d	d         }|dz  }|S )
a  Create the srcset string for including on the rst line.

    For example; `sources_dir` might be `/home/sample-proj/source`,
    hinames posix paths:
    0: /home/sample-proj/source/plot_types/images/img1.png,
    2.0: /home/sample-proj/source/plot_types/images/img1_2_00x.png,

    The result would be:
    '/plot_types/basic/images/sphx_glr_pie_001.png,
    /plot_types/basic/images/sphx_glr_pie_001_2_00x.png 2.00x'
    rM   r   r   r&   r   z1.2fzx, N)keysr   r   r   rf   r   r   )r   r   srcstkr   s        r   r   r     s     E\\^^ % %wwqz;77??LLSSTWXXt66TMEE_____$EERSSzTcrc
	RKELr   c                 .    |                      dd          S )zRemove problematic newlines.
r   )rf   )ss    r   r   r     s     99T3r   z%
.. rst-class:: sphx-glr-horizontal

z
    *
zn
    *

      .. image-sg:: /%s
          :alt: %s
          :srcset: %s
          :class: sphx-glr-multi-img
zM
.. image-sg:: /%s
   :alt: %s
   :srcset: %s
   :class: sphx-glr-single-img
z@
 .. image:: /%s
     :alt: %s
     :class: sphx-glr-single-img
c                     t                      \  }}|                                 t          j        |j                   t          j        |j                   t          j        |j                   dS )zReset matplotlib.N)r   
rcdefaults	importlibreloadunitsdatesr   )rr   fnamemplr   s       r   _reset_matplotlibr  -  s`    !##HCNNSYSYS\"""""r   c                 t    t           j                            d          }||                                 dS dS )zReset seaborn.seabornN)sysmodulesr^   reset_defaults)rr   r
  seaborn_modules      r   _reset_seabornr  6  s;    [__Y//N!%%''''' "!r   )r   r  c                 V   ddl m}  || d          D ]}t          j        |          }t	          |j                  dk    r[t          |j                                                  d         }|dk    rt          d|j	         d|            || ||	            || |           d
S )a@  Remove, unload, or reset modules.

    After a script is executed it can load a variety of settings that one
    does not want to influence in other examples in the gallery.

    Parameters
    ----------
    gallery_conf : dict
        The gallery configuration.
    fname : str or None
        The example being run. Will be None when this is called entering
        a directory of examples to be built.
    when : str
        Whether this module is run before or after examples.

        This parameter is only forwarded when the callables accept 3
        parameters.
    r   r   reset_modules      whenz3rd parameter in z( function signature must be 'when', got )r  N)
r   r   inspect	signaturern   
parametersr   r   
ValueErrorr   )rr   r
  r  r   reset_modulesigthird_params          r   r   r   C  s    & ('''''&|_EE . .--s~!##s~224455a8Kf$$ )(= ) )&) )  
 Lu488888Lu----. .r   )rM   N))r   r  r  r   rO   r  pathlibr   textwrapr   warningsr   sphinx.errorsr   utilsr   __all__r   r4   r   r   r   r_   dict_scraper_dictr   r   r   r	   r
   r   r   ro   rV   r   r   SINGLE_IMAGEr  r  _reset_dictr   r   r   r   <module>r*     s         				 				 



 ! ! ! ! ! !       # # # # # # ( ( ( ( ( (             F  " { { {|4 4 4n !  
5 5 5 5 5 5 5 5t 7	" 	" 	"' ' 'TI I I IX  6     
  # # #( ( ( $ !. !. !. !. !.r   