
    uj~                       d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	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 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 m!Z!m"Z"m#Z# d d	l$m%Z% d dl&Z&d dl'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l0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^ d dl_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZi d dljmkZk d dllmmZmmnZn d dlompZp d dlqmrZr d dlsmtZt d dlumvZvmwZwmxZxmyZy d dlzm{Z{ d dl|m}Z}m~Z~mZmZmZmZmZ d dlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZmZmZ d dlmZ d dlmZmZmZmZmZmZmZmZ  e            ZdedefdZ G d d           Z G d! d"          Z G d# d$          Z G d% d&          ZdS )'    N)defaultdict)ThreadPoolExecutor)
HTTPStatus)	CookieJar)
expanduserPath)	AnyBinaryIODictIterableListLiteralOptionalTupleUnion)	urlencode)Session)HTTPAdapterRetry)	HTTPErrortqdm).API_HTTP_CLIENT_MAX_RETRIESAPI_HTTP_CLIENT_TIMEOUTAPI_RESPONSE_FIELD_DATAAPI_RESPONSE_FIELD_EMAIL#API_RESPONSE_FIELD_GIT_ACCESS_TOKENAPI_RESPONSE_FIELD_MESSAGEAPI_RESPONSE_FIELD_USERNAMEDEFAULT_MAX_WORKERSDEFAULT_MODELSCOPE_INTL_DOMAINMODELSCOPE_CLOUD_ENVIRONMENTMODELSCOPE_CLOUD_USERNAMEMODELSCOPE_CREDENTIALS_PATHMODELSCOPE_DOMAINMODELSCOPE_PREFER_AI_SITEMODELSCOPE_REQUEST_IDMODELSCOPE_URL_SCHEMEONE_YEAR_SECONDSREQUESTS_API_HTTP_METHODTEMPORARY_FOLDER_NAMEUPLOAD_ADAPTIVE_BATCH_SIZEUPLOAD_BLOB_MAX_RETRIESUPLOAD_BLOB_RETRY_BACKOFFUPLOAD_BLOB_RETRY_MAX_WAITUPLOAD_BLOB_TIMEOUT"UPLOAD_BLOB_TQDM_DISABLE_THRESHOLDUPLOAD_COMMIT_BATCH_SIZEUPLOAD_FAILED_FILE_MAX_RETRIESUPLOAD_MAX_FILE_COUNTUPLOAD_MAX_FILE_COUNT_IN_DIRUPLOAD_MAX_FILE_SIZE#UPLOAD_NORMAL_FILE_SIZE_TOTAL_LIMIT!UPLOAD_REACT_BACKOFF_MAX_EXPONENTUPLOAD_REACT_ENABLEDUPLOAD_REACT_MAX_DELAYUPLOAD_REACT_ROUND2_BASE_DELAYUPLOAD_REACT_ROUND3_FILE_DELAYUPLOAD_RETRY_ALLOWED_METHODS$UPLOAD_SIZE_THRESHOLD_TO_ENFORCE_LFSUPLOAD_USE_CACHEUPLOAD_VALIDATE_BLOB_BATCH_SIZEVALID_SORT_KEYSDatasetVisibilityLicensesModelVisibility
VisibilityVisibilityMap)
InvalidParameterNotExistErrorNotLoginExceptionRequestErrordatahub_raise_on_errorhandle_http_post_errorhandle_http_responseis_okraise_for_http_statusraise_on_error)GitCommandWrapper)DatasetInfo	ModelInfo
Repository)UPLOAD_HASH_CACHE_FILE)BatchTracker)_LEGACY_PROGRESS_FILENullTrackerUploadTrackerclassify_error)	AigcModel)add_content_to_file
get_domainget_endpointget_readable_folder_sizeget_release_datetimeis_env_truemodel_id_to_group_owner_name)DEFAULT_DATASET_REVISIONDEFAULT_MODEL_REVISIONDEFAULT_REPOSITORY_REVISIONMASTER_MODEL_BRANCHMETA_FILES_FORMATREPO_TYPE_DATASETREPO_TYPE_MODELREPO_TYPE_SUPPORTConfigFieldsDatasetFormationsDatasetMetaFormatsDownloadChannelDownloadMode
Frameworks	ModelFileTasksVirgoDatasetConfig)compute_file_hashget_file_sizeis_relative_path)
get_logger)DATASET_LFS_SUFFIXDEFAULT_IGNORE_PATTERNSMODEL_LFS_SUFFIXCommitHistoryResponse
CommitInfoCommitOperationCommitOperationAdd	RepoUtilstotal_filesreturnc                     | dk    rdS | dk    r| S | dk    rt          d| dz            S | dk    r!t          dt          d| dz                      S d	S )
a  Calculate optimal commit batch size based on total file count.

    Adaptive strategy ensures batch granularity scales with workload:
    - Very few files (1-10): no splitting, single batch
    - Few files (11-100): ~10 batches for failure isolation
    - Medium (101-10K): 64-256 files per batch
    - Large (>10K): 512 files per batch to limit commit frequency

    Args:
        total_files: Total number of files (including checkpoint-skipped).

    Returns:
        Recommended batch size (>= 1).
    r      
   d   i'  @      P   i   )maxmin)r   s    b/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/modelscope/hub/api.py_calculate_adaptive_batch_sizer   v   st     aqbc1kR'(((f2s3r 1223333    c                   <    e Zd ZdZd ZddZed             Zd ZdS )	_CountedReadStreamzFile wrapper that counts bytes read and updates a progress bar.

    Unlike a generator, this is a file-like object that requests can
    use with Content-Length header for transfer integrity verification.
    c                 L    || _         || _        || _        || _        d| _        d S Nr   )_file_expected_size_pbar_chunk_size_bytes_read)selffile_objexpected_sizepbar
chunk_sizes        r   __init__z_CountedReadStream.__init__   s.    
+
%r   c                     |dk     r| j         nt          || j                   }| j                            |          }|r9t	          |          }| xj        |z  c_        | j                            |           |S )z-Read a chunk from the underlying file object.r   )r   r   r   readlenr   r   update)r   size	read_sizechunkns        r   r   z_CountedReadStream.read   sy    (,qD$$c$@P6Q6Q	
	** 	!E

A!Ja   r   c                     | j         S )zTotal bytes read so far.)r   r   s    r   
bytes_readz_CountedReadStream.bytes_read   s     r   c                 f    | j         | j        k    r t          d| j          d| j         d          dS )z9Raise IOError if bytes read does not match expected size.zUpload data incomplete: read z bytes, expected z2 bytes. File may have been modified during upload.N)r   r   IOErrorr   s    r   verify_completez"_CountedReadStream.verify_complete   sV    t222>0@ > > /> > >? ? ? 32r   N)r   )	__name__
__module____qualname____doc__r   r   propertyr   r    r   r   r   r      sk                   X ? ? ? ? ?r   r   c                      e Zd ZU dZdeedfdee         dee         fdZdefdZ	ddee         d	ee
         fd
Z	 	 ddee         dee         fdZej        ej        dddddfdedee         dee         dee         dee         dee         dee         ded         defdZ	 	 	 ddededee         dee         ded         defdZddedee         dee         fdZddedee         fdZeddfdedee         dee         dee         def
dZddddedee         dee         defdZedd dedee         dee         defd!Zddd dedee         dee         defd"Zeedd#dedee         dee         dee         deeef         f
d$Z ddddd%dedee         dee         d&ee
         dee         de
fd'Z!	 	 ddededee         dee         fd(Z"e#d)             Z$ej        ej        dd*de%ddddf
ded+edee         dee         dee         d,ee         d-ee         dee         dee         d.eee&e         ef                  d/eeee&e         f                  dee         fd0Z'	 	 	 	 dd3ed4ee         d5ee         dee         dee         defd6Z(d1d2ddddd7d3ed4ee         d5ee         d8ee         d9ee         dee         dee         defd:Z)dd;ee
e*f         de*fd<Z+	 	 dded=ee         d;ee
e*f         de&e         fd>Z,	 	 	 dded=ee         d;ee
e*f         dee         de&e         f
d?Z-d@ Z.	 	 	 ddedAee*         dee         fdBZ/	 	 	 ddedAee*         dee         fdCZ0	 	 dded;ee
e*f         dee         de1e&e         e&e         f         fdDZ2	 dded;ee
e*f         de1e&e         e&e         f         fdEZ3edddi dfdedee         dFee         dGee
         d;ee
e*f         dHee         dee         de&e         fdIZ4dddJdedKedee         dee         fdLZ5dej        e6j        dddfdMedNedee         dee         dee         dOee         dee         dee         defdPZ7	 	 ddQedee         dee         fdRZ8i Z9ee:dS<   	 	 ddMedNedee         dee         fdTZ;	 	 	 	 	 ddMedNededWedGe
d4ed5edee         dee         fdXZ<ee%d1dYdddZdedee         dee         d4ed5edee         dee         fd[Z=e%d\dUd1dVdddd]dededWedGe
d4ed5edee         dee         d^ee         fd_Z>e%ddfdQedee         dee         dee         fd`Z?	 	 ddMedNedQededee         dee         fdaZ@e#dbedcefdd            ZA	 	 ddMedNededcedbedeeBdee         dee         fdfZCe#dgeDjE        dfdee         fdh            ZFeGddUdfdiedMedNedee         djee
         dkee
         dee         fdlZHeGdfdiedMedNedee         dee         f
dmZIeGddfdMedNedee         dee         dee         f
dnZJeGddfdMedNedoe
dee         dee         dee         fdpZKddQedqedee         defdrZL	 	 ddMedNededsedee         dee         fdtZM	 	 ddee         dee         fduZN	 	 ddvedMedNededee         dee         defdwZO	 	 ddvedMedNededee         dee         defdxZPddee         fdyZQ	 	 ddMedNedze
dee         dee         ddfd{ZRd| ZS	 	 ddee         d}e
deTeef         fd~ZUe#dddeTeeVf         fd            ZWddedee         defdZXdeYj        edej        dddUdd	dedeee
df         dee         dee         dee         dee         dee         dee
         dee
         deeZ         defdZ[ddee%dddede\e]         d,edee         dedee         dee         dee         de^fdZ_deddddde%ddeee`eaebf         dededeedf         dee         d,ee         dee         dee         dee         dee
         dee         de^fdZcd Zdd ZeddddedededededefdZfddee%ddded,edee         dedededede^fdZgdeBdedeBfdZhddddeddeieje%d
dedeee`e&e         e&e`         f         dee         d,ee         dee         deedf         dee         deee&e         ef                  deee&e         ef                  dede
dee         deee^e&e^         f                  fdZkd Zldddddddededededeee`eaebf         dee
         dee         dee         dee         defdZmddddedede&eTeeVf                  dee         dee         deTeee         f         fdZn	 	 ddeee`e&e         e&e`         f         dedeee&e         ef                  deee&e         ef                  de&eeoeBf                  f
dZpe#de\e]         d,edeTeeVf         fd            ZqdderfdZseddddededeee&e         f         dee         dee         dee         deTeeVf         fdZt	 ddedeud         deud         deedf         def
dZv	 	 	 	 ddeded4ed5edee         defdZw	 	 ddedee         dee         defdZxdS )HubApizModel hub api interface.
    Nendpointtokenc                    ||nt                      | _        || _        dt                                          i| _        t                      | _        t          |ddddt          d          }t          |          }| j                            d|           | j                            d	|           t          D ]?}t          | j        |t          j        t!          | j        |          |
                     @t#                      | _        dS )u   The ModelScope HubApi。

        Args:
            endpoint (str, optional): The modelscope server http|https address. Defaults to None.
        N
user-agent   )  i  i  i  T)totalr   connectbackoff_factorstatus_forcelistallowed_methodsrespect_retry_after_header)max_retrieszhttp://zhttps://timeout)r`   r   r   ModelScopeConfigget_user_agentheadersr   sessionr   r>   r   mountr+   setattr	functoolspartialgetattrUploadingCheckupload_checker)r   r   r   r   r   retryadaptermethods           r   r   zHubApi.__init__   s    %-$8lnn
$&6&E&E&G&GHyy18'+
 
 
 %0009g...:w///. 	& 	&Ff!DL&11#% % %& & & & -..r   access_tokenc                     ddl m} ddlm} | j        r || j                  j        nt                      } |            }|                    d||d           |S )z
        Get jar cookies for authentication from access_token.

        Args:
            access_token (str): user access token on ModelScope.

        Returns:
            jar (CookieJar): cookies for authentication.
        r   )RequestsCookieJar)urlparsem_session_id/)domainpath)requests.cookiesr   urllib.parser   r   netlocr_   set)r   r   r   r   r   jars         r   _get_cookieszHubApi._get_cookies   s     	766666))))))8<Whht}--44:<<!! 	 	 	 	 
r   Fcookies_requiredc                     |p%| j         pt          j                            d          }|r|                     |          }nt
                                          }||rt          d          |S )a  
        Get cookies for authentication from local cache or access_token.

        Args:
            access_token (Optional[str]): user access token on ModelScope. If not provided, try to get from local cache.
            cookies_required (bool): whether to raise error if no cookies found, defaults to `False`.

        Returns:
            cookies (CookieJar): cookies for authentication.

        Raises:
            ValueError: If no credentials found and cookies_required is True.
        MODELSCOPE_API_TOKENr   NzNo credentials found.You can pass the `--token` argument, or use HubApi().login(access_token=`your_sdk_token`). Your token is available at https://modelscope.cn/my/myaccesstoken)r   osenvirongetr   r   get_cookies
ValueError)r   r   r   r   cookiess        r   r   zHubApi.get_cookies   s~     T
Tbjnn=S.T.T 	5''U';;GG&2244G?/?T   r   c                    |p%| j         pt          j                            d          }|sdS |s| j        }| d}| j                            |d|i|                     | j                            }t          |           |
                                }t          |           |t                   t                   }|j        }t                              |           t                              |           t                              |t                   t&                   |t                   t(                              |t                   t                   |fS )a|  Login with your SDK access token, which can be obtained from
           https://www.modelscope.cn user center.

        Args:
            access_token (str): user access token on modelscope, set this argument or set `MODELSCOPE_API_TOKEN`.
            If neither of the tokens exist, login will directly return.
            endpoint: the endpoint to use, default to None to use endpoint specified in the class

        Returns:
            cookies: to authenticate yourself to ModelScope open-api
            git_token: token to access your git repository.

        Note:
            You only have to login once within 30 days.
        r   NNz/api/v1/loginAccessToken)jsonr   )r   r   r   r   r   r   postbuilder_headersr   rP   r   rQ   r   r   r   r   
save_tokensave_cookiessave_user_infor    r   )r   r   r   r   rdr   r   s           r   loginzHubApi.login  sN   ( $[tz[RZ^^DZ5[5[ 	: 	%}H)))L.((66  8 8 	a   FFHHq)*+NO) 	##E***%%g...''%&'BC%&'?@	B 	B 	B ()/129: 	:r    model_id
visibilitylicensechinese_nameoriginal_model_id
aigc_modelr]   r   c	                    |t          d          |                     |d          }	|s| j        }t          |          \  }
}|
|||||t          j                            dd          d}|| d}|                    |	|                     | j	                  |	           |
                    |j        |j        |j        |j        |j        |j        p||j        |j        |j        |j        |j        |j        |j        d
           |j        r
|j        |d<   n| d}|                     | j	                  }t3          j        d          d         }|                    d                              d|           rd|d<   | j                            |||	|          }t?          |           |                                 }tC          |           | d| }||"                    | ||           |S )a  Create model repo at ModelScope Hub.

        Args:
            model_id (str): The model id in format {owner}/{name}
            visibility (int, optional): visibility of the model(1-private, 5-public), default 5.
            license (str, optional): license of the model, default apache-2.0.
            chinese_name (str, optional): chinese name of the model.
            original_model_id (str, optional): the base model id which this model is trained from
            endpoint: the endpoint to use, default to None to use endpoint specified in the class
            token (str, optional): access token for authentication
            aigc_model (AigcModel, optional): AigcModel instance for AIGC model creation.
                If provided, will create an AIGC model with automatic file upload.
                Refer to modelscope.hub.utils.aigc.AigcModel for details.

        Returns:
            str: URL of the created model repository

        Raises:
            InvalidParameter: If model_id is invalid or required AIGC parameters are missing.
            ValueError: If not login.

        Note:
            model_id = {owner}/{name}
        Nmodel_id is required!Tr   r   MODELSCOPE_TRAIN_IDr   )r	   NameChineseNamerF   LicenseOriginalModelIdTrainIdz/api/v1/models/aigcr   r   r   )TagShowNameCoverImagesAigcTypeTagDescriptionVisionFoundation	BaseModelWeightsNameWeightsSha256WeightsSize	ModelPathTriggerWordsModelSourceSubVisionFoundationOfficialTagsz/api/v1/models.r   r   en_USzX-Modelscope-Accept-Languager   r   r   /models/)#rH   r   r   rd   r   r   r   preupload_weightsr   r   r   tagcover_images	aigc_typedescriptionbase_model_typebase_model_idweight_filenameweight_sha256weight_size
model_pathtrigger_wordsmodel_sourcebase_model_sub_typeofficial_tagsr"   splitrstripendswithr   r   rP   r   rQ   upload_to_repo)r   r   r   r   r   r   r   r   r   r   owner_or_groupnamebodyr   r   intl_endr   r   model_repo_urls                      r   create_modelzHubApi.create_modelA  sU   B "#:;;;"""MM 	%}H;HEE #'$0z~~&;R@@
 
 !333D(($BVBVW[WcBdBdow(xxx KK)~)6&0","8$.$>'5J9J)9!+!9)5'2 * 8)6'1'E      ' @'1'?^$ ...D&&t|4417<<R@??3((X88 	>6=G23L	   
 	a   FFHHq$88h88 !%%dHe<<<r   tag_namec                    |t          d          |t          d          |                                dv rt          d| d          |                     |d          }|s| j        }t	          |          \  }}|f| d	}	|                    ||                     | j                  |
           |j        ||||j	        |j
        |j        |j        |j        |j        d
}
n| d| d}	d}||d}
| j                            |	|
||                     | j                            }t#          |           |                                }t'          |           | d| d| }|S )a]  Create a tag for a model at ModelScope Hub.

        Args:
            model_id (str): The model id in format {owner}/{name}
            tag_name (str): The tag name (e.g., "v1.0.0")
            endpoint: the endpoint to use, default to None to use endpoint specified in the class
            token (str, optional): access token for authentication
            aigc_model (AigcModel, optional): AigcModel instance for AIGC model tag creation.
                If provided, will create an AIGC model tag with automatic parameters.
                Refer to modelscope.hub.utils.aigc.AigcModel for details.

        Returns:
            str: URL of the created tag

        Raises:
            InvalidParameter: If model_id, tag_name, ref, or description is invalid.
            ValueError: If not login.

        Note:
            model_id = {owner}/{name}
        Nr   ztag_name is required!)mainmasterz
