o
    *j#                     @   s   d dl m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 d dlmZmZmZ d dlmZ e Zd	Zd
ZdZdZdZdZdd ZG dd dZdS )    )print_functionN)hash_url_to_filename)HubApi)DataDownloadConfig)MS_CACHE_HOME)"DEFAULT_DATA_ACCELERATION_ENDPOINTMetaDataFields
UploadMode)
get_loggerZAccessIdZAccessSecretZSecurityTokenBucketZ	BackupDirZDirc                    s:   ddl m} ddlm  G  fddd|}| S )zCreate a credentials provider for oss2 with lazy import.

    Returns an instance that subclasses oss2.CredentialsProvider so that the
    oss2 SDK can call ``get_credentials()`` automatically when the token
    expires or authentication is needed.
    r   )CredentialsProviderCredentialsc                       s*   e Zd ZfddZ fddZdS )z?_create_credential_provider.<locals>._CredentialProviderWrapperc                    s&    | _ | _| _| _t | _d S )N)apidataset_name	namespacerevision	threadingLock_lock)selfr   r   r   r    f/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/msdatasets/utils/oss_utils.py__init__'   s
   zH_create_credential_provider.<locals>._CredentialProviderWrapper.__init__c                    s^   | j " | jj| j| jd| jd} |t |t |t dW  d   S 1 s(w   Y  dS )ztoss2 SDK will call this method automatically when it finds
            the token is expired or needs authentication.Fr   r   Zcheck_cookier   )Zaccess_key_idZaccess_key_secretZsecurity_tokenN)	r   r   !get_dataset_access_config_sessionr   r   r   	ACCESS_IDACCESS_SECRETSECURITY_TOKEN)r   
oss_configr   r   r   get_credentials.   s   $zO_create_credential_provider.<locals>._CredentialProviderWrapper.get_credentialsN)__name__
__module____qualname__r   r!   r   r   r   r   r   r   r   r   _CredentialProviderWrapper%   s    r&   )oss2r   Zoss2.credentialsr   )r   r   r   r   r   r&   r   r%   r   _create_credential_provider   s   r(   c                
   @   sX   e Zd ZdZdd Zedd Zdededefd	d
Z	dedede
dedef
ddZdS )OssUtilitiesz`
    A utility class for handling Alibaba Cloud OSS operations such as upload and download.
    c                 C   s  || _ || _|| _t | _| jj| j | jd| jd}tddkr%t| _	n	d|d  d| _	tj
td| _t | _d	| _d
| _d| _ddl}|j| jd| _|j| jd| _t| j| j | j| jd}||}|t | _|j|| j	| j|d dd| _|t  | _!|t" | _#dS )zh
        Initializes the OssUtilities with the given OSS configuration and dataset information.
        Fr   ZENABLE_DATASET_ACCELERATIONTruezhttps://Regionz.aliyuncs.comztmp/resumable_storei   i      r   N)rootr   zoss-)authendpointbucket_nameregion)$r   r   r   r   r   r   osgetenvr   r/   pathjoinr   Zresumable_store_root_pathmultiprocessing	cpu_countnum_threads	part_sizemultipart_thresholdmax_retriesr'   ZResumableDownloadStoreresumable_store_downloadZResumableStoreresumable_store_uploadr(   ZProviderAuthV4BUCKETr0   r   lstripbucketDIRoss_dirBACK_DIRoss_backup_dir)r   r   r   r   r    r'   Zcredential_providerr.   r   r   r   r   F   sV   



zOssUtilities.__init__c                 C   s8   |rt dt| t|  }td|ddd d S d S )Nd   z{0}%  T)endflush)intfloatprintformat)Zconsumed_bytestotal_bytesZrater   r   r   _percentagey   s   zOssUtilities._percentageoss_file_namedownload_configreturnc              
   C   s<  |j }tj| j|}tj| j|}|j}d}|r(|j|}|r(|t	j
}d}	ddl}
	 z;|r5|}n
| j|r=|n|}t|dd}tj||}|jsUtj|sh|
j| j||| j| j| j| j| jd W |S  ty } z&td| d| d	 |	d
7 }	|	| jkrtd| d |W Y d}~nd}~ww q/)a<  
        Downloads a file from OSS to the local cache.

        Args:
            oss_file_name (str): The name of the file in OSS to download.
            download_config (DataDownloadConfig): Configuration for the download process.

        Returns:
            str: The local path to the downloaded file.
        Fr   NT)etag)r@   keyfilenamestoreZmultiget_thresholdr9   progress_callbackr8   zError downloading : , trying again...   zFailed to download  due to exceeded retries.)	cache_dirr2   r4   r5   rB   rD   splitZmeta_args_mapgetr   ZARGS_BIG_DATAr'   r@   object_existsr   Zforce_downloadexistsZresumable_downloadr<   r:   r9   rN   r8   	Exceptionloggerwarningr;   error)r   rO   rP   r[   Zcandidate_keyZcandidate_key_backupr\   Zbig_dataZ	args_dictretry_countr'   Zfile_oss_keyrT   Z
local_pather   r   r   download   sf   	

zOssUtilities.downloadoss_object_namelocal_file_pathindicate_individual_progressupload_modec              
   C   s   d}t j| j|}|r| j}nd}ddl}	 z2| j|}	|tj	kr5|	r5t
d| d|j d W |S |j| j||| j| j| j|| jd W |S  ty{ }
 z&t
d| d	|
 d
 |d7 }|| jkrqt
d| d |
W Y d}
~
nd}
~
ww q)a  
        Uploads a local file to OSS.

        Args:
            oss_object_name (str): The name of the object in OSS.
            local_file_path (str): The local file path to upload.
            indicate_individual_progress (bool): Whether to show individual progress.
            upload_mode (UploadMode): The upload mode (e.g., OVERWRITE, APPEND).

        Returns:
            str: The OSS object key where the file is uploaded.
        r   NTzSkip z in case of z mode.)r@   rS   rT   rU   r:   r9   rV   r8   zError uploading rW   rX   rY   zFailed to upload rZ   )r2   r4   r5   rB   rN   r'   r@   r^   r	   APPENDra   infovalueZresumable_uploadr=   r:   r9   r8   r`   rb   r;   rc   )r   rg   rh   ri   rj   rd   Z
object_keyrV   r'   existre   r   r   r   upload   sR   	

zOssUtilities.uploadN)r"   r#   r$   __doc__r   staticmethodrN   strr   rf   boolr	   ro   r   r   r   r   r)   A   s"    3


=r)   )
__future__r   r6   r2   r   Zdatasets.utils.file_utilsr   Zmodelscope.hub.apir   Z.modelscope.msdatasets.download.download_configr   Zmodelscope.utils.config_dsr   Zmodelscope.utils.constantr   r   r	   Zmodelscope.utils.loggerr
   ra   r   r   r   r>   rC   rA   r(   r)   r   r   r   r   <module>   s&   &