
    Zi1              
          U 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 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 d d
lmZmZ d dlZd dlZd dl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)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:  ej;        dej<                  Z=e G d d                      Z> e?ej@                  ZAeeBd<    G d deA          ZC G d dej@        eC          ZD G d dejE        jF                  ZG G d  d!ejE        jF                  ZHd"eId#eIfd$ZJd%eId#eIfd&ZKd'eId(eeL         d#efd)ZMd*eDd'eId+eId,eNd-eIf
d.ZOd/ ZP eD            ZQdS )0    N)deque)	ExitStack)deepcopy)	dataclassfield)datetime)chain)Path)AnyIteratorNoReturnOptionalUnion)quoteunquote)_DEFAULT_CALLBACKNoOpCallbackTqdmCallback)
isfilelike   )	constants)CommitOperationCopyCommitOperationDelete)EntryNotFoundErrorHfHubHTTPErrorRepositoryNotFoundErrorRevisionNotFoundError)
hf_hub_urlhttp_get)HfApiLastCommitInfoRepoFile)HFValidationErrorhf_raise_for_statushttp_backoffhttp_stream_backoff)md5zy
    (^refs\/convert\/\w+)     # `refs/convert/parquet` revisions
    |
    (^refs\/pr\/\d+)          # PR revisions
    c                   x    e Zd ZU dZeed<   eed<   eed<   eed<    edd          Zee         ed	<   d
efdZ	dS )HfFileSystemResolvedPathzUData structure containing information about a resolved Hugging Face file system path.	repo_typerepo_idrevisionpath_in_repoNF)defaultrepr_raw_revisionreturnc                    t           j                            | j        d          | j        z   }| j        r'| d| j         d| j                             d          S | j        t           j	        k    r4| dt          | j                   d| j                             d          S | d| j                             d          S )N @/)r   REPO_TYPES_URL_PREFIXESgetr*   r+   r0   r-   rstripr,   DEFAULT_REVISIONsafe_revision)self	repo_paths     Y/root/projects/butler/venv/lib/python3.11/site-packages/huggingface_hub/hf_file_system.py	unresolvez"HfFileSystemResolvedPath.unresolve4   s    599$."MMPTP\\	 	BJJ$"4JJt7HJJQQRUVVV]i888TT-">">TTARTT[[\_```55$"355<<SAAA    )
__name__
__module____qualname____doc__str__annotations__r   r0   r   r>    r?   r=   r)   r)   (   s         __NNNLLLMMM $)5E#B#B#BM8C=BBBB3 B B B B B Br?   r)   _cached_basec                   (     e Zd ZdZ fdZd Z xZS )_Cacheda  
    Metaclass for caching HfFileSystem instances according to the args.

    This creates an additional reference to the filesystem, which prevents the
    filesystem from being garbage collected when all *user* references go away.
    A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also*
    be made for a filesystem instance to be garbage collected.

    This is a slightly modified version of `fsspec.spec._Cached` to improve it.
    In particular in `_tokenize` the pid isn't taken into account for the
    `fs_token` used to identify cached instances. The `fs_token` logic is also
    robust to defaults values and the order of the args. Finally new instances
    reuse the states from sister instances in the main thread.
    c                 H     t                      j        |i | i | _        d S N)super__init___cache)clsargskwargs	__class__s      r=   rM   z_Cached.__init__R   s,    $)&))) 


r?   c                 T   |                     dd          } | j        | t          j                    g|R i |} | j        | t          j                    j        g|R i |}|s$| j        r|| j        v r|| _        | j        |         S t          j
        | g|R i |}|sZ| j        rS|| j        v rJ| j        |                                         }|                                D ]\  }}	t          |||	           ||_        ||_        ||_        | j        r|s|| _        || j        |<   |S )Nskip_instance_cacheF)pop	_tokenize	threading	get_identmain_threadidentcachablerN   _latesttype__call___get_instance_stateitemssetattr
_fs_token_storage_argsstorage_options)
rO   rP   rQ   skipfs_tokenfs_token_main_threadobjinstance_stateattrstate_values
             r=   r^   z_Cached.__call__Z   sr   zz/77 3=i&9&;&;MdMMMfMM,s}S)2G2I2I2OaRVaaaZ`aa 	 	SZ)?)?"CK:h'' -5d555f55C 4CL 4-ASZ-O-O!$,@!A!U!U!W!W)7)=)=)?)? 4 4%D+C{3333%CN#C"(C| +D +&'*
8$Jr?   )r@   rA   rB   rC   rM   r^   __classcell__rR   s   @r=   rI   rI   B   sQ                   r?   rI   c                   4    e Zd ZdZdZdZddddddee         dee	edf         dee
         d	ee	         f fd
Zede
defd            Zdededee         dee	ee         f         fdZd5dedee         defdZd5dee         ddfdZ	 	 	 d6dededee
         dee         ded         f
dZd5dedee         ddfdZ	 	 	 d7dede	dee
         dee         ddf
dZ	 d8dede	d e	dee         deeeeeef         f                  f
d!Z	 	 	 	 	 d9dede	d e	dee         d	ee	         dee
         fd"Zdedeeeee         ee         f                  f fd#Zd5dedee
         dee         f fd$Z	 	 	 	 	 d:dedee
         d%e	de	d e	dee         deee         eeeeef         f         f         fd&Zd5d'ed(edee         ddfd)Z dede!fd*Z"d;ded e	dee         deeef         fd+Z#d, Z$d- Z%d. Z&dedefd/Z'e(dfd< fd0Z)e*d1             Z+d2 Z,d3 Z-d4 Z. xZ/S )=HfFileSystemaL  
    Access a remote Hugging Face Hub repository as if were a local file system.

    > [!WARNING]
    > [`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading
    >     Hugging Face datasets directly with `pandas`). However, it introduces additional overhead due to this compatibility
    >     layer. For better performance and reliability, it's recommended to use `HfApi` methods when possible.

    Args:
        endpoint (`str`, *optional*):
                Endpoint of the Hub. Defaults to <https://huggingface.co>.
        token (`bool` or `str`, *optional*):
            A valid user access token (string). Defaults to the locally saved
            token, which is the recommended method for authentication (see
            https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
            To disable authentication, pass `False`.
        block_size (`int`, *optional*):
            Block size for reading and writing files.
        expand_info (`bool`, *optional*):
            Whether to expand the information of the files.
        **storage_options (`dict`, *optional*):
            Additional options for the filesystem. See [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.__init__).

    Usage:

    ```python
    >>> from huggingface_hub import hffs

    >>> # List files
    >>> hffs.glob("my-username/my-model/*.bin")
    ['my-username/my-model/pytorch_model.bin']
    >>> hffs.ls("datasets/my-username/my-dataset", detail=False)
    ['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json']

    >>> # Read/write files
    >>> with hffs.open("my-username/my-model/pytorch_model.bin") as f:
    ...     data = f.read()
    >>> with hffs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
    ...     f.write(data)
    ```

    Specify a token for authentication:
    ```python
    >>> from huggingface_hub import HfFileSystem
    >>> hffs = HfFileSystem(token=token)
    ```
    r3   hfN)endpointtoken
