
    -Ph,                        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mZ ddl	m
Z
 ddlmZ ddlmZmZ ddlZddlmZ 	 ddlmZ n# e$ r	 ddlmZ Y nw xY wej        j                            d	          Z ed
d          Zd Zd Zd)dZd Z d*dZ!d+dddddZ"d Z#d Z$d,dZ%d+dZ&d Z'd Z(d Z)d,d Z*g d!Z+d" Z,d# Z-d$ Z.d-d&Z/d' Z0d( Z1dS ).z%Utilities.

Miscellaneous utilities.
    N)defaultdict)partial)Path)copyfilemove)ExtensionError)status_iteratorzsphinx-galleryutf-8
)encodingnewlinec                      	 ddl m}  n=# t          $ r0}	 dd l} n # t          $ r t          d|           w xY wY d }~nd }~ww xY w| S )Nr   )ImagezUCould not import pillow, which is required to rescale images (e.g., for thumbnails): )PILr   ImportErrorr   )r   excs     T/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sphinx_gallery/utils.py
_get_imager   $   s    	   	LLLL 	 	 	 C=@C C  	 LLLL Ls   	 
A>6>Ac                    t                      }|                    |           }|j        \  }}|t          |          z  }|t          |          z  }	||z  |k    r|}
n|	}
|
dk    r| |k    rdS t	          t          |
|z                      }t	          t          |
|z                      }	 |j        j        }n# t          $ r
 |j        }Y nw xY w|	                    ||f|          }|
                    d||fd          }||z
  dz  ||z
  dz  f}|                    ||           	 |                    |           dS # t          $ r, |                    d                              |           Y dS w xY w)zScales image centered in image box using `max_width` and `max_height`.

    The same aspect ratio is retained. If `in_fname` == `out_fname` the image can only
    be scaled down.
    g      ?NRGBA)   r   r   r      RGB)r   opensizefloatintround
ResamplingBICUBIC	ExceptionresizenewpastesaveOSErrorconvert)in_fname	out_fname	max_width
max_heightr   imgwidth_in	height_inscale_wscale_hscalewidth_sc	height_scbicubicthumb
pos_inserts                   r   scale_imager7   2   s    LLE
**X

