
    5pjf(                      % S r SSKJr  SSKJrJr  SSKJr  SSKJ	r	J
r
Jr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJrJr  SSKJr  SSKJr  SSKJ r   SSK!J"r"J#r#  SSK$J%r%J&r&J'r'  SSK(J)r)J*r*J+r+J,r,J-r-J.r.  SSK/J0r0J1r1J2r2J3r3J4r4J5r5  SSK6J7r7  S/r8\7" S5      r9Sr:S\;S'   \<" \&Rz                  \&R|                  \&R~                  \&R                  15      rAS\;S'   \<" \&R~                  \&R                  15      rBS\;S'   \<" \&Rz                  \&R|                  \&R~                  \&R                  15      rCS\;S'   SS S!S"S#S$S%S&S'S(S)S*S+S,S-S..rDS/\;S0'   S1S20rES/\;S3'   \<" 1 S4k5      rFS5\;S6'    " S7 S5      rGg8)9u;  High-level public API facade for the ModelScope Hub SDK.

:class:`HubApi` is the **only** entry point users should construct. It composes
the low-level :class:`OpenAPIClient`, :class:`LegacyClient`,
:class:`DownloadManager`, :class:`UploadManager` and the cache helpers into a
unified, OpenAPI-first surface.

Design principles
-----------------
* **OpenAPI-first** — every operation that has an OpenAPI counterpart goes
  through :mod:`._openapi`. Legacy endpoints are used only as a transparent
  fallback when no OpenAPI equivalent exists.
* **Unified repo pattern** — every repository operation accepts a
  ``repo_type`` parameter; there are no type-specific methods like
  ``create_model`` or ``get_dataset``.
* **Transparent fallback** — callers do not need to know which path served
  their request.
* **Lazy clients** — the underlying HTTP clients are instantiated on demand
  so that ``HubApi()`` never fails just because no token is present.
* **SOLID** — :class:`HubApi` only routes and orchestrates; concrete network
  logic lives in the injected dependencies.
    )annotations)IterableMapping)Path)AnyBinaryIO	TypeAlias)urlparse)RequestsCookieJar   )_resolve_verification_root)clear_cache)
scan_cache)verify_cache)DownloadManagerProgressCallback)LegacyClient)OpenAPIClient)UploadManager)	HubConfigget_default_config)DEFAULT_ENDPOINTRepoType
Visibility)AuthenticationErrorHubErrorInvalidParameterNetworkErrorNotExistErrorNotSupportedError)	CacheInfoCacheVerificationFileInfoPagedResultRepoInfoUserInfo)
get_loggerHubApiapizstr | RepoTyper	   RepoTypeLikezfrozenset[RepoType]_CREATABLE_TYPES_OPENAPI_CREATE_TYPES_OPENAPI_DETAIL_TYPESz
apache-2.0mitzgpl-2.0zgpl-3.0zlgpl-2.1zlgpl-3.0zafl-3.0zecl-2.0zbsd-2-clausezbsd-3-clausez	cc-by-4.0zcc-by-sa-4.0zcc-by-nc-4.0zcc0-1.0	unlicense)zApache License 2.0zMIT LicensezGPL-2.0zGPL-3.0zLGPL-2.1zLGPL-3.0zAFL-3.0zECL-2.0zBSD-2-ClausezBSD-3-Clausez	CC-BY-4.0zCC-BY-SA-4.0zCC-BY-NC-4.0zCC0-1.0	Unlicensezdict[str, str]_LICENSE_DISPLAY_TO_SPDXcover_image
coverImage_STUDIO_FIELD_RENAMES>   Namer   Ownerzfrozenset[str]_RESERVED_EXTRA_FIELDSc                     \ rS rSrSr SUSSS.       SVS jjjr\SWS j5       r\SXS j5       r\SYS j5       r	\SZS	 j5       r
\S[S
 j5       rS\S jr\S]S j5       r\S^S j5       rSr\" 1 Sk5      r\S_S j5       r\SSS.         S`S jj5       r SUSS.     SaS jjjrSbS jrScS jrSdS jrSeS jr\SfS j5       rSgS jrShS jrSSSSSS.                 SiS jjrSS.       SjS  jjrSSSS!S"S#.               SkS$ jjrSlS% jr SmS& jr!S'SS(.       SnS) jjr"SoS* jr#SSSS+SS,.                   SpS- jjr$S.SSSSSSS/SSS0.
                           SqS1 jjr%SSSSSSSS2.                     SrS3 jjr&SSSSSS4SSSS5.	                       SsS6 jjr'SS/S7.         StS8 jjr(SSS9.           SuS: jjr)SvS; jr*SS.         SwS< jjr+\,RZ                  4SS=.       SxS> jjjr.\,RZ                  4     SyS? jjr/\,RZ                  4S@S!SASSSSB.                 SzSC jjjr0        S{SD jr1\,RZ                  4SvSE jjr2\,RZ                  4         S|SF jjr3\,RZ                  4         S|SG jjr4\,RZ                  4       S}SH jjr5SS!S"SI.         S~SJ jjr6SSK.     SSL jjr7SS=.SSM jjr8SSN jr9 SSSSSO.           SSP jjjr:SUSSQ jjr;SSSSR.       SSS jjr<STr=g)r(   c   u  Unified client for ModelScope Hub operations.

Provides a high-level interface for repository management, file
operations, deployment, secret management and local caching. All
repo-type-specific operations use a unified ``repo_type`` parameter
following the OpenAPI-First design — there are no type-specific
methods like ``create_model`` or ``get_dataset``.

Internally the class composes :class:`OpenAPIClient`,
:class:`LegacyClient`, :class:`DownloadManager`, :class:`UploadManager`
and the cache helpers. HTTP clients are instantiated lazily, so
``HubApi()`` never fails just because no token is present.

Parameters
----------
config : HubConfig or None, optional
    Pre-built configuration. When omitted, the process-wide default
    from :func:`get_default_config` is used (which reads the
    ``MODELSCOPE_API_TOKEN`` env var and the local config file).
endpoint : str or None, optional
    Override the API endpoint. Takes precedence over ``config.endpoint``.
    Defaults to ``https://modelscope.cn``.
token : str or None, optional
    Override the API token. Takes precedence over ``config.token``.

Examples
--------
>>> from modelscope_hub import HubApi
>>> api = HubApi(token="ms-xxxxxxxx")
>>> user = api.whoami()
>>> user.username
'alice'

Create and manage repositories:

>>> api.create_repo("alice/my-model", repo_type="model", visibility="private")
>>> api.upload_file("alice/my-model", "model", "./weights.bin", "weights.bin")
>>> path = api.download_file("alice/my-model", "model", "weights.bin")
Nendpointtokenc               z   U=(       d
    [        5       nUc&  Uc  Ub   SSKJn  UR                  nU" U5      nXdl        X@l        Ub6  [
        R                  " U5      U R                  l        SU R                  l        Ub!  X0R                  l        SU R                  l	        S U l
        S U l        S U l        S U l        g )Nr   )replaceT)r   dataclassesr>   _endpoint_overridden_configr   normalize_endpointr;   r<   _token_overridden_openapi_legacy_downloader	_uploader)selfconfigr;   r<   baser>   was_overriddens          N/var/www/html/pdf-tiff/venv/lib/python3.13/site-packages/modelscope_hub/api.py__init__HubApi.__init__   s     -+->x3u7H+!66N4=D )7%$-$@$@$JDLL!04DLL-!&LL-1DLL*.2,037/3    c                h    U R                   c  [        U R                  5      U l         U R                   $ )z"Lazily-constructed OpenAPI client.)rD   r   rA   rH   s    rL   openapiHubApi.openapi   s(     == )$,,7DM}}rO   c                   U R                   cu  SSKJn  [        U R                  R
                  U R                  R                  =(       d    [        U" U R                  R                  5       5      S9U l         U R                   $ U R                   R
                  U R                  R
                  :w  a%  U R                  R
                  U R                   l        U R                   $ )z-Lazily-constructed legacy ``/api/v1`` client.r   )build_user_agent)r<   r;   
