U
    ”Ê¹jÒ¼  ã                   @   sÞ  d dl Z d dlZd dlZd dlmZ d dlmZmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZmZmZmZmZmZmZmZ d dlmZm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# ddl$m%Z%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5 e 6dej7¡Z8eG dd„ dƒƒZ9G dd„ dej:ƒZ;G dd„ dej<j=ƒZ>G dd„ dej<j=ƒZ?e@e@dœdd„ZAe@e@dœd d!„ZBe@eeC ed"œd#d$„ZDe;e@e@eEe@d%œd&d'„ZFd(d)„ ZGdS )*é    N)Údeque)Ú	dataclassÚfield)Údatetime)Úchain)ÚPath)ÚAnyÚDictÚIteratorÚListÚNoReturnÚOptionalÚTupleÚUnion)ÚquoteÚunquote)Ú_DEFAULT_CALLBACKÚNoOpCallbackÚTqdmCallback)Ú
isfilelike)ÚResponseé   )Ú	constants)ÚCommitOperationCopyÚCommitOperationDelete)ÚEntryNotFoundErrorÚRepositoryNotFoundErrorÚRevisionNotFoundError)Ú
hf_hub_urlÚhttp_get)ÚHfApiÚLastCommitInfoÚRepoFile)ÚHFValidationErrorÚhf_raise_for_statusÚhttp_backoffzy
    (^refs\/convert\/\w+)     # `refs/convert/parquet` revisions
    |
    (^refs\/pr\/\d+)          # PR revisions
    c                   @   sX   e Zd ZU dZeed< eed< eed< eed< eddd�Zee ed	< ed
œd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                 C   s‚   t j | jd¡| j }| jr:|› d| j› d| j› � d¡S | jt j	krh|› dt
| jƒ› d| j› � d¡S |› d| j› � d¡S d S )NÚ ú@ú/)r   ÚREPO_TYPES_URL_PREFIXESÚgetr'   r(   r-   r*   Úrstripr)   ÚDEFAULT_REVISIONÚsafe_revision)ÚselfÚ	repo_path© r:   ú]/var/www/html/bwave/python/venv/lib/python3.8/site-packages/huggingface_hub/hf_file_system.pyÚ	unresolve0   s    "z"HfFileSystemResolvedPath.unresolve)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚstrÚ__annotations__r   r-   r   r<   r:   r:   r:   r;   r&   $   s   
r&   c                       st  e Zd ZdZdZdZddddœee ee	edf ee
 dœ‡ fdd„Zeeee ee	ee f dœd	d
