
    -:j@                        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
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jD                  d      Z#dZ$dddZ% G d d      Z&e	 	 	 	 d8d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-	 	 	 d9d"d#d$e(de'dz  de(e'e'f   dz  de'dz  ddfd%Z.d&e(fd'Z/d(e(fd)Z0d*e(fd+Z1d"d#d,e'ddfd-Z2d"d#d.e(d/e3d,e'ddf
d0Z4d.e(d1e&d/e3de)e'   fd2Z5d3e)e(   d4e'de-fd5Z6d"d#d6e)e'   d/e3de)e(   fd7Z7y):z.Git LFS related type definitions and utilities    N)Iterable)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dZ	 	 ddedededz  dedz  fdZedefd	       Z	e	j                  d
eddfd       Z	edefd       ZdefdZedefd       Zedefd       Zedefd       Zy)
UploadInfoa  
    Data structure holding required information to determine whether a blob
    should be uploaded to the hub using the LFS protocol or the regular protocol.

    The SHA256 of the blob is computed lazily: creating an `UploadInfo` from a local path only reads
    the first 512 bytes of the file. The full file is read (and hashed) only if `sha256` is accessed
    before it has been set. When a file is uploaded through the Xet protocol, the SHA256 is computed
    during upload (single read pass) and set afterwards.

    Args:
        size (`int`):
            Size in bytes of the blob
        sample (`bytes`):
            First 512 bytes of the blob
        sha256 (`bytes`, *optional*):
            SHA256 hash of the blob, if already known. Otherwise computed lazily from `source_path`.
        source_path (`str`, *optional*):
            Path to the local file the blob comes from. Required to lazily compute `sha256` if not provided.
    Nsizesampler   source_pathc                 Z    ||t        d      || _        || _        || _        || _        y )Nz2Either `sha256` or `source_path` must be provided.)