block_sizeexpand_inforq   rr   rs   rt   c                     t                      j        |i | |pt          j        | _        || _        t          ||          | _        || _        || _	        i | _
        i | _        d S )N)rq   rr   )rL   rM   r   ENDPOINTrq   rr   r    _apirs   rt   _repo_and_revision_exists_cachedircache)r;   rq   rr   rs   rt   rP   rd   rR   s          r=   rM   zHfFileSystem.__init__   st     	$2/222 6I$6
85999	$&  	, :<r?   threading_identr1   c                 B                        d          pt          j        d<                        d          d<   fdt                    D             | ||f}t	          t          |                                                    }|                                S )zDeterministic token for cachingrq   rr   c                 "    i | ]}||         S rF   rF   ).0keyrQ   s     r=   
<dictcomp>z*HfFileSystem._tokenize.<locals>.<dictcomp>   s    ===s#vc{===r?   )r7   r   rv   sortedr'   rD   encode	hexdigest)rO   rz   rP   rQ   tokenize_argshs      `  r=   rV   zHfFileSystem._tokenize   s     $ZZ
33Iy7Iz **W--w====fVnn===otV<M""))++,,{{}}r?   r*   r+   r,   c                    |||f| j         vr	 | j                            |||t          j                   d| j         |||f<   d| j         ||d f<   nj# t
          t          f$ r(}d|f| j         |||f<   d|f| j         ||d f<   Y d }~n6d }~wt          $ r&}d|f| j         |||f<   d| j         ||d f<   Y d }~nd }~ww xY w| j         |||f         S )N)r,   r*   timeout)TNF)rx   rw   	repo_infor   HF_HUB_ETAG_TIMEOUTr   r#   r   )r;   r*   r+   r,   es        r=   _repo_and_revision_existz%HfFileSystem._repo_and_revision_exist   sT    w)1UUU^	##h)YMj $    Xb4i(5STS]4i$5OPP ,->? \ \ \W\^_W_4i(5STSXZ[S[4i$5OPPPPPP( ^ ^ ^W\^_W_4i(5STS]4i$5OPPPPPP^ 3Y4RSSs#   (A B8"BB8B33B8pathc                    dt           t                   dt           t                   dt           t                   fd}|                     |          }|st          d          |                    d          d         dz   t
          j                                        v r?d|vrt          d          |                    dd          \  }}t
          j        |         }nt
          j	        }|
                    d          dk    rTd	d                    |                    d          d
d                   v r|                    d	d          \  }}d|v rt                              |          }|[|d
|                                fv rCt                              d|                              d          }|                                }n|                    dd          \  }}nd} |t#          |          |          }|                     |||          \  }	}
|	st'          ||
           nd
}d                    |                    d          d
d                   }d                    |                    d          dd
                   }|                    d          d         }d                    |                    d          dd
                   }|}|}|                     |||          \  }	}
|	s]t)          |
t*          t,          f          r1|}|}|                     |||          \  }	}|	st'          ||
           nyt'          ||
           nh|}d}d	|v r3|                    d	d          \  }} |t#          |          |          }nd
}|                     |||          \  }	}|	st          d          ||nt
          j        }t1          |||||          S )a  
        Resolve a Hugging Face file system path into its components.

        Args:
            path (`str`):
                Path to resolve.
            revision (`str`, *optional*):
                The revision of the repo to resolve. Defaults to the revision specified in the path.

        Returns:
            [`HfFileSystemResolvedPath`]: Resolved path information containing `repo_type`, `repo_id`, `revision` and `path_in_repo`.

        Raises:
            `ValueError`:
                If path contains conflicting revision information.
            `NotImplementedError`:
                If trying to list repositories.
        revision_in_pathr,   r1   c                 L    || | |k    rt          d|  d| d          n| }|S )NzRevision specified in path ("z ") and in `revision` argument ("z") are not the same.)
ValueError)r   r,   s     r=   %_align_revision_in_path_with_revisionzHHfFileSystem.resolve_path.<locals>._align_revision_in_path_with_revision   s^     ##/4D4P4P$-8H - -jr - - -  
 ,Or?   z0Access to repositories lists is not implemented.r5   r   r   r4   N   r3   )r0   )r   rD   _strip_protocolNotImplementedErrorsplitr   r6   valuesREPO_TYPES_MAPPINGREPO_TYPE_MODELcountjoinSPECIAL_REFS_REVISION_REGEXsearchgroupsublstripr   r   _raise_file_not_found