„ZdCeee edœdd„ZdDee ddœdd„ZdEeeee ee
 ddœdd„ZdFeee ddœdd„ZdGee	ee
 ee ddœdd„ZdHee	e	ee eeeeeef f  dœdd„ZdIee	e	ee e	ee
 d œd!d"„Zeeeeee ee f  dœ‡ fd#d$„Zeee dœ‡ fd%d&„ZdJeee
 e	e	e	ee eee eeeeef f f d'œd(d)„ZdKeeee dd*œd+d,„Zeedœd-d.„Z dLee	ee eeef d/œd0d1„Z!d2d3„ Z"d4d5„ Z#d6d7„ Z$eedœd8d9„Z%e&dfdd:œ‡ fd;d<„Z'e(d=d>„ ƒZ)d?d@„ Z*dAdB„ Z+‡  Z,S )MÚHfFileSystema%  
    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:
        token (`str` or `bool`, *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`.
        endpoint (`str`, *optional*):
            Endpoint of the Hub. Defaults to <https://huggingface.co>.
    Usage:

    ```python
    >>> from huggingface_hub import HfFileSystem

    >>> fs = HfFileSystem()

    >>> # List files
    >>> fs.glob("my-username/my-model/*.bin")
    ['my-username/my-model/pytorch_model.bin']
    >>> fs.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 fs.open("my-username/my-model/pytorch_model.bin") as f:
    ...     data = f.read()
    >>> with fs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
    ...     f.write(data)
    ```
    r0   ZhfN)ÚendpointÚtokenÚ
block_sizec                   sD   t ƒ j||Ž |ptj| _|| _t||d�| _|| _i | _	i | _
d S )N)rD   rE   )ÚsuperÚ__init__r   ZENDPOINTrD   rE   r    Ú_apirF   Ú_repo_and_revision_exists_cacheÚdircache)r8   rD   rE   rF   ÚargsÚstorage_options©Ú	__class__r:   r;   rH   c   s    þzHfFileSystem.__init__)r'   r(   r)   r/   c              
   C   sî   |||f| j krÞz| jj|||tjd� W n’ ttfk
rx } z,d|f| j |||f< d|f| j ||d f< W 5 d }~X Y nf tk
r¼ } z(d|f| j |||f< d| j ||d f< W 5 d }~X Y n"X d| j |||f< d| j ||d f< | j |||f S )N)r)   r'   ÚtimeoutF)TN)rJ   rI   Z	repo_infor   ZHF_HUB_ETAG_TIMEOUTr   r#   r   )r8   r'   r(   r)   Úer:   r:   r;   Ú_repo_and_revision_existy   s"       ÿ
$"z%HfFileSystem._repo_and_revision_exist)Úpathr)   r/   c                 C   s|  t t t t t t dœdd„}|  |¡}|s6tdƒ‚nN| d¡d d tj ¡ kr~d|krbtdƒ‚| dd¡\}}tj| }ntj	}| 
d¡dk�r d|k�r>| dd¡\}}d|k�rt |¡}|d	k	rö|d	| ¡ fkröt d
|¡ d¡}| ¡ }n| dd¡\}}nd
}|t|ƒ|ƒ}|  |||¡\}	}
|	�sþt||
ƒ nÀd	}d | d¡d	d… ¡}d | d¡dd	… ¡}| d¡d }d | d¡dd	… ¡}|}|}|  |||¡\}	}
|	�sVt|
ttfƒ�rô|}|}|  |||¡\}	}|	�sþt||
ƒ n
t||
ƒ nV|}d
}d|k�r2| dd¡\}}|t|ƒ|ƒ}nd	}|  |||¡\}	}|	�sVtdƒ‚|d	k	�rd|ntj}t|||||d�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)   r/   c                 S   s8   |d k	r0| d k	r4| |kr4t d| › d|› d�ƒ‚n| }|S )NzRevision specified in path ("z ") and in `revision` argument ("z") are not the same.)Ú
ValueError)rT   r)   r:   r:   r;   Ú%_align_revision_in_path_with_revision    s    ÿzHHfFileSystem.resolve_path.<locals>._align_revision_in_path_with_revisionz0Access to repositories lists is not implemented.r2   r   r   r1   Nr0   é   )r-   )r   rA   Z_strip_protocolÚNotImplementedErrorÚsplitr   r3   ÚvaluesZREPO_TYPES_MAPPINGZREPO_TYPE_MODELÚcountÚSPECIAL_REFS_REVISION_REGEXÚsearchÚgroupÚsubÚlstripr   rR   Ú_raise_file_not_foundÚjoinÚ
isinstancer   r#   r6   r&   )r8   rS   r)   rV   r'   r(   rT   Úmatchr*   Zrepo_and_revision_existÚerrZrepo_id_with_namespaceZpath_in_repo_with_namespaceZrepo_id_without_namespaceZpath_in_repo_without_namespaceÚ_r:   r:   r;   Úresolve_pathŒ   sl     þ






zHfFileSystem.resolve_path)rS   r/   c                 C   s†   |s| j  ¡  | j ¡  nh|  |¡}| ¡ }|rJ| j  |d¡ |  |¡}q,|js‚| j |j|j	dfd¡ | j |j|j	|j
fd¡ 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)rK   ÚclearrJ   rg   r<   ÚpopÚ_parentr*   r'   r(   r)   )r8   rS   Úresolved_pathr:   r:   r;   Úinvalidate_cacheë   s    

 ÿzHfFileSystem.invalidate_cacheÚrbÚHfFileSystemFile)rS   Úmoder)   rF   r/   c                 K   sn   |d k	r|n| j }|d k	r"||d< d|kr2tdƒ‚|dkrRt| |f||dœ|—ŽS t| |f||dœ|—ŽS d S )NrF   Úaz/Appending to remote files is not yet supported.r   )ro   r)   )rF   rX   ÚHfFileSystemStreamFilern   )r8   rS   ro   r)   rF   Úkwargsr:   r:   r;   Ú_open  s    zHfFileSystem._openc              
   K   sR   | j ||d�}| jj|j|j| j|j|j| d¡| d¡d� | j	| 
¡ d� d S )N©r)   Úcommit_messageÚcommit_description)r*   r(   rE   r'   r)   ru   rv   ©rS   )rg   rI   Zdelete_filer*   r(   rE   r'   r)   r4   rl   r<   )r8   rS   r)   rr   rk   r:   r:   r;   Ú_rm  s    ù	zHfFileSystem._rmF)rS   Ú	recursiveÚmaxdepthr)   r/   c              
      s¼   ˆ j ||d�}ˆ j||||d�}‡ fdd„|D ƒ}dd„ |D ƒ}	d|› d�}
|
|rVdnd	7 }
|
|d
k	rrd|› d�nd	7 }
ˆ jj|j|jˆ j|	|j| d|
¡| d¡d� ˆ j	| 
¡ 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.

        rt   )ry   rz   r)   c                    s"   g | ]}ˆ   |¡sˆ  |¡j‘qS r:   )Úisdirrg   r*   )Ú.0rS   ©r8   r:   r;   Ú
<listcomp>C  s     
 z#HfFileSystem.rm.<locals>.<listcomp>c                 S   s   g | ]}t |d �‘qS ))r*   )r   )r|   r*   r:   r:   r;   r~   D  s     zDelete ú zrecursively r0   Nzup to depth ru   rv   )r(   r'   rE   Ú
operationsr)   ru   rv   rw   )rg   Zexpand_pathrI   Úcreate_commitr(   r'   rE   r)   r4   rl   r<   )r8   rS   ry   rz   r)   rr   rk   ÚpathsZpaths_in_repor€   ru   r:   r}   r;   Úrm&  s"    
ù	zHfFileSystem.rmT)rS   ÚdetailÚrefreshr)   r/   c                    s´   | j ˆ |d�}| ¡ ‰ z| jˆ f||dœ|—Ž}W nj tk
rœ   |jsRtˆ dƒ | j|  ˆ ¡f||dœ|—Ž}‡ fdd„|D ƒ}t|ƒdkr˜tˆ dƒ Y nX |r¦|S d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).
        rt   )r…   r)   Nc                    s   g | ]}|d  ˆ kr|‘qS ©Únamer:   ©r|   Úorw   r:   r;   r~   w  s      z#HfFileSystem.ls.<locals>.<listcomp>r   c                 S   s   g | ]}|d  ‘qS r†   r:   rˆ   r:   r:   r;   r~   z  s     )rg   r<   Ú_ls_treer   r*   ra   rj   Úlen)r8   rS   r„   r…   r)   rr   rk   Úoutr:   rw   r;   ÚlsT  s    
zHfFileSystem.ls)rS   ry   r…   r)   Úexpand_inforz   c              
      sØ  ˆj ||d�}| ¡ }t|j|j|jd|jd� ¡ }g }	|ˆjk�r|�sˆj| }
|	 |
¡ g }|rðd‰t	‡fdd„|
D ƒƒ}|rð| 
¡ \‰}|d ks ˆ|kr€|d ˆjkr¾| |d ¡ q€ˆj|d  }
|	 |
¡ | ‡fdd„|
D ƒ¡ q€g }|�r‡fd	d„|	D ƒ}|�r|�s$|�rÔ|�rÔtj || ¡}| d
¡�sZ||k�sZ|t||ƒk�rd| d
¡nˆ |¡‰ |d k	�r–ˆ t|ƒd …  d
¡}||8 }‡ fdd„|	D ƒ}	tˆjƒD ]$}| ˆ d
 ¡�r²ˆj |d ¡ �q²ˆj ˆ d ¡ |	 ˆjˆ |d|||d�¡ nÐˆjj|j|j|||j|jd�}|D ]ª}|d
 |j }t|tƒ�rf||jd|j|j |j!|j"dœ}n|dd|j#|j!dœ}ˆ |d ¡}ˆj $|g ¡ |¡ |t|ƒd …  d
¡‰|d k�sÆˆ|k�r(|	 |¡ �q(|	S )Nrt   r0   ©r*   r-   rW   c                    s    g | ]}|d  dkrˆ |f‘qS ©ÚtypeÚ	directoryr:   ©r|   Ú	path_info©Údepthr:   r;   r~   ™  s      z)HfFileSystem._ls_tree.<locals>.<listcomp>r‡   c                    s$   g | ]}|d  dkrˆ d |f‘qS )r‘   r’   r   r:   r“   r•   r:   r;   r~   ¤  s   þc                    s&   g | ]}|d  dkrˆ   |d ¡‘qS )Úlast_commitNr‡   )rj   rˆ   r}   r:   r;   r~   ®  s      r2   c                    s"   g | ]}|d    ˆ d ¡s|‘qS )r‡   r2   )Ú
startswithrˆ   )Úcommon_pathr:   r;   r~   ¿  s      T)ry   r…   r)   rŽ   rz   )ry   Úexpandr)   r'   Úfile©r‡   Úsizer‘   Úblob_idÚlfsr—   Úsecurityr   r’   ©r‡   r�   r‘   Útree_idr—   )%rg   r<   r&   r'   r(   r)   r-   rK   Úextendr   ÚpopleftÚappendÚosrS   ÚcommonprefixÚendswithr   r5   rj   r‹   r[   Úlistr˜   ri   rŠ   rI   Zlist_repo_treer*   rc   r"   r�   rž   rŸ   r—   r    r¢   Ú
setdefault)r8   rS   ry   r…   r)   rŽ   rz   rk   Ú	root_pathrŒ   Zcached_path_infosZdirs_not_in_dircacheZdirs_to_visitÚdir_infoZdirs_not_expandedÚcommon_prefixZcommon_path_depthZcached_pathÚtreer”   Ú
cache_pathZcache_path_infoÚparent_pathr:   )r™   r–   r8   r;   rŠ   |  sº    	û


ÿ

þÿÿþýû
úÿúùûzHfFileSystem._ls_treec                 /   s6   | j || d¡d� ¡ }tƒ j|f|ž|ŽE dH  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)   rt   N)rg   r4   r<   rG   Úwalk)r8   rS   rL   rr   rN   r:   r;   r±   ò  s    zHfFileSystem.walkc                    s(   | j || d¡d� ¡ }tƒ j|f|Ž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)   rt   )rg   r4   r<   rG   Úglob©r8   rS   rr   rN   r:   r;   r²     s    zHfFileSystem.glob)rS   rz   Úwithdirsr„   r…   r)   r/   c                    s,  |dk	r|dk rt dƒ‚| j||d�}| ¡ }z"| j|fd||j|dœ|—Ž‰ W n^ tk
r®   z0| j|fd|i|—Žd d	krŠ|i i‰ ni ‰ W n tk
r¨   i ‰ Y nX Y nVX |sÄd
d„ ˆ D ƒ‰ n2| j|fd|ji|—Ž}	|	d dkrò|	gˆ  nˆ ‰ dd„ ˆ D ƒ‰ tˆ ƒ}
|�s|
S ‡ fdd„|
D ƒS 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 1rt   T)ry   r…   r)   rz   r)   r‘   r›   c                 S   s   g | ]}|d  dkr|‘qS r�   r:   rˆ   r:   r:   r;   r~   E  s      z%HfFileSystem.find.<locals>.<listcomp>r’   c                 S   s   i | ]}|d  |“qS r†   r:   rˆ   r:   r:   r;   Ú
<dictcomp>J  s      z%HfFileSystem.find.<locals>.<dictcomp>c                    s   i | ]}|ˆ | “qS r:   r:   )r|   r‡   ©rŒ   r:   r;   rµ   O  s      )	rU   rg   r<   rŠ   r)   r   ÚinfoÚFileNotFoundErrorÚsorted)r8   rS   rz   r´   r„   r…   r)   rr   rk   r”   Únamesr:   r¶   r;   Úfind  s>     ÿ   ÿÿ

zHfFileSystem.find)Úpath1Úpath2r)   r/   c                 K   s  | j ||d�}| j ||d�}|j|jko2|j|jk}|rŠd|› d|› �}| jj|j|j|j| d|¡| dd¡t|j|j|jd�gd� nj| j	|d	|jd��}	|	 
¡ }
W 5 Q R X d|› d|› �}| jj|
|j|j| j|j|j| d|¡| d¡d
� | j| ¡ d� | j| ¡ 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.

        rt   zCopy z to ru   rv   r0   )Zsrc_path_in_repor*   Zsrc_revision)r(   r'   r)   ru   rv   r€   rm   ©Zpath_or_fileobjr*   r(   rE   r'   r)   ru   rv   rw   N)rg   r'   r(   rI   r�   r)   r4   r   r*   ÚopenÚreadÚupload_filerE   rl   r<   )r8   r¼   r½   r)   rr   Zresolved_path1Zresolved_path2Z	same_reporu   ÚfÚcontentr:   r:   r;   Úcp_fileQ  sD    ÿ

ýÿú
ø
zHfFileSystem.cp_filec                 K   s"   | j |f|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.
        rŽ   Tr—   Údate©r·   )r8   rS   rr   r·   r:   r:   r;   Úmodified‰  s    zHfFileSystem.modified)rS   r…   r)   r/   c                    sÎ  | j ˆ|d�}| ¡ ‰| dd¡}|jsxˆddddœ‰ |rt| jj|j|j|jd�d	 }ˆ dt	|j
|j|jd
�dœ–‰ �nDd‰ |  ˆ¡}|sž|| jkrž|  |¡ || jkrÖ‡fdd„| j| D ƒ}	|	sÎtˆdƒ |	d ‰ |süˆ dksü|�r¼ˆ �r¼ˆ d dk�r¼| jj|j|j||j|jd�}
|
�s*tˆdƒ |
d }t|j|j|jd|jd� ¡ }t|tƒ�r†|d |j |jd|j|j|j|jdœ‰ n|d |j dd|j|jdœ‰ |�s¼‡ fdd„dD ƒ‰ ˆ dk	�sÊt‚ˆ 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.).

        rt   rŽ   Fr   r’   N)r‡   r�   r‘   r—   )r'   r)   éÿÿÿÿ)ÚoidÚtitlerÅ   )r¢   r—   c                    s   g | ]}|d  ˆ kr|‘qS r†   r:   rˆ   rw   r:   r;   r~   Î  s      z%HfFileSystem.info.<locals>.<listcomp>r—   )rš   r)   r'   r0   r�   r2   r›   rœ   r¡   c                    s   i | ]}|ˆ | “qS r:   r:   )r|   Úkr¶   r:   r;   rµ   ÷  s      z%HfFileSystem.info.<locals>.<dictcomp>)r‡   r�   r‘   )rg   r<   r4   r*   rI   Zlist_repo_commitsr(   r'   r)   r!   Ú	commit_idrÊ   Z
created_atrj   rK   r�   ra   Zget_paths_infor&   r-   rc   r"   rS   r�   rž   rŸ   r—   r    r¢   ÚAssertionError)r8   rS   r…   r)   rr   rk   rŽ   r—   r°   Zout1Z
paths_infor”   r«   r:   )rŒ   rS   r;   r·   ™  s”     ÿü  ÿþ  ÿý



&û
û
ùûzHfFileSystem.infoc                 K   s>   z*|  dd¡r|  |¡ | j|f|Ž W dS    Y dS X dS )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…   FTN)r4   rl   r·   r³   r:   r:   r;   Úexistsû  s    
zHfFileSystem.existsc                 C   s0   z|   |¡d dkW S  tk
r*   Y dS X dS )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’   FN)r·   ÚOSError©r8   rS   r:   r:   r;   r{     s    zHfFileSystem.isdirc                 C   s(   z|   |¡d dkW S    Y dS X dS )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›   FNrÆ   rÐ   r:   r:   r;   Úisfile&  s    zHfFileSystem.isfilec                 C   sB   |   |¡}t|j|j|j|j| jd�}|  |¡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)   rD   z	/resolve/z/tree/r   )	rg   r   r(   r*   r'   r)   rD   r{   Úreplace)r8   rS   rk   Úurlr:   r:   r;   rÓ   8  s    
û
zHfFileSystem.urlr.   c              
      sV  |  d¡}t| ¡ ƒdh }t|ttfƒr6t|ƒdkrRtƒ j||f||dœ|—ŽS t	|ƒr`|}n|  
