
    "hV                     r   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mZm	Z	m
Z
mZmZ ddlmZ ddlmZmZ ddlmZmZmZmZ  ej.                  d      Z G d	 d
      Z G d de      Z	 	 	 	 	 	 	 	 	 	 ddZd Zd Z	 	 	 	 	 	 ddZddZ d Z!d Z"d Z#d Z$	 	 	 	 	 	 ddZ%d Z& G d de jN                        Z(y)    N)	has_magic   )	BaseCache
BlockCache
BytesCache	MMapCacheReadAheadCachecaches)compr)
filesystemget_filesystem_class)_unstrip_protocolbuild_name_functioninfer_compressionstringify_pathfsspecc                   V    e Zd ZdZ	 	 	 	 	 ddZd Zd Zd Zd Ze	d        Z
d	 Zd
 Zy)OpenFileaF  
    File-like object to be used in a context

    Can layer (buffered) text-mode and compression over any file-system, which
    are typically binary-only.

    These instances are safe to serialize, as the low-level file object
    is not created until invoked using ``with``.

    Parameters
    ----------
    fs: FileSystem
        The file system to use for opening the file. Should be a subclass or duck-type
        with ``fsspec.spec.AbstractFileSystem``
    path: str
        Location to open
    mode: str like 'rb', optional
        Mode of the opened file
    compression: str or None, optional
        Compression to apply
    encoding: str or None, optional
        The encoding to use if opened in text mode.
    errors: str or None, optional
        How to handle encoding errors if opened in text mode.
    newline: None or str
        Passed to TextIOWrapper in text mode, how to handle line endings.
    autoopen: bool
        If True, calls open() immediately. Mostly used by pickle
    pos: int
        If given and autoopen is True, seek to this location immediately
    Nc                     || _         || _        || _        t        ||      | _        || _        || _        || _        g | _        y N)	fspathmodeget_compressioncompressionencodingerrorsnewlinefobjects)selfr   r   r   r   r   r   r   s           H/var/www/html/sandstorm/venv/lib/python3.12/site-packages/fsspec/core.py__init__zOpenFile.__init__=   sD     		*4=     c                     t         | j                  | j                  | j                  | j                  | j
                  | j                  | j                  ffS r   )r   r   r   r   r   r   r   r   r    s    r!   
__reduce__zOpenFile.__reduce__P   sG    				  
 	
r#   c                 "    d| j                    dS )Nz<OpenFile 'z'>)r   r%   s    r!   __repr__zOpenFile.__repr__^   s    TYYKr**r#   c                    | j                   j                  dd      j                  dd      dz   }| j                  j                  | j                  |      }|g| _        | j                  ;t        | j                     } |||d         }| j
                  j                  |       d| j                   vrHt        || j                  | j                  | j                        }| j
                  j                  |       | j
                  d   S )Nt b)r   r   )r   r   r   )r   replacer   openr   r   r   r   appendPickleableTextIOWrapperr   r   r   )r    r   fcompresss       r!   	__enter__zOpenFile.__enter__a   s    yy  b)11#r:S@GGLLL.'T--.Ha)AMM  #dii'DMM$++t||A MM  #}}R  r#   c                 $    | j                          y r   )close)r    argss     r!   __exit__zOpenFile.__exit__v   s    

r#   c                 B    t        | j                  | j                        S r   )r   r   r   r%   s    r!   	full_namezOpenFile.full_namey   s     DGG44r#   c                 "    | j                         S )a  Materialise this as a real open file without context

        The OpenFile object should be explicitly closed to avoid enclosed file
        instances persisting. You must, therefore, keep a reference to the OpenFile
        during the life of the file-like it generates.
        )r4   r%   s    r!   r/   zOpenFile.open}   s     ~~r#   c                     t        | j                        D ]<  }d| j                  vr|j                  s|j	                          |j                          > | j                  j                          y)z#Close all encapsulated file objectsrN)reversedr   r   closedflushr6   clear)r    r2   s     r!   r6   zOpenFile.close   sP    $--( 	A$))#AHH	GGI	 	r#   )rbNNNN)__name__