isinstancer   r#   r9   r)   )r;   r   r,   r   r*   r+   r   matchr-   repo_and_revision_existerrrepo_id_with_namespacepath_in_repo_with_namespacerepo_id_without_namespacepath_in_repo_without_namespace_s                   r=   resolve_pathzHfFileSystem.resolve_path   s   (	&sm	7?}	c]	 	 	 	 ##D)) 
	2%&XYYYZZ__Q#%)J)Q)Q)S)SSS$)*\]]]"jja00OIt!4Y?II!1I::c??Qchhtzz#rr23333,0JJsA,>,>))***7>>?OPPE(X$9N-N-N'B'F'FrK['\'\'c'cdg'h'h+0;;==((9I9O9OPSUV9W9W6(,,#%L@@IYAZAZ\dee/3/L/LYX_ai/j/j,'. 5)$444#' ),$**S//"1"2E)F)F&.1hhtzz#qrr7J.K.K+,0JJsOOA,>)14$**S//!"":M1N1N.0:/3/L/LYX_ai/j/j,'. 9!#(?AR'STT 9";'E595R5RS\^ego5p5p2/6 =1$<<<-dC888GLd{{,0JJsA,>,>))@@IYAZAZ\dee#' )-)F)FyRY[c)d)d&#Q* ^)*\]]]'3889S'	7Hlbrssssr?   c                    |s4| j                                          | j                                         dS |                     |          }|                                }|r2| j                             |d           |                     |          }|2|j        sW| j                            |j        |j	        dfd           | j                            |j        |j	        |j
        fd           dS dS )ac  
        Clear the cache for a given path.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.invalidate_cache).

        Args:
            path (`str`, *optional*):
                Path to clear from cache. If not provided, clear the entire cache.

        N)ry   clearrx   r   r>   rU   _parentr-   r*   r+   r,   )r;   r   resolved_paths      r=   invalidate_cachezHfFileSystem.invalidate_cache>  s     	M!!!06688888 --d33M **,,D *!!$---||D))  *
 !- 488-:QS`Shjn9oquvvv488",m.C]E[\^b     r?   rbmode)HfFileSystemFileHfFileSystemStreamFilec                     ||n| j         }|||d<   d|v rt          d          |dk    rt          | |f||d|S t          | |f||d|S )Nrs   az/Appending to remote files is not yet supported.r   )r   r,   )rs   r   r   r   )r;   r   r   rs   r,   rQ   s         r=   _openzHfFileSystem._openZ  s     $.#9ZZt
!#-F< $;;%&WXXX??)$]4(]]V\]]]#D$WTHWWPVWWWr?   c                 D   |                      ||          }| j                            |j        |j        | j        |j        |j        |                    d          |                    d                     | 	                    |
                                           d S )Nr,   commit_messagecommit_description)r-   r+   rr   r*   r,   r   r   r   )r   rw   delete_filer-   r+   rr   r*   r,   r7   r   r>   )r;   r   r,   rQ   r   s        r=   _rmzHfFileSystem._rml  s    ))$)BB	&3!)*#-"+!::&677%zz*>?? 	 	
 	
 	
 	=#:#:#<#<=====r?   F	recursivemaxdepthc                                           ||          }                     ||||          } fd|D             }d |D             }	d| d}
|
|rdndz  }
|
|d
| dndz  }
 j                            |j        |j         j        |	|j        |                    d|
          |                    d                      	                    |
                                           d	S )a  
        Delete files from a repository.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.rm).

        > [!WARNING]
        > Note: When possible, use `HfApi.delete_file()` for better performance.

        Args:
            path (`str`):
                Path to delete.
            recursive (`bool`, *optional*):
                If True, delete directory and all its contents. Defaults to False.
            maxdepth (`int`, *optional*):
                Maximum number of subdirectories to visit when deleting recursively.
            revision (`str`, *optional*):
                The git revision to delete from.

        r   )r   r   r,   c                 n    g | ]1}                     |                              |          j        2S rF   )isdirr   r-   )r}   r   r;   s     r=   
<listcomp>z#HfFileSystem.rm.<locals>.<listcomp>  s?    hhh$W[WaWabfWgWgh**400=hhhr?   c                 .    g | ]}t          |           S ))r-   )r   )r}   r-   s     r=   r   z#HfFileSystem.rm.<locals>.<listcomp>  s$    iii<+FFFiiir?   zDelete  zrecursively r3   Nzup to depth r   r   )r+   r*   rr   
operationsr,   r   r   r   )r   expand_pathrw   create_commitr+   r*   rr   r,   r7   r   r>   )r;   r   r   r   r,   rQ   r   pathspaths_in_repor   r   s   `          r=   rmzHfFileSystem.rmy  s1   6 ))$)BB  XX` aahhhh%hhhii[hiii
*4***I=..2=8L44444RTT	!)#-*!"+!::&6GG%zz*>?? 	  	
 	
 	
 	=#:#:#<#<=====r?   Tdetailrefreshc                    |                      |          }|                                	  | j        f||d|}n|# t          $ ro |j        st          d            | j        |                               f||d|}fd|D             }t          |          dk    rt          d           Y nw xY w|r|nd |D             S )a  
        List the contents of a directory.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.ls).

        > [!WARNING]
        > Note: When possible, use `HfApi.list_repo_tree()` for better performance.

        Args:
            path (`str`):
                Path to the directory.
            detail (`bool`, *optional*):
                If True, returns a list of dictionaries containing file information. If False,
                returns a list of file paths. Defaults to True.
            refresh (`bool`, *optional*):
                If True, bypass the cache and fetch the latest data. Defaults to False.
            revision (`str`, *optional*):
                The git revision to list from.

        Returns:
            `list[Union[str, dict[str, Any]]]`: List of file paths (if detail=False) or list of file information
            dictionaries (if detail=True).
        r   )r   r,   Nc                 ,    g | ]}|d          k    |S namerF   r}   or   s     r=   r   z#HfFileSystem.ls.<locals>.<listcomp>  s'    777QvY$%6%61%6%6%6r?   r   c                     g | ]
}|d          S r   rF   r}   r   s     r=   r   z#HfFileSystem.ls.<locals>.<listcomp>  s    ":":":1V9":":":r?   )r   r>   _ls_treer   r-   r   r   len)r;   r   r   r   r,   rQ   r   outs    `      r=   lszHfFileSystem.ls  s   4 ))$)BB&&((		2$-SgSSFSSCC! 	2 	2 	2 - 2%dD111$-T 2 2aGhaaZ`aaC7777c777C3xx1}}%dD111	2 :ss":":c":":"::s   A   A6B98B9c           
          ||n j          j         nd}                     ||          }|                                }t          |j        |j        |j        d|j                                                  }g }	| j        v rF|sC j        |         }
|		                    |
           g }|rdt          fd|
D                       }|r|                                \  }||k    rt|d          j        vr|                    |d                    nI j        |d                  }
|		                    |
           |	                    fd|
D                        |g }|r fd	|	D             }|r|s|rN|rKt          j                            ||z             }|                    d
          s||k    s|t#          ||          v r|                    d
          n                     |          |/t)          |          d                              d
          }||z  }fd|	D             }	t-           j                  D ]5}|                    d
z             r j                            |d            6 j                            d            |		                                         |d|||                     n' j                            |j        |j        |||j        |j                  }|D ]}|d
z   |j        z   }t;          |t<                    r*||j        d|j         |j!        |j"        |j#        |j$        d}n|dd|j%        |j#        d}                     |d                   } j        &                    |g                               |           |t)          |          d                              d
          ||k    r|	                    |           |	S )NFr   r3   r-   r0   r   c                 0    g | ]}|d          dk    |fS r]   	directoryrF   r}   	path_infodepths     r=   r   z)HfFileSystem._ls_tree.<locals>.<listcomp>  s/    oooIiX^N_cnNnNneY'NnNnNnr?   r   c                 6    g | ]}|d          dk    dz   |fS )r]   r   r   rF   r   s     r=   r   z)HfFileSystem._ls_tree.<locals>.<listcomp>  s<     !" !" !"(1'0'8K'G'G &+QY	$:'G'G'Gr?   c                 V    g | ]%}|d          
                     |d                   &S )last_commitNr   )r   )r}   r   r;   s     r=   r   z)HfFileSystem._ls_tree.<locals>.<listcomp>  s3    $f$f$fQ}M]MeT\\!F)%<%<MeMeMer?   r5   c                 P    g | ]"}|d                               dz              |#S )r   r5   )
startswith)r}   r   common_paths     r=   r   z)HfFileSystem._ls_tree.<locals>.<listcomp>  s6    UUUQQvY-A-A+PSBS-T-TUqUUUr?   T)r   r   r,   rt   r   )r   expandr,   r*   filer   sizer]   blob_idlfsxet_hashr   securityr   r   r   r   r]   tree_idr   )'rt   r   r>   r)   r*   r+   r,   r0   ry   extendr   popleftappendosr   commonprefixendswithr	   r8   r   r   r   listr   rU   r   rw   list_repo_treer-   r   r"   r   r   r   r   r   r   r   
setdefault)r;   r   r   r   r,   rt   r   r   	root_pathr   cached_path_infosdirs_not_in_dircachedirs_to_visitdir_infodirs_not_expandedcommon_prefixcommon_path_depthcached_pathtreer   
cache_pathcache_path_infoparent_pathr   r   s   `                      @@r=   r   zHfFileSystem._ls_tree  s    '2KKTM]Mi9I9Iot 	 ))$)BB&&((,#!"'5
 
 
 )++ 	 4=    $d 3JJ()))#%    %oooo9Jooo! ! $ &3&;&;&=&=OE8'5H+<+<#F+4=@@0778HIIII04hv>N0O-JJ'8999)00!" !" !" !"5F!" !" !"   $   !# g$f$f$f$fc$f$f$f! 2  HY  !# 4 45IL]5] ^ ^ %--c225$	11$.BDU(V(VVV "((--- m44  '(3CIIKK(@(F(Fs(K(K% 11HUUUU#UUU#'#6#6 = =K"--kC.?@@ =))+t<<<!!+t444

