U
    -eFw                     @  s$  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	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 d d	lmZ d d
lmZ d dlmZ edZG dd deZ G dd de Z!G dd de!Z"G dd dZ#dd Z$ej%dddZ&dS )    )annotationsN)rmtree)ClassVar)AbstractFileSystem
filesystem)_DEFAULT_CALLBACK)compr)	BaseCache	MMapCache)BlocksizeMismatchError)AbstractBufferedFile)infer_compressionzfsspec.cachedc                	      s   e Zd ZU dZdZded< d, fd
d	Zdd Zdd Zdd Z	dd Z
dd Zdd Zd-ddZdd Zd.ddZd d! Zd"d# Z fd$d%Zd&d' Zd(d) Zd*d+ Z  ZS )/CachingFileSystemaS  Locally caching filesystem, layer over any other FS

    This class implements chunk-wise local storage of remote files, for quick
    access after the initial download. The files are stored in a given
    directory with hashes of URLs for the filenames. If no directory is given,
    a temporary one is used, which should be cleaned up by the OS after the
    process ends. The files themselves are sparse (as implemented in
    :class:`~fsspec.caching.MMapCache`), so only the data which is accessed
    takes up space.

    Restrictions:

    - the block-size must be the same for each access of a given file, unless
      all blocks of the file have already been read
    - caching can only be applied to file-systems which produce files
      derived from fsspec.spec.AbstractBufferedFile ; LocalFileSystem is also
      allowed, for testing
    )Z
blockcachecachedzClassVar[str | tuple[str, ...]]protocolNTMP
   F:	 c
                   s  t  jf |
 |dkr&|dkr&td|dk|dkA s>td|dkrRt g}nt|trd|g}n|}tj|d dd | _	|pi  _
| _| _| _|	 _| _t|tr|nt|jtr|jn|jd  _   |dk	r|nt|f j
 _ fd	d
}| _dS )a  

        Parameters
        ----------
        target_protocol: str (optional)
            Target filesystem protocol. Provide either this or ``fs``.
        cache_storage: str or list(str)
            Location to store files. If "TMP", this is a temporary directory,
            and will be cleaned up by the OS when this process ends (or later).
            If a list, each location will be tried in the order given, but
            only the last will be considered writable.
        cache_check: int
            Number of seconds between reload of cache metadata
        check_files: bool
            Whether to explicitly see if the UID of the remote file matches
            the stored one before using. Warning: some file systems such as
            HTTP cannot reliably give a unique hash of the contents of some
            path, so be sure to set this option to False.
        expiry_time: int
            The time in seconds after which a local copy is considered useless.
            Set to falsy to prevent expiry. The default is equivalent to one
            week.
        target_options: dict or None
            Passed to the instantiation of the FS, if fs is None.
        fs: filesystem instance
            The target filesystem to run against. Provide this or ``protocol``.
        same_names: bool (optional)
            By default, target URLs are hashed, so that files from different backends
            with the same basename do not conflict. If this is true, the original
            basename is used.
        compression: str (optional)
            To decompress on download. Can be 'infer' (guess from the URL name),
            one of the entries in ``fsspec.compression.compr``, or None for no
            decompression.
        Nz9Please provide filesystem instance(fs) or target_protocolz@Both filesystems (fs) and target_protocol may not be both given.r   Texist_okr   c                   s    j t | S N)fs_strip_protocoltypepathself ^/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/fsspec/implementations/cached.pyr      s    z3CachingFileSystem.__init__.<locals>._strip_protocol)super__init__
ValueErrortempfilemkdtemp
isinstancestrosmakedirsstoragekwargscache_checkcheck_filesexpirycompression
same_namesr   target_protocol
load_cacher   r   r   )r   r1   Zcache_storager,   r-   expiry_timeZtarget_optionsr   r0   r/   r+   r*   r   	__class__r   r    r"   /   s<    0

