o
    hY                     @  s  U d dl m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
 d dlmZ d dlmZ d dlmZmZmZmZmZmZmZmZ d dlmZ erad dlZd dlmZ d d	lmZ d
ZedZ 	ddddZ!	ddddZ"i Z#de$d< dddZ%dd"d#Z&dd+d,Z'		-ddd4d5Z(dd9d:Z)dd=d>Z*ddBdCZ+ddFdGZ,	-	-dddMdNZ-ddPdQZ.ddSdTZ/ddVdWZ0ddYdZZ1dd\d]Z2			^	_dddfdgZ3ddjdkZ4ddodpZ5ej6ddrdsZ7	 		_ddd{d|Z8dd~dZ9ej6ddddZ:dd Z;dd Z<dS )    )annotationsN)partial)md5)version)IOTYPE_CHECKINGAnyCallableIterableIteratorSequenceTypeVar)urlsplit)	TypeGuard)AbstractFileSystemi  P Turlpathstrinherit_storage_optionsdict[str, Any] | Nonereturndict[str, Any]c                 C  sZ  t d| st d| du rd| dS t| }|jpd}|jr)d|j|jg}n|j}|dkrEt d|}|rE| \}}| d| }|d	v rN|| dS ||d}|jr|j	d
dd 	ddd |d< |dv rv|d |d  |d< n|d |d< |j
r|j
|d< |jr|j|d< |jr|j|d< |jr|j|d< |jr|j|d< |rt|| |S )a  Infer storage options from URL path and merge it with existing storage
    options.

    Parameters
    ----------
    urlpath: str or unicode
        Either local absolute file path or URL (hdfs://namenode:8020/file.csv)
    inherit_storage_options: dict (optional)
        Its contents will get merged with the inferred information from the
        given path

    Returns
    -------
    Storage options dict.

    Examples
    --------
    >>> infer_storage_options('/mnt/datasets/test.csv')  # doctest: +SKIP
    {"protocol": "file", "path", "/mnt/datasets/test.csv"}
    >>> infer_storage_options(
    ...     'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1',
    ...     inherit_storage_options={'extra': 'value'},
    ... )  # doctest: +SKIP
    {"protocol": "hdfs", "username": "username", "password": "pwd",
    "host": "node", "port": 123, "path": "/mnt/datasets/test.csv",
    "url_query": "q=1", "extra": "value"}
    z^[a-zA-Z]:[\\/]z^[a-zA-Z0-9]+://Nfile)protocolpath#z^/([a-zA-Z])[:|]([\\/].*)$:)httphttps@   r   host)s3s3agcsgsr   portusernamepassword	url_queryurl_fragment)rematchr   schemefragmentjoinr   groupsnetlocrsplitr'   r(   r)   queryupdate_storage_options)r   r   parsed_pathr   r   windows_pathdriveoptions r:   `/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/fsspec/utils.pyinfer_storage_options&   sF   
 



"





r<   r9   	inheritedNonec                 C  sV   |si }t | t |@ }|r$|D ]}| |||kr#td| q| | d S )Nz9Collision between inferred and specified storage option:
)setgetKeyErrorupdate)r9   r=   
collisions	collisionr:   r:   r;   r5   {   s   r5   zdict[str, str]compressionsfilename
str | Nonec                 C  s.   t j| d d }|tv rt| S dS )a  Infer compression, if available, from filename.

    Infer a named compression type, if registered and available, from filename
    extension. This includes builtin (gz, bz2, zip) compressions, as well as
    optional compressions. See fsspec.compression.register_compression.
    r!   .N)osr   splitextstriplowerrE   )rF   	extensionr:   r:   r;   infer_compression   s   rN   max_intfloatCallable[[int], str]c                   s.   | d7 } t tt|  d	 fdd}|S )
