o
    QDiz                     @  sR  d dl mZ d dlZd dlZd dlmZmZmZmZm	Z	m
Z
mZmZ d dlZd dlmZ ddlmZmZmZmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddl m Z  ddl!m"Z" ddl#m$Z$ ddl%m%Z% ddl&m'Z' ddl(m)Z) erddlm*Z* ddl+m,Z, ddl-m.Z. ddl%m/Z/ ej0dddG dd dee'dZ1dS )    )annotationsN)TYPE_CHECKINGAnyClassVarDictListOptionalUnioncast)Self   )errorsfieldshelperssettings)	Checklist)Detector)ControlDialect)FrictionlessException)Metadata)platform)Report)Schema)system   )Factory)ResourceStats)types)Error)Package)LoaderTF)kw_onlyreprc                      s  e Zd ZU dZejdddZded< 	 dZded< 	 dZ	d	ed
< 	 ejdddZ
ded< 	 ded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< 	 ejedZded< 	 ejedZded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< 	 ejdddZded< 	 dZded < 	 dZded!< 	 ejedZd"ed#< 	 dZded$< 	 dZded%< 	 dZded&< 	 dZd'ed(< 	 dZd'ed)< 	 dZd'ed*< 	 eje d+d,Z!d-ed.< 	 eje"d/d,Z#d0ed1< 	 ejdd2dZ$ded3< 	 eje%dZ&d4ed5< 	 dZ'd6ed7< 	 ejdd8Z(d9ed:< 	 dZ)d;ed<< 	  fd=d>Z*d?d@ Z+dAdB Z,e-ddDdEZ.e-ddFdGZ/e-ddHdIZ0e-ddKdLZ1e-ddMdNZ2e-ddOdPZ3e-ddQdRZ4e-ddTdUZ5e5j6ddWdUZ5e-ddYdZZ7e7j6dd[dZZ7e-dd\d]Z8e8j6dd^d]Z8e-dd`daZ9e-ddcddZ:e-ddfdgZ;e-ddhdiZ<ddkdlZ=dmdn Z>e?ddod fdudvZ@ddwddydzZAddwdd{d|ZBddwdd}d~ZCdddddZDdd ZEe?	ddddddddZFdddddZ	dddddeGjHddddZIdʇ fddZJdZKeLjMZNddgi ddeGjOdddeGjPddddidddidddidddidddddiddiddiddddddddiddiddiddddddiddddgidddidddid ddid!ddid#dddidd$ddid%ddiddiddiddiddidddgidddgiddZQe?dddZRe?dddZSe?d͇ fddZTe?d͇ fddZUe?d· fddZV fddZW  ZXS )Resourceu  Resource representation.

    This class is one of the cornerstones of of Frictionless framework.
    It loads a data source, and allows you to stream its parsed contents.
    At the same time, it's a metadata class data description.

    ```python
    with Resource("data/table.csv") as resource:
        resource.header == ["id", "name"]
        resource.read_rows() == [
            {'id': 1, 'name': 'english'},
            {'id': 2, 'name': '中国人'},
        ]
    ```

    NF)defaultr"   Optional[Any]sourcezOptional[Control]controlbool	packagify name)r%   aliasOptional[str]_namezClassVar[str]typetitledescriptionhomepageprofile)factoryzList[Dict[str, Any]]licensessourcespathdataschemeformatdatatype	_datatype	mediatypecompression	List[str]
extrapaths	innerpathencodinghashOptional[int]bytesr   rowsdialect)r5   r-   Union[Dialect, str]_dialectschemaUnion[Schema, str]_schemabasepath	_basepathr   detectorzOptional[Package]package)initr   statszClassVar[bool]tabularc                   s   | j pd| _| jp
d| _t | _tt| dd }t|t	r || _d | _
d | _t|  | d | d | d | d | d | d | d	 t   d S )
Nr+   r<   r,   r:   r;   r?   r>   rH   rS   )r/   r,   r=   r<   r   rS   getattrr0   
isinstancestr_Resource__loader_Resource__bufferr   detect_resourceadd_definedsuper__attrs_post_init__)selfr<   	__class__ W/var/www/Datamplify/venv/lib/python3.10/site-packages/frictionless/resource/resource.pyr]      s"   