tag_name "zp" is not allowed. Please use a different tag name (e.g., "v1.0", "v1.1", "latest"). Reserved names: main, masterTr   z/api/v1/models/aigc/repo/tagr  )
r	  r  r	   r  r  r  r  r  r
  r  /api/v1/models/z	/repo/tagr6  )TagNameRefr  r  z/tags/)rH   lowerr   r   rd   r  r   r   r  r!  r"  r#  r%  r  r  r   r   rP   r   rQ   )r   r   r3  r   r   r   r   r-  r.  r   r/  revisionr   r   tag_urls                  r   create_model_tagzHubApi.create_model_tag  s   6 "#:;;;"#:;;;>>111"0X 0 0 0   """MM 	%}H;HEE !<<<D(($BVBVW[WcBdBdow(xxx  *6&')9!+!9)5 * 8&0$.$> DD BBxBBBDH# D
 L((66	  8 8 	a   FFHHqAAxAAxAAr   c                 x   t          j        dt          d           |                     |d          }|s| j        }|t          d          | d| }| j                            |||                     | j	                  	          }t          |           t          |                                           dS )
a  
        @deprecated
        Delete model_id from ModelScope.

        Args:
            model_id (str): The model id.
            endpoint: the endpoint to use, default to None to use endpoint specified in the class
            token (str, optional): access token for authentication

        Raises:
            ValueError: If not login.

        Note:
            model_id = {owner}/{name}
        This function is deprecated due to security reasons, and will be recovered in future versions with proper token authentication. r   
stacklevelTr   N)Token does not exist, please login first.r7  r   r   warningswarnDeprecationWarningr   r   r   r   deleter   r   rP   rQ   r   )r   r   r   r   r   r   r   s          r   delete_modelzHubApi.delete_model  s      	Z		
 	
 	
 	
 """MM 	%}H?HIII55855L(/(,(<(<T\(J(J   L L 	a   qvvxx     r   c                 $    |s| j         }| d| dS )Nr7  z.git)r   )r   r   r   s      r   get_model_urlzHubApi.get_model_url$  s(     	%}H9989999r   r;  c                 V   |                      |d          }t          |          \  }}|s| j        }|r| d| d| d| }n
| d| d| }| j                            |||                     | j                            }	t          |	t          ||           |	j	        t          j        k    rlt          |	                                          r|	                                t                   S t          |	                                t                              t#          |	           dS )a  Get model information at ModelScope

        Args:
            model_id (str): The model id.
            revision (str optional): revision of model.
            endpoint: the endpoint to use, default to None to use endpoint specified in the class
            token (str, optional): access token for authentication

        Returns:
            The model detail information.

        Raises:
            NotExistError: If the model is not exist, will throw NotExistError

        Note:
            model_id = {owner}/{name}
        Fr   r7  r   
?Revision=rC  N)r   rd   r   r   r   r   r   rN   loggerstatus_coder   OKrO   r   r   rI   r   rP   )
r   r   r;  r   r   r   r-  r.  r   r   s
             r   	get_modelzHubApi.get_model)  s:   0 """NN;HEE 	%}H 	GZZ~ZZZZPXZZDDFF~FFFFDLT7%)%9%9$,%G%G  I IQ:::=JM))QVVXX Jvvxx 788#AFFHH-G$HIII!!$$$$$r   )	repo_typer   repo_idrR  c          	         t           j                            t                    }|p|                                dk    rXt
          |z   }	 |                     |||d|           n0# t          $ r# t          	                    d| d| d            w xY w|S t          t                     }t          |          }|                     ||||	          st          |           }t                              d| d
| d| d           	 |                     |||d|           |S # t          $ r% t          	                    d| d| d|             w xY w|S )a  Get proper endpoint for read operation (such as download, list etc.)
        1. If user has set MODELSCOPE_DOMAIN, construct endpoint with user-specified domain.
           If the repo does not exist on that endpoint, throw 404 error, otherwise return the endpoint.
        2. If domain is not set, check existence of repo in cn-site and ai-site (intl version) respectively.
           Checking order is determined by MODELSCOPE_PREFER_AI_SITE.
             a. if MODELSCOPE_PREFER_AI_SITE is not set ,check cn-site first before ai-site (intl version)
             b. otherwise check ai-site before cn-site
           return the endpoint with which the given repo_id exists.
           if neither exists, throw 404 error
        Nr   T)rS  rR  r   re_raiser   Repo z does not exist on r  )cn_siterR  r   r   z not exists on z#, will try on alternative endpoint rR  r   rU  r   z not exists on either z or )r   r   r   r&   stripr)   repo_exists	ExceptionrN  errorrc   r'   r`   warning)	r   rS  rR  r   sr   check_cn_firstprefer_endpointalternative_endpoints	            r   get_endpoint_for_readzHubApi.get_endpoint_for_readV  s    JNN,--=QWWYY"__,q0H  IPXcgot uuuu   LWLLLLLMMM O()BCCC&~>>>9e   U U 	##/^9K#M#M#M NN W7 W W? W W?SW W W X X X,  y;OZ^fk ! m m m ,+	    oWooOooYmooppp #"s   
A% %-BD' '/E)r;  r   c                    t          |          \  }}|                     |||          }|                     |t          ||          }|                     ||d|          }t          di ||||d}	|	S )aD  Get model information including commit history.

        Args:
            repo_id (str): The model id in the format of
                ``namespace/model_name``.
            revision (str, optional): Specific revision of the model.
                Defaults to ``DEFAULT_MODEL_REVISION``.
            endpoint (str, optional): Hub endpoint to use. When ``None``,
                use the endpoint specified when initializing :class:`HubApi`.

        Returns:
            ModelInfo: The model detailed information returned by
            ModelScope Hub with commit history.
        )r   r;  r   rS  rR  r;  r   T)r   r;  	recursiver   commitsauthorsiblingsr   )rd   rQ  list_repo_commitsrk   get_model_filesrT   )
r   rS  r;  r   r-  _
model_datarh  rj  
model_infos
             r   ro  zHubApi.model_info  s    & 9AA^^x( $ D D
((T\ ) ^ ^''x4( ( T T gggW^^fgggg
r   c                    t          |          \  }}|                     |||          }|                     |t          ||          }|                     ||pt
          d|          }t          di ||||d}	|	S )a>  Get dataset information including commit history.

        Args:
            repo_id (str): The dataset id in the format of
                ``namespace/dataset_name``.
            revision (str, optional): Specific revision of the dataset.
                Defaults to ``None``.
            endpoint (str, optional): Hub endpoint to use. When ``None``,
                use the endpoint specified when initializing :class:`HubApi`.

        Returns:
            DatasetInfo: The dataset detailed information returned by
            ModelScope Hub with commit history.
        )
dataset_idr;  r   re  T)rS  r;  rf  r   rg  r   )rd   get_datasetrk  rj   get_dataset_filesre   rS   )
r   rS  r;  r   r-  rm  dataset_datarh  rj  dataset_infos
             r   ru  zHubApi.dataset_info  s    & 9AA''H ( F F(('88V^ ) ` `))h&J2JVZem * o o #mm\m7>dlmmmmr   )rR  r;  r   c                    ||t           k    r|                     |||          S |t          k    r|                     |||          S t	          d| dt
           d          )aR  Get repository information for models or datasets.

        Args:
            repo_id (str): The repository id in the format of
                ``namespace/repo_name``.
            revision (str, optional): Specific revision of the repository.
                Currently only effective for model repositories. Defaults to
                ``DEFAULT_MODEL_REVISION``.
            repo_type (str, optional): Type of the repository. Supported
                values are ``"model"`` and ``"dataset"``. If not provided,
                ``"model"`` is assumed.
            endpoint (str, optional): Hub endpoint to use. When ``None``,
                use the endpoint specified when initializing :class:`HubApi`.

        Returns:
            Union[ModelInfo, DatasetInfo]: The repository detailed information
            returned by ModelScope Hub.
        N)rS  r;  r   Arg repo_type z# not supported. Please choose from r  )rk   ro  rj   ru  rH   rl   )r   rS  rR  r;  r   s        r   	repo_infozHubApi.repo_info  s    4 	_ < <??7XPX?YYY)))$$WxRZ$[[[_Y__K\___a a 	ar   rY  rU  c                   || j         }|-|                                t          vrt          d|z            ||                    d          dk    rt          d|z            |                     |d          }t          |          \  }}|(|                                t          k    r| d| d| }	n
| d	| d| }	| j        	                    |	|| 
                    | j                  
          }
t          |
t          ||d          }|dk    rdS |dk    r|rt          |
          dS t                              d| d           t          d|z            )a  
        Checks if a repository exists on ModelScope

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            repo_type (`str`, *optional*):
                `None` or `"model"` if getting repository info from a model. Default is `None`.
                TODO: support studio
            endpoint(`str`):
                None or specific endpoint to use, when None, use the default endpoint
                set in HubApi class (self.endpoint)
            re_raise(`bool`):
                raise exception when error
            token (`str`, *optional*): access token to use for checking existence.
        Returns:
            True if the repository exists, False otherwise.
        NzNot support repo-type: %sr   r   z5Invalid repo_id: %s, must be of format namespace/nameFr   /api/v1/datasets/r7  rC     Ti  z%Check repo_exists return status code r  zOFailed to check existence of repo: %s, make sure you have access authorization.)r   r:  rl   r\  countr   rd   rj   r   r   r   r   rN   rN  r   rF  )r   rS  rR  r   rU  r   r   r-  r.  r   r   codes               r   r[  zHubApi.repo_exists  s   8 }H!y'8'8@Q'Q'Q7)CDDDOc 2 2a 7 7SV__```"""NN;GDD!y'8'8<M'M'MHHHH$HHDDFF~FFFFDLT7%)%9%9$,%G%G  I I#AvwGG3;;4S[[ ll"uKKGGGGHHHa  r   c                 B   t          j        dt          d           |s| j        }|t          k    r|                     |||           n7|t          k    r|                     |||           nt          d| d          t          
                    d| d	           d
S )al  
        @deprecated
        Delete a repository from ModelScope.

        Args:
            repo_id (`str`):
                A namespace (user or an organization) and a repo name separated
                by a `/`.
            repo_type (`str`):
                The type of the repository. Supported types are `model` and `dataset`.
            endpoint(`str`):
                The endpoint to use. If not provided, the default endpoint is `https://www.modelscope.cn`
                Could be set to `https://ai.modelscope.ai` for international version.
            token (str): Access token of the ModelScope.
        r?  r   r@  )rq  r   r   )r   r   r   rw  z not supported.rV  z deleted successfully.N)rE  rF  rG  r   rj   delete_datasetrk   rI  r\  rN  info)r   rS  rR  r   r   s        r   delete_repozHubApi.delete_repo  s    * 	Z		
 	
 	
 	
  	%}H)))"!      
 /)) !     
 GYGGGHHH;G;;;<<<<<r   c                 2   t           j                            | t          j                  }t
          j        t          j        t
          j	        t          j        i}t          |d          5 }t          j        ||           d d d            d S # 1 swxY w Y   d S )Nw)r   r   joinrs   CONFIGURATIONrm   	frameworkrr   torchtaskrt   otheropenr   dump)	model_dircfg_filecfgfiles       r   _create_default_configzHubApi._create_default_configM  s    7<<	9+BCC"J$4u{
 (C   	!DIc4   	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!s   )BBBzupload modelr  commit_messager  ignore_file_pattern
lfs_suffixc           	      F
   t          j        dt          d           	 |t          d          |t          d          t          j                            |          rt          j                            |          rt          d          t          j                            |t          j
                  }t          j                            |          sEt                              dt          j
         d| d	           t                              |           |                     |d
          }|t!          d          t	          j        |          }t%          |          }|
g }
t'          |
t(                    r|
g}
||t          d          |                     ||          s?t                              d| d           |                     |||||	|| j                   t          j                            |t2                    }t5                      }t                              d| d| d           t                              d| d           	 t7          |||| j                  }|                    |          }||vr3t                              d|            |                    ||           |                    ||           t	          j        |          }|D ]xd         dk    rjt          j                            |          }t          j                            |          rt	          j        |           btA          j!        |d
           y|D ]d         dk    rtE          fd|
D                       r*t          j                            |          }t          j        #                    |          r4tA          j$        |t          j                            |                     tA          j%        ||           |s9tL          j&        '                                (                    d          }d|d|}|4t'          |t(                    r|gn|}|D ]}|)                    |           |*                    |||           ||+                    ||           t                              d | d!| d"           n# tX          $ r  w xY w	 tA          j!        |d
           d S # tA          j!        |d
           w xY w)#NzThis function is deprecated and will be removed in future versions. Please use git command directly or use HubApi().upload_folder insteadr   r@  zmodel_id cannot be empty!zmodel_dir cannot be empty!z$model_dir must be a valid directory.zNo z file found in z, creating a default one.Tr   zMust login before upload!z5Visibility and License cannot be empty for new model.r   zCreating new model [])r   r   r   r   r   r   r   zPushing folder z
 as model r  zTotal folder size z;, this may take a while depending on actual pushing size...)r  
clone_from
auth_tokenr   zCreating new branch r   )ignore_errorsc                 >    g | ]}t          j        |          d uS N)research).0patternfs     r   
<listcomp>z%HubApi.push_model.<locals>.<listcomp>  s*    aaa'BIgq11=aaar   z%Y_%m_%d_%H_%M_%Sz[automsg] push model z to hub at )r  local_branchremote_branchzSuccessfully push folder z to remote repo [z].)-rE  rF  rG  rH   r   r   existsisfiler  rs   r  rN  r^  r   r  r   rJ   listdirra   
isinstancestrr[  r  r2  r   r,   rR   rV   get_remote_branches
new_branchcheckoutremoveshutilrmtreeanyisdircopytreecopydatetimenowstrftimeadd_lfs_typepushtag_and_pushr\  )r   r   r  r   r   r   r  r  r;  r   r  r  r   r  r   files_to_savefolder_sizetmp_dirgit_wrapperrepobranchesfiles_in_reposrcdatelfs_suffix_listsuffixr  s                             @r   
push_modelzHubApi.push_modelW  s^    	T		
 	
 	
 	
.	^ "#>???"#?@@@w~~i(( 	KBGNN9,E,E 	K"#IJJJ7<<	9+BCCw~~h'' 	5NNbi-bbibbbd d d)))444"""MM?#$?@@@
9--.y99&"$)3// 	8#6"7"#Z[[[66 		(KK:x:::;;;!%)"3  ( ( ( ',,y*?@@'))FiFF8FFFGGGqqqqrrr*	7HQVaeanoooD"66w??Hx''=8==>>>&&w999  (333Jw//M" ? ?Q43;;',,w22Cw~~c** ?	#c>>>>" 2 2Q43;;aaaaM`aaabb ! ',,y!44Cw}}S)) 2RW\\'1-E-EFFFFC111! $(,,..778KLLHHdd"$%2<Z2M2M"]:,,S]- . .F%%f----II-%&  ( ( ( !!#s+++KK\I\\PX\\\]]]] 	 	 		 ^ M'666666FM'66666s   J S  T  S,,T T r   r   r-  page_number	page_sizec           
      "   |                      |d          }|s| j        }| d}| j                            |d|d|d|d||                     | j                            }t          |t          ||           |j        t          j
        k    rnt          |                                          r!|                                t                   }	|	S t          |                                t                             t!          |           d	S )
aH  List models in owner or group.

        Args:
            owner_or_group(str): owner or group.
            page_number(int, optional): The page number, default: 1
            page_size(int, optional): The page size, default: 10
            endpoint: the endpoint to use, default to None to use endpoint specified in the class
            token (str, optional): access token for authentication

        Raises:
            RequestError: The request error.

        Returns:
            dict: {"models": "list of models", "TotalCount": total_number_of_models_in_owner_or_group}
        Fr   r7  z	{"Path":"z", "PageNumber":z, "PageSize": })datar   r   N)r   r   r   putr   r   rN   rN  rO  r   rP  rO   r   r   rK   r   rP   )
