
    ~j+7                     @   d 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
 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mZmZmZmZ d
dlmZ d
dlmZmZ erd
dlm Z   ej!        e"          Z# ej$        d          Z%dZ&dddZ'e G d d                      Z(e	 	 	 	 d9dee(         de)dz  de)de)de)dz  de)dz  de*e)e)f         dz  de+e)         dz  de,e+e*         e+e*         e)dz  f         fd            Z- G d d e          Z. G d! d"e          Z/	 	 	 d:d#d$d%e*de)dz  de*e)e)f         dz  de)dz  ddfd&Z0d'e*fd(Z1d)e*fd*Z2d+e*fd,Z3d#d$d-e)ddfd.Z4d#d$d/e*d0e5d-e)ddf
d1Z6d/e*d2e(d0e5de+e)         fd3Z7d4e+e*         d5e)de/fd6Z8d#d$d7e+e)         d0e5de+e*         fd8Z9dS );z.Git LFS related type definitions and utilities    N)Iterable)	dataclass)ceil)getsize)TYPE_CHECKINGBinaryIO	TypedDict)unquote)	constants   )build_hf_headersfix_hf_endpoint_in_urlhf_raise_for_statushttp_backoffloggingvalidate_hf_hub_args)SliceFileObj)sha256sha_fileobj)CommitOperationAddz^[0-9a-f]{40}$zlfs-multipart-uploadzapplication/vnd.git-lfs+json)AcceptzContent-Typec                       e Zd ZU dZeed<   eed<   eed<   edefd            Z	edefd            Z
ed	efd
            ZdS )
UploadInfoad  
    Dataclass holding required information to determine whether a blob
    should be uploaded to the hub using the LFS protocol or the regular protocol

    Args:
        sha256 (`bytes`):
            SHA256 hash of the blob
        size (`int`):
            Size in bytes of the blob
        sample (`bytes`):
            First 512 bytes of the blob
    r   sizesamplepathc                     t          |          }t          |d          5 }|                    d          d d         }t          |          }d d d            n# 1 swxY w Y    | |||          S )Nrb   r   r   r   )r   openpeekr   )clsr   r   filer   shas         c/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/huggingface_hub/lfs.py	from_pathzUploadInfo.from_pathI   s    t}}$ 	$YYs^^DSD)Fd##C	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ sS8888s   -AA Adatac                     t          |                                          } | t          |          |d d         |          S )Nr   )r   r   r   )r   digestlen)r#   r(   r%   s      r&   
from_byteszUploadInfo.from_bytesQ   s>    Tll!!##sD		$tt*SAAAA    fileobjc                    |                     d          }|                    dt          j                   t	          |          }|                                }|                    dt          j                    | |||          S )Nr   r   r    )readseekioSEEK_SETr   tell)r#   r.   r   r%   r   s        r&   from_fileobjzUploadInfo.from_fileobjV   sp    c""Q$$$'""||~~Q$$$sS8888r-   N)__name__
__module____qualname____doc__bytes__annotations__intclassmethodstrr'   r,   r   r5    r-   r&   r   r   6   s           MMM
IIIMMM9S 9 9 9 [9 Be B B B [B 98 9 9 9 [9 9 9r-   r   upload_infostoken	repo_typerepo_idrevisionendpointheaders	transfersreturnc                 |   ||nt           j        }d}|t           j        v rt           j        |         }| d| | d}	d||nddgd | D             d	d
}
|dt          |          i|
d<   i t          t          |          |pi }t          d|	||
          }t          |           |                                }|	                    dd          }t          |t                    st          d          |	                    d          }t          |t                    r|nd}d |D             d |D             |fS )a  
    Requests the LFS batch endpoint to retrieve upload instructions

    Learn more: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md

    Args:
        upload_infos (`Iterable` of `UploadInfo`):
            `UploadInfo` for the files that are being uploaded, typically obtained
            from `CommitOperationAdd.upload_info`
        repo_type (`str`):
            Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
        repo_id (`str`):
            A namespace (user or an organization) and a repo name separated
            by a `/`.
        revision (`str`, *optional*):
            The git revision to upload to.
        headers (`dict`, *optional*):
            Additional headers to include in the request
        transfers (`list`, *optional*):
            List of transfer methods to use. Defaults to ["basic", "multipart"].

    Returns:
        `LfsBatchInfo`: 3-tuple:
            - First element is the list of upload instructions from the server
            - Second element is a list of errors, if any
            - Third element is the chosen transfer adapter if provided by the server (e.g. "basic", "multipart", "xet")

    Raises:
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If an argument is invalid or the server response is malformed.
        [`HfHubHTTPError`]
            If the server returned an error.
    N /z.git/info/lfs/objects/batchuploadbasic	multipartc                 P    g | ]#}|j                                         |j        d $S )oidr   )r   hexr   ).0rL   s     r&   