|¡r|tj|dd� dS t|ttfƒr tjtj |¡dd� d}|dkrºt|dƒ}d}| ¡ }	| j||d	�}
| j||d	�d
 }| |¡ zTtt|
j|
j|
j|
j| jd�|||d| j ¡ t|tƒ�r,|j ndd� | !|	¡ W 5 |�rP| ¡  X dS )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Úwbrt   r�   ©r(   r)   Úfilenamer'   rD   )rÓ   Ú	temp_fileZdisplayed_filenameÚexpected_sizeZresume_sizeÚheadersZ	_tqdm_bar)"r4   ÚsetÚkeysrc   r   r   r‹   rG   Úget_filer   r{   r¦   ÚmakedirsrA   r   rS   Údirnamer¿   Útellrg   r·   Zset_sizeÚcloser   r   r(   r)   r*   r'   rD   rI   Ú_build_hf_headersZtqdmÚseek)r8   ZrpathZlpathrÔ   rÕ   rr   r)   Zunhandled_kwargsZ
close_fileZinitial_posZresolve_remote_pathrÛ   rN   r:   r;   rß   O  sL    



ûózHfFileSystem.get_filec                 C   s   t dƒ‚dS )z½A 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.N©rX   r}   r:   r:   r;   Útransaction“  s    	zHfFileSystem.transactionc                 C   s   t dƒ‚dS )z@Begin write transaction for deferring files, non-context versionræ   Nrç   r}   r:   r:   r;   Ústart_transactionž  s    zHfFileSystem.start_transactionc                 C   s"   t t| ƒ| j| j| j| jdœffS )N)rK   rJ   )Úmake_instancer‘   Zstorage_argsrM   rK   rJ   r}   r:   r:   r;   Ú
__reduce__¤  s    þüzHfFileSystem.__reduce__)N)N)rm   NN)N)FNN)TFN)FFNFN)NFFFN)N)FN)-r=   r>   r?   r@   Zroot_markerÚprotocolr   rA   r   ÚboolÚintrH   r   Ú	ExceptionrR   r&   rg   rl   rs   rx   rƒ   r   r	   r   r�   rŠ   r
   r±   r²   r»   rÄ   r   rÇ   r·   rÎ   r{   rÑ   rÓ   r   rß   Úpropertyrè   ré   rë   Ú__classcell__r:   r:   rN   r;   rC   :   s´   %ûû  þ_   ûù   ûù/     ÿ   þ+     ùùv*     ù÷?8"bD

rC   c                       s†   e Zd Zdeeee dœ‡ fdd„Z‡ fdd„Zeee	dœdd	„Z
dd
œdd„Zdeddœdd„Zd‡ fdd„	Zed
œdd„Z‡  ZS )rn   N)ÚfsrS   r)   c              
      sz   z|j ||d�| _W nD tk