r   r-  r  r  r   r   r   r   r   r  s
             r   list_modelszHubApi.list_models  s   * """NN 	%}H+++LD ..+++yyy:((66  8 8 	Q@@@=JM))QVVXX Ivvxx 78"16688,F#GHHH!!$$$tr   )r  r  sortr  r   r   r  r  c                b   |s| j         }| d}||d}	|r5|t          vr't          d| dt          t                               ||	d<   |r||	d<   |r||	d<   |                     |d	          }
| j                            ||	|

          }t          |           |                     |          S )aq  List datasets via OpenAPI with pagination, filtering and sorting.

        Args:
            owner_or_group (str): Search by dataset authors (including organizations and individuals).
            page_number (int, optional): The page number. Defaults to 1.
            page_size (int, optional): The page size. Defaults to 10.
            sort (str, optional): Sort key. If not provided, the server's default sorting is used.
                choose from ['default', 'downloads', 'likes', 'last_modified'].
            search (str, optional): Search by substring keywords in the dataset's Chinese name,
                English name, and authors (including organizations and individuals).
            endpoint (str, optional): Hub endpoint to use. When None, use the endpoint specified in the class.
            token (str, optional): Access token for authentication.

        Returns:
            dict: The OpenAPI data payload, e.g.
                  {
                    "datasets": [...],
                    "total_count": int,
                    "page_number": int,
                    "page_size": int
                  }
        z/openapi/v1/datasets)r  r  zInvalid sort key: z. Supported sort keys: r  r  ri  F)r   token_required)paramsr   )	r   rB   rH   list_build_bearer_headersr   r   rP   _parse_openapi_response)r   r-  r  r  r  r  r   r   r   r  r   r   s               r   list_datasetszHubApi.list_datasets  s    >  	%}H000 '""
 "
  	"?**&]]]d?F[F[]]_ _ _!F6N 	&%F8 	.-F8,,5,OOLT&'BBa   ++A...r   use_cookiesc                     d }t          |t                    r|}n+t          |t                    r|                     |          }|S )N)r   )r  r   boolr   )r   r  r   s      r   _check_cookiezHubApi._check_cookieL  sO    k9-- 	E!GGT** 	E&&&DDGr   cutoff_timestampc                 V    |                      |||          }|rd |D             ng }|S )a3  Get model branch and tags.

        Args:
            model_id (str): The model id
            cutoff_timestamp (int): Tags created before the cutoff will be included.
                                    The timestamp is represented by the seconds elapsed from the epoch time.
            use_cookies (Union[bool, CookieJar], optional): If is cookieJar, we will use this cookie, if True,
                        will load cookie from local. Defaults to False.

        Returns:
            Tuple[List[str], List[str]]: Return list of branch name and tags
        )r   r  r  c                     g | ]
}|d          S Revisionr   r  xs     r   r  z/HubApi.list_model_revisions.<locals>.<listcomp>h  (       !*   r   )list_model_revisions_detail)r   r   r  r  tags_detailstagss         r   list_model_revisionszHubApi.list_model_revisionsT  s_    " 77IYDO 8 Q Q "*  |    ') 	r   c                    |                      |          }|t                      }|s| j        }| d| d|z  }| j                            |||                     | j                            }t          |t          ||           |	                                }t          |           |t                   }	|	d         d         S )a  Get model branch and tags.

        Args:
            model_id (str): The model id
            cutoff_timestamp (int): Tags created before the cutoff will be included.
                                    The timestamp is represented by the seconds elapsed from the epoch time.
            use_cookies (Union[bool, CookieJar], optional): If is cookieJar, we will use this cookie, if True,
                        will load cookie from local. Defaults to False.
            endpoint: the endpoint to use, default to None to use endpoint specified in the class

        Returns:
            Tuple[List[str], List[str]]: Return list of branch name and tags
        Nr7  z/revisions?EndTime=%srC  RevisionMapTags)r  rb   r   r   r   r   r   rN   rN  r   rQ   r   )
r   r   r  r  r   r   r   r   r   r  s
             r   r  z"HubApi.list_model_revisions_detaill  s    & $$[11#355 	%}HJJ8JJJM]]LT7%)%9%9$,%G%G  I IQ:::FFHHq()M"6**r   c                 0    |D ]}|d         |k    r|c S d S )Nr  r   )r   detailsr.  items       r   get_branch_tag_detailzHubApi.get_branch_tag_detail  s4     	 	DJ4'' (tr   r   c           	         |s| j         }t                      t          t          t          j                                                                                            }|                     ||dn||          \  }}|rd |D             ng }|rd |D             ng }	|t          z   k    r|%t          }t                              d| d           ||vr||	vrt          d|d|d	          |                     ||          }
|
|                     ||          }
t                              d
|            n|||v r|                     ||          }
|
S t          |          dk    rC||t          k    rt          }nt          d|d|d          |                     ||          }
nR||rfd|D             ng }t          |          dk    r|d         d         }|d         }
nRt          }|                     ||          }
dd                    |	          z  }t                              d|            t                              d|            n||	vrm|t          k    r1t                              d           |                     ||          }
nGdd                    |	          z  }t          d|d|d|d          |                     ||          }
t                              d|            |
S )NF)r  r   c                     g | ]
}|d          S r  r   r  s     r   r  z4HubApi.get_valid_revision_detail.<locals>.<listcomp>  s    CCC!*CCCr   c                     g | ]
}|d          S r  r   r  s     r   r  z4HubApi.get_valid_revision_detail.<locals>.<listcomp>  s    ;;;aAjM;;;r   z-Model revision not specified, using default [z
] version.zThe model: z has no revision : z .zDevelopment mode use revision: r   z has no revision:  !c                 ,    g | ]}|d          k    |S )	CreatedAtr   )r  r  release_timestamps     r   r  z4HubApi.get_valid_revision_detail.<locals>.<listcomp>  s5     (M (M (Ma()+:K(K(K )*(K(K(Kr   r  z[%s],z3Model revision should be specified from revisions: z,Model revision not specified, use revision: z?Using the master branch is fragile, please use it with caution!z valid are: !z#Use user-specified model revision: )r   rb   introundr  r  	timestamp#get_model_branches_and_tags_detailsr*   rh   rN  r  rI   r  debugr   r  r^  )r   r   r;  r   r   current_timestampall_branches_detailall_tags_detailall_branchesall_tagsrevision_detailrevisions_detailvlr  s                @r   get_valid_revision_detailz HubApi.get_valid_revision_detail  s   
  	%}H022h&7&;&;&=&=&G&G&I&I J JKK 04/W/W7?%%RZ 0X 0\ 0\,_GZbCC/BCCCC`b?NV;;?;;;;TV03CCCC.XHXXXZ Z Z|++0H0H#mhhhX`X`X`$abbb"88(SSO&"&"<"<=PRZ"["[LLE8EEFFFF#L(@(@"&"<"<=PRZ"["[&&?##q((#x3F'F'F2HH'-QYQYQY[c[c[c(deee"&"<"<=PRZ"["[# Q`(h (M (M (M (M(7(M (M (M (Meg % +,,q00#3A#6z#B*:1*=#6*.*D*DEXZb*c*c#chhx&8&88'a]_'a'abbbNN#\RZ#\#\]]]]  x//#':::"NN+lmmm.2.H.HI\^f.g.gOO!'#((8*<*<!<B"/-19888RRR1I #J #J J +/*D*D_V^*_*_KK Ph P PQQQr   c                 @    |                      ||||          d         S )N)r   r;  r   r   r  )r  )r   r   r;  r   r   s        r   get_valid_revisionzHubApi.get_valid_revision  s<    
 --x7?6=7? . A A BLM 	Mr   c                 ~   |                      |          }|s| j        }| d| d}| j                            |||                     | j                            }t          |t          ||           |                                }t          |           |t                   }|d         d         |d         d         fS )a  Get model branch and tags.

        Args:
            model_id (str): The model id
            use_cookies (Union[bool, CookieJar], optional): If is cookieJar, we will use this cookie, if True,
                        will load cookie from local. Defaults to False.
            endpoint: the endpoint to use, default to None to use endpoint specified in the class

        Returns:
            Tuple[List[str], List[str]]: Return list of branch name and tags
        r7  z
/revisionsrC  r  Branchesr  )r  r   r   r   r   r   rN   rN  r   rQ   r   )	r   r   r  r   r   r   r   r   r  s	            r   r  z*HubApi.get_model_branches_and_tags_details  s    " $$[11 	%}H??8???LT7%)%9%9$,%G%G  I IQ:::FFHHq()M":.]0CF0KKKr   c                 ~    |                      ||          \  }}|rd |D             ng }|rd |D             ng }||fS )aq  Get model branch and tags.

        Args:
            model_id (str): The model id
            use_cookies (Union[bool, CookieJar], optional): If is cookieJar, we will use this cookie, if True,
                        will load cookie from local. Defaults to False.

        Returns:
            Tuple[List[str], List[str]]: Return list of branch name and tags
        )r   r  c                     g | ]
}|d          S r  r   r  s     r   r  z6HubApi.get_model_branches_and_tags.<locals>.<listcomp>  s(       aAjM   r   c                     g | ]
}|d          S r  r   r  s     r   r  z6HubApi.get_model_branches_and_tags.<locals>.<listcomp>  r  r   )r  )r   r   r  branches_detailtags_detailr  r  s          r   get_model_branches_and_tagsz"HubApi.get_model_branches_and_tags  s     (,'O'OYa\g (P (i (i$ )1  ?    .0 	 !)  {    &( 	~r   rootrf  r   c                    |s| j         }|r|d|d|d|}n
|d|d|}|                     |          }	||d| z   }|| j        n|}t          t	          j                    j                  |d<   | j                            ||	|          }
t          |
t          |	|           |
                                }t          |           g }|t                   d	         s#t                              d
| d| d           |S |t                   d	         D ]0}|d         dk    s|d         dk    r|                    |           1|S )a  List the models files.

        Args:
            model_id (str): The model id
            revision (Optional[str], optional): The branch or tag name.
            root (Optional[str], optional): The root path. Defaults to None.
            recursive (Optional[bool], optional): Is recursive list files. Defaults to False.
            use_cookies (Union[bool, CookieJar], optional): If is cookieJar, we will use this cookie, if True,
                        will load cookie from local. Defaults to False.
            headers: request headers
            endpoint: the endpoint to use, default to None to use endpoint specified in the class

        Returns:
            List[dict]: Model file list.
        r7  z/repo/files?Revision=&Recursive=z/repo/files?Recursive=Nz&Root=zX-Request-IDrC  FileszNo files found in model z at revision r  r  z
.gitignorez.gitattributes)r   r  r   r  uuiduuid4hexr   r   rN   rN  r   rQ   r   r^  append)r   r   r;  r  rf  r  r   r   r   r   r   r   filesr  s                 r   rl  zHubApi.get_model_files  s   .  	%}H 	/(((HHHii9DD (((II/D$$[11/4//)D")/$,,w"%djll&6"7"7L'7  4 4 	Q:::FFHHq()'2 	NNXhXXXXXXYYYL-.w7 	 	DF||++tF|?O/O/OLLr   )r;  r   filenamec                    |                      |          }|                     |d||dn|          }d |D             }||v S )a  Get if the specified file exists

        Args:
            repo_id (`str`): The repo id to use
            filename (`str`): The queried filename, if the file exists in a sub folder,
                please pass <sub-folder-name>/<file-name>
            revision (`Optional[str]`): The repo revision
            token (`Optional[str]`): The access token
        Returns:
            The query result in bool value
        r   TNF)rf  r;  r  c                     g | ]
}|d          S r   r   )r  r  s     r   r  z&HubApi.file_exists.<locals>.<listcomp>f  s    000$f000r   )r   rl  )r   rS  r  r;  r   r   r  s          r   file_existszHubApi.file_existsL  sh    & """66$$!(g	 % 
 
 10%0005  r   dataset_name	namespacer  c	                    ||t          d          |                     |d          }	|s| j        }| d}
d|fd|fd|fd|fd|fd|fd}| j                            |
||	|                     | j                            }t          ||
|           t          |	                                           | d| d	| }t                              d
|            |S )aN  
        Create a dataset in ModelScope.

        Args:
            dataset_name (str): The name of the dataset.
            namespace (str): The namespace (user or organization) for the dataset.
            chinese_name (str, optional): The Chinese name of the dataset. Defaults to ''.
            license (str, optional): The license of the dataset. Defaults to Licenses.APACHE_V2.
            visibility (int, optional): The visibility of the dataset. Defaults to DatasetVisibility.PUBLIC.
            description (str, optional): The description of the dataset. Defaults to ''.
            endpoint (str, optional): The endpoint to use. If not provided, the default endpoint is used.
            token (str, optional): The access token for authentication.

        Returns:
            str: The URL of the created dataset repository.
        Nz(dataset_name and namespace are required!Tr   z/api/v1/datasets)r  r  Ownerr  rF   Description)r  r   r   z
/datasets/r   zCreate dataset success: )rH   r   r   r   r   r   r   rM   rQ   r   rN  r  )r   r  r  r   r   r   r  r   r   r   r   r  r   dataset_repo_urls                 r   create_datasetzHubApi.create_dataseti  s0   4 9#4"#MNNN"""MM 	%}H,,,<( ,/I&g, +.
 
 L((66	  
 
 	q$...qvvxx   &LL)LLlLLA/?AABBBr   rq  c                 x   t          j        dt          d           |                     |d          }|s| j        }|t          d          | d| }| j                            |||                     | j	                  	          }t          |           t          |                                           dS )
ac  
        @deprecated
        Delete a dataset from ModelScope.

        Args:
            dataset_id (str): The dataset id to delete.
            endpoint (str, optional): The endpoint to use. If not provided, the default endpoint is used.
            token (str, optional): The access token for authentication.

        Returns:
            None
        r?  r   r@  Tr   NrB  rz  rC  rD  )r   rq  r   r   r   r   r   s          r   r  zHubApi.delete_dataset  s      	Z		
 	
 	
 	
 """MM 	%}H?HIII99Z99L(/(,(<(<T\(J(J   L L 	a   qvvxx     r   _dataset_id_type_cachec                    |s| j         }|||f}t          j                            |          }||S | d| d| }|                     |          }| j                            ||          }	|	                                }
t          ||
|	           |
d         d         }|
d         d         }||ft          j        |<   ||fS )	z Get the dataset id and type. Nrz  r   r   r   DataIdType)r   r   r!  r   r   r   r   rL   )r   r  r  r   r   	cache_keycacheddatahub_urlr   r   resprq  dataset_types                r   get_dataset_id_and_typezHubApi.get_dataset_id_and_type  s      	%}Hh7	.229==M!NNINNNN"""66L['::vvxx{D!444&\$'
F|F+4>3M%i0<''r   Tr   	root_pathc
                 p   t          j        dt                     |                     ||||	          \  }
}|rdnd}|s| j        }| d|
 d}|r|nd|r|nd|||d	}|                     |	
          }| j                            |||          }|                                }t          |||           |S )z?
        @deprecated: Use `get_dataset_files` instead.
        zMThe function `list_repo_tree` is deprecated, use `get_dataset_files` instead.r  r  r   r   TrueFalserz  
/repo/treer6  r   r  Root	Recursive
PageNumberPageSizer   r  r   )
rE  rF  rG  r,  r   r   r   r   r   rL   )r   r  r  r;  r-  rf  r  r  r   r   dataset_hub_idr+  r)  r  r   r   r*  s                    r   list_repo_treezHubApi.list_repo_tree  s    	e(	* 	* 	* (,'C'C%XUZ (D (\ (\$ (4FFW	 	%}H!NNNNNN*2@hh'09))c	 +D D """66L[IIvvxx{D!444r   2   )rR  r;  r  r  r   r   c          	         t          |          r2|                    d          dk    r|                    d          \  }}	nt          d| d          |s| j        }|r| d| d| dn| d| d}
|pt
          ||d	}|                     |
          }	 | j                            |
||| 	                    | j
                            }t          |           |                                }t          |           |                    d          t          j        k    rt!          j        |          S dS # t$          j        j        $ r'}t+          d| dt-          |                     d}~ww xY w)au  
        Get the commit history for a repository.

        Args:
            repo_id (str): The repository id, in the format of `namespace/repo_name`.
            repo_type (Optional[str]): The type of the repository. Supported types are `model` and `dataset`.
            revision (str): The branch or tag name. Defaults to `DEFAULT_REPOSITORY_REVISION`.
            page_number (int): The page number for pagination. Defaults to 1.
            page_size (int): The number of commits per page. Defaults to 50.
            endpoint (Optional[str]): The endpoint to use, defaults to None to use the endpoint specified in the class.
            token (Optional[str]): The access token.

        Returns:
            CommitHistoryResponse: The commit history response.

        Examples:
            >>> from modelscope.hub.api import HubApi
            >>> api = HubApi()
            >>> commit_history = api.list_repo_commits('meituan/Meeseeks')
            >>> print(f"Total commits: {commit_history.total_count}")
            >>> for commit in commit_history.commits:
            ...     print(f"{commit.short_id}: {commit.title}")
        r   r   Invalid repo_id: r  z/api/v1/s/z/commitsr7  )r9  r6  r7  r   r  r   r   Codez%Failed to get repository commits for : N)rx   r|  r)  r   r   rg   r   r   r   r   r   rP   r   rQ   r   rP  r}   from_api_responserequests
exceptionsRequestExceptionr\  r  )r   rS  rR  r;  r  r  r   r   _owner_dataset_namecommits_urlr  r   r   r*  es                   r   rk  zHubApi.list_repo_commits  s   B G$$ 	>s););q)@)@$+MM#$6$6!FMM<<<<=== 	%}HMV :II9IIIIII99999 	 ::%!
 

 """66	Y  V)0$:N:Nt|:\:\ ! ^ ^A!!$$$6688D4   xx:=00,>tDDD 10 "3 	Y 	Y 	YWGWWsSTvvWWXXX	Ys   BD8 8E3"E..E3r   )r;  r-  rf  r  r  r   r   r9  r9  c                0   |	pt          |          r2|                    d          dk    r|                    d          \  }
}nt          d| d          |                     ||
||          \  }	}|s| j        }| d|	 d}|||rd	nd
||d}|                     |          }| j                            |||          }|	                                }t          |||           |                    d          }|g S |                    d          pg S )a  
        Get the dataset files.

        Args:
            repo_id (str): The repository id, in the format of `namespace/dataset_name`.
            revision (str): The branch or tag name. Defaults to `DEFAULT_REPOSITORY_REVISION`.
            root_path (str): The root path to list. Defaults to '/'.
            recursive (bool): Whether to list recursively. Defaults to True.
            page_number (int): The page number for pagination. Defaults to 1.
            page_size (int): The number of items per page. Defaults to 100.
            endpoint (Optional[str]): The endpoint to use, defaults to None to use the endpoint specified in the class.
            token (Optional[str]): The access token.
            dataset_hub_id (Optional[str]): Pre-fetched dataset hub id. When provided,
                skips the internal ``get_dataset_id_and_type`` lookup. Useful in pagination
                loops to avoid redundant API calls per page.

        Returns:
            List: The response containing the dataset repository tree information.
                e.g. [{'CommitId': None, 'CommitMessage': '...', 'Size': 0, 'Type': 'tree'}, ...]
        Nr   r   r=  r  r/  rz  r2  r0  r1  r3  r   r8  r$  r  )rx   r|  r)  r   r,  r   r   r   r   r   rL   )r   rS  r;  r-  rf  r  r  r   r   r9  rF  rG  rm  r)  r  r   r   r*  r  s                      r   rs  zHubApi.get_dataset_files=  s_   @ !(( BW]]3-?-?1-D-D(/c(:(:% !@W!@!@!@AAA $ < <*fxW\ != !^ !^NA  	%}H!NNNNNN #,9'%!
 
 """66L[IIvvxx{D!444xx<Ixx  &B&r   c                 T   |                      |          }|s| j        }|r| d| d| }n| d| }| j                            |||                     | j                            }t          |           |                                }t          |||           |t                   S )a  
        Get the dataset information.

        Args:
            dataset_id (str): The dataset id.
            revision (Optional[str]): The revision of the dataset.
            endpoint (Optional[str]): The endpoint to use, defaults to None to use the endpoint specified in the class.
            token (Optional[str]): The access token.

        Returns:
            dict: The dataset information.
        r   rz  rM  rC  )