<listcomp>z'post_lfs_batch_info.<locals>.<listcomp>   sG     
 
 

  }((** 
 
 
r-   r   )	operationrG   objects	hash_algonameref)rA   POSTrF   jsonrV   zMalformed response from servertransferc                 4    g | ]}d |vt          |          S error)_validate_batch_actionsrS   objs     r&   rT   z'post_lfs_batch_info.<locals>.<listcomp>   s+    OOO#G3<N<N	 	%	%<N<N<Nr-   c                 4    g | ]}d |v t          |          S r_   )_validate_batch_errorrb   s     r&   rT   z'post_lfs_batch_info.<locals>.<listcomp>   s&    III'S..	s	#	#...r-   )r   ENDPOINTREPO_TYPES_URL_PREFIXESr
   LFS_HEADERSr   r   r   r\   get
isinstancelist
ValueErrorr>   )r@   rA   rB   rC   rD   rE   rF   rG   
url_prefix	batch_urlpayloadresp
batch_inforV   chosen_transfers                  r&   post_lfs_batch_infors   `   s   X $/xxY5GHJI5556yA
NNjN'NNNI"+"7YYg{=S
 

 '
 
 
  G  '("3"34


'
'
' =bG
 	7IIIDJnnY--Ggt$$ ;9::: nnZ00O)3OS)I)ISootO 	POOOOIIwIII r-   c                   $    e Zd ZU eed<   eed<   dS )PayloadPartT
partNumberetagN)r6   r7   r8   r<   r;   r>   r?   r-   r&   ru   ru      s"         OOO
IIIIIr-   ru   c                   4    e Zd ZU dZeed<   ee         ed<   dS )CompletionPayloadTz?Payload that will be sent to the Hub when uploading multi-part.rQ   partsN)r6   r7   r8   r9   r>   r;   rk   ru   r?   r-   r&   ry   ry      s2         II	HHHr-   ry   rU   r   lfs_batch_actionc                    t          |           |                    d          }|%t                              d| j         d           dS |d         d         }t          |           |d                             d          }|t          |           |                    di           }|                    d          }	t          |d	         |
          }
|	M	 t          |	          }	n(# t          t          f$ r t          d|	 d          w xY wt          | ||	|
           nt          | |
           |t          |           t          |d	         |          }t          d|t          ||          | j        j                                        | j        j        d          }t%          |           t                              | j         d           dS )a9  
    Handles uploading a given object to the Hub with the LFS protocol.

    Can be a No-op if the content of the file is already present on the hub large file storage.

    Args:
        operation (`CommitOperationAdd`):
            The add operation triggering this upload.
        lfs_batch_action (`dict`):
            Upload instructions from the LFS batch endpoint for this object. See [`~utils.lfs.post_lfs_batch_info`] for
            more details.
        headers (`dict`, *optional*):
            Headers to include in the request, including authentication and user agent headers.

    Raises:
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If `lfs_batch_action` is improperly formatted
        [`HfHubHTTPError`]
            If the upload resulted in an error
    actionsNzContent of file z. is already present upstream - skipping uploadrL   verifyheader
chunk_sizehref)rE   zTMalformed response from LFS batch endpoint: `chunk_size` should be an integer. Got 'z'.)rU   r   r   
upload_url)rU   r   rZ   )rA   rF   rP   r[   z: Upload successful)ra   ri   loggerdebugpath_in_repo_validate_lfs_actionr   r<   rl   	TypeError_upload_multi_part_upload_single_partr   r   upload_infor   rR   r   r   )rU   r{   rA   rF   rE   r}   upload_actionverify_actionr   r   r   
verify_urlverify_resps                r&   
lfs_uploadr      s   8 ,---""9--Gn	(>nnnooo %Y/9M'''$Y/33H==M ]+++ x,,FL))J'f(=QQQJ	ZJJI& 	 	 	ugquuu  	 	Yv*akllllliJGGGG  ]++++M&,A8LL
"$5'BBB".599;;YEZE_``	
 
 
 	K(((
LLI*???@@@@@s   C* *%D
lfs_actionc                     t          |                     d          t                    r=|                     d          7t          |                     d          t                    st	          d          | S ).validates response from the LFS batch endpointr   r   Nz"lfs_action is improperly formatted)rj   ri   r>   dictrl   )r   s    r&   r   r   
  se     	:>>&))3//?^^H%%-JNN8<T<TVZ1[1[-=>>>r-   lfs_batch_actionsc                    t          |                     d          t                    r(t          |                     d          t                    st	          d          |                     di                               d          }|                     di                               d          }|t          |           |t          |           | S )r   rQ   r   z)lfs_batch_actions is improperly formattedr}   rL   r~   )rj   ri   r>   r<   rl   r   )r   r   r   s      r&   ra   ra     s    (,,U33S99 FjIZI^I^_eIfIfhk>l>l FDEEE%)))R88<<XFFM%)))R88<<XFFM ]+++ ]+++r-   lfs_batch_errorc                    t          |                     d          t                    r(t          |                     d          t                    st	          d          |                     d          }t          |t
                    rPt          |                    d          t                    r(t          |                    d          t                    st	          d          | S )r   rQ   r   z'lfs_batch_error is improperly formattedr`   messagecode)rj   ri   r>   r<   rl   r   )r   