zCachingFileSystem.__init__c                 C  s   t j| jd dd d S )Nr   Tr   )r(   r)   r*   r   r   r   r    _mkcache   s    zCachingFileSystem._mkcachec              
   C  s   g }| j D ]}tj|d}tj|rt|dF}t|}| D ]"}t	|d t
rFt|d |d< qF|| W 5 Q R X q
|i  q
|   |pi g| _t | _dS )z#Read set of stored blocks from filecacherbblocksN)r*   r(   r   joinexistsopenpickleloadvaluesr&   listsetappendr6   cached_filestime
last_cache)r   rC   r*   fnfZloaded_cached_filescr   r   r    r2      s    

zCachingFileSystem.load_cachec              	   C  s  t j| jd d}| jd }t j|rt|d}t|}W 5 Q R X |	 D ]\}}||krR|d dks~|| d dkrd|d< n"|| d }|
|d  ||d< t|d || d |d< || d |d< qR|	 D ]\}}||kr|||< qn|}dd	 |	 D }| D ]&}t|d trt|d |d< q|   t|}t|| W 5 Q R X || jd< t | _d
S )z#Save set of stored blocks from filer   r7   r8   r9   TrD   uidc                 S  s   i | ]\}}||  qS r   )copy).0kvr   r   r    
<dictcomp>   s      z0CachingFileSystem.save_cache.<locals>.<dictcomp>N)r(   r   r:   r*   rC   r;   r<   r=   r>   itemsupdatemaxr?   r&   rA   r@   r6   atomic_writedumprD   rE   )r   rF   r7   rG   rC   rL   rH   r9   r   r   r    
save_cache   s6    



zCachingFileSystem.save_cachec                 C  sN   |    | jsdS t | j | jk}tdd | jD }|sB|sJ|   dS )z0Reload caches if time elapsed or any disappearedNc                 s  s   | ]}t j|V  qd S r   )r(   r   r;   )rK   r*   r   r   r    	<genexpr>   s     z1CachingFileSystem._check_cache.<locals>.<genexpr>)r6   r,   rD   rE   allr*   r2   )r   ZtimecondZ	existcondr   r   r    _check_cache   s    zCachingFileSystem._check_cachec                 C  s   |  |}|   t| j| jD ]\}}||kr2q ||  }| jrZ|d | j|krZq | j	rxt

 |d  | j	krxq tj||d }tj|r ||f  S q dS )z Is path in cache and still validrI   rD   rF   F)r   rW   zipr*   rC   rJ   r-   r   ukeyr.   rD   r(   r   r:   r;   )r   r   r*   r7   detailrF   r   r   r    _check_file   s     
zCachingFileSystem._check_filec                 C  s   t | jd  |   dS )zRemove all files and metadat from the cache

        In the case of multiple cache locations, this clears only the last one,
        which is assumed to be the read/write one.
        r   N)r   r*   r2   r   r   r   r    clear_cache   s    zCachingFileSystem.clear_cachec              	   C  s  |s
| j }|   | jd   D ]\}}t |d  |kr$| jrltj	|d }tj
| jd |}ntj
| jd |d }tj|r$t| | jd | q$| jd rtj
| jd d}t|}t| jd | W 5 Q R X nt| jd  |   dS )a  Remove all expired files and metadata from the cache

        In the case of multiple cache locations, this clears only the last one,
        which is assumed to be the read/write one.

        Parameters
        ----------
        expiry_time: int
            The time in seconds after which a local copy is considered useless.
            If not defined the default is equivalent to the attribute from the
            file caching instantiation.
        r   rD   originalrF   r7   N)r.   rW   rC   rJ   rO   rD   r0   r(   r   basenamer:   r*   r;   removepoprR   r=   rS   r   r2   )r   r3   r   rZ   r^   rF   
cache_pathfcr   r   r    clear_expired_cache   s$    


