
    U[i              
       0   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jv                  dejx                        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j                  j                        ZG G d  d!ej                  j                        ZHd"eId#eIfd$ZJd%eId#eIfd&ZKd'eId(eeL   d#efd)ZMd*eDd'eId+eId,eNd-eIf
d.ZOd3d/ej                  d0eNd#eQfd1ZRd2 ZS eD       ZTy)4    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                   j    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	y)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                  | j                  d      | j                  z   }| j
                  r-| d| j
                   d| j                   j                  d      S | j                  t         j                  k7  r6| dt        | j                         d| j                   j                  d      S | d| j                   j                  d      S )N @/)r   REPO_TYPES_URL_PREFIXESgetr*   r+   r0   r-   rstripr,   DEFAULT_REVISIONsafe_revision)self	repo_paths     l/var/www/html/chatbot/Makanify-Chatbot-3/venv/lib/python3.12/site-packages/huggingface_hub/hf_file_system.py	unresolvez"HfFileSystemResolvedPath.unresolve4   s    5599$.."MPTP\P\\	[$"4"4!5Qt7H7H6IJQQRUVV]]i888[-">!?qARAR@ST[[\_``[$"3"3!45<<SAA    )
__name__
__module____qualname____doc__str__annotations__r   r0   r   r>    r?   r=   r)   r)   (   s?    _NLM $)E#BM8C=BB3 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                 2    t        |   |i | i | _        y N)super__init___cache)clsargskwargs	__class__s      r=   rM   z_Cached.__init__R   s    $)&) 
r?   c                    |j                  dd      } | j                  | t        j                         g|i |} | j                  | t        j                         j
                  g|i |}|s0| j                  r$|| j                  v r|| _        | j                  |   S t        j                  | g|i |}|s\| j                  rP|| j                  v rB| j                  |   j                         }|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   s:   zz/7 3==i&9&9&;MdMfM,s}}S)2G2G2I2O2OaRVaZ`aSZZ)?"CK::h'' --5d5f5CCLL-ASZZ-O!$,@!A!U!U!W)7)=)=)? 4%D+C{34%CN#C"(C||D&'*

8$Jr?   )r@   rA   rB   rC   rM   r^   __classcell__rR   s   @r=   rI   rI   B   s    r?   rI   c                   J    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d2dedee   defdZd2dee   ddfdZ	 	 	 d3dededee
   dee   ded   f
dZd2dedee   ddfdZ	 	 	 d4dede	dee
   dee   ddf
dZ	 d5dede	de	dee   deeeeeef   f      f
dZ	 	 	 	 	 d6d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d2dedee
   dee   f fd!Z	 	 	 	 	 d7d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d2d$ed%edee   ddfd&Z dede!fd'Z"d8d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d9 fd-Z)e*d.        Z+d/ Z,d0 Z-d1 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        |   |i | |xs t        j                  | _        || _        t        ||      | _        || _        || _	        i | _
        i | _        y )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__   sc     	$2/2 6I$6$6
859	$&  	, :<r?   threading_identr1   c                 (   |j                  d      xs t        j                  |d<   |j                  d      |d<   t        |      D ci c]  }|||   
 }}| |||f}t	        t        |      j                               }|j                         S c c}w )zDeterministic token for cachingrq   rr   )r7   r   rv   sortedr'   rD   encode	hexdigest)rO   rz   rP   rQ   keytokenize_argshs          r=   rV   zHfFileSystem._tokenize   s     $ZZ
3Iy7I7Iz **W-w.4Vn=s#vc{"==otV<M"))+,{{}	 >s   Br*   r+   r,   c                    |||f| j                   vrR	 | j                  j                  |||t        j                         d| j                   |||f<   d| j                   ||d f<   | j                   |||f   S # t
        t        f$ r2}d|f| j                   |||f<   d|f| j                   ||d f<   Y d }~Nd }~wt        $ r0}d|f| j                   |||f<   d| j                   ||d f<   Y d }~d }~ww xY w)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   s!    w)1U1UU^		##h)YMjMj $  Xb44i(5STS]44i$5OP33Y4RSS ,->? \W\^_W_44i(5STSXZ[S[44i$5OP( ^W\^_W_44i(5STS]44i$5OP^s#   -A6 6C.(B22C.>&C))C.pathc                    dt         t           dt         t           dt         t           fd}| j                  |      }|st        d      |j	                  d      d   dz   t
        j                  j                         v r8d|vrt        d      |j	                  dd      \  }}t
        j                  |   }nt
        j                  }|j                  d      dkD  rd	|v r|j	                  d	d      \  }}d|v rwt        j                  |      }|J|d
|j                         fv r6t        j                  d|      j                  d      }|j                         }n|j	                  dd      \  }}nd} |t!        |      |      }| j#                  |||      \  }	}
|	sJt%        ||
       n<d
}dj'                  |j	                  d      d
d       }dj'                  |j	                  d      dd
       }|j	                  d      d   }dj'                  |j	                  d      dd
       }|}|}| j#                  |||      \  }	}
|	st)        |
t*        t,        f      r)|}|}| j#                  |||      \  }	}|	sot%        ||
       nbt%        ||
       nU|}d}d	|v r(|j	                  d	d      \  }} |t!        |      |      }nd
}| j#                  |||      \  }	}|	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                 D    || | |k7  rt        d|  d| d      |S | }|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   sU     ##/4D4P$78H7IIijris t- -  O ,Or?   z0Access to repositories lists is not implemented.r5   r   r   r4   Nr3      )r0   )r   rD   _strip_protocolNotImplementedErrorsplitr   r6   valuesREPO_TYPES_MAPPINGREPO_TYPE_MODELcountSPECIAL_REFS_REVISION_REGEXsearchgroupsublstripr   r   _raise_file_not_foundjoin
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)%&XYYZZ_Q#%)J)J)Q)Q)SS$)*\]]"jja0OIt!44Y?I!11I::c?Qd{,0JJsA,>))**7>>?OPE(X$9N-N'B'F'FrK['\'c'cdg'h+0;;=(9I9O9OPSUV9W6(,#%L@IYAZ\de/3/L/LYX_ai/j,'.)$4#' ),$**S/"12E)F&.1hhtzz#qr7J.K+,0JJsOA,>)14$**S/!":M1N.0:/3/L/LYX_ai/j,'.!#(?AR'ST";'E595R5RS\^ego5p2/61$<-dC8GLd{,0JJsA,>))@IYAZ\de#' )-)F)FyRY[c)d&#Q*)*\]]'389S9S'	7Hlbrssr?   c                    |s5| j                   j                          | j                  j                          y| j                  |      }|j	                         }|r0| j                   j                  |d       | j                  |      }|r0|j                  sq| j                  j                  |j                  |j                  dfd       | j                  j                  |j                  |j                  |j                  fd       yy)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     MM!00668 --d3M **,D!!$-||D) 
 !--4488-:Q:QS`ShShjn9oquv4488",,m.C.C]E[E[\^b .r?   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  sr     $.#9Zt