zResource.__attrs_post_init__c                 C  s   | j r|   | S N)closedopenr^   ra   ra   rb   	__enter__  s   zResource.__enter__c                 C  s   |    d S rc   )close)r^   r0   value	tracebackra   ra   rb   __exit__  s   zResource.__exit__returnc                 C  s*   g }| j dur|| j  || j |S )zAll paths of the resourceN)r8   appendextendrA   )r^   pathsra   ra   rb   ro     s
   
zResource.pathsc                 C  s*   g }| j D ]}|tj|| jd q|S )z Normalized paths of the resourcerN   )ro   rm   r   normalize_pathrN   )r^   	normpathsr8   ra   ra   rb   rr     s   
zResource.normpathsc                 C  s   | j rtj| j | jdS dS )z3Normalized path of the resource or raise if not setrp   N)r8   r   rq   rN   rf   ra   ra   rb   normpath  s   zResource.normpathrW   c                 C  sH   | j durdS | jr| j dS | jr| j d| j S | jr"| jS dS )zStringified resource locationNz<memory>z (multipart)z -> r+   )r9   rA   r8   rB   rf   ra   ra   rb   place#  s   
zResource.placec                 C  s
   | j duS )z"Whether resource is not path basedN)r9   rf   ra   ra   rb   memory0  s   
zResource.memoryc                 C  s   t | jp	| jp	dS )zWhether resource is remoter+   )r   is_remote_pathrN   r8   rf   ra   ra   rb   remote5  s   zResource.remotec                 C  s   | j  ot| jS )zWhether resource is multipart)ru   r)   rA   rf   ra   ra   rb   	multipart:  s   zResource.multipartr   c                 C  &   t | jtrtj| j| jd| _| jS Nrp   )rV   rJ   rW   r   from_descriptorrN   rf   ra   ra   rb   rH   ?     zResource.dialectri   c                 C  
   || _ d S rc   )rJ   r^   ri   ra   ra   rb   rH   E     
r   c                 C  ry   rz   )rV   rM   rW   r   r{   rN   rf   ra   ra   rb   rK   I  r|   zResource.schemac                 C  r}   rc   )rM   r~   ra   ra   rb   rK   O  r   c                 C  s   | j r| j S | jr| jjS dS )zr
        A basepath of the resource
        The normpath of the resource is joined `basepath` and `/path`
        N)rO   rQ   rN   rf   ra   ra   rb   rN   S  s
   zResource.basepathc                 C  r}   rc   )rO   r~   ra   ra   rb   rN   ^  r   types.IBufferc                 C  s   | j du r	td| j S )zFile's bytes used as a sample

        These buffer bytes are used to infer characteristics of the
        source file (e.g. encoding, ...).
        N"resource is not open or non binary)rY   r   rf   ra   ra   rb   bufferd  s   
zResource.buffertypes.IByteStreamc                 C  2   | j rtd| jst| | _| j  | jjS )zaByte stream in form of a generator

        Yields:
            gen<bytes>?: byte stream
        r   )rd   r   rX   r   create_loaderre   byte_streamrf   ra   ra   rb   r   o     
zResource.byte_streamtypes.ITextStreamc                 C  r   )zaText stream in form of a generator

        Yields:
            gen<str[]>?: text stream
        z#resource is not open or non textual)rd   r   rX   r   r   re   text_streamrf   ra   ra   rb   r   }  r   zResource.text_streamc                 C  s
   | j du S )zRWhether the table is closed

        Returns:
            bool: if closed
        N)rX   rf   ra   ra   rb   rd     s   
zResource.closedNonec                 C  s   | j r| j   d| _ dS dS )z+Close the resource as "filelike.close" doesN)rX   rh   rf   ra   ra   rb   rh     s   