error_infos     r&   re   re   "  s    **511377 DJGZGZ[aGbGbdg<h<h DBCCC $$W--J:t$$Dz~~i00#66D z~~f--s33D
 BCCCr-   r   c                     |                      d          5 }t          d||          }t          |           ddd           dS # 1 swxY w Y   dS )aK  
    Uploads `fileobj` as a single PUT HTTP request (basic LFS transfer protocol)

    Args:
        upload_url (`str`):
            The URL to PUT the file to.
        fileobj:
            The file-like object holding the data to upload.

    Raises:
        [`HfHubHTTPError`]
            If the upload resulted in an error.
    T	with_tqdmPUTr(   N)as_filer   r   )rU   r   r.   responses       r&   r   r   0  s     
		T		*	* &gz@@@H%%%& & & & & & & & & & & & & & & & & &s   "AA
A
r   r   c           	          t          || j        |          }t          | ||          }t          d|t	          || j        j                                                  t                    }t          |           dS )z@
    Uploads file using HF multipart LFS transfer protocol.
    )r   r   r   )rU   sorted_parts_urlsr   rZ   )r\   rF   N)	_get_sorted_parts_urlsr   _upload_parts_iterativelyr   _get_completion_payloadr   rR   rh   r   )rU   r   r   r   r   response_headerscompletion_ress          r&   r   r   D  s    
 /f)J_lvwww 1/@Z   "$%5y7L7S7W7W7Y7YZZ	  N '''''r-   r   c                     d t          d |                                 D             d           D             }t          |          }|t          |j        |z            k    rt          d          |S )Nc                     g | ]\  }}|S r?   r?   )rS   _r   s      r&   rT   z*_get_sorted_parts_urls.<locals>.<listcomp>\  s,     
 
 
Az 	
 
 
r-   c                     g | ]>\  }}|                                 r%t          |          d k    ,t          |d          |f?S )r   
   )isdigitr+   r<   )rS   part_numr   s      r&   rT   z*_get_sorted_parts_urls.<locals>.<listcomp>_  s\       (Hj##%% +.h--!*;*; Xr""J/*;*;*;r-   c                     | d         S )Nr   r?   )ts    r&   <lambda>z(_get_sorted_parts_urls.<locals>.<lambda>d  s
    !A$ r-   )keyz0Invalid server response to upload large LFS file)sorteditemsr+   r   r   rl   )r   r   r   sorted_part_upload_urls	num_partss        r&   r   r   [  s    
 
# ,2LLNN  
 
 
 

 
 
 +,,ID)J67777KLLL""r-   r   rQ   c                     g }t          |           D ]U\  }}|                    d          }||dk    rt          d| d|dz              |                    |dz   |d           V||dS )Nrw   rJ   zInvalid etag (`z`) returned for part r   )rv   rw   )rQ   rz   )	enumerateri   rl   append)r   rQ   rz   part_numberr   rw   s         r&   r   r   m  s     "E()9:: 	
 	
Vzz&!!<42::[t[[+XY/[[\\\)Ao 	
 	
 	
 	
 '''r-   r   c                 b   g }|                      d          5 }t          |          D ]m\  }}t          |||z  |          5 }t          d||          }t	          |           |                    |j                   d d d            n# 1 swxY w Y   n	 d d d            n# 1 swxY w Y   |S )NTr   )	seek_from
read_limitr   r   )r   r   r   r   r   r   rF   )	rU   r   r   rF   r.   part_idxpart_upload_urlfileobj_slicepart_upload_ress	            r&   r   r   |  sK    G			T		*	* 
8g)23D)E)E 		8 		8%Ho$x/%   8 ".uoM"Z"Z"Z#O44467778 8 8 8 8 8 8 8 8 8 8 8 8 8 8		8
8 
8 
8 
8 
8 
8 
8 
8 
8 
8 
8 
8 
8 
8 
8 Ns5   *B$<B?B$BB$BB$$B(+B()NNNN)NNN):r9   r2   recollections.abcr   dataclassesr   mathr   os.pathr   typingr   r   r	   urllib.parser
   huggingface_hubr   utilsr   r   r   r   r   r   
utils._lfsr   	utils.shar   r   _commit_apir   
get_loggerr6   r   compile	OID_REGEXLFS_MULTIPART_UPLOAD_COMMANDrh   r   r>   r   rk   tuplers   ru   ry   r   r   ra   re   r   r<   r   r   r   r   r?   r-   r&   <module>r      s   5 4 				 				 $ $ $ $ $ $ ! ! ! ! ! !             5 5 5 5 5 5 5 5 5 5             % % % % % %                % $ $ $ $ $ * * * * * * * *  0//////		H	%	%BJ())	5  -2  &9 &9 &9 &9 &9 &9 &9 &9R   %)"&S S:&S:S S 	S
 DjS DjS #s(^d"S Cy4S 4:tDz3:-.S S S Sl    9   
        %)DA DA#DADA :DA #s(^d"	DA
 DjDA 
DA DA DA DANT    t    4    &#7 &S &T & & & &(("6 ( (RU (cf (ko ( ( ( (.#4 #j #c #VZ[^V_ # # # #$(d4j (s (GY ( ( ( (#8<S	OR	$Z     r-   