MM#"+ $!)$/!) "  	 	 	 9++%*#"&/'1 ,  D " 0 0	&_y~=
i22  * ) &#,#4(}$-$6'0'<$-$6	' 	'OO !+ ! +#,#4'0'<' 'O #ll?6+BCC((b99@@QQQ"3t99;;/55c::#u'8'8JJ///
r?   c              /      K   |                      ||                    d                                                    } t                      j        |g|R i |E d{V  dS )a  
        Return all files below the given path.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.walk).

        Args:
            path (`str`):
                Root path to list files from.

        Returns:
            `Iterator[tuple[str, list[str], list[str]]]`: An iterator of (path, list of directory names, list of file names) tuples.
        r,   r   N)r   r7   r>   rL   walk)r;   r   rP   rQ   rR   s       r=   r  zHfFileSystem.walkI  sw         

:0F0F GGQQSS577<6t666v66666666666r?   c                     |                      ||                    d                                                    } t                      j        |fd|i|S )ah  
        Find files by glob-matching.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.glob).

        Args:
            path (`str`):
                Path pattern to match.

        Returns:
            `list[str]`: List of paths matching the pattern.
        r,   r   r   )r   r7   r>   rL   glob)r;   r   r   rQ   rR   s       r=   r
  zHfFileSystem.globY  sX       

