U
    wbJ                     @   sF  d Z zddlmZ W n  ek
r4   ddlmZ Y nX ddlmZ ddlm	Z	 zddl
mZ W nF ek
r   zddlmZ W n  ek
r   ddlmZ Y nX Y nX eZddlZeeee dd d	k rdd
lmZ ddlmZ zeZW n ek
r
   eZY nX zeZW n ek
r.   eZY nX dZdZdZ G dd de!Z"G dd de#Z$deddddfddZ%d(ddZ&d)ddZ'd*d!d"Z(e)d#krBddl*Z*ddl+Z+ze*j,j-Z,e*j.j-Z.W n" e/k
r   e*j,Z,e*j.Z.Y nX e*j0d$d \Z1ee1Z1d%d& Z2z(e%e,e1e2ed'Z3e1dkr(e2g e3 W n e4k
r@   Y nX dS )+z:Makes working with XML feel like you are working with JSON    )pyexpat)expat)XMLGenerator)AttributesImpl)StringION   )      )OrderedDict)isgeneratorzMartin Blechz0.13.0MITc                   @   s   e Zd ZdS )ParsingInterruptedN)__name__
__module____qualname__ r   r   h/mounts/lovelace/software/anaconda3/envs/qiime2-amplicon-2024.2/lib/python3.8/site-packages/xmltodict.pyr   '   s   r   c                   @   s~   e Zd Zddd dddddd	edd
d	d	dfddZdd Zdd Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zd	S ) _DictSAXHandlerr   c                  G   s   dS NTr   )argsr   r   r   <lambda>.       z_DictSAXHandler.<lambda>T@#textF N:z#commentc                 C   sx   g | _ g | _g | _d | _|| _|| _|| _|| _|| _|| _	|| _
|| _|	| _|
| _|| _|| _|	 | _|| _|| _d S N)pathstackdataitem
item_depthxml_attribsitem_callbackattr_prefix	cdata_keyforce_cdatacdata_separatorpostprocessordict_constructorstrip_whitespacenamespace_separator
namespacesnamespace_declarations
force_listcomment_key)selfr!   r#   r"   r$   r%   r&   r'   r(   r)   r*   r+   r,   r.   r/   r   r   r   __init__,   s&    z_DictSAXHandler.__init__c                 C   s   | j d kr|S || j}|dkr&|S |d | ||d d   }}z| j | }W n tk
rj   |}Y nX |st|S | j||fS d S )N   )r,   rfindr+   KeyErrorjoin)r0   	full_namei	namespacenameZshort_namespacer   r   r   _build_nameO   s    

z_DictSAXHandler._build_namec                 C   s2   t |tr|S | t|dd d |dd d S )Nr   r   r3   )
isinstancedictr)   zip)r0   attrsr   r   r   _attrs_to_dict_   s    
z_DictSAXHandler._attrs_to_dictc                 C   s   || j |pd< d S )Nr   )r-   )r0   prefixurir   r   r   startNamespaceDecld   s    z"_DictSAXHandler.startNamespaceDeclc                 C   s   |  |}| |}|r2| jr2| j|d< |  | _| j||p@d f t| j| jkr| j| j	| j
f | jrg }| D ]F\}}| j|  | }| jr| | j||}n||f}|r||| q|| |}nd }|pd | _	g | _
d S )Nxmlns)r;   r@   r-   r)   r   appendlenr!   r   r    r   r"   itemsr$   r(   )r0   r7   r?   r:   Zattr_entrieskeyvalueentryr   r   r   startElementg   s*    





z_DictSAXHandler.startElementc                 C   s  |  |}t| j| jkrX| j}|d kr@| js2d n| j| j}| | j|}|sXt	 | j
r| jsjd n| j| j}| j}| j
 \| _| _| jr|r| pd }|r| jr|d kr|  }|d k	r|r| || j| | | j||| _n| | j||| _nd | _g | _| j  d S r   )r;   rF   r   r!   r    r   r'   r6   r#   r   r   popr*   stripr&   r)   	push_datar%   )r0   r7   r:   r    Zshould_continuer   r   r   r   
endElement   s8    



z_DictSAXHandler.endElementc                 C   s    | j s|g| _ n| j | d S r   )r   rE   r0   r   r   r   r   
characters   s    
z_DictSAXHandler.charactersc                 C   s&   | j r| }| | j| j|| _d S r   )r*   rM   rN   r    r/   rP   r   r   r   comments   s    z_DictSAXHandler.commentsc                 C   s   | j d k	r.|  | j||}|d kr&|S |\}}|d kr>|  }z.|| }t|tr^|| n||g||< W n4 tk
r   | ||r|g||< n|||< Y nX |S r   )r(   r   r)   r<   listrE   r5   _should_force_list)r0   r    rH   r   resultrI   r   r   r   rN      s"    

