
    PiFG              
         d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlZ ddl!Z ddl"Z dd	l#m$Z$ erdd
lm%Z% g dZ& ede          Z' ed          Z(i ddddddddddddddddddddddddddddd dddZ)d!gd"gd#gd$gd%gd&d'gd(gd)gd*gd+	Z*d,gd-gd.gd/gd0Z+dzd5Z,d{d8Z-d|d}d>Z.d~dAZ/	 dddFZ0	 	 	 dddLZ1ddNZ2ddPZ3dddTZ4dddXZ5	 ddd`Z6da dddbfddlZ7eddn            Z8edodpddq            Z8ddpddrZ8dsZ9	 dte9z   duz   Z:	 e:dvz   Z;	 e9dtz   Z<	 e:dwz   Z=	 ddyZ>dS )z
Some utility functions.

Miscellaneous utilities

* list2set
* first
* uniq
* more_than

Term characterisation and generation

* to_term
* from_n3

Date/time utilities

* date_time
* parse_date_time

    )annotations)timegm)splitext)altzonegmtime	localtimetimetimezone)TYPE_CHECKINGAnyCallableDictHashableIterableIteratorListOptionalSetTupleTypeVarUnionoverload)quoteurlsplit
urlunsplitN)sign)Graph)list2setfirstuniq	more_thanto_termfrom_n3	date_timeparse_date_timeguess_format
find_rootsget_tree	_coalesce_iri2uri
_HashableT)bound_AnyTxmlrdfowln3ttlturtlenttrixxhtmlrdfahtmlsvgnqnquadstrigjsonjson-ldjsonldzapplication/rdf+xmlztext/n3ztext/turtlezapplication/n-tripleszapplication/trixz	text/htmlzapplication/xhtml+xmlzapplication/n-quadszapplication/trigzapplication/ld+json)	r.   r1   r3   r4   r5   r7   r;   r<   r>   zapplication/sparql-results+xmlzapplication/sparql-results+jsonztext/csvztext/tab-separated-values)r.   r=   csvtsvseqIterable[_HashableT]returnList[_HashableT]c                <    t                      fd| D             S )zX
    Return a new list without duplicates.
    Preserves the order, unlike set(seq)
    c                F    g | ]}|v                     |          |S  )add).0xseens     _/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/rdflib/util.py
<listcomp>zlist2set.<locals>.<listcomp>}   s,    @@@!atmmDHHQKKmAmmm    set)rB   rL   s    @rM   r   r   v   s(    
 55D@@@@s@@@@rO   Iterable[_AnyT]Optional[_AnyT]c                    | D ]}|c S dS )z_
    return the first element in a python sequence
    for graphs, use graph.value instead
    NrH   )rB   results     rM   r   r      s!    
   4rO   sequenceIterable[str]stripintSet[str]c                V    |rt          d | D                       S t          |           S )z,removes duplicate strings from the sequence.c              3  >   K   | ]}|                                 V  d S N)rX   )rJ   ss     rM   	<genexpr>zuniq.<locals>.<genexpr>   s*      //17799//////rO   rP   )rV   rX   s     rM   r    r       s3     //h//////8}}rO   Iterable[Any]numberc                0    d}| D ]}|dz  }||k    r dS dS )z>Returns 1 if sequence has more items than number and 0 if not.r      rH   )rV   ra   iitems       rM   r!   r!      s9    	A  	Qv::11 1rO   r^   Optional[str]default Optional[rdflib.term.Identifier]c                   | s|S |                      d          r<|                     d          r't          j                            | dd                   S |                      d          r<|                     d          r't          j                            | dd                   S |                      d          rt          j                            |           S d| z  }t          |          )ay  
    Creates and returns an Identifier of type corresponding
    to the pattern of the given positional argument string `s`:

    '' returns the `default` keyword argument value or `None`

    '<s>' returns `URIRef(s)` (i.e. without angle brackets)

    '"s"' returns `Literal(s)` (i.e. without doublequotes)

    '_s' returns `BNode(s)` (i.e. without leading underscore)

    <>rc   "_zUnrecognised term syntax: '%s')
startswithendswithrdflibtermURIRefLiteralBNode	Exception)r^   rg   msgs      rM   r"   r"      s       
	
c		 qzz# {!!!AbD'***	
c		 qzz# {""1QrT7+++	
c		 {  ###.2nnrO   strbackendnsm+Optional[rdflib.namespace.NamespaceManager]&Optional[Union[rdflib.term.Node, str]]c                0	   | s|S |                      d          rMt          j                            | dd                             d                              d                    S |                      d          r|                      d          rd}nd}|                     |d          \  }}|t          |          d         }d}d}|                    d	          }	|	d
k    rt          ||	dz   d         |||          }n|                     d          r
|dd         }|
                    dd          }|
                    dd          }|                    d                              d          }t          j                            |||          S | dk    s| dk    r#t          j                            | dk              S |                                 
                    ddd          
                    ddd          
                    ddd                                          rd|                                 v r5t          j                            | t          j        j        j                  S d| v rBt          j                            t#          |           t          j        j        j                  S t          j                            t'          |           t          j        j        j                  S |                      d          r7t          | dd                   }
t          j                            ||
          S |                      d          r7t          | dd                   }
t          j                            ||
          S |                      d          r't          j                            | dd                   S d| v r|;t          j                            t          j                                                  }|                     dd          \  }}t7          |                                          |         }t          j                            |          |         S t          j                            |           S )a  Creates the Identifier corresponding to the given n3 string.

    ```python
    >>> from rdflib.term import URIRef, Literal
    >>> from rdflib.namespace import NamespaceManager
    >>> from_n3('<http://ex.com/foo>') == URIRef('http://ex.com/foo')
    True
    >>> from_n3('"foo"@de') == Literal('foo', lang='de')
    True
    >>> from_n3('"""multi\nline\nstring"""@en') == Literal(
    ...     'multi\nline\nstring', lang='en')
    True
    >>> from_n3('42') == Literal(42)
    True
    >>> from_n3(Literal(42).n3()) == Literal(42)
    True
    >>> from_n3('"42"^^xsd:integer') == Literal(42)
    True
    >>> from rdflib import RDFS
    >>> from_n3('rdfs:label') == RDFS['label']
    True
    >>> nsm = NamespaceManager(rdflib.graph.Graph())
    >>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/')
    >>> berlin = URIRef('http://dbpedia.org/resource/Berlin')
    >>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin
    True

    ```
    rj   rc   rl   zraw-unicode-escapezunicode-escaperm   z"""Nz^^r      @z\"z\xz\\xtruefalse. -e)datatype{[z_::)ro   rq   rr   rs   encodedecodersplitlenrfindr#   replacert   lower	isnumeric	namespaceXSDdoublefloatdecimalrY   integergraphQuotedGraphr   ru   NamespaceManagersplitdict
namespaces	Namespace)r^   rg   ry   rz   quotesvaluerestr   languagedtoffset
identifierprefix	last_partnss                 rM   r#   r#      s   F  ||C H$ {!!adGNN/00778HII
 
 	
 
c		 B$<< 	FFFhhvq))tc&kkmm$ ::d##q==
 tHqLNN3WgsKKHHs## $8eS)) eV,, 12299:JKK{""5(H===	
fW{""1;///				b!			b!			b!			!$ !''));&&q63C3G3N&OOO!88;&&uQxx&:J:N:V&WWW{""3q66F4D4H4P"QQQ	
c		 $QqtW%%
 |''<<<	
c		 $QqtW%%
 |!!':666	
d		 
${  122'''	;"33FL4F4F4H4HIICGGCOO	#..""##F+))"--i88{  ###rO   Fc           	         | t                      } |r:t          |           }|d         rt          dz  }n
t          dz  }d|dz  |dz  fz  }nt	          |           }d}|\	  }}}}}	}
}}}d|||||	|
|fz  }|S )a  http://www.w3.org/TR/NOTE-datetime ex: 1997-07-16T19:20:30Z

    ```python
    >>> date_time(1126482850)
    '2005-09-11T23:54:10Z'

    @@ this will change depending on where it is run
    #>>> date_time(1126482850, local_time_zone=True)
    #'2005-09-11T19:54:10-04:00'

    >>> date_time(1)
    '1970-01-01T00:00:01Z'

    >>> date_time(0)
    '1970-01-01T00:00:00Z'

    ```
    N   <   z
-%02d:%02dZz!%0004d-%02d-%02dT%02d:%02d:%02d%s)r	   r   r   r
   r   )tlocal_time_zone
time_tupletz_minstzdyearmonthdayhhmmsswdyzr^   s                  rM   r$   r$   )  s    & 	yFF 	q\\
a= 	%mGG"nGgmWr\::AYY
-7*D%b"b"a+tUCRS.QQAHrO   valc                l   d| vr| dz  } |                      d          \  }}|dd         |dd         }}|r|dk    r|dd         }d}nLt          |dd                   }t          |d	d
                   }t          |          |z  |dz  z   dz  }| }|                     d          \  }	}
}|                     d          \  }}}t          t          |	          t          |
          t          |          t          |          t          |          t          |          dddf	          }||z   }|S )a  always returns seconds in UTC

    ```python
    # tests are written like this to make any errors easier to understand
    >>> parse_date_time('2005-09-11T23:54:10Z') - 1126482850.0
    0.0

    >>> parse_date_time('2005-09-11T16:54:10-07:00') - 1126482850.0
    0.0

    >>> parse_date_time('1970-01-01T00:00:01Z') - 1.0
    0.0

    >>> parse_date_time('1970-01-01T00:00:00Z') - 0.0
    0.0
    >>> parse_date_time("2005-09-05T10:42:00") - 1125916920.0
    0.0

    ```
    Tz
T00:00:00Zr   r   Nr   rl            r   r   r   )r   rY   r   r   )r   ymdr	   hmstz_str	tz_offset
signed_hrsminssecsr   r   r   hourminutesecondr   s                   rM   r%   r%   O  s=   , #~~|		#ICqs)T!""XC Vs]]CRCy		__
6!A#;Z  4'*r/9R?E	yy~~D%99S>>D&&	TCJJC#d))S[[#f++qRSUVW	 	A 	
IAHrO   fpathfmapOptional[Dict[str, str]]c                    |pt           }|                    t          |                     p&|                    |                                           S )a}  
    Guess RDF serialization based on file suffix. Uses
    `SUFFIX_FORMAT_MAP` unless `fmap` is provided.

    Example:
        ```python
        >>> guess_format('path/to/file.rdf')
        'xml'
        >>> guess_format('path/to/file.owl')
        'xml'
        >>> guess_format('path/to/file.ttl')
        'turtle'
        >>> guess_format('path/to/file.json')
        'json-ld'
        >>> guess_format('path/to/file.xhtml')
        'rdfa'
        >>> guess_format('path/to/file.svg')
        'rdfa'
        >>> guess_format('path/to/file.xhtml', {'xhtml': 'grddl'})
        'grddl'

        ```

        This also works with just the suffixes, with or without leading dot, and
        regardless of letter case:

        ```python
        >>> guess_format('.rdf')
        'xml'
        >>> guess_format('rdf')
        'xml'
        >>> guess_format('RDF')
        'xml'

        ```
    )SUFFIX_FORMAT_MAPget_get_extr   )r   r   s     rM   r&   r&   ~  sA    J $$D88HUOO$$?(?(??rO   Tr   boolc                    t          |           d         }|dk    r|                     d          r| }|r|                                }|                    d          r
|dd         }|S )aK  
    Gets the file extension from a file(path); stripped of leading '.' and in
    lower case.

    Example:
        ```python
        >>> _get_ext("path/to/file.txt")
        'txt'
        >>> _get_ext("OTHER.PDF")
        'pdf'
        >>> _get_ext("noext")
        ''
        >>> _get_ext(".rdf")
        'rdf'

        ```
    rl   r   r   rc   N)r   ro   r   )r   r   exts      rM   r   r     so    $ 5//"
C
byyU%%c**y iikk
~~c !""gJrO   r   r   proprdflib.term.URIRefrootsOptional[Set[rdflib.term.Node]]Set[rdflib.term.Node]c                   t                      }|t                      }|                     |          D ]L\  }}|                    |           ||v r|                    |           ||vr|                    |           M|S )a  Find the roots in some sort of transitive hierarchy.

    find_roots(graph, rdflib.RDFS.subClassOf)
    will return a set of all roots of the sub-class hierarchy

    Assumes triple of the form (child, prop, parent), i.e. the direction of
    `RDFS.subClassOf` or `SKOS.broader`
    )rQ   subject_objectsrI   remove)r   r   r   	non_rootsrK   r   s         rM   r'   r'     s     (+uuI}%%d++  1a::LLOOOIIIaLLLLrO   c                    | S r]   rH   )rK   s    rM   <lambda>r     s    q rO   downrootrdflib.term.Nodemapper.Callable[[rdflib.term.Node], rdflib.term.Node]sortkeyOptional[Callable[[Any], Any]]donedir,Optional[Tuple[rdflib.term.Node, List[Any]]]c           
     \   |t                      }||v rdS |                    |           g }|dk    r|                     ||          }n|                     ||          }|D ].}	t	          | |	|||||          }
|
r|                    |
           / ||          t          ||          fS )a  
    Return a nested list/tuple structure representing the tree
    built by the transitive property given, starting from the root given

    i.e.

    ```python
    get_tree(
        graph,
        rdflib.URIRef("http://xmlns.com/foaf/0.1/Person"),
        rdflib.RDFS.subClassOf,
    )
    ```

    will return the structure for the subClassTree below person.

    dir='down' assumes triple of the form (child, prop, parent),
    i.e. the direction of RDFS.subClassOf or SKOS.broader
    Any other dir traverses in the other direction
    Nr   )key)rQ   rI   subjectsobjectsr(   appendsorted)r   r   r   r   r   r   r   treebranchesbranchr   s              rM   r(   r(     s    < |uut||HHTNNND f}}>>$--==t,,  UFD&'4EE 	KKNNNF4LL&733344rO   argsc                    d S r]   rH   rg   r   s     rM   r)   r)     s    @CrO   .)rg   c                    d S r]   rH   r   s     rM   r)   r)     s	     crO   c                    |D ]}||c S 	| S )a  
    This is a null coalescing function, it will return the first non-`None`
    argument passed to it, otherwise it will return `default` which is `None`
    by default.

    For more info regarding the rationale of this function see deferred
    [PEP 505](https://peps.python.org/pep-0505/).

    Args:
        *args: Values to consider as candidates to return, the first arg that
            is not `None` will be returned. If no argument is passed this function
            will return None.
        default: The default value to return if none of the args are not `None`.

    Returns:
        The first `args` that is not `None`, otherwise the value of
            `default` if there are no `args` or if all `args` are `None`.
    rH   )rg   r   args      rM   r)   r)     s+    *   ?JJJ NrO   z!$&'()*+,;=%z:@z/?/iric                   t          |           }|\  }}}}}|dvr| S t          |t                    }t          |t                    }t          |t                    }|j        r.|j                            d                              d          }nd}d|v rd| d}|j        r| d|j         }|j        rKt          |j        t                    }|j
        r"t          |j
        t                    }| d| }| d	| }t          |||||f          }	|                     d
          r|	                    d
          s|	d
z  }	|	S )u*  
    Prior art:

    - [iri_to_uri from Werkzeug](https://github.com/pallets/werkzeug/blob/92c6380248c7272ee668e1f8bbd80447027ccce2/src/werkzeug/urls.py#L926-L931)

    ```python
    >>> _iri2uri("https://dbpedia.org/resource/Almería")
    'https://dbpedia.org/resource/Almer%C3%ADa'

    ```
    )httphttps)safeidnaasciir   r   r   ]r   #)r   r   _PATH_SAFE_CHARS_QUERY_SAFE_CHARShostnamer   r   portusername_USERNAME_SAFE_CHARSpasswordr   rp   )
r   partsschemenetlocpathqueryfragmentauthpass_quoteduris
             rM   r*   r*   a  s    SMME.3+VVT5( &&&
,---D%/000EX$5666H~ &&v..55g>>
f}}Vz *))UZ))~ $U^*>???> 	+5IJJJK**[**D##6##
ffdE8<
=
=C
||C c!2!2 s
JrO   )rB   rC   rD   rE   )rB   rR   rD   rS   )r   )rV   rW   rX   rY   rD   rZ   )rV   r`   ra   rY   rD   rY   r]   )r^   rf   rg   rh   rD   rh   )NNN)
r^   rx   rg   rf   ry   rf   rz   r{   rD   r|   )NF)r   rx   rD   rY   )r   rx   r   r   rD   rf   )T)r   rx   r   r   rD   rx   )r   r   r   r   r   r   rD   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   rx   rD   r   )r   rS   rg   r-   rD   r-   )r   rS   rg   rS   rD   rS   )r   rx   rD   rx   )?__doc__
__future__r   calendarr   os.pathr   r	   r   r   r   r
   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   urllib.parser   r   r   rdflib.graphrq   rdflib.namespacerdflib.termrdflib.compatr   r   __all__r+   r-   r   FORMAT_MIMETYPE_MAP"RESPONSE_TABLE_FORMAT_MIMETYPE_MAPr   r   r    r!   r"   r#   r$   r%   r&   r   r'   r(   r)   _RFC3986_SUBDELIMS_RFC3986_PCHAR_NUr  r  r  r*   rH   rO   rM   <module>r"     s   , # " " " " "             < ; ; ; ; ; ; ; ; ; ; ; ; ;                                 5 4 4 4 4 4 4 4 4 4                   #""""""    W\222
	5	5 
5 	$	
 
8 	$ F V F 
6 	( h F I i  y! * ""+o"
# 12$% %&
 
  --./<'(	& & "A A A A           CG    > "!7;	m$ m$ m$ m$ m$`# # # #L, , , ,^&@ &@ &@ &@ &@R    > .2    < >I[.2,015 15 15 15 15h 
 C C C 
 C 
7:     
 8<     6 # 
 ,,t3  &,  *C/ 
 %s* 2 2 2 2 2 2rO   