a  Returns a function that receives a single integer
    and returns it as a string padded by enough zero characters
    to align with maximum possible integer

    >>> name_f = build_name_function(57)

    >>> name_f(7)
    '07'
    >>> name_f(31)
    '31'
    >>> build_name_function(1000)(42)
    '0042'
    >>> build_name_function(999)(42)
    '042'
    >>> build_name_function(0)(0)
    '0'
    g:0yE>iintr   r   c                   s   t |  S N)r   zfill)rR   
pad_lengthr:   r;   name_function   s   z*build_name_function.<locals>.name_functionN)rR   rS   r   r   )rS   mathceillog10)rO   rX   r:   rV   r;   build_name_function   s   r\   r   	IO[bytes]	delimiterbytes	blocksizerS   boolc              	   C  s   |   dkrdS d}	 | |}|sdS |r|| n|}z(||v r:||}| |   t||  t|  W dS t||k rCW dS W n ttfyO   Y nw |t| d }q)a  Seek current file to file start, file end, or byte after delimiter seq.

    Seeks file to next chunk delimiter, where chunks are defined on file start,
    a delimiting sequence, and file end. Use file.tell() to see location afterwards.
    Note that file start is a valid split, so must be at offset > 0 to seek for
    delimiter.

    Parameters
    ----------
    file: a file
    delimiter: bytes
        a delimiter like ``b'\n'`` or message sentinel, matching file .read() type
    blocksize: int
        Number of bytes to read from the file at once.


    Returns
    -------
    Returns True if a delimiter was found, False if at file start or end.

    r   FNT)tellreadindexseeklenOSError
