
    Pi                       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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ZddlmZmZmZ ddlm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mZm Z  dd	l!m"Z" dd
lm#Z#  e$            Z%g 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+d,d-i d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\Z'd](                                Z)ej*        Z* G d^ d_          Z+ e+            Z,ej-         G d` dae                      ZdddZ.deej/        e0e1f         fdfZ2ddge3fdhZ4ddiZ5 G dj dkej6                  Z6dl Z7 G dm dn          Z8ddpZ9 G dq drej:                  Z;ds Z<dt Z=ej-         G du dv                      Z>dw Z?ej-         G dx dye>                      Z@dz ZAd{ ZBej-         G d| d}e>                      ZCd~ ZDej-         G d deC                      ZEd ZFej-         G d d                      ZGej-         G d d                      ZHd ZIej-         G d deC                      ZJd ZKd ZLej-         G d deC                      ZMej-         G d deM                      ZNd ZOej-         G d deM                      ZP G d d          ZQdS )zFunctionality to read and write metadata for CSV files.

This module implements (partially) the W3C recommendation
"Metadata Vocabulary for Tabular Data".

.. seealso:: https://www.w3.org/TR/tabular-metadata/
    N)urljoinurlparse
urlunparse)tags   )utils	DATATYPES)DialectUnicodeReaderWithLineNumberUnicodeWriter)DataPackage)jsonld)	
TableGroupTableColumn
ForeignKeyLinkNaturalLanguageDatatypeis_urlCSVWcsvwzhttp://www.w3.org/ns/csvw#rdfz+http://www.w3.org/1999/02/22-rdf-syntax-ns#rdfsz%http://www.w3.org/2000/01/rdf-schema#xsdz!http://www.w3.org/2001/XMLSchema#dczhttp://purl.org/dc/terms/dcatzhttp://www.w3.org/ns/dcat#provzhttp://www.w3.org/ns/prov#schemazhttp://schema.org/asz&https://www.w3.org/ns/activitystreams#cczhttp://creativecommons.org/ns#ctagzhttp://commontag.org/ns#dc11z http://purl.org/dc/elements/1.1/dctypeszhttp://purl.org/dc/dcmitype/dqvzhttp://www.w3.org/ns/dqv#duvzhttps://www.w3.org/ns/duv#foafzhttp://xmlns.com/foaf/0.1/grz!http://purl.org/goodrelations/v1#grddlz#http://www.w3.org/2003/g/data-view#icalz&http://www.w3.org/2002/12/cal/icaltzd#r   zhttp://www.w3.org/ns/json-ld#ldpzhttp://www.w3.org/ns/ldp#mazhttp://www.w3.org/ns/ma-ont#oazhttp://www.w3.org/ns/oa#odrlzhttp://www.w3.org/ns/odrl/2/ogzhttp://ogp.me/ns#orgzhttp://www.w3.org/ns/org#owlzhttp://www.w3.org/2002/07/owl#qbz!http://purl.org/linked-data/cube#rdfazhttp://www.w3.org/ns/rdfa#revzhttp://purl.org/stuff/rev#rifzhttp://www.w3.org/2007/rif#rrzhttp://www.w3.org/ns/r2rml#sdz0http://www.w3.org/ns/sparql-service-description#sioczhttp://rdfs.org/sioc/ns#z$http://www.w3.org/2004/02/skos/core#z"http://www.w3.org/2008/05/skos-xl#zhttp://www.w3.org/ns/sosa/zhttp://www.w3.org/ns/ssn/zhttp://www.w3.org/2006/time#z http://rdf.data-vocabulary.org/#z http://www.w3.org/2006/vcard/ns#zhttp://rdfs.org/ns/void#z!http://www.w3.org/2007/05/powder#z#http://www.w3.org/2007/05/powder-s#z#http://www.w3.org/1999/xhtml/vocab#z$http://www.w3.org/XML/1998/namespace)skosskosxlsosassntimevvcardvoidwdrwrdsxhvxmla  Cell
Column
Datatype
Dialect
Direction
ForeignKey
JSON
NumericFormat
Row
Schema
Table
TableGroup
TableReference
Transformation
aboutUrl
base
columnReference
columns
commentPrefix
datatype
decimalChar
default
delimiter
describes
dialect
doubleQuote
encoding
foreignKeys
format
groupChar
header
headerRowCount
json
lang
length
lineTerminators
maxExclusive
maxInclusive
maxLength
maximum
minExclusive
minInclusive
minLength
minimum
name
notes
null
ordered
pattern
primaryKey
propertyUrl
quoteChar
reference
referencedRows
required
resource
row
rowTitles
rownum
schemaReference
scriptFormat
separator
skipBlankRows
skipColumns
skipInitialSpace
skipRows
source
suppressOutput
tableDirection
tableSchema
tables
targetFormat
textDirection
titles
transformations
trim
uriTemplate
url
valueUrl
virtualc                       e Zd ZdS )InvalidN__name__
__module____qualname__     a/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/csvw/metadata.pyrG   rG      s        DrM   rG   c            	           e Zd ZdZ ej        d ej        ej	        e
dd          ej                            ej                            e
                              ZdS )r   a  
    The spec is ambiguous regarding a default for the commentPrefix property:

    > commentPrefix
    >     An atomic property that sets the comment prefix flag to the single provided value, which
    >     MUST be a string. The default is "#".

    vs.

    > comment prefix
    >     A string that, when it appears at the beginning of a row, indicates that the row is a
    >     comment that should be associated as a rdfs:comment annotation to the table. This is set
    >     by the commentPrefix property of a dialect description. The default is null, which means
    >     no rows are treated as comments. A value other than null may mean that the source numbers
    >     of rows are different from their numbers.

    So, in order to pass the number formatting tests, with column names like `##.#`, we chose
    the second reading - i.e. by default no rows are treated as comments.
    NT
allow_nonedefault	converter	validator)rI   rJ   rK   __doc__attrib	functoolspartialr   rT   str
validatorsoptionalinstance_ofcommentPrefixrL   rM   rN   r   r      sv         & DG#)#EOS$4PPP/**4?+F+Fs+K+KLLN N NMMMrM   r   rutf-8c                 @    |dk    sJ t          j        | ||          S )Nra   encoding)ioopen)filenamemoderd   s      rN   	json_openri      s*    w78TH5555rM   returnc                 4   t          |           } t          |           r2t          j        |                               t
          j                  S t          |           5 }t	          j        |t
          j                  cd d d            S # 1 swxY w Y   d S )N)object_pairs_hook)	r[   r   requestsgetjsoncollectionsOrderedDictri   load)fnamefs     rN   get_jsonru      s    JJEe}} S|E""''+:Q'RRR	5		 GQyk.EFFFG G G G G G G G G G G G G G G G G Gs     BBBwarningc                 R    |r t          ||          |            d S  ||           Ngetattr)msgloglevelexception_clss       rN   log_or_raiser      s:    
 !UC     mC   rM   c                     ddl m}  G d dt                    } |            }t          ||  |d |                     |S )Nr   )
MethodTypec                       e Zd ZdS )nolog.<locals>.LogNrH   rL   rM   rN   Logr      s        rM   r   c                      d S rx   rL   )argskws     rN   <lambda>znolog.<locals>.<lambda>   s    t rM   )typesr   objectsetattr)r}   r   r   r|   s       rN   nologr      sr              f    #%%CC

#;#;SAABBBJrM   c                   $     e Zd Z fdZd Z xZS )URITemplatec                     t          |t                    r| j        |k    S t          |d          sdS t	          t
          |                               |          S )NuriF)
isinstancer[   r   hasattrsuperr   __eq__)selfother	__class__s     rN   r   zURITemplate.__eq__   sW    eS!! 	%8u$$ue$$ 	5[$''..u555rM   c                 ,    d                     |           S N{}format)r   r   s     rN   asdictzURITemplate.asdict   s    {{4   rM   )rI   rJ   rK   r   r   __classcell__r   s   @rN   r   r      sG        6 6 6 6 6! ! ! ! ! ! !rM   r   c            	          d } t          j        dt           j                            t           j                            t
          t          f                    |           S )z

    Note: We do not currently provide support for supplying the "_" variables like "_row"
    when expanding a URI template.

    .. seealso:: http://w3c.github.io/csvw/metadata/#uri-template-properties
    c                     | d S t          | t                    st          j        d           t          S t          |           S )Nz#Invalid value for aboutUrl property)r   r[   warningswarnINVALIDr   r?   s    rN   converter_uriTemplatez4uri_template_property.<locals>.converter_uriTemplate	  s@    94!S!! 	M?@@@N1~~rM   NrS   rU   rT   )rW   rX   r\   r]   r^   r   rG   )r   s    rN   uri_template_propertyr     s[       7/**4?+F+FU\G]+^+^__') ) ) )rM   c                   \    e Zd ZdZdej        eej        f         fdZ	d Z
d
dZd Zd Zd	S )r   zK

    .. seealso:: http://w3c.github.io/csvw/metadata/#link-properties
    stringc                 t    t          |t          t          j        f          st	          d          || _        d S )NzInvalid value for link property)r   r[   pathlibPath
ValueErrorr   )r   r   s     rN   __init__zLink.__init__  s6    &3"566 	@>???rM   c                     | j         S rx   r   r   s    rN   __str__zLink.__str__"  
    {rM   Tc                     | j         S rx   r   r   omit_defaultss     rN   r   zLink.asdict%  r   rM   c                 P    t          |t                    r| j        |j        k    ndS NF)r   r   r   )r   r   s     rN   r   zLink.__eq__(  s%    .8.E.EPt{el**5PrM   c                     t          |d          r@t          | j                  r| j        S |                                r|n|j        | j        z  S t          || j                  S )z
        Resolve a `Link` relative to `base`.

        :param base:
        :return: Either a string, representing a URL, or a `pathlib.Path` object, representing         a local file.
        joinpath)r   r   r   is_dirparentr   )r   bases     rN   resolvezLink.resolve,  sc     4$$ 	Jdk"" #{" KKMM:DDt{dkIItT[)))rM   NT)rI   rJ   rK   rV   typingUnionr[   r   r   r   r   r   r   r   rL   rM   rN   r   r     s         