ValueErrorr   r   _sha256_source_path)selfr   r   r   r   s        U/var/www/html/tokenscope/api/venv/lib/python3.12/site-packages/huggingface_hub/lfs.py__init__zUploadInfo.__init__J   s7     >k1QRR	'    returnc                     | j                   I| j                  J t        | j                  d      5 }t        |      | _         ddd       | j                   S | j                   S # 1 sw Y   | j                   S xY w)zZSHA256 of the blob. If not set yet, reads the whole file from `source_path` to compute it.Nrb)r   r   openr   )r    files     r!   r   zUploadInfo.sha256X   sk     <<$$000d''. 1$*401||t||1||s   A""A6valuec                     || _         y )Nr   )r    r)   s     r!   r   zUploadInfo.sha256a   s	    r#   c                     | j                   duS )zVWhether the SHA256 is already known (accessing `sha256` will not trigger a file read).Nr+   )r    s    r!   	is_hashedzUploadInfo.is_hashede   s     ||4''r#   c                 x    | j                   | j                   j                         nd}d| j                   d| dS )Nz<not computed>zUploadInfo(size=z	, sha256=))r   hexr   )r    shas     r!   __repr__zUploadInfo.__repr__j   s9    $(LL$<dll BR!$))IcU!<<r#   pathc                     t        |      }t        |d      5 }|j                  d      d d }d d d         | ||      S # 1 sw Y   xY w)Nr&      )r   r   r   )r   r'   peek)clsr3   r   r(   r   s        r!   	from_pathzUploadInfo.from_pathn   sO    t}$ 	*YYs^DS)F	*V>>	* 	*s   A  A	datac                 b    t        |      j                         } | t        |      |d d |      S )Nr5   )r   r   r   )r   digestlen)r7   r9   r1   s      r!   
from_byteszUploadInfo.from_bytesu   s-    Tl!!#D	$t*SAAr#   fileobjc                     |j                  d      }|j                  dt        j                         t	        |      }|j                         }|j                  dt        j                          | |||      S )Nr5   r   )r   r   r   )readseekioSEEK_SETr   tell)r7   r>   r   r1   r   s        r!   from_fileobjzUploadInfo.from_fileobjz   sX    c"Q$'"||~Q$S88r#   )NN)__name__
__module____qualname____doc__intbytesstrr"   propertyr   setterboolr-   r2   classmethodr8   r=   r   rE    r#   r!   r   r   5   s    0  $"&(( ( 	(
 4Z(    ]]E d   (4 ( (=# = ?S ? ? Be B B 98 9 9r#   r   upload_infostoken	repo_typerepo_idrevisionendpointheaders	transfersr$   c                    ||nt         j                  }d}|t         j                  v rt         j                  |   }| d| | d}	d||nddg| D 
cg c])  }
|
j                  j	                         |
j
                  d+ c}
d	d
}|dt        |      i|d<   i t        t        |      |xs i }t        d|	||      }t        |       |j                         }|j                  dd      }t        |t              st        d      |j                  d      }t        |t               r|nd}|D cg c]  }d|vst#        |       c}|D cg c]  }d|v st%        |       c}|fS c c}
w c c}w c c}w )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`
        token (`str` or `None`):
            An authentication token (see https://huggingface.co/settings/token).
            Pass `None` to fall back to the local cached token (or no token if unauthenticated).
        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.
        endpoint (`str`, *optional*):
            The Hub endpoint to send the request to. Defaults to the value of `HF_ENDPOINT`.
        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	multipartoidr   r   )	operationrY   objects	hash_algonameref)rS   POSTrX   jsonrc   zMalformed response from servertransfererror)r
   ENDPOINTREPO_TYPES_URL_PREFIXESr   r0   r   r	   LFS_HEADERSr   r   r   ri   get
isinstancelistr   rL   _validate_batch_actions_validate_batch_error)rR   rS   rT   rU   rV   rW   rX   rY   
url_prefix	batch_urlr]   payloadresp
batch_inforc   chosen_transferobjs                    r!   post_lfs_batch_infor{      s   b $/xY5G5GHJI55566yA
*Aj\'2MNI"+"7Yg{=S '

  }}((*
 G  '("34


' =bG
 	7IDJnnY-Ggt$9:: nnZ0O)3OS)IotO 29O#G3<N	 	%O/6I'S.	s	#I 9
: 	PIs   .E+2	E0<E0	E5E5c                   "    e Zd ZU eed<   eed<   y)PayloadPartT
partNumberetagN)rF   rG   rH   rJ   __annotations__rL   rQ   r#   r!   r}   r}      s    O
Ir#   r}   c                   ,    e Zd ZU dZeed<   ee   ed<   y)CompletionPayloadTz?Payload that will be sent to the Hub when uploading multi-part.ra   partsN)rF   rG   rH   rI   rL   r   rq   r}   rQ   r#   r!   r   r      s    I	Hr#   r   rb   r   lfs_batch_actionc                 (   t        |       |j                  d      }|$t        j                  d| j                   d       y|d   d   }t        |       |d   j                  d      }|t        |       |j                  di       }|j                  d      }	t        |d	   |
      }
|		 t        |	      }	t        | ||	|
       nt        | |
       |xt        |       t        |d	   |      }t        d|t        ||      | j                  j                  j!                         | j                  j"                  d      }t%        |       t        j                  | j                   d       y# t        t        f$ r t        d|	 d      w xY w)a  
    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.
        token (`str`, *optional*):
            An authentication token (see https://huggingface.co/settings/token). Used to call the
            optional LFS verify step at the end of the upload. If `None`, falls back to the local
            cached token.
        headers (`dict`, *optional*):
            Headers to include in the request, including authentication and user agent headers.
        endpoint (`str`, *optional*):
            The Hub endpoint to send the request to. Defaults to the value of `HF_ENDPOINT`.

    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 uploadr]   verifyheader
chunk_sizehref)rW   zTMalformed response from LFS batch endpoint: `chunk_size` should be an integer. Got 'z'.)rb   r   r   
upload_url)rb   r   rg   )rS   rX   r`   rh   z: Upload successful)rr   ro   loggerdebugpath_in_repo_validate_lfs_actionr   rJ   r   	TypeError_upload_multi_part_upload_single_partr   r   upload_infor   r0   r   r   )rb   r   rS   rX   rW   r   upload_actionverify_actionr   r   r   
verify_urlverify_resps                r!   
lfs_uploadr      s   D ,-""9-G'	(>(>'??mno %Y/9M'$Y/33H=M ]+ x,FL)J'f(=QJ	ZJ
 	Yv*akliJG  ]++M&,A8L
