a
    1$eAo                     @   sp  d 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	m
Z
 ddlmZmZmZ ddlmZmZ ddlmZmZmZ dd	lmZmZ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&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z. e! Z/e  Z0e1e2Z3G dd dZ4dd e5 D Z6e67d dd Z8dd Z9G dd de4Z:dS )z5Collections provide file-like access to feature data.    )	ExitStackN)OrderedDict)compatvfs)IteratorItemsIteratorKeysIterator)SessionWritingSession)buffer_to_virtual_fileremove_virtual_fileGEOMETRY_TYPES)DriverErrorDriverSupportErrorGDALVersionErrorSchemaErrorUnsupportedGeometryTypeErrorUnsupportedOperation)FieldSkipLogFilter)CRS)get_gdal_release_nameget_gdal_version_tuple)env_ctx_if_needed)FionaDeprecationWarning)driver_from_extensionsupported_driversdriver_mode_mingdal+_driver_converts_field_type_silently_to_str_driver_supports_field)Pathvsi_path
parse_pathc                   @   sJ  e Zd ZdZdGddZdd Zd	d
 Zedd Zedd Z	edd Z
edd ZdHddZdIddZdJddZdKddZedd ZeZdd Zdd  Zd!d" Zd#d$ ZeZd%d& Zd'd( ZeZd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Z ed7d8 Z!d9d: Z"d;d< Z#d=d> Z$ed?d@ Z%dAdB Z&dCdD Z'dEdF Z(dS )L
CollectionzA file-like interface to features of a vector dataset

    Python text file objects are iterators over lines of a file. Fiona
    Collections are similar iterators (not lists!) over features
    represented as GeoJSON-like mappings.
    rNFc                 K   s"  d| _ t|ttfs td| t|tr2|dvr>td| |rXt|tsXtd| |rrt|dsrtd| |rt|tjttf st|drt	|j
std	| |rt|tstd
| |rt|tstd| |rt|ttfstd| |r&t|trt|s&td| |	rDt|	tsDtd|	 |dur`|dur`td|dkr||du r|t|}|t| v rt t| | k rdtttt| | }tdj|||t dd| _d| _d| _d| _d| _d| _d| _d| _|
| _ || _!|| _"t#|| _$|| _%d| _&d| _ |t| v rt t| | k rdtttt| | }tdj|||t d|rt'|||	| _(t)| j(}nt)|}t'|| _(|dkr&|rt|tstd|dkr|durtdd| _*n"|p t+j(,t+j(-|j(d | _*n2|dv r8d| _*n |pTt+j(,t+j(-|d | _*|| _.| j.dkrL|dkrxd}|std|s|t/vrtd| | j.t/| vrtd| j. || _|st0d d!|v r|1 }t2|d! |d!< |}n
t2 |d!< d"|vrd|d"< || _| 3  |s2|rLt4|p>|j
|d#| _|| _|j5|d$ || _6zV| j.d%krt7 | _| jj8| fi | n(| j.d&v rt9 | _| jj8| fi | W n t:y   d| _ Y n0 | jdur| ;  | j.d&v rt<| j=| j>| _?t@ | _AtB | _&d'| _ dS )(ae  The required ``path`` is the absolute or relative path to
        a file, such as '/data/test_uk.shp'. In ``mode`` 'r', data can
        be read only. In ``mode`` 'a', data can be appended to a file.
        In ``mode`` 'w', data overwrites the existing contents of
        a file.

        In ``mode`` 'w', an OGR ``driver`` name and a ``schema`` are
        required. A Proj4 ``crs`` string is recommended. If both ``crs``
        and ``crs_wkt`` keyword arguments are passed, the latter will
        trump the former.

        In 'w' mode, kwargs will be mapped to OGR layer creation
        options.

        Tzinvalid path: %r)r#   wazinvalid mode: %rzinvalid driver: %rgetzinvalid schema: %rto_wktzinvalid crs: %rzinvalid crs_wkt: %rzinvalid encoding: %rzinvalid name: %rzinvalid vsi: %rzinvalid archive: %rNz8Cannot specify both 'ignore_fields' and 'include_fields'r$   .zo{driver} driver requires at least GDAL {min_gdal_version} for mode '{mode}', Fiona was compiled against: {gdal})drivermodemin_gdal_versionZgdalr   z(in 'w' mode, layer names must be stringsGeoJSONz'the GeoJSON format does not have layersZ
OgrGeoJSON)r   NZ	ShapefileESRI Shapefilez	no driverunsupported driver: %runsupported mode: %rz	no schema
propertiesgeometry)version)encodingr#   r%   r$   F)C_closed
isinstancestrr   	TypeErrorhasattrr   Z
DICT_TYPESr   callabler'   intr   Z	valid_vsi
ValueErrorr   r   r   joinlistmapr   formatr   sessioniterator_len_bounds_driver_schema_crs_crs_wktenabled_driversinclude_fieldsignore_fieldsboolignore_geometry_allow_unsupported_drivers_envr    pathr!   nameosbasenamesplitextr*   r   r   copyr   _check_schema_driver_supportZfrom_user_inputupdater3   r	   startr
   OSErrorguard_driver_mode_get_valid_geom_typesschemar)   Z_valid_geom_typesr   field_skip_log_filterr   )selfrP   r*   r)   r\   crsr3   layervsiarchiverI   crs_wktrK   rM   rJ   Zwkt_versionZallow_unsupported_driverskwargsr+   Zthis_schema re   L/var/www/html/django/DPS/env/lib/python3.9/site-packages/fiona/collection.py__init__3   s   $