z%CachingFileSystem.clear_expired_cachec                 C  sd   |  |}| |}|sdS |\}}|| jd rXt| | jd | |   nt	ddS )zRemove cached version of given file

        Deletes local copy of the given (remote) path. If it is found in a cache
        location which is not the last, it is assumed to be read-only, and
        raises PermissionError
        Nr   z<Can only delete cached file in last, writable cache location)
r   r[   
startswithr*   r(   r_   rC   r`   rT   PermissionError)r   r   details_rF   r   r   r    pop_from_cache  s    



z CachingFileSystem.pop_from_cacher8   Tc                   s   |}j |}d|kr<jj|f||||d|S |}|r|\}}|d |d  }	}
|
dkrtd|  t||S td|  n`|j}	t	j
jd |	}t }
||	|
t j|d	}|jd |< td
|    jj|f||||dd|jrNjdkr8t|nj}t| ddd|kr|d jkrtd|d jf n
j|d< tjjj||
_j  fdd_  S )a!  Wrap the target _open

        If the whole file exists in the cache, just open it locally and
        return that.

        Otherwise, open the file on the target FS, and make it have a mmap
        cache pointing to the location which we determine, in our cache.
        The ``blocks`` instance is shared, so as the mmap cache instance
        updates, so does the entry in our ``cached_files`` attribute.
        We monkey-patch this file, so that when it closes, we call
        ``close_and_update`` to save the state of the blocks.
        r)mode
block_size
autocommitcache_optionsrF   r9   TOpening local copy of %sz#Opening partially cached copy of %sr   r]   rF   r9   rD   rI   z!Creating local sparse file for %snone)rj   rk   rl   rm   Z
cache_typeinferr8   rj   	blocksizezNCached file must be reopened with same blocksize as original (old: %i, new %i)c                     s     S r   )close_and_updater   closerG   r   r   r    <lambda>      z)CachingFileSystem._open.<locals>.<lambda>)r   r   _openr[   loggerdebugr<   	hash_namer0   r(   r   r:   r*   rA   rD   rY   rC   r6   r/   r   r   rs   r   r
   Z_fetch_rangesizer7   rv   rT   )r   r   rj   rk   rl   rm   r+   rZ   rF   hashr9   compr   ru   r    ry   )  s~    



	

zCachingFileSystem._openc                 C  s   t ||dS )N)	same_name)r|   )r   r   r   r   r   r    r|     s    zCachingFileSystem.hash_namec                 C  s   |j r
dS | |j}| jd | }|d dk	rPt|d |j |jkrPd|d< z td | 	  td W n: t
k
r   td Y n tk
r   td Y nX |  d|_ dS )	z9Called when a file is closing, so store the set of blocksNr   r9   Tzgoing to saveZsavedz&Cache saving failed while closing filez-Cache save failed due to interpreter shutdown)closedr   r   rC   lenrs   r}   rz   r{   rT   OSError	NameError)r   rG   rv   r   rH   r   r   r    rt     s     $
z"CachingFileSystem.close_and_updatec                   s    dkr fddS  dkr"t  dkr8tt S  dkrHtS td}|dd } |krp|  S |d k	rֈ |jkr|j  S t|}t| }t|st	|rt
|d	r|jd kr|||S |S t  S d S )
N)r2   ry   rT   rt   r"   __getattribute__
__reduce___make_local_detailsr<   catZcat_filegetZ
read_blocktailheadr[   rW   r6   r\   rc   rh   r6   
local_fileZ_paths_from_pathZ
get_mapper	open_manycommit_manyr|   __hash____eq__to_jsonc                    s   t t | |S r   )getattrr   __get__)argskwitemr   r   r    rw     s    z4CachingFileSystem.__getattribute__.<locals>.<lambda>)__reduce_ex__)_cacher5   __dict__r   __self__)AttributeErrorr   r   objectr   r   r   inspect
isfunctionisdatadescriptorhasattrr   r   r!   )r   r   dr   clsmr4   r   r    r     s2    #