z_DictSAXHandler.push_datac                 C   sZ   | j s
dS t| j tr| j S z|| j kW S  tk
rT   |  | jd d || Y S X d S )NFr2   )r.   r<   bool	TypeErrorr   )r0   rH   rI   r   r   r   rT      s    z"_DictSAXHandler._should_force_list)r   r   r   _dictr1   r;   r@   rC   rK   rO   rQ   rR   rN   rT   r   r   r   r   r   +   s0   
#r   Fr   Tc                 K   s.  t f d|i|}t| tr.|s$d}| |} |s6d}|||}	z
d|	_W n tk
r`   Y nX |j|	_|j	|	_
|j|	_|j|	_|r|j|	_d|	_|rzd}
|	j|
d W n( tk
r   dd |	_dd |	_Y nX t| d	r|	|  n:t| r| D ]}|	|d
 q|	dd n|	| d |jS )a  Parse the given XML input and convert it into a dictionary.

    `xml_input` can either be a `string`, a file-like object, or a generator of strings.

    If `xml_attribs` is `True`, element attributes are put in the dictionary
    among regular child elements, using `@` as a prefix to avoid collisions. If
    set to `False`, they are just ignored.

    Simple example::

        >>> import xmltodict
        >>> doc = xmltodict.parse("""
        ... <a prop="x">
        ...   <b>1</b>
        ...   <b>2</b>
        ... </a>
        ... """)
        >>> doc['a']['@prop']
        u'x'
        >>> doc['a']['b']
        [u'1', u'2']

    If `item_depth` is `0`, the function returns a dictionary for the root
    element (default behavior). Otherwise, it calls `item_callback` every time
    an item at the specified depth is found and returns `None` in the end
    (streaming mode).

    The callback function receives two parameters: the `path` from the document
    root to the item (name-attribs pairs), and the `item` (dict). If the
    callback's return value is false-ish, parsing will be stopped with the
    :class:`ParsingInterrupted` exception.

    Streaming example::

        >>> def handle(path, item):
        ...     print('path:%s item:%s' % (path, item))
        ...     return True
        ...
        >>> xmltodict.parse("""
        ... <a prop="x">
        ...   <b>1</b>
        ...   <b>2</b>
        ... </a>""", item_depth=2, item_callback=handle)
        path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1
        path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2

    The optional argument `postprocessor` is a function that takes `path`,
    `key` and `value` as positional arguments and returns a new `(key, value)`
    pair where both `key` and `value` may have changed. Usage example::

        >>> def postprocessor(path, key, value):
        ...     try:
        ...         return key + ':int', int(value)
        ...     except (ValueError, TypeError):
        ...         return key, value
        >>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>',
        ...                 postprocessor=postprocessor)
        {'a': {'b:int': [1, 2], 'b': 'x'}}

    You can pass an alternate version of `expat` (such as `defusedexpat`) by
    using the `expat` parameter. E.g:

        >>> import defusedexpat
        >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat)
        {'a': 'hello'}

    You can use the force_list argument to force lists to be created even
    when there is only a single child of a given level of hierarchy. The
    force_list argument is a tuple of keys. If the key for a given level
    of hierarchy is in the force_list argument, that level of hierarchy
    will have a list as a child (even if there is only one sub-element).
    The index_keys operation takes precedence over this. This is applied
    after any user-supplied postprocessor has already run.

        For example, given this input:
        <servers>
          <server>
            <name>host1</name>
            <os>Linux</os>
            <interfaces>
              <interface>
                <name>em0</name>
                <ip_address>10.0.0.1</ip_address>
              </interface>
            </interfaces>
          </server>
        </servers>

        If called with force_list=('interface',), it will produce
        this dictionary:
        {'servers':
          {'server':
            {'name': 'host1',
             'os': 'Linux'},
             'interfaces':
              {'interface':
                [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } }

        `force_list` can also be a callable that receives `path`, `key` and
        `value`. This is helpful in cases where the logic that decides whether
        a list should be forced is more complex.


        If `process_comment` is `True` then comment will be added with comment_key
        (default=`'#comment'`) to then tag which contains comment

            For example, given this input:
            <a>
              <b>
                <!-- b comment -->
                <c>
                    <!-- c comment -->
                    1
                </c>
                <d>2</d>
              </b>
            </a>

            If called with process_comment=True, it will produce
            this dictionary:
            'a': {
                'b': {
                    '#comment': 'b comment',
                    'c': {

                        '#comment': 'c comment',
                        '#text': '1',
                    },
                    'd': '2',
                },
            }
    r+   utf-8NTz4http://apache.org/xml/features/disallow-doctype-declc                 S   s   d S r   r   xr   r   r   r   p  r   zparse.<locals>.<lambda>c                  W   s   dS )Nr3   r   rZ   r   r   r   r   r  r   readFr   )r   r<   _unicodeencodeParserCreateordered_attributesAttributeErrorrC   StartNamespaceDeclHandlerrK   StartElementHandlerrO   EndElementHandlerrQ   CharacterDataHandlerrR   CommentHandlerbuffer_text_reader
setFeatureDefaultHandlerExternalEntityRefHandlerhasattr	ParseFiler   Parser    )Z	xml_inputencodingr   Zprocess_namespacesr+   Zdisable_entitiesZprocess_commentskwargshandlerparserfeaturechunkr   r   r   parse   sP     






ru   r   c                 C   sl   |s| S z|  |d\}} W n tk
r0   Y n8X |||}|rdd||rX|nd||| n| } | S )Nr3   z{}{}{}{}r   )rsplit
ValueErrorgetrM   format
startswith)r:   r,   Zns_sepr$   nsZns_resr   r   r   _process_namespace~  s"      r|   r   
	c                 C   s  t | ||
|} |d k	r4|| |}|d kr,d S |\} }t|drRt|tsRt|trX|g}t|D ]@\}}|r|dkr|dkrtd|d krt }n\t|tr|rt	d}qt	d}n:t|ts|rt|drt|tst||ff}nt	|}t|trt||ff}d }t }g }|
 D ]\}}||kr<|}q"||rt |||
|}|dkrt|tr|
 D ]0\}}d|rd|nd	}t	|||< qtq"t|t	st	|}|||t|d  < q"|||f q"|r|||	  || t| |r"|r"|| |D ]0\}}t||||||d
 ||||	||
|d q&|d k	rl|| |r|r|||	  ||  |r`|r`|| q`d S )N__iter__r   zdocument with multiple rootstruefalsez@xmlnszxmlns{}z:{}r   r3   )r,   r+   expand_iter)r|   rl   r<   _basestringr=   	enumeraterw   rX   rV   r]   rG   rz   ry   rF   rE   ZignorableWhitespacerK   r   _emitrQ   rO   )rH   rI   content_handlerr$   r%   depthpreprocessorprettynewlindentr+   r,   full_documentr   rU   indexvcdatar?   childrenikivkattrZ	child_keychild_valuer   r   r   r     s    







      