r   r   r   r   r   r   rP   r   rL   r   )	r   rq  r;  r   r   r   r   r   r*  s	            r   rr  zHubApi.get_dataset{  s    & """66 	%}H 	>QQQQxQQDD====DL'4+?+?+M+M  O Oa   vvxxtT1---+,,r   c           	      b   |s| j         }| d| d| }|                     |          }| j                            |||                     | j                            }	|	                                }
t          ||
|	           |
d         }|t          d| d| d	| d
          |d         }|S )z( Get the meta file-list of the dataset. rz  z/repo/tree?Revision=r   rC  r$  Nz'The modelscope dataset [dataset_name = z, namespace = z, version = z] dose not existr  )	r   r   r   r   r   r   r   rL   rI   )r   r  r  rq  r;  r   r   r)  r   r   r*  	file_lists               r   get_dataset_meta_file_listz!HubApi.get_dataset_meta_file_list  s      	%}H!^^J^^T\^^"""66L[%,%)%9%9$,%G%G  I I vvxx{D!444L	8, 8 8V_ 8 8%8 8 89 9 9 g&	r   r+  meta_cache_dirc                    t           j                            |t          |            t          j        j                   }t          |d          5 }|                    d           ddd           dS # 1 swxY w Y   dS )z
        Dump the data_type as a local file, in order to get the dataset
         formation without calling the datahub.
        More details, please refer to the class
        `modelscope.utils.constant.DatasetFormations`.
        r  z3*** Automatically-generated file, do not modify ***N)	r   r   r  r  rn   formation_mark_extvaluer  write)r+  rO  dataset_type_file_pathfps       r   dump_datatype_filezHubApi.dump_datatype_file  s     "$n14\1B1B.pDUDhDn.p.p"r "r(#.. 	L"HHJKKK	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	Ls   A44A8;A8rM  c	           
      z   t          t                    }	t          |          }
t          |
         }|                     |          }t
                              ||           |s| j        }|D ]I}|d         }t          j	        
                    |          d         }||v r| d| d| d| d| 	}| j                            ||	          }t          |           t          j	                            ||          }t          j	                            |          r=t                               d
| d| d           |	|                             |           t'          |d          5 }|                    |j                   d d d            n# 1 swxY w Y   |	|                             |           K|	|
fS )Nr   )r+  rO  r	   r   rz  r   /repo?Revision=
&FilePath=r#  zReusing dataset z's python file ()wb)r   r  rn   ro   r   r   rV  r   r   r   splitextr   r   rP   r  r  rN  r^  r  r  rS  content)r   r  r  r;  rO  r+  rM  r   r   local_pathsdataset_formationdataset_meta_formatr   	file_info	file_path	extensionr)  r   
local_pathr  s                       r   "get_dataset_meta_files_local_pathsz)HubApi.get_dataset_meta_files_local_paths  s.    "$''-l;;01BC"""66 	!!|N![[[ 	%}H" 	: 	:I!&)I((33B7I///!) J JI J J J J*2J J>GJ JL$$['$BB%a(((W\\.)DD
7>>*-- NNV<VVVVV    	*11*===*d++ 'qGGAI&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' 'I&--j999---s   *FF	F	   c                    ddl }ddlm} ddl}t          j                            ||                    |                     d                    	                                          }|t          j        k    r3t          j                            |          rt	          j        |           t          j                            |          rt                              d|            |S t!                                          |          }t                              d           t%          j        | |d	
          }	t)          |	j                            dd                    }
 ||
d	          }fd}d}t-          |d          5 } ||	          D ]}|                    t1          |                     |                     d          r_d |D             }t1          |          dk    rY|dk    rd	}nd}|                    |          }|                    |d|d           |dz  }|D ]}|                    |dz              	 ddd           n# 1 swxY w Y   |                                 |S )zO
        Fetch the meta-data files from the url, e.g. csv/jsonl files.
        r   Nr   zUTF-8encodingzReusing cached meta-data file: r   zLoading meta-data file ...T)r   streamzcontent-length)r   dynamic_ncolsc              3      K   g }|                                  D ]E}|                    d          }|                    |           t          |          k    r|V  g }F|V  d S )Nutf-8)
iter_linesdecoder  r   )r*  
chunk_datar  r   s      r   	get_chunkz3HubApi.fetch_meta_files_from_url.<locals>.get_chunk  s      J)) $ ${{7++!!$'''z??j00$$$$!#Jr   ajsonlc                 ^    g | ]*}|                                 t          j        |          +S r   )rZ  r   loads)r  lines     r   r  z4HubApi.fetch_meta_files_from_url.<locals>.<listcomp>  s/    PPP$4::<<PTZ--PPPr   F\)indexheader
escapecharr   
)hashlib	tqdm.autor   pandasr   r   r  md5encode	hexdigestrq   FORCE_REDOWNLOADr  r  rN  r  r   r   rC  r   r  r   r  r   r   r+  	DataFrameto_csvrS  close)urlout_pathr   moder   r|  r   pdr   response
total_sizeprogressrq  iter_numr  r   with_headerchunk_dfrv  s     `                r   fetch_meta_files_from_urlz HubApi.fetch_meta_files_from_url  s    	""""""7<<'++cjj'j6R6R*S*S*]*]*_*_``<000RW^^H5M5M0Ih7>>(## 	KKD(DDEEEO((&&E&:: 	0111<WTBBB)--.>BBCC
4j===	 	 	 	 	 (C   	-A"8,, - -E

+++<<(( -PP%PPPE5zzQ 1}}&*&+!||E22HOOAU;SWOXXXMHH !& - -t,,,,--	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-$ 	s   	CIII	file_nameviewextension_filterc                     |r|r|st          d          d|||d}t          |          }|s| j        }| d| d| d| }	|	S )Nz:Args (file_name, dataset_name, namespace) cannot be empty!SDK)Sourcer  FilePathViewrz  r   /repo?)r   r   r   )
r   r  r  r  r;  r  r  r   r  file_urls
             r   get_dataset_file_urlzHubApi.get_dataset_file_url  s      	[ 	[I 	[YZZZ #(X9^bcc'' 	%}HYYYY\YYQWYYr   c           	          |s| j         }|r<t          j                            |          d         t          v r| d| d| d| d| 	}|S )Nr   rz  r   rX  rY  )r   r   r   r\  ri   )r   r  r  r  r;  r   s         r   get_dataset_file_url_originz"HubApi.get_dataset_file_url_origin>  s      	%}H 	D)))44R8<MMM# D Di D D, D D$,D D8AD DIr   c                 \    |s| j         }| d| d| d| }|                     ||          S )Nrz  r   /ststoken?Revision=r  )r   datahub_remote_call)r   r  r  r;  r   r   r)  s          r   get_dataset_access_configz HubApi.get_dataset_access_configL  s`      	%}H! 6 6I 6 6 6 6+36 6''5'AAAr   check_cookiec                 L   |s| j         }| d| d| d| }|r|                     d          }n|                     |          }| j                            |||                     | j                            }	|	                                }
t          |
           |
d         S )	Nrz  r   r  T)r  r   r  r   r   r$  )	r   r  r   r   r   r   r   r   rQ   )r   r  r  r  r;  r   r   r)  r   r   r*  s              r   !get_dataset_access_config_sessionz(HubApi.get_dataset_access_config_sessionY  s      	%}H! 6 6I 6 6 6 6+36 6 	;((T(::GG&&E&::GL((66  8 8 vvxxtF|r   versionc                 &   t           j                            t          j        d          }|st          dt          j                   | d}t          j                            | 	                    |                    }t          ||          }t          |          }| j                            ||||                     | j                  d          }	|	                                }
|
d	         d
k    rt          d|
           |
d         S )z.
        Get virgo dataset meta info.
        r   z"Virgo endpoint is not set in env: z/data/set/downloadr   )	dataSetIddataSetVersion)r  i  )r  r   r   r   r   r}  r   zFailed to get virgo dataset: r  )r   r   r   ru   env_virgo_endpointRuntimeErrorrC  utilsdict_from_cookiejarr   dictr   r   r   r   r   )r   rq  r  r   virgo_endpointvirgo_dataset_urlr   ru  r  r   r*  s              r   get_virgo_metazHubApi.get_virgo_metas  s&    (:(MrRR 	mkDVDikklll-AAA.44T5E5ESX5E5Y5YZZ "
 
 
 
 
 
 L"3#'&-&*&:&:4<&H&H&)	  + +
 vvxx<1EtEEFFFF|r   zip_file_namec                 R   |s| j         }| d| d| }|                     |          }| j                            |||                     | j                            }	|	                                }
t          |
           |
d         }t          j        |d                   }| d| }| j                            |||                     | j                            }|                                }t          |           |d         }|dz   dz   |z   d	z   |z   d	z   |z   }||d
<   |S )Nrz  r   r   r  r$  rF   r  z	-unzippedrm  Dir)	r   r   r   r   r   r   r   rQ   rG   )r   r  r  r;  r  r   r   r)  r   r   r*  r  r   datahub_sts_urlr_stsresp_stsdata_stsfile_dirs                     r   &get_dataset_access_config_for_unzippedz-HubApi.get_dataset_access_config_for_unzipped  sW     	%}H!NNINNNN"""66Lg%)%9%9$,%G%G  I IvvxxtF|"&tL'9::
(GGXGG  _g)-)=)=dl)K)K ! M M::<<x   F#+c1I=ClRUXX[hh"r   c	                     |s| j         }| d| d| d| d| d| d| }	|                     |          }
| j                            |	|
d	          }|                                }t          |           |d
         }|S )Nrz  r   z/oss/tree/?MaxLimit=
&Revision=r  z&FilterDir=r   i  )r  r   r   r$  )r   r   r   r   r   rQ   )r   r  r  	max_limitis_recursiveis_filter_dirr;  r   r   r  r   r*  s               r   list_oss_dataset_objectszHubApi.list_oss_dataset_objects  s      	%}H m mI m m m m#m m/7m mDPm m]jm m """66|C$GGyy{{tF|r   object_namec           	      "   |r|r|r|st          d          |s| j        }| d| d| d| d| 	}|                     |d          }| j                            ||          }	|	                                }	t          |	           |	d	         }	|	S )
NArgs cannot be empty!rz  r   z
/oss?Path=r  Tr   r  r   Messager   r   r   r   rH  r   rQ   
r   r  r  r  r;  r   r   r  r   r*  s
             r   delete_oss_dataset_objectz HubApi.delete_oss_dataset_object  s      	6, 	6i 	6x 	64555 	%}HqqIqqqqP[qqgoqq"""MM|""sG"<<yy{{tIr   c           	      "   |r|r|r|st          d          |s| j        }| d| d| d| d| 	}|                     |d          }| j                            ||          }	|	                                }	t          |	           |	d	         }	|	S )
Nr  rz  r   z/oss/prefix?Prefix=z/&Revision=Tr   r  r  r  r  s
             r   delete_oss_dataset_dirzHubApi.delete_oss_dataset_dir  s      	6, 	6i 	6x 	64555 	%}H & &I & & & &Yd & &#& & """MM|""sG"<<yy{{tIr   c                     |                      |          }| j                            ||dt                                          i          }|                                }t          |||           |d         S )Nr   r   rC  r$  )r   r   r   r   r   r   rL   )r   r  r   r   r   r*  s         r   r  zHubApi.datahub_remote_call  s|    """66L!#3#B#B#D#DE  G G vvxxsD!,,,F|r   use_streamingc           	      >   t          j        d          dk    }|s| j        }|rr|rq|sp|so	 |                     |          }| d| d| d}| j                            |||                     | j                            }	t          |	           t          j
        j        }
d}t          t           j        v rt           j        t                   }
t          t           j        v rt           j        t                   }| d| d| d	|
 d
| 	}| j                            |||                     | j                            }|                                }t!          |           d S # t"          $ r%}t$                              |           Y d }~d S d }~ww xY wd S d S d S d S )NCI_TESTr0  r   rz  r   z/download/increaserC  r   z/download/uv/z?user=)r   getenvr   r   r   r   r   r   rP   rp   LOCALrR  r#   r   r$   r   rQ   r\  rN  r]  )r   r  r  r  r   r   
is_ci_testr   download_count_urldownload_count_respchannel	user_namedownload_uv_urldownload_uv_resprI  s                  r   dataset_download_statisticsz"HubApi.dataset_download_statistics  s    Yy))V3
 	%}H 	 I 	 j 	  	  ***>> )1%o%o9%o%o|%o%o%o"&*l&7&78JT[@D@T@TUYUa@b@b '8 'd 'd#%&9::: */5	/2:== j)EFG,
:: "
+D EI%- #@ #@	 #@ #@L #@ #@%,#@ #@4=#@ #@ $(<#4#4_g=A=Q=QRVR^=_=_ $5 $a $a #3#8#8#:#: /00000      Q 3	  	  	  	  	  	  	  	 s   D4E% %
F/FFc                 ^    t           t          t          j                    j                  i|S r  )r(   r  r  r  r  )r   r   s     r   r   zHubApi.builder_headers	  s*    %s4:<<+;'<'<  	r   r  c                 $   |                      | j                  }|p%| j        pt          j                            d          }|s/|                                 }|r|D ]}|j        dk    r	|j        } n|r	d| |d<   n|rt          d          |S )a  
        Build HTTP headers with optional Bearer token for OpenAPI endpoints.

        Token resolution order:
            1. Explicit token param
            2. self.token (set at construction)
            3. MODELSCOPE_API_TOKEN env var
            4. Locally cached cookies (m_session_id from login())

        Args:
            token: Optional access token for one-time authentication.
            token_required: If True, raise ValueError when no token is available.

        Returns:
            Headers dict with user-agent, request-id, and optionally Authorization.

        Raises:
            ValueError: If token_required is True but no token is available.
        r   r   zBearer AuthorizationzAuthentication required but no token found. You can pass the `token` argument, or set MODELSCOPE_API_TOKEN environment variable, or use HubApi(token=`your_sdk_token`). Your token is available at https://modelscope.cn/my/myaccesstoken)
r   r   r   r   r   r   r   r.  rR  r   )r   r   r  r   resolved_tokenr   cookies          r   r  zHubApi._build_bearer_headers  s    , &&t|44  $$* $
"1$ 1$  	&&((G %  F{n44)/ 5  		'A'A'AGO$$ 	T   r   r  zrequests.Responsec                    	 |                                  }nS# t          j        j        t          f$ r5}t
                              d|            t          d|           |d}~ww xY wt          |t                    rMd|v rI|
                    d          du rd|v r|d         S |
                    d          pd}t          |          t          |t                    r|
                    di           ni S )	a'  
        Parse OpenAPI response with unified JSON parsing and data extraction.

        Handles the standard OpenAPI response envelope:
            {"success": bool, "data": {...}, "message": str}
        Also handles the simpler envelope where only "data" is present.

        Args:
            response: requests Response object (HTTP status already validated).

        Returns:
            Parsed 'data' dict from the response envelope.

        Raises:
            RequestError: If JSON parsing fails or business-level error is returned.
        zJSON parsing failed: zInvalid JSON response: NsuccessTr  messagezOpenAPI request failed)r   rC  rD  JSONDecodeErrorr   rN  r]  rK   r  r  r   )r  r*  rI  msgs       r   r  zHubApi._parse_openapi_response>  s   $	E==??DD#3Z@ 	E 	E 	ELL444555<<<==1D	E
 dD!! 	(i4&7&7xx	""d**v~~F|#hhy))E-E"3''' (2$'='=Etxx###2Es    A'0A""A'c                 Z    |                     d          \  }}|s| j        }| d| d| dS )Nr   rz  r  )r)  r   )r   rS  r   
_namespacerG  s        r   get_file_base_pathzHubApi.get_file_base_patha  sF    $+MM#$6$6!
M 	%}HOOZOO-OOOOr   )	r   r   rR  r   r   r   exist_okcreate_default_configr   r  r  c       	   	      >   |st          d          |s| j        }|                     ||||          }|rA|r,| d| d| }t                              d| d|            |S t          d| d          |                    d          }t          |          dk    rt          d	          |\  }}|t          k    r#d
 t          j	        
                                D             }|                    |                                          }|t          d| d          |                     |||||
||          }|	rt          j                    5 }ddlm}  |||||          }dddd}|                    d          }|si }i ||}t%          |dt'          j        |          gd           ddd           n# 1 swxY w Y   t+          d| dd           n|t,          k    rd t.          j	        
                                D             }|                    |                                          }|t          d| d          |                     |||||||          }t+          d| dd           nt          d| d t2                     |S )!a%  
        Create a repository on the ModelScope Hub.

        Args:
            repo_id (str): The repo id in the format of `owner_name/repo_name`.
            token (Union[str, bool, None]): The access token.
            visibility (Optional[str]): The visibility of the repo,
                could be `public`, `private`, `internal`, default to `public`.
            repo_type (Optional[str]): The repo type, default to `model`.
            chinese_name (Optional[str]): The Chinese name of the repo.
            license (Optional[str]): The license of the repo, default to `apache-2.0`.
            endpoint (Optional[str]): The endpoint to use.
                In the format of `https://www.modelscope.cn` or 'https://www.modelscope.ai'
            exist_ok (Optional[bool]): If the repo exists, whether to return the repo url directly.
            create_default_config (Optional[bool]): If True, create a default configuration file in the model repo.
            **kwargs: The additional arguments.

        Returns:
            str: The repo url.
        Repo id cannot be empty!rX  r   r>  rV  z already exists, got repo url: z already exists!r   zBInvalid repo id, should be in the format of `owner_name/repo_name`c                 D    i | ]\  }}|                     d           ||S __
startswithr  kvs      r   
<dictcomp>z&HubApi.create_repo.<locals>.<dictcomp>  s3    hhhTQUVUaUabfUgUghAqhhhr   NInvalid visibility: z9, supported visibilities: `public`, `private`, `internal`)r   r   r   r   r   r   r   r   rU   )r  r   pytorchztext-generationT)r  r  allow_remoteconfig_jsonzconfiguration.json)ignore_push_errorz"New model created successfully at r  flushc                 D    i | ]\  }}|                     d           ||S r  r  r  s      r   r  z&HubApi.create_repo.<locals>.<dictcomp>  s3    jjjTQWXWcWcdhWiWijAqjjjr   )r  r  r   r   r   r   r   z$New dataset created successfully at Invalid repo type: , supported repos: )r   r   r[  rN  r^  r)  r   rk   rE   __dict__itemsr   upperr2  tempfileTemporaryDirectorymodelscope.hub.repositoryrV   r^   r   dumpsprintrj   rC   r  rl   )r   rS  r   r   rR  r   r   r   r  r  r   kwargsr[  repo_urlrepo_id_listr  	repo_namevisibilitiestemp_cache_dirrV   r  default_configr  configs                           r   create_repozHubApi.create_repoh  s   H  	97888 	%}H ,,W	T\di,jj 	D D#+ D Di D D7 D DYwYYxYYZZZ !B!B!B!BCCC}}S))|!!abbb+	9''hh_-E-K-K-M-MhhhL*..z/?/?/A/ABBJ!  "\
 "\ "\ "\ ] ] ] -- %)%! .  H % 0022 0nDDDDDD%:ng%ZbcccD%. 1(,& &N
 #)**]";";K& )&(>>+>F',tz&/A/A.B*.0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0  BxBBB$OOOOO+++jj->-G-M-M-O-OjjjL*..z/?/?/A/ABBJ!  "\
 "\ "\ "\ ] ] ] //&#)%! 0  H DDDDDQQQQQ d9ddQbddeees   A!GGG)commit_descriptionr   rR  r;  r   
