-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapi.py
More file actions
2083 lines (1854 loc) · 74.1 KB
/
Copy pathapi.py
File metadata and controls
2083 lines (1854 loc) · 74.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""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.
"""
from __future__ import annotations
from collections.abc import Iterable, Mapping
from pathlib import Path
from typing import Any, BinaryIO, TypeAlias
from urllib.parse import urlparse
from requests.cookies import RequestsCookieJar
from ._cache_manager import _resolve_verification_root
from ._cache_manager import clear_cache as _clear_cache
from ._cache_manager import scan_cache as _scan_cache
from ._cache_manager import verify_cache as _verify_cache
from ._download import DownloadManager, ProgressCallback
from ._legacy_api import LegacyClient
from ._openapi import OpenAPIClient
from ._upload import UploadManager
from .config import HubConfig, get_default_config
from .constants import DEFAULT_ENDPOINT, RepoType, Visibility
from .errors import (
AuthenticationError,
HubError,
InvalidParameter,
NetworkError,
NotExistError,
NotSupportedError,
)
from .types import CacheInfo, CacheVerification, FileInfo, PagedResult, RepoInfo, UserInfo
from .utils.logger import get_logger
__all__ = ["HubApi"]
logger = get_logger("api")
RepoTypeLike: TypeAlias = "str | RepoType"
# Routing tables — declarative dispatch keeps :class:`HubApi` free of long
# if/elif chains and makes adding new repo types a one-line change.
_CREATABLE_TYPES: frozenset[RepoType] = frozenset({RepoType.MODEL, RepoType.DATASET, RepoType.STUDIO, RepoType.SKILL})
_OPENAPI_CREATE_TYPES: frozenset[RepoType] = frozenset({RepoType.STUDIO, RepoType.SKILL})
_OPENAPI_DETAIL_TYPES: frozenset[RepoType] = frozenset(
{RepoType.MODEL, RepoType.DATASET, RepoType.STUDIO, RepoType.SKILL}
)
# Mapping of common license display names to their SPDX identifiers. The Hub
# backend rejects display names like ``"Apache License 2.0"`` — we translate
# them transparently while passing unknown values (already SPDX) through.
_LICENSE_DISPLAY_TO_SPDX: dict[str, str] = {
"Apache License 2.0": "apache-2.0",
"MIT License": "mit",
"GPL-2.0": "gpl-2.0",
"GPL-3.0": "gpl-3.0",
"LGPL-2.1": "lgpl-2.1",
"LGPL-3.0": "lgpl-3.0",
"AFL-3.0": "afl-3.0",
"ECL-2.0": "ecl-2.0",
"BSD-2-Clause": "bsd-2-clause",
"BSD-3-Clause": "bsd-3-clause",
"CC-BY-4.0": "cc-by-4.0",
"CC-BY-SA-4.0": "cc-by-sa-4.0",
"CC-BY-NC-4.0": "cc-by-nc-4.0",
"CC0-1.0": "cc0-1.0",
"Unlicense": "unlicense",
}
_STUDIO_FIELD_RENAMES: dict[str, str] = {
"cover_image": "coverImage",
}
# Reserved fields that are controlled by create_repo method parameters.
# These MUST NOT be overridden via extra kwargs to avoid silent conflicts.
_RESERVED_EXTRA_FIELDS: frozenset[str] = frozenset({"Path", "Owner", "Name"})
class HubApi:
"""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")
"""
def __init__(
self,
config: HubConfig | None = None,
*,
endpoint: str | None = None,
token: str | None = None,
) -> None:
base = config or get_default_config()
if config is None and (endpoint is not None or token is not None):
from dataclasses import replace
was_overridden = base._endpoint_overridden
base = replace(base)
# replace() re-runs __post_init__ which sees the inherited
# endpoint string as "explicit" and sets _endpoint_overridden.
# Restore the original state so resolve_endpoint_for_read works.
base._endpoint_overridden = was_overridden
self._config = base
if endpoint is not None:
self._config.endpoint = HubConfig.normalize_endpoint(endpoint)
self._config._endpoint_overridden = True
if token is not None:
self._config.token = token
self._config._token_overridden = True
self._openapi: OpenAPIClient | None = None
self._legacy: LegacyClient | None = None
self._downloader: DownloadManager | None = None
self._uploader: UploadManager | None = None
# ==================================================================
# Lazy client accessors
# ==================================================================
@property
def openapi(self) -> OpenAPIClient:
"""Lazily-constructed OpenAPI client."""
if self._openapi is None:
self._openapi = OpenAPIClient(self._config)
return self._openapi
@property
def legacy(self) -> LegacyClient:
"""Lazily-constructed legacy ``/api/v1`` client."""
if self._legacy is None:
from .utils import build_user_agent
self._legacy = LegacyClient(
token=self._config.token,
endpoint=self._config.endpoint or DEFAULT_ENDPOINT,
user_agent=build_user_agent(self._config.get_session_id()),
)
elif self._legacy.token != self._config.token:
# Clears propagate as well as changes: a cached client left holding a
# revoked token would keep authenticating with it.
self._legacy.token = self._config.token
return self._legacy
@property
def downloader(self) -> DownloadManager:
"""Lazily-constructed :class:`DownloadManager`."""
if self._downloader is None:
self._downloader = DownloadManager(self.legacy, self._config)
return self._downloader
@property
def uploader(self) -> UploadManager:
"""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.
"""
if self._uploader is None:
self._uploader = UploadManager(
self.legacy,
self._config,
self.openapi,
create_repo_fn=self._create_repo_exist_ok,
)
return self._uploader
# ==================================================================
# Static helpers
# ==================================================================
@staticmethod
def _parse_repo_id(repo_id: str) -> tuple[str, str]:
"""Split a canonical ``owner/name`` identifier into its two halves."""
if not repo_id or "/" not in repo_id:
raise InvalidParameter(f"repo_id {repo_id!r} should be in format of 'owner/name'.")
owner, _, name = repo_id.partition("/")
if not owner or not name:
raise InvalidParameter(
f"repo_id {repo_id!r} should be in format of 'owner/name': owner and name must both be non-empty."
)
return owner, name
def _create_repo_exist_ok(self, repo_id: str, repo_type: str) -> None:
"""Auto-create the repo if it doesn't exist, silently ignore if it does."""
try:
self.create_repo(repo_id, repo_type)
except HubError:
pass
@staticmethod
def _normalize_repo_type(repo_type: RepoTypeLike) -> RepoType:
"""Coerce a ``str`` or :class:`RepoType` value to a :class:`RepoType`."""
if isinstance(repo_type, RepoType):
return repo_type
try:
return RepoType(str(repo_type).lower())
except ValueError as exc:
allowed = ", ".join(t.value for t in RepoType)
raise InvalidParameter(f"Unknown repo_type {repo_type!r}. Expected one of: {allowed}.") from exc
@staticmethod
def _normalize_visibility(visibility: int | str | Visibility | None) -> int | None:
"""Normalise visibility input to its integer wire encoding."""
if visibility is None:
return None
if isinstance(visibility, Visibility):
return int(visibility)
if isinstance(visibility, int):
return visibility
return int(Visibility.from_label(str(visibility)))
_PAGED_ITEM_KEYS = (
"items",
"list",
"data",
"results",
"models",
"datasets",
"skills",
"servers",
"mcp_server_list",
"Models",
"Datasets",
"Skills",
"Servers",
)
_PAGED_META_KEYS = frozenset(
{
"total_count",
"total",
"page_number",
"page",
"page_size",
"size",
"TotalCount",
"Total",
"PageNumber",
"PageSize",
}
)
@staticmethod
def _extract_paged(payload: Any) -> tuple[list[Any], int, int, int]:
"""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.
"""
if isinstance(payload, list):
return payload, len(payload), 1, len(payload)
if not isinstance(payload, dict):
return [], 0, 1, 0
items: list[Any] = []
for key in HubApi._PAGED_ITEM_KEYS:
if isinstance(payload.get(key), list):
items = payload[key]
break
else:
for key, value in payload.items():
if isinstance(value, list) and key not in HubApi._PAGED_META_KEYS:
items = value
break
def _first(keys: tuple[str, ...], default: int) -> int:
for k in keys:
v = payload.get(k)
if v is not None:
return int(v)
return default
total = _first(("total_count", "TotalCount", "total"), len(items))
page = _first(("page_number", "PageNumber", "page"), 1)
size = _first(("page_size", "PageSize", "size"), len(items))
return items, total, page, size
@staticmethod
def _repo_info_from_payload(
data: Mapping[str, Any] | None,
repo_type: RepoType,
*,
owner_hint: str | None = None,
name_hint: str | None = None,
) -> RepoInfo:
"""Build 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.
"""
data = dict(data or {})
# PascalCase → snake_case shims for legacy responses.
normalised: dict[str, Any] = {}
aliases = {
"Id": "id",
"Path": "owner",
"Name": "name",
"Owner": "owner",
"Visibility": "visibility",
"License": "license",
"Description": "description",
"Downloads": "downloads",
"Likes": "likes",
"CreatedAt": "created_at",
"UpdatedAt": "last_modified",
"LastModified": "last_modified",
"last_modified": "last_modified",
"updated_at": "last_modified",
"Tags": "tags",
}
for key, value in data.items():
normalised[aliases.get(key, key)] = value
# The OpenAPI surface uses ``private`` bool for visibility.
# gated is orthogonal and does not affect visibility mapping.
if normalised.get("visibility") is None:
private_flag = normalised.get("private")
if isinstance(private_flag, bool):
if private_flag:
normalised["visibility"] = Visibility.PRIVATE
else:
normalised["visibility"] = Visibility.PUBLIC
elif normalised.get("gated"):
# Rule 4: visibility unknown + gated=True → imply PRIVATE
normalised["visibility"] = Visibility.PRIVATE
# The OpenAPI list endpoints return ``id`` as "owner/name".
# Split it so the computed ``repo_id`` property works.
id_val = normalised.get("id")
if isinstance(id_val, str) and "/" in id_val:
parts = id_val.split("/", 1)
if not normalised.get("owner"):
normalised["owner"] = parts[0]
if not normalised.get("name"):
normalised["name"] = parts[1]
if not normalised.get("owner"):
normalised["owner"] = owner_hint
if not normalised.get("name"):
normalised["name"] = name_hint
normalised["repo_type"] = repo_type
return RepoInfo.from_dict(normalised)
# ==================================================================
# Authentication
# ==================================================================
def get_cookies(
self,
access_token: str | None = None,
*,
cookies_required: bool = False,
) -> RequestsCookieJar | None:
"""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'
"""
token = access_token or self._config.token
if token:
domain = urlparse(self._config.endpoint).hostname or ""
jar = RequestsCookieJar()
jar.set("m_session_id", token, domain=domain, path="/")
return jar
# An explicitly overridden (empty) token means "run without local
# credentials" -- never silently fall back to the persisted cookies.
if not getattr(self._config, "_token_overridden", False):
cookies = self._config.load_cookies()
if cookies is not None:
return cookies
if cookies_required:
raise AuthenticationError(
"No credentials found. "
"Pass --token, call HubApi.login(), or set MODELSCOPE_API_TOKEN. "
"Your token is available at https://modelscope.cn/my/myaccesstoken"
)
return None
def login(self, token: str) -> UserInfo:
"""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'
"""
if not token or not token.strip():
raise InvalidParameter("token must be a non-empty string")
token = token.strip()
previous_token = self._config.token
previous_logged_out = self._config._logged_out
self._config.token = token
self._config._logged_out = False
self._openapi = None
if self._legacy is not None:
self._legacy.token = token
try:
data, cookies = self.legacy.login(token)
except HubError as exc:
self._restore_credential_state(previous_token, previous_logged_out)
explained = self._explain_login_failure(token, exc)
if explained is exc:
raise
raise explained from exc
git_token = data.get("AccessToken", "")
username = data.get("Username", "")
email = data.get("Email", "")
self._config.save_cookies(cookies)
if git_token:
self._config.save_git_token(git_token)
if username:
self._config.save_user_info(username, email or "")
return self.whoami()
def _restore_credential_state(self, token: str | None, logged_out: bool) -> None:
"""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.
"""
self._config.token = token
self._config._logged_out = logged_out
self._openapi = None
if self._legacy is not None:
self._legacy.token = token
def _explain_login_failure(self, token: str, exc: HubError) -> HubError:
"""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.
"""
if not isinstance(exc, AuthenticationError):
return exc
peer = self._peer_site_endpoint()
if peer is None or not self._token_valid_on(token, peer):
return exc
return AuthenticationError(
f"{exc.message} This token is valid on {peer} instead; retry with "
f"--endpoint {peer} (or set MODELSCOPE_ENDPOINT={peer}).",
status_code=exc.status_code,
request_id=exc.request_id,
response_body=exc.response_body,
url=exc.url,
method=exc.method,
)
def _peer_site_endpoint(self) -> str | None:
"""Return 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.
"""
if self._config._endpoint_overridden:
return None
from .constants import DEFAULT_INTL_ENDPOINT
def site_key(url: str) -> str:
host = (urlparse(url).hostname or "").lower()
return host[4:] if host.startswith("www.") else host
current = site_key(self._config.endpoint or DEFAULT_ENDPOINT)
for candidate in (DEFAULT_ENDPOINT, DEFAULT_INTL_ENDPOINT):
if site_key(candidate) != current:
return candidate
return None
@staticmethod
def _token_valid_on(token: str, endpoint: str) -> bool:
"""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.
"""
from .constants import API_CONNECT_TIMEOUT
probe = LegacyClient(
token=None,
endpoint=endpoint,
timeout=API_CONNECT_TIMEOUT,
max_retries=0,
)
try:
probe.login(token)
except Exception: # advisory only -- never mask the original failure
return False
return True
def logout(self) -> None:
"""Clear the locally persisted token.
Cached HTTP clients are reset so subsequent calls behave as if
no credential was ever provided.
Examples
--------
>>> api.logout()
"""
self._config.clear_token()
self._openapi = None
if self._legacy is not None:
self._legacy.token = None
def whoami(self) -> UserInfo:
"""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
"""
payload = self.openapi.get_current_user()
return UserInfo.from_dict(payload if isinstance(payload, dict) else {})
# ==================================================================
# Unified repo CRUD
# ==================================================================
def create_repo(
self,
repo_id: str,
repo_type: RepoTypeLike,
*,
visibility: int | str | Visibility | None = None,
license: str | None = None,
chinese_name: str | None = None,
description: str | None = None,
gated_mode: bool | None = None,
**extra: Any,
) -> RepoInfo:
"""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")
"""
rt = self._normalize_repo_type(repo_type)
if rt not in _CREATABLE_TYPES:
supported = ", ".join(sorted(t.value for t in _CREATABLE_TYPES))
raise NotSupportedError(
f"create_repo does not support repo_type={rt.value!r}. Supported types: {supported}."
)
owner, name = self._parse_repo_id(repo_id)
vis = self._normalize_visibility(visibility)
if license is not None:
license = _LICENSE_DISPLAY_TO_SPDX.get(license, license)
if rt in _OPENAPI_CREATE_TYPES:
is_private = vis is not None and vis == int(Visibility.PRIVATE)
if rt is RepoType.STUDIO:
payload: dict[str, Any] = {
"owner": owner,
"repo_name": name,
}
if vis is not None:
payload["private"] = is_private
if chinese_name is not None:
payload["display_name"] = chinese_name
else:
payload = {
"owner": owner,
"skill_name": name,
}
if vis is not None:
payload["private"] = is_private
if chinese_name is not None:
payload["display_name"] = chinese_name
if license is not None:
payload["license"] = license
if description is not None:
payload["description"] = description
for old_key, new_key in _STUDIO_FIELD_RENAMES.items():
if old_key in extra:
extra[new_key] = extra.pop(old_key)
payload.update(extra)
data = self.openapi.create_studio(payload) if rt is RepoType.STUDIO else self.openapi.create_skill(payload)
return self._repo_info_from_payload(data, rt, owner_hint=owner, name_hint=name)
if rt is RepoType.DATASET:
body: dict[str, Any] = {
"Owner": owner,
"Name": name,
"Visibility": vis if vis is not None else int(Visibility.PUBLIC),
"License": license or "Apache-2.0",
}
else:
body = {
"Path": owner,
"Name": name,
"Visibility": vis if vis is not None else int(Visibility.PUBLIC),
"License": license or "Apache-2.0",
}
if chinese_name is not None:
body["ChineseName"] = chinese_name
if description is not None:
body["Description"] = description
# gated_mode → ProtectedMode wire field (1=gated, 2=off).
# gated only effective with PRIVATE; when vis=None + gated=True,
# implicitly set visibility to PRIVATE (user intent: gated repo).
if gated_mode is not None:
if vis is None:
vis = int(Visibility.PRIVATE)
body["Visibility"] = vis
body["ProtectedMode"] = 1 if gated_mode else 2
elif vis == int(Visibility.PRIVATE):
body["ProtectedMode"] = 1 if gated_mode else 2
else:
logger.warning("gated_mode is only effective when visibility is PRIVATE, ignored.")
# Blocklist filtering: only reject fields controlled by method params.
filtered: dict[str, Any] = {}
for k, v in extra.items():
if k in _RESERVED_EXTRA_FIELDS:
logger.warning("Reserved field %r in extra ignored (controlled by method params)", k)
continue
filtered[k] = v
if "ProtectedMode" in filtered:
pm = filtered["ProtectedMode"]
if not isinstance(pm, int) or isinstance(pm, bool) or pm not in (1, 2):
raise ValueError("ProtectedMode must be int 1 (gated) or 2 (off); use gated_mode=True/False instead")
body.update(filtered)
data = self.legacy.create_repo(repo_type=str(rt), body=body)
return self._repo_info_from_payload(data, rt, owner_hint=owner, name_hint=name)
def get_repo(
self,
repo_id: str,
repo_type: RepoTypeLike,
*,
revision: str | None = None, # noqa: ARG002 - reserved for future use
) -> RepoInfo:
"""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
"""
rt = self._normalize_repo_type(repo_type)
owner, name = self._parse_repo_id(repo_id)
if rt is RepoType.MODEL:
try:
data = self.openapi.get_model(owner, name)
except NotExistError:
data = self.legacy.get_repo_info(repo_id, str(rt))
elif rt is RepoType.DATASET:
try:
data = self.openapi.get_dataset(owner, name)
except NotExistError:
logger.debug(
"Dataset %s/%s not found in OpenAPI, falling back to legacy API",
owner,
name,
)
data = self.legacy.get_repo_info(repo_id, str(rt))
elif rt is RepoType.STUDIO:
data = self.openapi.get_studio(owner, name)
elif rt is RepoType.SKILL:
data = self.openapi.get_skill(f"{owner}/{name}")
elif rt is RepoType.MCP:
data = self.openapi.get_mcp_server(f"{owner}/{name}")
else: # pragma: no cover - defensive
raise NotSupportedError(f"get_repo not supported for {rt}")
return self._repo_info_from_payload(data, rt, owner_hint=owner, name_hint=name)
def list_repos(
self,
repo_type: RepoTypeLike,
*,
owner: str | None = None,
search: str | None = None,
sort: str | None = None,
page_number: int = 1,
page_size: int = 10,
**filters: Any,
) -> PagedResult[RepoInfo]:
"""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)
"""
rt = self._normalize_repo_type(repo_type)
clean_filters: dict[str, Any] = {k: v for k, v in filters.items() if v is not None}
if rt is RepoType.MODEL:
payload = self.openapi.list_models(
search=search,
owner=owner,
sort=sort,
page_number=page_number,
page_size=page_size,
filters=clean_filters or None,
)
elif rt is RepoType.DATASET:
payload = self.openapi.list_datasets(
search=search,
owner=owner,
sort=sort,
page_number=page_number,
page_size=page_size,
filters=clean_filters or None,
)
elif rt is RepoType.SKILL:
if owner:
clean_filters.setdefault("owner", owner)
payload = self.openapi.list_skills(
search=search,
page_number=page_number,
page_size=page_size,
filters=clean_filters or None,
)
elif rt is RepoType.MCP:
payload = self.openapi.list_mcp_servers(
search=search,
page_number=page_number,
page_size=page_size,
filter=clean_filters or None,
)
elif rt is RepoType.STUDIO:
raise NotSupportedError("Listing studios is not supported by the OpenAPI surface yet.")
else: # pragma: no cover - defensive
raise NotSupportedError(f"list_repos not supported for {rt}")
items, total, page, size = self._extract_paged(payload)
# MCP response omits page_number/page_size — use requested values.