zResource.closec                 C  sH   |    zt| | _| j  | jj| _W | S  ty#   |     w )z#Open the resource as "io.open" does)rh   r   r   rX   re   r   rY   	Exceptionrf   ra   ra   rb   re     s   
zResource.openr<   
descriptorUnion[types.IDescriptor, str]optionsr   r   c                  s@   |rt j|d} | j|fi |}||_|S t j|fi |S )Nr   )r   select_resource_classr{   r<   r\   )clsr   r<   r   r^   r_   ra   rb   r{     s   zResource.from_descriptorsizer   c                C  s   | j rdS t| , |s)d}	 tt| j }||7 }|snq|W  d   S | j|W  d   S 1 s9w   Y  dS )zURead bytes into memory

        Returns:
            any[][]: resource bytes
            TN)ru   r   ensure_openr
   rF   r   read1)r^   r   r   chunkra   ra   rb   
read_bytes  s   
$zResource.read_bytesc                C  sD   | j rdS t|  | j|W  d   S 1 sw   Y  dS )zORead text into memory

        Returns:
            str: resource text
        r+   N)ru   r   r   r   read)r^   r   ra   ra   rb   	read_text  s
   
$zResource.read_textc                C  sX   | j dur| j S t|  | j|d}t|}|W  d   S 1 s%w   Y  dS )zORead data into memory

        Returns:
            any: resource data
        Nr   )r9   r   r   r   jsonloads)r^   r   textr9   ra   ra   rb   	read_data  s   

$zResource.read_datarS   c                C  s   | j sd}ttj|d| ' |s	 W d   dS t| j d| jj | _	| jj
| _
W d   dS 1 s9w   Y  dS )zfInfer metadata

        Parameters:
            stats: stream file completely and infer stats
        z0Resource.infer cannot be used on a open resourcenoteNsha256:)rd   r   r   ResourceErrorr   pass_throughr   rS   sha256rD   rF   )r^   rS   r   ra   ra   rb   infer  s   "zResource.inferc                 C  s$   d| j _d| j _d| j_d| j_dS )zDereference underlaying metadata

        If some of underlaying metadata is provided as a string
        it will replace it by the metadata object
        N)rH   metadata_descriptor_pathmetadata_descriptor_initialrK   rf   ra   ra   rb   dereference  s   zResource.dereference)r,   r0   rS   r   c          
      K  s   t jj}t jj}t|f|pd|dkd|}|dv r5t||r5| }	|	j|d |dur3|		|S |	S |j|d |dkrV||gd}	|	j|d |durT|		|S |	S |dkr]|j
S |d	krd|jS |S )
a  Describe the given source as a resource

        Parameters:
            source: data source
            name: resoucrce name
            type: data type: "package", "resource", "dialect", or "schema"
            stats: if `True` infer resource's stats
            **options: Resource constructor options

        Returns:
            Metadata: metadata describing this data source

        r+   rQ   )r,   r*   )rQ   Nr   N)	resourcesrH   rK   )r   frictionlessr    frictionless_resourcesPackageResourcer$   rV   read_metadatar   get_resourcerH   rK   )
r   r'   r,   r0   rS   r   r    r   resourcerQ   ra   ra   rb   describe  s8   

zResource.describe)r,   List[Resource]c                C  s   | gS )zmList dataset resources

        Parameters:
            name: limit to one resource (if applicable)

        ra   )r^   r,   ra   ra   rb   listK  s   zResource.list)r,   on_rowparallel
