o
    0j+7                     @   s  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!e"Z#e$dZ%dZ&dddZ'eG dd dZ(e				dCdee( de)dB de)de)de)dB de)dB de*e)e)f dB de+e) dB de,e+e* e+e* e)dB f fddZ-G d d! d!eZ.G d"d# d#eZ/			dDd$d%d&e*de)dB de*e)e)f dB de)dB ddfd'd(Z0d)e*fd*d+Z1d,e*fd-d.Z2d/e*fd0d1Z3d$d%d2e)ddfd3d4Z4d$d%d5e*d6e5d2e)ddf
d7d8Z6d5e*d9e(d6e5de+e) fd:d;Z7d<e+e* d=e)de/fd>d?Z8d$d%d@e+e) d6e5de+e* fdAdBZ9dS )Ez.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                   @   s`   e Zd ZU dZeed< eed< eed< edefddZ	edefd	d
Z
edefd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                 C   sZ   t |}t|d}|dd d }t|}W d    n1 s!w   Y  | |||dS )Nrb   r   r   r   )r   openpeekr   )clsr   r   filer   sha r#   T/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/huggingface_hub/lfs.py	from_pathI   s   
zUploadInfo.from_pathdatac                 C   s&   t | }| t||d d |dS )Nr   )r   r   r   )r   digestlen)r    r&   r"   r#   r#   r$   
from_bytesQ   s   zUploadInfo.from_bytesfileobjc                 C   sD   | d}|dtj t|}| }|dtj | |||dS )Nr   r   r   )readseekioSEEK_SETr   tell)r    r*   r   r"   r   r#   r#   r$   from_fileobjV   s   
zUploadInfo.from_fileobjN)__name__
__module____qualname____doc__bytes__annotations__intclassmethodstrr%   r)   r   r0   r#   r#   r#   r$   r   6   s   
 r   upload_infostoken	repo_typerepo_idrevisionendpointheaders	transfersreturnc                 C   s  |dur|nt j}d}|t jv rt j| }| d| | d}	d|dur&|nddgdd	 | D d
d}
|dur?dt|i|
d< i tt|d|pJi }td|	||
d}t| | }|	dd}t
|tsktd|	d}t
|trw|nd}d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                 S   s   g | ]}|j  |jd qS )oidr   )r   hexr   ).0rE   r#   r#   r$   
<listcomp>   s    z'post_lfs_batch_info.<locals>.<listcomp>r   )	operationrA   objectsZ	hash_algonameref)r;   POSTr@   jsonrN   zMalformed response from serverZtransferc                 S   s   g | ]
}d |vrt |qS error)_validate_batch_actionsrK   objr#   r#   r$   rL          c                 S   s   g | ]
}d |v rt |qS rT   )_validate_batch_errorrW   r#   r#   r$   rL      rY   )r
   ZENDPOINTZREPO_TYPES_URL_PREFIXESr	   LFS_HEADERSr   r   r   rS   get
isinstancelist
ValueErrorr9   )r:   r;   r<   r=   r>   r?   r@   rA   Z
url_prefixZ	batch_urlpayloadrespZ
batch_inforN   Zchosen_transferr#   r#   r$   post_lfs_batch_info`   sB   ,