__module____qualname____doc__r"   r&   r(   r4   r8   propertyr:   r/   r6    r#   r!   r   r      sP    H &
+!* 5 5 r#   r   c                   F     e Zd ZdZddd fd
Zd Zd Z fdZd	 Z xZ	S )
	OpenFilesa  List of OpenFile instances

    Can be used in a single context, which opens and closes all of the
    contained files. Normal list access to get the elements works as
    normal.

    A special case is made for caching filesystems - the files will
    be down/uploaded together at the start or end of the context, and
    this may happen concurrently, if the target filesystem supports it.
    rB   Nr   r   c                H    || _         || _        g | _        t        |   |  y r   )r   r   filessuperr"   )r    r   r   r7   	__class__s       r!   r"   zOpenFiles.__init__   s%    	
$r#   c                 :   | j                   t        d      | j                   }	 t        |d      r"|j                  |       | _        | j                  S t        |d      r|j                   |j                   }nnU| D cg c]  }|j                          c}S c c}w )NzContext has already been used	open_manyr   )r   
ValueErrorhasattrrQ   rM   r4   )r    r   ss      r!   r4   zOpenFiles.__enter__   s    77?<==WWr;'\\$/
zz!r4 RUU%6UU  (,,!,,,s   >Bc                    | j                   }| D cg c]  } |j                  |  c} d| j                  vrP	 t        |d      r|j	                  | j
                         y t        |d      r|j                   |j                   }ny Oy c c}w )Nr=   rQ   r   )r   r8   r   rS   commit_manyrM   )r    r7   r   rT   s       r!   r8   zOpenFiles.__exit__   s~    WW$()qT	)dii2{+NN4::.2t$):B    	*s   B	c                     t         |   |      }t        |t              r"t	        || j
                  | j                        S |S )NrK   )rN   __getitem__
isinstanceslicerJ   r   r   )r    itemoutrO   s      r!   rX   zOpenFiles.__getitem__   s8    g!$'dE"StyyTWW==
r#   c                      dt        |        dS )Nz	<List of z OpenFile instances>)lenr%   s    r!   r(   zOpenFiles.__repr__   s    3t9+%9::r#   )
rC   rD   rE   rF   r"   r4   r8   rX   r(   __classcell__rO   s   @r!   rJ   rJ      s(    	 $(D  - ;r#   rJ   c                 \   t        | ||||||
      \  }}}|j                  dk(  r|	|_        nEd|vrA|	r?|D ch c]  }|j                  |       }}|D cg c]  }|j	                  |d       c} t        |D cg c]  }t        |||||||       c}||      S c c}w c c}w c c}w )av
  Given a path or paths, return a list of ``OpenFile`` objects.

    For writing, a str path must contain the "*" character, which will be filled
    in by increasing numbers, e.g., "part*" ->  "part1", "part2" if num=2.

    For either reading or writing, can instead provide explicit list of paths.

    Parameters
    ----------
    urlpath: string or list
        Absolute or relative filepath(s). Prefix with a protocol like ``s3://``
        to read from alternative filesystems. To read from multiple files you
        can pass a globstring or a list of paths, with the caveat that they
        must all have the same protocol.
    mode: 'rb', 'wt', etc.
    compression: string or None
        If given, open file using compression codec. Can either be a compression
        name (a key in ``fsspec.compression.compr``) or "infer" to guess the
        compression from the filename suffix.
    encoding: str
        For text mode only
    errors: None or str
        Passed to TextIOWrapper in text mode
    name_function: function or None
        if opening a set of files for writing, those files do not yet exist,
        so we need to generate their names by formatting the urlpath for
        each sequence number
    num: int [1]
        if writing mode, number of files we expect to create (passed to
        name+function)
    protocol: str or None
        If given, overrides the protocol found in the URL.
    newline: bytes or None
        Used for line terminator in text mode. If None, uses system default;
        if blank, uses no translation.
    auto_mkdir: bool (True)
        If in write mode, this will ensure the target directory exists before
        writing, by calling ``fs.mkdirs(exist_ok=True)``.
    expand: bool
    **kwargs: dict
        Extra options that make sense to a particular storage connection, e.g.
        host, port, username, password, etc.

    Examples
    --------
    >>> files = open_files('2015-*-*.csv')  # doctest: +SKIP
    >>> files = open_files(
    ...     's3://bucket/2015-*-*.csv.gz', compression='gzip'
    ... )  # doctest: +SKIP

    Returns
    -------
    An ``OpenFiles`` instance, which is a list of ``OpenFile`` objects that can
    be used as a single context

    Notes
    -----
    For a full list of the available protocols and the implementations that
    they map across to see the latest online documentation:

    - For implementations built into ``fsspec`` see
      https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
    - For implementations in separate packages see
      https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
    )numname_functionstorage_optionsprotocolexpandfiler=   T)exist_ok)r   r   r   r   r   rK   )get_fs_token_pathsre   