limit_rowslimit_errors	checklistOptional[Checklist]r   !Optional[types.ICallbackFunction]r   r   r   intr   c                C  s  d}t  }g }	g }
g }|pt }|| }z| jdd W n ty; } ztj| |j|	 dW  Y d}~S d}~ww | j
rRt | j
\}}|dvrRd}|| | jr}z|   W n! ty| } z|   tj| |j|	 dW  Y d}~S d}~ww |  t|D ]\}}| D ]}|jdkr||= ||r|
| qqt| tjjs| j
dus| jdurt | j nd	}| j}		 |d
7 }zt| j}W n  ty } z|
|j W Y d}~qd}~w ty   Y nSw |D ]}| |D ]}||r|
| qq|r|| |r ||kr d| }|| d}n|r=t!|
|kr=|
d| }
d| }|| d}nq|sZ|D ]}|" D ]}||rV|
| qIqCW d   n	1 sew   Y  tj| |j|	|
|dS )a  Validate resource

        Parameters:
            checklist: a Checklist object
            name: limit validation to one resource (if applicable)
            on_row: callbacke for every row
            paraller: allow parallel validation (multiprocessing)
            limit_rows: limit amount of rows to this number
            limit_errors: limit amount of errors to this number

        Returns:
            Report: validation report

        FT)validate)timer   Nmd5r   z1hash is ignored; supported algorithms: md5/sha256zcheck-errorr   r   zreached row limit: zreached error limit: )r   labelsr   warnings)#r   Timerr   connectto_descriptorr   r   from_validation_taskr   	to_errorsrD   parse_resource_hash_v1rm   rd   re   rh   	enumeratevalidate_startr0   matchrV   r   r   TableResourcerF   r   r   r   next
row_streamerrorStopIterationvalidate_rowlenvalidate_end)r^   r   r,   r   r   r   r   partialtimerr   r   r   checks	exception	algorithm_warningindexcheckr   	row_countrowra   ra   rb   r   V  s   











(
AzResource.validatec                   s$   t  jd| j| j| j| jd|S )zCreate a copy from the resource)r9   rN   rP   rQ   Nra   )r\   to_copyr9   rN   rP   rQ   )r^   r   r_   ra   rb   r     s   zResource.to_copyr   objectstring)r0   patternarray)r,   r8   r1   )r0   
properties)r0   items)r1   r8   email)r0   iteminteger)rD   rF   r   rG   rH   rK   )r0   requiredr   c                 C  s
   t |S rc   )r   r   )r   r0   ra   ra   rb   metadata_select_class  r   zResource.metadata_select_classc                 C  s   |dkrt S |dkrtS d S )NrH   rK   )r   r   )r   r,   ra   ra   rb   metadata_select_property_class  s
   z'Resource.metadata_select_property_classtypes.IDescriptorc                   s  t  | |dd }|d}|d}|s$|d u r$|r$|d| |d}|r>t|tr>|d |d< |dd  |d< |dd }t|trX|rXt|d trX|d |d< |d	d }|rl|d
i  ||d
 d	< |dd }|d
d }|r|r|dd }	|	r|	||< d}
|
d7 }
t	|
t
 |dd }	|	rt|	\}}	|dv r|d |d
i  |	|d
 |< |d
d }|rt|tr|dd }|dd }|rd| |d< n|r||d< dD ]}||}|r|||< q|d}|dkr|d d}
|
d7 }
t	|
t
 |dd }|r|dkrd|d< |dd }|rB|di  |d | d}
|
d7 }
t	|
t
 d S d S )Nurlr8   r9   r   r   rA   profilesr4   rF   rS   hashingrD   zBResource "stats.hash" is deprecated in favor of "stats.sha256/md5"z.(it will be removed in the next major version)r   r   r   r   )rF   r   rG   r?   noz>Resource "compression=no" is deprecated in favor not set valuetabular-data-resourcetabler0   layoutrH   z5Resource "layout" is deprecated in favor of "dialect")r\   metadata_transformpopget
setdefaultrV   r   rW   r   warnUserWarningr   r   dictupdate)r   r   r   r8   r9   r   rF   r   rS   rD   r   algor   r   r,   ri   r?   r4   r   r_   ra   rb   r   &  s   








