a
    h3                     @   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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:   Z/var/www/html/assistant/venv/lib/python3.9/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                       sb  e Zd ZdZdZdZdddee ee	edf d fddZ
eeee ee	ee f dd	d
ZdAeee edddZdBee ddddZdCeeee ee ddddZdDeee ddddZdEee	ee ee ddddZdFee	e	ee eeeeeef f  dddZdGe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dHeee e	e	e	ee eee eeeeef f f d' fd(d)ZdIeeee dd*d+d,Zeedd-d.Z dJe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*  Z+S )KHfFileSystema8  
    Access a remote Hugging Face Hub repository as if were a local file system.

    <Tip warning={true}>

        [`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.

    </Tip>

    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tokenc                   s<   t  j|i | |ptj| _|| _t||d| _i | _d S )NrD   )	super__init__r   ZENDPOINTrE   rF   r    _api_repo_and_revision_exists_cache)r8   rE   rF   argsZstorage_options	__class__r:   r;   rH   f   s    zHfFileSystem.__init__)r'   r(   r)   r/   c              
   C   s   |||f| j vrz| jj|||tjd W n ttfyz } z4d|f| j |||f< d|f| j ||d f< W Y d }~npd }~0  ty } z0d|f| j |||f< d| j ||d f< W Y d }~n*d }~0 0 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_existx   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 v r~d|vrbtd|dd\}}tj| }ntj	}|
ddkr d|v r>|dd\}}d|v rt|}|d	ur|d	| fv rtd
|d}| }n|dd\}}nd
}|t||}| |||\}	}
|	st||
 nd	}d|dd	d }d|ddd	 }|dd }d|ddd	 }|}|}| |||\}	}
|	sVt|
ttfr|}|}| |||\}	}|	st||
 n
t||
 nV|}d
}d|v r2|dd\}}|t||}nd	}| |||\}	}|	sVtd|d	u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 ur0| d ur4| |kr4t d|  d| dn| }|S )NzRevision specified in path ("z ") and in `revision` argument ("z") are not the same.)
ValueError)rR   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   rP   _raise_file_not_foundjoin
isinstancer   r#   r6   r&   )r8   rQ   r)   rT   r'   r(   rR   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   sj    






zHfFileSystem.resolve_path)rQ   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)dircacheclearrJ   re   r<   pop_parentr*   r'   r(   r)   )r8   rQ   resolved_pathr:   r:   r;   invalidate_cache   s    

zHfFileSystem.invalidate_cacherbHfFileSystemFile)rQ   moder)   
block_sizer/   c                 K   sP   d|v rt d|dkr2t| |f|||d|S t| |f|||d|S d S )Naz/Appending to remote files is not yet supported.r   )rn   r)   ro   )rV   HfFileSystemStreamFilerm   )r8   rQ   rn   r)   ro   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(   rF   r'   r)   ru   rv   rQ   )re   rI   Zdelete_filer*   r(   rF   r'   r)   r4   rk   r<   )r8   rQ   r)   rr   rj   r:   r:   r;   _rm  s    	zHfFileSystem._rmF)rQ   	recursivemaxdepthr)   r/   c              
      s    j ||d} j||||d} fdd|D }dd |D }	d| d}
|
|rVdnd	7 }
|
|d
u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).

        <Tip warning={true}>

            Note: When possible, use `HfApi.delete_file()` for better performance.

        </Tip>

        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:   )isdirre   r*   ).0rQ   r8   r:   r;   
<listcomp>B      z#HfFileSystem.rm.<locals>.<listcomp>c                 S   s   g | ]}t |d qS ))r*   )r   )r|   r*   r:   r:   r;   r~   C  r   zDelete  zrecursively r0   Nzup to depth ru   rv   )r(   r'   rF   
operationsr)   ru   rv   rw   )re   Zexpand_pathrI   create_commitr(   r'   rF   r)   r4   rk   r<   )r8   rQ   ry   rz   r)   rr   rj   pathsZpaths_in_repor   ru   r:   r}   r;   rm"  s"    
	zHfFileSystem.rmT)rQ   detailrefreshr)   r/   c                    s   | j  |d}|  z| j f||d|}W nh ty   |jsPt d | j|  f||d|} fdd|D }t|dkrt d Y n0 |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).

        <Tip warning={true}>

            Note: When possible, use `HfApi.list_repo_tree()` for better performance.

        </Tip>

        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~   y  r   z#HfFileSystem.ls.<locals>.<listcomp>r   c                 S   s   g | ]}|d  qS r   r:   r   r:   r:   r;   r~   |  r   )re   r<   _ls_treer   r*   r_   ri   len)r8   rQ   r   r   r)   rr   rj   outr:   rw   r;   lsS  s    
zHfFileSystem.ls)rQ   ry   r   r)   expand_infoc              	      s`  j ||d}| }t|j|j|jd|jd }g }|jv r|sj| }	||	 g }
|rt	dd |	D }|r|
 }|d jvr|