user_agent)	rE   utilsrU   r   rA   r<   r;   r   get_session_id)rH   rU   s     rL   legacyHubApi.legacy   s     <</'ll((..B2B+DLL,G,G,IJDL ||	 \\4<<#5#55 "&!3!3DLL||rO   c                ~    U R                   c%  [        U R                  U R                  5      U l         U R                   $ )z,Lazily-constructed :class:`DownloadManager`.)rF   r   rY   rA   rQ   s    rL   
downloaderHubApi.downloader   s3     #.t{{DLLIDrO   c                    U R                   c9  [        U R                  U R                  U R                  U R
                  S9U l         U R                   $ )u   Lazily-constructed :class:`UploadManager`.

The OpenAPI client is injected so small files (≤ 5 MiB) flow through
``POST /files/upload`` instead of the legacy commit endpoint.
)create_repo_fn)rG   r   rY   rA   rR   _create_repo_exist_okrQ   s    rL   uploaderHubApi.uploader   sD     >>!*#99	DN ~~rO   c                    U (       a  SU ;  a  [        SU < S35      eU R                  S5      u  pnU(       a  U(       d  [        SU < S35      eX4$ )z@Split a canonical ``owner/name`` identifier into its two halves./zrepo_id z% should be in format of 'owner/name'.zL should be in format of 'owner/name': owner and name must both be non-empty.)r   	partition)repo_idowner_names       rL   _parse_repo_idHubApi._parse_repo_id   s`     #W,"Xg[8]#^__ **3/$D"7+%qr  {rO   c                H     U R                  X5        g! [         a     gf = f)zEAuto-create the repo if it doesn't exist, silently ignore if it does.N)create_repor   rH   rf   	repo_types      rL   r`   HubApi._create_repo_exist_ok   s'    	W0 		    
!!c                    [        U [        5      (       a  U $  [        [        U 5      R                  5       5      $ ! [         a5  nSR                  S [         5       5      n[        SU < SU S35      UeSnAff = f)zCCoerce a ``str`` or :class:`RepoType` value to a :class:`RepoType`., c              3  8   #    U  H  oR                   v   M     g 7fNvalue.0ts     rL   	<genexpr>.HubApi._normalize_repo_type.<locals>.<genexpr>   s     :A   zUnknown repo_type z. Expected one of: .N)
isinstancer   strlower
ValueErrorjoinr   )ro   excalloweds      rL   _normalize_repo_typeHubApi._normalize_repo_type   s}     i**	mC	N00233 	mii:::G"%7	}DWX_W``a#bcill	ms   !; 
A:0A55A:c                    U c  g[        U [        5      (       a  [        U 5      $ [        U [        5      (       a  U $ [        [        R                  " [	        U 5      5      5      $ )z8Normalise visibility input to its integer wire encoding.N)r   r   int
from_labelr   )
visibilitys    rL   _normalize_visibilityHubApi._normalize_visibility   sQ     j*--z?"j#&&:((Z9::rO   )itemslistdataresultsmodelsdatasetsskillsserversmcp_server_listModelsDatasetsSkillsServers>
   pagesizeTotaltotalPageSize	page_size
PageNumber
TotalCountpage_numbertotal_countc                  ^  [        T [        5      (       a  T [        T 5      S[        T 5      4$ [        T [        5      (       d  / SSS4$ / n[        R
                   H.  n[        T R                  U5      [        5      (       d  M)  T U   n  OJ   T R                  5        H4  u  p#[        U[        5      (       d  M  U[        R                  ;  d  M2  Un  O   SU 4S jjnU" S[        U5      5      nU" SS5      nU" S[        U5      5      nXXg4$ )a2  Decode a paginated OpenAPI response into ``(items, total, page, size)``.

The ModelScope API returns item arrays under type-specific keys
(``models``, ``datasets``, ``skills``, ``servers``). This method
checks known keys first, then falls back to the first list-valued
key that is not pagination metadata.
r   r   c                \   > U  H$  nTR                  U5      nUc  M  [        U5      s  $    U$ ru   )getr   )keysdefaultkvpayloads       rL   _first%HubApi._extract_paged.<locals>._first?  s/    KKN=q6M  NrO   )r   r   r   )r   r   r   )r   r   r   )r   ztuple[str, ...]r   r   returnr   )	r   r   lendictr(   _PAGED_ITEM_KEYSr   r   _PAGED_META_KEYS)r   r   keyrw   r   r   r   r   s   `       rL   _extract_pagedHubApi._extract_paged&  s     gt$$CL!S\99'4((q!Q;**C'++c*D11 +
 &mmo
eT**s&:Q:Q/Q!E .
	 =s5zJ;Q?7UDT''rO   
owner_hint	name_hintc               Z   [        U =(       d    0 5      n 0 nSSSSSSSSSS	S
S
S
S
SS.nU R                  5        H  u  pgXtUR                  Xf5      '   M     UR                  S5      c~  UR                  S5      n[        U[        5      (       a/  U(       a  [
        R                  US'   O=[
        R                  US'   O)UR                  S5      (       a  [
        R                  US'   UR                  S5      n	[        U	[        5      (       aT  SU	;   aN  U	R                  SS5      n
UR                  S5      (       d  U
S   US'   UR                  S5      (       d  U
S   US'   UR                  S5      (       d  X$S'   UR                  S5      (       d  X4S'   XS'   [        R                  " U5      $ )zBuild a :class:`RepoInfo` from an arbitrary API payload.

The legacy and OpenAPI surfaces use different field-naming conventions
(PascalCase vs snake_case). This helper normalises both into the
SDK's canonical dataclass.
idrg   ri   r   licensedescription	downloadslikes
created_atlast_modifiedtags)Idr   r5   r6   r   LicenseDescription	DownloadsLikes	CreatedAt	UpdatedAtLastModifiedr   
updated_atTagsprivategatedrd   r   r   ro   )r   r   r   r   boolr   PRIVATEPUBLICr   splitr%   	from_dict)r   ro   r   r   
normalisedaliasesr   rw   private_flagid_valpartss              rL   _repo_info_from_payloadHubApi._repo_info_from_payloadK  s    DJB%'
& ($%(+,)
" **,JC05w{{3,- '
 >>,'/%>>)4L,--/9/A/AJ|,/9/@/@J|,((+5+=+=
<( %fc""sf}LLa(E>>'**&+Ah
7#>>&))%*1X
6"~~g&&",w~~f%%!*v"+;!!*--rO   F)cookies_requiredc                  U=(       d    U R                   R                  nU(       aO  [        U R                   R                  5      R                  =(       d    Sn[        5       nUR                  SX4SS9  U$ [        U R                   SS5      (       d  U R                   R                  5       nUb  U$ U(       a  [        S5      eg)	a  Get cookies for authentication from token or local cache.

Resolution order:
1. Explicit ``access_token`` argument
2. Token from config (explicit arg > env var > persisted cookie)
3. Saved cookies from ``~/.modelscope/credentials/cookies``

When a token is available (steps 1-2), a fresh
:class:`~requests.cookies.RequestsCookieJar` with ``m_session_id``
is built. Otherwise the locally cached cookies from a prior
``login()`` call are loaded.

Parameters
----------
access_token : str, optional
    Explicit token override.
cookies_required : bool, optional
    When ``True``, raise :class:`AuthenticationError` if no
    credentials are available. Default is ``False``.

Returns
-------
RequestsCookieJar or None
    Cookie jar for authentication, or ``None`` when no
    credentials are available and ``cookies_required`` is ``False``.

Raises
------
AuthenticationError
    When ``cookies_required`` is ``True`` and no credentials found.

Examples
--------
>>> cookies = api.get_cookies()
>>> cookies['m_session_id']
'ms-xxxxxxxx'
 m_session_idrd   )domainpathrC   FNzNo credentials found. Pass --token, call HubApi.login(), or set MODELSCOPE_API_TOKEN. Your token is available at https://modelscope.cn/my/myaccesstoken)
rA   r<   r
   r;   hostnamer   setgetattrload_cookiesr   )rH   access_tokenr   r<   r   jarcookiess          rL   get_cookiesHubApi.get_cookies  s    V 2 2 2dll334==CF#%CGGNEsGCJ t||%8%@@ll//1G"%T 
 rO   c                `   U(       a  UR                  5       (       d  [        S5      eUR                  5       nU R                  R                  nU R                  R                  nXR                  l        SU R                  l        SU l        U R                  b  XR                  l         U R                  R                  U5      u  pEUR                  SS5      nUR                  SS5      n	UR                  SS5      n
U R                  R                  U5        U(       a  U R                  R                  U5        U	(       a$  U R                  R                  X=(       d    S5        U R!                  5       $ ! [         a.  nU R                  X#5        U R                  X5      nXvL a  e XveSnAff = f)a  Authenticate and persist credentials locally.

Calls ``POST /api/v1/login`` to obtain server-issued session cookies
and a git access token, then saves them to
``~/.modelscope/credentials/`` (compatible with the old modelscope SDK).

Parameters
----------
token : str
    ModelScope API token. Must be non-empty after stripping.

Returns
-------
UserInfo
    Profile of the authenticated user.

Raises
------
InvalidParameter
    When ``token`` is empty or whitespace-only.
AuthenticationError
    When the server rejects the token. The server's own explanation is
    preserved, and an endpoint hint is appended when the token turns
    out to be valid on the peer ModelScope site.
HubError
    Transport, timeout and server-side failures propagate unchanged --
    they are never reported as a rejected token.

Notes
-----
A failed attempt leaves persisted credentials untouched. Until the
server has accepted the new token, the stored credential is still the
caller's only working one, so revoking it on failure would turn a
mistyped token into an unintended logout.

Examples
--------
>>> api = HubApi()
>>> user = api.login("ms-xxxxxxxx")
>>> user.username
'alice'
z token must be a non-empty stringFNAccessTokenr   UsernameEmail)stripr   rA   r<   _logged_outrD   rE   rY   loginr   _restore_credential_state_explain_login_failurer   save_cookiessave_git_tokensave_user_infowhoami)rH   r<   previous_tokenprevious_logged_outr   r   r   	explained	git_tokenusernameemails              rL   r   HubApi.login  sQ   V EKKMM"#EFF++"ll66"#( <<#!&LL	% KK--e4MD HH]B/	88J+"%!!'*LL''	2LL''+2>{{}#  	%**>O33E?I$	%s   *E5 5
F-?)F((F-c                    XR                   l        X R                   l        SU l        U R                  b  XR                  l        gg)a  Roll the in-memory credential back to its pre-login value.

Persisted credentials are deliberately left alone; only this instance's
transient state is rewound, so a failed attempt leaves the object
exactly as it was found instead of poisoning it with a rejected token.
N)rA   r<   r   rD   rE   )rH   r<   
logged_outs      rL   r    HubApi._restore_credential_state  s8     ##- <<#!&LL $rO   c           
     2   [        U[        5      (       d  U$ U R                  5       nUb  U R                  X5      (       d  U$ [        UR                   SU SU SU S3UR
                  UR                  UR                  UR                  UR                  S9$ )a2  Return the exception to surface for a failed login attempt.

Only authentication failures are re-worded. Network, timeout and
server-side errors are handed back untouched, because presenting them
as a rejected token would send the caller after the wrong remedy.

The two ModelScope sites keep separate account systems and answer an
unknown token with the same business code, so the server cannot tell
"invalid token" apart from "token issued by the other site". Only the
client knows which site it addressed, which is why that disambiguation
has to happen here.
z This token is valid on z  instead; retry with --endpoint z (or set MODELSCOPE_ENDPOINT=).)status_code
request_idresponse_bodyurlmethod)
r   r   _peer_site_endpoint_token_valid_onmessager  r  r  r  r  )rH   r<   r   peers       rL   r   HubApi._explain_login_failure+  s     #233J'')<t33E@@J"{{m3D6 :<TF"F~~++::
 	
rO   c                    U R                   R                  (       a  gSSKJn  SS jnU" U R                   R                  =(       d    [
        5      n[
        U4 H  nU" U5      U:w  d  M  Us  $    g)zReturn the sibling ModelScope site, or ``None`` when not applicable.

An explicitly configured endpoint is always respected, mirroring
:meth:`resolve_endpoint_for_read`: when the caller has pinned a site we
do not second-guess it.
Nr   )DEFAULT_INTL_ENDPOINTc                    [        U 5      R                  =(       d    SR                  5       nUR                  S5      (       a  USS  $ U$ )Nr   zwww.   )r
   r   r   
startswith)r  hosts     rL   site_key,HubApi._peer_site_endpoint.<locals>.site_keyR  s>    SM**0b779D#v6648@D@rO   )r  r   r   r   )rA   r@   	constantsr  r;   r   )rH   r  r  current	candidates        rL   r  HubApi._peer_site_endpointG  sb     <<,,4	A 4<<00D4DE*,ABI	"g-   C rO   c                l    SSK Jn  [        SUUSS9n UR                  U 5        g! [         a     gf = f)a<  Best-effort check of whether *token* authenticates against *endpoint*.

Runs on the failure path only and is strictly advisory: any error means
"cannot confirm", so a probe outage degrades to the plain server message
rather than producing a misleading hint. Retries are disabled to keep
the failure path responsive.
r   )API_CONNECT_TIMEOUTNr   )r<   r;   timeoutmax_retriesFT)r  r  r   r   	Exception)r<   r;   r  probes       rL   r	  HubApi._token_valid_on\  sG     	3'	
	KK   		s   & 
33c                    U R                   R                  5         SU l        U R                  b  SU R                  l        gg)zClear the locally persisted token.

Cached HTTP clients are reset so subsequent calls behave as if
no credential was ever provided.

Examples
--------
>>> api.logout()
N)rA   clear_tokenrD   rE   r<   rQ   s    rL   logoutHubApi.logouts  s6     	  "<<#!%DLL $rO   c                    U R                   R                  5       n[        R                  " [	        U[
        5      (       a  U5      $ 0 5      $ )a  Return the profile for the currently authenticated user.

Returns
-------
UserInfo
    Authenticated user profile (username, email, avatar, ...).

Raises
------
AuthenticationError
    When no token is configured or the token is invalid.

Examples
--------
>>> from modelscope_hub import HubApi
>>> api = HubApi(token="ms-xxxxxxxx")
>>> user = api.whoami()
>>> print(user.username, user.email)
alice alice@example.com
)rR   get_current_userr&   r   r   r   )rH   r   s     rL   r   HubApi.whoami  s;    * ,,//1!!Z-F-F'OOBOOrO   )r   r   chinese_namer   
gated_modec                  U R                  U5      n	U	[        ;  aB  SR                  [        S [         5       5      5      n
[	        SU	R
                  < SU
 S35      eU R                  U5      u  pU R                  U5      nUb  [        R                  XD5      nU	[        ;   Ga  USL=(       a    U[        [        R                  5      :H  nU	[        R                  L a  UUS.nUb  XS'   Ub  X_S	'   OUUS
.nUb  XS'   Ub  X_S	'   Ub  XOS'   Ub  XoS'   [         R#                  5        H"  u  nnUU;   d  M  UR%                  U5      UU'   M$     UR'                  U5        U	[        R                  L a  U R(                  R+                  U5      OU R(                  R-                  U5      nU R/                  UXUS9$ U	[        R0                  L a-  UUUb  UO[        [        R2                  5      U=(       d    SS.nO,UUUb  UO[        [        R2                  5      U=(       d    SS.nUb  UUS'   Ub  UUS'   Ubq  Uc-  [        [        R                  5      nUUS'   U(       a  SOSUS'   OAU[        [        R                  5      :X  a  U(       a  SOSUS'   O[4        R7                  S5        0 nUR#                  5        H-  u  nnU[8        ;   a  [4        R7                  SU5        M(  UUU'   M/     SU;   a@  US   n[;        U[        5      (       a  [;        U[<        5      (       d  US;  a  [?        S5      eUR'                  U5        U R@                  RC                  [E        U	5      US9nU R/                  UXUS9$ )u@  Create a new repository.

Routing is decided by ``repo_type``:

* ``studio`` / ``skill`` → OpenAPI ``POST /studios`` / ``POST /skills``
* ``model`` / ``dataset`` → legacy ``POST /api/v1/{type}s``

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    One of ``"model"``, ``"dataset"``, ``"studio"``, ``"skill"``.
visibility : int, str or Visibility, optional
    Visibility level. Accepts the integer wire encoding, a label
    (``"public"`` / ``"private"``) or a :class:`Visibility` value.
    Defaults to public.
license : str, optional
    SPDX-style license identifier (e.g. ``"apache-2.0"``).
chinese_name : str, optional
    Chinese display name shown on the Hub UI.
description : str, optional
    Short description of the repository.
gated_mode : bool, optional
    Enable gated (application-based download) mode for private repos.
    True = gated, False = normal private. Only effective when
    visibility is PRIVATE; ignored otherwise.
**extra : Any
    Additional fields forwarded verbatim to the underlying client.

Returns
-------
RepoInfo
    Metadata of the newly created repository.

Raises
------
InvalidParameter
    When ``repo_id`` does not have the ``owner/name`` shape.
AuthenticationError
    When the token is missing or invalid.

Examples
--------
Create a private model repository:

>>> info = api.create_repo(
...     "alice/llama-7b-finetuned",
...     repo_type="model",
...     visibility="private",
...     license="apache-2.0",
...     description="A LoRA fine-tune of LLaMA-7B",
... )
>>> info.repo_id
'alice/llama-7b-finetuned'

Create a private gated dataset:

>>> api.create_repo("alice/my-data", "dataset", visibility="private", gated_mode=True)

Create a public Studio space:

>>> api.create_repo("alice/chat-demo", repo_type="studio", visibility="public")
rs   c              3  8   #    U  H  oR                   v   M     g 7fru   rv   rx   s     rL   r{   %HubApi.create_repo.<locals>.<genexpr>  s     (K:JQ:Jr}   z'create_repo does not support repo_type=z. Supported types: r~   N)rg   	repo_namer   display_name)rg   
skill_namer   r   r   z
Apache-2.0)r6   r5   r   r   )r   r5   r   r   ChineseNamer   r   r      ProtectedModezAgated_mode is only effective when visibility is PRIVATE, ignored.z@Reserved field %r in extra ignored (controlled by method params))r   r0  zQProtectedMode must be int 1 (gated) or 2 (off); use gated_mode=True/False instead)ro   body)#r   r+   r   sortedr    rw   rj   r   r1   r   r,   r   r   r   r   STUDIOr4   r   popupdaterR   create_studiocreate_skillr   DATASETr   loggerwarningr7   r   r   r   rY   rm   r   )rH   rf   ro   r   r   r'  r   r(  extrart	supportedrg   ri   vis
is_privater   old_keynew_keyr   r2  filteredr   r   pms                           rL   rm   HubApi.create_repo  sv   X &&y1%%		&(K:J(K"KLI#9"((EXYbXccde  ))'2((4.227DG&&DKSC
8J8J4K-KJX__$"!%+ ?)3I&+.:N+ #"& ?)3I&+.:N+"%,	"&)4&$9$?$?$A e#%*YYw%7E'N %B NN5!:<:O4<<--g6UYUaUaUnUnovUwD//bVZ/[[!!!%(_c#j>O>O:P"2l	$D %(_c#j>O>O:P"2l	D #".D""-D
 !{*,,-%(\"-7Q_%J..//-7Q_%bc $&KKMDAq**acdeHQK	 "
 h&/*Bb#&&*R*>*>"FBR !tuuH{{&&Rt&D++D"RV+WWrO   )revisionc               v   U R                  U5      nU R                  U5      u  pVU[        R                  L a   U R                  R                  XV5      nOU[        R                  L a   U R                  R                  XV5      nOU[        R                  L a  U R                  R                  XV5      nOvU[        R                   L a!  U R                  R#                  U SU 35      nOBU[        R$                  L a!  U R                  R'                  U SU 35      nO[)        SU 35      eU R+                  XtXVS9$ ! [         a(    U R                  R                  U[        U5      5      n NAf = f! [         a?    [        R                  SUU5        U R                  R                  U[        U5      5      n Nf = f)a  Fetch a repository's metadata via the OpenAPI surface.

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    One of ``"model"``, ``"dataset"``, ``"studio"``, ``"skill"``, ``"mcp"``.
revision : str, optional
    Reserved for future use; currently ignored.

Returns
-------
RepoInfo
    Repository metadata (id, owner, name, visibility, stats, ...).

Raises
------
NotExistError
    When the repository does not exist or is not visible to the caller.
AuthenticationError
    When the request requires auth and the token is missing or invalid.

Examples
--------
>>> info = api.get_repo("alice/llama-7b", repo_type="model")
>>> info.visibility
'public'
>>> info.downloads
1234
z>Dataset %s/%s not found in OpenAPI, falling back to legacy APIrd   zget_repo not supported for r   )r   rj   r   MODELrR   	get_modelr   rY   get_repo_infor   r9  get_datasetr:  debugr4  
get_studioSKILL	get_skillMCPget_mcp_serverr    r   )rH   rf   ro   rF  r=  rg   ri   r   s           rL   get_repoHubApi.get_repoC  s   L &&y1))'2C||--e: 8###C||//< 8??"<<**57D8>>!<<))UG1TF*;<D8<<<<..%$/@AD#&A"$FGG++D+WW+ ! C{{00#b'BC
 ! CT
 {{00#b'BCs$   D: )E/ :/E,+E,/AF87F8r   
   )rg   searchsortr   r   c          	     B   U R                  U5      nUR                  5        V	V
s0 s H  u  pU
c  M
  X_M     nn	n
U[        R                  L a(  U R                  R                  UUUUUU=(       d    SS9nOU[        R                  L a(  U R                  R                  UUUUUU=(       d    SS9nOU[        R                  L a?  U(       a  UR                  SU5        U R                  R                  UUUU=(       d    SS9nOeU[        R                  L a&  U R                  R                  UUUU=(       d    SS9nO,U[        R                  L a  [        S5      e[        SU 35      eU R                  U5      u  pnnU[        R                  L a  UnUnU Vs/ s H  nU R!                  UU5      PM     nn[        R                  S[        R                  S	[        R                  S
[        R                  S0nUR#                  US5      n[%        UXUUS9$ s  sn
n	f s  snf )as  List repositories of the given type via OpenAPI.

Parameters
----------
repo_type : str or RepoType
    One of ``"model"``, ``"dataset"``, ``"skill"``, ``"mcp"``.
    ``"studio"`` raises :class:`NotSupportedError` (no list endpoint).
owner : str, optional
    Restrict results to repositories owned by this user/org.
search : str, optional
    Free-text search query.
sort : str, optional
    Sort key understood by the upstream endpoint (e.g. ``"downloads"``).
page_number : int, optional
    1-based page index. Default is 1.
page_size : int, optional
    Items per page. Default is 10.
**filters : Any
    Additional filter fields. ``None`` values are dropped.

Returns
-------
PagedResult[RepoInfo]
    Paginated repository listing.

Raises
------
NotSupportedError
    When ``repo_type`` is ``"studio"`` (no list endpoint yet).

Examples
--------
Browse public LLaMA models:

>>> page = api.list_repos("model", search="llama", page_size=5)
>>> page.total_count
42
>>> [r.repo_id for r in page.items]
['meta-llama/Llama-2-7b', ...]

List datasets owned by an organisation:

>>> api.list_repos("dataset", owner="my_org", page_number=2)
N)rU  rg   rV  r   r   filtersrg   )rU  r   r   rX  )rU  r   r   filterz<Listing studios is not supported by the OpenAPI surface yet.zlist_repos not supported for r   r   r   r   r   )r   r   r   r   collection_key)r   r   r   rH  rR   list_modelsr9  list_datasetsrN  
setdefaultlist_skillsrP  list_mcp_serversr4  r    r   r   r   r$   )rH   ro   rg   rU  rV  r   r   rX  r=  r   r   clean_filtersr   r   r   r   r   iteminfos_COLLECTION_KEYSr   s                        rL   
list_reposHubApi.list_repos  s   n &&y1:A--/([/$!Q/([ll..'#%- / G 8###ll00'#%- 1 G 8>>!((%8ll..'#%-	 / G 8<<ll33'#$,	 4 G 8??"#$bcc#&CB4$HII#'#6#6w#? dDDDDIJED--dB7EJ NNHjNNHLL)	
 ""2w/EW[loppo )\\ Ks   	HHHc                    SSK nUR                  S[        SS9  U R                  U5      nU R	                  U5        U R
                  R                  U[        U5      S9  g)a  Delete a repository.

.. deprecated::
    Programmatic repository deletion is not currently supported by
    the Hub API for security reasons. This method will be restored
    in a future release once proper token-scoped authentication is
    available. To delete a repository now, use the web console at
    https://modelscope.cn.

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    Repository type (``"model"``, ``"dataset"``, etc.).
r   NzThis function is deprecated due to security reasons, and will be recovered in future versions with proper token authentication. Please go to https://modelscope.cn to delete repositories via the web console.r0  )
stacklevelrf   ro   )warningswarnDeprecationWarningr   rj   rY   delete_repor   )rH   rf   ro   ri  r=  s        rL   rl  HubApi.delete_repo  sa    " 	]  	 	
 &&y1G$3r7CrO   c                H     U R                  X5        g! [         a     gf = f)zReturn ``True`` iff the repository exists and is visible to the caller.

This is a thin wrapper around :meth:`get_repo` that converts a
:class:`NotExistError` into a boolean.

Examples
--------
>>> api.repo_exists("alice/my-model", "model")
True
TF)rR  r   rn   s      rL   repo_existsHubApi.repo_exists  s(    	MM'- 		rq   model)ro   r<   c                  SSK JnJnJnJn  U R
                  R                  (       a  U R
                  R                  =(       d    U$ U=(       d    U R
                  R                  nU" US5      n	U	(       a  UOUn
U	(       a  UOUn[        XS9nUR                  X5      (       a  U
$ [        XS9nUR                  X5      (       a  [        R                  SUU
U5        U$ [        SU SU
 SU 35      e)	a  Resolve the best endpoint for read operations (download, list, get).

1. If the endpoint was explicitly configured (via constructor arg,
   ``MODELSCOPE_ENDPOINT``, or the deprecated ``MODELSCOPE_DOMAIN``),
   trust the user's configuration and return it directly (no probe).
2. If ``MODELSCOPE_PREFER_AI_SITE=true``, check ``.ai`` first, then
   fall back to ``.cn``.
3. Otherwise (default), check ``.cn`` first, then fall back to ``.ai``.

Parameters
----------
token : str, optional
    Explicit token for the probe requests.  Falls back to the
    token stored in this instance's config.

Returns
-------
str
    The endpoint URL where the repo exists.

Raises
------
NotExistError
    If the repo is not found on any checked endpoint.
r   )r   r  ENV_PREFER_AI_SITE	_env_boolFr:   z*Repo %s not found on %s, using %s instead.zRepo z not found on either z or )r  r   r  rs  rt  rA   r@   r;   r<   r(   ro  r:  r;  r   )rH   rf   ro   r<   r   r  rs  rt  effective_token	prefer_aiprimaryfallbackprimary_probefallback_probes                 rL   resolve_endpoint_for_read HubApi.resolve_endpoint_for_read&  s    @	
 	
 <<,,<<((<,<<54<<#5#50%8	+4':J'0#6KG$$W88NI%%g99NN<	 OeG9,A'$xjYZZrO   c                >    U R                   R                  US9nUS   $ )zUpload a file (max 5 MiB) via OpenAPI and return the file ID.

This is a generic upload not tied to any repository.  The returned
ID can be used in subsequent API calls (e.g. ``skill_file`` when
creating a skill).
)filer   )rR   upload_file)rH   r~  r   s      rL   upload_file_to_openapiHubApi.upload_file_to_openapii  s%     ||''T'2DzrO      )commit_messagecommit_descriptionrF  buffer_size_mbdisable_tqdmc                   U R                  U5      n
U R                  R                  U[        U
5      UUU=(       d    SUU=(       d    SUU	S9	$ )a^  Upload a single file to a repository.

LFS files upload/reuse their blob first, then commit an LFS pointer.
Normal files are committed directly with inline base64 content.
LFS mode is determined by file suffix and size threshold.

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    Repository type (``"model"``, ``"dataset"``, ...).
path_or_fileobj : str, Path, bytes or BinaryIO
    Local path, raw bytes, or a binary file-like object.
path_in_repo : str
    Destination path inside the repository.
commit_message : str, optional
    Commit message. Defaults to ``"Upload file"``.
commit_description : str, optional
    Extended commit description.
revision : str, optional
    Branch to commit on. Defaults to ``"master"``.
buffer_size_mb : int, optional
    Buffer size in MiB for reading file data. Default 16.
disable_tqdm : bool, optional
    Disable progress bar. Default False.

Returns
-------
dict
    Commit info from the server.

Raises
------
AuthenticationError
    When the token is missing or invalid.
NotExistError
    When the target repository does not exist.

Examples
--------
>>> api.upload_file(
...     "alice/llama-7b",
...     repo_type="model",
...     path_or_fileobj="./pytorch_model.bin",
...     path_in_repo="pytorch_model.bin",
...     commit_message="Add fine-tuned weights",
... )
zUpload filemaster)	rf   ro   path_or_fileobjpath_in_repor  r  rF  r  r  )r   ra   r  r   )rH   rf   ro   r  r  r  r  rF  r  r  r=  s              rL   r  HubApi.upload_files  sZ    | &&y1}}(("g+%):]1))% ) 

 
	
rO   r   T)
r  r  r  rF  allow_patternsignore_patternsmax_workers	use_cacher  sync_remote_repoc       
            U R                  U5      nU R                  R                  U[        U5      UUU=(       d    SUU=(       d    SUU	U
UUUS9$ )a  Upload an entire folder to a repository with resumable support.

Files are walked recursively from ``folder_path`` and uploaded in
parallel with adaptive batching, per-file retry, and ReAct progressive
retry fallback.

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    Repository type.
folder_path : str or Path
    Local directory whose contents will be uploaded.
path_in_repo : str, optional
    Destination prefix inside the repository. Defaults to the repo root.
commit_message : str, optional
    Commit message. Defaults to ``"Upload folder"``.
commit_description : str, optional
    Extended commit description.
revision : str, optional
    Branch to commit on. Defaults to ``"master"``.
allow_patterns : list of str, optional
    If given, only files matching at least one pattern are uploaded.
ignore_patterns : list of str, optional
    Files matching any pattern are skipped.
max_workers : int, optional
    Concurrency for parallel uploads. Defaults to adaptive.
use_cache : bool, optional
    Use ``.ms_upload_cache`` for resumable uploads. Default True.
disable_tqdm : bool, optional
    Disable progress bars. Default False.
sync_remote_repo : bool, optional
    If True, delete remote files that are not present locally after
    a successful upload (sync semantics). Default False.

Returns
-------
None
    If all files were already committed (nothing to do).
dict
    If only one batch was committed.
list of dict
    If multiple batches were committed.

Examples
--------
>>> api.upload_folder(
...     "alice/llama-7b",
...     repo_type="model",
...     folder_path="./checkpoint-1000",
...     ignore_patterns=["*.optim", "events.out.*"],
...     max_workers=8,
... )
zUpload folderr  )rf   ro   folder_pathr  r  r  rF  r  r  r  r  r  r  )r   ra   upload_folderr   )rH   rf   ro   r  r  r  r  rF  r  r  r  r  r  r  r=  s                  rL   r  HubApi.upload_folder  sf    P &&y1}}**"g#%)<_1))+#%- + 
 	
rO   )rF  	cache_dir	local_dirforceexpected_sha256local_files_onlyrV   c                  U R                  U5      nU[        R                  L a  [        SU S35      eU R                  R                  U[        U5      UU=(       d    SU(       a  [        U5      OSU(       a  [        U5      OSUUU	U
S9
$ )a  Download a single file from a repository.

      The file is fetched into the local cache and a path pointing at the
      cached blob is returned. Subsequent calls reuse the cached copy
      unless ``force=True``.

      Parameters
      ----------
      repo_id : str
          Canonical ``owner/name`` identifier.
      repo_type : str or RepoType
          Repository type.
      file_path : str
          Path of the file inside the repository.
      revision : str, optional
          Branch, tag or commit SHA. Defaults to ``"master"``.
      cache_dir : str or Path, optional
          Override the default cache directory.
      local_dir : str or Path, optional
          When set, download directly into this directory instead of cache.
      force : bool, optional
          Re-download even if a cached copy exists. Default is ``False``.
      expected_sha256 : str, optional
          When provided, verify downloaded file hash and use it for
          cache hit validation. On mismatch, re-download up to 3 times.
      local_files_only : bool, optional
          When ``True``, return the cached path without network access.
          Raises :class:`CacheNotFound` if the file is not cached.
      user_agent : dict, str or None, optional
          Custom user-agent info appended to the default UA string.

      Returns
      -------
      Path
          Absolute path to the downloaded file on disk.

      Raises
      ------
      NotExistError
          When the file or repository does not exist.

      Examples
      --------
      >>> path = api.download_file(
      ...     "alice/llama-7b",
      ...     repo_type="model",
      ...     file_path="config.json",
      ... )
      >>> path.read_text()[:30]
      '{
"architectures": [
  "Ll'
      File download is not supported for studio repositories. Studios are application containers without a file listing API. To access studio source code, use: git clone https://modelscope.cn/studios/.gitr  N)
rf   ro   	file_pathrF  r  r  r  r  r  rV   )r   r   r4  r    r\   download_filer   r   )rH   rf   ro   r  rF  r  r  r  r  r  rV   r=  s               rL   r  HubApi.download_file  s    B &&y1 #^^e]ffjl 
 ,,"g))2d9o)2d9o+-! - 
 	
rO   r  )	rF  r  r  r  r  r  r  rV   progress_callbacksc       	           U R                  U5      nU[        R                  L a  [        SU S35      eU R                  R                  U[        U5      U=(       d    SU(       a  [        U5      OSU(       a  [        U5      OSUUUU	U
US9$ )a-  Download an entire repository snapshot.

All files at the given ``revision`` are fetched into the local cache
in parallel. The returned path is the snapshot root directory.

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    Repository type.
revision : str, optional
    Branch, tag or commit SHA. Defaults to ``"master"``.
cache_dir : str or Path, optional
    Override the default cache directory.
local_dir : str or Path, optional
    When set, download directly into this directory instead of cache.
allow_patterns : list of str, optional
    If given, only matching files are downloaded.
ignore_patterns : list of str, optional
    Matching files are skipped.
max_workers : int, optional
    Concurrency for parallel downloads. Default is 4.
local_files_only : bool, optional
    When ``True``, return the cached snapshot path without network.
user_agent : dict, str or None, optional
    Custom user-agent info for download headers.
progress_callbacks : list of ProgressCallback subclasses, optional
    Callback *classes* (not instances); each is instantiated per file
    to report byte-level download progress.

Returns
-------
Path
    Absolute path to the snapshot/local directory.

Examples
--------
Download only the tokenizer assets of a model:

>>> root = api.download_repo(
...     "alice/llama-7b",
...     repo_type="model",
...     allow_patterns=["tokenizer*", "*.json"],
...     max_workers=8,
... )
>>> sorted(p.name for p in root.iterdir())
['config.json', 'tokenizer.json', 'tokenizer_config.json']
r  r  r  N)rf   ro   rF  r  r  r  r  r  r  rV   r  )r   r   r4  r    r\   download_repor   r   )rH   rf   ro   rF  r  r  r  r  r  r  rV   r  r=  s                rL   r  HubApi.download_repol  s    @ &&y1 #^^e]ffjl 
 ,,"g))2d9o)2d9o)+#-!1 - 
 	
rO   rF  	recursivec          
        U R                  U5      nU R                  R                  U[        U5      U=(       d    SUS9n/ nU GH  nUR	                  S5      =(       d2    UR	                  S5      =(       d    UR	                  S5      =(       d    S[        UR	                  S5      =(       d    UR	                  S5      =(       d    S	5      UR	                  S
5      =(       d)    UR	                  S5      =(       d    UR	                  S5      UR	                  S5      =(       d    UR	                  S5      UR	                  S5      =(       d    UR	                  S5      =(       d    SUR	                  S5      =(       d    UR	                  S5      UR	                  S5      =(       d    UR	                  S5      S.n	UR                  [        R                  " U	5      5        GM     U$ )up  List files inside a repository (legacy — no OpenAPI equivalent).

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    Repository type.
revision : str, optional
    Branch, tag or commit SHA. Defaults to ``"master"``.
recursive : bool, optional
    Walk subdirectories recursively. Default is ``True``.

Returns
-------
list of FileInfo
    File metadata entries (path, size, blob id, last modified, ...).

Examples
--------
>>> files = api.list_repo_files("alice/llama-7b", "model")
>>> [f.path for f in files][:3]
['README.md', 'config.json', 'pytorch_model.bin']
r  )rf   ro   rF  r  r   r   r5   r   Sizer   r   BlobIdblob_idSha256sha256TypetypeblobCommittedDater   Lfslfs)r   r   r  r  r  r   r  )	r   rY   list_repo_filesr   r   r   appendr#   r   )
rH   rf   ro   rF  r  r=  rawfilesra  r   s
             rL   r  HubApi.list_repo_files  sa   @ &&y1kk))"g)	 * 
 !#D(VDHHV,<V@PVTVDHHV,E0@EAF88H-Z)1DZQYHZ((8,B0B(FDHHV,<F!%/!:!Wdhh>Wxx9$((5/J LL++J78  rO   )r  rF  c                  U R                  U5      nU Vs/ s H  ow(       d  M  UPM     nnU(       d  [        S5      e/ / pU HC  n U R                  R                  U[	        U5      UU=(       d    SS9  U	R                  U5        ME     X[        U5      S.$ s  snf ! [        [        4 a    U
R                  U5        e [         a    U
R                  U5         M  f = f)a  Delete one or more files from a repository.

.. note::
   File deletion is restricted by the server to cookie-based session
   auth (interactive login). API tokens (``ms-...``) may receive a 401
   "token no longer supports deletion operations" error.

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    Repository type.
file_paths : iterable of str
    Paths of files to remove. Empty entries are ignored.
commit_message : str, optional
    Unused (kept for API compatibility).
revision : str, optional
    Branch to delete from. Defaults to ``"master"``.

Returns
-------
dict
    Summary with ``deleted_files`` and ``failed_files`` lists.

Raises
------
InvalidParameter
    When ``file_paths`` resolves to an empty list.

Examples
--------
>>> api.delete_files(
...     "alice/llama-7b",
...     "model",
...     ["old_weights.bin", "deprecated/config.json"],
... )
z4file_paths must contain at least one non-empty path.r  )rf   ro   r  rF  )deleted_filesfailed_filestotal_files)
r   r   rY   delete_filer   r  r   r   r  r   )rH   rf   ro   
file_pathsr  rF  r=  ppathsdeletedfaileds              rL   delete_filesHubApi.delete_files  s    ^ &&y1&,Jq!J,"#YZZbA!''#!"g%1	 (  q!  ")QTUZQ[\\) - (6 a  !a !s   
BB?B<CCc                j    U R                  U5      nU R                  R                  U[        U5      S9$ )zReturn branches and tags of a repository (legacy).

Examples
--------
>>> revs = api.list_repo_revisions("alice/llama-7b", "model")
>>> [r["name"] for r in revs]
['master', 'v1.0', 'experimental']
rh  )r   rY   list_revisionsr   )rH   rf   ro   r=  s       rL   list_repo_revisionsHubApi.list_repo_revisions?  s2     &&y1{{))'SW)MMrO   c                   U R                  U5      nU R                  R                  U[        U5      UU=(       d    SS9$ )zCreate a tag pointing at ``revision`` (defaults to ``master``).

Examples
--------
>>> api.create_repo_tag("alice/llama-7b", "model", "v1.0")
r  )rf   ro   tagrF  )r   rY   
create_tagr   )rH   rf   ro   r  rF  r=  s         rL   create_repo_tagHubApi.create_repo_tagK  sE     &&y1{{%%"g)	 & 
 	
rO   )r   c               8   U R                  U5      nU[        R                  L a/  U R                  U5      u  pVU R                  R                  XVU5      $ U[        R                  L a  U R                  R                  X5      $ [        SUR                  < S35      e)a  Deploy a Studio space or an MCP server.

Parameters
----------
repo_id : str
    For Studios, an ``owner/name`` pair. For MCP servers, the
    server identifier accepted by the OpenAPI surface.
repo_type : str or RepoType, optional
    ``"studio"`` (default) or ``"mcp"``.
payload : Mapping, optional
    Deployment configuration forwarded verbatim to the backend
    (hardware tier, env vars, ...).

Returns
-------
dict
    Deployment response payload (deployment id, status URL, ...).

Raises
------
NotSupportedError
    When ``repo_type`` is neither ``"studio"`` nor ``"mcp"``.

Examples
--------
Deploy a Studio space on a GPU instance:

>>> api.deploy_repo(
...     "alice/chat-demo",
...     repo_type="studio",
...     payload={"instance_type": "GPU-A10", "min_replicas": 1},
... )
z+deploy_repo is not supported for repo_type=r~   )
r   r   r4  rj   rR   deploy_studiorP  deploy_mcp_serverr    rw   )rH   rf   ro   r   r=  rg   ri   s          rL   deploy_repoHubApi.deploy_repod  s    P &&y1 --g6KE<<--e7CC<<11'CC"Mbhh\YZ [\\rO   c                6   U R                  U5      nU[        R                  L a.  U R                  U5      u  pEU R                  R                  XE5      $ U[        R                  L a  U R                  R                  U5      $ [        SUR                  < S35      e)z}Stop a running Studio or undeploy an MCP server.

Examples
--------
>>> api.stop_repo("alice/chat-demo", repo_type="studio")
z)stop_repo is not supported for repo_type=r~   )
r   r   r4  rj   rR   stop_studiorP  undeploy_mcp_serverr    rw   )rH   rf   ro   r=  rg   ri   s         rL   	stop_repoHubApi.stop_repo  s     &&y1 --g6KE<<++E88<<33G<<"KBHH<WX YZZrO   run   )log_typepage_numr   keywordstart_timestampend_timestampc                   U R                  U5      n	U	[        R                  La  [        SU	R                  < S35      eU R                  U5      u  pU R                  R                  U
UUUUUUUS9$ )at  Fetch paginated runtime/build logs for a Studio space.

Parameters
----------
repo_id : str
    Studio identifier in ``owner/name`` form.
repo_type : str or RepoType, optional
    Must be ``"studio"``. Defaults to :class:`RepoType.STUDIO`.
log_type : str, optional
    Either ``"run"`` (default) or ``"build"``.
page_num : int, optional
    1-based page index. Default is 1.
page_size : int, optional
    Lines per page. Default is 20.
keyword : str, optional
    Filter logs containing this substring.
start_timestamp, end_timestamp : int, optional
    Unix timestamps (seconds) bounding the log window.

Returns
-------
dict
    Paginated log payload.

Raises
------
NotSupportedError
    When ``repo_type`` is not ``"studio"``.

Examples
--------
>>> logs = api.get_repo_logs(
...     "alice/chat-demo",
...     log_type="run",
...     keyword="ERROR",
...     page_size=50,
... )
z:get_repo_logs is currently only supported for studio (got r  )r  r   r  r  r  )r   r   r4  r    rw   rj   rR   get_studio_logs)rH   rf   ro   r  r  r   r  r  r  r=  rg   ri   s               rL   get_repo_logsHubApi.get_repo_logs  s    d &&y1X__$#&`acaiai`lln$opp))'2||+++' , 	
 		
rO   c                   U R                  U5      nU R                  U5      u  pV[        R                  5        H  u  pxXs;   d  M  UR	                  U5      X8'   M!     U[
        R                  L a  U R                  R                  XVU5      $ U[
        R                  L a  U R                  R                  XVU5      $ [        SUR                  < S35      e)a1  Update repo settings (Studio or Skill).

Parameters
----------
repo_id : str
    Canonical ``owner/name`` identifier.
repo_type : str or RepoType
    Either ``"studio"`` or ``"skill"``.
**settings : Any
    Setting key/value pairs forwarded to the backend.

Returns
-------
dict
    Updated settings payload.

Raises
------
NotSupportedError
    When ``repo_type`` is neither studio nor skill.

Examples
--------
>>> api.update_repo_settings(
...     "alice/chat-demo",
...     repo_type="studio",
...     visibility="public",
...     hardware="GPU-A10",
... )
z4update_repo_settings is not supported for repo_type=r~   )r   rj   r4   r   r5  r   r4  rR   update_studio_settingsrN  update_skill_settingsr    rw   )	rH   rf   ro   settingsr=  rg   ri   rA  rB  s	            rL   update_repo_settingsHubApi.update_repo_settings  s    H &&y1))'2 5 ; ; =G"$,LL$9! !>  <<66uHMM<<55e8LL"VWYW_W_Vbbc deerO   c                   U R                  U5      nU[        R                  La  [        SUR                  < S35      eU R                  U5      u  pEU R                  R                  XE5      n[        U[        5      (       a  U$ [        U[        5      (       a3  S H-  n[        UR                  U5      [        5      (       d  M)  Xg   s  $    / $ )zList secrets attached to a Studio.

Examples
--------
>>> api.list_secrets("alice/chat-demo")
[{'key': 'OPENAI_API_KEY', 'updated_at': 1712345678}, ...]
z4Secret management is only supported for studio (got r  )r   secretsr   )r   r   r4  r    rw   rj   rR   list_studio_secretsr   r   r   r   )rH   rf   ro   r=  rg   ri   r   r   s           rL   list_secretsHubApi.list_secrets  s     &&y1X__$#&Z[][c[cZffh$ijj))'2||//<dD!!KdD!!3dhhsmT229$ 4 	rO   c                    U R                  U5      nU[        R                  La  [        S5      eU R	                  U5      u  pgU R
                  R                  XgX#5      $ )zsAdd a new secret to a Studio.

Examples
--------
>>> api.add_secret("alice/chat-demo", "OPENAI_API_KEY", "sk-...")
"Only studio secrets are supported.)r   r   r4  r    rj   rR   add_studio_secretrH   rf   r   rw   ro   r=  rg   ri   s           rL   
add_secretHubApi.add_secret/  sU     &&y1X__$#$HII))'2||--e3FFrO   c                    U R                  U5      nU[        R                  La  [        S5      eU R	                  U5      u  pgU R
                  R                  XgX#5      $ )z}Update an existing secret value.

Examples
--------
>>> api.update_secret("alice/chat-demo", "OPENAI_API_KEY", "sk-new-...")
r  )r   r   r4  r    rj   rR   update_studio_secretr  s           rL   update_secretHubApi.update_secretB  sU     &&y1X__$#$HII))'2||00cIIrO   c                    U R                  U5      nU[        R                  La  [        S5      eU R	                  U5      u  pVU R
                  R                  XVU5      $ )zmDelete a secret from a Studio.

Examples
--------
>>> api.delete_secret("alice/chat-demo", "OPENAI_API_KEY")
r  )r   r   r4  r    rj   rR   delete_studio_secret)rH   rf   r   ro   r=  rg   ri   s          rL   delete_secretHubApi.delete_secretU  sU     &&y1X__$#$HII))'2||00cBBrO   )rU  r   r   c                   U R                   R                  UUUUR                  5        VVs0 s H  u  pVUc  M
  XV_M     snn=(       d    SS9nU R                  U5      u  pp[	        [        U5      XUS9$ s  snnf )a  List MCP servers via the OpenAPI surface.

Parameters
----------
search : str, optional
    Free-text search query.
page_number : int, optional
    1-based page index. Default is 1.
page_size : int, optional
    Items per page. Default is 10.
**extra : Any
    Additional filter fields. ``None`` values are dropped.

Returns
-------
PagedResult[dict]
    Paginated MCP server listing.

Examples
--------
>>> page = api.list_mcp_servers(search="weather", page_size=5)
>>> page.total_count
12
N)rU  r   r   r<  )r   r   r   r   )rR   r_  r   r   r$   r   )rH   rU  r   r   r<  r   r   r   r   r   r   r   s               rL   r_  HubApi.list_mcp_serversj  s}    @ ,,//#$)KKMCMDAQ414MCKt	 0 
 $(#6#6w#? de%]abb Ds
   	A6A6get_operational_urlc               4    U R                   R                  XS9$ )a  Fetch a single MCP server's metadata.

Parameters
----------
server_id : str
    MCP server identifier.
get_operational_url : bool, optional
    When ``True``, the response includes the live runtime URL.

Returns
-------
dict
    MCP server metadata.

Examples
--------
>>> info = api.get_mcp_server("alice/weather-mcp", get_operational_url=True)
>>> info["operational_url"]
'https://...'
r  )rR   rQ  )rH   	server_idr  s      rL   rQ  HubApi.get_mcp_server  s    4 ||**9*^^rO   c               8    U R                   R                  X5      $ )zDeploy or redeploy an MCP server.

Examples
--------
>>> api.deploy_mcp_server("alice/weather-mcp", payload={"region": "cn-hangzhou"})
)rR   r  )rH   r  r   s      rL   r  HubApi.deploy_mcp_server  s     ||--iAArO   c                8    U R                   R                  U5      $ )zcUndeploy a running MCP server.

Examples
--------
>>> api.undeploy_mcp_server("alice/weather-mcp")
)rR   r  )rH   r  s     rL   r  HubApi.undeploy_mcp_server  s     ||//	::rO   rF  r  r  c          
        Ub  Ub  [        S5      eU R                  U5      n[        U[        U5      UUUS9u  pxU R	                  XUSS9n	U	 V
s0 s H?  oR
                  (       a  M  U
R                  (       d  M(  U
R                  U
R                  _MA     nn
[        U[        U5      UUU(       a  [        U5      OSU(       a  [        U5      S9$ SS9$ s  sn
f )zEVerify local repository files against SHA-256 checksums from the Hub.Nz.cache_dir and local_dir are mutually exclusiver  Tr  )
r   r   r   r   r  is_dirr   r  _verify_cacher   )rH   rf   ro   rF  r  r  r=  rh   resolved_revisionr  r~  expecteds               rL   r   HubApi.verify_cache  s      Y%:"#STT&&y19G 
 $$W;LX\$]7<^utKK*TXT]T]*DIIt{{*u^G&)2d9o)2d9o
 	
 9=
 	
 _s   C(C;Cc                D    [        U(       a  [        U5      5      $ S5      $ )a  Inspect the local cache directory.

Parameters
----------
cache_dir : str or Path, optional
    Override the default cache root.

Returns
-------
CacheInfo
    Aggregated cache stats (total bytes, repo entries, ...).

Examples
--------
>>> info = api.scan_cache()
>>> info.size_on_disk
12345678
>>> [r.repo_id for r in info.repos][:3]
['alice/llama-7b', 'bob/imagenet', 'carol/whisper-base']
N)_scan_cacher   )rH   r  s     rL   r   HubApi.scan_cache  s    * i4	?BBTBBrO   r  ro   rf   c               z    SnUb  [        U R                  U5      5      n[        U(       a  [        U5      OSUUS9$ )a   Remove cached data and return the number of bytes freed.

Parameters
----------
cache_dir : str or Path, optional
    Override the default cache root.
repo_type : str or RepoType, optional
    Restrict deletion to a single repository type.
repo_id : str, optional
    Restrict deletion to a single repository id.

Returns
-------
int
    Number of bytes reclaimed from disk.

Examples
--------
Wipe the cache for a single model:

>>> api.clear_cache(repo_type="model", repo_id="alice/llama-7b")
4823412

Wipe everything:

>>> api.clear_cache()
Nr  )r   r   _clear_cacher   )rH   r  ro   rf   rt_values        rL   r   HubApi.clear_cache  sC    D  $ 444Y?@H)2d9o
 	
rO   )rA   rF   rE   rD   rG   ru   )rI   zHubConfig | Noner;   
str | Noner<   r  r   None)r   r   )r   r   )r   r   )r   r   )rf   r   r   ztuple[str, str])rf   r   ro   r   r   r  )ro   r*   r   r   )r   int | str | Visibility | Noner   
int | None)r   r   r   ztuple[list[Any], int, int, int])
r   Mapping[str, Any] | Nonero   r   r   r  r   r  r   r%   )r   r  r   r   r   zRequestsCookieJar | None)r<   r   r   r&   )r<   r  r   r   r   r  )r<   r   r   r   r   r   )r   r  )r<   r   r;   r   r   r   )r   r  )r   r&   )rf   r   ro   r*   r   r  r   r  r'  r  r   r  r(  bool | Noner<  r   r   r%   )rf   r   ro   r*   rF  r  r   r%   )ro   r*   rg   r  rU  r  rV  r  r   r   r   r   rX  r   r   zPagedResult[RepoInfo])rf   r   ro   r*   r   r  )rf   r   ro   r*   r   r   )rf   r   ro   r*   r<   r  r   r   )r~  zstr | Path | BinaryIOr   r   )rf   r   ro   r*   r  zstr | Path | bytes | BinaryIOr  r   r  r  r  r  rF  r  r  r   r  r   r   r   )rf   r   ro   r*   r  z
str | Pathr  r   r  r  r  r  rF  r  r  list[str] | Noner  r  r  r  r  r   r  r   r  r   r   zdict | list[dict] | None)rf   r   ro   r*   r  r   rF  r  r  str | Path | Noner  r  r  r   r  r  r  r   rV   dict | str | Noner   r   )rf   r   ro   r*   rF  r  r  r  r  r  r  r  r  r  r  r   r  r   rV   r  r  z#list[type[ProgressCallback]] | Noner   r   )
rf   r   ro   r*   rF  r  r  r   r   zlist[FileInfo])rf   r   ro   r*   r  zIterable[str]r  r  rF  r  r   r   )rf   r   ro   r*   r   z
list[dict])
rf   r   ro   r*   r  r   rF  r  r   r   )rf   r   ro   r*   r   r  r   r   )rf   r   ro   r*   r   r   )rf   r   ro   r*   r  r   r  r   r   r   r  r  r  r  r  r  r   r   )rf   r   ro   r*   r  r   r   r   )
rf   r   r   r   rw   r   ro   r*   r   r   )rf   r   r   r   ro   r*   r   r   )
rU  r  r   r   r   r   r<  r   r   zPagedResult[dict])r  r   r  r  r   r   )r  r   r   r  r   r   )r  r   r   r   )rq  )rf   r   ro   r*   rF  r  r  r  r  r  r   r"   )r  r  r   r!   )r  r  ro   zRepoTypeLike | Nonerf   r  r   r   )>__name__
__module____qualname____firstlineno____doc__rM   propertyrR   rY   r\   ra   staticmethodrj   r`   r   r   r   	frozensetr   r   r   r   r   r   r   r  r	  r"  r   rm   rR  rd  rl  ro  r{  r  r  r  r  r  r  r  r  r  r   r4  r  r  r  r  r  r  r  r  r_  rQ  r  r  r   r   r   __static_attributes__ rO   rL   r(   r(   c   s	   &T $(4  $ 4 4 	4
 4 
4B           $ 	 	 m m ; ; !	
 "( "(H 
 "& $@.&@.@. 	@.
 @. 
@. @.N $(? "'	? ? 	?
 
"?BJX'
8*  ,&P@ 59"#'"&"&dXdX  dX
 2dX dX !dX  dX  dX dX 
dXV  $AXAX  AX
 AX 
AXN !!oqoq 	oq
 oq oq oq oq oq 
oqbD<* #* >[>[  	>[
 >[ 
>[F" &*)-# "I
I
  I
 7	I

 I
 #I
 'I
 I
 I
 I
 
I
b %))-#+/,0"&"!&W
W
  W
  	W
 W
 #W
 'W
 W
 )W
 *W
  W
 W
 W
 W
  
"!W
~  $'+'+&*!&(,S
S
  S
 	S
 S
 %S
 %S
 S
 $S
 S
 &S
 
S
t  $'+'++/,0!&(,BFS
S
  S

 S
 %S
 %S
 )S
 *S
 S
 S
 &S
 @S
 
S
t  $33  3
 3 3 
3v &*#D]D]  D] "	D] #D] D] 
D]R
N$  $

  
 	
 
 

8 #+//.]
 -1.].]  .]
 *.] 
.]f #+//[[  [ 
	[, #+//?

 "&*$(?
?
  ?

 ?
 ?
 ?
 ?
 $?
 "?
 
?
B-f-f  -f 	-f
 
-fd DL?? 4 #+//GG G 	G
  G 
G0 #+//JJ J 	J
  J 
J. #+//	CC C  	C
 
C0 "'c 'c 	'c
 'c 'c 
'cZ ,0	__ )	_
 
_8 X\ B; #*

  $'+'+

  

 
 %
 %
 

>C4 (,)-")
 %)
 '	)

 )
 
)
 )
rO   N)Hr!  
__future__r   collections.abcr   r   pathlibr   typingr   r   r	   urllib.parser
   requests.cookiesr   _cache_managerr   r   r  r   r  r   r  	_downloadr   r   _legacy_apir   rD   r   _uploadr   rI   r   r   r  r   r   r   errorsr   r   r   r   r   r    typesr!   r"   r#   r$   r%   r&   utils.loggerr'   __all__r:  r*   __annotations__r$  rH  r9  r4  rN  r+   r,   r-   r1   r4   r7   r(   r&  rO   rL   <module>r6     si  . # -  + + ! . 6 7 5 9 8 % # " 1 = =  [ Z $*	E	*i *
 )28>>8CSCSU]UdUdfnftft2u(v % v-67X-Y * Y-6^^X%%xG. *  '"""", . ( <) ~  *33L)M  M@
 @
rO   