
    -PhC                         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ZddlmZ ddlmZ dd	lmZ dd
lmZmZ dZdZ G d dej                  Zd ZddZddZdZedz   Z	 ddZ d Z!d Z"dS )z^Backreferences Generator.

Parses example file code in order to keep track of used functions.
    N)defaultdict)escape)Path)ExtensionError   )
DummyClass)_find_image_ext)_W_KW_replace_md5zT
.. raw:: html

    <div class="sphx-glr-thumbnails">

.. thumbnail-parent-div-open
z;
.. thumbnail-parent-div-close

.. raw:: html

    </div>

c                   D     e Zd ZdZd
 fd	ZddZd Zd Zd Zd	 Z	 xZ
S )
NameFinderzwFinds the longest form of variable names and their imports in code.

    Only retains names from imported modules.
    Nc                     t                                                       i | _        |pi | _        t	                      | _        d S N)super__init__imported_namesglobal_variablessetaccessed_names)selfr   	__class__s     ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sphinx_gallery/backreferences.pyr   zNameFinder.__init__0   s@      0 6B!ee     c                 Z    |j         D ]"}|j        p|j        }||j        z   | j        |<   #dS )z0For 'import' add node names to `imported_names`.N)namesasnamenamer   )r   nodeprefixalias
local_names        r   visit_ImportzNameFinder.visit_Import6   sF    Z 	B 	BE3J.4uz.AD
++	B 	Br   c                 B    |                      ||j        dz              dS )zIFor 'from import' add node names to `imported_names`, incl module prefix..N)r#   moduler   r   s     r   visit_ImportFromzNameFinder.visit_ImportFrom<   s%    $c 122222r   c                 D    | j                             |j                   dS )z Add node id to `accessed_names`.N)r   addidr'   s     r   
visit_NamezNameFinder.visit_Name@   s!    (((((r   c                    g }t          |t          j                  r;|                    |j                   |j        }t          |t          j                  ;t          |t          j                  rV|                    |j                   | j        	                    d
                    t          |                               dS |                     |           dS )z<Add attributes, including their prefix, to `accessed_names`.r%   N)
isinstanceast	AttributeappendattrvalueNamer+   r   r*   joinreversedvisit)r   r   attrss      r   visit_AttributezNameFinder.visit_AttributeD   s    s}-- 	LL###:D s}-- 	 dCH%% 	LL!!!##CHHXe__$=$=>>>>> JJtr   c                    t                      }| j        D ]}|                    d          }t          t	          |                    D ]}d                    |d|dz                      }|t	          |          d         }|| j        v r| j        |         }dg }	}|r|dd                             d          D ]x}
|}t          |j        |
d          }t          |t                    r	|}d|
g}	} nA	 t          ||
          }n# t          $ r Y  n"w xY wt          j        |          r	|}d|
g}	} ny~t          j        |          }|s|rl|r|n|j        g}d}|t	          |          k     rJ||         j        D ]$}||vr|t           ur|                    |           %|dz  }|t	          |          k     Jn|j        g}|D ]}t          j        |          }||j                            d          }|j        }t          t	          |          dd          D ]@}d                    |d|         |gz   |	z             }|                    ||||df           At          t	          |                    D ]p}d                    |d|dz                      }|t	          |          d         }|| j        v r.| j        |         |z   }dx}}|                    ||||df           q|S )a  Map names used in code, using AST nodes, to their fully qualified names.

        Returns
        -------
        options : List[Tuple[str]]
            List of tuples, each tuple containing the following information about
            an `accessed_name`:

                accessed name : str,
                fully qualified name : str
                if it is a class attribute (i.e., property or method) : bool
                if it is a class : bool
                if it is an explicit backreference : bool (always false here)
        r%   Nr   FTr   )listr   splitrangelenr5   r   getattrr   r.   property	Exceptioninspectismethodisclass	__bases__objectr1   	getmodule__name____qualname__r   )r   optionsr   local_name_splitsplit_levelr"   	remainderobj
class_attrmethodlevellast_objpropis_classclassesoffsetbaseccr&   
class_namedepth	full_names                         r   get_mappingzNameFinder.get_mappingS   s    &&' D	S D	SD#zz#$S)9%:%:;; 7" 7" XX&67Hq7H&IJJ
 Z!2!23	!666/
;C).J  &%.qrr]%8%8%=%= & &E'*H#*8+=ud#K#KD)$99 &&.59E7F
 %&&-c5&9&9#, & & & %&&/44 &&.59E7F
 %& "&s33H 2: 2*2#E33"F!"$s7||33(/(A 9 9#'w#6#64v;M;M$+NN4$8$8$8"aKF %s7||33 $'=/% " "!(!22!6!6!-%+_%:%:3%?%?F)+J */s6{{Ar)B)B " ",/HH$*6E6Nj\$AF$J-" -"	 !(%)9j(E$R!" !" !" !"  %S)9%:%:;; S S XX&67Hq7H&IJJ
 Z!2!23	!444 $ 3J ?) KI,11HzNND)Z5#QRRRS s   7D