|d  qxj|d  }	||	 |dd |	D  qxg }|rfdd|D }|r|
s|r\|r\tj|
| }|d	s4||ks4|t|
|v r>|d	n|  fd
d|D }jD ]$}| d	 r`j|d  q`j d  |j |d||d njj|j|j|||j|jd}|D ]}t|tr|d	 |j |jd|j|j|j|jd}n|d	 |j dd|j |jd}|d }j!|g | || q|S )Nrt   r0   r*   r-   c                 S   s   g | ]}|d  dkr|qS type	directoryr:   r|   	path_infor:   r:   r;   r~     r   z)HfFileSystem._ls_tree.<locals>.<listcomp>r   c                 S   s   g | ]}|d  dkr|qS r   r:   r   r:   r:   r;   r~     r   c                    s&   g | ]}|d  du r  |d qS )last_commitNr   )ri   r   r}   r:   r;   r~     r   r2   c                    s"   g | ]}|d    d s|qS )r   r2   )
startswithr   )common_pathr:   r;   r~     r   T)ry   r   r)   r   )ry   expandr)   r'   filer   sizer   blob_idlfsr   securityr   r   r   r   r   tree_idr   )"re   r<   r&   r'   r(   r)   r-   rf   extendr   popleftappendosrQ   commonprefixendswithr   r5   ri   r   rh   r   rI   Zlist_repo_treer*   ra   r"   r   r   r   r   r   r   
setdefault)r8   rQ   ry   r   r)   r   rj   	root_pathr   Zcached_path_infosZdirs_not_in_dircacheZdirs_to_visitdir_infoZdirs_not_expandedcommon_prefixZcached_pathtreer   Zcache_path_infoparent_pathr:   )r   r8   r;   r   ~  s    





zHfFileSystem._ls_treec                 /   s<   | j ||dd }t j|g|R i |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)re   r4   r<   rG   walk)r8   rQ   rK   rr   rL   r:   r;   r     s    zHfFileSystem.walkc                    s,   | j ||dd }t j|f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)   rt   )re   r4   r<   rG   globr8   rQ   rr   rL   r:   r;   r     s    zHfFileSystem.glob)rQ   rz   withdirsr   r   r)   r/   c                    s  |r$t  j|f|||||d|S | j||d}| }z | j|fd||jd| W n> ty   | j|fd|i|d dkr|i i ni  Y nV0 |sd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.
        )rz   r   r   r   r)   rt   T)ry   r   r)   r)   r   r   c                 S   s   g | ]}|d  dkr|qS r   r:   r   r:   r:   r;   r~   6  r   z%HfFileSystem.find.<locals>.<listcomp>r   c                 S   s   i | ]}|d  |qS r   r:   r   r:   r:   r;   
<dictcomp>;  r   z%HfFileSystem.find.<locals>.<dictcomp>c                    s   i | ]}| | qS r:   r:   )r|   r   r   r:   r;   r   @  r   N)	rG   findre   r<   r   r)   r   infosorted)r8   rQ   rz   r   r   r   r)   rr   rj   r   namesrL   r   r;   r     s2     
 

zHfFileSystem.find)path1path2r)   r/   c                 K   s,  | j ||d}| j ||d}|j|jko2|j|jk}|rd| d| }| jj|j|j|j|d||ddt|j|j|jdgd n~| j	|d	|jd}	|	
 }