$
 




zCollection.__init__c                 C   s4   d | jrdpd| jd t| j | jtt| S )Nz%<{} Collection '{}', mode '{}' at {}>closedopen:r@   rh   rP   r7   rQ   r*   hexidr^   re   re   rf   __repr__  s    
zCollection.__repr__c                 C   sD   | j s@| j }|tvr$td| | jt| vr@td| j d S )Nr.   r/   )rN   rA   
get_driverr   r   r*   )r^   r)   re   re   rf   rZ     s    
zCollection.guard_driver_modec                 C   s(   | j s"| jdv r"| jr"| j | _ | j S )z*Returns the name of the proper OGR driver.r%   r#   )rE   r*   rA   rp   rn   re   re   rf   r)     s    zCollection.driverc                 C   s(   | j s"| jdv r"| jr"| j | _ | j S )a  Returns a mapping describing the data schema.

        The mapping has 'geometry' and 'properties' items. The former is a
        string such as 'Point' and the latter is an ordered mapping that
        follows the order of fields in the data file.
        rq   )rF   r*   rA   Z
get_schemarn   re   re   rf   r\     s    zCollection.schemac                 C   s"   | j du r| jr| j | _ | j S )z8The coordinate reference system (CRS) of the Collection.N)rG   rA   Zget_crsrn   re   re   rf   r_   (  s    zCollection.crsc                 C   s"   | j du r| jr| j | _ | j S )zReturns a WKT string.N)rH   rA   Zget_crs_wktrn   re   re   rf   rc   /  s    zCollection.crs_wktc                 C   s0   t jdk rtdt| jr,| jj|dS dS )a  Returns a dict containing copies of the dataset or layers's
        tags. Tags are pairs of key and value strings. Tags belong to
        namespaces.  The standard namespaces are: default (None) and
        'IMAGE_STRUCTURE'.  Applications can create their own additional
        namespaces.

        Parameters
        ----------
        ns: str, optional
            Can be used to select a namespace other than the default.

        Returns
        -------
        dict
           z5tags requires GDAL 2+, fiona was compiled against: {}nsN)_GDAL_VERSION_TUPLEmajorr   r@   _GDAL_RELEASE_NAMErA   tags)r^   rt   re   re   rf   rx   6  s    
zCollection.tagsc                 C   s2   t jdk rtdt| jr.| jj||dS dS )a  Returns tag item value

        Parameters
        ----------
        key: str
            The key for the metadata item to fetch.
        ns: str, optional
            Used to select a namespace other than the default.

        Returns
        -------
        str
        rr   z=get_tag_item requires GDAL 2+, fiona was compiled against: {})keyrt   N)ru   rv   r   r@   rw   rA   get_tag_item)r^   ry   rt   re   re   rf   rz   O  s    
