@simplexai/localmodels-win32-x64 0.1.0-dev.58 → 0.1.0-dev.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +105 -98
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +104 -43
- package/modules/localmodels/app.py +1 -1
- package/modules/localmodels/apple_sensors.py +431 -0
- package/modules/localmodels/bifrost_admin.py +83 -8
- package/modules/localmodels/bifrost_checks.py +2 -2
- package/modules/localmodels/bifrost_config.py +235 -13
- package/modules/localmodels/bifrost_log.py +166 -0
- package/modules/localmodels/bifrost_models.py +1 -1
- package/modules/localmodels/budget.py +1 -1
- package/modules/localmodels/catalog.json +192 -77
- package/modules/localmodels/catalog.py +20 -3
- package/modules/localmodels/catalog_add.py +42 -11
- package/modules/localmodels/custom_hub.py +983 -0
- package/modules/localmodels/custom_hub_http.py +579 -0
- package/modules/localmodels/custom_probe.py +451 -0
- package/modules/localmodels/deploy.py +27 -5
- package/modules/localmodels/deploy_steps.py +5 -0
- package/modules/localmodels/download-mirrors.json +8 -0
- package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
- package/modules/localmodels/engines.py +38 -8
- package/modules/localmodels/estimator.py +60 -7
- package/modules/localmodels/frontend.py +26 -21
- package/modules/localmodels/gateway.py +48 -3
- package/modules/localmodels/gateway_app_bifrost.py +4 -4
- package/modules/localmodels/gateway_bifrost.py +128 -21
- package/modules/localmodels/gguf.py +6 -0
- package/modules/localmodels/host_sensors.py +704 -0
- package/modules/localmodels/hosts.py +99 -12
- package/modules/localmodels/library_cli.py +181 -3
- package/modules/localmodels/library_convert.py +34 -0
- package/modules/localmodels/library_custom.py +831 -0
- package/modules/localmodels/library_elastic.py +182 -127
- package/modules/localmodels/library_gateway.py +193 -40
- package/modules/localmodels/library_jobs.py +92 -18
- package/modules/localmodels/library_kept.py +50 -6
- package/modules/localmodels/library_model.py +254 -2
- package/modules/localmodels/library_pricing.py +97 -8
- package/modules/localmodels/library_serve.py +196 -66
- package/modules/localmodels/library_smoke.py +315 -0
- package/modules/localmodels/library_state.py +81 -2
- package/modules/localmodels/library_status.py +144 -8
- package/modules/localmodels/metal.py +1 -1
- package/modules/localmodels/metal_probe.py +4 -4
- package/modules/localmodels/nvml_ctypes.py +431 -0
- package/modules/localmodels/plan_envelope.py +18 -7
- package/modules/localmodels/process_identity_linux.py +39 -0
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/remote_ops.py +57 -8
- package/modules/localmodels/remote_ops_download.py +205 -53
- package/modules/localmodels/remote_ops_mirrors.py +43 -2
- package/modules/localmodels/remote_ops_ranges.py +2 -5
- package/modules/localmodels/remote_ops_service.py +95 -37
- package/modules/localmodels/remote_ops_verify.py +22 -5
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_auth.py +4 -1
- package/modules/localmodels/service_control.py +32 -1
- package/modules/localmodels/service_wiring.py +237 -12
- package/modules/localmodels/service_worker.py +6 -2
- package/modules/localmodels/services_cli.py +35 -27
- package/modules/localmodels/setup_inspection.py +47 -70
- package/modules/localmodels/setup_inspection_harness.py +159 -15
- package/modules/localmodels/setup_text.py +14 -0
- package/modules/localmodels/setup_upgrade.py +1 -1
- package/modules/localmodels/source_byok.py +9 -7
- package/modules/localmodels/source_byok_probe.py +6 -1
- package/modules/localmodels/stack.py +9 -1
- package/modules/localmodels/stack_binding.py +3 -35
- package/modules/localmodels/stack_cleanup.py +4 -0
- package/modules/localmodels/stack_compose.py +18 -2
- package/modules/localmodels/stack_lifecycle.py +26 -3
- package/modules/localmodels/stack_memory.py +1 -0
- package/modules/localmodels/stack_plan.py +6 -2
- package/modules/localmodels/stack_ports.py +2 -0
- package/modules/localmodels/stack_remove.py +10 -1
- package/modules/localmodels/stack_up.py +33 -7
- package/modules/localmodels/stack_update.py +3 -1
- package/modules/localmodels/stack_view.py +77 -53
- package/modules/localmodels/stack_view_demo.py +36 -5
- package/modules/localmodels/stack_view_events.py +147 -12
- package/modules/localmodels/stack_view_gpu.py +97 -17
- package/modules/localmodels/stack_view_llm.py +15 -0
- package/modules/localmodels/stack_view_measure.py +4 -1
- package/modules/localmodels/stack_view_schema.py +54 -8
- package/modules/localmodels/stack_view_serve.py +40 -3
- package/modules/localmodels/stack_view_slots.py +89 -10
- package/modules/localmodels/stack_view_telemetry.py +163 -0
- package/modules/localmodels/stack_view_text.py +5 -2
- package/modules/localmodels/stack_view_tick.py +658 -0
- package/modules/localmodels/stack_view_words.py +4 -0
- package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
- package/modules/localmodels/suite.py +45 -27
- package/modules/localmodels/telemetry_math.py +538 -0
- package/modules/localmodels/transport.py +13 -2
- package/modules/localmodels/web/view/view.js +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/RECORD +102 -95
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/bifrost_datasheet.py +0 -53
- package/modules/localmodels/bifrost_provider.py +0 -88
- package/modules/localmodels/bifrost_unit.py +0 -99
- package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
- package/modules/localmodels/gateway_switch.py +0 -51
- package/modules/localmodels/library_floor.py +0 -78
- package/modules/localmodels/service_stop.py +0 -52
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,983 @@
|
|
|
1
|
+
"""Read-only Hugging Face and ModelScope hub client for custom GGUF discovery and probing.
|
|
2
|
+
|
|
3
|
+
Strictly stdlib-only Python (no ``huggingface_hub`` or ``modelscope`` SDK imports). Handles URL
|
|
4
|
+
and shorthand parsing, concurrent hub search with partial-success warnings, recursive file tree
|
|
5
|
+
listing, directory-scoped split GGUF shard grouping with completeness validation, ``mmproj``
|
|
6
|
+
ranking, non-GGUF format detection, and bounded HTTP Range GGUF header inspection. HTTP transport,
|
|
7
|
+
redirect/SSRF defense, and token gating live in ``localmodels/custom_hub_http.py``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import concurrent.futures
|
|
13
|
+
import http.client
|
|
14
|
+
import io
|
|
15
|
+
import struct
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.parse
|
|
18
|
+
from collections.abc import Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Literal, NamedTuple, cast
|
|
21
|
+
|
|
22
|
+
from localmodels import catalog_add, quant_formats
|
|
23
|
+
from localmodels.custom_hub_http import (
|
|
24
|
+
CUSTOM_MODEL_ID_MAX_LEN as CUSTOM_MODEL_ID_MAX_LEN,
|
|
25
|
+
)
|
|
26
|
+
from localmodels.custom_hub_http import (
|
|
27
|
+
HF_HOSTS as HF_HOSTS,
|
|
28
|
+
)
|
|
29
|
+
from localmodels.custom_hub_http import (
|
|
30
|
+
HF_MIRROR_HOSTS as HF_MIRROR_HOSTS,
|
|
31
|
+
)
|
|
32
|
+
from localmodels.custom_hub_http import (
|
|
33
|
+
HF_OFFICIAL_HOSTS as HF_OFFICIAL_HOSTS,
|
|
34
|
+
)
|
|
35
|
+
from localmodels.custom_hub_http import (
|
|
36
|
+
MAX_JSON_RESPONSE_BYTES as MAX_JSON_RESPONSE_BYTES,
|
|
37
|
+
)
|
|
38
|
+
from localmodels.custom_hub_http import (
|
|
39
|
+
MODEL_ID_RE as MODEL_ID_RE,
|
|
40
|
+
)
|
|
41
|
+
from localmodels.custom_hub_http import (
|
|
42
|
+
MODELSCOPE_API as MODELSCOPE_API,
|
|
43
|
+
)
|
|
44
|
+
from localmodels.custom_hub_http import (
|
|
45
|
+
MS_HOSTS as MS_HOSTS,
|
|
46
|
+
)
|
|
47
|
+
from localmodels.custom_hub_http import (
|
|
48
|
+
RANGE_TIMEOUT_S as RANGE_TIMEOUT_S,
|
|
49
|
+
)
|
|
50
|
+
from localmodels.custom_hub_http import (
|
|
51
|
+
SEARCH_TIMEOUT_S as SEARCH_TIMEOUT_S,
|
|
52
|
+
)
|
|
53
|
+
from localmodels.custom_hub_http import (
|
|
54
|
+
TREE_TIMEOUT_S as TREE_TIMEOUT_S,
|
|
55
|
+
)
|
|
56
|
+
from localmodels.custom_hub_http import (
|
|
57
|
+
USER_AGENT as USER_AGENT,
|
|
58
|
+
)
|
|
59
|
+
from localmodels.custom_hub_http import (
|
|
60
|
+
ParsedRepoSpec as ParsedRepoSpec,
|
|
61
|
+
)
|
|
62
|
+
from localmodels.custom_hub_http import (
|
|
63
|
+
SafeRedirectHandler as SafeRedirectHandler,
|
|
64
|
+
)
|
|
65
|
+
from localmodels.custom_hub_http import (
|
|
66
|
+
build_opener as build_opener,
|
|
67
|
+
)
|
|
68
|
+
from localmodels.custom_hub_http import (
|
|
69
|
+
build_suggested_gguf_query as build_suggested_gguf_query,
|
|
70
|
+
)
|
|
71
|
+
from localmodels.custom_hub_http import (
|
|
72
|
+
hf_endpoints as hf_endpoints,
|
|
73
|
+
)
|
|
74
|
+
from localmodels.custom_hub_http import (
|
|
75
|
+
http_json as http_json,
|
|
76
|
+
)
|
|
77
|
+
from localmodels.custom_hub_http import (
|
|
78
|
+
http_range as http_range,
|
|
79
|
+
)
|
|
80
|
+
from localmodels.custom_hub_http import (
|
|
81
|
+
infer_family as infer_family,
|
|
82
|
+
)
|
|
83
|
+
from localmodels.custom_hub_http import (
|
|
84
|
+
infer_parameter_billions as infer_parameter_billions,
|
|
85
|
+
)
|
|
86
|
+
from localmodels.custom_hub_http import (
|
|
87
|
+
make_custom_model_id as make_custom_model_id,
|
|
88
|
+
)
|
|
89
|
+
from localmodels.custom_hub_http import (
|
|
90
|
+
parse_repo_spec as parse_repo_spec,
|
|
91
|
+
)
|
|
92
|
+
from localmodels.custom_hub_http import (
|
|
93
|
+
redact_secrets as redact_secrets,
|
|
94
|
+
)
|
|
95
|
+
from localmodels.custom_hub_http import (
|
|
96
|
+
repo_web_url as repo_web_url,
|
|
97
|
+
)
|
|
98
|
+
from localmodels.custom_hub_http import (
|
|
99
|
+
resolve_token as resolve_token,
|
|
100
|
+
)
|
|
101
|
+
from localmodels.custom_hub_http import (
|
|
102
|
+
token_for_endpoint as token_for_endpoint,
|
|
103
|
+
)
|
|
104
|
+
from localmodels.custom_hub_http import (
|
|
105
|
+
validate_redirect_target as validate_redirect_target,
|
|
106
|
+
)
|
|
107
|
+
from localmodels.custom_hub_http import (
|
|
108
|
+
variant_slug as _variant_slug,
|
|
109
|
+
)
|
|
110
|
+
from localmodels.gguf import SPLIT_PART_RE, GGUFHeader, read_header_stream
|
|
111
|
+
from localmodels.library_model import (
|
|
112
|
+
CustomFormatFilter,
|
|
113
|
+
CustomHub,
|
|
114
|
+
CustomIncompatibleReason,
|
|
115
|
+
CustomRepoFormat,
|
|
116
|
+
CustomSearchHub,
|
|
117
|
+
CustomSearchResult,
|
|
118
|
+
CustomSearchWarning,
|
|
119
|
+
LibraryError,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
SUPPORTED_FORMATS: tuple[str, ...] = ("gguf",)
|
|
123
|
+
HEADER_INITIAL_BYTES = 8 << 20
|
|
124
|
+
HEADER_MAX_BYTES = 32 << 20
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class RepoFile(NamedTuple):
|
|
128
|
+
path: str
|
|
129
|
+
size_bytes: int
|
|
130
|
+
sha256: str | None
|
|
131
|
+
revision: str
|
|
132
|
+
download_url: str
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass(frozen=True)
|
|
136
|
+
class FetchedRepo:
|
|
137
|
+
hub: CustomHub
|
|
138
|
+
repo_id: str
|
|
139
|
+
revision: str
|
|
140
|
+
url: str
|
|
141
|
+
title: str
|
|
142
|
+
owner: str
|
|
143
|
+
license: str | None
|
|
144
|
+
gated: bool
|
|
145
|
+
tags: tuple[str, ...]
|
|
146
|
+
files: tuple[RepoFile, ...]
|
|
147
|
+
endpoint: str
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass(frozen=True)
|
|
151
|
+
class HubGated:
|
|
152
|
+
hub: CustomHub
|
|
153
|
+
repo_id: str
|
|
154
|
+
url: str
|
|
155
|
+
http_status: Literal[401, 403]
|
|
156
|
+
token_provided: bool
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True)
|
|
160
|
+
class HubNotFound:
|
|
161
|
+
hub: CustomHub
|
|
162
|
+
repo_id: str
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
FetchOutcome = FetchedRepo | HubGated | HubNotFound
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@dataclass(frozen=True)
|
|
169
|
+
class MmprojInfo:
|
|
170
|
+
path: str
|
|
171
|
+
size_bytes: int
|
|
172
|
+
sha256: str | None
|
|
173
|
+
recommended: bool
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass(frozen=True)
|
|
177
|
+
class GgufVariantGroup:
|
|
178
|
+
variant_id: str
|
|
179
|
+
label: str
|
|
180
|
+
quant: str
|
|
181
|
+
bits_per_weight: float | None
|
|
182
|
+
files: tuple[RepoFile, ...]
|
|
183
|
+
weights_bytes: int
|
|
184
|
+
mmproj_file: str | None
|
|
185
|
+
mmproj_bytes: int
|
|
186
|
+
stem: str
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@dataclass(frozen=True)
|
|
190
|
+
class TreeInspection:
|
|
191
|
+
format: CustomRepoFormat
|
|
192
|
+
compatible: bool
|
|
193
|
+
reason: CustomIncompatibleReason | None
|
|
194
|
+
suggested_search_query: str | None
|
|
195
|
+
mmproj_candidates: tuple[MmprojInfo, ...]
|
|
196
|
+
variants: tuple[GgufVariantGroup, ...]
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# --------------------------------------------------------------------------- hub search
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _classify_format_from_meta(
|
|
203
|
+
repo_id: str, tags: Sequence[str], library_name: str = ""
|
|
204
|
+
) -> CustomRepoFormat:
|
|
205
|
+
lower_tags = {t.lower() for t in tags}
|
|
206
|
+
lower_repo = repo_id.lower()
|
|
207
|
+
lower_lib = library_name.lower()
|
|
208
|
+
owner = lower_repo.split("/", 1)[0]
|
|
209
|
+
if "gguf" in lower_tags or "gguf" in lower_repo or lower_lib == "gguf":
|
|
210
|
+
return "gguf"
|
|
211
|
+
if (
|
|
212
|
+
"mlx" in lower_tags
|
|
213
|
+
or owner == "mlx-community"
|
|
214
|
+
or "-mlx" in lower_repo
|
|
215
|
+
or "_mlx" in lower_repo
|
|
216
|
+
or lower_lib == "mlx"
|
|
217
|
+
):
|
|
218
|
+
return "mlx"
|
|
219
|
+
if "safetensors" in lower_tags or "transformers" in lower_tags or lower_lib == "transformers":
|
|
220
|
+
return "safetensors"
|
|
221
|
+
return "unknown"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _incompat_for_format(fmt: CustomRepoFormat) -> CustomIncompatibleReason:
|
|
225
|
+
return (
|
|
226
|
+
"mlx_unsupported"
|
|
227
|
+
if fmt == "mlx"
|
|
228
|
+
else ("raw_safetensors" if fmt == "safetensors" else "no_runnable_files")
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _int_or_zero(value: object) -> int:
|
|
233
|
+
if isinstance(value, bool):
|
|
234
|
+
return 0
|
|
235
|
+
if isinstance(value, int):
|
|
236
|
+
return max(0, value)
|
|
237
|
+
try:
|
|
238
|
+
return max(0, int(float(value))) if isinstance(value, float | str) else 0
|
|
239
|
+
except ValueError:
|
|
240
|
+
return 0
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _license_from_hf(item: Mapping[str, object], tags: Sequence[str]) -> str | None:
|
|
244
|
+
card = item.get("cardData")
|
|
245
|
+
if isinstance(card, Mapping):
|
|
246
|
+
lic = card.get("license")
|
|
247
|
+
if isinstance(lic, list) and lic:
|
|
248
|
+
return str(lic[0])
|
|
249
|
+
if name := _str_or_none(lic):
|
|
250
|
+
return name
|
|
251
|
+
for tag in tags:
|
|
252
|
+
if tag.lower().startswith("license:") and (val := tag.split(":", 1)[1].strip()):
|
|
253
|
+
return val
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _search_result(
|
|
258
|
+
hub: CustomHub,
|
|
259
|
+
owner: str,
|
|
260
|
+
title: str,
|
|
261
|
+
tags: Sequence[str],
|
|
262
|
+
lib: str,
|
|
263
|
+
supported_formats: Sequence[str],
|
|
264
|
+
*,
|
|
265
|
+
arch: str | None = None,
|
|
266
|
+
param_b: float | None = None,
|
|
267
|
+
ctx: int | None = None,
|
|
268
|
+
downloads: int = 0,
|
|
269
|
+
likes: int = 0,
|
|
270
|
+
updated_at: str | None = None,
|
|
271
|
+
description: str | None = None,
|
|
272
|
+
license_name: str | None = None,
|
|
273
|
+
gated: bool = False,
|
|
274
|
+
) -> CustomSearchResult:
|
|
275
|
+
repo_id = f"{owner}/{title}"
|
|
276
|
+
fmt = _classify_format_from_meta(repo_id, tags, lib)
|
|
277
|
+
compatible = fmt in supported_formats
|
|
278
|
+
return {
|
|
279
|
+
"hub": hub,
|
|
280
|
+
"repo_id": repo_id,
|
|
281
|
+
"url": repo_web_url(hub, repo_id),
|
|
282
|
+
"title": title,
|
|
283
|
+
"owner": owner,
|
|
284
|
+
"format": fmt,
|
|
285
|
+
"family": infer_family(repo_id, tags, arch),
|
|
286
|
+
"architecture": arch,
|
|
287
|
+
"parameter_billions": param_b if param_b is not None else infer_parameter_billions(repo_id),
|
|
288
|
+
"context_tokens": ctx,
|
|
289
|
+
"downloads": downloads,
|
|
290
|
+
"likes": likes,
|
|
291
|
+
"updated_at": updated_at,
|
|
292
|
+
"description": description,
|
|
293
|
+
"license": license_name,
|
|
294
|
+
"gated": gated,
|
|
295
|
+
"compatible": compatible,
|
|
296
|
+
"incompatibility_code": None if compatible else _incompat_for_format(fmt),
|
|
297
|
+
"quant_count": None,
|
|
298
|
+
"default_quant": None,
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _decode_hf_search_item(
|
|
303
|
+
item: object, supported_formats: Sequence[str]
|
|
304
|
+
) -> CustomSearchResult | None:
|
|
305
|
+
if not isinstance(item, Mapping):
|
|
306
|
+
return None
|
|
307
|
+
repo_id = str(item.get("id") or item.get("modelId") or "").strip()
|
|
308
|
+
if "/" not in repo_id:
|
|
309
|
+
return None
|
|
310
|
+
owner, title = repo_id.split("/", 1)
|
|
311
|
+
raw_tags = item.get("tags")
|
|
312
|
+
tags = [str(t) for t in raw_tags] if isinstance(raw_tags, list) else []
|
|
313
|
+
raw_gguf = item.get("gguf")
|
|
314
|
+
gguf_obj: Mapping[str, object] = raw_gguf if isinstance(raw_gguf, Mapping) else {}
|
|
315
|
+
total_params = _int_or_zero(gguf_obj.get("total"))
|
|
316
|
+
return _search_result(
|
|
317
|
+
"huggingface",
|
|
318
|
+
owner,
|
|
319
|
+
title,
|
|
320
|
+
tags,
|
|
321
|
+
str(item.get("library_name") or ""),
|
|
322
|
+
supported_formats,
|
|
323
|
+
arch=_str_or_none(gguf_obj.get("architecture")),
|
|
324
|
+
param_b=round(total_params / 1e9, 1) if total_params >= 100_000_000 else None,
|
|
325
|
+
ctx=_int_or_zero(gguf_obj.get("context_length")) or None,
|
|
326
|
+
downloads=_int_or_zero(item.get("downloads")),
|
|
327
|
+
likes=_int_or_zero(item.get("likes")),
|
|
328
|
+
updated_at=_str_or_none(item.get("lastModified") or item.get("createdAt")),
|
|
329
|
+
license_name=_license_from_hf(item, tags),
|
|
330
|
+
gated=bool(item.get("gated")),
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _str_or_none(value: object) -> str | None:
|
|
335
|
+
return value.strip() or None if isinstance(value, str) else None
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _warn(hub: CustomHub, code: str, detail: str) -> CustomSearchWarning:
|
|
339
|
+
return {"hub": hub, "code": code, "detail": detail}
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _http_err_outcome(
|
|
343
|
+
hub: CustomHub, repo_id: str, web_url: str, exc: urllib.error.HTTPError, token_provided: bool
|
|
344
|
+
) -> HubGated | HubNotFound | None:
|
|
345
|
+
if exc.code in (401, 403):
|
|
346
|
+
return HubGated(hub, repo_id, web_url, 401 if exc.code == 401 else 403, token_provided)
|
|
347
|
+
return HubNotFound(hub, repo_id) if exc.code == 404 else None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _hf_search_url(endpoint: str, query: str, format_filter: CustomFormatFilter, limit: int) -> str:
|
|
351
|
+
params: list[tuple[str, str]] = [
|
|
352
|
+
("sort", "downloads"),
|
|
353
|
+
("direction", "-1"),
|
|
354
|
+
("limit", str(limit)),
|
|
355
|
+
]
|
|
356
|
+
clean_q = query.strip()
|
|
357
|
+
if clean_q:
|
|
358
|
+
params.append(("search", clean_q))
|
|
359
|
+
if format_filter in ("compatible", "gguf") or (not clean_q and format_filter == "all"):
|
|
360
|
+
params.append(("filter", "gguf"))
|
|
361
|
+
elif format_filter == "mlx":
|
|
362
|
+
params.append(("filter", "mlx"))
|
|
363
|
+
return f"{endpoint.rstrip('/')}/api/models?{urllib.parse.urlencode(params)}"
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _hf_err_note(
|
|
367
|
+
hub: CustomHub, code: str, detail: str
|
|
368
|
+
) -> tuple[list[CustomSearchResult], list[CustomSearchWarning], bool]:
|
|
369
|
+
return [], [_warn(hub, code, detail)], code != "HUB_UNREACHABLE"
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def search_huggingface(
|
|
373
|
+
query: str,
|
|
374
|
+
format_filter: CustomFormatFilter,
|
|
375
|
+
limit: int,
|
|
376
|
+
token: str | None,
|
|
377
|
+
supported_formats: Sequence[str],
|
|
378
|
+
*,
|
|
379
|
+
timeout: float = SEARCH_TIMEOUT_S,
|
|
380
|
+
hub_explicit: bool = True,
|
|
381
|
+
) -> tuple[list[CustomSearchResult], list[CustomSearchWarning], bool]:
|
|
382
|
+
"""Return ``(results, warnings, reached_hub)`` from Hugging Face / hf-mirror."""
|
|
383
|
+
resolved_token = resolve_token("huggingface", token, hub_explicit=hub_explicit)
|
|
384
|
+
warnings: list[CustomSearchWarning] = []
|
|
385
|
+
last_err = ""
|
|
386
|
+
for idx, endpoint in enumerate(hf_endpoints()):
|
|
387
|
+
url = _hf_search_url(endpoint, query, format_filter, limit)
|
|
388
|
+
ep_token = token_for_endpoint("huggingface", url, resolved_token)
|
|
389
|
+
try:
|
|
390
|
+
payload = http_json(url, token=ep_token, timeout=timeout)
|
|
391
|
+
except urllib.error.HTTPError as exc:
|
|
392
|
+
if exc.code == 429:
|
|
393
|
+
msg = redact_secrets(
|
|
394
|
+
f"Hugging Face rate limited (HTTP 429): {exc}", extra_token=resolved_token
|
|
395
|
+
)
|
|
396
|
+
return _hf_err_note("huggingface", "RATE_LIMITED", msg)
|
|
397
|
+
last_err = redact_secrets(f"HTTP {exc.code}: {exc.reason}", extra_token=resolved_token)
|
|
398
|
+
continue
|
|
399
|
+
except (OSError, http.client.HTTPException, ValueError) as exc:
|
|
400
|
+
last_err = redact_secrets(str(exc), extra_token=resolved_token)
|
|
401
|
+
continue
|
|
402
|
+
if not isinstance(payload, list):
|
|
403
|
+
return _hf_err_note(
|
|
404
|
+
"huggingface", "HUB_SCHEMA_DRIFT", "unexpected Hugging Face search response shape"
|
|
405
|
+
)
|
|
406
|
+
if idx > 0:
|
|
407
|
+
host = urllib.parse.urlsplit(endpoint).netloc
|
|
408
|
+
warnings.append(_warn("huggingface", "HUB_FALLBACK", f"fell back to {host}"))
|
|
409
|
+
rows = [
|
|
410
|
+
r
|
|
411
|
+
for item in payload
|
|
412
|
+
if (r := _decode_hf_search_item(item, supported_formats)) is not None
|
|
413
|
+
]
|
|
414
|
+
return rows, warnings, True
|
|
415
|
+
return _hf_err_note("huggingface", "HUB_UNREACHABLE", last_err or "Hugging Face search failed")
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _extract_ms_models(payload: object) -> list[object] | None:
|
|
419
|
+
"""Defensively locate the list of model items across ModelScope API schema variants."""
|
|
420
|
+
if isinstance(payload, list):
|
|
421
|
+
return payload
|
|
422
|
+
if not isinstance(payload, Mapping):
|
|
423
|
+
return None
|
|
424
|
+
data = payload.get("Data")
|
|
425
|
+
if isinstance(data, list):
|
|
426
|
+
return data
|
|
427
|
+
if isinstance(data, Mapping):
|
|
428
|
+
model_node = data.get("Model")
|
|
429
|
+
if isinstance(model_node, Mapping) and isinstance(model_node.get("Models"), list):
|
|
430
|
+
return cast(list[object], model_node["Models"])
|
|
431
|
+
for key in ("Models", "Items", "List"):
|
|
432
|
+
if isinstance(data.get(key), list):
|
|
433
|
+
return cast(list[object], data[key])
|
|
434
|
+
for key in ("Models", "models", "items"):
|
|
435
|
+
if isinstance(payload.get(key), list):
|
|
436
|
+
return cast(list[object], payload[key])
|
|
437
|
+
return None
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _ms_tags(item: Mapping[str, object]) -> list[str]:
|
|
441
|
+
tags: list[str] = []
|
|
442
|
+
for key in ("Tags", "Frameworks", "Libraries", "Tasks"):
|
|
443
|
+
raw = item.get(key)
|
|
444
|
+
for entry in raw if isinstance(raw, list) else ():
|
|
445
|
+
if isinstance(entry, str):
|
|
446
|
+
tags.append(entry)
|
|
447
|
+
elif isinstance(entry, Mapping) and (
|
|
448
|
+
name := _str_or_none(entry.get("Name") or entry.get("ChineseName"))
|
|
449
|
+
):
|
|
450
|
+
tags.append(name)
|
|
451
|
+
return tags
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _decode_ms_search_item(
|
|
455
|
+
item: object, supported_formats: Sequence[str]
|
|
456
|
+
) -> CustomSearchResult | None:
|
|
457
|
+
if not isinstance(item, Mapping):
|
|
458
|
+
return None
|
|
459
|
+
path_val = str(item.get("Path") or item.get("Namespace") or "").strip()
|
|
460
|
+
name_val = str(item.get("Name") or item.get("ModelName") or "").strip()
|
|
461
|
+
if not path_val and "/" in name_val:
|
|
462
|
+
path_val, name_val = name_val.split("/", 1)
|
|
463
|
+
if not path_val or not name_val:
|
|
464
|
+
return None
|
|
465
|
+
return _search_result(
|
|
466
|
+
"modelscope",
|
|
467
|
+
path_val,
|
|
468
|
+
name_val,
|
|
469
|
+
_ms_tags(item),
|
|
470
|
+
str(item.get("LibraryName") or ""),
|
|
471
|
+
supported_formats,
|
|
472
|
+
downloads=_int_or_zero(item.get("Downloads") or item.get("DownloadCount")),
|
|
473
|
+
likes=_int_or_zero(item.get("Stars") or item.get("Likes")),
|
|
474
|
+
updated_at=_str_or_none(item.get("LastUpdatedTime") or item.get("GmtModified")),
|
|
475
|
+
description=_str_or_none(item.get("Description") or item.get("ChineseName")),
|
|
476
|
+
license_name=_str_or_none(item.get("License")),
|
|
477
|
+
gated=bool(item.get("IsGated") or item.get("Gated")),
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def search_modelscope(
|
|
482
|
+
query: str,
|
|
483
|
+
format_filter: CustomFormatFilter,
|
|
484
|
+
limit: int,
|
|
485
|
+
token: str | None,
|
|
486
|
+
supported_formats: Sequence[str],
|
|
487
|
+
*,
|
|
488
|
+
timeout: float = SEARCH_TIMEOUT_S,
|
|
489
|
+
hub_explicit: bool = True,
|
|
490
|
+
) -> tuple[list[CustomSearchResult], list[CustomSearchWarning], bool]:
|
|
491
|
+
"""Return ``(results, warnings, reached_hub)`` from ModelScope with defensive decoding."""
|
|
492
|
+
resolved_token = resolve_token("modelscope", token, hub_explicit=hub_explicit)
|
|
493
|
+
clean_q = query.strip()
|
|
494
|
+
if not clean_q:
|
|
495
|
+
search_term = "MLX" if format_filter == "mlx" else "GGUF"
|
|
496
|
+
elif format_filter in ("compatible", "gguf") and "gguf" not in clean_q.lower():
|
|
497
|
+
search_term = f"{clean_q} GGUF"
|
|
498
|
+
elif format_filter == "mlx" and "mlx" not in clean_q.lower():
|
|
499
|
+
search_term = f"{clean_q} MLX"
|
|
500
|
+
else:
|
|
501
|
+
search_term = clean_q
|
|
502
|
+
url = f"{MODELSCOPE_API}/api/v1/dolphin/models"
|
|
503
|
+
ep_token = token_for_endpoint("modelscope", url, resolved_token)
|
|
504
|
+
body: dict[str, object] = {
|
|
505
|
+
"PageSize": limit,
|
|
506
|
+
"PageNumber": 1,
|
|
507
|
+
"SortBy": "Downloads",
|
|
508
|
+
"Target": "",
|
|
509
|
+
"SingleCriterion": [],
|
|
510
|
+
"Name": search_term,
|
|
511
|
+
}
|
|
512
|
+
try:
|
|
513
|
+
payload = http_json(url, method="PUT", body=body, token=ep_token, timeout=timeout)
|
|
514
|
+
except urllib.error.HTTPError as exc:
|
|
515
|
+
code = "RATE_LIMITED" if exc.code == 429 else "HUB_UNREACHABLE"
|
|
516
|
+
detail = redact_secrets(
|
|
517
|
+
f"ModelScope HTTP {exc.code}: {exc.reason}", extra_token=resolved_token
|
|
518
|
+
)
|
|
519
|
+
return [], [_warn("modelscope", code, detail)], exc.code == 429
|
|
520
|
+
except (OSError, http.client.HTTPException, ValueError) as exc:
|
|
521
|
+
detail = redact_secrets(str(exc), extra_token=resolved_token)
|
|
522
|
+
return [], [_warn("modelscope", "HUB_UNREACHABLE", detail)], False
|
|
523
|
+
|
|
524
|
+
items = _extract_ms_models(payload)
|
|
525
|
+
if items is None:
|
|
526
|
+
return (
|
|
527
|
+
[],
|
|
528
|
+
[
|
|
529
|
+
_warn(
|
|
530
|
+
"modelscope", "HUB_SCHEMA_DRIFT", "unexpected ModelScope search response shape"
|
|
531
|
+
)
|
|
532
|
+
],
|
|
533
|
+
True,
|
|
534
|
+
)
|
|
535
|
+
rows = [
|
|
536
|
+
r for item in items if (r := _decode_ms_search_item(item, supported_formats)) is not None
|
|
537
|
+
]
|
|
538
|
+
return rows, [], True
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _matches_format_filter(row: CustomSearchResult, format_filter: CustomFormatFilter) -> bool:
|
|
542
|
+
return (
|
|
543
|
+
True
|
|
544
|
+
if format_filter == "all"
|
|
545
|
+
else (
|
|
546
|
+
row["compatible"] if format_filter == "compatible" else row["format"] == format_filter
|
|
547
|
+
)
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def search_hubs(
|
|
552
|
+
*,
|
|
553
|
+
hub: CustomSearchHub,
|
|
554
|
+
query: str,
|
|
555
|
+
format_filter: CustomFormatFilter,
|
|
556
|
+
limit: int,
|
|
557
|
+
token: str | None = None,
|
|
558
|
+
supported_formats: Sequence[str] = SUPPORTED_FORMATS,
|
|
559
|
+
timeout: float = SEARCH_TIMEOUT_S,
|
|
560
|
+
) -> tuple[list[CustomSearchResult], list[CustomSearchWarning]]:
|
|
561
|
+
"""Search one or both hubs concurrently with per-hub timeout and partial-success warnings."""
|
|
562
|
+
fetch_limit = max(1, min(limit, 50))
|
|
563
|
+
targets: tuple[CustomHub, ...] = (
|
|
564
|
+
("huggingface", "modelscope") if hub == "all" else (cast(CustomHub, hub),)
|
|
565
|
+
)
|
|
566
|
+
hub_explicit = hub != "all"
|
|
567
|
+
results: list[CustomSearchResult] = []
|
|
568
|
+
warnings: list[CustomSearchWarning] = []
|
|
569
|
+
reached_any = False
|
|
570
|
+
|
|
571
|
+
def _run(
|
|
572
|
+
target_hub: CustomHub,
|
|
573
|
+
) -> tuple[list[CustomSearchResult], list[CustomSearchWarning], bool]:
|
|
574
|
+
fn = search_huggingface if target_hub == "huggingface" else search_modelscope
|
|
575
|
+
return fn(
|
|
576
|
+
query,
|
|
577
|
+
format_filter,
|
|
578
|
+
fetch_limit,
|
|
579
|
+
token,
|
|
580
|
+
supported_formats,
|
|
581
|
+
timeout=timeout,
|
|
582
|
+
hub_explicit=hub_explicit,
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
if len(targets) == 1:
|
|
586
|
+
rows, warns, reached_any = _run(targets[0])
|
|
587
|
+
results.extend(rows)
|
|
588
|
+
warnings.extend(warns)
|
|
589
|
+
else:
|
|
590
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
|
591
|
+
futures = {pool.submit(_run, target_hub): target_hub for target_hub in targets}
|
|
592
|
+
for future, target_hub in futures.items():
|
|
593
|
+
try:
|
|
594
|
+
rows, warns, ok = future.result(timeout=timeout + 1.0)
|
|
595
|
+
results.extend(rows)
|
|
596
|
+
warnings.extend(warns)
|
|
597
|
+
reached_any = reached_any or ok
|
|
598
|
+
except concurrent.futures.TimeoutError:
|
|
599
|
+
warnings.append(
|
|
600
|
+
_warn(
|
|
601
|
+
target_hub,
|
|
602
|
+
"HUB_TIMEOUT",
|
|
603
|
+
f"{target_hub} search timed out after {timeout:.0f}s",
|
|
604
|
+
)
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
if not reached_any:
|
|
608
|
+
detail = "; ".join(w["detail"] for w in warnings) or "all requested hubs are unreachable"
|
|
609
|
+
raise LibraryError("HUB_UNREACHABLE", redact_secrets(detail, extra_token=token))
|
|
610
|
+
|
|
611
|
+
filtered = [row for row in results if _matches_format_filter(row, format_filter)]
|
|
612
|
+
filtered.sort(key=lambda r: (-r["downloads"], -r["likes"], r["repo_id"].lower(), r["hub"]))
|
|
613
|
+
return filtered[:fetch_limit], warnings
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
# --------------------------------------------------------------------------- recursive tree fetch
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def _hf_tree_files(endpoint: str, repo_id: str, commit: str, raw_tree: object) -> list[RepoFile]:
|
|
620
|
+
if not isinstance(raw_tree, list):
|
|
621
|
+
raise ValueError("Hugging Face tree response must be an array")
|
|
622
|
+
files: list[RepoFile] = []
|
|
623
|
+
base = endpoint.rstrip("/")
|
|
624
|
+
q_commit = urllib.parse.quote(commit, safe="")
|
|
625
|
+
for entry in raw_tree:
|
|
626
|
+
if not isinstance(entry, Mapping) or entry.get("type", "file") != "file":
|
|
627
|
+
continue
|
|
628
|
+
path = str(entry.get("path") or "").strip()
|
|
629
|
+
if not path:
|
|
630
|
+
continue
|
|
631
|
+
lfs = entry.get("lfs")
|
|
632
|
+
if isinstance(lfs, Mapping):
|
|
633
|
+
size_bytes = _int_or_zero(lfs.get("size") or entry.get("size"))
|
|
634
|
+
sha256 = _str_or_none(lfs.get("oid"))
|
|
635
|
+
else:
|
|
636
|
+
size_bytes, sha256 = _int_or_zero(entry.get("size")), None
|
|
637
|
+
dl_url = f"{base}/{repo_id}/resolve/{q_commit}/{urllib.parse.quote(path, safe='/')}"
|
|
638
|
+
files.append(RepoFile(path, size_bytes, sha256, commit, dl_url))
|
|
639
|
+
return files
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def fetch_hf_repo(
|
|
643
|
+
repo_id: str,
|
|
644
|
+
*,
|
|
645
|
+
revision: str | None = None,
|
|
646
|
+
token: str | None = None,
|
|
647
|
+
explicit_endpoint: str | None = None,
|
|
648
|
+
timeout: float = TREE_TIMEOUT_S,
|
|
649
|
+
hub_explicit: bool = True,
|
|
650
|
+
) -> FetchOutcome:
|
|
651
|
+
"""Fetch Hugging Face model metadata and recursive file tree."""
|
|
652
|
+
resolved_token = resolve_token("huggingface", token, hub_explicit=hub_explicit)
|
|
653
|
+
web_url = repo_web_url("huggingface", repo_id)
|
|
654
|
+
last_err = ""
|
|
655
|
+
for endpoint in hf_endpoints(explicit_endpoint):
|
|
656
|
+
base = endpoint.rstrip("/")
|
|
657
|
+
meta_url = f"{base}/api/models/{repo_id}" + (
|
|
658
|
+
f"/revision/{urllib.parse.quote(revision, safe='')}" if revision else ""
|
|
659
|
+
)
|
|
660
|
+
ep_token = token_for_endpoint("huggingface", meta_url, resolved_token)
|
|
661
|
+
try:
|
|
662
|
+
meta = http_json(meta_url, token=ep_token, timeout=timeout)
|
|
663
|
+
if not isinstance(meta, Mapping):
|
|
664
|
+
last_err = "invalid Hugging Face model metadata response"
|
|
665
|
+
continue
|
|
666
|
+
commit = str(meta.get("sha") or revision or "main").strip()
|
|
667
|
+
tree_url = f"{base}/api/models/{repo_id}/tree/{urllib.parse.quote(commit, safe='')}?recursive=true"
|
|
668
|
+
files = _hf_tree_files(
|
|
669
|
+
base, repo_id, commit, http_json(tree_url, token=ep_token, timeout=timeout)
|
|
670
|
+
)
|
|
671
|
+
except urllib.error.HTTPError as exc:
|
|
672
|
+
if outcome := _http_err_outcome("huggingface", repo_id, web_url, exc, bool(ep_token)):
|
|
673
|
+
return outcome
|
|
674
|
+
last_err = redact_secrets(f"HTTP {exc.code}: {exc.reason}", extra_token=resolved_token)
|
|
675
|
+
continue
|
|
676
|
+
except (OSError, http.client.HTTPException, ValueError) as exc:
|
|
677
|
+
last_err = redact_secrets(str(exc), extra_token=resolved_token)
|
|
678
|
+
continue
|
|
679
|
+
owner, title = repo_id.split("/", 1)
|
|
680
|
+
raw_tags = meta.get("tags")
|
|
681
|
+
tags = tuple(str(t) for t in raw_tags) if isinstance(raw_tags, list) else ()
|
|
682
|
+
return FetchedRepo(
|
|
683
|
+
"huggingface",
|
|
684
|
+
repo_id,
|
|
685
|
+
commit,
|
|
686
|
+
web_url,
|
|
687
|
+
title,
|
|
688
|
+
owner,
|
|
689
|
+
_license_from_hf(meta, tags),
|
|
690
|
+
bool(meta.get("gated")),
|
|
691
|
+
tags,
|
|
692
|
+
tuple(files),
|
|
693
|
+
base,
|
|
694
|
+
)
|
|
695
|
+
detail = f"cannot reach Hugging Face for {repo_id}: {last_err or 'network error'}"
|
|
696
|
+
raise LibraryError("HUB_UNREACHABLE", redact_secrets(detail, extra_token=resolved_token))
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _ms_code_outcome(
|
|
700
|
+
doc: Mapping[str, object], repo_id: str, web_url: str, token_provided: bool
|
|
701
|
+
) -> HubGated | HubNotFound | None:
|
|
702
|
+
code = doc.get("Code")
|
|
703
|
+
if code == 200:
|
|
704
|
+
return None
|
|
705
|
+
msg = str(doc.get("Message") or "").lower()
|
|
706
|
+
if code in (401, 403, 10010203001) or any(
|
|
707
|
+
w in msg for w in ("permission", "unauthorized", "gated")
|
|
708
|
+
):
|
|
709
|
+
return HubGated(
|
|
710
|
+
"modelscope",
|
|
711
|
+
repo_id,
|
|
712
|
+
web_url,
|
|
713
|
+
403 if (code == 403 or token_provided) else 401,
|
|
714
|
+
token_provided,
|
|
715
|
+
)
|
|
716
|
+
if code in (404, 10010101001) or "not exist" in msg or "not found" in msg:
|
|
717
|
+
return HubNotFound("modelscope", repo_id)
|
|
718
|
+
return None
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _ms_tree_files(repo_id: str, default_rev: str, raw_files: Sequence[object]) -> list[RepoFile]:
|
|
722
|
+
files: list[RepoFile] = []
|
|
723
|
+
for entry in raw_files:
|
|
724
|
+
if not isinstance(entry, Mapping) or str(entry.get("Type") or "blob").lower() != "blob":
|
|
725
|
+
continue
|
|
726
|
+
path = str(entry.get("Path") or "").strip()
|
|
727
|
+
if not path:
|
|
728
|
+
continue
|
|
729
|
+
file_rev = str(entry.get("Revision") or default_rev).strip() or default_rev
|
|
730
|
+
sha256 = _str_or_none(entry.get("Sha256"))
|
|
731
|
+
dl_url = f"{MODELSCOPE_API}/models/{repo_id}/resolve/{urllib.parse.quote(file_rev, safe='')}/{urllib.parse.quote(path, safe='/')}"
|
|
732
|
+
files.append(RepoFile(path, _int_or_zero(entry.get("Size")), sha256, file_rev, dl_url))
|
|
733
|
+
return files
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def fetch_ms_repo(
|
|
737
|
+
repo_id: str,
|
|
738
|
+
*,
|
|
739
|
+
revision: str | None = None,
|
|
740
|
+
token: str | None = None,
|
|
741
|
+
timeout: float = TREE_TIMEOUT_S,
|
|
742
|
+
hub_explicit: bool = True,
|
|
743
|
+
) -> FetchOutcome:
|
|
744
|
+
"""Fetch ModelScope model metadata and recursive file tree (default revision ``master``)."""
|
|
745
|
+
resolved_token = resolve_token("modelscope", token, hub_explicit=hub_explicit)
|
|
746
|
+
rev = (revision or "").strip() or "master"
|
|
747
|
+
web_url = repo_web_url("modelscope", repo_id)
|
|
748
|
+
tree_url = f"{MODELSCOPE_API}/api/v1/models/{repo_id}/repo/files?Revision={urllib.parse.quote(rev, safe='')}&Recursive=true"
|
|
749
|
+
ep_token = token_for_endpoint("modelscope", tree_url, resolved_token)
|
|
750
|
+
try:
|
|
751
|
+
doc = http_json(tree_url, token=ep_token, timeout=timeout)
|
|
752
|
+
except urllib.error.HTTPError as exc:
|
|
753
|
+
if outcome := _http_err_outcome("modelscope", repo_id, web_url, exc, bool(ep_token)):
|
|
754
|
+
return outcome
|
|
755
|
+
msg = f"ModelScope HTTP {exc.code} reading {repo_id}: {exc.reason}"
|
|
756
|
+
raise LibraryError(
|
|
757
|
+
"HUB_UNREACHABLE", redact_secrets(msg, extra_token=resolved_token)
|
|
758
|
+
) from None
|
|
759
|
+
except (OSError, http.client.HTTPException, ValueError) as exc:
|
|
760
|
+
msg = f"cannot reach ModelScope for {repo_id}: {exc}"
|
|
761
|
+
raise LibraryError(
|
|
762
|
+
"HUB_UNREACHABLE", redact_secrets(msg, extra_token=resolved_token)
|
|
763
|
+
) from None
|
|
764
|
+
if not isinstance(doc, Mapping):
|
|
765
|
+
raise LibraryError("HUB_UNREACHABLE", "unexpected ModelScope tree response shape")
|
|
766
|
+
if outcome := _ms_code_outcome(doc, repo_id, web_url, bool(ep_token)):
|
|
767
|
+
return outcome
|
|
768
|
+
data = doc.get("Data")
|
|
769
|
+
raw_files = data.get("Files") if isinstance(data, Mapping) else None
|
|
770
|
+
if not isinstance(raw_files, list):
|
|
771
|
+
raise LibraryError("HUB_UNREACHABLE", "ModelScope tree response missing Data.Files")
|
|
772
|
+
files = _ms_tree_files(repo_id, rev, raw_files)
|
|
773
|
+
owner, title = repo_id.split("/", 1)
|
|
774
|
+
return FetchedRepo(
|
|
775
|
+
"modelscope",
|
|
776
|
+
repo_id,
|
|
777
|
+
files[0].revision if files else rev,
|
|
778
|
+
web_url,
|
|
779
|
+
title,
|
|
780
|
+
owner,
|
|
781
|
+
None,
|
|
782
|
+
False,
|
|
783
|
+
(),
|
|
784
|
+
tuple(files),
|
|
785
|
+
MODELSCOPE_API,
|
|
786
|
+
)
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def fetch_repo(
|
|
790
|
+
spec: ParsedRepoSpec, *, token: str | None = None, timeout: float = TREE_TIMEOUT_S
|
|
791
|
+
) -> FetchOutcome:
|
|
792
|
+
"""Resolve and fetch a parsed repository spec across explicit or auto-selected hubs."""
|
|
793
|
+
hub_explicit = spec.hub is not None
|
|
794
|
+
|
|
795
|
+
def _fetch(hub_name: CustomHub) -> FetchOutcome:
|
|
796
|
+
if hub_name == "huggingface":
|
|
797
|
+
return fetch_hf_repo(
|
|
798
|
+
spec.repo_id,
|
|
799
|
+
revision=spec.revision,
|
|
800
|
+
token=token,
|
|
801
|
+
explicit_endpoint=spec.explicit_endpoint,
|
|
802
|
+
timeout=timeout,
|
|
803
|
+
hub_explicit=hub_explicit,
|
|
804
|
+
)
|
|
805
|
+
return fetch_ms_repo(
|
|
806
|
+
spec.repo_id,
|
|
807
|
+
revision=spec.revision,
|
|
808
|
+
token=token,
|
|
809
|
+
timeout=timeout,
|
|
810
|
+
hub_explicit=hub_explicit,
|
|
811
|
+
)
|
|
812
|
+
|
|
813
|
+
if spec.hub is not None:
|
|
814
|
+
return _fetch(spec.hub)
|
|
815
|
+
first_error: LibraryError | None = None
|
|
816
|
+
last_not_found: HubNotFound | None = None
|
|
817
|
+
for hub_name in ("huggingface", "modelscope"):
|
|
818
|
+
try:
|
|
819
|
+
outcome = _fetch(cast(CustomHub, hub_name))
|
|
820
|
+
except LibraryError as exc:
|
|
821
|
+
first_error = first_error or exc
|
|
822
|
+
continue
|
|
823
|
+
if isinstance(outcome, HubNotFound):
|
|
824
|
+
last_not_found = outcome
|
|
825
|
+
continue
|
|
826
|
+
return outcome
|
|
827
|
+
if last_not_found is not None:
|
|
828
|
+
return last_not_found
|
|
829
|
+
if first_error is not None:
|
|
830
|
+
raise first_error
|
|
831
|
+
return HubNotFound("huggingface", spec.repo_id)
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
# --------------------------------------------------------------------------- format & shard inspection
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def _is_mmproj(path: str) -> bool:
|
|
838
|
+
name = path.rsplit("/", 1)[-1].lower()
|
|
839
|
+
return name.startswith("mmproj") or "-mmproj" in name or "_mmproj" in name
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def _rank_mmproj(gguf_files: Sequence[RepoFile]) -> tuple[MmprojInfo, ...]:
|
|
843
|
+
def key(f: RepoFile) -> tuple[int, str]:
|
|
844
|
+
name = f.path.rsplit("/", 1)[-1].lower()
|
|
845
|
+
return next(
|
|
846
|
+
((i, f.path) for i, m in enumerate(("bf16", "f16", "f32", "q8_0")) if m in name),
|
|
847
|
+
(4, f.path),
|
|
848
|
+
)
|
|
849
|
+
|
|
850
|
+
found = sorted((f for f in gguf_files if _is_mmproj(f.path)), key=key)
|
|
851
|
+
return tuple(
|
|
852
|
+
MmprojInfo(f.path, f.size_bytes, f.sha256, idx == 0) for idx, f in enumerate(found)
|
|
853
|
+
)
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _pick_mmproj_for_dir(parent_dir: str, candidates: Sequence[MmprojInfo]) -> MmprojInfo | None:
|
|
857
|
+
if not candidates:
|
|
858
|
+
return None
|
|
859
|
+
for c in candidates:
|
|
860
|
+
if (c.path.rsplit("/", 1)[0] if "/" in c.path else "") == parent_dir:
|
|
861
|
+
return c
|
|
862
|
+
return candidates[0]
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def _group_gguf_variants(
|
|
866
|
+
gguf_files: Sequence[RepoFile], mmproj_candidates: Sequence[MmprojInfo]
|
|
867
|
+
) -> tuple[GgufVariantGroup, ...]:
|
|
868
|
+
"""Group directory-scoped GGUFs, validate contiguous 1..N shard completeness, and pair mmproj."""
|
|
869
|
+
buckets: dict[tuple[str, str, int], list[tuple[int, RepoFile]]] = {}
|
|
870
|
+
for f in gguf_files:
|
|
871
|
+
if _is_mmproj(f.path):
|
|
872
|
+
continue
|
|
873
|
+
parent_dir, _, filename = f.path.rpartition("/")
|
|
874
|
+
if match := SPLIT_PART_RE.search(filename):
|
|
875
|
+
key = (parent_dir, filename[: match.start()], int(match.group(2)))
|
|
876
|
+
buckets.setdefault(key, []).append((int(match.group(1)), f))
|
|
877
|
+
else:
|
|
878
|
+
buckets.setdefault((parent_dir, filename[:-5], 1), []).append((1, f))
|
|
879
|
+
|
|
880
|
+
used_ids: set[str] = set()
|
|
881
|
+
variants: list[GgufVariantGroup] = []
|
|
882
|
+
for (parent_dir, base_stem, expected_total), entries in sorted(buckets.items()):
|
|
883
|
+
if expected_total < 1 or len(entries) != expected_total:
|
|
884
|
+
continue
|
|
885
|
+
entries.sort(key=lambda pair: (pair[0], pair[1].path))
|
|
886
|
+
if [pair[0] for pair in entries] != list(range(1, expected_total + 1)):
|
|
887
|
+
continue
|
|
888
|
+
ordered = tuple(pair[1] for pair in entries)
|
|
889
|
+
quant = catalog_add.quant_from_path(ordered[0].path) or _variant_slug(base_stem)
|
|
890
|
+
vid = quant
|
|
891
|
+
if vid.lower() in used_ids:
|
|
892
|
+
vid = f"{quant}-{_variant_slug(parent_dir or base_stem)}"
|
|
893
|
+
counter = 2
|
|
894
|
+
while vid.lower() in used_ids:
|
|
895
|
+
vid, counter = f"{quant}-{counter}", counter + 1
|
|
896
|
+
used_ids.add(vid.lower())
|
|
897
|
+
qf = quant_formats.lookup(quant)
|
|
898
|
+
mmproj = _pick_mmproj_for_dir(parent_dir, mmproj_candidates)
|
|
899
|
+
variants.append(
|
|
900
|
+
GgufVariantGroup(
|
|
901
|
+
vid,
|
|
902
|
+
vid,
|
|
903
|
+
quant,
|
|
904
|
+
qf.bits if qf is not None else None,
|
|
905
|
+
ordered,
|
|
906
|
+
sum(f.size_bytes for f in ordered),
|
|
907
|
+
mmproj.path if mmproj is not None else None,
|
|
908
|
+
mmproj.size_bytes if mmproj is not None else 0,
|
|
909
|
+
base_stem,
|
|
910
|
+
)
|
|
911
|
+
)
|
|
912
|
+
variants.sort(key=lambda v: (v.weights_bytes, v.variant_id.lower()))
|
|
913
|
+
return tuple(variants)
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
def inspect_tree(repo: FetchedRepo) -> TreeInspection:
|
|
917
|
+
"""Classify repo format, group valid GGUF variants, or produce incompatible guidance."""
|
|
918
|
+
gguf_files = [f for f in repo.files if f.path.lower().endswith(".gguf") and f.size_bytes > 0]
|
|
919
|
+
mmproj = _rank_mmproj(gguf_files)
|
|
920
|
+
variants = _group_gguf_variants(gguf_files, mmproj)
|
|
921
|
+
if variants:
|
|
922
|
+
return TreeInspection("gguf", True, None, None, mmproj, variants)
|
|
923
|
+
lower_paths = [f.path.lower() for f in repo.files]
|
|
924
|
+
has_weights = any(
|
|
925
|
+
p.endswith(".safetensors")
|
|
926
|
+
or (
|
|
927
|
+
p.endswith((".bin", ".pt", ".pth"))
|
|
928
|
+
and any(k in p for k in ("pytorch_model", "consolidated", "model"))
|
|
929
|
+
)
|
|
930
|
+
for p in lower_paths
|
|
931
|
+
)
|
|
932
|
+
query = build_suggested_gguf_query(repo.repo_id)
|
|
933
|
+
if _classify_format_from_meta(repo.repo_id, repo.tags) == "mlx":
|
|
934
|
+
return TreeInspection("mlx", False, "mlx_unsupported", query, (), ())
|
|
935
|
+
if has_weights:
|
|
936
|
+
return TreeInspection("safetensors", False, "raw_safetensors", query, (), ())
|
|
937
|
+
return TreeInspection("unknown", False, "no_runnable_files", query, (), ())
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
def _is_truncated_gguf_error(exc: BaseException) -> bool:
|
|
941
|
+
if isinstance(exc, EOFError):
|
|
942
|
+
return True
|
|
943
|
+
return isinstance(exc, ValueError) and "truncated" in str(exc).lower()
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def read_remote_gguf_header(
|
|
947
|
+
url: str, *, token: str | None = None, timeout: float = RANGE_TIMEOUT_S
|
|
948
|
+
) -> tuple[GGUFHeader | None, str | None]:
|
|
949
|
+
"""Read a remote GGUF header via bounded HTTP Range (8 MiB initial, capped 32 MiB, 10s timeout).
|
|
950
|
+
|
|
951
|
+
Retries at 32 MiB only on truncation errors; non-truncation GGUF format/type errors return an
|
|
952
|
+
accurate diagnostic note immediately without wasting a larger Range fetch.
|
|
953
|
+
"""
|
|
954
|
+
limit = HEADER_INITIAL_BYTES
|
|
955
|
+
while limit <= HEADER_MAX_BYTES:
|
|
956
|
+
try:
|
|
957
|
+
data = http_range(url, limit, token=token, timeout=timeout)
|
|
958
|
+
except urllib.error.HTTPError as exc:
|
|
959
|
+
msg = f"Range header read failed (HTTP {exc.code}); using rough memory estimate"
|
|
960
|
+
return None, redact_secrets(msg, extra_token=token)
|
|
961
|
+
except (OSError, http.client.HTTPException, ValueError) as exc:
|
|
962
|
+
msg = f"Range header read failed ({type(exc).__name__}); using rough memory estimate"
|
|
963
|
+
return None, redact_secrets(msg, extra_token=token)
|
|
964
|
+
try:
|
|
965
|
+
return read_header_stream(io.BytesIO(data), url), None
|
|
966
|
+
except (EOFError, ValueError, KeyError, struct.error, OverflowError) as exc:
|
|
967
|
+
if _is_truncated_gguf_error(exc):
|
|
968
|
+
if limit >= HEADER_MAX_BYTES:
|
|
969
|
+
cap_mib = HEADER_MAX_BYTES // (1 << 20)
|
|
970
|
+
return (
|
|
971
|
+
None,
|
|
972
|
+
f"GGUF header exceeded {cap_mib} MiB probe cap; using rough memory estimate",
|
|
973
|
+
)
|
|
974
|
+
limit = min(HEADER_MAX_BYTES, limit * 4)
|
|
975
|
+
continue
|
|
976
|
+
if "not a GGUF file" in str(exc):
|
|
977
|
+
return None, "Remote file header is not a valid GGUF; using rough memory estimate"
|
|
978
|
+
msg = (
|
|
979
|
+
f"Unsupported or malformed GGUF header ({type(exc).__name__}); "
|
|
980
|
+
"using rough memory estimate"
|
|
981
|
+
)
|
|
982
|
+
return None, redact_secrets(msg, extra_token=token)
|
|
983
|
+
return None, "GGUF header unavailable; using rough memory estimate"
|