operationsr  c                ,   |st          d          |s| j        }|t          vrt          d| dt                     | d| d| d| }	|pd| }|pd}|                     |d	
          }
|                     ||          }| j                            |	|                     | j                  t          j
        |          |
          }|j        dk    rQ	 |	                                }n# t          j        $ r
 |j        }Y nw xY wd|j         d|	 d| }t          |          |	                                }|                    di                               dd          }t                              d|	            t#          |	|||          S )a  
        Create a commit on the ModelScope Hub.

        Args:
            repo_id (str): The repo id in the format of `owner_name/repo_name`.
            operations (Iterable[CommitOperation]): The commit operations.
            commit_message (str): The commit message.
            commit_description (Optional[str]): The commit description.
            token (str): The access token. If None, will use the cookies from the local cache.
                See `https://modelscope.cn/my/myaccesstoken` to get your token.
            repo_type (Optional[str]): The repo type, should be `model` or `dataset`. Defaults to `model`.
            revision (Optional[str]): The branch or tag name. Defaults to `DEFAULT_REPOSITORY_REVISION`.
            endpoint (Optional[str]): The endpoint to use.
                In the format of `https://www.modelscope.cn` or 'https://www.modelscope.ai'
            timeout (int): Timeout for each request in seconds (default: 180).

        Returns:
            CommitInfo: The commit info.

        Raises:
            ValueError: If the request fails with a 4xx client error.
            requests.exceptions.RequestException: If a network-level error occurs.
        r  r  r  /api/v1/repos/r>  z/commit/z
Commit to r   Tr   )r  r  r   r  r   r{  zHTTP z error from rA  r$  oidzCommit succeeded: )
commit_urlr  r  r  )r   r   rl   r   _prepare_commit_payloadr   r   r   r   r   r  rO  r  textr   rN  r  r~   )r   rS  r  r  r  r   rR  r;  r   r  r   payloadr  error_detail	error_msgr*  r  s                    r   create_commitzHubApi.create_commit  s   F  	97888 	%}H---d9ddQbddeeeQQQQgQQxQQ'A+A+A+A/52"""MM ..!) / 
 

 <$$((66G$$	 % 
 
 3&&-'}}' - - -'}-W 4WW#WWWWIY'''}}hhvr""&&ub11...///)1	
 
 
 	
s   C- -DD   z[Uploading])r   rR  r  r  buffer_size_mb	tqdm_descdisable_tqdmr;  path_or_fileobjpath_in_repor  r  r  c          
      d   |t           vrt          d| dt                      |st          d          |                     |d           t          |t          t
          f          r^t          j                            t          j        	                    |                    }|pt          j        
                    |          }n|st          d          t          |t          j                  r|                                }| j                            |           | j                            |g|           ||nd	| d
}|dk    rt          d          t#          ||          }|d         }|d         }|                     |||| j        dd           |                     ||||||
|	|          }t+          |||          }| j                            ||          rdnd|_        |d         |_        |g}t3          d| dd           |                     |||||||          }|S )a  
        Upload a file to the ModelScope Hub.

        Args:
            path_or_fileobj (Union[str, Path, bytes, BinaryIO]):
                The local file path or file-like object (BinaryIO) or bytes to upload.
            path_in_repo (str): The path in the repo to upload to.
            repo_id (str): The repo id in the format of `owner_name/repo_name`.
            token (Union[str, None]): The access token. If None, will use the cookies from the local cache.
                See `https://modelscope.cn/my/myaccesstoken` to get your token.
            repo_type (Optional[str]): The repo type, default to `model`.
            commit_message (Optional[str]): The commit message.
            commit_description (Optional[str]): The commit description.
            buffer_size_mb (Optional[int]): The buffer size in MB for reading the file. Default to 1MB.
            tqdm_desc (Optional[str]): The description for the tqdm progress bar. Default to '[Uploading]'.
            disable_tqdm (Optional[bool]): Whether to disable the tqdm progress bar. Default to False.
            revision (Optional[str]): The branch or tag name. Defaults to `DEFAULT_REPOSITORY_REVISION`.

        Returns:
            CommitInfo: The commit info.

        Examples:
            >>> from modelscope.hub.api import HubApi
            >>> api = HubApi()
            >>> commit_info = api.upload_file(
            ...     path_or_fileobj='/path/to/your/file.txt',
            ...     path_in_repo='optional/path/in/repo/file.txt',
            ...     repo_id='your-namespace/your-repo-name',
            ...     commit_message='Upload file.txt to ModelScope hub'
            ... )
            >>> print(commit_info)
        r  r  z$Path or file object cannot be empty!Tr   z#Arg `path_in_repo` cannot be empty!file_path_listrR  NzUpload z to ModelScope hubr   z4Buffer size: `buffer_size_mb` must be greater than 0)file_path_or_objr  	file_size	file_hashFrS  r   rR  r   r  r  )rS  rR  sha256r   r  r  r  r   r   r  file_hash_infolfsnormalis_uploadedzCommitting file to  ...r  rS  r  r  r  r   rR  r;  )rl   r   r   r  r  r	   r   r   abspathr   basenameioBufferedIOBaser   r   
check_filecheck_normal_filesrv   r  r   _upload_blobr   is_lfs_upload_mode_is_uploadedr  r  )r   r  r   rS  r   rR  r  r  r  r  r  r;  hash_info_dr%  r&  
upload_resadd_operationr  commit_infos                      r   upload_filezHubApi.upload_file(	  s   ^ ---d9ddQbddeee 	ECDDD 	edCCCoT{33 	H goobg.@.@.Q.QRRO'L27+;+;O+L+LLL   H !FGGG or'899 	5-2244O&&777..+, 	/ 	
 	
 	
 -8NN>h>h>h>h 	 QSTTT-,)
 
 
 %[1	$[1	$#,"&-"&/4 	 	6 	6 	6  ,, % - 	
 	

 -?%+&-
 -
 -

 /3.A.H.HZc.d.d%rUUjr"%/%>"#_
1G111>>>>"&"4"4!)1 #5 #
 #
 r   c                     |D ]+}|                     |d         |d         |d                    ,|                                 dS )z1Mark files as uploaded and persist tracker state.file_path_in_repo
file_mtimefile_size_on_diskN)mark_uploadedsave)r   trackerresultsr   s       r   _track_uploaded_batchzHubApi._track_uploaded_batch	  sY     	( 	(A!!%&,%&( ( ( ( 	r   c                 l    |                     d |D                        |                                 dS )z2Mark files as committed and persist tracker state.c                 <    g | ]}|d          |d         |d         fS )r@  rA  rB  r   r  r   s     r   r  z1HubApi._track_committed_batch.<locals>.<listcomp>	  sD     & & &  "#Q|_"#%& & &r   N)mark_committed_batchrD  )r   rE  rF  s      r   _track_committed_batchzHubApi._track_committed_batch	  sK    $$ & & & & & 	 	 	 	r   )rE  pre_validatedr@  rb  c                p   |t                      }d}d}	t          |t          t          j        f          }
|
rR	 t          j        |          }	|                    ||	j        |	j                  }||}||d<   n# t          $ r d}	Y nw xY w|\t          |          }|
rJ	 |	t          j        |          }	|                    ||	j        |	j        |           n# t          $ r Y nw xY w|	(|
r&	 t          j        |          }	n# t          $ r Y nw xY w|d         }|d         }d}t          t                    D ]}	 t          |t          t          j        f          rJt          j                            t          |                    }||k    rt!          d| d| d|           |                     ||||||t$          k    d	|z   d
z   ||	  	        } n# t&          t(          j        j        t(          j        j        t           f$ r}t          |t(          j        j                  r(t/          |d          r|j        |j        j        dk     r |}|t          dz
  k     rct5          t6          |z  t8                    }t:                              d|dz    dt           d| d| d| d           t?          j         |           Y d}~d}~ww xY wtC          dt           d| d|           ||||	r|	j        nd|	r|	j        n|"                    dd          |d         |"                    dd          |dS )z5Hash and upload a single file, returning result dict.Nr$  )r$  r%  r&  z.File size changed since hash computation: was z, now z. File may have been modified: z[Uploading r  )	rS  rR  r(  r   r  r  r  r   rM  r  r   r   zBlob upload attempt r   z failed for rA  , retrying in s ...zBlob upload failed after z attempts for r   r-  	is_reusedF)r@  rb  rA  rB  r-  rQ  r*  )#rZ   r  r  r   PathLikestatget_hashst_mtimest_sizeOSErrorrv   put_hashranger.   r   getsizer   r6  r2   ConnectionErrorrC  rD  r   hasattrr  rO  r   r/   r0   rN  r^  timesleepr  r   )r   r@  rb  rS  rR  r   rE  rM  r:  	file_statis_real_pathr(  r%  r&  
last_errorattemptcurrent_sizer;  rI  waits                       r   _upload_single_filezHubApi._upload_single_file	  sh    ?!mmG	!)c2;-?@@ 		!!GI..	 ))%y'99;LN N%"(K6?K 23 ! ! ! 			! +YGGGK  ($&GI$6$6	$$)9+=!);8 8 8 8    D GI..		    %[1	$[1	 
455 (	J (	JG#%i#r{);<< Q#%7??3y>>#B#BL#y00%P#,P P4@P P<MP PQ Q Q $(#4#4#'$""!*.P!P+.??#E"/ $5 
$ 
$
 #X%8%H'17< % % % a!4!>?? "q*-- "!*2H:1C77!
4q8888GC9; ;DNNXw{ X X=T X X&7X X;<X XLPX X XY Y Y Jt$$$%  9,C 9 9(9 9,69 9: :?IJ
 "3"09@),,q6?!d!2!2[__U`bcEdEd%m4#U;;)
 
 	
sO   >A8 8BB8C 
C%$C%-D 
DD<BG1KB:KK   )r  r   rR  r;  r   r   c                   d}	t          |          D ]`}
	 |                     |||||||          c S # t          t          j        j        f$ r}|}	Y d}~nd}~wt
          t          j        j        f$ r>}t          |d          r"|j        d|j        j        cxk    rdk     rn n |}	Y d}~ntd}~wt          $ rP}t          |          t          j        d          r ddg}t          fd	|D                       s |}	Y d}~nd}~wt          $ r}|}	Y d}~nd}~ww xY wt          d
|
z  d          }t                               d|
dz    d| d|	 d| d	           t%          j        |           bt)          d| d|	           |	)a  Commit with application-level exponential backoff retry.

        Retries on transient errors (5xx, ConnectionError) and specific
        retryable 4xx errors (e.g. git ref conflicts).
        Raises immediately on non-retryable client errors (4xx).
        Nr/  r  i  r   zHTTP 4\d{2}zCould not update refsz	try againc              3       K   | ]}|v V  	d S r  r   )r  p	error_strs     r   	<genexpr>z,HubApi._commit_with_retry.<locals>.<genexpr>O
  s'      JJ!qI~JJJJJJr   r   <   zCommit attempt r   r   z	 failed: rO  rP  zCommit failed after z attempts: )rY  r  r[  rC  rD  r   r\  r  rO  r   r  r  r  r  r\  r   rN  r^  r]  r^  r  )r   rS  r  r  r  r   rR  r;  r   ra  rb  rI  retryable_patternsrd  rj  s                 @r   _commit_with_retryzHubApi._commit_with_retry"
  sY   $ 
[)) $	 $	G))#)#1'9'% *      $X%8%HI   





x2<=   1j)) aj.Daj4::::s:::::





 	 	 	FF	9^Y77 /#*& JJJJ7IJJJJJ 





   





 qG|R((DNN+'A+ + + + +j + +#+ + +, , , JtG;GG:GG
 
	s:   5DAD54B..D;ADDDDrF  c                     g }|D ]r}t          |d         |d         |d                   }| j                            |d         |          rdnd|_        |d         |_        |                    |           s|S )z2Build CommitOperationAdd list from upload results.r@  rb  r*  r)  r+  r,  r-  )r   r   r7  r8  r9  r  )r   rF  rR  r  item_dopts         r   _build_batch_operationszHubApi._build_batch_operations_
  s     
 		# 		#F$#$78 &{ 3%&67  C
 )-(;(B(B{#Y)0 )0  >uu5= %m4Cc""""r   )
r   r  r  r   rR  allow_patternsignore_patternsmax_workers	use_cacher;  folder_pathrs  rt  ru  rv  c                   DEF t          j                     }st          d          |t          d          t          vrt          d dt                                          d           rnd|	r|	nd}	|	g }	nt	          |	t
                    r|	g}	|	t          z  }	fd|	D             }	||nd	 d
}|pd}t          t          g}|	|}	n.t	          |	t
                    r|	g|z   }	nt          |	          |z   }	t                              d                                |||	          }t          |          dk    rt          d| d          t                              dt          |           d            j                            d |D                                              j        dd           t%          |d           }t&          rKt)          t          |                    }t                              d| dt          |           d           n!t*          dk    rt*          nt          |          }t	          |t
          t,          f          r!t-          |                                          n+t-          |d                                                   j        }|r|t          z  }t3          |          Fnt5                      Ft7          t          |          |          Dg }t9                      Et;          |          D ]\  }\  }}t	          |t
          t<          j        f          r	 t=          j         |          }F!                    ||j"        |j#                  r+E$                    |           D%                    |           n7# tL          $ r*}t          '                    d| d|            Y d}~nd}~ww xY w|(                    |||ff           i }i }g }|D ]\  }\  }}t	          |t
          t<          j        f          rQ	 t=          j         |          }F)                    ||j"        |j#                  }|||f||<   in# tL          $ r Y nw xY w|(                    |||ff           |rd |*                                D             } +                    |           }|}tY          d! |*                                D                       }t                              d"t          |           d#| d$t          |          |z
   d%           t          E          } | dk    rt                              |  d&           t                              d't          |           d(|  d)t          |           d*           t                              d+t          |           d,Dj-         d-| d.           	 dhd/t\          d0t^          fD Ffd1}!g }"g }#g }$Dj-        }%	 ta          |
2          5 }&|D ]P\  }}'d}(||v r-||         d         d3         })|1                    |)          }(|(d}(|&2                    |!||'|(           Qtg          ti          |%          d4|%5          D ]}*|*|z  }+tk          |+|z   t          |                    },tm          Efd6ti          |+|,          D                       r%t                              d7|*d8z    d9|% d:           vD7                    |*          \  }-}.|.rC|$8                    |.           |.D ]+\  }/}0t          9                    d;|/d          d<|0            , :                    F|-            ;                    |-          }1|1s&t          9                    d7|*d8z    d9|% d=           '| d>|*d8z    d9|% d?}2	  <                    |1|2||@          }3|"(                    |3           |#8                    |-           t                              d7|*d8z    d9|% dAt          |-           dB            =                    F|-           # t|          $ r}t          9                    d7|*d8z    d9|% dC|            |-D ]-}4F?                    |4dD         |4dE         |4dF         dGH           .|-D ]'}4|$(                    |4dD         |4dI         f|f           (t          '                    d7|*d8z    d9|% dJt          |-           dK           Y d}~d}~ww xY w	 ddd           n# 1 swxY w Y   F@                                 n# F@                                 w xY w|$rUt          rN B                    |$F||||
L	  	        \  }$}5}6|"8                    |5           |#8                    |6           n(|$r%ti          t                    D ]}7|$s n	t                              dM|7d8z    d9t           dNt          |$           dO           g }8g }9|$D ]\  \  }}}:	  D                    ||FP          };|9(                    |;           :# t|          $ rC}t          9                    dQ| d<|            |8(                    ||f|f           Y d}~d}~ww xY w|9r9 :                    F|9            ;                    |9          }1|1r
	  <                    |1| dR|7d8z    d?||@          }3|"(                    |3           |#8                    |9            =                    F|9           t                              dS|7d8z    dAt          |9           dB           nr# t|          $ re}t          9                    dS|7d8z    dC|            |9D ]5};|8(                    |;dD         |;1                    dIdT          f|f           6Y d}~nd}~ww xY w|8}$F@                                 t          j                     |z
  }<t          |          }=t          |$          }>tY          dU |#D                       }?tY          dV |#D                       }@t          dW           t          dX           t          dY           t          dZ|=            t          d[|             t          d\|?            t          d]|@            t          d^|>            |?|@z   }At          d_|A            t          d`|<dadb           t          dW           |$r[|$D ]=\  \  }}B}0t          9                    dc| dJt          |0          jG         dJ|0            >|=|>z
  }Ct          dd|> de|C df          |"s1| t          |          k    rt                              dg           dS dS t          |"          d8k    r|"d         n|"S )iad  Upload a folder to ModelScope Hub with resumable support.

        Upload files from a local folder (or explicit file list) to a remote
        repository, with automatic batching, parallel upload, and progressive
        retry fallback (ReAct) for failed files.

        Args:
            repo_id: Repository identifier in 'owner/repo' format.
            folder_path: Local folder path, or a list of (path_in_repo, local_path) tuples.
            path_in_repo: Target directory path within the repository.
            commit_message: Commit message for the upload.
            commit_description: Optional extended commit description.
            revision: Branch or tag name (default: 'master').
            token: Authentication token. If None, uses stored credentials.
            repo_type: One of 'model', 'dataset', or 'space'.
            ignore_patterns: Glob patterns for files to exclude.
            max_workers: Max concurrent upload threads.
            use_cache: If True, uses .ms_upload_cache for resumable uploads.
                Files with matching path, mtime, and size that are already
                committed will be skipped automatically.

        Returns:
            None if all files were already committed (nothing to do).
            A single CommitInfo if only one batch was committed.
            A list of CommitInfo if multiple batches were committed.

        Raises:
            ValueError: If folder_path is empty or contains no valid files.
            RuntimeError: If any files remain failed after all retry rounds,
                with a message indicating the count and a retry hint.
        "The arg `repo_id` cannot be empty!Nz%The arg `folder_path` cannot be None!r  r  Tr   c                     g | ]}|v|	S r   r   )r  ri  rs  s     r   r  z(HubApi.upload_folder.<locals>.<listcomp>
  s*       a~.E.E.E.E.Er   z