zCollection.get_tag_itemc                 C   s<   t jdk rtdtt| jts,td| jj	||dS )a  Writes a dict containing the dataset or layers's tags.
        Tags are pairs of key and value strings. Tags belong to
        namespaces.  The standard namespaces are: default (None) and
        'IMAGE_STRUCTURE'.  Applications can create their own additional
        namespaces.

        Parameters
        ----------
        tags: dict
            The dict of metadata items to set.
        ns: str, optional
            Used to select a namespace other than the default.

        Returns
        -------
        int
        rr   z<update_tags requires GDAL 2+, fiona was compiled against: {}z-Unable to update tags as not in writing mode.rs   )
ru   rv   r   r@   rw   r6   rA   r
   r   update_tags)r^   rx   rt   re   re   rf   r{   f  s    
zCollection.update_tagsc                 C   s>   t jdk rtdtt| jts,td| jj	|||dS )aW  Updates the tag item value

        Parameters
        ----------
        key: str
            The key for the metadata item to set.
        tag: str
            The value of the metadata item to set.
        ns: str, optional
            Used to select a namespace other than the default.

        Returns
        -------
        int
        rr   z@update_tag_item requires GDAL 2+, fiona was compiled against: {}z,Unable to update tag as not in writing mode.)ry   tagrt   )
ru   rv   r   r@   rw   r6   rA   r
   r   update_tag_item)r^   ry   r|   rt   re   re   rf   r}     s    
zCollection.update_tag_itemc                 C   s   | j | j| j| jdS )zRReturns a mapping with the driver, schema, crs, and additional
        properties.r)   r\   r_   rc   r~   rn   re   re   rf   meta  s
    zCollection.metac           
      O   s   | j rtdn| jdkr"td|rBt| }|j}|j}|j}nd } }}|d}|d}|rr|rrtd|d}	t	| ||||||	| _
| j
S )	az  Returns an iterator over records, but filtered by a test for
        spatial intersection with the provided ``bbox``, a (minx, miny,
        maxx, maxy) tuple or a geometry ``mask``. An attribute filter can
        be set using an SQL ``where`` clause, which uses the `OGR SQL dialect
        <https://gdal.org/user/ogr_sql_dialect.html#where>`__.

        Positional arguments ``stop`` or ``start, stop[, step]`` allows
        iteration to skip over items or stop at a specific item.

        Note: spatial filtering using ``mask`` may be inaccurate and returning
        all features overlapping the envelope of ``mask``.

        "I/O operation on closed collectionr#   collection not open for readingNbboxmask%mask and bbox can not be set togetherwhere)rh   r<   r*   rY   slicerX   stopstepr&   r   rB   
r^   argskwdssrX   r   r   r   r   r   re   re   rf   filter  s"    




zCollection.filterc           
      O   s   | j rtdn| jdkr"td|rBt| }|j}|j}|j}nd } }}|d}|d}|rr|rrtd|d}	t	| ||||||	| _
| j
S )	a  Returns an iterator over FID, record pairs, optionally
        filtered by a test for spatial intersection with the provided
        ``bbox``, a (minx, miny, maxx, maxy) tuple or a geometry
        ``mask``. An attribute filter can be set using an SQL ``where``
        clause, which uses the `OGR SQL dialect
        <https://gdal.org/user/ogr_sql_dialect.html#where>`__.

        Positional arguments ``stop`` or ``start, stop[, step]`` allows
        iteration to skip over items or stop at a specific item.

        Note: spatial filtering using ``mask`` may be inaccurate and returning
        all features overlapping the envelope of ``mask``.

        r   r#   r   Nr   r   r   r   )rh   r<   r*   rY   r   rX   r   r   r&   r   rB   r   re   re   rf   items  s"    




zCollection.itemsc           
      O   s   | j rtdn| jdkr"td|rBt| }|j}|j}|j}nd } }}|d}|d}|rr|rrtd|d}	t	| ||||||	| _