:0F0F GGQQSSuww|D>>8>v>>>r?   withdirsc                    ||dk     rt          d          |                     ||          }|                                }	  | j        |fd||j        |d||sd D             n) | j        |fd|j        i|}	|	d	         d
k    r|	gz   nd D             nE# t          $ r8 	  | j        |fd|i|d	         dk    r|i ini n# t          $ r i Y nw xY wY nw xY wt                    }
|s|
S fd|
D             S )a  
        List all files below path.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.find).

        Args:
            path (`str`):
                Root path to list files from.
            maxdepth (`int`, *optional*):
                Maximum depth to descend into subdirectories.
            withdirs (`bool`, *optional*):
                Include directory paths in the output. Defaults to False.
            detail (`bool`, *optional*):
                If True, returns a dict mapping paths to file information. Defaults to False.
            refresh (`bool`, *optional*):
                If True, bypass the cache and fetch the latest data. Defaults to False.
            revision (`str`, *optional*):
                The git revision to list from.

        Returns:
            `Union[list[str], dict[str, dict[str, Any]]]`: List of paths or dict of file information.
        Nr   zmaxdepth must be at least 1r   T)r   r   r,   r   c                 *    g | ]}|d          dk    |S r   rF   r   s     r=   r   z%HfFileSystem.find.<locals>.<listcomp>  s&    BBBQ6k)A)Aq)A)A)Ar?   r,   r]   r   c                      i | ]}|d          |S r   rF   r   s     r=   r   z%HfFileSystem.find.<locals>.<dictcomp>  s    ---A1V9a---r?   r   c                 "    i | ]}||         S rF   rF   )r}   r   r   s     r=   r   z%HfFileSystem.find.<locals>.<dictcomp>  s    666D#d)666r?   )	r   r   r>   r   r,   infor   FileNotFoundErrorr   )r;   r   r   r  r   r   r,   rQ   r   r   namesr   s              @r=   findzHfFileSystem.findi  s   @ HqLL:;;;))$)BB&&((	.$- $g@Vai ms C  UBB#BBB &DIdVV]5KVvVV	+4V+<+K+KykC''QT-----CC! " 	 	 	49T??H???G6QQ*CCC$   	" s 	7L66666666s6   B" "
C$-!CC$CC$CC$#C$path1path2c                    |                      ||          }|                      ||          }|j        |j        k    o|j        |j        k    }|rd| d| }| j                            |j        |j        |j        |                    d|          |                    dd          t          |j        |j        |j                  g           n| 	                    |d	|j                  5 }	|	
                                }
d
d
d
           n# 1 swxY w Y   d| d| }| j                            |
|j        |j        | j        |j        |j        |                    d|          |                    d                     |                     |                                           |                     |                                           d
S )a  
        Copy a file within or between repositories.

        > [!WARNING]
        > Note: When possible, use `HfApi.upload_file()` for better performance.

        Args:
            path1 (`str`):
                Source path to copy from.
            path2 (`str`):
                Destination path to copy to.
            revision (`str`, *optional*):
                The git revision to copy from.

        r   zCopy z to r   r   r3   )src_path_in_repor-   src_revision)r+   r*   r,   r   r   r   r   Npath_or_fileobjr-   r+   rr   r*   r,   r   r   r   )r   r*   r+   rw   r   r,   r7   r   r-   openreadupload_filerr   r   r>   )r;   r  r  r,   rQ   resolved_path1resolved_path2	same_repor   fcontents              r=   cp_filezHfFileSystem.cp_file  s<     **58*DD**58*DD $(@@u^E[_m_uEu 	  	7U7777NI##&.(2'0%zz*:NKK#)::.BB#G#G')7)D%3%@%3%<   $     5$1HII #Q&&((# # # # # # # # # # # # # # #7U7777NI!! '+8&.j(2'0%zz*:NKK#)::.B#C#C " 	 	 	 	>#;#;#=#=>>>>#;#;#=#=>>>>>s   .DDDc                 F     | j         |fi i |ddi}|d         d         S )ai  
        Get the last modified time of a file.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.modified).

        Args:
            path (`str`):
                Path to the file.

        Returns:
            `datetime`: Last commit date of the file.
        rt   Tr   dater  )r;   r   rQ   r  s       r=   modifiedzHfFileSystem.modified  s=     tyAA!@F!@M4!@!@AAM"6**r?   c           	         |                      |          }|                                |                    d| j        | j        nd          }|j        sedddd|rZ| j                            |j        |j        |j	                  d	         }i dt          |j        |j        |j        
          dnd|                               }|s|| j        vr|                     |           || j        v r3fd| j        |         D             }	|	st#          d           |	d         |s|r	rd         | j                            |j        |j        ||j	        |j                  }
|
st#          d           |
d         }t'          |j        |j        |j	        d|j                                                  }t+          |t,                    r5|dz   |j        z   |j        d|j        |j        |j        |j        |j        dn|dz   |j        z   dd|j        |j        d|sfddD             J S )a   
        Get information about a file or directory.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.info).

        > [!WARNING]
        > Note: When possible, use `HfApi.get_paths_info()` or `HfApi.repo_info()`  for better performance.

        Args:
            path (`str`):
                Path to get info for.
            refresh (`bool`, *optional*):
                If True, bypass the cache and fetch the latest data. Defaults to False.
            revision (`str`, *optional*):
                The git revision to get info from.

        Returns:
            `dict[str, Any]`: Dictionary containing file information (type, size, commit info, etc.).

        r   rt   NFr   r   )r   r   r]   r   )r*   r,   )oidtitler%  )r   r   c                 ,    g | ]}|d          k    |S r   rF   r   s     r=   r   z%HfFileSystem.info.<locals>.<listcomp>%  s'    SSSa6dARARARARARr?   r   )r   r,   r*   r3   r   r5   r   r   r   c                 "    i | ]}||         S rF   rF   )r}   kr   s     r=   r   z%HfFileSystem.info.<locals>.<dictcomp>O  s    GGG1c!fGGGr?   )r   r   r]   )r   r>   r7   rt   r-   rw   list_repo_commitsr+   r*   r,   r!   	commit_idr+  