Upload to z on ModelScope hubzUploading fileszPreparing files to upload ...)folder_path_or_filesr   rs  rt  r   z"No files to upload in the folder: r  z	Checking z files to upload ...c                     g | ]\  }}|S r   r   )r  rm  r  s      r   r  z(HubApi.upload_folder.<locals>.<listcomp>
  s    FFFWQDFFFr   r"  Fr'  c                     | d         S r   r   )r  s    r   <lambda>z&HubApi.upload_folder.<locals>.<lambda>
  s
    1Q4 r   )keyzAdaptive batch size: z (for z files))rS  zCannot stat file z, will re-upload: c                 6    g | ]\  }}|d          |d         dS )r&  r%  r  r   r   )r  r  rm  s      r   r  z(HubApi.upload_folder.<locals>.<listcomp>"  s>       D! [)43DEE  r   rS  rR  objectsr   c              3      K   | ]}|dV  	d S )Nr   r   )r  r  s     r   rk  z'HubApi.upload_folder.<locals>.<genexpr>*  s"      DDq!)))))DDr   zPre-validated z cached hash(es): z globally existing, z need upload.z% file(s) already committed, skipping.zScan complete: z total, z committed (skip), z to process.z
Uploading z file(s) in z batch(es) of size z (pipeline mode).file_idxra  c           	         |\  }}	 t                               d| d           
                    ||	|          }t                               d|                                | |           d S # t          $ rB}t                               d| d|                                | ||           Y d }~d S d }~ww xY w)NzUploading: r.  )rS  rR  r   rE  rM  z
Uploaded: zUpload failed:  - )rN  r  re  record_successr\  r]  record_failure)r  ra  rM  r   rb  resultrI  batch_trackerrS  rR  r   r   rE  s          r   _upload_workerz,HubApi.upload_folder.<locals>._upload_worker>  s   &/#L)E=<===>>>11 )#y"/	 2 1 1
 8,88999,,Xv>>>>> E E EC|CCCCDDD,,Xy!DDDDDDDDDEs   A-A7 7
C7B>>Cru  r&  z[Committing batches])descr   c              3       K   | ]}|v V  	d S r  r   )r  iskipped_indicess     r   rk  z'HubApi.upload_folder.<locals>.<genexpr>e  s(      WWA1/WWWWWWr   zBatch r   r   z fully committed, skipping.z
  Failed: r  z$: all files failed, skipping commit.z (batch rZ  r/  : committed 	 file(s). commit failed: r@  rA  rB  commit_failed
error_typerb  rA  z+ uploaded file(s) recovered to retry queue.)	failed_filesrE  rS  rR  r   r  r  r;  ru  zRetry round z: re-uploading z failed file(s) ...rS  rR  r   rE  z  Retry failed: z (retry round z  Retry round r   c              3   D   K   | ]}|                     d           dV  dS rQ  r   Nr   rJ  s     r   rk  z'HubApi.upload_folder.<locals>.<genexpr>  sG       : :aeeK&8&8:: : : : : :r   c              3   D   K   | ]}|                     d           dV  dS r  r  rJ  s     r   rk  z'HubApi.upload_folder.<locals>.<genexpr>  sG       > >!%%*<*<>> > > > > >r   z<============================================================zUpload Reportz<------------------------------------------------------------z  Total files      : z  Skipped (cached) : z  Existed (server) : z  Uploaded (PUT)   : z  Failed           : z  Committed        : z  Elapsed          : z.1fr_  z  - zERROR - zL file(s) failed to upload. Please manually try again. Successfully uploaded z8 file(s) will be automatically skipped during the retry.z!All files were already committed.r  )Ir]  r   rl   r   r  r  r{   rW   rY   r  rN  r  _prepare_upload_folderr   r   r5  r  r   sortedr-   r   r3   r	   resolveparentr[   rZ   rX   r   	enumerater   rR  rS  is_committedrU  rV  addmark_file_skippedrW  r^  r  rT  values_validate_blobsumnum_batchesr  tupler   r   submitr   rY  r   allwait_for_batchextendr]  rG  rr  rn  rL  r\  mark_failedrD  r:   _retry_failed_files_reactr4   re  r  typer   r  )Gr   rS  rw  r   r  r  r   rR  rs  rt  ru  rv  r;  
start_time_internal_ignoreprepared_repo_objectssorted_filescommit_batch_sizefolder_path_resolved
cache_pathfiles_to_uploadr  rb  strI  pre_validated_maphash_info_mapfiles_need_hashr(  r  	validatedreusedskipped_countr  commit_infosall_resultstotal_failed_filesr  executorra  pvcached_hash	batch_idxbatch_start	batch_endrF  failuresr  errr  batch_commit_messager=  r   react_commitsreact_resultsretry_roundretry_failuresretry_successes_errr  elapsedr   failed_countreused_countuploaded_countcommitted_countrm  	succeededr  r  rE  sG   ``    ```                                                           @@@r   upload_folderzHubApi.upload_folderr
  s   ^ Y[[
 	CABBBDEEE---d9ddQbddeee 	edCCC+9Ct-<F//$ " OO-- 	0./O22 %   *  O
 -8NN>f7>f>f>f 	 0D3D 34IJ".OO-- 	G./2BBOO"?336FFO 	3444 $ ; ;!,%)+	 !< !
 !
 $%%**Q+QQQRRRP$9 : :PPPQQQ..FF0EFFF 	/ 	
 	
 	

 	$#,"&-"&/4 	 	6 	6 	6 3HHH & 		( >s<?P?P Q QKK3(9 3 3L))3 3 34 4 4 4 ,a// )(&&  +T{33 _tK0088:::9=k!n9M9M9U9U9W9W9^ 	 	$-0FFJ#J@@@GG!mmG$S%6%68IJJ %%3<\3J3J 	J 	J/H/|Y)c2;%788 	QQ++B++L"+rzRR !'++H555%77AAA !  Q Q QNNOLOOAOOQ Q Q Q Q Q Q QQ ""H|Y.G#HIIII 3B 	J 	J/H/|Y)c2;%788 	++B$--$bk2:? ?F)392,h/  *    D""H|Y.G#HIIII  	9 ,3355  G ++9u , . .I !*DDI$4$4$6$6DDDDDFKK8W 8 88 8w<<&(8 8 89 9 9
 O,,1KK=OOOPPP2c,// 2 22 2?##2 2 2	3 	3 	3
 	<_-- < <=;T < <(< < <	= 	= 	= *.	E 	ES 	EU 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E" *,"$*,#/I	#<<< FZ+: 	M 	M'HiB=00&3H&=a&@&M.22;??:!%BOONHiLLLL!%eK&8&8?U]h!i!i!i :Z :ZI"+.?"?K #K2C$CSEVEV W WIWWWW{I9V9VWWWWW !$eY]$e$e[$e$e$efff (5(D(DY(O(O%GX I*11(;;;)1 I IID#"LL)Gd1g)G)G#)G)GHHHH ..w@@@!%!=!=gy!Q!QJ% !BY] B B[ B B BC C C ! *QQ9q=QQ;QQQ )Z&*&=&=$+'1+?/A"'&/%- '> ' ' %++K888#**7333AY] A A[ A A),WA A AB B B 33GWEEEE$ Z Z ZUY]UU[UURSUUW W W!( < <A#// !"5 6, !"5 6+: 0 < < < <
 ") O OA.55"#$7"8!K.!I1 MO O O OYY] Y Y[ Y Y"7||Y Y YZ Z Z Z Z Z Z ZZY:ZFZ FZ FZ FZ FZ FZ FZ FZ FZ FZ FZ FZ FZ FZ FZP LLNNNNGLLNNNN  =	4"6 =	4?C?]?]/#-#5!' @^ 
@ 
@<} ...}---- /	4$%CDD -4 -4) EQ;? Q Q5S Q Q$'(:$;$;Q Q QR R R "$"$7I 	N 	N3-\9tN!%!9!9()$+y"' ": ": ": (..v6666$ N N N%L%L%L%L%LMMM&--i/H!.LMMMMMMMMN # H..wHHH!%!=!='"4 "4J! HH*.*A*A(/+52@/b/bP[^_P_/b/b/b3E&+*3)1 +B +3 +3K )//<<<'..??? 77QQQ"KK!Mq !M !M-0-A-A!M !M !MN N N N  ) H H H"LL Uq U URS U UW W W*9 H H . 5 5&,-@&A&,jjb&A&A&CDE%G!H !H !H !HH H H H HH &4"" 	 )++
*,''-.. : :": : : : : > >"> > > > > 	hoh3k334445m556664l445556n667774l44555&77o778884g4444555h  	&*< Q Q&!q3OLOODII4FOO#OOPPPP#l2I%< % %% % %& & &  	L 1 111?@@@t4"%l"3"3q"8"8|AlJs   AN55
O)? O$$O)8>Q88
RRe (F(d<Ba#!d<#
d,-B4d'!d<'d,,d<0e <e  e e e e230i$$
j1.9j,,j1'Bm>>
o-Ao((o-c
                 b   g }
g }i }g }t          |          }g }|D ]}|\  \  }}}t          |          }|j        r|                    |           6|                    |           	 t	          |t
          t          j        f          rt          j        |          nd}n# t          $ r d}Y nw xY w|
                    ||r|j        nd|r|j        nd|j                   t                              d| d|j         d| d           |}dd	t!          d
|	dz            dddddd
dt"          dddd
d
t$          dg}t'          |          D ])\  }}|s n |d         }t                              d| dt+          |           d           g }g }|d         rt+          |          d
k    rddlm}m}  ||d                   5 }i }|D ]0\  \  }}} |                    | j        ||||||          }!||f||!<   1 ||          D ]g}!||!         \  }}	 |!                                }"|                    |"           8# t8          $ r#}#|                    ||f|#f           Y d}#~#`d}#~#ww xY w	 ddd           n# 1 swxY w Y   n,t'          |          D ]\  }$\  \  }}} |d         dk    r|$dk    ry|d
k    r!|d         dt;          |$t<                    z  z  n|d         }%t;          |%t>                    }%t                              d|% d| d           tA          j!        |%           	 |                     ||||||          }"|                    |"           # t8          $ rG}#t                              d| d| d |#            |                    ||f|#f           Y d}#~#d}#~#ww xY w|"                    |           t;          |d!         t!          d
t+          |                              }&tG          dt+          |          |&          D ]}'||'|'|&z            }(| $                    ||(           | %                    |(|          })|)s?	 | &                    ||)| d| d||||"          }*|
                    |*           | '                    ||(           t                              d| d#t+          |(           d$           # t8          $ rU}#t                              d| d%|#            |(D ]'}+|                    |+d&         |+d'         f|#f           (Y d}#~#d}#~#ww xY wg },|D ]}|\  \  }}}|(                    |d          d
z   ||<   ||         d(k    r|                    |           	 t	          |t
          t          j        f          rt          j        |          nd}n# t          $ r d}Y nw xY w|
                    ||r|j        nd|r|j        ndd)           t                              d*|            t          |          }|j        r|,                    |           	|                    |           	 t	          |t
          t          j        f          rt          j        |          nd}n# t          $ r d}Y nw xY w|
                    ||r|j        nd|r|j        nd|j                   t                              d| d|j         d           t+          |          t+          |,          z
  }-|-dk    r2t                              d| d+|- d,t+          |,           d-           n |,rt          )                    d| d.           |,}+||z   }.|r+t                              dt+          |           d/           |.|
|fS )0a  ReAct-style progressive retry for failed files.

        Implements Reason-Act-Observe loop with three escalating rounds:
          Round 1: Parallel retry with reduced concurrency (workers//2, batch=16)
          Round 2: Serial retry with exponential backoff (delay * 2^min(i, max_exp))
          Round 3: Single-file commit with long delays (one file per commit)

        Files that exceed the per-file retry limit are classified as permanent
        failures and will not be retried further.

        Args:
            failed_files: List of ((path_in_repo, file_path), error) tuples.
            tracker: UploadTracker or NullTracker instance.
            repo_id: Repository identifier.
            repo_type: Repository type.
            token: Authentication token.
            commit_message: Base commit message.
            commit_description: Commit description.
            revision: Branch or tag name.
            max_workers: Max upload concurrency from caller.

        Returns:
            Tuple of (all_failures, commit_infos, all_successes) where:
              - all_failures: list of ((path_in_repo, file_path), error) for
                files that could not be resolved (permanent + exhausted retries).
              - commit_infos: list of CommitInfo for successful retry commits.
              - all_successes: list of upload result dicts for successfully
                retried files (to be merged into the upload report).
        Nr   r  z[ReAct] Permanent failure: z (rA  rZ  zRound 1 (parallel)Tr   r   r  )r.  parallelworkers
batch_sizedelayzRound 2 (serial+backoff)F   zRound 3 (single-file)r.  z[ReAct] z: retrying z file(s) ...r  )r   as_completedr  r  r  r  z[ReAct] Waiting zs before retrying r.  z	: failed r  r  r/  r  r  r  r@  rb     max_retries_exceededz![ReAct] Max retries exceeded for u   : made progress — z file(s) resolved, z remaining.z(: no progress, escalating to next round.z. file(s) still failing after all retry rounds.)*r  r\   is_retryabler  r  r  r   rR  rS  rW  r  rU  rV  rR  rN  r]  r   r<   r=   r  r  r   concurrent.futuresr   r  r  re  r  r\  r   r9   r;   r]  r^  r  rY  rG  rr  rn  rL  r   r^  )/r   r  rE  rS  rR  r   r  r  r;  ru  r  all_successesretry_countspermanent_failures	retryable	remainingitem_errr   rb  r  categoryr  round_configs	round_idxr  
round_nameround_successesround_failuresr   r  r  
future_mapr  futurer  rI  r  r  r  r  batchr  r=  r   new_retryabler  all_failuress/                                                  r   r  z HubApi._retry_failed_files_react  sg   R  &&	 	! 	2 	2H-5*%\9s%c**H$ 2  ****"))(333/9!C#507 07 A+++<@ B   BBB## #%,BKK1"$+BJJ!'~	 $ / / /
 1, 1 1 1 1*-1 1 12 2 2 2 	 - q+"233   3!7  0!7 
0 (66 N	& N	&NIs VJKKN:NN#i..NNNP P P !ON : )<3y>>A#5#5OOOOOOOO''C	NCCC @x!#J;D G G71y4!) 4()$+y"'	 "1 ": ":
 /;I-F
6**".,z":": @ @2<V2D/i@%+]]__F+226::::( @ @ @*11".	!:A >@ @ @ @ @ @ @ @@@@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$ =Fi<P<P < <8A81y47|a''AEE$-NN "%Wc!=^6_6_1_!`!`&)'l  !$E+A B B;u ; ;(4; ; ;< < < 
5)))<!%!9!9()$+y"' ": ": ": (..v6666$ < < <;z ; ;&2; ;78; ;< < < '--*I6:< < < < < < < <	<   111 S.As?7K7K0L0LMMJ$QO(<(<jII 3 3'K*4L(LM**7E:::!99%KK
! 3"&"9"9 '#-->>>>>+=#"+!) #: #+ #+K !''444//???KK;: ; ;%(ZZ; ; ;< < < < ! 3 3 3LLB:BBqBBD D D # 3 3&-- 34n./023 3 3 33 3 3 3 3	3 M* #/ #/19.)y3-9-=-=lA-N-NQR-R\*-22&--h777"3=%R['94; 4; ERWY///@D " " " "!"''$')0q&(/

a#9	 ( ; ; ;
 LLJLJJL L L)#..( /!((2222&--h777"3=%R['94; 4; ERWY///@D " " " "!"''$')0q&(/

a#+>	 ( 3 3 3
 LL.l . .$N. . ./ / / / 9~~M(:(::H!||7z 7 77 7=))7 7 78 8 8 8  21z 1 1 12 2 2 &II *I5 	,LL+3y>> + + +, , , \=88s   (7B  B/.B/	AI?)II?
I/	I*	%I?*I/	/I??J	J	30M$$
N5.<N00N5A;S
T7"A
T22T77V??WW7ZZ$#Z$)r  r  r  r   rM  r(  r   r  c       
            t          d ddd d           }|
du r2t                              d|d d          d           d|d<   d|d<   |S t          |
t                    r|
}nf|                     ||||d	g|	
          }|                    |          }|2t                              d|d d          d           d|d<   d|d<   |S |                     |	d          }|rt          |          nd }|t          d          | j	        
                    dd|d          i           |                     | j	                  }|dz  dz  }t	          |          |d<   t          |dd||          5 }t          |t          t          f          rrt          |d          5 }t          ||||          }| j                            |||t$                    }d d d            n# 1 swxY w Y   |                                 nt          |t(                    r\t          t+          j        |          |||          }| j                            |||t$                    }|                                 nst          |t*          j                  rJt          ||||          }| j                            |||t$                    }|                                 nt          d          d d d            n# 1 swxY w Y   t1          |           |                                }t5          |           ||d<   d|d<   |d         |d<   |d         |d<   |S )NF)r  r-  rQ  rO  
status_msgTzBlob r  z  already exists globally, reuse.r-  rQ  r  r  r   rB  Cookiezm_session_id=r   rf  zContent-LengthB)r   unit
unit_scaler  disablerb)r   r  r   zInvalid data type to uploadrspr  r@  rO  r  r  )r  rN  r  r  r  r  r   r   r   r   r   r   r   r	   r  r   r   r  r1   r   bytesr2  BytesIOr3  rP   r   rQ   )r   rS  rR  r(  r   r  r  r  r  r   rM  res_d
upload_urlr  r   r   r   r   r  rj  r  r*  s                         r   r6  zHubApi._upload_blob  se    
 
 
 D  KKLrr
LLLMMM#'E- !%E+LmS)) 	&JJ++#!'667	 ,  I #v..J!PF2A2JPPPQQQ'+m$%)k""""MM#*4$w---?HIIIX'Pw~7N'P'PQRRR&&t|44#d*T1
$'II !$
 
 
 *	@ $d,, #@$%% /4z3 3F#|//" '# 3	  0    H               &&((((D%(( @+Jt$$dD*> ><++#/	 ,   &&((((D""344 @+$j2 2<++#/	 ,   &&(((( !!>???U*	@ *	@ *	@ *	@ *	@ *	@ *	@ *	@ *	@ *	@ *	@ *	@ *	@ *	@ *	@X 	(++++}}4    !e#m#F|m"9ols7   1-K06G K0 G$	$K0'G$	(C<K00K47K4)r   r   r  c                   |s| j         }i }t          }t          dt          |          |          D ]G}||||z            }	| d| d| d}
d|	d}|                     |d          }| j                            |
|                     | j                  t          j
        |          |	          }t          |
           |	                                }t          |
           |d         d         }t                      }|D ][}|                    di           }|                    d          }|r,|d         ||d         <   |                    |d                    \|	D ]}|d         |vrd||d         <   I|S )a   Validate whether blobs need uploading.

        Queries the LFS batch API in chunks of UPLOAD_VALIDATE_BLOB_BATCH_SIZE.

        Args:
            repo_id: The repo id on ModelScope.
            repo_type: The repo type ('dataset', 'model', etc.).
            objects: Objects to check, each with 'oid' (sha256) and 'size'.
            endpoint: API endpoint override.
            token: Access token.

        Returns:
            Dict mapping oid -> upload_url (needs upload) or None (already exists).
        r   r  r>  z/info/lfs/objects/batchupload)	operationr  Tr   r  r  r$  r  actionshrefr  N)r   rA   rY  r   r   r   r   r   r   r   r  rP   rQ   r   r   r  )r   rS  rR  r  r   r   r  r  r  r   r  r  r   r  r*  resp_objectsneeds_uploadobjr  upload_actionos                        r   r  zHubApi._validate_blobr  s   .  	%}H+-4