| j
S )	a  Returns an iterator over FIDs, optionally
        filtered by a test for spatial intersection with the provided
        ``bbox``, a (minx, miny, maxx, maxy) tuple or a geometry
        ``mask``. An attribute filter can be set using an SQL ``where``
        clause, which uses the `OGR SQL dialect
        <https://gdal.org/user/ogr_sql_dialect.html#where>`__.

        Positional arguments ``stop`` or ``start, stop[, step]`` allows
        iteration to skip over items or stop at a specific item.

        Note: spatial filtering using ``mask`` may be inaccurate and returning
        all features overlapping the envelope of ``mask``.
        r   r#   r   Nr   r   r   r   )rh   r<   r*   rY   r   rX   r   r   r&   r   rB   r   re   re   rf   keys  s"    




zCollection.keysc                 C   s   | j |S N)rA   Zhas_feature)r^   Zfidre   re   rf   __contains__  s    zCollection.__contains__c                 C   s   |   S )z!Returns an iterator over records.)r   rn   re   re   rf   __iter__  s    zCollection.__iter__c                 C   s(   t jdtdd | jst|  t| jS )z"Returns next record from iterator.zdCollection.__next__() is buggy and will be removed in Fiona 2.0. Switch to `next(iter(collection))`.rr   )
stacklevel)warningswarnr   rB   iternextrn   re   re   rf   __next__  s    zCollection.__next__c                 C   s   | j |S r   )rA   __getitem__r^   itemre   re   rf   r   "  s    zCollection.__getitem__c                 C   s   | j |S r   )rA   r&   r   re   re   rf   r&   %  s    zCollection.getc                 C   sD   | j rtd| jdvr td| j||  | j | _d| _dS )z,Stages multiple records for writing to disk.r   r4   zcollection not open for writingN)	rh   r<   r*   rY   rA   Z	writerecs
get_lengthrC   rD   )r^   recordsre   re   rf   writerecords(  s    
zCollection.writerecordsc                 C   s   |  |g dS )zStages a record for writing to disk.
        
        Note: Each call of this method will start and commit a
        unique transaction with the data source.
        N)r   r^   recordre   re   rf   write2  s    zCollection.writec                 C   s,   t |d  t | jd  ko*| |S )zyCompares the record to the collection's schema.

        Returns ``True`` if the record matches, else ``False``.
        r0   )setr   r\   validate_record_geometryr   re   re   rf   validate_record:  s
    zCollection.validate_recordc                 C   sb   | j dkrBd|d d vrB|d d d| jd ddkS |d d | jd dkS dS )zCompares the record's geometry to the collection's schema.

        Returns ``True`` if the record matches, else ``False``.
        r-   Pointr1   typeMulti3D N)r)   lstripr\   r   re   re   rf   r   E  s    
z#Collection.validate_record_geometryc                 C   s8   | j dkr | jd ur | j | _ | j dk r2td| j S )Nr   zLayer does not support counting)rC   rA   r   r8   rn   re   re   rf   __len__X  s
    
zCollection.__len__c                 C   s&   | j du r | jdur | j | _ | j S )z!Returns (minx, miny, maxx, maxy).N)rD   rA   Z
get_extentrn   re   re   rf   boundsa  s    zCollection.boundsc                 C   s   t j}| jd  D ]}|dd }t| j|sl| jdkrV|dk rV|dkrVtdqtdj| j|d	q|d
v rt	| j|r| j
dkr|dk r|dv rtd| qtdj| j|d	 qdS )z\Check support for the schema against the driver

        See GH#572 for discussion.
        r0   rj   r   ZGPKGrr   datetimez5GDAL 1.x GPKG driver does not support datetime fieldsz-{driver} does not support {field_type} fields)r)   
field_type>   datetimer   r,   >   r   r   zPGeoJSON driver in GDAL 1.x silently converts {} to string in non-standard formatz8{driver} driver silently converts {field_type} to stringN)ru   rv   rF   valuessplitr   r)   r   r@   r   rE   r   r   )r^   Zgdal_version_majorfieldr   re   re   rf   rV   h  sP    

z'Collection._check_schema_driver_supportc                 C   s@   | j dur<| j |  | j  }|| jkr.|p2| j| _d| _dS )zFlush the buffer.N)rA   syncr   rC   rD   )r^   Znew_lenre   re   rf   flush  s
    