auto_mkdir_parentmakedirsrJ   r   )urlpathr   r   r   r   rc   rb   re   r   rj   rf   kwargsr   fs_tokenpathsr   parentsparents                     r!   
open_filesrs      s    ^ -#B% 
{{f"	DZ0562::d#66:ABVd	+B 	
  '!	
   7B	
s   BB$<B)c                 ~   t        j                  d      }d| v r9| j                  d      D cg c]  }d|v s|j                  |      r|n|dz     c}n| g}g }d }|j	                         }t        |      D ]  }|j                  dd       xs t        |      d   xs d}t        |      }	|	j                  |      }
|j                  |i       }||d   u r|j                  |       t        d	i |
|}|	j                  |      }|dv rd|vr|}|j                  |||f       |} t        t        |            }|S c c}w )
Nz.*[^a-z]+.*z::://re   r   rg   >   	filecache
blockcachesimplecachetarget_protocolrH   )recompilesplitmatchcopyr>   popsplit_protocolr   _get_kwargs_from_urlsupdatedict_strip_protocolr0   list)r   rn   xpbitsr\   previous_bitbitre   clsextra_kwargskwskws                r!   	_un_chainr   8  sQ   


=!A 4< @Dzz$?OP!eqjAGGAJAI	5PV 	 CL[[]F~ ::j$/S>#3Fq3ISV"8,005jj2&$q'>JJv(L(C(!!#&BB!+C

C2&'  x}
CJ3 	Qs   #D:c                 j   h d}|j                         D ci c]  \  }}||vs|| }}}t        | |      }i }t        t        |            D ]D  \  }}|\  }	}
}|t	        |      dz
  k(  rt        di ||}+t        di |||d<   |
|d<   |	|d<   F |d   \  }}
}t        |
fi |}||fS c c}}w )a  
    Turn fully-qualified and potentially chained URL into filesystem instance

    Parameters
    ----------
    url : str
        The fsspec-compatible URL
    **kwargs: dict
        Extra options that make sense to a particular storage connection, e.g.
        host, port, username, password, etc.

    Returns
    -------
    filesystem : FileSystem
        The new filesystem discovered from ``url`` and created with
        ``**kwargs``.
    urlpath : str
        The file-systems-specific URL for ``url``.
    >   rb   r   r   rf   r   r   r   rc   r   target_optionsry   for   rH   )itemsr   	enumerater>   r^   r   r   )urlrn   known_kwargskvchaininkwargsichurlsre   r   rm   _r   s                  r!   	url_to_fsr   W  s    ,	L  &||~Gtq!,1FadGFGc6"EH8E?+ 2hE
Q-b-H-H%)%;B%;(%;!"&."# !8GXq	H	)	)Bw; Hs
   B/B/c                 P    t        d| g||||||dd|}|st        |       |d   S )a  Given a path or paths, return one ``OpenFile`` object.

    Parameters
    ----------
    urlpath: string or list
        Absolute or relative filepath. Prefix with a protocol like ``s3://``
        to read from alternative filesystems. Should not include glob
        character(s).
    mode: 'rb', 'wt', etc.
    compression: string or None
        If given, open file using compression codec. Can either be a compression
        name (a key in ``fsspec.compression.compr``) or "infer" to guess the
        compression from the filename suffix.
    encoding: str
        For text mode only
    errors: None or str
        Passed to TextIOWrapper in text mode
    protocol: str or None
        If given, overrides the protocol found in the URL.
    newline: bytes or None
        Used for line terminator in text mode. If None, uses system default;
        if blank, uses no translation.
    **kwargs: dict
        Extra options that make sense to a particular storage connection, e.g.
        host, port, username, password, etc.

    Examples
    --------
    >>> openfile = open('2015-01-01.csv')  # doctest: +SKIP
    >>> openfile = open(
    ...     's3://bucket/2015-01-01.csv.gz', compression='gzip'
    ... )  # doctest: +SKIP
    >>> with openfile as f:
    ...     df = pd.read_csv(f)  # doctest: +SKIP
    ...

    Returns
    -------
    ``OpenFile`` object.

    Notes
    -----
    For a full list of the available protocols and the implementations that
    they map across to see the latest online documentation:

    - For implementations built into ``fsspec`` see
      https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
    - For implementations in separate packages see
      https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
    F)rm   r   r   r   r   re   r   rf   r   rH   )rs   FileNotFoundError)	rm   r   r   r   r   re   r   rn   r\   s	            r!   r/   r/     sQ    x  
	
 