D	D	r   r   )rI   
__module__rJ   __doc__r   r#   r(   r,   r9   r]   __classcell__)r   s   @r   r   r   *   s         
$ $ $ $ $ $B B B B3 3 3) ) )  U U U U U U Ur   r   c                 R   d|v r|                     d          \  }}nd}	 t          t          j        |          |          }|t          ||           n# t          t
          f$ r Y dS w xY w|                      d          }| }t          t          |          dz
  dd          D ]}d                    |d|                   }	 |t          t          j        |         |          u sJ E# t          t          t
          f$ r$ d                    |d|dz                      }Y  nw xY w|S )z&Get the shortest possible module name.r%   Nr   r   r;   )
r=   r@   sysmodulesAttributeErrorKeyErrorr>   r?   r5   AssertionError)module_nameobj_namer2   real_objparts
short_nameis          r   _get_short_module_namern      sW   
h!,,$$	 3;{3X>>Hd###H%    tt
 c""EJ3u::>1b)) 
 
XXeBQBi((
	ws{:'>IIIIIII9 	 	 	
 %	1q5	"233JEE	 s#   2A A)(A)$C))7D$#D$r   c                 R    d}t          j        d| d|           rdnd}d| d| dS )	z/Make regex to find reference to python objects.zfunc|meth|attr|obj|classz	(?:py:)?()z|[^:]?r   z(?::(?:z):z()(?!``)`~?[^!]*?<?([^!~\s<>`]+)>?(?!``)`)re	fullmatch)default_rolerolesdef_role_regexs      r   _make_ref_regexrv      sY     'EL!5U!5!5!5|DDL" 	35 	3 	3N 	3 	3 	3r   c                    |dk    r3d                     d | D                       }t          j        |          }t          |          }||                    |           t          |                                          }d                     d | D                       }|                    d t          j	        ||          D                        t                      }|D ]\  }	}
}}}|	|vrt                      ||	<   |
                    dd|z             }t          |          dk    rd	|d
         f}nAt          |          dk    r*|sJ |d
         d                     |dd                   f}n|rJ |\  }}t          ||          }t          |||p|||          }||	                             |           |S )a  Build a codeobj summary by identifying and resolving used names.

    Parameters
    ----------
    script_blocks : list
        (label, content, line_number)
        List where each element is a tuple with the label ('text' or 'code'),
        the corresponding content string of block and the leading line number.
    ref_regex : str
        Regex to find references to python objects.
    example_globals: Optional[Dict[str, Any]]
        Global variables for examples. Default=None
    node : ast.Module or str
        The parsed node. Default="".

    Returns
    -------
    example_code_obj : Dict[str, Any]
        Dict with information about all code object references found in an
        example. Dict contains the following keys:

            - example_code_obj['name'] : function or class name (str)
            - example_code_obj['module'] : module name (str)
            - example_code_obj['module_short'] : shortened module name (str)
            - example_code_obj['is_class'] : whether object is class (bool)
            - example_code_obj['is_explicit'] : whether object is an explicit
                backreference (referred to by sphinx markup) (bool)
    r   
c              3   :   K   | ]}|j         d k    |j        V  dS )codeNtypecontent.0blocks     r   	<genexpr>z!identify_names.<locals>.<genexpr>   s1      WW%*PVBVBVemBVBVBVBVWWr   Nc              3   :   K   | ]}|j         d k    |j        V  dS )textNr{   r~   s     r   r   z!identify_names.<locals>.<genexpr>  s0      VVuvAUAUU]AUAUAUAUVVr   c              3   $   K   | ]}||d d dfV  dS )FTN )r   xs     r   r   z!identify_names.<locals>.<genexpr>  s-      QQ!Qud+QQQQQQr   r%   r   builtinsr      )r   r&   module_shortrU   is_explicit)r5   r/   parser   r7   r<   r]   extendrq   findalldictrsplitr?   rn   r1   )script_blocks	ref_regexr   r   cfinderr   r   example_code_objr   r\   
class_likerU   r   splitsr&   	attributer   cobjs                      r   identify_namesr      s   : rzzIIWWWWWWWy||())FT##%%&&E99VVVVVVVD	LLQQRZ	45P5PQQQQQQvv ?D , ,:iX{'''%)VVT" !!#q:~66v;;! &),FF[[AQi&*!5!56FF!!!!"	 .fi@@%/#
 
 
 	%%d++++r   z
.. raw:: html

    <div class="sphx-glr-thumbcontainer" tooltip="{intro}">

.. only:: html

  .. image:: /{thumbnail}
    :alt:

  :ref:`sphx_glr_{ref_name}`

.. raw:: html

      <div class="sphx-glr-thumbnail-title">{title}</div>
    </div>

z3
.. only:: not html

 * :ref:`sphx_glr_{ref_name}`