q#g,,
33 !	, !	,AAa*n,-EZZYZZ'ZZZC%  G
 &&ED&QQG|((,,T\::Z((	 )  H "h////==??Dt$$$$<	2L55L# 1 1'')R00 'H 5 5  1)6v)>F3u:& $$SZ000  , ,U8<//'+F1U8$, r   r{  c                   	
 d 	d }t          |t                    r7t          j                            |d                   r|}n4t          d          t          j                            |          r|g}n|	|| j                            	           t          	          	                                
                                		                                st          d	 d          	fdt          	                    d                    D             nbi |D ]]}t          j                            |          r<| j                            |           |t          j                            |          <   ^t          t!          j                                        ||                    }|r|                    d           dnd	

fd
|D             }t(                              dt-          |           d           |S )Nr   z0Uploading multiple folders is not supported now.zProvided path: 'z' is not a directoryc                     i | ]>}|                                 |                                                              |?S r   )is_filerelative_toas_posix)r  r   rw  s     r   r  z1HubApi._prepare_upload_folder.<locals>.<dictcomp>  sS     " " "<<>>"  --6688$" " "r   z**/*)rs  rt  r   r   c                 D    g | ]}|z   t          |                   fS r   )r  )r  relpathprefixrelpath_to_abspaths     r   r  z1HubApi._prepare_upload_folder.<locals>.<listcomp>  sA     !
 !
 !
 gs#5g#>??@!
 !
 !
r   z	Prepared z files for upload.)r  r  r   r   r  r   r   check_folderr	   r   r  is_dirr  globr4  r1  r   filter_repo_objectskeysrZ  rN  r  r   )r   r{  r   rs  rt  
files_pathr   filtered_repo_objectsr  rw  r  r  s            @@@r   r  zHubApi._prepare_upload_folder  sS    
*D11 		3w~~21566 U1

 !STTTw~~233 323

2,,[999{++6688@@BBK%%'' W !UK!U!U!UVVV" " " "";#3#3F#;#;<<" " " "$" F F7>>$'' F'224888AE&rw'7'7'='=> !%)"'')).Zi  !
 !
 3?FL&&s++....B!
 !
 !
 !
 !
0!
 !
 !

 	N$9 : :NNNOOO$$r   c                    |g d}d}| D ]C}t          |t                    r0|j        r)t                              d|j         d           |dz  }Ht          |t                    rd|j        dk    rYd|j        d|j        j        d|	                                
                                d	d
}|d                             |           t          |t                    rK|j        dk    r@d|j        d|j        j        |j        j        ddd
}|d                             |           !t          d| dt          |dd                     |dk    rt                              d| d           |S )zN
        Prepare the commit payload to be sent to the ModelScope hub.
        )r  r  r   zSkipping file 'z(' in commit (ignored by gitignore file).r   r,  creater   base64)actionr   r  r   r(  r]  ri  r  r+  z(Unknown operation to commit. Operation: z. Upload mode: r8  NzSkipped z/ file(s) in commit (ignored by gitignore file).)r  r   _should_ignorerN  r  r   r8  upload_infor   
b64contentro  r  r(  r   r   r  )r  r  r  nb_ignored_filesr  commit_actions         r   r  zHubApi._prepare_commit_payload  s    -
 

  $ (	 (	I )%788 Y=U oy/Eoooppp A%  )%788 Y=SW_=_=_ '%2$%16 (3355<<>> (! ! 	"))-8888 I'9:: y?UY^?^?^ '%2!%16'3:! "! ! 	"))-8888 !Cy C C	>4@@C C  
 aKKd#3dddeeer   皙?internal_timeoutc                    dt           dt          fd}| j         d} |||          }d}|S|                                }d|v r|d         d	         }nd}|r( |||
          }||j                                        }|S )a  
        Get the internal acceleration domain.

        Args:
            internal_timeout (float): The timeout for the request. Default to 0.2s

        Returns:
            str: The internal acceleration domain. e.g. `cn-hangzhou`, `cn-zhangjiakou`
        r  r   c                     	 t          j        | |          }|                                 n# t           j        j        $ r d }Y nw xY w|S )Nr   )rC  r   raise_for_statusrD  rE  )r  r   r  s      r   send_requestz>HubApi._get_internal_acceleration_domain.<locals>.send_request8  sa     #<W===))++++&7        Os   *- AAz&/api/v1/repos/internalAccelerationInfo)r  r   r   Nr$  InternalRegionQueryAddressr   )r  floatr   r   r  rZ  )r   r(  r,  internal_urlinternal_info_response	region_id
query_addrdomain_responses           r   !_get_internal_acceleration_domainz(HubApi._get_internal_acceleration_domain-  s    	c 	E 	 	 	 	 -OOO ".,HX!Y!Y!Y	!-%;%@%@%B%B"///3F;<XY

"$
 =".,zCS"T"T"T". / 4 : : < <Ir   )r;  r   r   delete_patternsc          
         |t           vrt          d|           |st          d          t          |t                    r|g}|                     |d          }|s| j        }|t          d          |                     | j                  }|t          k    r/| 	                    ||pt          d||          }	d |	D             }
n|t          k    rg }
|                    d	          \  }}|                     ||||
          \  }}d}d}	 	 |                     ||pt          d|||||          }nD# t           $ r7}t"                              d| dt          |                      Y d}~nNd}~ww xY w|D ])}|d         dk    r|
                    |d                    *t)          |          |k     rn|dz  }nt          d| dt                      g }|
D ]3}|D ].}t+          j        ||          r|                    |            n/4g g }}|D ]J}	 |t          k    r0|                    d	          \  }}| d| d	| d}|pt          |d}nM|t          k    r(|                    d	          \  }}| d| d	| d}d|i}nt          d| dt                      | j                            ||||          }t1          |           |                                }t5          |           |                    |           # t           $ rM}|                    |           t"                              d| dt          |                      Y d}~Dd}~ww xY w||t)          |          dS )am  
        Delete files in batch using glob (wildcard) patterns, e.g. '*.py', 'data/*.csv', 'foo*', etc.

        Example:
            # Delete all Python and Markdown files in a model repo
            api.delete_files(
                repo_id='your_username/your_model',
                repo_type=REPO_TYPE_MODEL,
                delete_patterns=['*.py', '*.md']
            )

            # Delete all CSV files in the data/ directory of a dataset repo
            api.delete_files(
                repo_id='your_username/your_dataset',
                repo_type=REPO_TYPE_DATASET,
                delete_patterns='data/*.csv'
            )

        Args:
            repo_id (str): 'owner/repo_name' or 'owner/dataset_name', e.g. 'Koko/my_model'
            repo_type (str): REPO_TYPE_MODEL or REPO_TYPE_DATASET
            delete_patterns (str or List[str]): List of glob patterns, e.g. '*.py', 'data/*.csv', 'foo*'
            revision (str, optional): Branch or tag name
            endpoint (str, optional): API endpoint
            token (str, optional): Access token
        Returns:
            dict: Deletion result
        zUnsupported repo_type: zdelete_patterns cannot be emptyTr   NrB  )r;  rf  r   r  c                     g | ]
}|d          S r   r   )r  r  s     r   r  z'HubApi.delete_files.<locals>.<listcomp>  s    333!F)333r   r   r/  r   r   )rS  r;  rf  r  r  r   r   r9  zGet dataset: z file list failed, message: r&  treer	   r  r7  z/file)r  r  rz  z/repor  r?  zFailed to delete rA  )deleted_filesr  r   )rl   r   r  r  r   r   r   r   rk   rl  rf   rj   r)  r,  rs  re   r\  rN  r]  r  r   fnmatchr   rH  rP   r   rQ   ) r   rS  rR  r5  r;  r   r   r   r   r  
file_pathsrF  rG  _hub_idrm  r  r  dataset_filesrI  file_info_d	to_deleter   delete_patternr9  r  ownerr  r  r  r  r   r*  s                                    r   delete_fileszHubApi.delete_filesT  s   H ---ByBBCCC 	@>???os++ 	0./O"""MM 	%}H?HIII&&t|44 ''((!;%;!# )  E 43U333JJ+++J$+MM#$6$6!FM55*fxW\ 6 ^ ^JGQKI!:>:P:P '!)!E-E"&$/"+!)#'. ;Q 	; 	;MM !   LL!^!^!^VYZ[V\V\!^!^___EEEE
 $1 ? ?K"6*f44"))+f*=>>>}%%	11q 1!4 hyhhUfhhiii 	 	 	D"1  ?488 $$T***E ')"| 	C 	CDC//'.}}S'9'9$E9%NNeNNiNNNC$,$F0F$( FF "333*1--*<*<'E<%SSSSSSSC"DFF %%py%p%p]n%p%pqqqL''FGU\']]%a(((vvxxt$$$$$T**** C C C##D)))AAAQAABBBBBBBBC
 +(y>>
 
 	
s2   $D6 6
E7 -E22E7C-L
M"AMM")modeldatasetprivatepublicc                 X   |st          d          |dvrt          d| d          d t          j                    D             }|                    |d          }|                     |d          }|t
          k    r|                     ||	          }| j         d
| }	|                    d          }
d}t          |
t                    r6|
r4|
d         }t          |t                    r|r|                    d          }|                    dd          |                    dd          |d|                    dd          |                    dd          |                    dd          |                    dd          |                    dd          |                    dd          |                    di                               dd          |                    di                               dd          ||                    dd          d}n|t          k    r|                    d          }t          |          dk    st          |          st          d | d!          |                     |d"         |d         |#          \  }}| j         d$| }	|dd%}nt          d&| d't                      | j                            |	|||                     | j                  (          }t+          |           |                                }t/          |           |S ))aK  
        Set the visibility of a repo.

        Args:
            repo_id (str): The repo id in the format of `owner_name/repo_name`.
            repo_type (Literal['model', 'dataset']): The repo type, `model` or `dataset`.
            visibility (Literal['private', 'public']): The visibility to set, `private` or `public`.
            token (Union[str, None]): The access token. If None, will use the cookies from the local cache.
                See `https://modelscope.cn/my/myaccesstoken` to get your token.

        Returns:
            dict: The response from the server.
        ry  rE  r  z-, supported visibilities: `private`, `public`c                     i | ]\  }}||	S r   r   r  s      r   r  z.HubApi.set_repo_visibility.<locals>.<dictcomp>  s    )Q)Q)Q41a!Q)Q)Q)Qr   rf  Tr   )r   r   r7  rt   r   r   r.  r  ModelFrameworkPytorchr   ApprovalModer  r
  r  
ModelCoverSubScientificFieldNNEXAScientificFieldr  r  )r  rJ  rF   ProtectedModerL  r  r
  r  rM  rN  rP  r  	ModelTaskr  r   zInvalid dataset repo_id: z-, should be in format of `owner/dataset_name`r   )r  r  r   rz  )rF   rQ  r  r  r  )r   rG   r  r   r   rk   rQ  r   r  r  r  rj   r)  r   r  r,  rl   r   r  r   r   rP   r   rQ   )r   rS  rR  r   r   visibility_mapvisibility_coder   ro  r   tasksmodel_tasksfirstr  repo_id_partsdataset_idxrm  r   r*  s                      r   set_repo_visibilityzHubApi.set_repo_visibility  sX   &  	CABBB222mJmmmnnn)Q)Q=;N;P;P)Q)Q)Q-11*a@@"""MM''FFJm==G==DNN7++EK%&& 45 4aeT** 4u 4"'))F"3"3K)~~mR@@",..1A9"M"M-!" *~q A A)~~mR@@&NN:r::$.NN3Er$J$J(nn\2>>&0nn5I4&P&P#->>&"#=#=#A#ABSUW#X#X$..44882FF(%>>)R88 GG  +++#MM#..M=!!Q&&c-.@.@& !sW!s!s!sttt!99*1-'* :  NK mCCkCCD-!" GG
 d9ddQbddeeeL((66	  8 8 	a   vvxxtr   skillcollection_idc                 p   |s| j         }|dk    rt          d| d          |                                 }| d}||||d}| j                            ||||                     | j                            }	t          |	           |	                                }
t          |
           |
t                   S )a  Get collection details and its elements.

        Args:
            collection_id (str): The collection ID (Fid).
            repo_type (str): Element type filter, only 'skill' is supported currently.
            page_number (int): Page number for pagination.
            page_size (int): Page size for pagination.

        Returns:
            dict: Collection details including elements.

        Raises:
            ValueError: If repo_type is not 'skill'.
            RequestError: If the API request fails.
        r[  z
repo_type=z7 is not supported, only "skill" is currently supported.z/api/v1/collections)FidElementTyper6  r7  r?  )r   r   r   r   r   r   r   rP   r   rQ   r   )r   r\  rR  r  r  r   r   r   r  r   r   s              r   get_collectionzHubApi.get_collection4  s    *  	%}H7Y 7 7 78 8 8 ""$$/// $%!	
 
 LT&'%)%9%9$,%G%G  I Ia   FFHHq())r   skill_id	local_dirc                    |s| j         }t          j        |          \  }}|                                 }| d| d| d}|t	          j                    }t	          j        |d           t          j                            ||          }| j	        
                    |d||                     | j                            }	t          |	           t          j                            || d          }
	 t          |
d	          5 }|	                    d
          D ]}|r|                    |           	 ddd           n# 1 swxY w Y   t          j                            |          rt%          j        |           t	          j        |d           t)          j        |
d          5 }|                    |           ddd           n# 1 swxY w Y   t	          j        |          }t1          |          dk    rt          j                            ||d                   }t          j                            |          r|t	          j        |          D ]S}t%          j        t          j                            ||          t          j                            ||                     Tt	          j        |           t          j                            |
          rt	          j        |
           n9# t          j                            |
          rt	          j        |
           w w xY wt:                              d| d| d|            |S )a  Download a single skill archive and extract it.

        Args:
            skill_id (str): The skill identifier in format '<path>/<name>'.
            local_dir (Optional[str]): Target directory for extraction.
                Defaults to current directory.

        Returns:
            str: Path to the extracted skill directory.

        Raises:
            ValueError: If skill_id format is invalid.
            RequestError: If the download request fails.
        z/api/v1/skills/r   z/archive/zip/masterNTr  )rj  r   r   z.zipr[  i    )r   r   r   r   zSkill z downloaded to )r   r   validate_repo_idr   r   getcwdmakedirsr   r  r   r   r   r   rP   r  iter_contentrS  r  r  r  zipfileZipFile
extractallr  r   r  movermdirr  rN  r  )r   ra  rb  r   element_pathelement_namer   r  	skill_dirr   zip_pathr  r   zfentries
nested_dirr  s                    r   download_skillzHubApi.download_skill^  s   "  	%}H%.%?%I%I"l""$$ZZ,ZZZZZ	I
I---- GLLL99	LSw%)%9%9$,%G%G  I Ia    7<<	l+@+@+@AA	$h%% '^^t^<< ' 'E ''' ' ' ' ' ' ' ' ' ' ' ' ' ' ' w~~i(( )i(((K	D11113// )2i((() ) ) ) ) ) ) ) ) ) ) ) ) ) ) j++G7||q  W\\)WQZ@@
7==,, ) "
: 6 6 ; ;GLLT::GLLD99; ; ; ; HZ(((w~~h'' $	(### w~~h'' $	(####$ 	T\TTLTTTTUUUsV   4K4 1E6K4 EK4 	E
A!K4 +GK4 GK4 GC+K4 46L*)NFr   )NNNr  )r   r   NN)F)NFN)FN)Tr   r   NN)r   N)FNN)r'  )r[  r   r;  N)yr   r   r   r   r   r   r   r  r   r   r  r   r   rE   PUBLICrD   	APACHE_V2r  r2  r=  rI  rK  rf   r  rQ  rc  rT   ro  rS   ru  rk   r   rx  r[  r  staticmethodr  rg   r   r  r  r  r   r  r  r  r  r  r  r   r  r  rl  r  rC   r  r  r!  __annotations__r,  r:  rk  rs  rr  rN  rV  r  re  rq   REUSE_DATASET_IF_EXISTSr  re   r  r  r  r  r  r  r  r  r  r  r  r   r   r  r
   r  r  rF   r]   r  r   r   r~   r  r	   r   r   r>  rG  rL  re  rn  rr  r!   r@   r  r  r6  r  r  r  r  r.  r4  rB  r   rZ  r`  ru  r   r   r   r   r      s,          ,008(,	"/ "/#C="/ !	"/ "/ "/ "/H    ,  PXY]P^    @ +/&*-: -:"3--: sm-: -: -: -:b 2A1G.6.@378:/3,09=g g"g!)#g 'smg $,C=	g
 )1g  (}g %SMg "*+!6g CFg g g gX 4804=AU U#&U#&U $,C=U !)	U
 &.k%:U
 GJU U U Un!! !!S !!HSM !!QYZ]Q^ !! !! !! !!F: :c :Xc] : : : : '=&*#'+% +%+% sm+% sm	+%
 C=+% 
+% +% +% +%` :>59	)# )# )#'*)# *2#)# &.c]	)# ?B	)# )# )# )#\ .D-1	   &c] &c]	 7@	   F 04/3	  !  (}  (}	 9D	   H $3"8"&!a !a !a!a C=	!a
 3-!a 3-!a 
y+%	&!a !a !a !aN (,&*',#'8 8 88  }	8
 sm8 tn8 C=8 