rb   c                   @   s   e Zd ZU eed< eed< dS )PayloadPartT
partNumberetagN)r1   r2   r3   r7   r6   r9   r#   r#   r#   r$   rc      s   
 rc   c                   @   s&   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.rI   partsN)r1   r2   r3   r4   r9   r6   r^   rc   r#   r#   r#   r$   rf      s   
 rf   rM   r   lfs_batch_actionc              	   C   sF  t | |d}|du rtd| j d dS |d d }t| |d d}|dur2t| |di }|d}	t|d	 |d
}
|	durjzt|	}	W n tt	fy`   td|	 dw t
| ||	|
d nt| |
d |durt| t|d	 |}td|t||d| jj | jjd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 uploadrE   verifyheader
chunk_sizehref)r?   zTMalformed response from LFS batch endpoint: `chunk_size` should be an integer. Got 'z'.)rM   rk   rl   
upload_url)rM   rn   rQ   )r;   r@   rH   rR   z: Upload successful)rV   r\   loggerdebugZpath_in_repo_validate_lfs_actionr   r7   r_   	TypeError_upload_multi_part_upload_single_partr   r   upload_infor   rJ   r   r   )rM   rh   r;   r@   r?   ri   upload_actionverify_actionrk   rl   rn   Z
verify_urlZverify_respr#   r#   r$   
lfs_upload   sD   



rx   
lfs_actionc                 C   s:   t | dtr| ddu st | dtstd| S ).validates response from the LFS batch endpointrm   rk   Nz"lfs_action is improperly formatted)r]   r\   r9   dictr_   )ry   r#   r#   r$   rq   
  s
   rq   lfs_batch_actionsc                 C   sp   t | dtrt | dtstd| di d}| di d}|dur.t| |dur6t| | S )rz   rI   r   z)lfs_batch_actions is improperly formattedri   rE   rj   N)r]   r\   r9   r7   r_   rq   )r|   rv   rw   r#   r#   r$   rV     s    rV   lfs_batch_errorc                 C   sh   t | dtrt | dtstd| d}t |tr.t |dtr.t |dts2td| S )rz   rI   r   z'lfs_batch_error is improperly formattedrU   messagecode)r]   r\   r9   r7   r_   r{   )r}   
error_infor#   r#   r$   rZ   "  s    
rZ   rn   c                 C   sH   | j dd}td||d}t| W d   dS 1 s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Z	with_tqdmPUTr&   N)as_filer   r   )rM   rn   r*   responser#   r#   r$   rt   0  s   
"rt   rk   rl   c                 C   sH   t || j|d}t| ||d}td|t|| jj td}t| dS )z@
    Uploads file using HF multipart LFS transfer protocol.
    )rk   ru   rl   )rM   sorted_parts_urlsrl   rQ   )rS   r@   N)	_get_sorted_parts_urlsru   _upload_parts_iterativelyr   _get_completion_payloadr   rJ   r[   r   )rM   rk   rl   rn   r   response_headersZcompletion_resr#   r#   r$   rs   D  s   rs   ru   c                 C   sN   dd t dd |  D dd dD }t|}|t|j| kr%td|S )Nc                 S   s   g | ]\}}|qS r#   r#   )rK   _rn   r#   r#   r$   rL   \  s    z*_get_sorted_parts_urls.<locals>.<listcomp>c                 S   s2   g | ]\}}|  rt|d krt|d|fqS )r   
   )isdigitr(   r7   )rK   Zpart_numrn   r#   r#   r$   rL   _  s    c                 S   s   | d S )Nr   r#   )tr#   r#   r$   <lambda>d  s    z(_get_sorted_parts_urls.<locals>.<lambda>)keyz0Invalid server response to upload large LFS file)sorteditemsr(   r   r   r_   )rk   ru   rl   Zsorted_part_upload_urlsZ	num_partsr#   r#   r$   r   [  s   r   r   rI   c                 C   sf   g }t | D ]'\}}|d}|d u s|dkr#td| d|d  ||d |d q||dS )Nre   rC   zInvalid etag (`z`) returned for part r   )rd   re   )rI   rg   )	enumerater\   r_   append)r   rI   rg   Zpart_numberrk   re   r#   r#   r$   r   m  s   

r   r   c           	   
   C   s   g }| j dd<}t|D ].\}}t||| |d}td||d}t| ||j W d    n1 s6w   Y  qW d    |S 1 sGw   Y  |S )NTr   )Z	seek_fromZ
read_limitr   r   )r   r   r   r   r   r   r@   )	rM   r   rl   r@   r*   Zpart_idxZpart_upload_urlZfileobj_sliceZpart_upload_resr#   r#   r$   r   |  s&   
r   )NNNN)NNN):r4   r-   recollections.abcr   dataclassesr   mathr   Zos.pathr   typingr   r   r   urllib.parser	   Zhuggingface_hubr
   utilsr   r   r   r   r   r   Z
utils._lfsr   Z	utils.shar   r   Z_commit_apir   Z
get_loggerr1   ro   compileZ	OID_REGEXZLFS_MULTIPART_UPLOAD_COMMANDr[   r   r9   r{   r^   tuplerb   rc   rf   rx   rq   rV   rZ   rt   r7   rs   r   r   r   r#   r#   r#   r$   <module>   s    

)
	V

G