rX } z&d| dd¡krFt|› d�ƒ|‚‚ W 5 d }~X Y nX tƒ j|| j ¡ f|Ž |  d S )Nrt   Úwro   r0   úB.
Make sure the repository and revision exist before writing data.)rg   rk   r¸   r4   rG   rH   r<   )r8   rò   rS   r)   rr   rQ   rN   r:   r;   rH   ²  s    ÿþzHfFileSystemFile.__init__c                    s   t | dƒsd S tƒ  ¡ S ©Nrk   ©ÚhasattrrG   Ú__del__r}   rN   r:   r;   rø   ¾  s    
zHfFileSystemFile.__del__)ÚstartÚendr/   c                 C   sj   dd|› d|d › �i| j j ¡ –}t| jj| jj| jj| jj| j j	d�}t
d||tjd�}t|ƒ |jS )NÚrangezbytes=ú-r   rØ   ÚGET)rÜ   rP   )rò   rI   rä   r   rk   r(   r)   r*   r'   rD   r%   r   ÚHF_HUB_DOWNLOAD_TIMEOUTr$   rÃ   )r8   rù   rú   rÜ   rÓ   Úrr:   r:   r;   Ú_fetch_rangeÄ  s     ÿ
þûzHfFileSystemFile._fetch_ranger.   c                 C   s   t jddd�| _d S )Nzhffs-F)ÚprefixÚdelete)ÚtempfileÚNamedTemporaryFilerÚ   r}   r:   r:   r;   Ú_initiate_uploadÔ  s    z!HfFileSystemFile._initiate_uploadF)Úfinalr/   c                 C   sœ   | j  d¡ | j  ¡ }| j |¡ |r˜| j ¡  | jjj| jj	| j
j| j
j| jj| j
j| j
j| j d¡| j d¡d� t | jj	¡ | jj| j
 ¡ d� d S )Nr   ru   rv   r¾   rw   )Úbufferrå   rÀ   rÚ   Úwriterã   rò   rI   rÁ   r‡   rk   r*   r(   rE   r'   r)   rr   r4   r¦   Úremoverl   r<   )r8   r  Úblockr:   r:   r;   Ú_upload_chunk×  s&    



ø
ÿzHfFileSystemFile._upload_chunkrÈ   c              
      sv   | j dkrj|dks|dkrj| jdkrj| jj| jddd��,}| ¡ }|  jt|ƒ7  _|W  5 Q R £ S Q R X tƒ  |¡S )a)  Read remote file.

        If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems and if
        `hf_transfer` is not enabled, the file is loaded in memory directly. Otherwise, the file is downloaded to a
        temporary file and read from there.
        rm   NrÈ   r   )rF   )ro   Úlocrò   r¿   rS   rÀ   r‹   rG   )r8   ÚlengthrÂ   rŒ   rN   r:   r;   rÀ   ì  s    $zHfFileSystemFile.readc                 C   s   | j  | j¡S ©N©rò   rÓ   rS   r}   r:   r:   r;   rÓ   ú  s    zHfFileSystemFile.url)N)F)rÈ   )r=   r>   r?   rC   rA   r   rH   rø   rî   Úbytesr   r  rí   r  rÀ   rÓ   rñ   r:   r:   rN   r;   rn   ±  s   rn   c                       sv   e Zd Zdeeeee eedœ‡ fdd„Zdeedœd	d