created_atr   ry   r   r   get_paths_infor)   r0   r   r"   r   r   r   r   r   r   r   r   )r;   r   r   r,   rQ   r   rt   r   r  out1
paths_infor   r   r   s    `           @r=   r  zHfFileSystem.info  s   * ))$)BB&&((jjt/?/K4++QV
 
 ) E	H ##	 C  
"i99!)]5LWdWm :  ##1'19JQ\Qg$ $ $   C,,t,,K %;dm#C#C$$$dm++SSSS4=#=SSS 6)$5551g &H#+++#+#mBTB\!Y55!)!.&*3+5 6  
 " 6)$555&qM	4!+!)!*!#"/"=   )++  i22  )C). @ ) &#,#4(}$-$6'0'<$-$6	 	CC !*C). @ ! +#,#4'0'< C # HGGGG.FGGGC
r?   c                     	 |                     dd          r|                     |            | j        |fi | dS #  Y dS xY w)a  
        Check if a file exists.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.exists).

        > [!WARNING]
        > Note: When possible, use `HfApi.file_exists()` for better performance.

        Args:
            path (`str`):
                Path to check.

        Returns:
            `bool`: True if file exists, False otherwise.
        r   FT)r7   r   r  )r;   r   rQ   s      r=   existszHfFileSystem.existsS  s`     	zz)U++ ,%%d+++DId%%f%%%4	55s	   9= Ac                 d    	 |                      |          d         dk    S # t          $ r Y dS w xY w)ai  
        Check if a path is a directory.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isdir).

        Args:
            path (`str`):
                Path to check.

        Returns:
            `bool`: True if path is a directory, False otherwise.
        r]   r   F)r  OSErrorr;   r   s     r=   r   zHfFileSystem.isdirl  sC    	99T??6*k99 	 	 	55	s   ! 
//c                 R    	 |                      |          d         dk    S #  Y dS xY w)a`  
        Check if a path is a file.

        For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isfile).

        Args:
            path (`str`):
                Path to check.

        Returns:
            `bool`: True if path is a file, False otherwise.
        r]   r   Fr&  r9  s     r=   isfilezHfFileSystem.isfile~  s1    	99T??6*f44	55s   ! &c                     |                      |          }t          |j        |j        |j        |j        | j                  }|                     |          r|                    ddd          }|S )z
        Get the HTTP URL of the given path.

        Args:
            path (`str`):
                Path to get URL for.

        Returns:
            `str`: HTTP URL to access the file or directory on the Hub.
        )r*   r,   rq   z	/resolve/z/tree/r   )	r   r   r+   r-   r*   r,   rq   r   replace)r;   r   r   urls       r=   r>  zHfFileSystem.url  sx     ))$//!&#-"+]
 
 
 ::d 	8++k8Q77C
r?   c                    |                     d          }t          |                                          dhz
  }t          |t          t
          f          rt          |          dk    r t                      j        ||f||d|S t          |          r|}n-| 
                    |          rt          j        |d           dS t          |t          t          f          r3t          j        t          j                            |          d           d}|t#          |d          }d}|                                }	|                     ||	          }
|                     ||	          d
         }|                    |           	 t-          t/          |
j        |
j        |
j        |
j        | j                  |||d| j                                        t          |t
                    r|j        nd           |                     |	           |r|!                                 dS dS # |r|!                                 w w xY w)aC  
        Copy single remote file to local.

        > [!WARNING]
        > Note: When possible, use `HfApi.hf_hub_download()` for better performance.

        Args:
            rpath (`str`):
                Remote path to download from.
            lpath (`str`):
                Local path to download to.
            callback (`Callback`, *optional*):
                Optional callback to track download progress. Defaults to no callback.
            outfile (`IO`, *optional*):
                Optional file-like object to write to. If provided, `lpath` is ignored.

        r,   r   )callbackoutfileT)exist_okNFwbr   r   r+   r,   filenamer*   rq   )r>  	temp_filedisplayed_filenameexpected_sizeresume_sizeheaders	_tqdm_bar)"r7   setkeysr   r   r   r   rL   get_filer   r   r   makedirsrD   r
   r   dirnamer  tellr   r  set_sizer   r   r+   r,   r-   r*   rq   rw   _build_hf_headerstqdmseekclose)r;   rpathlpathr@  rA  rQ   r,   unhandled_kwargs
close_fileinitial_posresolve_remote_pathrH  rR   s               r=   rN  zHfFileSystem.get_file  s[   $ ::j))v{{}}--<(\<$@AA 	`SIYEZEZ]^E^E^ $577#E5_8W__X^___ e 	GGZZ 	K----4ec4[)) 	?K..>>>> 
?5$''GJllnn #///II		%(	;;FC-(((	 /7090=1;!]   "#(+	3355+5h+M+MW(--SW    LL%%%      z   s   B	H. .Ic                      t          d          )zA context within which files are committed together upon exit

        Requires the file class to implement `.commit()` and `.discard()`
        for the normal and exception cases.
        (Transactional commits are not supported.r   r;   s    r=   transactionzHfFileSystem.transaction  s     ""LMMMr?   c                      t          d          )z@Begin write transaction for deferring files, non-context versionr^  r_  r`  s    r=   start_transactionzHfFileSystem.start_transaction  s     ""LMMMr?   c                 n    t           t          |           | j        | j        |                                 ffS rK   )make_instancer]   rc   rd   r_   r`  s    r=   
__reduce__zHfFileSystem.__reduce__  s8    JJ $$&&	
 
 	
r?   c                 T    t          | j                  t          | j                  dS )N)ry   rx   )r   ry   rx   r`  s    r=   r_   z HfFileSystem._get_instance_state  s,     ///78\/]/]
 
 	
r?   rK   )r   NN)FNN)TFN)FFNNN)NFFFN)FNr1   N)0r@   rA   rB   rC   root_markerprotocolr   rD   r   boolintrM   classmethodrV   tuple	Exceptionr   r)   r   r   r   r   r   r   dictr   r   r   r   r  r
  r  r#  r   r'  r  r6  r   r;  r>  r   rN  propertyra  rc  rf  r_   rl   rm   s   @r=   ro   ro   t   s       . .` KH
 #'(,$(&*< < < 3-< T3_%	<
 SM< d^< < < < < <0 	 	 	 	 	 [	TT'*T6>smT	tXi((	)T T T T&]t ]t ]t ]tIa ]t ]t ]t ]t~ Xc] d    > $("&X XX X SM	X
 3-X 
;	<X X X X$> > >x} >$ > > > >   "&"&,> ,>,> ,> 3-	,>
 3-,> 