"$5'B"..5599;YEZEZE_E_`	
 	K(
LLI**++>?@' I& 	fgqfrrtu 	s   -E2 2F
lfs_actionc                     t        | j                  d      t              r0| j                  d      *t        | j                  d      t              st	        d      | S ).validates response from the LFS batch endpointr   r   z"lfs_action is improperly formatted)rp   ro   rL   dictr   )r   s    r!   r   r   9  sK     	:>>&)3/^^H%-JNN8<TVZ1[=>>r#   lfs_batch_actionsc                 P   t        | j                  d      t              rt        | j                  d      t              st	        d      | j                  di       j                  d      }| j                  di       j                  d      }|t        |       |t        |       | S )r   ra   r   z)lfs_batch_actions is improperly formattedr   r]   r   )rp   ro   rL   rJ   r   r   )r   r   r   s      r!   rr   rr   C  s    (,,U3S9jIZI^I^_eIfhk>lDEE%)))R8<<XFM%)))R8<<XFM ]+ ]+r#   lfs_batch_errorc                 l   t        | j                  d      t              rt        | j                  d      t              st	        d      | j                  d      }t        |t
              r>t        |j                  d      t              rt        |j                  d      t              st	        d      | S )r   ra   r   z'lfs_batch_error is improperly formattedrk   messagecode)rp   ro   rL   rJ   r   r   )r   
error_infos     r!   rs   rs   Q  s    **5137JGZGZ[aGbdg<hBCC $$W-J:t$z~~i0#6z~~f-s3BCCr#   r   c                     | j                  d      5 }t        d||      }t        |       ddd       y# 1 sw Y   yxY w)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r9   N)as_filer   r   )rb   r   r>   responses       r!   r   r   _  sB     
		T		* &gz@H%& & &s   6?r   r   c           	          t        || j                  |      }t        | ||      }t        d|t	        || j                  j
                  j                               t              }t        |       y)z@
    Uploads file using HF multipart LFS transfer protocol.
    )r   r   r   )rb   sorted_parts_urlsr   rg   )ri   rX   N)	_get_sorted_parts_urlsr   _upload_parts_iterativelyr   _get_completion_payloadr   r0   rn   r   )rb   r   r   r   r   response_headerscompletion_ress          r!   r   r   s  sn    
 /f)J_J_lvw 1/@Z "$%5y7L7L7S7S7W7W7YZ	N 'r#   r   c           
      V   t        | j                         D cg c]1  \  }}|j                         rt        |      dkD  rt	        |d      |f3 c}}d       D cg c]  \  }}|	 }}}t        |      }|t        |j                  |z        k7  rt        d      |S c c}}w c c}}w )Nr   
   c                     | d   S )Nr   rQ   )ts    r!   <lambda>z(_get_sorted_parts_urls.<locals>.<lambda>  s
    !A$ r#   )keyz0Invalid server response to upload large LFS file)sorteditemsisdigitr<   rJ   r   r   r   )r   r   r   part_numr   _sorted_part_upload_urls	num_partss           r!   r   r     s     $ -3LLN(Hj##%#h-!*; Xr"J/
 

Az 	
 
 +,ID))J677KLL""
s   6B
B%r   ra   c                     g }t        |       D ]H  \  }}|j                  d      }||dk(  rt        d| d|dz          |j                  |dz   |d       J ||dS )Nr   r[   zInvalid etag (`z`) returned for part r   )r~   r   )ra   r   )	enumeratero   r   append)r   ra   r   part_numberr   r   s         r!   r   r     s     "E()9: 	
Vzz&!<42:tf4I+XY/IZ[\\)Ao	
		
 ''r#   r   c                 6   g }| j                  d      5 }t        |      D ]S  \  }}t        |||z  |      5 }t        d||      }t	        |       |j                  |j                         d d d        U 	 d d d        |S # 1 sw Y   jxY w# 1 sw Y   |S xY w)NTr   )	seek_from
read_limitr   r   )r   r   r   r   r   r   rX   )	rb   r   r   rX   r>   part_idxpart_upload_urlfileobj_slicepart_upload_ress	            r!   r   r     s     G			T		* 
8g)23D)E 		8%Ho$x/% 8 ".uoM"Z#O46678 8		8
8 N8 8
8 Ns"   #B5B-
BBBB)NNNN)NNN)8rI   rB   recollections.abcr   mathr   os.pathr   typingr   r   r   urllib.parser	   huggingface_hubr
   utilsr   r   r   r   r   r   
utils._lfsr   	utils.shar   r   _commit_apir   
get_loggerrF   r   compile	OID_REGEXLFS_MULTIPART_UPLOAD_COMMANDrn   r   rL   r   rq   tupler{   r}   r   r   r   rr   rs   r   rJ   r   r   r   r   rQ   r#   r!   <module>r      s   5 	 	 $   5 5   %  % * /			H	%BJJ()	5  -2L9 L9^   %)"&X:&X:X X 	X
 DjX DjX #s(^d"X Cy4X 4:tDz3:-.X Xv9 
  %)JA#JAJA :JA #s(^d"	JA
 DjJA 
JAZT t 4 &#7 &S &T &(("6 ( (RU (cf (ko (.#4 #j #c #VZ[^V_ #$(d4j (s (GY (#8<S	OR	$Zr#   