C ((q6Mr#   c                 4   d|vrt        d      t        | fd|i|}t        |d   j                  dd      st        d      |5 }|D cg c]  }|j                   }}ddd       t        | t              rt        |       sd   S S c c}w # 1 sw Y   0xY w)	aK  Open file(s) which can be resolved to local

    For files which either are local, or get downloaded upon open
    (e.g., by file caching)

    Parameters
    ----------
    url: str or list(str)
    mode: str
        Must be read mode
    storage_options:
        passed on to FS for or used by open_files (e.g., compression)
    r=   z(Can only ensure local files when readingr   r   
local_fileFzOopen_local can only be used on a filesystem which has attribute local_file=TrueN)rR   rs   getattrr   namerY   strr   )r   r   rd   ofrM   r2   rp   s          r!   
open_localr     s     $CDD	C	6d	6o	6B2a588\51-
 	
 
 (u!&'A''(#sIcNQxL (( (s   B
B	B	BBc                 X    |dk(  rt        |       }||t        vrt        d| d      |S )NinferzCompression type z not supported)r   r   rR   )rm   r   s     r!   r   r     s<    g'0;e#;,[MHIIr#   c                 v    t        |       } d| v r'| j                  dd      \  }}t        |      dkD  r||fS d| fS )zReturn protocol, path pairru   r   N)r   r|   r^   )rm   re   r   s      r!   r   r     sH    W%G ua0$x=1T>!=r#   c                 V    t        |       \  }}t        |      }|j                  |       S )zCReturn only path part of full URL, according to appropriate backend)r   r   r   )rm   re   r   r   s       r!   strip_protocolr     s+     )KHa
x
(Cw''r#   c                    g }t        |       } d|v rt        | D cg c]	  }d|v sd c}      dkD  rt        d      t        |t	        |             }| D ]4  }d|v r|j                  t        |||             $|j                  |       6 t	        |      |kD  r|d| }|S | D ]?  }t        |      r!|j                  |j                  |             /|j                  |       A |S c c}w )a(  Expand paths if they have a ``*`` in them (write mode) or any of ``*?[]``
    in them (read mode).

    :param paths: list of paths
    mode: str
        Mode in which to open files.
    num: int
        If opening in writing mode, number of files we expect to create.
    fs: filesystem object
    name_function: callable
        If opening in writing mode, this callable is used to generate path
        names. Names are generated for each partition by
        ``urlpath.replace('*', name_function(partition_index))``.
    :return: list of paths
    w*r   z;When writing data, only one filename mask can be specified.N)
r   sumrR   maxr^   extend_expand_pathsr0   r   glob)rp   r   rb   r   rc   expanded_pathsr   	curr_paths           r!   expand_paths_if_neededr     s     NKE
d{5-aC1H-.2M  #s5z" 	1Ii%%mI}c&RS%%i0	1 ~$+DS1N   	1I#%%bggi&89%%i0	1 1 .s
   	C'C'c                 J   t        | t        t        t        f      r%| st	        d      t        t        |       d         }nt        |       }|xs i }|r||d<   t        ||xs i       }i }	t        t        |            D ]D  \  }
}|\  }}}|
t        |      dz
  k(  rt        di ||	}	+t        di ||	|	d<   ||	d<   ||	d<   F |d   \  }}}t        |fi |	}t        | t        t        t        f      rg| D cg c]  }t        t        |      |xs i       d     }}t        |D ch c]  }|d   	 c}      dkD  rt	        d|       |D cg c]  }|d   	 }}n|j                  |      }t        |t        t        t        f      rt        |||||      }nid	|v r|rt        |||      }nUd