C(Hi%//)G5+++G7j((||I--5)**++HE%)+,,--I
 "*      - 
**h	*G
4
4C
 IIfy*57IJJEx'A-
Y0F1/LMJ	KKZ   -

9 - - -e!!),,,,,,-s$   -B: :CC)E   2E65E6 c                    t          |           } |                     d          r`	 t          j        dgt	          |          z   | gz   t          j        t          j                   dS # t          j        t          f$ r Y dS w xY wdS )a]  Optimize a PNG in place.

    Parameters
    ----------
    fname : str
        The filename. If it ends with '.png', ``optipng -o7 fname`` will
        be run. If it fails because the ``optipng`` executable is not found
        or optipng fails, the function returns.
    args : tuple
        Extra command-line arguments, such as ``['-o7']``.
    z.pngoptipngstdoutstderrN)strendswith
subprocess
check_calllistPIPECalledProcessErrorr&   )fnameargss     r   r:   r:   b   s     JJE~~f 
	!d4jj(E72!!     
 -w7 	 	 	DD	
 
s   A A( (BBc                      	 t          j        ddgt           j        t           j                   dS # t          $ r Y dS w xY w)Nr:   z	--versionr;   TF)r@   rA   rC   r&   r8       r   _has_optipngrI   |   s\    $Z_Z_	
 	
 	
 	
 t    uus   -1 
??bc                    |dk    rddd}ni }t          | d| fi |5 }|                                }|dk    r |j        di |}t          j        |                                          cddd           S # 1 swxY w Y   dS )a  Returns md5sum of file.

    Parameters
    ----------
    src_file : str
        Filename to get md5sum for.
    mode : 't' or 'b'
        File mode to open file with. When in text mode, universal line endings
        are used to ensure consistency in hashes between platforms.
    tsurrogateescaper
   )errorsr   rNr8   )r   readencodehashlibmd5	hexdigest)src_filemodekwargssrc_datasrc_contents        r   
get_md5sumrZ      s     s{{-7CC	h
D

	-	-f	-	- 4mmoo3;;,+,66v66K{;''1133	4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4s   AA::A>A>r   rS   )methodrV   checkc                   t          |           } |dv sJ |<|                     d          sJ t          j                            |           d         }d}t          j                            |          r|dk    rt          t          |          }n|dk    sJ d }	  ||           ||           k    }n# t          $ r d	}Y nw xY w|rd	}|d
k    rt          j	        |            n t                              d| d|             |r'|d
k    rt          | |           nt          | |           t          j                            |          sJ d S )N)r   copy.newr   TrS   rV   jsonc                 j    t          j        t          |                               d                    S )Nr
   )ra   loadsr   	read_text)xs    r   funcz_replace_md5.<locals>.func   s&    z$q''"3"3G"<"<===rH   Fr   zReplacing stale z with )r>   r?   ospathsplitextisfiler   rZ   r!   removeloggerdebugr   r   )	fname_new	fname_oldr[   rV   r\   replacerf   equivs           r   _replace_md5rr      s   II%%%%%!!&)))))G$$Y//2	G	w~~i   JE>>:D111DDF????> > >	DOOttI6EE 	 	 	EEE	 	JG	)$$$LLHIHHYHHIII +VI&&&&Y	***7>>)$$$$$$$s   B7 7CCc                 ^   t                      }t                      }| D ]P}t          j                            |          }||v r|                    |           ;|                    |           Qt          |          dk    r*t          	                    dt          |                     dS dS )z9Check for duplicate filenames across gallery directories.r   zjDuplicate example file name(s) found. Having duplicate file names will break some links. List of files: %sN)setrB   rg   rh   basenameappendaddlenrl   warningsorted)files
used_names	dup_names	this_file
this_fnames        r   check_duplicate_filenamesr      s     JI ' '	W%%i00
##Y''''NN:&&&&
9~~  9		
 	
 	
 	
 	
 rH   c                     t          j        d          }t          t          |j        |                     }|r*t
                              dt          |                     dS dS )z9Check for spaces in filenames across example directories.z[\s]zlExample file name(s) with spaces found. Having spaces in file names will break some links. List of files: %sN)recompilerB   filtersearchrl   ry   rz   )r{   regexfiles_with_spaces      r   check_spaces_in_filenamesr      sp    JwEF5<7788 
  #$$		
 	
 	
 	
 	

 
rH   Fc                    |d         }|rdnd}g }| D ]}t           j                            |                              t           j                  }t          j        |          D ]\  }}	}
t           j                            |          }|                    t           j                  |z
  |k    r nt|
D ]p}t          |          j        x}rX||v rTt          j
        |d         |          9|}|r t           j                            ||          }|                    |           q|rt          |           t          |           |S )a  Collect files with `example_extensions`, accounting for `ignore_pattern`.

    If `check_filenames` we check one level of sub-folders as well as root
    `example_dirs` for gallery example files. We then check for duplicate and
    spaces in full file paths.
    example_extensions   r   ignore_pattern)rg   rh   abspathcountsepwalknormpathr   suffixr   r   joinrv   r   r   )examples_dirsgallery_confcheck_filenamesexts	max_depthr{   example_direxample_depthroot_	filenamesfilenamesfiles                 r   _collect_gallery_filesr      sX    ,-D$+!IE$ + +44::26BB"$'+"6"6 
	+ 
	+D!Y7##D))D

26""]2i??% + +h..A +AIIy.>!?JJR'* @#%7<<h#?#?DT***+  )!%(((!%(((LrH   c           	      l   t          |          dz   }t          j        |d          5 }| D ]`}|(t          j                            |          d         |z   }|                    |t          j                            ||                     a	 ddd           n# 1 swxY w Y   t          |           |S )z
    Creates a zip file with the given files.

    A zip file named `zipname` will be created containing the files listed in
    `file_list`. The zip file contents will be stored with their paths stripped to be
    relative to `relative_to`.
    r_   wr`   Nr   )	r>   zipfileZipFilerg   rh   ri   writerelpathrr   )	file_listzipnamerelative_to	extensionzipname_newzipfrE   s          r   	zip_filesr      s    g,,'K	3	/	/	/ C4 	C 	CE$((//2Y>JJubgooe[AABBBB	CC C C C C C C C C C C C C C C
 Ns   A$BB!Bc                  l    	 ddl } |                                 }d|fS # t          t          f$ r Y dS w xY w)z$Check if pypandoc package available.r   NT)NN)pypandocget_pandoc_versionr   r&   )r   versions     r   _has_pypandocr     sX     --// W} !   zzs    33c                  |    	 dd l } n5# t          $ r(}t                              d|            Y d }~dS d }~ww xY wdS )Nr   zP`graphviz` required for graphical visualization but could not be imported, got: FT)graphvizr   rl   info)r   r   s     r   _has_graphvizr     so       5/25 5	
 	
 	
 uuuuu 4s    
949c                 .    t          j        dd|           S )z9Remove ANSI terminal formatting characters from a string.z*(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~] )r   sub)r   s    r   _escape_ansir   +  s    6?QGGGrH   c                 x    d}|r|dz  }|d                     d                    |                     z  }|dz  }|S )zFormat a toc tree.z
.. toctree::
   :hidden:z
   :includehidden:
z

   {}
z
   r   )formatr   )itemsincludehiddensts      r   _format_toctreer   0  s\    
B  
  	  6',,u%%&&'B $JBIrH   )		plot_1.py	plot_3.py	plot_2.pyz	plot_5.pyz	plot_6.pyz	plot_4.pyz	plot_8.pyz	plot_7.pyz	plot_9.pyc                 6    t                               |           S )z6Importable custom sorter func, used in our test suite.)_CUSTOM_EXAMPLE_ORDERindex)r   s    r   _custom_example_sorterr   O  s     &&x000rH   c                     | ddd         S )zMImportable custom sorter func for subsection folders, used in our test suite.Nr8   )
foldernames    r   _custom_subsection_sorterr   T  s    dddrH   c                 X    g d}|                     t          |           j                  S )zLImportable custom sorter for minigallery_sort_order, used in our test suite.)r   r   r   )r   r   name)r   ORDERs     r   $custom_minigallery_sort_order_sorterr   Y  s/      E
 ;;tDzz'''rH   r   c           	         t          |                               | j        | dz             }t          |dfi t          5 }t          j        ||dddd           ddd           n# 1 swxY w Y   t          |d	           dS )
zWrite dictionary to JSON file.z	.json.newr   TFr   )	sort_keysensure_asciiindentcheck_circularNra   )r\   )r   	with_namestemr   _W_KWra   dumprr   )target_fileto_saver   codeobj_fnamefids        r   _write_jsonr   d  s    %%//0@dCUCUCU0UVVM	mS	*	*E	*	* 
c	 	
 	
 	
 	

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 f------s   A((A,/A,c                     t          | dd          5 }t          j        |          }ddd           n# 1 swxY w Y   |S )zRead JSON dictionary from file.rO   r
   )r   N)r   ra   load)
json_fnamer   	json_dicts      r   
_read_jsonr   s  s|    	j#	0	0	0 #CIcNN	# # # # # # # # # # # # # # #s   488c                     t          |t                    rC|                                D ].\  }}|                     |g                               |           /| S )zJCombine backreferences dictionaries, joining lists when keys are the same.)
isinstancedictr   
setdefaultextend)dict_adict_bkeyvalues       r   _combine_backreferencesr   z  s]     &$ 5 ,,.. 	5 	5JCc2&&--e4444MrH   )r8   )rJ   )N)F)r   )2__doc__rR   ra   rg   r   r@   r   collectionsr   	functoolsr   pathlibr   shutilr   r   sphinx.utilsphinxsphinx.errorsr   sphinx.util.displayr	   r!   utillogging	getLoggerrl   r   r   r   r7   r:   rI   rZ   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r8   rH   r   <module>r      s      				 				      # # # # # #             ! ! ! ! ! ! ! !     ( ( ( ( ( (,3333333 , , ,++++++++, 
		&	&'7	8	8 	gt,,,  -- -- --`   4  4 4 4 4.%f3e % % % % %D
 
 
,

 

 

   :   $
 
 
	 	 	H H H
   $
 
 
 1 1 1
  
( ( (. . . .      s    A AA