z"CachingFileSystem.__getattribute__c                 C  s~   | |krdS t |t| sdS | j|jko|| j|jko|| j|jko|| j|jko|| j|jko|| j|jko|| j|jko|| j	|j	kS )zTest for equality.TF)
r&   r   r*   r+   r,   r-   r.   r/   r0   r1   )r   otherr   r   r    r     s&    






zCachingFileSystem.__eq__c                 C  sX   t t| jt t| jA t | jA t | jA t | jA t | jA t | j	A t | j
A S )zCalculate hash.)r~   tupler*   r'   r+   r,   r-   r.   r/   r0   r1   r   r   r   r    r     s     zCachingFileSystem.__hash__c                 C  s   t ddS )z[Calculate JSON representation.

        Not implemented yet for CachingFileSystem.
        z5CachingFileSystem JSON representation not implementedN)NotImplementedErrorr   r   r   r    r     s    zCachingFileSystem.to_json)	Nr   r   Fr   NNFN)N)r8   NTN)__name__
__module____qualname____doc__r   __annotations__r"   r6   r2   rT   rW   r[   r\   rc   rh   ry   r|   rt   r   r   r   r   __classcell__r   r   r4   r    r      s>   
         X(	
&    
[Cr   c                   @  sJ   e Zd ZdZdZdZdd Zdd Zdd	 Zd
de	fddZ
dddZdS )WholeFileCacheFileSystema  Caches whole remote files on first access

    This class is intended as a layer over any other file system, and
    will make a local copy of each file accessed, so that all subsequent
    reads are local. This is similar to ``CachingFileSystem``, but without
    the block-wise functionality and so can work even when sparse files
    are not allowed. See its docstring for definition of the init
    arguments.

    The class still needs access to the remote store for listing files,
    and may refresh cached files.
    	filecacheTc                   s   dd D }dj kr"  nfdd|D S jr@tfdd|D }dd t||D }fddt||D }dd t||D }|rވj|| fd	d|D }jd
 dd t||D  	  dd   fddt||D S )Nc                 S  s   g | ]
}|j qS r   r   )rK   Zofr   r   r    
<listcomp>  s     z6WholeFileCacheFileSystem.open_many.<locals>.<listcomp>ri   c                   s   g | ]}t j| jd qS rr   )LocalTempFiler   rj   rK   r   )
open_filesr   r   r    r     s    c                   s   g | ]}  |qS r   )r[   )rK   spr   r   r    r   "  s     c                 S  s   g | ]\}}|s|qS r   r   rK   pr   r   r   r    r   #  s      c              	     s.   g | ]&\}}t j jd   | jqS )r   )r(   r   r:   r*   r|   r0   r   r   r   r    r   $  s   c                 S  s   g | ]\}}|s|qS r   r   )rK   rF   r   r   r   r    r   (  s      c              	     s2   g | ]*}|  | jd t  j|dqS )Tro   )r|   r0   rD   r   rY   r   r   r   r    r   .  s   
r   c                 S  s   i | ]\}}||qS r   r   )rK   r   rZ   r   r   r    rN   9  s      z6WholeFileCacheFileSystem.open_many.<locals>.<dictcomp>c                 S  s   t | tr| d S | S )N   )r&   r   rF   r   r   r    	firstpart=  s    z5WholeFileCacheFileSystem.open_many.<locals>.firstpartc                   s*   g | ]"\}}t |r |n|jd qS r   )r<   rj   )rK   Zfn0Zfn1)r   r   r   r    r   A  s   )
rj   r6   r/   r   rX   r   r   rC   rP   rT   )r   r   pathsrf   ZdownpathZdownfn0ZdownfnZ	newdetailr   )r   r   r   r    r     s6    