„Zdedœdd„Z	edœdd„Z
‡ fdd„Zdd„ Z‡  ZS )rq   rm   Nr   Únone)rò   rS   ro   r)   rF   Ú
cache_typec           	   
      sà   |dkrt d|› �ƒ‚|dkr,t d|› �ƒ‚d|krDt d|› d�ƒ‚z|j||d�| _W nB tk
rš } z$d| d	d
¡krŠt|› d�ƒ|‚W 5 d }~X Y nX | j ¡ d dœ| _tƒ j|| j ¡ f|||dœ|—Ž d | _	|  d S )Nr   z:HfFileSystemStreamFile only supports block_size=0 but got r  z?HfFileSystemStreamFile only supports cache_type='none' but got ró   z;HfFileSystemStreamFile only supports reading but got mode='ú'rt   ro   r0   rô   )r‡   r�   ©ro   rF   r  )
rU   rg   rk   r¸   r4   r<   ÚdetailsrG   rH   Úresponse)	r8   rò   rS   ro   r)   rF   r  rr   rQ   rN   r:   r;   rH   ÿ  s8    
ÿþ ÿ  ÿÿzHfFileSystemStreamFile.__init__)r  Úwhencec                 C   s6   |dkr|dkrd S || j kr*|dkr*d S tdƒ‚d S )Nr   r   zCannot seek streaming HF file)r  rU   )r8   r  r  r:   r:   r;   rå     s
    zHfFileSystemStreamFile.seekrÈ   )r  c                 C   sZ  |dkr|fnd}| j d krjt| jj| jj| jj| jj| jjd�}t	d|| jj
 ¡ dtjd�| _ t| j ƒ zd| j j_| j jj|Ž }W n¼ tk