!#-F< $;%&WXX?)$]4(]V\]]#D$WTHWPVWWr?   c                 N   | j                  ||      }| j                  j                  |j                  |j                  | j
                  |j                  |j                  |j                  d      |j                  d             | j                  |j                                y )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		&33!))**#--"++!::&67%zz*>? 	 	
 	=#:#:#<=r?   	recursivemaxdepthc                 X   | j                  ||      }| j                  ||||      }|D cg c]/  }| j                  |      r| j                  |      j                  1 }}|D 	cg c]  }	t	        |	       }
}	d d}||rdndz  }||d	| dndz  }| j
                  j                  |j                  |j                  | j                  |
|j                  |j                  d
|      |j                  d             | j                  |j                                yc c}w c c}	w )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,   )r-   zDelete  zrecursively r3   Nzup to depth r   r   )r+   r*   rr   
operationsr,   r   r   r   )r   expand_pathisdirr-   r   rw   create_commitr+   r*   rr   r,   r7   r   r>   )r;   r   r   r   r,   rQ   r   pathspaths_in_repor-   r   r   s               r=   rmzHfFileSystem.rmy  s3   6 ))$)B  XX` aJOh$W[WaWabfWg**40==hh[hi<+Fi
i"4&*I.2=8LL
!4RTT		!))#--**!"++!::&6G%zz*>? 	  	
 	=#:#:#<= iis   D"D"'D'detailrefreshc                    | j                  ||      }|j                         }	  | j                  |f||d|}|r|S |D cg c]  }|d   	 c}S # t        $ rx |j                  st        |d        | j                  | j                  |      f||d|}|D cg c]  }|d   |k(  s| nc c}w }}t        |      dk(  rt        |d       Y w xY wc c}w )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,   Nnamer   )r   r>   _ls_treer   r-   r   r   len)	r;   r   r   r   r,   rQ   r   outos	            r=   lszHfFileSystem.ls  s    4 ))$)B&&(		2$--SgSFSC s:c":1V9":: " 	2 --%dD1$--T 2aGhaZ`aC!7QvY$%6177C73x1}%dD1	2 #;s*   A CA