z"WholeFileCacheFileSystem.open_manyc              	   C  sd   | j dd |D dd |D  dd |D  |D ]*}zt|j W q4 tk
r\   Y q4X q4d S )Nc                 S  s   g | ]
}|j qS r   r   rK   rG   r   r   r    r   G  s     z8WholeFileCacheFileSystem.commit_many.<locals>.<listcomp>c                 S  s   g | ]
}|j qS r   r   r   r   r   r    r   G  s     c                 S  s   g | ]}|  qS r   rv   r   r   r   r    r   H  s     )r   putr(   r_   nameFileNotFoundError)r   r   rG   r   r   r    r   F  s    "z$WholeFileCacheFileSystem.commit_manyc                 C  s^   |  || j}tj| jd |}||dt | j|d}|| j	d |< t
d|  |S )Nr   Tro   Copying %s to local cache)r|   r0   r(   r   r:   r*   rD   r   rY   rC   rz   r{   )r   r   r~   rF   rZ   r   r   r    r   P  s    
z,WholeFileCacheFileSystem._make_local_detailsFraisec                 K  sr  | j |||dd d}g }g }g }	i }
| D ]}zV| |}|sd| |}|| || nt|trr|nd |f\}}|	| W q0 tk
r } z(|dkr |dkr||
|< |	| W 5 d }~X Y q0X q0|r| j
|| |   |t| t||	D ]6\}}t|d}| |
|< W 5 Q R X |d qt|trnt|dkrn|dkrn|
|d  }
|
S )	Nmaxdepth)	recursiver   r   returnr8   r   Fr   )Zexpand_pathr   rJ   r[   r   rB   r&   r   	Exceptionr_   r   rT   Zset_sizer   rX   r<   readZrelative_updater'   )r   r   r   Zon_errorcallbackr+   r   ZgetpathsZ
storepathsfnsoutr   rZ   rF   erG   r   r   r    r   ^  sF      



$zWholeFileCacheFileSystem.catr8   c              
   K  sr  |  |}d|kr t| ||dS | |}|r|\}}|d |d  }}|dkrxtd|  t||}|d|_|S td| n
| 	|}||d	< | 
  | jrP| jj|f|}t|d
z}	t|trtd|jj|j|_| jdkrt|n| j}
t|
 |dd}d}|r:t|dd}||}|	| qW 5 Q R X W 5 Q R X n| j|| |   | ||S )Nri   rr   rF   r9   Trn   r]   z?Attempt to open partially cached file %sas a wholly cached filerj   wbr   rq   r8   rs     P )r   r   r[   rz   r{   r<   r   r]   r#   r   r6   r/   r   ry   r&   r   r	   r7   fetcherr}   r   r   r   r   writerT   )r   r   rj   r+   rZ   rF   rg   r9   rG   f2r   datablockr   r   r    ry     sJ    






$zWholeFileCacheFileSystem._openN)r8   )r   r   r   r   r   r   r   r   r   r   r   ry   r   r   r   r    r     s   /

-r   c                      sJ   e Zd ZdZdZdZ fddZdd Zdd	 Zd
d Z	dddZ
  ZS )SimpleCacheFileSystema  Caches whole remote files on first access

    This class is intended as a layer over any other file system, and
    will make a local copy of each file accessed, so that all subsequent
    reads are local. This implementation only copies whole files, and
    does not keep any metadata about the download time or file details.
    It is therefore safer to use in multi-threaded/concurrent situations.

    This is the only of the caching filesystems that supports write: you will
    be given a real local open file, and upon close and commit, it will be
    uploaded to the target filesystem; the writability or the target URL is
    not checked until that time.

    ZsimplecacheTc                   sZ   |  }dD ]}d||< qt jf | | jD ]}tj|s.tj|dd q.i g| _d S )N)r,   r3   r-   FTr   )	rJ   r!   r"   r*   r(   r   r;   r)   rC   )r   r+   r   keyr*   r4   r   r    r"     s    

zSimpleCacheFileSystem.__init__c                 C  sH   |    | || j}| jD ]&}tj||}tj|r|  S qd S r   )rW   r|   r0   r*   r(   r   r:   r;   )r   r   shar*   rF   r   r   r    r[     s    
z!SimpleCacheFileSystem._check_filec                 C  s   d S r   r   r   r   r   r    rT     s    z SimpleCacheFileSystem.save_cachec                 C  s   d S r   r   r   r   r   r    r2     s    z SimpleCacheFileSystem.load_cacher8   c              
   K  s@  |  |}d|kr t| ||dS | |}|r8t||S | || j}tj| j	d |}t