W d
   n1 s0    Y  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.

        <Tip warning={true}>

            Note: When possible, use `HfApi.upload_file()` for better performance.

        </Tip>

        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   rl   NZpath_or_fileobjr*   r(   rF   r'   r)   ru   rv   rw   )re   r'   r(   rI   r   r)   r4   r   r*   openreadupload_filerF   rk   r<   )r8   r   r   r)   rr   Zresolved_path1Zresolved_path2Z	same_reporu   fcontentr:   r:   r;   cp_fileB  sD    

&

zHfFileSystem.cp_filec                 K   s*   | 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.
        r   Tr   dater   )r8   rQ   rr   r   r:   r:   r;   modified}  s    zHfFileSystem.modified)rQ   r   r)   r/   c                    s  | j |d}| |dd}|js|dddd |rx| jj|j|j|jdd	 }i  dt	|j
|j|jd
d nHd | }|s|| jvr| | || jv rڇfdd| j| D }	|	std |	d  |s du s|rĈ rĈ d du r| jj|j|j||j|jd}
|
s2t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usJ  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).

        <Tip warning={true}>

            Note: When possible, use `HfApi.get_paths_info()` or `HfApi.repo_info()`  for better performance.

        </Tip>

        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~     r   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     r   z%HfFileSystem.info.<locals>.<dictcomp>)r   r   r   )re   r<   r4   r*   rI   Zlist_repo_commitsr(   r'   r)   r!   	commit_idr   Z
created_atri   rf   r   r_   Zget_paths_infor&   r-   ra   r"   rQ   r   r   r   r   r   r   )r8   rQ   r   r)   rr   rj   r   r   r   Zout1Z
paths_infor   r   r:   )r   rQ   r;   r     s    



*

zHfFileSystem.infoc                 K   sB   z.| ddr| | | j|fi | W dS    Y dS 0 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).

        <Tip warning={true}>

            Note: When possible, use `HfApi.file_exists()` for better performance.

        </Tip>

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

        Returns:
            `bool`: True if file exists, False otherwise.
        r   FTN)r4   rk   r   r   r:   r:   r;   exists  s    
zHfFileSystem.existsc                 C   s.   z|  |d dkW S  ty(   Y dS 0 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   rQ   r:   r:   r;   r{     s    zHfFileSystem.isdirc                 C   s(   z|  |d dkW S    Y dS 0 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)   rE   z	/resolve/z/tree/r   )	re   r   r(   r*   r'   r)   rE   r{   replace)r8   rQ   rj   urlr:   r:   r;   r   2  s    

zHfFileSystem.urlr.   c              
      sd  | 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rtjtj|dd d}|du rt|d}d}| }	| j||d	}
| j||d	d
 }|| zbtt|