,> ,> ,> ,>^ `d&; &;&;!%&;7;&;OWX[}&;	eCc3h'(	)&; &; &; &;V  "&&*"&x xx x 	x
 3-x d^x 3-x x x xt7 7(5d3iQUVYQZAZ;[2\ 7 7 7 7 7 7 ? ? ? ?4PS9 ? ? ? ? ? ?& #'"&=7 =7=7 3-=7 	=7
 =7 =7 3-=7 
tCy$sDcN233	4=7 =7 =7 =7~6? 6?S 6? 6? 6?[_ 6? 6? 6? 6?p+S +x + + + + a a at ax} abfgjlogobp a a a aF  2  $  $     . /@ B  B  B  B  B  B  B H N N XNN N N
 
 

 
 
 
 
 
 
r?   ro   )	metaclassc                        e Zd Zddededee         f fdZ fdZdeded	e	fd
Z
ddZdded	dfdZd fd	Zd	efdZ xZS )r   Nfsr   r,   c                 (   	 |                     ||          | _        n># t          $ r1}d|                    dd          v rt          | d          | d }~ww xY w t	                      j        || j                                        fi | |  d S )Nr   wr   r3   B.
Make sure the repository and revision exist before writing data.)r   r   r  r7   rL   rM   r>   )r;   rt  r   r,   rQ   r   rR   s         r=   rM   zHfFileSystemFile.__init__  s    	!#!I!ID  	 	 	fjj,,,,']]]  	 	T/99;;FFvFFFs     
A,AAc                 h    t          | d          sd S t                                                      S Nr   )hasattrrL   __del__r;   rR   s    r=   r{  zHfFileSystemFile.__del__  s.    t_-- 	Fww   r?   startendr1   c                 J   dd| d|dz
   i| j         j                                        }t          | j        j        | j        j        | j        j        | j        j        | j         j	                  }t          d||t          j                  }t          |           |j        S )Nrangebytes=-r   rD  GETrJ  r   )rt  rw   rS  r   r   r+   r,   r-   r*   rq   r%   r   HF_HUB_DOWNLOAD_TIMEOUTr$   r"  )r;   r}  r~  rJ  r>  rs         r=   _fetch_rangezHfFileSystemFile._fetch_range  s    /e//cAg//
gl,,..
 &.'0'4(2W%
 
 
 Wi>_```Ayr?   c                 <    t          j        dd          | _        d S )Nzhffs-F)prefixdelete)tempfileNamedTemporaryFilerF  r`  s    r=   _initiate_uploadz!HfFileSystemFile._initiate_upload/  s    !4GERRRr?   Ffinalc                    | j                             d           | j                                         }| j                            |           |r| j                                         | j        j                            | j        j	        | j
        j        | j
        j        | j        j        | j
        j        | j
        j        | j                            d          | j                            d                     t%          j        | j        j	                   | j                            | j
                                                   d S d S )Nr   r   r   r  r   )bufferrU  r  rF  writerV  rt  rw   r  r   r   r-   r+   rr   r*   r,   rQ   r7   r   remover   r>   )r;   r  blocks      r=   _upload_chunkzHfFileSystemFile._upload_chunk2  s1     ""U### 	N  """GL$$ $ 3!/<*2gm,6+4#{/?@@#';??3G#H#H % 	 	 	 Idn)***G$$'1133 %     	 	r?   r)  c                 \   | j         dk    r||dk    rx| j        dk    rm| j                            | j        dd          5 }|                                }| xj        t          |          z  c_        |cddd           S # 1 swxY w Y   t                                          |          S )zRead remote file.

        If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems the file is
        loaded in memory directly. Otherwise, the file is downloaded to a temporary file and read from there.
        r   Nr)  r   )rs   )r   locrt  r  r   r  r   rL   )r;   lengthr!  r   rR   s       r=   r  zHfFileSystemFile.readG  s     9&.FbLLdhRSmmdi!<< ffhhCHH$                ww||F###s   3BB	Bc                 @    | j                             | j                  S rK   rt  r>  r   r`  s    r=   r>  zHfFileSystemFile.urlT      w{{49%%%r?   rK   rh  )Fr)  )r@   rA   rB   ro   rD   r   rM   r{  rl  bytesr  r  rk  r  r  r>  rl   rm   s   @r=   r   r     s       
 
< 
s 
hsm 
 
 
 
 
 
! ! ! ! !# C E     S S S S 4 D    *$ $ $ $ $ $&S & & & & & & & &r?   r   c                        e Zd Z	 	 	 	 ddedededee         d	ed
ef fdZddedefdZddefdZ	dde
e         dedefdZdefdZ fdZd Zd Z xZS )r   r   Nr   nonert  r   r   r,   rs   
cache_typec                 p   |dk    rt          d|           |dk    rt          d|           d|v rt          d| d          	 |                    ||          | _        nB# t          $ r5}d|                    d	d
          v rt          | d          |Y d }~nd }~ww xY w| j                                        d d| _         t                      j        || j                                        f|||d| d | _	        |  t                      | _        d | _        t                      | _        d S )Nr   z:HfFileSystemStreamFile only supports block_size=0 but got r  z?HfFileSystemStreamFile only supports cache_type='none' but got rv  z;HfFileSystemStreamFile only supports reading but got mode=''r   r   r3   rw  )r   r   r   rs   r  )r   r   r   r  r7   r>   detailsrL   rM   responser   _exit_stack_stream_iterator	bytearray_stream_buffer)
r;   rt  r   r   r,   rs   r  rQ   r   rR   s
            r=   rM   zHfFileSystemStreamFile.__init__Y  s    ??fZdffgggk_ikklll$;;b[_bbbccc	!#!I!ID  	 	 	fjj,,,,']]]  -,,,,	 !% 2 < < > >MM",,..	
59j]g	
 	
kq	
 	
 	
 37$;;;?'kks   