FTc           
         t          |          }t          t          j                            | ddd|j         d                    \  }}|r1t          j                            |          st          d|           t          j                            ||          }t          j                            | |          }	|	                    t          j
        d          }t          j                            |	|          	                    t          j
        d          }
|rt          nt          }|                    t          |          |||
          S )	a  Generate reST to place a thumbnail in a gallery.

    Parameters
    ----------
    target_dir : str
        Absolute path to output directory, where thumbnails are saved.
    src_dir : str
        Absolute path to build source directory.
    fname : str
        Filename of example file.
    intro : str
        Introductory docstring of example, to show in tooltip
    title: str
        Title of example.
    is_backref : bool
        Whether the thumbnail is for a html backreference/recommendation file. If not
        a bullet list of the example is added for non-html documentation builds.
    check : bool
        Whether to check if the thumbnail image file exists.

    Returns
    -------
    thumbnail : str
        reST for a thumbnail.
    imagesthumb	sphx_glr_z
_thumb.pngz7Could not find internal Sphinx-Gallery thumbnail file:
/_)intro	thumbnailtitleref_name)r   r	   ospathr5   stemisfiler   relpathreplacesepBACKREF_THUMBNAIL_TEMPLATETHUMBNAIL_TEMPLATEformatr   )
target_dirsrc_dirfnamer   r   
is_backrefcheckr   r   full_dirr   templates               r   _thumbnail_divr   B  s(   8 KKE
Z74V
4V4V4VWW HE1  
RW^^E** 
NuNN
 
 	
 GOOE7++Ewz733H MM"&#&&Ew||He,,44RVSAAH-7O))=OH??UmmuEH    r   c                    |d         dS t          t                    }| D ]E}	t          j                            |d         |d         |	 d          }
|	|v }|rdnd}t          |
|fi t          5 }|sxd|	 d}|                    d	|z   d
z              |                    dt          |          z  d
z              |                    d           |                    t                     |                    t          ||d         |||d                     |                    |	           ||	                             |||||f           ddd           n# 1 swxY w Y   Gt          |          S )a  Write and return backreferences for one example.

    Backreferences '.examples' file written includes reST of the list of examples
    as thumbnails.

    Parameters
    ----------
    backrefs : set[str]
        Back references to write.
    seen_backrefs: set
        Back references already encountered when parsing this example.
    gallery_conf : Dict[str, Any]
        Gallery configurations.
    src_dir : str
        Stuff.
    target_dir : str
        Absolute path to directory where examples are saved.
    fname : str
        Filename of current example python file.
    intro : str
        Introductory docstring of example.
    title: str
        Title of example.

    Returns
    -------
    backrefs_example : dict[str, tuple]
        Dictionary where value is the backreference object and value
        is a tuple containing: example filename, full path to example source directory,
        full path to example target directory, intro, title.
    backreferences_dirNr   .examples.newawzExamples using ``z``z

rx   ^z 

.. start-sphx-glr-thumbnails

T)r   )r   r<   r   r   r5   openr
   writer?   THUMBNAIL_PARENT_DIVr   r*   r1   r   )backrefsseen_backrefsgallery_confr   r   r   r   r   backrefs_examplebackrefinclude_pathseenmodeex_fileheadings                  r   _write_backreferencesr   u  s   D ()1"4(( Y Yw||#-.%%%
 

 -'#ss,.... 	Y' 	4 :g999fw.5666cCLL047888DEEE 2333MM +#  	 	 	 g&&&W%,,eWj%QV-WXXX-	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y.  !!!s   1CEE	"E	c                 &   t           j        j                            d          }|d         dS | D ]}t          j                            |d         |d         | d          }t          j                            |          rWt          |dfi t          5 }|
                    t                     ddd           n# 1 swxY w Y   t          |d           |d	         d
         }t          ||          } |d|             |d           dS )z(Replace backref files only if necessary.zsphinx-galleryr   Nr   r   r   t)r   	log_levelbackreference_missingz$Could not find backreferences file: zTThe backreferences are likely to be erroneous due to file system case insensitivity.)sphinxutillogging	getLoggerr   r   r5   r   r   r
   r   THUMBNAIL_PARENT_DIV_CLOSEr   r@   )r   r   loggerr   r   r   rR   funcs           r   _finalize_backreferencesr     sz   [ **+;<<F()1   w||#-.%%%
 

 7>>$ 	 dC))5)) :W8999: : : : : : : : : : : : : : :C((((( -.EFE65))DD>>>???D9   ! s   B<<C 	C 	r^   )Nr   )FT)#r`   r/   rC   r   rq   rc   collectionsr   htmlr   pathlibr   sphinx.utilr   sphinx.errorsr   _dummyr   scrapersr	   utilsr
   r   r   r   NodeVisitorr   rn   rv   r   r   r   r   r   r   r   r   r   <module>r      s   
 


  				 				 



 # # # # # #                 ( ( ( ( ( (       % % % % % % & & & & & & & &  ~ ~ ~ ~ ~ ~ ~ ~B  D    E E E EP (   GK0 0 0 0fE" E" E"P    r   