CB/*B/."CCc           
         ||n| j                   | j                   nd}| j                  ||      }|j                         }t        |j                  |j
                  |j                  d|j                        j                         }g }	|| j                  v rX|sU| j                  |   }
|	j                  |
       g }|rd}t        |
D cg c]  }|d   dk(  s||f c}      }|r|j                         \  }}|||k  ru|d   | j                  vr|j                  |d          nO| j                  |d      }
|	j                  |
       |j                  |
D cg c]  }|d   dk(  r|d	z   |f c}       |rg }|r'|	D cg c]  }|d
   	| j                  |d          }}|r|s|rC|r@t        j                  j!                  ||z         }|j#                  d      s||k(  s|t%        ||      v r|j'                  d      n| j                  |      }|"|t)        |      d  j+                  d      }||z  }|	D cg c]  }|d   j-                  |dz         r| }	}t/        | j                        D ]3  }|j-                  |dz         s| j                  j1                  |d        5 | j                  j1                  |d        |	j                  | j3                  ||d|||             |	S | j4                  j7                  |j
                  |j8                  |||j                  |j                        }|D ]  }|dz   |j                  z   }t;        |t<              r=||j>                  d|j@                  |jB                  |jD                  |jF                  d}n|dd|jH                  |jD                  d}| j                  |d         }| j                  jK                  |g       j                  |       |t)        |      d  j+                  d      }|||k  s|	j                  |        |	S c c}w c c}w c c}w c c}w )NFr   r3   r-   r0   r   r]   	directoryr   r   last_commitr5   T)r   r   r,   rt   r   )r   expandr,   r*   filer   sizer]   blob_idlfsr   securityr   r   r   r]   tree_idr   )&rt   r   r>   r)   r*   r+   r,   r0   ry   extendr   popleftappendr   osr   commonprefixendswithr	   r8   r   r   
startswithlistrU   r   rw   list_repo_treer-   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depth	path_infodirs_to_visitdir_infodirs_not_expandedr   common_prefixcommon_pathcommon_path_depthcached_pathtree
cache_pathcache_path_infoparent_paths                             r=   r   zHfFileSystem._ls_tree  s    '2KTM]M]Mi9I9Iot 	 ))$)B&&(,##!!""'55
 )+ 	 4==  $d 3JJ()#%   %9JoIiX^N_cnNneY'o! $&3&;&;&=OE8'5H+<#F+4==@0778HI04hv>N0O-JJ'89)00 6G!"(1'0'8K'G &+QY	$:!" $  !#FI$fQ}M]MeT\\!F)%<$f!$f2HY !# 4 45IL]5] ^ %--c2$	1$.BDU(VV "((- m4  '(3CIK(@(F(Fs(K% 11H"%UQQvY-A-A+PSBS-TqUU#'#6 =K"--kC.?@))+t<= !!+t4

MM#"+ $!)$/!) " 	X 
C 99++%%**#"&//'11 , D " 0	&_y~~=
i2 * ) &#,#4#4(}}'0'<'<$-$6$6'O !+ ! +#,#4#4'0'<'<'O #ll?6+BC((b9@@Q"3t9;/55c:#u'8JJ/102 
o p!" %g" Vs*   P3P3P8
P=P=?QQc              /      K   | j                  ||j                  d            j                         }t        |   |g|i |E d{    y7 w)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.walkH  sL        

:0F GQQS7<6t6v666s   AA
AAc                     | j                  ||j                  d            j                         }t        |   |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.globX  sE       

:0F GQQSw|D>8>v>>r?   withdirsc                 X   ||dk  rt        d      | j                  ||      }|j                         }	  | j                  |fd||j                  |d|}	|s|	D 
cg c]  }
|
d   dk7  s|
 }	}
n/ | j
                  |fd|j                  i|}|d   dk(  r|g|	z   n|	}	|	D 
ci c]  }
|
d	   |

 }	}
t        |	      }|s|S |D ci c]  }||	|   
 c}S c c}
w c c}
w # 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 mw xY wc c}w )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.
        r   zmaxdepth must be at least 1r   T)r   r   r,   r   r]   r   r,   r   r   )	r   r   r>   r   r,   infor   FileNotFoundErrorr|   )r;   r   r   r   r   r   r,   rQ   r   r   r   r   namesr   s                 r=   findzHfFileSystem.findh  s   @ HqL:;;))$)B&&(	.$-- $g@V@VaimsC "%BQ6k)AqBB &DIIdV]5K5KVvV	+4V+<+KykC'QT),-A1V9a<-C-sL056D#d)O66 C
 .! " 	499T?H??G6Q*CC$ 	* 7sM   "C# C-C'C	D'#	D$-"DD$DD$DD$#D$path1path2c                    | j                  ||      }| j                  ||      }|j                  |j                  k(  xr |j                  |j                  k(  }|rd| d| }| j                  j	                  |j                  |j                  |j
                  |j                  d|      |j                  dd      t        |j                  |j                  |j
                        g       n| j                  |d	|j
                        5 }	|	j                         }
d
d
d
       d| d| }| j                  j                  
|j                  |j                  | j                  |j                  |j
                  |j                  d|      |j                  d             | j                  |j                                | j                  |j                                y
# 1 sw Y   xY w)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   rbN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**58*D $$(@(@@u^E[E[_m_u_uEu 	 $UG4w7NII##&..(22'00%zz*:NK#)::.BB#G')7)D)D%3%@%@%3%<%< $  5$1H1HI #Q&&(#$UG4w7NII!! '+88&..jj(22'00%zz*:NK#)::.B#C " 	 	>#;#;#=>>#;#;#=># #s   G$$G-c                 D     | 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  s6     tyyA!@F!@M4!@AM"6**r?   c                 b   | j                  ||      }|j                         }|j                  d| j                  | j                  nd      }|j                  s~|dddd}|r=| j
                  j                  |j                  |j                  |j                        d	   }i |dt        |j                  |j                  |j                  
      d}nd}| j                  |      }	|s|	| j                  vr| j!                  |	       |	| j                  v r8| j                  |	   D 
cg c]  }
|
d   |k(  s|
 }}
|st#        |d       |d   }|s||rH|rE|d   ?| j
                  j%                  |j                  |j                  ||j                  |j                        }|st#        |d       |d   }t'        |j                  |j                  |j                  d|j(                        j                         }t+        |t,              rM|dz   |j.                  z   |j0                  d|j2                  |j4                  |j6                  |j8                  d}n,|dz   |j.                  z   dd|j:                  |j6                  d}|sdD ci c]  }|||   
 }}|J |S c c}
w c c}w )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   r   r   )r   r,   r*   r3   r   r5   r   r   r   )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,   rQ   r   rt   r   r   r   r   out1
paths_infor   r   ks                   r=   r   zHfFileSystem.info  s   * ))$)B&&(jjt/?/?/K4++QV
 )) ##	C "ii99!))]5L5LWdWmWm : ##1'119J9JQ\QgQg$ C,,t,K;dmm#C$dmm+#'==#=Sa6dARSS)$51g#++##mBTB\!YY55!))!..&*33+55 6 
 ")$5&qM	4!++!))!**!#"/"="= )+  i2 )C).. @ ) &#,#4#4(}}'0'<'<$-$6$6C !*C).. @ ! +#,#4#4'0'<'<C #.FG1c!f9GCG
W TR Hs   +J'9J'J,c                     	 |j                  dd      r| j                  |        | j                  |fi | y#  Y y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.existsQ  sC     	zz)U+%%d+DIId%f%	s   69 =c                 P    	 | j                  |      d   dk(  S # t        $ r Y y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.isdirj  s1    	99T?6*k99 		s    	%%c                 @    	 | j                  |      d   dk(  S #  Y y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  r"  s     r=   isfilezHfFileSystem.isfile|  s)    	99T?6*f44	s    c                     | j                  |      }t        |j                  |j                  |j                  |j
                  | j                        }| j                  |      r|j                  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  sn     ))$/!!&&#--"++]]
 ::d++k8Q7C
r?   c                    |j                  d      }t        |j                               dhz
  }t        |t        t
        f      rt        |      dkD  rt        |    ||f||d|S t        |      r|}n)| j                  |      rt        j                  |d       yt        |t        t        f      r4t        j                  t        j                  j!                  |      d       d}|t#        |d      }d}|j%                         }	| j'                  ||	      }
| j)                  ||	      d
   }|j+                  |       	 t-        t/        |
j0                  |
j2                  |
j4                  |
j6                  | j8                        |||d| j:                  j=                         t        |t
              r|j>                  nd       |jA                  |	       |r|jC                          yy# |r|jC                          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)  r*  rQ   r,   unhandled_kwargs
close_fileinitial_posresolve_remote_pathr1  rR   s               r=   r7  zHfFileSystem.get_file  s   $ ::j)v{{}-<(\<$@ASIYEZ]^E^ 7#E5_8W_X^__ eGZZKK-ec4[)KK.> 
?5$'GJlln #///I		%(	;FC-(	 /770990==1;;!]] "#(+		335+5h+M(--SW LL%  z s   BG1 1H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Mr?   c                     t        d      )z@Begin write transaction for deferring files, non-context versionrG  rH  rI  s    r=   start_transactionzHfFileSystem.start_transaction  s     ""LMMr?   c                 p    t         t        |       | j                  | j                  | j	                         ffS rK   )make_instancer]   rc   rd   r_   rI  s    r=   
__reduce__zHfFileSystem.__reduce__  s9    J  $$&	
 
 	
r?   c                 X    t        | j                        t        | j                        dS )N)ry   rx   )r   ry   rx   rI  s    r=   r_   z HfFileSystem._get_instance_state  s&     //78\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   r  r   r$  r'  r   r7  propertyrJ  rL  rO  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Ia ]t~Xc] d > $("&XX X SM	X
 3-X 
;	<X$> >x} >$ >   "&"&,>,> ,> 3-	,>
 3-,> 
,>^ `d&;&;!%&;7;&;OWX[}&;	eCc3h'(	)&;V  "&&*"&ww w 	w
 3-w d^w 3-wr7 7(5d3iQUVYQZAZ;[2\ 7 ? ? ?4PS9 ?& #'"&=7=7 3-=7 	=7
 =7 =7 3-=7 
tCy$sDcN233	4=7~6?S 6? 6? 6?[_ 6?p+S +x + ` `t `x} `bfgjlogobp `D2$$  . /@ B H 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                     	 |j                  ||      | _        t	        |   || j                  j                         fi | |  y # t        $ r)}d|j                  dd      v rt        | d      | d }~ww xY w)Nr   wr   r3   B.
Make sure the repository and revision exist before writing data.)r   r   r   r7   rL   rM   r>   )r;   r]  r   r,   rQ   r   rR   s         r=   rM   zHfFileSystemFile.__init__  s    	!#!ID 	T//99;FvF ! 	fjj,,'c\] 	s   A 	A9$A44A9c                 :    t        | d      sy t        | 	         S Nr   )hasattrrL   __del__r;   rR   s    r=   rd  zHfFileSystemFile.__del__  s    t_-w  r?   startendr1   c                    dd| d|dz
   i| j                   j                  j                         }t        | j                  j
                  | j                  j                  | j                  j                  | j                  j                  | j                   j                        }t        d||t        j                        }t        |       |j                  S )Nrangebytes=-r   r-  GETr3  r   )r]  rw   r<  r   r   r+   r,   r-   r*   rq   r%   r   HF_HUB_DOWNLOAD_TIMEOUTr$   r  )r;   rf  rg  r3  r'  rs         r=   _fetch_rangezHfFileSystemFile._fetch_range  s    veWAcAgY/
ggll,,.
 &&..''00''44((22WW%%
 Wi>_>_`Ayyr?   c                 <    t        j                  dd      | _        y )Nzhffs-F)prefixdelete)tempfileNamedTemporaryFiler/  rI  s    r=   _initiate_uploadz!HfFileSystemFile._initiate_upload-  s    !44GERr?   finalc                 H   | j                   j                  d       | j                   j                         }| j                  j	                  |       |rO| j                  j                          | j                  j                  j                  | j                  j                  | j                  j                  | j                  j                  | j                  j                  | j                  j                  | j                  j                  | j                   j#                  d      | j                   j#                  d             t%        j&                  | j                  j                         | j                  j)                  | j                  j+                                y y )Nr   r   r   r  r   )bufferr>  r  r/  writer?  r]  rw   r  r   r   r-   r+   rr   r*   r,   rQ   r7   r   remover   r>   )r;   rw  blocks      r=   _upload_chunkzHfFileSystemFile._upload_chunk0  s"     "U#NN  "GGLL$$ $ 3 3!//<<**22ggmm,,66++44#{{/?@#';;??3G#H % 	 IIdnn))*GG$$''113 %  r?   c                 H   | j                   dk(  rx||dk(  rq| j                  dk(  rb| j                  j                  | j                  dd      5 }|j                         }| xj                  t        |      z  c_        |cddd       S t        |   |      S # 1 sw Y   xY w)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   locr]  r  r   r  r   rL   )r;   lengthr  r   rR   s       r=   r  zHfFileSystemFile.readE  s     99&.FbLdhhRSmdii!< ffhCH$  w|F##	 s   0BB!c                 L    | j                   j                  | j                        S rK   r]  r'  r   rI  s    r=   r'  zHfFileSystemFile.urlR      ww{{499%%r?   rK   rQ  )Fr  )r@   rA   rB   ro   rD   r   rM   rd  rU  bytesrp  rv  rT  r}  r  r'  rl   rm   s   @r=   r   r   
  sj    
< 
s 
hsm 
!# C E  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efdZ
 fdZd Zd Z xZS )r   r]  r   r   r,   rs   
cache_typec                    |dk7  rt        d|       |dk7  rt        d|       d|v rt        d| d      	 |j                  ||      | _        | j                  j                         d d| _        t        	|    || j                  j                         f|||d| d | _	        |  t               | _        y # t        $ r-}d|j	                  d	d
      v rt        | d      |Y d }~d }~ww xY w)Nr   z:HfFileSystemStreamFile only supports block_size=0 but got nonez?HfFileSystemStreamFile only supports cache_type='none' but got r_  z;HfFileSystemStreamFile only supports reading but got mode=''r   r   r3   r`  )r   r   r   rs   r  )r   r   r   r   r7   r>   detailsrL   rM   responser   _exit_stack)
r;   r]  r   r   r,   rs   r  rQ   r   rR   s
            r=   rM   zHfFileSystemStreamFile.__init__W  s%    ?YZdYefgg^_i^jkll$;Z[_Z``abcc	!#!ID !% 2 2 < < >M"",,.	
59j]g	
kq	
 37$; ! 	fjj,,'c\] -	s   B< <	C2#C--C2r  whencec                 X    |dk(  r|dk(  ry || j                   k(  r|dk(  ry t        d      )Nr   r   zCannot seek streaming HF file)r  r   )r;   r  r  s      r=   r>  zHfFileSystemStreamFile.seekw  s2    !8!$((?v{899r?   r  c                 ^   | j                   | j                          d}	 	 | j                   yt        | j                   |      }| xj                  t	        |      z  c_        |S # t
        $ r> | j                   | j                   j                          |r | j                          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.
        FTr?   )r  _open_connection_partial_readr  r   rX  r?  )r;   r  retried_oncer   s       r=   r  zHfFileSystemStreamFile.read~  s     == !!#$==(#DMM6:CH$
 $==,MM'')%%'#$ s   A$ 5A$ $AB+*B+r1   c                 L    | j                   j                  | j                        S rK   r  rI  s    r=   r'  zHfFileSystemStreamFile.url  r  r?   c                 n    t        | d      sy | j                  j                          t        |          S rb  )rc  r  r?  rL   rd  re  s    r=   rd  zHfFileSystemStreamFile.__del__  s/    t_- w  r?   c                     t         | j                  | j                  | j                  | j                  | j
                  j                  ffS rK   )reopenr]  r   r   	blocksizecacher   rI  s    r=   rO  z!HfFileSystemStreamFile.__reduce__  s0    DIIt~~tzzWWWr?   c                    t        | j                  j                  | j                  j                  | j                  j                  | j                  j
                  | j                  j                        }| j                  j                  j                         }| j                  dkD  rd| j                   d|d<   | j                  j                  t        d||t        j                              | _        	 t#        | j                          y	# t$        $ r+}|j                   j&                  dk(  rd	| _        Y d	}~y	 d	}~ww xY w)
z%Open a connection to the remote file.r-  r   rj  rk  Rangerl  rm  i  N)r   r   r+   r,   r-   r*   r]  rq   rw   r<  r  r  enter_contextr&   r   rn  r  r$   r   status_code)r;   r'  r3  r   s       r=   r  z'HfFileSystemStreamFile._open_connection  s   &&..''00''44((22WW%%
 '',,00288a<!'z3GG((66!99	
	. 	zz%%, $	s   7D 	E D<;D<<E)r  Nr   r  )r   r  )r@   rA   rB   ro   rD   r   rU  rM   r>  r  r'  rd  rO  r  rl   rm   s   @r=   r   r   V  s    
 "& '' ' 	'
 3-' ' '@: :S :$3 $8&S &!Xr?   r   r,   r1   c                 F    t         j                  |       r| S t        |       S rK   )r   r   
safe_quoter   s    r=   r:   r:     s     288B8\
S[H\\r?   sc                     t        | d      S )Nr3   )safe)r   )r  s    r=   r  r    s    r?   r   r   c                     | }t        |t              r|  d}n+t        |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#./-.	C.	/+,	C*	+./
C
 c)r?   r]  r   rs   r  c                 ,    | j                  ||||      S )Nr  )r  )r]  r   r   rs   r  s        r=   r  r    s    774dzj7QQr?   r  r  c                 P   t               }|dk  rt        d      |dk(  ry|dk(  r1| j                         D ]  }|j                  |        t	        |      S | j                  |      D ]1  }|j                  |       t        |      |k\  s#t	        |d|       c S  t	        |      S )zb
    Read up to `length` bytes from a streamed response.
    If length == -1, read until EOF.
    r  zlength must be -1 or >= 0r   r?   )
chunk_sizeN)	bytearrayr   
iter_bytesr   r  r   )r  r  bufchunks       r=   r  r    s    
 +C{455{|((* 	EJJu	Sz$$$7 '

5s8vWf&&'
 :r?   c                 `     | |i |}|j                         D ]  \  }}t        |||        |S rK   )r`   ra   )rO   rP   rQ   ri   r]  rj   rk   s          r=   rN  rN    s?    	d	f	B+113 'kD+&'Ir?   r  )Ur   rert  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  rX  r   rU  r  Responser  r  rN  hffsrF   r?   r=   <module>r     s   	 	       (    ; ; '   J J #  C f f / 3 3 \ \ ' )bjj
 JJ  B B B, 223c 3/l /dS
6,, S
lI&v{{77 I&XmV[[== m`]C ]C ]# # * *(9*= *( *R| R3 Rc Rs RPS RENN C  . ~r?   