A' '
B&1+B!!B&r  whencec                 b    |dk    r|dk    rd S || j         k    r|dk    rd S t          d          )Nr   r   zCannot seek streaming HF file)r  r   )r;   r  r  s      r=   rU  zHfFileSystemStreamFile.seek|  s?    !88!F$(??v{{F8999r?   r)  r  c                 h   | j         |                                  d}	 	 | j         | j        dS |                     | j        |          }| xj        t          |          z  c_        |S # t          $ r< | j         | j                                          |r |                                  d}Y nw xY w)zRead the remote file.

        If the file is already open, we reuse the connection.
        Otherwise, open a new connection and read from it.

        If reading the stream fails, we retry with a new connection.
        NFTr?   )r  _open_connectionr  _read_from_streamr  r   ro  rV  )r;   r  retried_oncer   s       r=   r  zHfFileSystemStreamFile.read  s     = !!###	$$=(D,A,I3,,T-BFKKCHH$
 $ $ $=,M''))) %%'''#$	$s   A* 9A* *AB0/B0iteratorr1   c                    |dk    rdS |dk     rVt          | j                  }| j                                         |D ]}|                    |           t	          |          S |t          | j                  k    r(t	          | j        d|                   }| j        d|= |S t          | j                  }| j                                         |D ]|}|t          |          z
  }|t          |          k    r|                    |           =|                    |d|                    | j                            ||d                     t	          |          S )zRead up to `length` bytes from stream buffer and stream.

        If length < 0, read until EOF.

        If EOF is reached before length, fewer bytes may be returned.
        r   r?   N)r  r  r   r   r  r   )r;   r  r  bufchunkresultneeds          r=   r  z(HfFileSystemStreamFile._read_from_stream  se    Q;;3A::D/00C%%'''! " "

5!!!!::S,----4.ww788F#GVG,M+,,!!### 	 	ECHH$Dc%jj  

5!!!!

5$<(((#**5<888Szzr?   c                 @    | j                             | j                  S rK   r  r`  s    r=   r>  zHfFileSystemStreamFile.url  r  r?   c                     t          | d          sd S | j                                         t                                                      S ry  )rz  r  rV  rL   r{  r|  s    r=   r{  zHfFileSystemStreamFile.__del__  sC    t_-- 	F   ww   r?   c                 Z    t           | j        | j        | j        | j        | j        j        ffS rK   )reopenrt  r   r   	blocksizecacher   r`  s    r=   rf  z!HfFileSystemStreamFile.__reduce__  s$    DIt~tzWWWr?   c                 |   | j                                          d| _        t          | j        j        | j        j        | j        j        | j        j        | j	        j
                  }| j	        j                                        }| j        dk    rd| j         d|d<   | j                            t!          d||t"          j                            | _        	 t)          | j                   n0# t*          $ r#}|j        j        d	k    rd| _        Y d}~dS  d}~ww xY w| j                                        | _        dS )
z%Open a connection to the remote file.NrD  r   r  r  Ranger  r  i  )r  r   r  r   r   r+   r,   r-   r*   rt  rq   rw   rS  r  r  enter_contextr&   r   r  r  r$   r   status_code
iter_bytes)r;   r>  rJ  r   s       r=   r  z'HfFileSystemStreamFile._open_connection  sQ    	!!### $&.'0'4(2W%
 
 
 ',00228a<<3333GG(66!9	  
 
	.... 	 	 	z%,, $	 !% 8 8 : :s   C. .
D8DDD)r   Nr   r  )r   r  )r@   rA   rB   ro   rD   r   rl  rM   rU  r  r   r  r  r>  r{  rf  r  rl   rm   s   @r=   r   r   X  s_       
 "& !* !*!* !* 	!*
 3-!* !* !* !* !* !* !* !*F: : :S : : : :$ $3 $ $ $ $8   (5/  3  PU        D&S & & & &! ! ! ! !X X X"; "; "; "; "; "; ";r?   r   r,   r1   c                 X    t                               |           r| nt          |           S rK   )r   r   
safe_quoter   s    r=   r:   r:     s(    288BB\88
S[H\H\\r?   sc                 $    t          | d          S )Nr3   )safe)r   )r  s    r=   r  r    s    r?   r   r   c                     | }t          |t                    r|  d}n5t          |t                    r|  d}nt          |t                    r|  d}t	          |          |)Nz (repository not found)z (revision not found)z (invalid repository id))r   r   r   r#   r  )r   r   msgs      r=   r   r     s~    
C#.// 0...	C.	/	/ 0,,,	C*	+	+ 0///
C
 
 c)r?   rt  r   rs   r  c                 4    |                      ||||          S )Nr  )r  )rt  r   r   rs   r  s        r=   r  r    s    774dzj7QQQr?   c                 l     | |i |}|                                 D ]\  }}t          |||           |S rK   )r`   ra   )rO   rP   rQ   ri   rt  rj   rk   s          r=   re  re  
  sP    	d	f		B+1133 ' 'kD+&&&&Ir?   )Rr   rer  rW   collectionsr   
contextlibr   copyr   dataclassesr   r   r   	itertoolsr	   pathlibr
   typingr   r   r   r   r   urllib.parser   r   fsspechttpxfsspec.callbacksr   r   r   fsspec.utilsr   r3   r   _commit_apir   r   errorsr   r   r   r   file_downloadr   r   hf_apir    r!   r"   utilsr#   r$   r%   r&   utils.insecure_hashlibr'   compileVERBOSEr   r)   r]   AbstractFileSystemrG   rE   rI   ro   specAbstractBufferedFiler   r   rD   r:   r  ro  r   rl  r  re  hffsrF   r?   r=   <module>r     s   					 				                              ( ( ( ( ( ( ( (                   ; ; ; ; ; ; ; ; ; ; ; ; ; ; ' ' ' ' ' ' ' '   J J J J J J J J J J # # # # # #       C C C C C C C C f f f f f f f f f f f f / / / / / / / / 3 3 3 3 3 3 3 3 3 3 \ \ \ \ \ \ \ \ \ \ \ \ ' ' ' ' ' ' )bj
 J   B B B B B B B B, D233c 3 3 3/ / / / /l / / /dU
 U
 U
 U
 U
6, U
 U
 U
 U
pI& I& I& I& I&v{7 I& I& I&XX; X; X; X; X;V[= X; X; X;v]C ]C ] ] ] ]# #    * *(9*= *( * * * *R| R3 Rc Rs RPS R R R R   |~~r?   