r   rY   c           
      K   s   |rt | dkrtdd}|dkr.t }d}|r@t||d}n
t||}|rV|  |  D ] \}}	t||	|fd|i| q^|r|  |r| }	z|		|}	W n t
k
r   Y nX |	S dS )ax  Emit an XML document for the given `input_dict` (reverse of `parse`).

    The resulting XML document is returned as a string, but if `output` (a
    file-like object) is specified, it is written there instead.

    Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
    as XML node attributes, whereas keys equal to `cdata_key`
    (default=`'#text'`) are treated as character data.

    The `pretty` parameter (default=`False`) enables pretty-printing. In this
    mode, lines are terminated with `'
'` and indented with `'	'`, but this
    can be customized with the `newl` and `indent` parameters.

    r3   z$Document must have exactly one root.FNTr   )rF   rw   r   r   ZstartDocumentrG   r   ZendDocumentgetvaluedecodera   )

input_dictoutputro   r   short_empty_elementsrp   Zmust_returnr   rH   rI   r   r   r   unparse  s0    
r   __main__r3   c                 C   s   t | |ft dS r   )marshaldumpstdout)r   r    r   r   r   handle_item  s    r   )r!   r#   r)   )r   r   )r   r   r   NFr}   r~   r   NTN)NrY   TF)5__doc__Zdefusedexpatr   r   ImportErrorxml.parsersZxml.sax.saxutilsr   Zxml.sax.xmlreaderr   	cStringIOr   ior=   rX   platformtuplemapintpython_version_tuplecollectionsr
   inspectr   
basestringr   	NameErrorstrunicoder]   
__author____version____license__	Exceptionr   objectr   ru   r|   r   r   r   sysr   stdinbufferr   ra   argvr!   r   rootKeyboardInterruptr   r   r   r   <module>   s   

    
 5
           
O  
+