�rB   | j  ¡  t| jj| jj| jj| jj| jjd�}t	d|dd| j i| jj
 ¡ –dtjd�| _ t| j ƒ zd| j j_| j jj|Ž }W n" tk
�r<   | j  ¡  ‚ Y nX Y nX |  jt|ƒ7  _|S )	Nr   r:   rØ   rý   T)rÜ   ÚstreamrP   ÚRangez	bytes=%d-)r  r   rk   r(   r)   r*   r'   rò   rD   r%   rI   rä   r   rþ   r$   ÚrawÚdecode_contentrÀ   rï   rã   r  r‹   )r8   r  Z	read_argsrÓ   rŒ   r:   r:   r;   rÀ   %  sZ    
û
û


ûû


zHfFileSystemStreamFile.readr.   c                 C   s   | j  | j¡S r  r  r}   r:   r:   r;   rÓ   V  s    zHfFileSystemStreamFile.urlc                    s   t | dƒsd S tƒ  ¡ S rõ   rö   r}   rN   r:   r;   rø   Y  s    
zHfFileSystemStreamFile.__del__c                 C   s   t | j| j| j| j| jjffS r  )Úreopenrò   rS   ro   Ú	blocksizeÚcacher‡   r}   r:   r:   r;   rë   _  s    z!HfFileSystemStreamFile.__reduce__)rm   Nr   r  )r   )rÈ   )r=   r>   r?   rC   rA   r   rî   rH   rå   rÀ   rÓ   rø   rë   rñ   r:   r:   rN   r;   rq   þ  s"       ùù1rq   )r)   r/   c                 C   s   t  | ¡r| S t| ƒS r  )r\   rd   Ú
safe_quotert   r:   r:   r;   r7   c  s    r7   )Úsr/   c                 C   s   t | dd�S )Nr0   )Úsafe)r   )r   r:   r:   r;   r  g  s    r  )rS   re   r/   c                 C   sR   | }t |tƒr| › d�}n*t |tƒr0| › d�}nt |tƒrD| › d�}t|ƒ|‚d S )Nz (repository not found)z (revision not found)z (invalid repository id))rc   r   r   r#   r¸   )rS   re   Úmsgr:   r:   r;   ra   k  s    



ra   ©rò   rS   ro   rF   r  c                 C   s   | j ||||d�S )Nr  )r¿   r#  r:   r:   r;   r  v  s    r  c                 C   s,   | ||Ž}|  ¡ D ]\}}t|||ƒ q|S r  )ÚitemsÚsetattr)ÚclsrL   rr   Zinstance_cache_attributes_dictrò   ÚattrZcached_valuer:   r:   r;   rê   z  s    
rê   )Hr¦   Úrer  Úcollectionsr   Údataclassesr   r   r   Ú	itertoolsr   Úpathlibr   Útypingr   r	   r
   r   r   r   r   r   Úurllib.parser   r   ZfsspecZfsspec.callbacksr   r   r   Zfsspec.utilsr   Úrequestsr   r0   r   Z_commit_apir   r   Úerrorsr   r   r   Zfile_downloadr   r   Zhf_apir    r!   r"   Úutilsr#   r$   r%   ÚcompileÚVERBOSEr\   r&   ZAbstractFileSystemrC   ÚspecZAbstractBufferedFilern   rq   rA   r7   r  rï   ra   rî   r  rê   r:   r:   r:   r;   Ú<module>   sN   (ú
      }Me