zResource.metadata_transformc                 #  s$   t t |}|r|E d H  d S tjsMg d}|D ]1}||}t|t r)|n|g}|D ]}|rKt|trKt	|sKt
jd| ddV    d S q.q|d}|d}	|d u rh|	d u rhd}
t
j|
dV  |d ury|	d uryd}
t
j|
dV  |d	g D ]}|ds|d
sd| }
t
j|
dV  qdD ]0}||g D ]'}|drtjddd}||d\}}
|
rd| d}
t
j|
dV  qq|d}|r|dvrtj||| jdE d H  |d}|dkr|sd}
t
j|
dV  dD ]}||v rd| d| d}
t
j|
dV  qd S )N)r8   rA   r4   rH   rK   zpath "z" is not safer   r8   r9   z2one of the properties "path" or "data" is requiredz2properties "path" and "data" is mutually exclusiver6   r,   z#license requires "path" or "name": )contributorsr7   r   )r,   r;   z
property "z[].email" is not valid "email"r4   )zdata-resourcer   )r4   error_classrK   r   z?profile "tabular-data-resource" requires "schema" to be present)missingValues"z" should be set as "schema.)r   r\   metadata_validater   trustedr   rV   rW   r   is_safe_pathr   r   r   StringField	read_cellr   metadata_Error)r   r   metadata_errorskeyskeyri   r   r   r8   r9   r   r,   fieldr   r4   rK   r_   ra   rb   r   |  sr   






	

zResource.metadata_validatec                   s   t  jd|dd|S )NT)r   with_basepathra   )r\   metadata_import)r   r   r   r_   ra   rb   r    s   zResource.metadata_importc           
        s   t   }|d}ttttttf}|d urt	||sg |d< t
jdkrE|d}|dd }|rEg |d< |r>|d | |d | t
jdkr||dd }|r||d}|d}|d}	|d urld	| |d
< |d urt||d
< |	d ur||	|d< |S )Nr9   v1r8   rA   rS   r   r   rF   r   rD   )r\   metadata_exportr   rW   r)   r   floatr   r   rV   r   	standardsr   rm   rn   )
r^   r   r9   r   r8   rA   rS   r   r   rF   r_   ra   rb   r    s4   







zResource.metadata_export)rl   r@   )rl   r.   )rl   rW   )rl   r)   )rl   r   )ri   rI   )rl   r   )ri   rL   )ri   r.   )rl   r   )rl   r   )rl   r   )rl   r   )r   r   r<   r.   r   r   rl   r   )r   rE   rl   rF   )r   rE   rl   rW   )r   rE   rl   r   )rS   r)   rl   r   rc   )r'   r&   r,   r.   r0   r.   rS   r)   r   r   rl   r   )r,   r.   rl   r   )r   r   r,   r.   r   r   r   r)   r   rE   r   r   rl   r   )r   r   rl   r   )r0   r.   )r,   rW   )r   r   )r   r   r   r   )Y__name__
__module____qualname____doc__attrsr	  r'   __annotations__r(   r*   r/   r1   r2   r3   r4   r   r6   r7   r8   r9   r:   r;   r=   r>   r?   rA   rB   rC   rD   rF   r   rG   r   rJ   r   rM   rO   r   rP   rQ   rS   rT   r]   rg   rk   propertyro   rr   rs   rt   ru   rw   rx   rH   setterrK   rN   r   r   r   rd   rh   re   classmethodr{   r   r   r   r   r   r   r   DEFAULT_LIMIT_ERRORSr   r   metadata_typer   r   r  NAME_PATTERNTYPE_PATTERNmetadata_profiler   r   r   r   r  r  __classcell__ra   ra   r_   rb   r$      s  
 


>  !"#$%&

2UCr$   )	metaclass)2
__future__r   r   r   typingr   r   r   r   r   r   r	   r
   r  typing_extensionsr   r+   r   r   r   r   r   r   rP   r   rH   r   r   r   r   metadatar   r   reportr   rK   r   r   r5   r   rS   r   r   r   r   rQ   r    r!   definer$   ra   ra   ra   rb   <module>   s2    (