ValueError)r   r^   r`   lastcurrentfullrR   r:   r:   r;   seek_delimiter   s*   

"rl   Ffoffsetlength
int | Nonebytes | Nonesplit_beforec           
      C  s   |rJ|  | t| |d}|du r|  S |  }||| 8 }|  ||  t| |d}|  }|r:|r:|t|8 }|rD|rD|t|8 }|}|| }|  | |dusUJ | |}	|	S )a  Read a block of bytes from a file

    Parameters
    ----------
    f: File
        Open file
    offset: int
        Byte offset to start read
    length: int
        Number of bytes to read, read through end of file if None
    delimiter: bytes (optional)
        Ensure reading starts and stops at delimiter bytestring
    split_before: bool (optional)
        Start/stop read *before* delimiter bytestring.


    If using the ``delimiter=`` keyword argument we ensure that the read
    starts and stops at delimiter boundaries that follow the locations
    ``offset`` and ``offset + length``.  If ``offset`` is zero then we
    start at zero, regardless of delimiter.  The bytestring returned WILL
    include the terminating delimiter string.

    Examples
    --------

    >>> from io import BytesIO  # doctest: +SKIP
    >>> f = BytesIO(b'Alice, 100\nBob, 200\nCharlie, 300')  # doctest: +SKIP
    >>> read_block(f, 0, 13)  # doctest: +SKIP
    b'Alice, 100\nBo'

    >>> read_block(f, 0, 13, delimiter=b'\n')  # doctest: +SKIP
    b'Alice, 100\nBob, 200\n'

    >>> read_block(f, 10, 10, delimiter=b'\n')  # doctest: +SKIP
    b'Bob, 200\nCharlie, 300'
    i   N)re   rl   rc   rb   rf   )
rm   rn   ro   r^   rr   found_start_delimstartfound_end_delimendbr:   r:   r;   
read_block   s(   +


rx   argsr   kwargsc                  O  sV   |r| |f7 } zt t|  }W | S  ty*   t t|  dd}Y | S w )zDeterministic token

    (modified from dask.base)

    >>> tokenize([1, 2, '3'])
    '9d71491b50023b06fc76928e6eddb952'

    >>> tokenize('Hello') == tokenize('Hello')
    True
    F)usedforsecurity)r   r   encoderh   	hexdigest)ry   rz   hr:   r:   r;   tokenize4  s   
r   filepath%str | os.PathLike[str] | pathlib.Pathc                 C  s4   t | tr| S t| dr|  S t| dr| jS | S )a6  Attempt to convert a path-like object to a string.

    Parameters
    ----------
    filepath: object to be converted

    Returns
    -------
    filepath_str: maybe a string version of the object

    Notes
    -----
    Objects supporting the fspath protocol are coerced according to its
    __fspath__ method.

    For backwards compatibility with older Python version, pathlib.Path
    objects are specially coerced.

    Any other object is passed through unchanged, which includes bytes,
    strings, buffers, or anything else that's not even path-like.
    
__fspath__r   )
isinstancer   hasattrr   r   )r   r:   r:   r;   stringify_pathI  s   


r   clsCallable[..., T]Sequence[Any]c                 C  s   | |i |}|   |S rT   )_determine_worker)r   ry   rz   instr:   r:   r;   make_instancei  s   r   pathsIterable[str]c                   sp   dd | D t dd D }d}t|D ] t fddD }|s( nq |7  dd d  S )	z;For a list of paths, find the shortest prefix common to allc                 S  s   g | ]}| d qS /)split.0pr:   r:   r;   
<listcomp>s  s    z!common_prefix.<locals>.<listcomp>c                 s      | ]}t |V  qd S rT   )rf   r   r:   r:   r;   	<genexpr>t  s    z common_prefix.<locals>.<genexpr>r   c                 3  s$    | ]}|  d    kV  qdS )r   Nr:   r   rR   partsr:   r;   r   w  s   " r   N)minrangeallr0   )r   lmaxrv   r:   r   r;   common_prefixq  s   r   	list[str]path2str | list[str]existsflattenc                   s   t trGd|rfdd| D S t|  |r% ddd   s;tdd | D r;fdd| D S  fd	d| D S t| tksQJ S )
a  In bulk file operations, construct a new file tree from a list of files

    Parameters
    ----------
    paths: list of str
        The input file tree
    path2: str or list of str
        Root to construct the new list in. If this is already a list of str, we just
        assert it has the right number of elements.
    exists: bool (optional)
        For a str destination, it is already exists (and is a dir), files should
        end up inside.
    flatten: bool (optional)
        Whether to flatten the input directory tree structure so that the output files
        are in the same directory.

    Returns
    -------
    list of str
    r   c                   s$   g | ]}d   |d d fqS )r   r!   )r0   r   r   r   r:   r;   r     s   $ zother_paths.<locals>.<listcomp>r    r   c                 s  s    | ]	}| d  V  qdS )r   N)
startswithr   sr:   r:   r;   r     s    zother_paths.<locals>.<genexpr>c                   s   g | ]	}d   |gqS r   )r0   r   r   r:   r;   r         c                   s   g | ]	}|  d qS )r    replacer   cpr   r:   r;   r     r   )r   r   rstripr   r3   r   rf   )r   r   r   r   r:   r   r;   other_paths~  s   

r   objc                 C  s
   t | tS rT   )r   BaseExceptionr   r:   r:   r;   is_exception     
r   TypeGuard[IO[bytes]]c                   s   t  fdddD S )Nc                 3  s    | ]}t  |V  qd S rT   )r   )r   attrrm   r:   r;   r     s    zisfilelike.<locals>.<genexpr>)rc   closerb   )r   r   r:   r   r;   
isfilelike  s   r   urlc                 C  s0   t | } tjd| dd}t|dkr|d S dS )Nz(\:\:|\://)r    )maxsplitr   r   )r   r,   r   rf   )r   r   r:   r:   r;   get_protocol  s
   r   r   c              	   C  s<   ddl m} zt|t| ddW S  ttfy   Y dS w )z*Can the given URL be used with open_local?r   )get_filesystem_class
local_fileF)fsspecr   getattrr   rh   ImportError)r   r   r:   r:   r;   can_be_local  s   r   namec              	   C  sl   | t jv rt j|  }t|dr|jS zt| W S    Y zddl}|| }|jW S  ttfy5   Y dS w )a  For given package name, try to find the version without importing it

    Import and package.__version__ is still the backup here, so an import
    *might* happen.

    Returns either the version string, or None if the package
    or the version was not readily  found.
    __version__r   N)	sysmodulesr   r   r   	importlibimport_moduler   AttributeError)r   modr   r:   r:   r;   "get_package_version_without_import  s   
	



r   DEBUGTloggerlogging.Logger | Nonelogger_namelevelclearlogging.Loggerc                 C  sh   | d u r|d u rt d| pt|} t }td}|| |r(| j  | | | 	| | S )Nz+Provide either logger object or logger namezD%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s)
rh   logging	getLoggerStreamHandler	FormattersetFormatterhandlersr   
addHandlersetLevel)r   r   r   r   handle	formatterr:   r:   r;   setup_logging  s   



r   fsr   c                 C  s
   | | S rT   )unstrip_protocol)r   r   r:   r:   r;   _unstrip_protocol  r   r   origin_namemethodsCallable[[type[T]], type[T]]c                   s"   dfddd fd
d}|S )zqMirror attributes and methods from the given
    origin_name attribute of the instance to the
    decorated classmethodr   selfr   r   c                   s   t | }t || S rT   )r   )r   r   origin)r   r:   r;   origin_getter   s   

z"mirror_from.<locals>.origin_getterr   type[T]c                   s(    D ]}t |}t| |t| q| S rT   )r   setattrproperty)r   r   wrapped_method)r   r   r:   r;   wrapper  s   
zmirror_from.<locals>.wrapperN)r   r   r   r   r   r   )r   r   r   r   r:   )r   r   r   r:   )r   r   r   r;   mirror_from  s   r   Iterator[T]c                 c  s    | V  d S rT   r:   r   r:   r:   r;   nullcontext  s   
r   startslist[int] | intendsmax_gap	max_blocksort&tuple[list[str], list[int], list[int]]c           
      C  s  t | tstt |ts|gt|  }t |ts|gt|  }t|t| ks/t|t| kr1tt|dkr<| ||fS dd |D }|rWdd ttt| || D \} }}| r| dd }|dd }|dd }tdt| D ]Q}	| |	 | |	d  kr|d du rqr| |	 | |	d  ks||	 |d  |ks|dur||	 |d  |kr|| |	  |||	  |||	  qr||	 |d< qr|||fS | ||fS )a}  Merge adjacent byte-offset ranges when the inter-range
    gap is <= `max_gap`, and when the merged byte range does not
    exceed `max_block` (if specified). By default, this function
    will re-order the input paths and byte ranges to ensure sorted
    order. If the user can guarantee that the inputs are already
    sorted, passing `sort=False` will skip the re-ordering.
    r    c                 S  s   g | ]}|pd qS )r   r:   r   r:   r:   r;   r   /  s    z'merge_offset_ranges.<locals>.<listcomp>c                 s  r   rT   )list)r   vr:   r:   r;   r   2  s
    
z&merge_offset_ranges.<locals>.<genexpr>Nr!   )	r   r   	TypeErrorrf   rh   zipsortedr   append)
r   r   r   r   r   r   	new_paths
new_startsnew_endsrR   r:   r:   r;   merge_offset_ranges  sF   


 

	 

r   filelikec              	   C  s.   |   }z| ddW | | S | | w )z+Find length of any open read-mode file-liker      )rb   re   )r   posr:   r:   r;   	file_sizeX  s   r  wbmodec                 c  s    t jtj| tj| d d\}}zt||}|V  W d   n1 s(w   Y  W n" tyP   t	t
 t| W d    1 sJw   Y   w t||  dS )z
    A context manager that opens a temporary file next to `path` and, on exit,
    replaces `path` with the temporary file, thereby updating `path`
    atomically.
    -)dirprefixN)tempfilemkstemprI   r   dirnamebasenameopenr   
contextlibsuppressFileNotFoundErrorunlinkr   )r   r  fdfnfpr:   r:   r;   atomic_writea  s$   

r  c                 C  s  g }|j }dt| }}||k rZ| | }|d }|dkr+|r%|d |ur)|| n+|dkr5|| n!|dkrO|}||k rJ| | dkrJ|d }||k rX| | dkrX|d }||k rp| | dkrp|d }||k rp| | dksb||kry|d	 n| || }	d
|	vr|	dd}	ng }
| | dkr|d n|d }	 | d
||}|dk rn|
 | ||  |d }|d }q| || }|r|
 | n|
d  d
7  < tt|
d ddD ]*}|
|d  d |
| d kr|
|d  d d |
| dd   |
|d < |
|= qd
dd |
D }	tdd|	}	|d }|	s!|d n5|	dkr+|d n+|	d dkr;d|	dd   }	n|	d dv rFd|	 }	|d|	 d n|t| ||k s||ksaJ |S )Nr   r    *r!   ?[!]z\[r  \\\r   T   c                 s  s$    | ]}| d d ddV  qdS )r  r  r  z\-Nr   r   r:   r:   r;   r     s    
z_translate.<locals>.<genexpr>z([&~|])z\\\1z(?!)rH   ^)r  r  )	r   rf   r   findr   r0   r,   subescape)patSTARQUESTION_MARKresaddrR   ncjstuffchunkskchunkr:   r:   r;   
_translatev  s~   


,



Ar-  c                 C  sD  t jjrt jjt jj }nt jj}dttj|}t|dkr&d| dn|}d| d}| d}| | }d| d}d	}g }	t	|| }
t|
d }t
|
D ]C\}}|d
krg|	||k rc|n| qS|dkrw|	||k rs|n| qSd|v rtd|r|	t|| d
| ||k r|	| qSd|	}d| dS )zBTranslate a pathname with shell wildcards to a regular expression. r    r  r  z[^+z(?:.+z)?z.*r  z**z:Invalid pattern: '**' can only be an entire path componentz(?s:z)\Z)rI   r   altsepsepr0   mapr,   r   rf   r   	enumerater   rh   extendr-  )r!  sepsescaped_sepsany_sepnot_sepone_last_segmentone_segmentany_segmentsany_last_segmentsresultsr   last_part_idxidxpartr$  r:   r:   r;   glob_translate  s>   


rA  rT   )r   r   r   r   r   r   )r9   r   r=   r   r   r>   )rF   r   r   rG   )rO   rP   r   rQ   )r   r]   r^   r_   r`   rS   r   ra   )NF)rm   r]   rn   rS   ro   rp   r^   rq   rr   ra   r   r_   )ry   r   rz   r   r   r   )r   r   r   r   )r   r   ry   r   rz   r   r   r   )r   r   r   r   )FF)
r   r   r   r   r   ra   r   ra   r   r   )r   r   r   ra   )rm   r   r   r   )r   r   r   r   )r   r   r   ra   )r   r   r   rG   )NNr   T)
r   r   r   rG   r   r   r   ra   r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   )r   NT)r   r   r   r   r   r   r   rS   r   rp   r   ra   r   r   )r   r]   r   rS   )r  )r   r   r  r   )=
__future__r   r  r   rY   rI   r,   r   r  	functoolsr   hashlibr   importlib.metadatar   typingr   r   r   r	   r
   r   r   r   urllib.parser   pathlibtyping_extensionsr   fsspec.specr   DEFAULT_BLOCK_SIZEr   r<   r5   rE   __annotations__rN   r\   rl   rx   r   r   r   r   r   r   r   r   r   r   r   r   r   contextmanagerr   r   r  r  r-  rA  r:   r:   r:   r;   <module>   sx    (
V


5
J

 

-






F	J