j|
j|
j|
j| jd|||d| j t|tr,|jndd | |	 W |r`|!  n|r^|!  0 dS )a^  
        Copy single remote file to local.

        <Tip warning={true}>

            Note: When possible, use `HfApi.hf_hub_download()` for better performance.

        </Tip>

        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'   rE   )r   	temp_fileZdisplayed_filenameexpected_sizeZresume_sizeheadersZ	_tqdm_bar)"r4   setkeysra   r   r   r   rG   get_filer   r{   r   makedirsrA   r   rQ   dirnamer   tellre   r   Zset_sizer   r   r(   r)   r*   r'   rE   rI   _build_hf_headersZtqdmseekclose)r8   ZrpathZlpathr   r   rr   r)   Zunhandled_kwargsZ
close_fileZinitial_posZresolve_remote_pathr   rL   r:   r;   r   I  sP    




zHfFileSystem.get_filec                 C   s   t ddS )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.NrV   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_transaction)N)N)rl   NN)N)FNN)TFN)FFNF)NFFFN)N)FN),r=   r>   r?   r@   Zroot_markerprotocolr   rA   r   boolrH   r   	ExceptionrP   r&   re   rk   intrs   rx   r   r   r	   r   r   r   r
   r   r   r   r   r   r   r   r   r{   r   r   r   r   propertyr   r   __classcell__r:   r:   rL   r;   rC   :   s   (
_      2 .    h*     <;"eG

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 )rm   N)fsrQ   r)   c              
      s   z|j ||d| _W nF tyZ } z.d|ddv rDt| d| W Y d }~n
d }~0 0 t j|| j fi | |  d S )Nrt   wrn   r0   B.
Make sure the repository and revision exist before writing data.)re   rj   FileNotFoundErrorr4   rG   rH   r<   )r8   r   rQ   r)   rr   rO   rL   r:   r;   rH     s    zHfFileSystemFile.__init__c                    s   t | dsd S t  S Nrj   hasattrrG   __del__r}   rL   r:   r;   r     s    
zHfFileSystemFile.__del__)startendr/   c                 C   sl   dd| d|d  i| j j }t| jj| jj| jj| jj| j j	d}t
d||dtjd}t| |jS )	Nrangezbytes=-r   r   GETi  i  i  i  )r   retry_on_status_codesrN   )r   rI   r   r   rj   r(   r)   r*   r'   rE   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   rj   r*   r(   rF   r'   r)   rr   r4   r   removerk   r<   )r8   r  blockr:   r:   r;   _upload_chunk  s&    




zHfFileSystemFile._upload_chunkr   c                    s   | j dkrv|du s|dkrv| jdkrv| jj| jddd.}| }|  jt|7  _|W  d   S 1 sl0    Y  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.
        rl   Nr   r   )ro   )rn   locr   r   rQ   r   r   rG   )r8   lengthr   r   rL   r:   r;   r     s    $"zHfFileSystemFile.readc                 C   s   | j | jS Nr   r   rQ   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:   rL   r;   rm     s   rm   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   rl   Nr   none)r   rQ   rn   r)   ro   
cache_typec           	   
      s   |dkrt d| |dkr,t d| d|v rDt d| dz|j||d| _W nD ty } z,d|d	d
v rt| d|W Y d }~n
d }~0 0 | 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   rn   r0   r   )r   r   rn   ro   r  )
rS   re   rj   r   r4   r<   detailsrG   rH   response)	r8   r   rQ   rn   r)   ro   r  rr   rO   rL   r:   r;   rH     s2    

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  rS   )r8   r  r  r:   r:   r;   r     s
    zHfFileSystemStreamFile.seekr   )r	  c                 C   sF  |dkr|fnd}| j d u rlt| jj| jj| jj| jj| jjd}t	d|| jj
 ddtjd| _ t| j  z| j jj| }W n ty.   | j   t| jj| jj| jj| jj| jjd}t	d|dd	| j i| jj
 ddtjd| _ t| j  z| j jj| }W n  ty(   | j    Y n0 Y n0 |  jt|7  _|S )
Nr   r:   r   r   r   T)r   r   streamrN   Rangez	bytes=%d-)r  r   rj   r(   r)   r*   r'   r   rE   r%   rI   r   r   r   r$   rawr   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   M  s    zHfFileSystemStreamFile.urlc                    s   t | dsd S t  S r   r   r}   rL   r:   r;   r   P  s    
zHfFileSystemStreamFile.__del__c                 C   s   t | j| j| j| j| jjffS r
  )reopenr   rQ   rn   	blocksizecacher   r}   r:   r:   r;   
__reduce__V  s    z!HfFileSystemStreamFile.__reduce__)rl   Nr   r  )r   )r   )r=   r>   r?   rC   rA   r   r   rH   r   r   r   r   r  r   r:   r:   rL   r;   rq     s"       1rq   )r)   r/   c                 C   s   t | r| S t| S r
  )rZ   rb   
safe_quotert   r:   r:   r;   r7   Z  s    r7   )sr/   c                 C   s   t | ddS )Nr0   )safe)r   )r  r:   r:   r;   r  ^  s    r  )rQ   rc   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))ra   r   r   r#   r   )rQ   rc   msgr:   r:   r;   r_   b  s    



r_   r   rQ   rn   ro   r  c                 C   s   | j ||||dS )Nr  )r   r  r:   r:   r;   r  m  s    r  )Gr   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VERBOSErZ   r&   ZAbstractFileSystemrC   specZAbstractBufferedFilerm   rq   rA   r7   r  r   r_   r   r  r:   r:   r:   r;   <module>   sL   (
      nSe