v|C,=>    
     Q Q Q* * * * *rM   r   Fc                     t          j        d t           j                            t           j                            t
                              d           S )Nc                 (    | | nt          |           S rx   )r   r   s    rN   r   zlink_property.<locals>.<lambda>?  s    AAQ rM   r   )rW   rX   r\   r]   r^   r   requireds    rN   link_propertyr   ;  sG    7/**4?+F+Ft+L+LMM779 9 9 9rM   c                   @     e Zd ZdZ fdZd	dZd
dZd Zd
dZ xZ	S )r   zW

    .. seealso:: http://w3c.github.io/csvw/metadata/#natural-language-properties
    c                 8   t          t          |                                            || _        t	          | j        t
                    r| j        g| d <   d S t	          | j        t          t          f          rMt          d | j        D                       st          j
        d           d S t          | j                  | d <   d S t	          | j        t                    r| j                                        D ]\  }}t          j        |          st          d          t	          |t          t          f          s|g}g }|D ]A}t	          |t
                    r|                    |           -t          j
        d           B|| |<   d S t          d          )Nc              3   @   K   | ]}t          |t                    V  d S rx   r   r[   ).0r?   s     rN   	<genexpr>z+NaturalLanguage.__init__.<locals>.<genexpr>N  s,      >>az!S))>>>>>>rM   zAtitles with array values containing non-string values are ignoredz(Invalid language tag for NaturalLanguagez1Title with value which is not a string is ignoredz&invalid value type for NaturalLanguage)r   r   r   valuer   r[   listtupleallr   r   dictitemsr   checkr   append)r   r   kr?   titlesvvr   s         rN   r   zNaturalLanguage.__init__H  s   ot$$--///
dj#&& 	G*DJJJ
T5M22 	G>>4:>>>>> .abbbbb!$*--T



D)) 	G
((** ! !1z!}} Q$%OPPP!!dE]33 A [ [B!"c** [b)))) &YZZZZ Q! ! EFFFrM   Tc                     t          |           d gk    r5t          | d                    dk    r|                                 S | d          S t          j        d |                                 D                       S )Nr   c              3   b   K   | ]*\  }}|dn|t          |          dk    r|d         n|fV  +d S )Nundr   r   )lenr   r   r?   s      rN   r   z)NaturalLanguage.asdict.<locals>.<genexpr>g  s]       '& '&1 iUUQA!!C'& '& '& '& '& '&rM   )r   r   getfirstrp   rq   r   r   s     rN   r   zNaturalLanguage.asdictb  s{    ::$4:!##}}&:& '& '&

'& '& '& & & 	&rM   Nc                 N    || vrg | |<   | |                              |           d S rx   )r   )r   r   langs      rN   addzNaturalLanguage.addk  s4    tDJT
&!!!!!rM   c                     |                                  p3t          t          |                                                     d         S Nr   )r   nextitervaluesr   s    rN   r   zNaturalLanguage.__str__p  s2    }}>$tDKKMM':':";";A">>rM   c                 <    |                      |d g          d         S r   rn   )r   r   s     rN   r   zNaturalLanguage.getfirsts  s    xxtf%%a((rM   r   rx   )
rI   rJ   rK   rV   r   r   r   r   r   r   r   s   @rN   r   r   B  s         
G G G G G4& & & &" " " "
? ? ?) ) ) ) ) ) ) )rM   r   c                     t          | t                    st          j        d           d S |                     d          r"t          d                    |                     | S )NzInconsistent link property_zInvalid @id property: {})r   r[   r   r   
startswithr   r   r   s    rN   valid_id_propertyr   w  s`    a 2333t||C ?3::1==>>>HrM   c                    t          | t                    rd | D                                 h d          st          d          d| v rt	          |           dk    r~t	          |           dk    s\t          |                                           ddhddhfvs3t          | d         t          t          t          t          j        f          st          d	          d| v rd| vrt          d
          d| v rt          | d                   | d<   d| v rLt          | d         t                    rt          j        | d                   st          j        d           | d= d| v r| d         t          t                    rl                    d          rt          d          t%                    s8t'          fdt(          D                       st*          vrt          d          n+t          t,          t          f          st          d          d |                                 D             S t          | t,                    rd | D             S | S )Nc                 L    h | ]!}|                     d           |dd         "S )@r   Nr   )r   r   s     rN   	<setcomp>z(valid_common_property.<locals>.<setcomp>  s1    666!ALL$5$56!""666rM   >   idtyper   languagezeAside from @value, @type, @language, and @id, the properties used on an object MUST NOT start with @.z@valuer      	@language@typea  If a @value property is used on an object, that object MUST NOT have any other properties aside from either @type or @language, and MUST NOT have both @type and @language as properties. The value of the @value property MUST be a string, number, or boolean value.zXA @language property MUST NOT be used on an object unless it also has a @value property.@idInvalid language tagz_:z\The value of any @id or @type contained within a metadata document MUST NOT be a blank node.c              3   T   K   | ]"}|k    p                     |d z             V  #dS ):Nr   )r   nsr   s     rN   r   z(valid_common_property.<locals>.<genexpr>  s<      YYb CBMM"s(,C,CYYYYYYrM   zThe value of any member of @type MUST be either a term defined in [csvw-context], a prefixed name where the prefix is a term defined in [csvw-context], or an absolute URL.zInvalid datatype for @typec                 4    i | ]\  }}|t          |          S rL   valid_common_property)r   r   r   s      rN   
<dictcomp>z)valid_common_property.<locals>.<dictcomp>  s'    DDDB(,,DDDrM   c                 ,    g | ]}t          |          S rL   r   r   r   s     rN   
<listcomp>z)valid_common_property.<locals>.<listcomp>  s!    666b%b))666rM   )r   r   issubsetr   r   setkeysr[   boolintdecimalDecimalr   r   r   r   r   r   r   any
NAMESPACES
CSVW_TERMSr   r   )r?   r   s    @rN   r   r     s   !T *E66q666??3335 5 	*)* * * q==1vvzzq66A::qvvxx==(K1H8U\J]0^^^)!H+T37XYY _$VW W W
 ! 1 1#$ $ $ A::(522AeH!q~s33 #
1[>8R8R #4555kNa<<7B"c"" ?==&& 5$45 5 5 bzz ?YYYYjYYYYY?*,,$>? ? ?  T4L11 ? !=>>>DD!''))DDDD!T 766A6666HrM   c            
       <   e Zd ZdZ ej         ej        e                    Z ej         ej        e                    Z	e
	 	 ddej        eej        f         dej        e         dej        edf         fd            Ze
defd	            Zd
 ZddefdZdS )DescriptionBasezzContainer for
    - common properties (see http://w3c.github.io/csvw/metadata/#common-properties)
    - @-properties.
    rS   NTd	type_namerj   c                 4   |rt          |t                    sd S t          j        |           }|p| j        }i i i }}}|pi                                 D ]\  }}	|                    d          rR|dk    rt          |	          }	|dk    r)|	|k    r#t          d	                    |	|                    |	||dd          <   ld|v rt          |	          ||<   |r-||vr)t          j        d	                    ||                     |	||<   t          d	||d|S )
Nr   r   r   z Invalid @type property {} for {}r   r   zInvalid property {} for {}common_propsat_propsrL   )r   r   rW   fields_dictrI   r   r   r   r   r   r   r   r   )
clsr  r  strictfieldscaddr   r?   s
             rN   partition_propertiesz$DescriptionBase.partition_properties  sP   
  	Z4(( 	F!#&&-	r2b1W"OO%% 	 	DAq||C   ::)!,,A<<ANN$%G%N%NqR[%\%\]]]!ABB%,Q//! qM">"E"Ea"S"STTTTBqEE5Q55"555rM   c                 8     | di |                      |          S NrL   )r  )r  r  s     rN   	fromvaluezDescriptionBase.fromvalue  s&    s11S--a00111rM   c              #     K   fdfd}t          | j                                                  D ]\  }}d|z    ||          fV  t          | j                                                  D ]\  }}| ||          fV  t	          j        |                                           D ]\  }}|dvr| ||          fV  d S )Nc                 T    t          | d          r|                               n| S )Nr   r   )r   r   )r?   r   s    rN   _asdict_singlez8DescriptionBase._iter_dict_items.<locals>._asdict_single  s,    <CAx<P<PW188-8888VWWrM   c                 n    t          | t          t          f          rfd| D             S  |           S )Nc                 &    g | ]} |          S rL   rL   )r   r   r%  s     rN   r  zNDescriptionBase._iter_dict_items.<locals>._asdict_multiple.<locals>.<listcomp>  s#    777rr**777rM   )r   r   r   )r?   r%  s    rN   _asdict_multiplez:DescriptionBase._iter_dict_items.<locals>._asdict_multiple  sC    !dE]++ 87777Q7777!>!$$$rM   r   r$  r  )sortedr  r   r  r   attr_asdict)r   r   r(  r   r?   r%  s    `   @rN   _iter_dict_itemsz DescriptionBase._iter_dict_items  s;     	X 	X 	X 	X 	X	% 	% 	% 	% 	%
 4=..0011 	/ 	/DAq'++A.......4,224455 	) 	)DAq%%a(((((((%d-HHHNNPP 	- 	-DAq444))!,,,,,,	- 	-rM   c                 d    t          j        d |                     |          D                       S )Nc              3   <   K   | ]\  }}|d k    s|g i fv||fV  dS )nullNrL   r   s      rN   r   z)DescriptionBase.asdict.<locals>.<genexpr>  sM       '5 '5q!V"b 1 1 F 1 1 1 1'5 '5rM   )rp   rq   r+  r   s     rN   r   zDescriptionBase.asdict  sC    
 & '5 '5#44]CC'5 '5 '5 5 5 	5rM   )NTr   )rI   rJ   rK   rV   rW   rX   Factoryr   r  r  classmethodr   r   AnyOptionalr[   r  r!  r+  r   rL   rM   rN   r  r    s        
 47<4<#5#5666Ltw|t|D11222H @D$(6 6 &T6:-= >6(.(<6 .4\$*-E6 6 6 [62 2$ 2 2 2 [2- - -&5 5D 5 5 5 5 5 5rM   r  c                      t          j        d t           j                            t           j                            t
                              d           S )Nc                 (    | | nt          |           S rx   )r  r   s    rN   r   zoptional_int.<locals>.<lambda>  s    AAA rM   r   )rW   rX   r\   r]   r^   r  rL   rM   rN   optional_intr5    sG    7/**4?+F+Fs+K+KLL668 8 8 8rM   c            
          e Zd ZdZ ej        d ej        ej	        e
ddd           ej                            ej                            e                              Z ej        d          Z e            Z e            Z e            Z ej        d          Z ej        d          Z ej        d          Z ej        d          Z ej        d          Z ej        d          Zed	ej        e
ed f         d
d fd            Zd Z ddZ!e"d             Z#e"d             Z$d Z%d Z&d Z'd Z(dS )r   a  
    A datatype description

        Cells within tables may be annotated with a datatype which indicates the type of the values
        obtained by parsing the string value of the cell.

    .. seealso:: `<https://www.w3.org/TR/tabular-metadata/#datatypes>`_
    Nr   Tc                     | d u p| t           v S rx   r	   )sss    rN   r   zDatatype.<lambda>  s    B$J<Y"PY/ rM   rQ   condrR   r  r?   rj   c                    t          |t                    r | |          S t          |t                    r1|                    dd            | di |                     |          S t          ||           r|S t          |          )a   
        :param v: Initialization data for `cls`; either a single string that is the main datatype         of the values of the cell or a datatype description object, i.e. a `dict` or a `cls`         instance.
        :return: An instance of `cls`
        )r   r   r   NrL   )r   r[   r   
setdefaultr  r   r  r?   s     rN   r!  zDatatype.fromvalue  s     a 	3A;;;a 	6LL***35511!44555a 	HmmrM   c                     dD ]D}t           |          2t           |                     t           |                               E j        L j         j         j        k     rt          d           j         j         j        k    rt          d           j        & j         j         j        k    rt          d          t           j        t                    st                      t           
                                t          d dD                                 s<t           fdd                                D                       rt          d	          t           
                                t          d
         t          d         t          d         f          s$ j        s j        s j        rt          d           j        r j        s j        r j        rt          d           j        r j        r j         j        k    s j        r& j        r j         j        k     rt          d           j        r j        r j         j        k    s j        r& j        r j         j        k    rt          d          d j        v r/t           fdt          D                       rt          d          t           
                                t          d                   r`d j        v rYt)           j        d                                       t)          d                    s!d  _        t/          j        d           d S d S d S d S )NminimummaximumminInclusivemaxInclusiveminExclusivemaxExclusivezminLength > lengthzmaxLength < lengthzminLength > maxLengthc              3   0   K   | ]}t           |         V  d S rx   r	   )r   names     rN   r   z/Datatype.__attrs_post_init__.<locals>.<genexpr>E  s&      ``4y``````rM   )r	  floatdatetimedurationc                 0    g | ]}t          |          S rL   ry   )r   atr   s     rN   r  z0Datatype.__attrs_post_init__.<locals>.<listcomp>F  s5     c c c"GD"%% c c crM   zCminimum maximum minExclusive maxExclusive minInclusive maxInclusivezApplications MUST raise an error if minimum, minInclusive, maximum, maxInclusive, minExclusive, or maxExclusive are specified and the base datatype is not a numeric, date/time, or duration type.r   base64Binary	hexBinaryzApplications MUST raise an error if length, maxLength, or minLength are specified and the base datatype is not string or one of its subtypes, or a binary type.zApplications MUST raise an error if both minInclusive and minExclusive are specified, or if both maxInclusive and maxExclusive are specified. r   c              3   V   K   | ]#}j         d          t          d         |z   k    V  $dS )r   r   N)r  r  )r   dtr   s     rN   r   z/Datatype.__attrs_post_init__.<locals>.<genexpr>c  sR       )S )SBDd#z%'82'==)S )S )S )S )S )SrM   z8datatype @id MUST NOT be the URL of a built-in datatype.r	  patternu   #0.,;%‰E-+zInvalid number pattern)rz   r   parselength	minLengthr   	maxLengthr   derived_descriptionr   basetyper   r  splitr
   rB  rD  rC  rE  r  r  r  r   r   r   )r   attr_s   ` rN   __attrs_post_init__zDatatype.__attrs_post_init__-  s   
 	G 	GE tU##/eTZZe0D0D%E%EFFF;"~)dkDN.J.J !5666~);//$%9:::>%$.*DNT^334555$2D99 	,,``3_```aac c 	O  c c c cY__aac c c d d O NO O O
 8$i&?;AWXZ Z 	$ { $dn $ $ #$ $ $
  	V$"3 	V9J 	VtO` 	VUV V V  	!$"3 	!8ITM^8^8^" 9_'+'8 9_=A=NQUQb=b=bR..  	!$"3 	!8ITM^8^8^! 9_&*&7 9_<@<MQUQb<b<bR.. 4=  S )S )S )S )SHQ)S )S )S &S &S WXXXdmmooy';<< 	8T555t/	:;;DDSEXEXYY 8"677777		8 	8558 8rM   c                     t                               | |          }dD ]$}||v r|                     ||                   ||<   %t          |          dk    rd|v r|d         S |S )Nr$  r?  r   r   )r  r   	formattedr   )r   r   resrZ  s       rN   r   zDatatype.asdictm  sv    $$T$GG
 	8 	8E ||!^^CJ77E
s88q==Vs]]v;
rM   c                 &    t           | j                 S rx   )r
   r   r   s    rN   rX  zDatatype.basetypex  s    ##rM   c                 6    | j                             |           S rx   )rX  rW  r   s    rN   rW  zDatatype.derived_description|  s    }00666rM   c                 2     | j         j        |fi | j        S rx   )rX  	to_stringrW  r   r?   s     rN   r]  zDatatype.formatted  s"    &t}&qEED,DEEErM   c                 :    ||S  | j         j        |fi | j        S rx   )rX  	to_pythonrW  rc  s     rN   rS  zDatatype.parse  s,    9H&t}&qEED,DEEErM   c                 p   ||S 	 t          |pd          }| j        2|| j        k    r't          d                    | j                            | j        2|| j        k     r't          d                    | j                            | j        2|| j        k    r't          d                    | j                            n# t          $ r Y nw xY w| j        j        rV| j	        2|| j	        k     r't          d                    | j	                            | j
        2|| j
        k     r't          d                    | j
                            | j        2|| j        k    r't          d                    | j                            | j        2|| j        k    r't          d                    | j                            | j        2|| j        k    r't          d                    | j                            | j        2|| j        k    r't          d                    | j                            |S )	NrO  zvalue must have length {}z"value must have at least length {}z!value must have at most length {}zvalue must be >= {}zvalue must be > {}zvalue must be <= {}zvalue must be < {})r   rT  r   r   rU  rV  	TypeErrorrX  minmaxr@  rB  rD  rA  rC  rE  )r   r?   l_s      rN   validatezDatatype.validate  s+   9H		QW"B{&2+<+< !<!C!CDK!P!PQQQ~)b4>.A.A !E!L!LT^!\!\]]]~)b4>.A.A !D!K!KDN![![\\\ 	 	 	D	= 	Q|'A,<,< !6!=!=dl!K!KLLL ,T5F1F1F !6!=!=d>O!P!PQQQ ,d6G1G1G !5!<!<T=N!O!OPPP|'A,<,< !6!=!=dl!K!KLLL ,T5F1F1F !6!=!=d>O!P!PQQQ ,d6G1G1G !5!<!<T=N!O!OPPPs   B<C 
CCc                 R    |                      |                     |                    S rx   )rj  rS  rc  s     rN   readzDatatype.read  s    }}TZZ]]+++rM   r   ))rI   rJ   rK   rV   rW   rX   rY   rZ   r   rT   r[   r\   r]   in_r
   r   r   r5  rT  rU  rV  r@  rA  rB  rC  rD  rE  r0  r   r   r   r!  r[  r   propertyrX  rW  r]  rS  rj  rl  rL   rM   rN   r   r     s         47#)#Od1Y1Y[ [ [ /**4?+>+>y+I+IJJL L LD TWT"""F\^^FIIdgd###Gdgd###G474(((L474(((L474(((L474(((L&,sD*'<= *    [&>8 >8 >8@	 	 	 	 $ $ X$ 7 7 X7F F FF F F
  8, , , , ,rM   r   c                     | g nt          | t                    r| n| g}t          d |D                       st          j        d           dgS |S )Nc              3   @   K   | ]}t          |t                    V  d S rx   r   r  s     rN   r   z!converter_null.<locals>.<genexpr>  s,      11rz"c""111111rM   zInvalid null propertyrO  )r   r   r   r   r   )r?   r^  s     rN   converter_nullrq    s`    	""Z4%8%8 AqcC11S11111 -...tJrM   c                 Z    t          j        |           st          j        d           dS | S )Nr   r   )r   r   r   r   r   s    rN   converter_langrs    s-    :a== ,---uHrM   c            
       z   e Zd ZdZ ej        ddd          Z e            Z ej        dd           Z	 ej        d e
j        ej        edd                    Z ej        d	e          Z ej         ej        d
           e          Z ej        d e
j        ej        edd                    Z e            Z ej        d          Z ej         e
j        ej        edd          d          Z ej        d e
j        ej        eddd                     Z e            Zd Zd ZdS )DescriptionzvAdds support for inherited properties.

    .. seealso:: http://w3c.github.io/csvw/metadata/#inherited-properties
    NF)rS   repreqc                 >    | s| nt                               |           S rx   )r   r!  r   s    rN   r   zDescription.<lambda>  s    QAAAH,>,>q,A,A rM   rS   rT   rO  )
allow_listr   c                      dgS )NrO  rL   rL   rM   rN   r   zDescription.<lambda>  s     rM   TrP   r  )rT   rS   c                 
    | dv S )N)NltrrtlautoinheritrL   r   s    rN   r   zDescription.<lambda>  s    q<c7c rM   r9  c                     t          | |          }|K| j        rDt          | j        d          r| j                            |          nt          | j        |          S |S )Nr  )rz   _parentr   r  )r   rW   r?   s      rN   r  zDescription.inherit  s^    D$9918y1Q1Q 14<''---T\4001rM   c                     | j         dgk    r5| j        r.t          | j        d          r| j                                        S | j         S )NrO  inherit_null)r.  r  r   r  r   s    rN   r  zDescription.inherit_null  sJ    9| 3n E E 3|00222yrM   )rI   rJ   rK   rV   rW   rX   r  r   aboutUrldatatyperY   rZ   r   rT   r[   rS   rs  r   r/  rq  r.  r  orderedpropertyUrlr   	separatortextDirectionvalueUrlr  r  rL   rM   rN   ru  ru    s         dgd5999G$$&&HtwAAC C CH dg#)#EOS"OOO  G 475N;;;D47<4<55PPPDdg#)#EOT5TRRR  G ('))Ktwt$$$H#)#EOS$4PPP  I DG#)#O$-c-ce e e  M %$&&H      rM   ru  c                 t    	 | | nt          |           S # t          $ r t          j        d           Y d S w xY w)NzInvalid titles property)r   r   r   r   r   s    rN   converter_titlesr    sP    Iqq?1#5#55   /000tts    77c            	          e Zd ZdZ ej        d ej        ej	        e
dd                    Z ej        d ej        ej	        ed                    Z ej        dej                            ej                            e                    e          Z ej        d ej        ej	        ed                    Z ej        dd          Zd	 Zd
 Zed             ZddZd ZdS )r   a  
    A column description is an object that describes a single column.

        The description provides additional human-readable documentation for a column, as well as
        additional information that may be used to validate the cells within the column, create a
        user interface for data entry, or inform conversion into other formats.

    .. seealso:: `<https://www.w3.org/TR/tabular-metadata/#columns>`_
    NTrP   ry  Fr   )rS   rv  c                     | j         p9| j        o| j                                        pd                    | j                  S )N_col.{})rG  r   r   r   _numberr   s    rN   r   zColumn.__str__  sA    y +[3T[1133+T\**	+rM   c                     | j         r| j         |k    rdS | j        pi                                 D ]\  }}||v r|pdc S dS )NTr   F)rG  r   r   )r   r?   tagr   s       rN   	has_titlezColumn.has_title  sd    9 	a4 K-24466 	$ 	$KCF{{|e### urM   c                 ,    d                     |           S r   r   r   s    rN   headerzColumn.header  s    {{4   rM   c                    |                      d          }|                                 |                      d          |                      d          }|                      d          |s}|r)|v r%|st          j        d           t	          d          |r<|sg }n=|v rd }n6fd|                    |          D             }fd|D             }n|v rd }rbt          |t                    r8	 fd|D             S # t          $ r |st          j        d	           |cY S  w xY w                    |          S |S )
Nr   rS   r  r   required column value is missingc              3       K   | ]}|pV  	d S rx   rL   )r   r   rS   s     rN   r   zColumn.read.<locals>.<genexpr>5  s'      @@rR]7@@@@@@rM   c                      g | ]
}|v rd n|S rx   rL   )r   r   r.  s     rN   r  zColumn.read.<locals>.<listcomp>6  s%    <<<BR4ZZTTR<<<rM   c                 :    g | ]}                     |          S rL   )rl  )r   r   r  s     rN   r  zColumn.read.<locals>.<listcomp>=  s%    :::"HMM"--:::rM   zInvalid value for list element.)	r  r  r   r   r   rY  r   r   rl  )r   r?   r  r   r  r  rS   r.  s        @@@rN   rl  zColumn.read   s   <<
++  "",,y))LL--	<<
++ 	A 	AT		 B@AAA?@@@ 		 =d@@@@QWWY-?-?@@@<<<<!<<<$YYA 		$!T"" ::::::::!   ! ! &GHHH 	
 ==###s   7D "D+)D+c                     |                      d          }|                                 |                      d          fd|r#|                    fd|pg D                       S  |          S )Nr  r  c                 J    | d         S r                     |           S | S r   )r]  )r?   r  r.  s    rN   fmtzColumn.write.<locals>.fmtK  s2    yAw -))!,,,HrM   c              3   .   K   | ]} |          V  d S rx   rL   )r   r   r  s     rN   r   zColumn.write.<locals>.<genexpr>S  s+      66CCGG666666rM   )r  r  join)r   r?   sepr  r  r.  s      @@@rN   writezColumn.writeF  s    ll;''  ""<<
++	 	 	 	 	 	  	7886666ag2666666s1vvrM   r   )rI   rJ   rK   rV   rW   rX   rY   rZ   r   rT   r[   rG  r  suppressOutputr\   r]   r^   r   r  r   virtualr  r   r  rn  r  rl  r  rL   rM   rN   r   r     sp         47#)#EOS$4PPP  D TW#)#EOT5AAC C CN TW/**4?+F+F+W+WXX"$ $ $F dge/@y/@RVX]/^/^___Gdgd///G+ + +
   ! ! X!$ $ $ $L    rM   r   c                      t          j        d t           j                            t           j                            t
                              d           S )Nc                 :    t          | t                    s| | n| gS rx   r   r   r   s    rN   r   z"column_reference.<locals>.<lambda>[  s    At!4!4J	AAs rM   r   )rW   rX   r\   r]   r^   r   rL   rM   rN   column_referencer  W  sK    7/**4?+F+Ft+L+LMMJJL L L LrM   c                   P    e Zd Z e            Z e            Z e            Zd ZdS )	Referencec                 D    | j         | j        t          |           d S d S rx   )resourceschemaReferencer   r   s    rN   r[  zReference.__attrs_post_init__e  s.    =$)=)IT""" %$)I)IrM   N)	rI   rJ   rK   r   r  r  r  columnReferencer[  rL   rM   rN   r  r  ^  sI         }H#mooO&&((O# # # # #rM   r  c                   `    e Zd Z e            Z ej        d          Zed             Z	d Z
dS )r   Nr  c           	      j   t          |t                    rv	 t          di |d         }n# t          $ r t	          d          w xY wt          |                                                              ddh          st	          d          t          |t          di |d                   } | di |S )N	referencezInvalid reference propertyr  zInvalid foreignKey spec)r  rL   )r   r   r  rg  r   r  r  r  )r  r  r   r   s       rN   fromdictzForeignKey.fromdictp  s    a 	<?//+// ? ? ? !=>>>?qvvxx==))+<k*JKK < !:;;;!y::1[>::;;;syyRyys	   * Ac                 `    t          j        | fi |}t          j        |d         fi ||d<   |S )Nr  )r   r*  )r   r   r^  s      rN   r   zForeignKey.asdict|  sA    ++++ ,S-=DDDDK
rM   )rI   rJ   rK   r  r  rW   rX   r  r0  r  r   rL   rM   rN   r   r   j  s`         '&((O%%%I	 	 [	    rM   r   c                    g } t          j        t          j        t          d           |           D ]T}	 |                    t                              |                     1# t          $ r t          j
        d           Y Qw xY w|S )NzInvalid foreignKeys spec)rY   rZ   r   rT   r   r   r   r  rg  r   r   )r?   r^  r  s      rN   converter_foreignKeysr    s    
C;Yud;;A>> 6 6	6JJz**1--.... 	6 	6 	6M455555	6Js   -A""BBc                   &   e Zd ZdZ ej         ej        e          d           Z ej         ej        e          d           Z	 e
            Z ej         ej        e          d           Zd Zed             Zed             Zdd
ZdS )SchemaaL  
    A schema description is an object that encodes the information about a schema, which describes
    the structure of a table.

    :ivar columns: `list` of :class:`Column` descriptions.
    :ivar foreignKeys: `list` of :class:`ForeignKey` descriptions.

    .. seealso:: `<https://www.w3.org/TR/tabular-metadata/#schemas>`_
    c           	          d  t          j        t          j        t          d            t          j        t          j        t
          g           |                     D             S )Nc                 B    g | ]}t                               |          S rL   )r   r!  r   r  s     rN   r  z#Schema.<lambda>.<locals>.<listcomp>  s9     B B B$%FQB B BrM   )rY   rZ   r   rT   r   r   r   s    rN   r   zSchema.<lambda>  sc     B B)W):5?DRV)W)W<	!%/4<<Q??*A *AB B B rM   ry  c                 (    | g nt          |           S rx   )r  r   s    rN   r   zSchema.<lambda>  s    !)BB1Fq1I1I rM   c                 6    t          | t                    r| n| gS rx   r  r   s    rN   r   zSchema.<lambda>  s    At!4!4=AA1# rM   c                    dt                      t                      }}}t          | j                  D ]\  }}|j        rH|j                            d          st          j        d|j                  rt          j        d           |j	        rd}n|rt          d          |s|j        |v rt          j        d           |j        rJ|j        |v r't          d                    |j                            |                    |j                   |                    |j                   | |_        |d	z   |_        | j        pg D ]@}| j                            |          }|r"|j        st          j        d
           d | _        Ad S )NFr   \szInvalid column nameTz3no non-virtual column allowed after virtual columnszDuplicate column name!zDuplicate column name {}r   z:A primaryKey referenced column MUST have a `name` property)r  	enumeratecolumnsrG  r   researchr   r   r  r   r  r   r   r  r  
primaryKey
columndictrn   )r   r  seennamesicolcolrefs          rN   r[  zSchema.__attrs_post_init__  s   $ceeSUUu-- 	  	 FAsx 5SX0055 55#(9S9S 53444{ X X !VWWW %:%%M":;;;8 (x5((()C)J)J38)T)TUUUIIch'''$$$CKa%CKKo+ 	' 	'F/%%f--C '38 'Z[[["&		' 	'rM   c                 D   t          |t                    r1	 t          j        |                                          }n	#  |cY S xY wt          |t
                    s+t          |t                    rt          j        d           i } | di | 	                    |          S )Nz&Invalid value for tableSchema propertyrL   )
r   r[   rm   rn   ro   r   r  r   r   r  r=  s     rN   r!  zSchema.fromvalue  s    a 	LOO((**!T"" 	!S!! HFGGGAs11S--a00111s	   &> Ac                 $    d | j         D             S )Nc                     i | ]
}|j         |S rL   r  r  s     rN   r   z%Schema.columndict.<locals>.<dictcomp>  s    222!222rM   )r  r   s    rN   r  zSchema.columndict  s    22T\2222rM   Fc                     | j                             |          }|r|r|j        sJ |sM| j        D ]E}|j        r!|j                                        |k    r|c S |j        r|j        j        |k    r|c S F|S rx   )r  rn   rG  r  r   r   r  r   )r   rG  r  r  r  s        rN   
get_columnzSchema.get_column  s    o!!$''11111 	\  8  1 1 3 3t ; ;HHH= Q]%6$%>%>HHH
rM   NF)rI   rJ   rK   rV   rW   rX   r/  r   r  foreignKeysr  r  	rowTitlesr[  r0  r!  rn  r  r  rL   rM   rN   r  r    s         dgT""B BC C CG
 $'T""IIK K KK "!##JT""==  I
' ' '2 2 2 [2 3 3 X3	 	 	 	 	 	rM   r  c                     t          | t                    st          j        d           i S t                              | dd          }|d= |d= |                    d          rd|d	<   |S )
NzInvalid dialect specr   F)r  r  r  r  headerRowCountTr  )r   r   r   r   ru  r  rn   )r  partitioneds     rN   dialect_propsr    sz    a ,---	221	RW2XXKJN#'(( % $HrM   c                     t          |t                    st          j        d           |D ]}t                              |d           d S )Nz Invalid transformations propertyTemplate)r  )r   r   r   r   ru  r  )instance	attributer   trs       rN   valid_transformationsr    s^    eT"" :8999 C C((z(BBBBC CrM   c            	          e Zd ZdZ ej        dd           Z ej         ej        e                    Z	 ej        d e
j        ej        edd           ej                            g d	          
          Z ej        dd           Z ej        e ej        e                    Z e            Z ej        d          Zd Zd Zeddej        eej        f         dd fd            Zeddedd fd            Z ddej        eej        f         dej        fdZ!e"dej        eej        f         fd            Z#dde$de%defdZ&dS )	TableLikeaH  
    A CSVW description object as encountered "in the wild", i.e. identified by URL on the web or
    as file on disk.

    Since `TableLike` objects may be instantiated from "externally referenced" objects
    (via file paths or URLs), they have the necessary means to resolve
    `link properties <https://www.w3.org/TR/tabular-metadata/#link-properties>`_

    .. code-block:: python

        >>> from csvw import Table, TableGroup, Link
        >>> t = Table.from_file('tests/fixtures/csv.txt-table-metadata.json')
        >>> Link('abc.txt').resolve(t.base)
        PosixPath('tests/fixtures/abc.txt')
        >>> tg = TableGroup.from_url(
        ...     'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/'
        ...     'csv.txt-metadata.json')
        >>> str(tg.tables[0].url)
        'csv.txt'
        >>> tg.tables[0].url.resolve(tg.base)
        'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/csv.txt'

    and `URI template properties <https://www.w3.org/TR/tabular-metadata/#uri-template-properties>`_
    (see :meth:`~TableLike.expand`).
    Nc                 f    | t          | t                    r| nt          di t          |           S r   )r   r[   r   r  r   s    rN   r   zTableLike.<lambda>  s6    !)z!S/A/A)AA((}Q''(( rM   ry  r  r  c                 
    | dv S )Nr~  r}  r  rL   )ss    rN   r   zTableLike.<lambda>  s    >T9T rM   )r:  r  rR   c                 6    t                               |           S rx   )r  r!  r   s    rN   r   zTableLike.<lambda>  s    F,,Q// rM   )rU   rS   c                 r   t          | j        t                    rUt          di t	          t          t          | j                                      | j                                      | _        | j	        r&t          | j	        t                    s| | j	        _
        d| j        v r| j        d         | j        | j        d<   | j                            d          }t          |t                    r|D ]}t          |t                    r6t          |                                                              ddh          rt          |t                    r|dk    rt%          d          t          |t                    r5d|v r1t'          j        |d                   st+          j        d           |d= d S d S )	Nr   context@baser   http://www.w3.org/ns/csvwa  The @context MUST have one of the following values: An array composed of a string followed by an object, where the string is http://www.w3.org/ns/csvw and the object represents a local context definition, which is restricted to contain either or both of@base and @language.z$Invalid value for @language propertyrL   )r   dialectr[   r   r  ru   r   r   r   tableSchemar  r  rn   r   r   r  r  r  r   r   r   r   r   )r   ctxobjs      rN   r[  zTableLike.__attrs_post_init__  s   dlC(( 	e"dd]8D<N<N<V<VW[W`<a<a3b3b%c%cddDL 	,Z0@#%F%F 	,'+D$4=  T]4%8%@"&)DM$m	**c4   	- - -sD)) 0#chhjj//2J2JGU`Ka2b2b 0&sC00058<W5W5W$/0 0 0 c4(( -[C-?-?:c+&677 - &LMMM,	- 	-- -rM   c                 H    | j         r| j                             |          nd S rx   r  r  )r   specs     rN   r  zTableLike.get_column5  s&    484DNt**4000$NrM   rs   rj   c                     t          t          |                    r$|                     t          |          |          S |                     |pt	          |                    }t          j        |          |_        |S )zZ
        Instantiate a CSVW Table or TableGroup description from a metadata file.
        data)r   r[   from_urlr!  ru   r   r   _fname)r  rs   r  r^  s       rN   	from_filezTableLike.from_file8  sh    
 #e** 	7<<E

<666mmD3HUOO44\%((

rM   urlc                    |pt          |          }t          |          }|                    dt          |j        |j        |j        dddf                     |                    d|g          D ]p}t          |t                    rYt          |                    d          t                    r1t          |d                                       |d                   |d<   q|                     |          }|S )zk
        Instantiate a CSVW Table or TableGroup description from a metadata file specified by URL.
        r  rO  tablesr  )ru   r   r<  r   schemenetlocpathrn   r   r   r[   r   r   r!  )r  r  r  tabler^  s        rN   r  zTableLike.from_urlC  s    
 $x}}smmSZSXrSUWY,Z![![\\\XXh// 	Y 	YE%&& Y:eii6N6NPS+T+T Y'+E-,@'A'A'I'I$w-'X'Xm$mmD!!
rM   Tc                     t          j        |          }|                     |          }t          t	          |          d          5 }t          j        ||dd           ddd           n# 1 swxY w Y   |S )a/  
        Write a CSVW Table or TableGroup description as JSON object to a local file.

        :param omit_defaults: The CSVW spec specifies defaults for most properties of most         description objects. If `omit_defaults==True`, these properties will be pruned from         the JSON object.
        r$  w   ),z: )indent
separatorsN)r   ensure_pathr   ri   r[   ro   dump)r   rs   r   r  rt   s        rN   to_filezTableLike.to_fileQ  s     !%(({{{77s5zz3'' 	A1IdAaK@@@@	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	As   A--A14A1c                    | j         r| j         j        n| j        }d}| j                            dg           D ]#}t          |t                    rd|v r|d         }$d|v r2|r(t          |                              |d                   S |d         S | j         r| j         j        r| j         j        j        n| j        r| j        j        ndS )z?
        The "base" to resolve relative links against.
        Nr  r  r   )	r  r  rn   r   r   r   r   r  r   )r   r  ctxbaser  s       rN   r   zTableLike.base_  s    
 -1LK4<((dm=$$Y33 	' 	'C#t$$ 'Cg,X ? G}},,Xf-=>>>F##.2l :t|?R :t|"))#';8T[D	:rM   Ftmplrowc           	         |t           u r| j                            | j                  S t                                          D ]X\  }}|j                            |dz             r6d                    ||j        	                    d          d                   } nxYt           |j        d||dd |                                D                                           | j        r| j                            | j                  n| j                  }t          |t          j                  sQ|rOt                                          D ]5\  }}|                    |          r|                    ||dz             } n6|S )a#  
        Expand a `URITemplate` using `row`, `_row` and `_name` as context and resolving the result
        against `TableLike.url`.

        .. code-block:: python

            >>> from csvw import URITemplate, TableGroup
            >>> tg = TableGroup.from_url(
            ...     'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/'
            ...     'csv.txt-metadata.json')
            >>> tg.expand(URITemplate('/path?{a}{#b}'), dict(a='1', b='2'), None)
            'https://raw.githubusercontent.com/path?1#2'

        r   z{}{}r   )_row_namec                 D    i | ]\  }}t          |t                    ||S rL   r   )r   _k_vs      rN   r   z$TableLike.expand.<locals>.<dictcomp>  s-    OOO&"b:b#;N;NOr2OOOrM   rL   )r   r  r   r   r  r   r   r   r   rY  r   expandr   r   r   replace)	r   r  r  r
  r  qnameprefixr  r^  s	            rN   r  zTableLike.expands  s    7??8##DI...%++-- 	S 	SKFCx""6C<00  mmC)<)<Q)?@@	    POCIIKKOOO  
 7$(Q48++DI666	RR  #w|,, 	 #-#3#3#5#5  KFC~~c** !kk#v|<< 
rM   rx   r   r   )'rI   rJ   rK   rV   rW   rX   r  r/  r   notesrY   rZ   r   rT   r[   r\   rm  tableDirectionr  r  transformationsr   r  r  r[  r  r0  r   r   r   r   r  r  r  rn  r   r   r   r  rL   rM   rN   r  r    sg        2 dg) )* * *G DGLDL..///ETW#)#OS&/T/TV V V/%%&<&<&<==	? ? ?N
 $'//1 1 1K dg'T""  O -//CTWT"""F- - -.O O O  fl3+<= [    [  3 k    [ V\#w|*;< U\Ua     :fl3#45 : : : X:&% %; %T %UX % % % % % %rM   r  c                      e Zd ZdZ ej        d          Zg Zd Zd Z	e
dej        edf         fd            Zdefd	Zedddfd
ej        ej        eeef                  dej        ej        eej        f                  dej        ej        eej        f                  dej        e         dej        e         dej        eef         fdZddefdZd Zdddej        dfdej         eddf         fdZ!dS )r   a  
    A table description is an object that describes a table within a CSV file.

    `Table` objects provide access to schema manipulation either by manipulating the `tableSchema`
    property directly or via higher-level methods like :meth:`~Table.add_foreign_key`

    `Table` objects also mediate read/write access to the actual data through

    - :meth:`~Table.write`
    - :meth:`~Table.iterdicts`

    .. seealso:: `<https://www.w3.org/TR/tabular-metadata/#tables>`_
    Fr  c                 >    t          |t          t          f          s|gn|}t           fd|D                       s"t	          d                    |                     j        j                            t          
                    |||dd                     dS )a	  
        Add a foreign key constraint to `tableSchema.foreignKeys`.

        :param colref: Column reference for the foreign key.
        :param ref_resource: Referenced table.
        :param ref_colref: Column reference of the key in the referenced table.
        c              3   H   K   | ]}|d  j         j        D             v V  dS )c                     g | ]	}|j         
S rL   )rG  r  s     rN   r  z3Table.add_foreign_key.<locals>.<genexpr>.<listcomp>  s    DDDa16DDDrM   N)r  r  )r   r  r   s     rN   r   z(Table.add_foreign_key.<locals>.<genexpr>  s=      WW3DD4+;+CDDDDWWWWWWrM   z unknown column in foreignKey {0})r  r  )r  r  N)r   r   r   r   r   r   r  r  r   r   r  )r   r  ref_resource
ref_colrefs   `   rN   add_foreign_keyzTable.add_foreign_key  s     ",FUDM!B!BN&WWWWPVWWWWW 	P?FFvNNOOO$++J,?,?%&2zRRA
 A
 - - 	 	 	 	 	rM   c                 f    t                               |            | j        st          d          d S )Nz#url property is required for Tables)r  r[  r  r   r   s    rN   r[  zTable.__attrs_post_init__  s<    %%d+++x 	DBCCC	D 	DrM   rj   Nc                 ,    | j         r| j         j        nd S rx   )r  r   r   s    rN   
local_namezTable.local_name  s    "&(4tx4rM   c                 R    | j         p | j        r| j        j         pt                      S rx   )r  r  r   r   s    rN   _get_dialectzTable._get_dialect  s$    |S E1ES'))SrM   r   rs   r   r  _zippedc           
         |                                  }d | j        j        D             }|t          u r5| j                            |rt          j        |          n| j                  }d}t          ||          5 }	|j
        r|	                    d |D                        |D ]ӊt          t          t          f          rfdt          |          D             }
n|rot!                                                    d |D             z
  }|r?t%          d                    d                    d	 |D                                           fd
|D             }
|dz  }|	                    |
           | |	                                cddd           S 	 ddd           n# 1 swxY w Y   |r|rt          j        |          }t-          j        t1          |j                            |j        dz                       dt,          j                  5 }|                    t1          |          |j                   ddd           n# 1 swxY w Y   |                                 |S )a  
        Write row items to a CSV file according to the table schema.

        :param items: Iterator of `dict` storing the data per row.
        :param fname: Name of the file to which to write the data.
        :param base: Base directory relative to which to interpret table urls.
        :param strict: Flag signaling to use strict mode when writing. This will raise `ValueError`        if any row (dict) passed in `items` contains unspecified fieldnames.
        :param _zipped: Flag signaling whether the resulting data file should be zipped.
        :return: The CSV content if `fname==None` else the number of rows written.
        c                      g | ]}|j         	|S rL   )r  r  s     rN   r  zTable.write.<locals>.<listcomp>  s    QQQ!qyQAQQQrM   r   r  c                     g | ]	}|j         
S rL   r  r  s     rN   r  zTable.write.<locals>.<listcomp>  s     D D Da D D DrM   c                 L    g | ] \  }}|                     |                   !S rL   )r  )r   r  r  items      rN   r  zTable.write.<locals>.<listcomp>  s-    XXX&!S399T!W--XXXrM   c                 8    h | ]}d                      |          S r   r   r   r  s     rN   r   zTable.write.<locals>.<setcomp>  s$    1_1_1_s$++c2B2B1_1_1_rM   z*dict contains fields not in fieldnames: {}z, c              3   @   K   | ]}d                      |          V  dS )z'{}'Nr   )r   fields     rN   r   zTable.write.<locals>.<genexpr>  s.      )P)P5&--*>*>)P)P)P)P)P)PrM   c                     g | ]V}|                                         |j                            d                     |                                        WS r*  )r  rn   r  r   )r   r  r(  s     rN   r  zTable.write.<locals>.<listcomp>  sl     5 5 5   		$((JS1A1A(B(B#D #D E E5 5 5rM   r   N.zipr  )compression)arcname)r!  r  r  DEFAULTr  r   r   r   r   r   r  writerowr   r   r   r  r  r  r   r   r  rl  zipfileZipFiler[   r   r   rG  ZIP_DEFLATEDr  unlink)r   r   rs   r   r  r"  r  non_virtual_colsrowcountwriterr  r   fpathzipfr(  s                 @rN   r  zTable.write  s:   " ##%%QQt'7'?QQQGH$$4%NW\$%7%7%7TYOOE5'222 	%f~ F D D3C D D DEEE % %dT5M22 5XXXXIFV<W<WXXXCC S!$))++..1_1_N^1_1_1__ S",-Y-`-` $		)P)PC)P)P)P P P.R .R #S #S S5 5 5 5 $45 5 5C A$$$$}{{}}'	% 	% 	% 	% 	% 	% 	% 	%$ %	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%(  	W 	L''EEL))%*v*=>>??#0   ; 

3u::uz
:::; ; ; ; ; ; ; ; ; ; ; ; ; ; ; LLNNNs%   =DF))F-0F-*IIIc                    d}|t          j        d           | j        j        rt	          j        | j        j         }t                      }|                     t                      d          D ]S\  }}} ||          }	|	|v r)t          d
                    |||	          |           d}>|                    |	           T|S )NTzSthe items argument of check_primary_key is deprecated (its content will be ignored)r|   with_metadataz"{0}:{1} duplicate primary key: {2}r|   F)r   r   r  r  operator
itemgetterr  	iterdictsr   r   r   r   )
r   r|   r   successget_pkr  rs   linenor  pks
             rN   check_primary_keyzTable.check_primary_key   s    M H I I I& 	!($*:*EFF55D&*nnPTn&U&U ! !"vsVC[[:: <CCE6SUVV! ! ! ! $GGHHRLLLLrM   c                 *    |                                  S rx   )rC  r   s    rN   __iter__zTable.__iter__  s    ~~rM   Tc              #   P   "K                                     }|p j                             j                  }g g t	                      }	}} j        j        D ]m}
|
j        r)|
j        r!|	                    |
j
        |
j        f           n|	                    |
j
                   |
j        r|	                    |
j
                   nt          j                    5 }t          |          rRt!          j        t!          j        t'          j        t+          |                    j                  |j                  }n|}t1          j        |          ""                                s"j                            "j        dz             }|                                r|                    t?          j         t+          |                              }t!          j        |!                    "fd|"                                D             d                   |j                  }|                    tG          ||                    }tI          |          }|j
        r7	 tK          |          \  }}|s j        j        r>tM           j        j                  tM          |          k     rtO          j(        d           tS          | j        j                  D ]\  }}
|
*                    |          }|
j        s|stO          j(        d           tW          |t*                    rS|,                    d          d         d	 j-        pd	,                    d          d         fvrtO          j(        d
           n# t\          $ r Y ddd           dS w xY w|}||k    s,tM           j        j                  tM          |          k    r*|s(t_          tS          | j        j                            }n|s j        j        rtM           j        j                  tM          |          k     rg }ta          |          D ]\  }}	 |	                    | j        j        |         f           .# tb          $ r` |	                    d2                    |dz             tf          4                    dd2                    |dz             i          f           Y w xY wn fd|D             }d ta          |          D             }|	t	          d |D                       z
  }|r#tk          d2                    ||                    |D ]\  }}d |D             } |            }d}|s|rd ta          |          D             }tS          ||          D ]\  \  }}}
}|
r	 |
6                    ||          ||
j
        <   n# tj          $ rr}|s9tO          j(        d2                    ||
j7        |                     |||
j
        <   n-tq          d2                    |||dz   ||          |           d}Y d}~nd}~ww xY w||v r||= |r-tO          j(        d2                    | j9                             |||<   |:                                D ]6\  }}||vr-tq          d2                    |||dz   |d          |           d}7|D ]} |;                    | d           |D ]\  } }! |!j<        di ||| <   |s|r	|||fV  |V  	 ddd           n# 1 swxY w Y   |j=         _>        dS )a$  Iterate over the rows of the table

        Create an iterator that maps the information in each row to a `dict` whose keys are
        the column names of the table and whose values are the values in the corresponding
        table cells, or for virtual columns (which have no values) the valueUrl for that
        column. This includes columns not specified in the table specification.

        Note: If the resolved data filename does not exist - but there is a zip file of the form
        `fname+'.zip'`, we try to read the data from this file after unzipping.

        :param log: Logger object (default None) The object that reports parsing errors.        If none is given, parsing errors raise ValueError instead.
        :param bool with_metadata: (default False) Also yield fname and lineno
        :param fname: file-like, pathlib.Path, or str (default None)        The file to be read. Defaults to inheriting from a parent object, if one exists.
        :param strict: Flag signaling whether data is read strictly - i.e. raising `ValueError`         when invalid data is encountered - or not - i.e. only issueing a warning and returning         invalid data as `str` as provided by the undelying DSV reader.
        :return: A generator of dicts or triples (fname, lineno, dict) if with_metadata
        rc   r/  c                 H    g | ]}|                     j                  |S rL   )endswithrG  )r   nr;  s     rN   r  z#Table.iterdicts.<locals>.<listcomp>K  s.    &\&\&\QQZZPUPZE[E[&\q&\&\&\rM   r   r%  zColumn number mismatchzIncompatible table models-r   zIncompatible column titlesNr  r   rG  c                 H    g | ]}|j                             |          fS rL   r  )r   hr   s     rN   r  z#Table.iterdicts.<locals>.<listcomp>x  s/    SSSq4#3#>#>q#A#ABSSSrM   c                 $    g | ]\  }\  }}|||fS rL   rL   r   jrQ  r  s       rN   r  z#Table.iterdicts.<locals>.<listcomp>y  s&    MMMFQAq!9MMMrM   c              3   0   K   | ]\  }}}||j         V  d S rx   r  rS  s       rN   r   z"Table.iterdicts.<locals>.<genexpr>z  s0      (R(RgaAPQ(R(R(R(R(R(R(RrM   z#{0} is missing required columns {1}c                 .    i | ]\  }}}||j         ||S rL   r   rS  s       rN   r   z#Table.iterdicts.<locals>.<dictcomp>  s,    PPPWQ1qPQZPAqPPPrM   Fc                     g | ]P\  }}|d                      |dz             t                              dd                      |dz             i          fQS )r  r   rG  )r   r   r!  )r   r  r   s      rN   r  z#Table.iterdicts.<locals>.<listcomp>  sq     #4 #4 #4 !Aq "))!a%00))693C3CAE3J3J*KLLN#4 #4 #4rM   r  zInvalid column value: {} {}; {}z{0}:{1}:{2} {3}: {4}r@  Tz%Unspecified column "{0}" in table {1}r  rL   )?r!  r  r   r   r  r  r  r  r  r   r  r   r   
contextlib	ExitStackr   re   TextIOWrapperBytesIOrm   rn   r[   contentrd   r   r   existsr   r   rG  enter_contextr4  r5  rf   namelistr   r   r   r   r   r   zipr  r   rY  r   StopIterationr   r  
IndexErrorr   r   r!  r   rl  r  r   r  r   r<  r  comments	_comments)#r   r|   r?  rs   _Rowr  r  colnamesvirtualcolsrequiredcolsr  stackhandlezipfnamer<  readerr   r  rG  r^  header_colsr  cnamemissingrF  r  r   errorrT  r   r?   ekeyr  r;  s#   `                                 @rN   rC  zTable.iterdicts  s     8 ##%%4))$)44.0"cee|+#+ 	- 	-C{ ,< C&&
CL'ABBB
+++| -  ,,,!## t	"ue}} 7)Jx|CJJ77?@@7K[] ] ] U++||~~ 7$|44UZ&5HIIH(( 7$227?3x==3Q3QRR!#!1 II&\&\&\&\$--//&\&\&\]^&_``%,%5"7 "7 "7 (()DVU\)])])]^^F&\\F ~ " $VIAv! 	L+3 DD<L<T8U8UX[\bXcXc8c8c$M*BCCC),VT5E5M)N)N L LID#"%--"5"5C$'H Kc K (.I J J J)#s33 L		#q8I$)DI,>+E+Ec+J+J1+MRO 9O 9O (.J K K K$   Et	" t	" t	" t	" t	" t	" t	" t	"B " ("")122c&kkAA&A #3vt/?/G#H#HII T 0 8 T)122S[[@@  )& 1 1 R RHAuR#**E43C3KA3N+OPPPP% R R R#**%,,QU33",,fi6F6Fq1u6M6M-NOO,Q R R R R RRR TSSSFSSSMMi6L6LMMMK"S(R(R(R(R(R%R%RRG _ !F!M!MeU\!]!]^^^% 5" 5"PPPPPdff# 4 4#4 #4 %.cNN	#4 #4 #4K
 '*+s&;&; # #NKQ3 #-.1hhqh.H.HC
OO) 	- 	- 	-#) - ($E$L$LQPSP\^_$`$`!b !b !b23CJ ,$:$A$A%QRUVQVXY[\$]$](+!- !- !- !- )-	- == (! d$M G N NqRVRa b bd d d!"A$NN,, % %DAq||$299 %vq1ua9[] ] #% % % % !% $ . .CNN3---- &1 6 6MC.x5555CHH "$ "#VS00000!			k5"t	" t	" t	" t	" t	" t	" t	" t	" t	" t	" t	" t	" t	" t	" t	"j  s   F\DM76\7
N\NB-\>'Q&%\&A'S\SC\V54\5
X1	?A(X,	'\,X1	1C\\\)NN)"rI   rJ   rK   rV   rW   rX   r  re  r  r[  rn  r   r   r[   r  r   r!  r2  Iterabler   r   r   r2  r   r   r  r  r  rH  rJ  rp   rq   	GeneratorrC  rL   rM   rN   r   r     s         TWU+++NI  "D D D
 5FLd3 5 5 5 X5Tg T T T T
 IPGK.3/44 4_V\$e2C%DE4_V\#w|2C%DE4 OFLgl1B$CD4 od+	4
 t,4
 :@c3h9O4 4 4 4l     (     
 (]) ]) 
	$d*	+]) ]) ]) ]) ]) ])rM   r   c                     g }| D ]w}t          |t          t          f          st          j        d           3|                    t          |t                    rt                              |          n|           x|S )NzInvalid value for Table spec)r   r   r   r   r   r   r!  )r?   r^  r   s      rN   converter_tablesrw    s}    
C L L"tUm,, 	LM89999JJjT.B.BJur***KKKKJrM   c                      e Zd ZdZ ej        d ej        e          e          Z	d Z
ed             Zd Z	 	 ddej        eej        f         dej        e         d	ej        e         d
ej        ej        eeef                  fdZdej        ej        ef         fdZedej        eef         fd            Zdej        ej        eeeef                  fdZ ddZ!ddZ"dS )r   aM  
    A table group description is an object that describes a group of tables.

    A `TableGroup` delegates most of its responsibilities to the `Table` objects listed in its
    `tables` property. For convenience, `TableGroup` provides methods to
    - read data from all tables: :meth:`TableGroup.read`
    - write data for all tables: :meth:`TableGroup.write`

    It also provides a method to check the referential integrity of data in related tables via
    :meth:`TableGroup.check_referential_integrity`

    .. seealso:: `<https://www.w3.org/TR/tabular-metadata/#table-groups>`_
    F)rv  rS   rT   c                 \    t                               |            | j        D ]	}| |_        
d S rx   )r  r[  r  r  )r   r  s     rN   r[  zTableGroup.__attrs_post_init__  s:    %%d+++[ 	! 	!E EMM	! 	!rM   c                 F    t          |                              |           S rx   )r   to_tablegroup)r  dps     rN   from_frictionless_datapackagez(TableGroup.from_frictionless_datapackage  s    2,,S111rM   c                 H    d | j                                         D             S )z/
        Read all data of a TableGroup
        c                 X    i | ]'\  }}|t          |                                          (S rL   )r   rC  )r   tnamets      rN   r   z#TableGroup.read.<locals>.<dictcomp>  s.    RRRxuatAKKMM**RRRrM   )	tabledictr   r   s    rN   rl  zTableGroup.read  s'     SR4>;O;O;Q;QRRRRrM   rs   r  r"  r   c                     t          j        |          }|                                D ].\  }}| j        |                             ||j        ||           /|                     |           dS )a  
        Write a TableGroup's data and metadata to files.

        :param fname: Filename for the metadata file.
        :param items: Keyword arguments are used to pass iterables of rows per table, where the         table URL is specified as keyword.
        )r   r  r"  N)r   r   r   r  r  r   r  )r   rs   r  r"  r   r  rowss          rN   r  zTableGroup.write  sr     U## ;;== 	a 	aKE4N5!''5<X_'````UrM   destc           	      f   t          j        |          }| j        D ]f}t          j        t          |j                            | j                            t          |j                            |                               g|| j	        j
        z  | _	        |                     | j	                   dS )z
        Write a TableGroup's data and metadata to files relative to `dest`, adapting the `base`
        attribute.

        :param dest:
        :return:
        N)r   r   r  shutilcopyr[   r  r   r   r  rG  r  )r   r  r  s      rN   r  zTableGroup.copy  s     |D!![ 	Y 	YEKEI--di88993uy?P?PQU?V?V;W;WXXXXT[--T[!!!!!rM   rj   c                 $    d | j         D             S )Nc                     i | ]
}|j         |S rL   r  r   r  s     rN   r   z(TableGroup.tabledict.<locals>.<dictcomp>  s    555Aa555rM   r  r   s    rN   r  zTableGroup.tabledict   s    555555rM   c                 *      fd j         D             S )Nc                     g | ]L}|j         j        D ]=}|j        j        j        |j        j        j                 |j        j        ||j        f>MS rL   )r  r  r  r  r  r  r   r  )r   r  fkr   s      rN   r  z+TableGroup.foreign_keys.<locals>.<listcomp>  sv     1 1 1 1=+D1 1 &(</1r|4;<,"	$1 1 1 1rM   r  r   s   `rN   foreign_keyszTableGroup.foreign_keys  s2    1 1 1 1 [1 1 1 	1rM   c           
         	 |                                  D ]\  }}}}t          |          t          |          k    rt          d          t          ||          D ]\  }}|j                            ||          }|j                            ||          }	|r|	s#t          d                    ||                    |j        rZ|	j        rS|j        j        |	j        j        k    r9t          d                    ||j        j        ||	j        j                            Ɛd S # t          t          f$ r'}
t          d                    |
                    d }
~
ww xY w)NzFForeign key error: non-matching number of columns in source and targetrX  z.Foregin key error: missing column "{}" or "{}"z;Foregin key error: non-matching datatype "{}:{}" or "{}:{}"z0Foreign key error: missing table "{}" referenced)r  r   r   ra  r  r  r   r  r   KeyErrorAssertionError)r   r  stsctttcscoltcolscolumntcolumnrr  s              rN   validate_schemazTableGroup.validate_schema  s   	["&"3"3"5"5 [ [BBr77c"gg%%$`b b b"%b"++ 
[ 
[JD$ n77V7LLG n77V7LLG# a a(LSSTXZ^__a a a' [G,< [#,1W5E5JJJ(Y`` $g&6&;T7CSCXZ Z[ [ [
[	[ [ .) 	[ 	[ 	[OVVWXYYZZZ	[s   D#D' 'E8"EENc                 "   |t          j        d           |rw| j        D ]o}|j        j        D ]`}|D ][t          fd|j        D                       r9t          d                    fd|j        D             |j                            \ap	 | 	                                 d}n8# t          $ r+}d}t          t          |          |d	           Y d}~nd}~ww xY w|                                 }t          |d
           }t          j        |d           D ]p\  }	}
t!          |
          }
|
d         d         }d t          j        |
d           D             }d |D             }|                    |          D ]9|D ]4\  }} |          |v r|rd}|                     |                     5:t'          ||          D ]\  \  }}\  }	}t)          |          dk    }|D ]\  }}t+          j        | }|                    |d          D ]t\  }}} ||          }||rt/          |t                     r|}n|g}|D ]@}|sd|v r	||vr3t          d                    ||||j        j                  |           d}Aur|S )zT
        Strict validation does not allow for nullable foreign key columns.
        Nz\the data argument of check_referential_integrity is deprecated (its content will be ignored)c              3   F   K   | ]}                     |          d u V  d S rx   r   r   r  r  s     rN   r   z9TableGroup.check_referential_integrity.<locals>.<genexpr>-  s2      RRswws||t3RRRRRRrM   z!Foreign key column is null: {} {}c                 :    g | ]}                     |          S rL   r   r  s     rN   r  z:TableGroup.check_referential_integrity.<locals>.<listcomp>/  s#     L L L# L L LrM   TFrq  )r|   r}   c                 D    | d         j         | d         | d         j         fS )Nr   r   r   r  xs    rN   r   z8TableGroup.check_referential_integrity.<locals>.<lambda>8  s    QqT_adAaDO,T rM   )rs  c                     | d         j         S r   r  r  s    rN   r   z8TableGroup.check_referential_integrity.<locals>.<lambda><  s    1 rM   r   c                 0    g | ]\  }}|d  |D             fS )c                      g | ]\  }}}}||fS rL   rL   )r   r   childrefs       rN   r  zETableGroup.check_referential_integrity.<locals>.<listcomp>.<listcomp>?  s%    HHH/?q!UCuclHHHrM   rL   )r   rs  kgrps      rN   r  z:TableGroup.check_referential_integrity.<locals>.<listcomp>?  sF     P P P$3 HH4HHHI P P PrM   c                     | d         S )Nr   rL   r  s    rN   r   z8TableGroup.check_referential_integrity.<locals>.<lambda>@  s
    1 rM   c                 L    g | ]!\  }}t          j        | t                      f"S rL   )rA  rB  r  )r   rs  r   s      rN   r  z:TableGroup.check_referential_integrity.<locals>.<listcomp>A  s-    QQQvsA,c2CEE:QQQrM   r@  r   r>  z({0}:{1} Key `{2}` not found in table {3})r   r   r  r  r  r  r  r   r   r  r   r[   r  r)  	itertoolsgroupbyr   rC  r   ra  r   rA  rB  r   r  r   )r   r  r|   r  r  r  rD  rr  fkeysr   grpr  t_fkeysget_seenrn   r  rs  childrensingle_columnr  r  get_refrs   rF  r(  r  colrefsr  s                              @rN   check_referential_integrityz&TableGroup.check_referential_integrity"  s    M H I I I 	c[ c c-3 c cB  c cRRRRr?QRRRRR c",-P-W-W L L L L9K L L LbN`.b .b #c #c cccc
	9  """GG 	9 	9 	9GQS888888888	9 !!##u"T"TUUU  '/H/HII (	0 (	0FAss))CF1IEP P(1(9#~~(N(NP P PGQQQQQH3// ' '!) ' 'ICs3xx4''! ,&+GHHSSXX&&&&' /2'8.D.D 0 0*h!T!$SQ"* 0 0JE3&137G/43VZ/[/[ 0 0+vt!(!>$* /z&$/G/G / '-GG'-hG&- 0 0F#0 0TV^^ (!'t!3!3 ,$N$U$U(-(.(.(-	(8	%: %:
 ),!- !- !- !- +000008 s   B) )
C3!CC)FFr  )NNF)#rI   rJ   rK   rV   rW   rX   r/  r   rw  r  r[  r0  r}  rl  r   r   r[   r   r   r2  r  rt  r   r   r  r  rn  Dictr   r  ListTupler  r  r  rL   rM   rN   r   r     s         TW%d););GWXXXF! ! !
 2 2 [2S S S /4/4 \#w|"34od+ t, v|D%4E'FG	   ""glC&78 " " " " 66;sEz2 6 6 6 X61fk&,udE47O*PQ 1 1 1 1[ [ [ [(C C C C C CrM   r   c                       e Zd ZdZddedej        e         defdZe	defd	            Z
e	d
             Zeddej        eef         fd            ZddZd Zd Zd ZdS )r   zH
    Python API to read CSVW described data and convert it to JSON.
    NFr  md_urlrj  c                    g | _         d }t          j                    5 }|r(|                    t          j        d                    }d}	 t          |p|          }n2# t          j        j        $ r | 	                    |          \  }}Y nw xY wt          |                                          ddhk    | _        d|                    dd          vrt          d          d	|v r|d	         rt          |d	         t                     st          d
          t#          |          r=t$                              ||          | _        | j                            d           nt$                              ||          | _        nt#          |          r\t.                              ||          | _        |r8| j        j        rd| j        j        _        n<t5          d          | j        _        n!t.                              ||          | _        t          | j        t$                    r| j        j        n| j        g| _        | j        D ]S}|j        j        D ]D}	|	j        r;t?          j         d|	j                  s|	j        !                    d          rd |	_        ET| j        j"        | _"        d d d            n# 1 swxY w Y   |r| j         #                    |           d S d S )NTrecordF@contextr  r  rO  zInvalid or no @contextr  z-Invalid TableGroup with empty tables propertyr  rX  r  r  r   )$r   rY  rZ  r_  catch_warningsru   ro   decoderJSONDecodeErrorlocate_metadatar  r  no_metadatarn   r   r   r   r   r   r  r  r  r  r   r  r  r   r  r  r  rG  r  r  r   r  extend)
r   r  r  rj  r  rj  	no_headermdr  r  s
             rN   r   zCSVW.__init__l  s    !## '	4u N''(?t(L(L(LMMI:fm,, </ : : : $ 4 4S 9 9III:  #27799~~*e1DDD*"&&R2H2HHH !9:::2~~(| V:blD+I+I V$%TUUU#;; @'0020>>DFF**$*7777'11#B1??DFF#;; ;"^^Cb^99DF  C6> C49DFN11-4E-B-B-BDFN"__Sr_::DF+5dfj+I+IW$&--PTPVxDK ( ( ,4 ( (Cx (RYuch%?%? (38CVCVWZC[C[ (#'( !% 3DO'	4 '	4 '	4 '	4 '	4 '	4 '	4 '	4 '	4 '	4 '	4 '	4 '	4 '	4 '	4P  	$M  #####	$ 	$s6   -J=AJ=,B	J=BH%J==KKrj   c                    | j         rdS t          j        d          5 }| j        D ]C}|                    d          D ]}|                                st          j        d           D| j                            d          st          j        d           |r| j                             |           ddd           n# 1 swxY w Y   t          | j                    S )z
        Performs CSVW validation.

        .. note::

            For this to also catch problems during metadata location, the
            `CSVW` instance must be initialized with `validate=True`.
        FTr  rX  zDuplicate primary keyz"Referential integrity check failedN)
r   r  r  rC  rH  r   
tablegroupr  r  r  )r   r  r  r   s       rN   is_validzCSVW.is_valid  s0    = 	5$D111 		(Q ; ;66  A..00 ;M"9:::?>>d>KK DBCCC ($$Q'''		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( &&&&s   BCC	Cc                     t          | j        t                    r| j        n!t          d| j        j        i| j                  S )Nr   )r  r  )r   r  r   r   r  r   s    rN   r  zCSVW.tablegroup  s>    #DFJ77 Ktvv 5dkJJJ	KrM   c           	      \   d }d}| rt          |           rt          j        |           }t          t	          j        d|j                            dd                              }|j                            d          }|rc|d         dv rYt          t          |d	                                       |                     } |||           r||fS t          j        d
           t          j        t          d                              |                     }|j        dk    r|j        nd}|                    d          D ]}t          j        t          t#          |                              |                                         |                     }|j        dk    rQ	 |                                } |||           r||fc S t          j        d           # t&          j        $ r Y w xY wnk| rit+          j        t/          |           dz                                             r3t          t+          j        t/          |           dz                       |fS d| d}t          | pd          s0t+          j        |           }t/          |          |d<   |j        |d	<   ||fS )u   
        Implements metadata discovery as specified in
        `§5. Locating Metadata <https://w3c.github.io/csvw/syntax/#locating-metadata>`_
        c                     |                      d| g          D ]C}|                    d          d         |d                             d          d         k    r dS DdS )Nr  /r  TF)rn   rY  )r  r  r  s      rN   	describesz'CSVW.locate_metadata.<locals>.describes  sf    2$//     99S>>"%u););C)@)@)DDD44 E5rM   Fzheader\s*=\s*absentzcontent-typerO  describedbyr   )zapplication/csvm+jsonzapplication/ld+jsonzapplication/jsonr  z?Ignoring linked metadata because it does not reference the dataz/.well-known/csvm   z&{+url}-metadata.json
csv-metadata.json
)r  z8Ignoring metadata because it does not reference the dataz-metadata.jsonr  )r  r  r  )r   rm   headr  r  r  headersrn   linksru   r   r   r   r   status_codetextrY  r   r  ro   r  r   r   r[   r^  rG  )	r  r  r  r^  descr  locslineps	            rN   r  zCSVW.locate_metadata  s   	 	 	 	 $	V6#;; $	V -$$CRY'=s{~_a?b?bccddI9==//D eV )X X Xd4;//77<<==9R%% ey=(M"cddd
 ,t$788@@EEFFC"#55388;dD

4(( 	 	l4D(9(9(@(@S(@(I(I#J#J#R#RSV#W#WXX?c)) XXZZ$9R-- 1#%y=000 &`aaaa/    *	  	V|CHH'7788??AA VSXX8H-H I IJJIUU3
 
 ciR   	  S!!Aq66CLCJI~s   '#G"G""G43G4c                 f    t          j                    } j        j        rMt	           j        t
                    s3|                    t          j         j        j        d                      fd j	        D             |d<   |r+t          t          j        d |d         D                        S |S )zk
        Implements algorithm described in `<https://w3c.github.io/csvw/csv2json/#standard-mode>`_
        T)flatten_listc                 H    g | ]}|j         	                    |          S rL   )r  _table_to_json)r   r  r   s     rN   r  z CSVW.to_json.<locals>.<listcomp>   sF     ] ] ]+0uG[]&&] ] ]rM   r  c                 2    g | ]}d  |d         D             S )c                 *    g | ]}|d          d         S )r  r   rL   )r   r`   s     rN   r  z+CSVW.to_json.<locals>.<listcomp>.<listcomp>  s!    "G"G"G1[>!#4"G"G"GrM   r  rL   r  s     rN   r  z CSVW.to_json.<locals>.<listcomp>  s+    !_!_!_A"G"Gah"G"G"G!_!_!_rM   )rp   rq   r  r  r   r   updater   to_jsonr  r   r  chain)r   minimalr^  s   `  rN   r  zCSVW.to_json  s     %'' 6 	Oz$&%'@'@ 	OJJv~df&9MMMNNN] ] ] ]48K] ] ]H 	b!_!_QTU]Q^!_!_!_`b b b 
rM   c                     t          j                    }t          j                            j                            |d<   dj        v rj        d         |d<   j        rt          j	        j                  |d<   |
                    t          j	        j                             t          j        d j        j        D                                                       D ]6}|                    d          |_        |                    d          |_        7 fdt%                              d	d
          d          D             }j        rd j        D             |d<   ||d<   |S )Nr  r   r   r  c                      g | ]}|j         |fS rL   r  r+  s     rN   r  z'CSVW._table_to_json.<locals>.<listcomp>  s    '_'_'_cS(9'_'_'_rM   r  r  c           	      P    g | ]"\  }\  }}}                     |||          #S rL   )_row_to_json)r   rownumr   rowsourcenumr  colsr   r  s        rN   r  z'CSVW._table_to_json.<locals>.<listcomp>  sJ     
 
 
..L# eT3EE
 
 
rM   TF)r?  r  r   startc                     g | ]
}|d          S )r   rL   r  s     rN   r  z'CSVW._table_to_json.<locals>.<listcomp>  s    "A"A"AA1Q4"A"A"ArM   zrdfs:commentr  )rp   rq   r[   r  r   r   r  r  r   r  r  r  r  r  r   r  r  r  r  rC  re  )r   r  r^  r  r  r  s   ``   @rN   r  zCSVW._table_to_json  s   %''**5:6677E
5>!!-CJ; 	7!>%+66CL 	

6>%"455666&'_'_UEVE^'_'_'_``;;== 	3 	3C!kk-88CO;;z22CLL
 
 
 
 
 
2;d5AA3L 3L 3L
 
 

 ? 	B"A"A"A"A"ACE

rM   c                    t          j                    }d                    |j                            |j                  |          |d<   ||d<   |j        j        rOd fd|j        j        D             D             |d<   t          |d                   dk    r|d         d         |d<   | 	                    |||          |d	<   |S )
Nz	{}#row={}r  r  c                     g | ]}||S rL   rL   r  s     rN   r  z%CSVW._row_to_json.<locals>.<listcomp>(  s5     Y Y YVWYY Y YrM   c                 :    g | ]}                     |          S rL   r   )r   rG  r  s     rN   r  z%CSVW._row_to_json.<locals>.<listcomp>)  s#    RRRdCGGDMMRRRrM   r   r   r   r  )
rp   rq   r   r  r   r   r  r  r   
_describes)r   r  r  r  r  r  r^  s      `   rN   r  zCSVW._row_to_json#  s    %'' ''	(9(9%*(E(E|TTE
H& 	1Y YRRRRe6G6QRRRY Y YCM3x=!!Q&& #Ha 0H  ??5$VDDK
rM   c                 |   g }|j                             d          }|r@|                    t          j        d d|                    |||                               t          |                                d          D ]\  }\  }}	|                    |          }
|
r|
j	        s|
j
        r.|
r|
                                n|                                }|r|	|v s|	dk    s|	|
r|
j        r|	g k    rv|                    t          j                            ||
||j         j        s| j        sd                    |          n||	|                     |j         j        D ]E}
|
j
        r<|                    t          j                            ||
||
j        d |                     Ft          j        |          S )	Nr  r   )r
  )aboutrn  r   r   r  rO  r  )r  r  r   r   Tripler  r  r   rn   r  r  r  r  from_colr  r  r   r  group_triples)r   r  r  r  r  triplesr  r  r   r?   r  r.  s               rN   r  zCSVW._describes2  s   $,,Z88 	]NN6=U%,,xSY,2Z2Z\ \ \ ] ] ] #399;;a888 	 	IAv1((1++C * ck  *-F3##%%%%2D2D2F2FD dqBww19 4= ] 4=/0BwwNN6=11)1S:>:JS	  ###QR      $, 	b 	bC{ bv}55eS#szSWY_``aaa#G,,,rM   r   rx   r  )rI   rJ   rK   rV   r[   r   r2  r  r   rn  r  r  staticmethodr  r   r  r  r  r  r  rL   rM   rN   r   r   h  s        ,$ ,$C ,$)= ,$PT ,$ ,$ ,$ ,$\ '$ ' ' ' X'. K K XK = =V\$*%= = = = \=~   "  6  - - - - -rM   r   )r`   ra   )rv   r  )RrV   re   r  ro   r  r	  r   r   r4  rA  r   rY   r  rY  rp   urllib.parser   r   r   language_tagsr   rW   rm   uritemplaterO  r   	datatypesr
   dsvr   BaseDialectr   r   frictionlessr   r   r   r2  __all__r  rY  r  r   rG   r   r  ri   r   r   r   ru   r   r   r   r   r   r   r   rq   r   r   r   r  r5  r   rq  rs  ru  r  r   r  r  r   r  r  r  r  r  r   rw  r   r   rL   rM   rN   <module>r     sp    
			 				                         6 6 6 6 6 6 6 6 6 6                               S S S S S S S S S S % % % % % %      
&((  /
(/	8/ 3/ 
.	/
 	
%/ (/ (/ "/ 	
2/ 	
*/ &/ ./ -/ 
&/ 
'/  (!/" 	
-#/ /$ 2%/& 4'/( -)/* 
&+/, 	
(-/. 	
$//0 *1/2 	
3/4 
&5/6 
+7/8 	
-9/: (;/< 
'=/> 
(?/@ 	
'A/B 	
<C/D &E/ /F 32(&*	+/&.101]/ / /
`O^ 577_ ` 
	 	 	 	 	 	 	 	 ')) N N N N Nk N N N46 6 6 6
Gv|D$J/ G G G G iz ! ! ! !   
! 
! 
! 
! 
!+) 
! 
! 
!) ) ),!* !* !* !* !* !* !* !*H9 9 9 92) 2) 2) 2) 2)k- 2) 2) 2)j  . . .b A5 A5 A5 A5 A5 A5 A5 A5H8 8 8 g, g, g, g, g, g, g, g,T     3 3 3 3 3/ 3 3 3l   ] ] ] ] ][ ] ] ]@L L L # # # # # # # #        .   L L L L L[ L L L^	 	 	C C C h h h h h h h hV X) X) X) X) X)I X) X) X)v   c c c c c c c cLi- i- i- i- i- i- i- i- i- i-rM   