|v r|rt        |||      }nAd|v r:t        |j!                  |            D cg c]  }|j#                  |      r| }}n|g}||j$                  |fS c c}w c c}w c c}w c c}w )a  Filesystem, deterministic token, and paths from a urlpath and options.

    Parameters
    ----------
    urlpath: string or iterable
        Absolute or relative filepath, URL (may include protocols like
        ``s3://``), or globstring pointing to data.
    mode: str, optional
        Mode in which to open files.
    num: int, optional
        If opening in writing mode, number of files we expect to create.
    name_function: callable, optional
        If opening in writing mode, this callable is used to generate path
        names. Names are generated for each partition by
        ``urlpath.replace('*', name_function(partition_index))``.
    storage_options: dict, optional
        Additional keywords to pass to the filesystem class.
    protocol: str or None
        To override the protocol specifier in the URL
    expand: bool
        Expand string paths for writing, assuming the path is a directory
    zempty urlpath sequencer   re   r   r   ry   r   z$Protocol mismatch getting fs from %sr   r   r   rH   )rY   r   tuplesetrR   r   r   r   r>   r^   r   r   r   r   r   sortedr   isdir	_fs_token)rm   r   rb   rc   rd   re   rf   urlpath0r   r   r   r   r   nested_protocolr   rp   r   r   upchainspcr2   s                         r!   ri   ri   :  sI   > 'D%-.566!$w-"23!'*%+O&.
#h 526EH8E?+ 2$&!orE
Q-b-H-H%)%;B%;(%;!"&5"# qE8Q	H	)	)B'D%-.LS
GHInQ')>B?B
 
 ("1()A-CWMM!()2A))""5)%$s+,&udC]K$;6!%<ED[V!%<EE\ &rwwu~ 6J1bhhqkQJEJGEr||U"")
 )) Ks   :#H(HH!H 8H c           	         t        | t              r| j                  d      dkD  rt        d      d| vr t        j
                  j                  | d      } |t        |dz
        }t        |      D cg c]  }| j                  d ||             }}|t        |      k7  rt        j                  d       |S t        | t        t        f      rt        |       |k(  sJ t        |       }|S t        d      c c}w )Nr   r   z.Output path spec must contain exactly one '*'.z*.partzqIn order to preserve order between partitions paths created with ``name_function`` should sort to partition orderzPath should be either
1. A list of paths: ['foo.json', 'bar.json', ...]
2. A directory: 'foo/
3. A path with a '*' in it: 'foo.*.json')rY   r   countrR   osr   joinr   ranger.   r   loggerwarningr   r   r^   )r   rc   rb   r   rp   s        r!   r   r     s    $::c?QMNN_77<<h/D /a8M>CCjIc=#34IIF5M!NN* L 
D5$-	(4yCT
 L 7
 	
 Js   1C5c                   4     e Zd ZdZ	 	 	 	 	 d fd	Zd Z xZS )r1   zTextIOWrapper cannot be pickled. This solves it.

    Requires that ``buffer`` be pickleable, which all instances of
    AbstractBufferedFile are.
    c                 L    ||||||f| _         t        |   | j                     y r   )r7   rN   r"   )r    bufferr   r   r   line_bufferingwrite_throughrO   s          r!   r"   z PickleableTextIOWrapper.__init__  s*     Hfg~}T	$))$r#   c                 &    t         | j                  fS r   )r1   r7   r%   s    r!   r&   z"PickleableTextIOWrapper.__reduce__  s    &		11r#   )NNNFF)rC   rD   rE   rF   r"   r&   r_   r`   s   @r!   r1   r1     s#     
%2r#   r1   )
rB   Nutf8NNr   NNTT)rB   Nr   NNN)rB   )rB   r   NNNT))iologgingr   rz   r   r   cachingr   r   r   r   r	   r
   r   r   registryr   r   utilsr   r   r   r   	getLoggerr   r   r   rJ   rs   r   r   r/   r   r   r   r   r   ri   r   TextIOWrapperr1   rH   r#   r!   <module>r      s    	  	 	    6  
		8	$p pf7; 7;x 
	l^>.f 
IX:(,b 
	J#Z<2b.. 2r#   