8 8 8 8z /3+/	-= -= -="-= 'sm-= $C=	-= -= -= -=^ ! ! \! 0?/E,4,>153A(,-H6:JNAE*.Q7 Q7 Q7!Q7  (}Q7 %SM	Q7
 "*#Q7 $,C=Q7 !Q7 &c]Q7 '/smQ7 )1tCy#~1F(GQ7  (c49n(=>Q7 #3-Q7 Q7 Q7 Q7j 23/1.2+/( ($'(!)#(  (}( 'sm	(
 $C=(
 59( ( ( (Z 4513,0.204-16/ 6/ 6/&)6/ $,C=6/ "*#	6/
 %SM6/ 'sm6/ !)6/ &c]6/ 7;6/ 6/ 6/ 6/p tY)? I     /327	  'sm tY/	 =AI	   6 /327&* +  + + 'sm + tY/	 +
 sm +
 04Cy +  +  +  +D   ,0AE<@	B B,/B ,4I+>B -5SM	B B B BL %):>59	M M%(M %-Y$7M &.c]	M M M M 38&*	L LL tY/L sm	L
 
tCy$s)#	$L L L L@ 38  tY/ 
tCy$s)#	$	   2 3I.249>C24264 4"%4"*3-4 'sm4 $,D>	4
 &+4?%;4 "*$4 #+3-4 <@:4 4 4 4v '+#'! ! !! !
 sm! C=! ! ! !@ 68080B3D3K4615.26  6 %(6 "%6  &.c]6  !)	6 
 $,C=6  %-SM6  "*#6  'sm6  8;6  6  6  6 t 26.2!! !!#&!!!)#!! 'sm!! !! !! !!F $&D%%%
 ;?7;	( (.1(+.( +33-( (0}	( ( ( (6 *.*+(+15.2   %( "%  "%  #&	 
 #'  %(  #&  "*#  'sm       J 6E4O-.+-4815=Y =Y =Y#&=Y &.c]=Y %-SM	=Y
 (+=Y &)=Y %-SM=Y "*#=Y =Y =Y =YD +F+.,0-.+.4815:><' <' <'#&<' %(<' &)	<'
 &*<' (+<' &)<' %-SM<' "*#<' +33-<' <' <' <'B #>"&#!- !-!- 3-!- 3-	!-
 }!- !- !- !-H ^b:> s s /2>AMUVY]*23-   , 
L 
Lc 
L 
L 
L \
L  FJBF". ".s ".69".58". <?". OR". _c". 6>c]	".
 3;3-". ". ". ".H <@|Gk9=6 6)1#6 6 6 \6z '?#(/3&*   	
 sm 4. 'tn sm   J '?&*   	
 sm sm   $ '?&*#'B BB B sm	B
 smB C=B B B B$ '?&*#'   	
 sm sm C=   4  s xPS} `d    D JNFJ =@:= := ?B	
 :B# 7?sm   < cg8< RZ[^R_(0     \`9= S  -0<?KSTW=)1#BE   " Y]6: # S *-9<HPQT&.sm?B   " hsm     \`;?           37  KSTW=  +3C=  DH           D  
 6:5:/ /%-c]/.2/?CCH~/ / / /b  F*=  F$sCx.  F  F  F \ FDP P# P# PRU P P P P -1(2(9'6*.%-%7&*',48.2m m mm dD)	m
 !m  }m #3-m c]m smm tnm $,D>m !+m 
m m m mj 15'6&A&*O
 O
 O
O
 !1O

  O
 !)O
 O
  }O
 smO
 smO
 
O
 O
 O
 O
n '+'6,004,.'4+0&A@ @ @ #3eX#=>@ 	@
 @ d#@  }@ %SM@ !)@ %SM@  }@ #4.@ sm@ 
@ @ @ @D      f
 f
 f
"f
 f

 f
 f
 f
 
f
 f
 f
 f
\ 15,7 ; ; ; ;
  ; !); ; ; ; ; 
; ; ; ;z  
	   0 +-,004&*'6>B?C2.&AWK WK WK WK sD$s)T$Z?@	WK
 #3-WK %SMWK !)WK d#WK  }WK %U49c>%:;WK &eDIsN&;<WK WK WK smWK 
%
D$445	6WK WK WK WKrv9 v9 v9@ ,1'4,.#'m m m m 	m
 m m T5(23m #4.m  }m %SMm C=m 
m m m mj '+#'@ @ @ @ 	@
 $sCx.)@ sm@ C=@ 
c8C= 	!@ @ @ @L ?C?C7% 7%"'T49d4j(H"I7% 7% %U49c>%:;	7%
 &eDIsN&;<7% 
eE4K 	!7% 7% 7% 7%r = 1== 
c3h= = = \=~% %% % % % %X 0F/3,0G
 G
 G
!G
 #G
 ',CcN&;G

  (}G
  (}G
 %SMG
 6:#s(^G
 G
 G
 G
Z 7;	T T%(T'./A'BT )00C(DT $)d#3	T
 "&T T T Tr )0*+(*15(* (*&)(*"%(* %((* #&	(*
 "*#(*
 ;?(* (* (* (*V 3715A As A"*3-A!)#A:=A A A A A Ar   r   c                   Z   e Zd Z ee          ZdZdZdZdZ	dZ
ed             Zedefd            Zed             Zed	             Zed
efd            Zededefd            Zedeeef         fd            Zedee         fd            Zeddeeedf         defd            ZdS )r   r   	git_tokenuserr   Fc                  F    t          j        t          j        d           d S )NTrd  )r   rg  r   path_credentialr   r   r   make_sure_credential_path_existz0ModelScopeConfig.make_sure_credential_path_exist  s!    
$4tDDDDDDr   c                    t                                            t          t          j                            t           j        t           j                  d          5 }t          j	        | |           d d d            d S # 1 swxY w Y   d S )Nzwb+)
r   r  r  r   r   r  r  COOKIES_FILE_NAMEpickler  )r   r  s     r   r   zModelScopeConfig.save_cookies  s    88:::-=-?A ABGI I 	$LMK###	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$   A??BBc                     t           j                            t          j        t          j                  } t           j                            |           rt          | d          5 }t          j	        |          }|s	 d d d            d S |D ]a}|j
        dk    rT|                                r@t          j        s4dt          _        t                              d            d d d            d S b|cd d d            S # 1 swxY w Y   d S )Nr  r   TzKNot logged-in, you can login for uploadingor accessing controlled entities.)r   r   r  r   r  r  r  r  r  loadr.  
is_expiredcookie_expired_warningrN  r  )cookies_pathr  r   r  s       r   r   zModelScopeConfig.get_cookies  s|   w||$4$D$4$FH H7>>,'' 	lD)) Q +a..          & $ $F{n449J9J9L9L4 0 G 5BF(? %H I I I#                        ts   $C;	AC;,C;;C?C?c                     t           j                            t          j        t          j                  } d}t           j                            |           r_t          | d          5 }t          |	                                
                                d          }|cd d d            S # 1 swxY w Y   |dk    st          |          dk    r{t          t          j                    j                  }t                                           t          | d          5 }|                    |           d d d            n# 1 swxY w Y   |S )Nr   r  rm  rh      w+)r   r   r  r   r  USER_SESSION_ID_FILE_NAMEr  r  r  readlinerZ  r   r  r  r  r  rS  )session_path
session_idr  wfs       r   get_user_session_idz$ModelScopeConfig.get_user_session_id  s   w||$4$D$4$NP P
7>>,'' 	"lD)) "Q !3!3!5!5HHH
!" " " " " " " " " " " " " " " " s:"44TZ\\-..J<<>>>lD)) %R$$$% % % % % % % % % % % % % % % s$   &7B**B.1B.D>>EEr   c                    t                                            t          t          j                            t           j        t           j                  d          5 }|                    |            d d d            d S # 1 swxY w Y   d S )Nr  )	r   r  r  r   r   r  r  GIT_TOKEN_FILE_NAMErS  r   r  s     r   r   zModelScopeConfig.save_token  s    88:::-=-AC CDHJ J 	MNGGENNN	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	r  r  
user_emailc                 "   t                                            t          t          j                            t           j        t           j                  d          5 }|                    | d|           d d d            d S # 1 swxY w Y   d S )Nr  :)	r   r  r  r   r   r  r  USER_INFO_FILE_NAMErS  )r  r  r  s      r   r   zModelScopeConfig.save_user_info  s    88:::-=-AC CDHJ J 	7MNGGyyy**5666	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7s   BBBr   c                  v   	 t          t          j                            t          j        t          j                  dd          5 } |                                 }|                    d          d         |                    d          d         fcd d d            S # 1 swxY w Y   n# t          $ r Y nw xY wdS )Nr   rm  rh  r  r   r   r   )
r  r   r   r  r   r  r  r   r)  FileNotFoundError)r  r  s     r   get_user_infozModelScopeConfig.get_user_info  s    		GLL!1!A!1!EG G$	& & & > *+vvxxzz#q)4::c??1+==> > > > > > > > > > > > > > > > > ! 	 	 	D	zs7   AB) A
BB) B!!B) $B!%B) )
B65B6c                     d} 	 t          t          j                            t          j        t          j                  dd          5 }|                                } ddd           n# 1 swxY w Y   n# t          $ r Y nw xY w| S )z
        Get token or None if not existent.

        Returns:
            `str` or `None`: The token, `None` if it doesn't exist.

        Nr   rm  rh  )	r  r   r   r  r   r  r  r   r  r  s     r   	get_tokenzModelScopeConfig.get_token  s     	GLL!1!A!1!EG G$	& & & ! *+! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 	 	 	D	s6   AA5 A)A5 )A--A5 0A-1A5 5
BBN
user_agentc                 X   d}t           t          j        v rt          j        t                    }d}t          t          j        v rt          j        t                   }ddlm} d|dt          j                    dt          	                                dt          j                    d	t          j
                    d
|d|}t          | t                    r8|dd                    d |                                 D                       z   z  }nt          | t                    r|d| z   z  }|S )a  Formats a user-agent string with basic info about a request.

        Args:
            user_agent (`str`, `dict`, *optional*):
                The user agent info in the form of a dictionary or a single string.

        Returns:
            The formatted user-agent string.
        customunknownr   )__version__zmodelscope/z	; python/z; session_id/z; platform/z; processor/z; env/z; user/z; c              3   *   K   | ]\  }}| d | V  dS )r   Nr   r  s      r   rk  z2ModelScopeConfig.get_user_agent.<locals>.<genexpr>-  s0      "M"M$!Qa::!::"M"M"M"M"M"Mr   )r#   r   r   r$   
modelscoper  platformpython_versionr   r  	processorr  r  r  r  r  )r  envr  r  uas        r   r   zModelScopeConfig.get_user_agent  s.    '2:55*9:C	$
22
#<=I*******KK#%%%%002222    CCI
 j$'' 	$$"M"M*:J:J:L:L"M"M"MMMMMBB
C(( 	$$##B	r   r  )r   r   r   r   r%   r  r  r  r  r  r  rx  r  r   r   r   r  r  r   r   r   r  r   r  r   r   r   r   r   r   r   r     s        j!<==O!%  )"E E \E $i $ $ $ \$   \$   \  #    \ 7# 73 7 7 7 \7 5c?    \ x}    \( " "5sD#9 "s " " " \" " "r   r   c                       e Zd ZdZeeeeefde	de	de	de	de	f
dZ
dd
Zdeeef         fdZdeeeeef         dedefdZdeeeef                  dedd	fdZd	S )r   a  
    Check the files and folders to be uploaded.

    Args:
        max_file_count (int): The maximum number of files to be uploaded. Default to `UPLOAD_MAX_FILE_COUNT`.
        max_file_count_in_dir (int): The maximum number of files in a directory.
            Default to `UPLOAD_MAX_FILE_COUNT_IN_DIR`.
        max_file_size (int): The maximum size of a single file in bytes. Default to `UPLOAD_MAX_FILE_SIZE`.
        size_threshold_to_enforce_lfs (int): The size threshold to enforce LFS in bytes.
            Files larger than this size will be enforced to be uploaded via LFS.
            Default to `UPLOAD_SIZE_THRESHOLD_TO_ENFORCE_LFS`.
        normal_file_size_total_limit (int): The total size limit of normal files in bytes.
            Default to `UPLOAD_NORMAL_FILE_SIZE_TOTAL_LIMIT`.

    Examples:
        >>> from modelscope.hub.api import UploadingCheck
        >>> upload_checker = UploadingCheck()
        >>> upload_checker.check_file('/path/to/your/file.txt')
        >>> upload_checker.check_folder('/path/to/your/folder')
        >>> is_lfs = upload_checker.is_lfs('/path/to/your/file.txt', repo_type='model')
        >>> print(f'Is LFS: {is_lfs}')
    max_file_countmax_file_count_in_dirmax_file_sizesize_threshold_to_enforce_lfsnormal_file_size_total_limitc                 L    || _         || _        || _        || _        || _        d S r  )r  r  r  r  r  )r   r  r  r  r  r  s         r   r   zUploadingCheck.__init__J  s2     -%:"*-J*,H)))r   r   Nc           	      N   t          |t          t          f          r2t          j                            |          st          d| d          t          |          }|| j        k    r<t          
                    d| j        dz   dt          |dz  d           d           dS dS )	a  
        Check a single file to be uploaded.

        Args:
            file_path_or_obj (Union[str, Path, bytes, BinaryIO]): The file path or file-like object to be checked.

        Raises:
            ValueError: If the file does not exist or exceeds the size limit.
        File  does not existzFile exceeds size limit:    @z	 GB, got     GBN)r  r  r	   r   r   r  r   rw   r  rN  r^  r  )r   r$  r%  s      r   r4  zUploadingCheck.check_fileX  s     &d44 	L7>>"233 L !J)9!J!J!JKKK&'788	t)))NN It7IY7W I I"'	Y(?"C"CI I I J J J J J *)r   rw  c           	         d}d}t          |t                    rt          |          }|                                D ]}|                                r_|dz  }t          |          }|| j        k    r?t                              d| d| j        dz   ddt          |dz  d           d           u|
                                rU|dz  }|                     |          \  }}||z   | j        k    r t          d	| d
||z    d| j                   ||z  }||z  }|| j        k    rt          d| d| j                   ||fS )z
        Check a folder to be uploaded.

        Args:
            folder_path (Union[str, Path]): The folder path to be checked.

        Raises:
            ValueError: If the folder does not exist or exceeds the file count limit.
        r   r   r  z exceeds size limit: r  r  zgot r  z
Directory z
 contains z items and exceeds limit: zTotal file count z and exceeds limit: )r  r  r	   iterdirr  rw   r  rN  r^  r  r  r  r  r   r  )r   rw  
file_count	dir_countr  	item_sizesub_file_countsub_dir_counts           r   r  zUploadingCheck.check_folderk  s    
	k3'' 	,{++K'')) 	+ 	+D||~~ +a
!.t!4!4	t111NN#k4#k#kdFX\eFf#k#k#k#P%	Y0G*K*K#P#P#PR R R +Q	040A0A$0G0G-"]2d6PPP$ &X$ &X &X.S`B` &X &X;?;U&X &X Y Y Yn,
]*	+++fffQUQdffggg9$$r   r$  rR  c                    d}t          |t          t          f          rt          |          }|                                st	          d| d          |t
          k    r|j        t          vrd}n6|t          k    r|j        t          vrd}nt	          d| dt                     t          |          }|| j        k    p|S )aj  
        Check if a file should be uploaded via LFS.

        Args:
            file_path_or_obj (Union[str, Path, bytes, BinaryIO]): The file path or file-like object to be checked.
            repo_type (str): The repo type, either `model` or `dataset`.

        Returns:
            bool: True if the file should be uploaded via LFS, False otherwise.
        Tr  r  Fr  r  )r  r  r	   r  r   rk   r  r|   rj   rz   rl   rw   r  )r   r$  rR  hit_lfs_suffixr%  s        r   r7  zUploadingCheck.is_lfs  s     &d44 	j#$455#**,, L !J)9!J!J!JKKKO++#*2BBB%*N///#*2DDD%*N !hy!h!hUf!h!hiii&'788	4==OOr   r#  c                       fd|D             }t          d |D                       }| j        k    r!t          d|dz   d j        dz   d          dS )af  
        Check a list of normal files to be uploaded.

        Args:
            file_path_list (List[Union[str, Path]]): The list of file paths to be checked.
            repo_type (str): The repo type, either `model` or `dataset`.

        Raises:
            ValueError: If the total size of normal files exceeds the limit.

        Returns: None
        c                 @    g | ]}                     |          |S r   )r7  )r  r  rR  r   s     r   r  z5UploadingCheck.check_normal_files.<locals>.<listcomp>  s-    ```T4;;tU^C_C_`D```r   c                 ,    g | ]}t          |          S r   )rw   )r  r  s     r   r  z5UploadingCheck.check_normal_files.<locals>.<listcomp>  s     KKK$---KKKr   zTotal size of non-lfs files i   zMB and exceeds limit: MBN)r  r  r   )r   r#  rR  normal_file_listr  s   ` `  r   r5  z!UploadingCheck.check_normal_files  s     a````^```KK:JKKKLL
999 iJ+<V i i373TXc3di i i j j j :9r   )r   N)r   r   r   r   r5   r6   r7   r?   r8   r  r   r4  r   r  r	   r  r   r   r  r7  r   r5  r   r   r   r   r   3  sA        0 #8)E!51U0SI II $'I 	I
 ,/I +.I I I IJ J J J&$%c4i(8 $% $% $% $%LPuS$x-G'H PUX P]a P P P P>jeCI6F1G jTW j\` j j j j j jr   r   )r  r:  r   r2  r   r  r  r  r  r   r]  r  rE  ri  collectionsr   r  r   httpr   http.cookiejarr   os.pathr   pathlibr	   typingr
   r   r   r   r   r   r   r   r   r   r   r   rC  r   requests.adaptersr   r   requests.exceptionsr   r}  r   modelscope.hub.constantsr   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   modelscope.hub.errorsrH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   modelscope.hub.gitrR   modelscope.hub.inforS   rT   r  rV   modelscope.hub.upload_cacherW   modelscope.hub.upload_pipelinerX   modelscope.hub.upload_trackerrY   rZ   r[   r\   modelscope.hub.utils.aigcr]   modelscope.hub.utils.utilsr^   r_   r`   ra   rb   rc   rd   modelscope.utils.constantre   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   modelscope.utils.file_utilsrv   rw   rx   modelscope.utils.loggerry   modelscope.utils.repo_utilsrz   r{   r|   r}   r~   r   r   r   rN  r  r   r   r   r   r   r   r   r   <module>r     s         				 				   				       # # # # # # 1 1 1 1 1 1       $ $ $ $ $ $            " " " " " " " " " " " " " " " " " " " " " " " " " " " "         0 0 0 0 0 0 0 0 ) ) ) ) ) )      )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5 )5TJ J J J J J J J J J J J J J J J J J J J J J J J 1 0 0 0 0 0 6 6 6 6 6 6 6 6 0 0 0 0 0 0 > > > > > > 7 7 7 7 7 7J J J J J J J J J J J J / / / / / /F F F F F F F F F F F F F F F F F F	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;; ; ; ; ; ; ; ; ; ; . . . . . .4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 
     4#? #? #? #? #? #? #? #?Li; i; i; i; i; i; i; i;XwN N N N N N N NbOj Oj Oj Oj Oj Oj Oj Oj Oj Ojr   