d|  ||d< |   | jr&| jj|f|}t|dx}t|trtd|jj|j|_| jdkrt|n| j}t| |d	d}d
}	|	rt|dd}
||
}	||	 qW 5 Q R X W 5 Q R X n| j|| | ||S )Nri   rr   r   r   rj   r   r   rq   r8   Trs   r   )r   r   r[   r<   r|   r0   r(   r   r:   r*   rz   r{   r6   r/   r   ry   r&   r   r	   r7   r   r}   r   r   r   r   r   r   )r   r   rj   r+   rF   r   rG   r   r   r   r   r   r   r    ry     s6    





"zSimpleCacheFileSystem._open)r8   )r   r   r   r   r   r   r"   r[   rT   r2   ry   r   r   r   r4   r    r     s   
r   c                   @  s^   e Zd ZdZdddZdd	 Zd
d Zdd Zdd Zdd Z	dd Z
edd Zdd ZdS )r   z8A temporary local file, which will be uploaded on commitNr   Tr   c                 C  sd   |r|| _ t||| _nt \}| _ t||| _|| _|rH| j| || _|| _d| _	|| _
d S )NF)rF   r<   fhr$   mkstemprj   seekr   r   r   rl   )r   r   r   rF   rj   rl   r   fdr   r   r    r"     s    zLocalTempFile.__init__c                 C  s    t | j| j| jd| j|  ffS )Nzrb+)r   r   r   rF   rl   tellr   r   r   r    r      s    zLocalTempFile.__reduce__c                 C  s   | j S r   )r   r   r   r   r    	__enter__'  s    zLocalTempFile.__enter__c                 C  s   |    d S r   r   )r   exc_typeexc_valexc_tbr   r   r    __exit__*  s    zLocalTempFile.__exit__c                 C  s,   | j r
d S | j  d| _ | jr(|   d S )NT)r   r   rv   rl   commitr   r   r   r    rv   -  s    
zLocalTempFile.closec                 C  s   | j   t| j d S r   )r   rv   r(   r_   rF   r   r   r   r    discard5  s    
zLocalTempFile.discardc              	   C  s@   | j | j| j zt| j W n ttfk
r:   Y nX d S r   )r   r   rF   r   r(   r_   re   r   r   r   r   r    r   9  s
    zLocalTempFile.commitc                 C  s   | j S r   r   r   r   r   r    r   A  s    zLocalTempFile.namec                 C  s   t | j|S r   )r   r   )r   r   r   r   r    __getattr__E  s    zLocalTempFile.__getattr__)Nr   Tr   )r   r   r   r   r"   r   r   r   rv   r   r   propertyr   r   r   r   r   r    r     s   

r   c                 C  s(   |rt j| }nt|   }|S r   )r(   r   r^   hashlibsha256encode	hexdigest)r   r   r~   r   r   r    r|   I  s    r|   r   c                 c  s   t jtj| tj| d d\}}z t||}|V  W 5 Q R X W n6 tk
r|   t	t
 t| W 5 Q R X  Y nX 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)r$   r   r(   r   dirnamer^   r<   BaseException
contextlibsuppressr   unlinkreplace)r   rj   r   rF   fpr   r   r    rR   Q  s    
 
rR   )r   )'
__future__r   r   r   r   loggingr(   r=   r$   rD   shutilr   typingr   Zfsspecr   r   Zfsspec.callbacksr   Zfsspec.compressionr   Zfsspec.corer	   r
   Zfsspec.exceptionsr   Zfsspec.specr   Zfsspec.utilsr   	getLoggerrz   r   r   r   r   r|   contextmanagerrR   r   r   r   r    <module>   s:   
   p :O;