zCollection.flushc                 C   sv   | j sr| jdurV| j rV| jdv r,|   td | j  td d| _d| _| j	rl| j	
  d| _	d| _ dS )z@In append or write mode, flushes data to disk, then ends access.Nr4   zFlushed bufferzStopped sessionT)r5   rA   Zisactiver*   r   logdebugr   rB   rO   closern   re   re   rf   r     s    




zCollection.closec                 C   s   | j S )z6``False`` if data can be accessed, otherwise ``True``.)r5   rn   re   re   rf   rh     s    zCollection.closedc                 C   s$   | j t  td| j | S Nzfiona.ogrext)rO   enter_contextr   logging	getLogger	addFilterr]   rn   re   re   rf   	__enter__  s    zCollection.__enter__c                 C   s   t d| j |   d S r   )r   r   removeFilterr]   r   )r^   r   value	tracebackre   re   rf   __exit__  s    zCollection.__exit__c                 C   s   | j s|   d S r   )r5   r   rn   re   re   rf   __del__  s    zCollection.__del__)r#   NNNNNNNNNNFNNF)N)N)N)N))__name__
__module____qualname____doc__rg   ro   rZ   propertyr)   r\   r_   rc   rx   rz   r{   r}   r   Zprofiler   r   r   r   r   r   r   r   r   r&   r   r   r   r   r   r   rV   r   r   rh   r   r   r   re   re   re   rf   r"   *   sx   
               
 S









!"!
	
0
r"   c                 C   s    h | ]}d |vr|dkr|qS )r   Nonere   ).0	geom_typere   re   rf   	<setcomp>  s   r   r   c                 C   s   | d }t |ts|du r |f}t }|D ]H}t|d}|dksL|dkrX|t q*|tvrht||| q*|dkrd|vrt|D ]}|	ds|d|  q|S )	z6Returns a set of geometry types the schema will acceptr1   Nr   UnknownAnyr-   r   r   )
r6   r7   r   r   rW   ALL_GEOMETRY_TYPESr   addr>   
startswith)r\   r)   Zschema_geom_typeZvalid_typesr   re   re   rf   r[     s     
r[   c                 C   s   | dd  drdS dS dS )zZDetect compression type of bytesbuf.

    ZIP only. TODO: add others relevant to GDAL/OGR.N   s   PKzip )r   )bytesbufre   re   rf   get_filetype  s    r   c                       s4   e Zd ZdZ fddZ fddZdd Z  ZS )BytesCollectionzrBytesCollection takes a buffer of bytes and maps that to
    a virtual file that can then be opened by fiona.
    c                    s   d| _ t|tstd|| _t| j}d}|dkr:d}n|ddkrLd}t| j|d	| _t	 j
| jfd
|i| d| _ dS )zTakes buffer of bytes whose contents is something we'd like
        to open with Fiona and maps it to a virtual file.

        Tzinput buffer must be bytesr   r   z.zipr)   r,   z.json)extra   FN)r5   r6   bytesr<   r   r   r&   r   virtual_filesuperrg   )r^   r   r   Zfiletyper   	__class__re   rf   rg     s    

zBytesCollection.__init__c                    s*   t    | jr&t| j d| _d| _dS )z3Removes the virtual file associated with the class.N)r   r   r   r   r   rn   r   re   rf   r     s
    

zBytesCollection.closec                 C   s4   d | jrdpd| jd t| j | jtt| S )Nz*<{} BytesCollection '{}', mode '{}' at {}>rh   ri   rj   rk   rn   re   re   rf   ro     s    
zBytesCollection.__repr__)r   r   r   r   rg   r   ro   __classcell__re   re   r   rf   r     s   r   );r   
contextlibr   r   rR   r   collectionsr   Zfionar   r   Zfiona.ogrextr   r   r   r	   r
   r   r   r   Zfiona.errorsr   r   r   r   r   r   Zfiona.logutilsr   Z	fiona.crsr   Z
fiona._envr   r   Z	fiona.envr   r   Zfiona.drvsupportr   r   r   r   r   Z
fiona.pathr   r    r!   ru   rw   r   r   r   r"   r   r   r   r[   r   r   re   re   re   rf   <module>   sB    
      

