@simplexai/localmodels-darwin-x64 0.1.0-dev.59 → 0.1.0-dev.61
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 +126 -107
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +107 -44
- package/modules/localmodels/apple_sensors.py +431 -0
- package/modules/localmodels/auth_proxy.py +185 -19
- package/modules/localmodels/bifrost_admin.py +30 -0
- package/modules/localmodels/bifrost_checks.py +2 -2
- package/modules/localmodels/bifrost_config.py +132 -9
- package/modules/localmodels/bifrost_models.py +1 -1
- package/modules/localmodels/catalog.json +509 -54
- package/modules/localmodels/catalog.py +21 -4
- package/modules/localmodels/catalog_add.py +42 -11
- package/modules/localmodels/catalog_license.py +2 -0
- package/modules/localmodels/catalog_recipes.py +2 -0
- package/modules/localmodels/cli_parser.py +6 -2
- package/modules/localmodels/context_policy.py +40 -4
- 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/debug_mode.py +13 -0
- package/modules/localmodels/debug_stub_server.py +156 -1
- package/modules/localmodels/deploy.py +38 -7
- package/modules/localmodels/deploy_steps.py +5 -0
- package/modules/localmodels/download-mirrors.json +20 -0
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -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-whisper-b5454.json +120 -1
- package/modules/localmodels/engines.py +38 -8
- package/modules/localmodels/estimator.py +60 -7
- package/modules/localmodels/gateway.py +48 -3
- package/modules/localmodels/gateway_app_bifrost.py +18 -18
- package/modules/localmodels/gateway_bifrost.py +102 -16
- package/modules/localmodels/gateway_cli.py +14 -80
- package/modules/localmodels/gateway_server.py +88 -16
- package/modules/localmodels/gguf.py +6 -0
- package/modules/localmodels/gpu_specs.py +35 -1
- package/modules/localmodels/harness.py +1 -2
- package/modules/localmodels/hf_repo.py +12 -4
- package/modules/localmodels/host_sensors.py +704 -0
- package/modules/localmodels/install.py +4 -4
- package/modules/localmodels/library_cli.py +181 -3
- package/modules/localmodels/library_custom.py +831 -0
- package/modules/localmodels/library_elastic.py +35 -7
- package/modules/localmodels/library_gateway.py +94 -32
- package/modules/localmodels/library_jobs.py +76 -11
- package/modules/localmodels/library_kept.py +50 -6
- package/modules/localmodels/library_model.py +254 -2
- package/modules/localmodels/library_pricing.py +83 -4
- package/modules/localmodels/library_serve.py +178 -60
- package/modules/localmodels/library_smoke.py +315 -0
- package/modules/localmodels/library_state.py +77 -1
- package/modules/localmodels/library_status.py +126 -4
- package/modules/localmodels/npm_transport.py +4 -58
- package/modules/localmodels/nvml_ctypes.py +431 -0
- package/modules/localmodels/plan_envelope.py +14 -6
- package/modules/localmodels/recommend_cli.py +2 -1
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/remote_ops.py +120 -665
- package/modules/localmodels/remote_ops_common.py +729 -0
- package/modules/localmodels/remote_ops_download.py +396 -241
- package/modules/localmodels/remote_ops_mirrors.py +26 -65
- package/modules/localmodels/remote_ops_prepare.py +43 -35
- package/modules/localmodels/remote_ops_ranges.py +98 -65
- package/modules/localmodels/remote_ops_remove.py +30 -22
- package/modules/localmodels/remote_ops_service.py +103 -95
- package/modules/localmodels/remote_ops_verify.py +113 -65
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_cli.py +15 -5
- package/modules/localmodels/runtime_io.py +54 -1
- package/modules/localmodels/service_control.py +32 -1
- package/modules/localmodels/service_wiring.py +2 -3
- package/modules/localmodels/service_worker.py +6 -2
- package/modules/localmodels/services_cli.py +35 -27
- package/modules/localmodels/source_byok.py +3 -5
- package/modules/localmodels/speech-sv.txt +93 -0
- package/modules/localmodels/speech_admission.py +437 -0
- package/modules/localmodels/speech_catalog.py +170 -0
- package/modules/localmodels/speech_cli.py +273 -0
- package/modules/localmodels/speech_jobs.py +772 -0
- package/modules/localmodels/speech_model.py +404 -0
- package/modules/localmodels/speech_serve.py +287 -0
- package/modules/localmodels/speech_server.py +837 -0
- package/modules/localmodels/speech_state.py +697 -0
- package/modules/localmodels/speech_worker_sensevoice.py +255 -0
- package/modules/localmodels/speech_workers.py +783 -0
- package/modules/localmodels/stack.py +0 -33
- package/modules/localmodels/stack_auto.py +5 -3
- package/modules/localmodels/stack_aux_gpu.py +45 -4
- package/modules/localmodels/stack_capacity.py +77 -8
- package/modules/localmodels/stack_cli.py +16 -1
- package/modules/localmodels/stack_compose.py +1 -1
- package/modules/localmodels/stack_down.py +24 -1
- package/modules/localmodels/stack_hardware.py +57 -88
- package/modules/localmodels/stack_hardware_text.py +4 -59
- package/modules/localmodels/stack_lifecycle.py +2 -2
- package/modules/localmodels/stack_memory.py +14 -3
- package/modules/localmodels/stack_suite.py +9 -10
- package/modules/localmodels/stack_summary.py +4 -4
- 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 +16 -1
- 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.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
- package/modules/localmodels/suite.py +3 -1
- package/modules/localmodels/telemetry_math.py +538 -0
- package/modules/localmodels/transport.py +3 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/localmodels/web/view/view.js +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +123 -104
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
- 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.20-poly.5.json +0 -94
- 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.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
"""Stdlib-only HTTP, redirect safety, SSRF blocking, and token gating for custom Hub requests.
|
|
2
|
+
|
|
3
|
+
Layer 4 helper split from ``custom_hub.py`` to keep security boundaries auditable and module
|
|
4
|
+
sizes well below the repository line cap. Strictly stdlib Python (no third-party Hub SDKs).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import ipaddress
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import socket
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.parse
|
|
17
|
+
import urllib.request
|
|
18
|
+
from collections.abc import Mapping, Sequence
|
|
19
|
+
from http.client import HTTPMessage
|
|
20
|
+
from typing import IO, NamedTuple, cast
|
|
21
|
+
|
|
22
|
+
from localmodels import region
|
|
23
|
+
from localmodels.library_model import CustomHub, LibraryError
|
|
24
|
+
|
|
25
|
+
HF_HOSTS = frozenset({"huggingface.co", "www.huggingface.co", "hf-mirror.com", "www.hf-mirror.com"})
|
|
26
|
+
HF_OFFICIAL_HOSTS = frozenset({"huggingface.co", "www.huggingface.co"})
|
|
27
|
+
HF_MIRROR_HOSTS = frozenset({"hf-mirror.com", "www.hf-mirror.com"})
|
|
28
|
+
MS_HOSTS = frozenset({"modelscope.cn", "www.modelscope.cn", "modelscope.com", "www.modelscope.com"})
|
|
29
|
+
MODELSCOPE_API = "https://modelscope.cn"
|
|
30
|
+
USER_AGENT = "localmodels-custom-hub"
|
|
31
|
+
|
|
32
|
+
SEARCH_TIMEOUT_S = 6.0
|
|
33
|
+
TREE_TIMEOUT_S = 15.0
|
|
34
|
+
RANGE_TIMEOUT_S = 10.0
|
|
35
|
+
MAX_JSON_RESPONSE_BYTES = 16 * 1024 * 1024
|
|
36
|
+
|
|
37
|
+
_BEARER_SECRET_RE = re.compile(r"(?i)\bBearer\s+[^\s,;\"']+")
|
|
38
|
+
_HF_TOKEN_RE = re.compile(r"\bhf_[A-Za-z0-9]+\b")
|
|
39
|
+
_MS_TOKEN_RE = re.compile(r"\bms[-_][A-Za-z0-9_-]+\b")
|
|
40
|
+
_BLOCKED_HOST_SUFFIXES = (".localhost", ".local", ".internal", ".home.arpa")
|
|
41
|
+
|
|
42
|
+
# Internal unit-test hook ONLY; strictly False in production.
|
|
43
|
+
_ALLOW_INSECURE_LOOPBACK_FOR_TESTS = False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def redact_secrets(text: str, *, extra_token: str | None = None) -> str:
|
|
47
|
+
"""Redact Hugging Face tokens, ModelScope tokens, Bearer headers, and any known token."""
|
|
48
|
+
out = text
|
|
49
|
+
if extra_token and len(extra_token.strip()) >= 4:
|
|
50
|
+
out = out.replace(extra_token.strip(), "[REDACTED]")
|
|
51
|
+
out = _BEARER_SECRET_RE.sub("Bearer [REDACTED]", out)
|
|
52
|
+
out = _HF_TOKEN_RE.sub("hf_[REDACTED]", out)
|
|
53
|
+
out = _MS_TOKEN_RE.sub("ms_[REDACTED]", out)
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _token_prefix_hub(token: str) -> CustomHub | None:
|
|
58
|
+
if token.startswith("hf_"):
|
|
59
|
+
return "huggingface"
|
|
60
|
+
if token.startswith(("ms-", "ms_")):
|
|
61
|
+
return "modelscope"
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def resolve_token(
|
|
66
|
+
hub: CustomHub,
|
|
67
|
+
explicit_token: str | None = None,
|
|
68
|
+
env: Mapping[str, str] | None = None,
|
|
69
|
+
*,
|
|
70
|
+
hub_explicit: bool = True,
|
|
71
|
+
) -> str | None:
|
|
72
|
+
"""Resolve an auth token strictly gated by hub compatibility.
|
|
73
|
+
|
|
74
|
+
- ``hf_*`` tokens are never forwarded to ModelScope.
|
|
75
|
+
- ``ms-*`` / ``ms_*`` tokens are never forwarded to Hugging Face.
|
|
76
|
+
- Unprefixed explicit tokens are only used when the target hub was explicitly specified
|
|
77
|
+
(``hub_explicit=True``), never broadcast blindly across ``hub="all"`` or ``hub="auto"``.
|
|
78
|
+
- Falls back to hub-specific environment variables when no compatible explicit token applies.
|
|
79
|
+
"""
|
|
80
|
+
if isinstance(explicit_token, str) and (clean := explicit_token.strip()):
|
|
81
|
+
prefix_hub = _token_prefix_hub(clean)
|
|
82
|
+
if prefix_hub == hub:
|
|
83
|
+
return clean
|
|
84
|
+
if prefix_hub is None and hub_explicit:
|
|
85
|
+
return clean
|
|
86
|
+
source = os.environ if env is None else env
|
|
87
|
+
if hub == "huggingface":
|
|
88
|
+
raw = source.get("HF_TOKEN") or source.get("HUGGING_FACE_HUB_TOKEN") or ""
|
|
89
|
+
else:
|
|
90
|
+
raw = source.get("MODELSCOPE_API_TOKEN") or ""
|
|
91
|
+
env_tok = raw.strip()
|
|
92
|
+
if not env_tok:
|
|
93
|
+
return None
|
|
94
|
+
env_prefix = _token_prefix_hub(env_tok)
|
|
95
|
+
if env_prefix is not None and env_prefix != hub:
|
|
96
|
+
return None
|
|
97
|
+
return env_tok
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _configured_hf_endpoint_host(env: Mapping[str, str] | None = None) -> str | None:
|
|
101
|
+
source = os.environ if env is None else env
|
|
102
|
+
raw = source.get("HF_ENDPOINT", "").strip()
|
|
103
|
+
if not raw:
|
|
104
|
+
return None
|
|
105
|
+
parsed = urllib.parse.urlsplit(raw)
|
|
106
|
+
if parsed.scheme.lower() != "https" or not parsed.hostname:
|
|
107
|
+
return None
|
|
108
|
+
host = parsed.hostname.lower()
|
|
109
|
+
return None if host in HF_MIRROR_HOSTS else host
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def token_for_endpoint(
|
|
113
|
+
hub: CustomHub,
|
|
114
|
+
url: str,
|
|
115
|
+
token: str | None,
|
|
116
|
+
*,
|
|
117
|
+
env: Mapping[str, str] | None = None,
|
|
118
|
+
) -> str | None:
|
|
119
|
+
"""Return ``token`` only if ``url`` is an HTTPS trusted origin for ``hub`` (never hf-mirror)."""
|
|
120
|
+
if not token or not token.strip():
|
|
121
|
+
return None
|
|
122
|
+
clean = token.strip()
|
|
123
|
+
prefix_hub = _token_prefix_hub(clean)
|
|
124
|
+
if prefix_hub is not None and prefix_hub != hub:
|
|
125
|
+
return None
|
|
126
|
+
parts = urllib.parse.urlsplit(url)
|
|
127
|
+
scheme = parts.scheme.lower()
|
|
128
|
+
host = (parts.hostname or "").lower()
|
|
129
|
+
if not host:
|
|
130
|
+
return None
|
|
131
|
+
if scheme != "https":
|
|
132
|
+
if (
|
|
133
|
+
_ALLOW_INSECURE_LOOPBACK_FOR_TESTS
|
|
134
|
+
and scheme == "http"
|
|
135
|
+
and host in ("127.0.0.1", "localhost")
|
|
136
|
+
):
|
|
137
|
+
return clean
|
|
138
|
+
return None
|
|
139
|
+
if hub == "huggingface":
|
|
140
|
+
if host in HF_MIRROR_HOSTS:
|
|
141
|
+
return None
|
|
142
|
+
if host in HF_OFFICIAL_HOSTS:
|
|
143
|
+
return clean
|
|
144
|
+
custom_host = _configured_hf_endpoint_host(env)
|
|
145
|
+
return clean if custom_host is not None and host == custom_host else None
|
|
146
|
+
return clean if host in MS_HOSTS else None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _effective_port(parts: urllib.parse.SplitResult) -> int:
|
|
150
|
+
if parts.port is not None:
|
|
151
|
+
return parts.port
|
|
152
|
+
scheme = parts.scheme.lower()
|
|
153
|
+
return 443 if scheme == "https" else 80 if scheme == "http" else 0
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _origin(url: str) -> tuple[str, str, int]:
|
|
157
|
+
parts = urllib.parse.urlsplit(url)
|
|
158
|
+
return (
|
|
159
|
+
parts.scheme.lower(),
|
|
160
|
+
(parts.hostname or "").lower().rstrip("."),
|
|
161
|
+
_effective_port(parts),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _is_disallowed_ip(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
|
166
|
+
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
|
|
167
|
+
addr = addr.ipv4_mapped
|
|
168
|
+
return (
|
|
169
|
+
addr.is_loopback
|
|
170
|
+
or addr.is_private
|
|
171
|
+
or addr.is_link_local
|
|
172
|
+
or addr.is_multicast
|
|
173
|
+
or addr.is_unspecified
|
|
174
|
+
or addr.is_reserved
|
|
175
|
+
or not addr.is_global
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def validate_redirect_target(url: str, *, allow_insecure_loopback: bool | None = None) -> None:
|
|
180
|
+
"""Enforce HTTPS and block loopback/private/link-local SSRF targets on redirects."""
|
|
181
|
+
allow_test = (
|
|
182
|
+
_ALLOW_INSECURE_LOOPBACK_FOR_TESTS
|
|
183
|
+
if allow_insecure_loopback is None
|
|
184
|
+
else allow_insecure_loopback
|
|
185
|
+
)
|
|
186
|
+
parts = urllib.parse.urlsplit(url)
|
|
187
|
+
scheme = parts.scheme.lower()
|
|
188
|
+
host = (parts.hostname or "").lower().rstrip(".")
|
|
189
|
+
if scheme != "https" and not (allow_test and scheme == "http"):
|
|
190
|
+
raise urllib.error.URLError(f"blocked redirect to non-HTTPS scheme {scheme!r}")
|
|
191
|
+
if not host:
|
|
192
|
+
raise urllib.error.URLError("blocked redirect with missing hostname")
|
|
193
|
+
if allow_test:
|
|
194
|
+
return
|
|
195
|
+
if host == "localhost" or host.endswith(_BLOCKED_HOST_SUFFIXES):
|
|
196
|
+
raise urllib.error.URLError(f"blocked redirect to local hostname {host!r}")
|
|
197
|
+
try:
|
|
198
|
+
literal = ipaddress.ip_address(host.split("%", 1)[0])
|
|
199
|
+
except ValueError:
|
|
200
|
+
literal = None
|
|
201
|
+
if literal is not None:
|
|
202
|
+
if _is_disallowed_ip(literal):
|
|
203
|
+
raise urllib.error.URLError(f"blocked redirect to non-public IP {host!r}")
|
|
204
|
+
return
|
|
205
|
+
port = _effective_port(parts) or 443
|
|
206
|
+
try:
|
|
207
|
+
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
208
|
+
except OSError as exc:
|
|
209
|
+
raise urllib.error.URLError(
|
|
210
|
+
f"blocked redirect: DNS resolution failed for {host!r}: {exc}"
|
|
211
|
+
) from None
|
|
212
|
+
if not infos:
|
|
213
|
+
raise urllib.error.URLError(f"blocked redirect: no addresses resolved for {host!r}")
|
|
214
|
+
for info in infos:
|
|
215
|
+
raw_ip = str(info[4][0]).split("%", 1)[0]
|
|
216
|
+
try:
|
|
217
|
+
resolved_ip = ipaddress.ip_address(raw_ip)
|
|
218
|
+
except ValueError:
|
|
219
|
+
raise urllib.error.URLError(f"blocked redirect: unparseable IP for {host!r}") from None
|
|
220
|
+
if _is_disallowed_ip(resolved_ip):
|
|
221
|
+
raise urllib.error.URLError(f"blocked redirect to non-public IP for {host!r}")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
225
|
+
"""Enforce HTTPS + anti-SSRF on redirects and strip ``Authorization`` on any origin change."""
|
|
226
|
+
|
|
227
|
+
def redirect_request(
|
|
228
|
+
self,
|
|
229
|
+
req: urllib.request.Request,
|
|
230
|
+
fp: IO[bytes],
|
|
231
|
+
code: int,
|
|
232
|
+
msg: str,
|
|
233
|
+
headers: HTTPMessage,
|
|
234
|
+
newurl: str,
|
|
235
|
+
) -> urllib.request.Request | None:
|
|
236
|
+
resolved = urllib.parse.urljoin(req.full_url, newurl)
|
|
237
|
+
validate_redirect_target(resolved)
|
|
238
|
+
new_req = super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
239
|
+
if new_req is None:
|
|
240
|
+
return None
|
|
241
|
+
if _origin(req.full_url) != _origin(resolved):
|
|
242
|
+
for mapping in (new_req.headers, new_req.unredirected_hdrs):
|
|
243
|
+
for key in [k for k in mapping if k.lower() == "authorization"]:
|
|
244
|
+
del mapping[key]
|
|
245
|
+
return new_req
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def build_opener() -> urllib.request.OpenerDirector:
|
|
249
|
+
return urllib.request.build_opener(SafeRedirectHandler())
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _require_https_request(url: str) -> None:
|
|
253
|
+
scheme = urllib.parse.urlsplit(url).scheme.lower()
|
|
254
|
+
if scheme != "https" and not (_ALLOW_INSECURE_LOOPBACK_FOR_TESTS and scheme == "http"):
|
|
255
|
+
raise ValueError(f"refusing non-HTTPS hub request ({scheme!r})")
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def http_json(
|
|
259
|
+
url: str,
|
|
260
|
+
*,
|
|
261
|
+
method: str = "GET",
|
|
262
|
+
body: Mapping[str, object] | None = None,
|
|
263
|
+
token: str | None = None,
|
|
264
|
+
timeout: float = TREE_TIMEOUT_S,
|
|
265
|
+
max_bytes: int = MAX_JSON_RESPONSE_BYTES,
|
|
266
|
+
) -> object:
|
|
267
|
+
"""Fetch a bounded JSON response using ``SafeRedirectHandler``."""
|
|
268
|
+
_require_https_request(url)
|
|
269
|
+
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
|
|
270
|
+
data: bytes | None = None
|
|
271
|
+
if body is not None:
|
|
272
|
+
headers["Content-Type"] = "application/json"
|
|
273
|
+
data = json.dumps(body).encode("utf-8")
|
|
274
|
+
if token:
|
|
275
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
276
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
277
|
+
with build_opener().open(req, timeout=timeout) as resp:
|
|
278
|
+
raw: bytes = resp.read(max_bytes + 1)
|
|
279
|
+
if len(raw) > max_bytes:
|
|
280
|
+
raise ValueError(f"hub JSON response exceeded {max_bytes // (1 << 20)} MiB size cap")
|
|
281
|
+
return json.loads(raw.decode("utf-8"))
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def http_range(
|
|
285
|
+
url: str,
|
|
286
|
+
limit: int,
|
|
287
|
+
*,
|
|
288
|
+
token: str | None = None,
|
|
289
|
+
timeout: float = RANGE_TIMEOUT_S,
|
|
290
|
+
) -> bytes:
|
|
291
|
+
"""Read at most ``limit`` bytes from ``url`` via an HTTP Range request."""
|
|
292
|
+
_require_https_request(url)
|
|
293
|
+
headers = {"User-Agent": USER_AGENT, "Range": f"bytes=0-{limit - 1}"}
|
|
294
|
+
if token:
|
|
295
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
296
|
+
req = urllib.request.Request(url, headers=headers)
|
|
297
|
+
with build_opener().open(req, timeout=timeout) as resp:
|
|
298
|
+
data: bytes = resp.read(limit)
|
|
299
|
+
return data
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _readonly_region(env: Mapping[str, str] | None = None) -> str:
|
|
303
|
+
"""Read active region without mutating ``region.json`` or running a network speed probe."""
|
|
304
|
+
active_env = os.environ if env is None else env
|
|
305
|
+
try:
|
|
306
|
+
explicit = region.forced(active_env)
|
|
307
|
+
except ValueError:
|
|
308
|
+
explicit = None
|
|
309
|
+
if explicit in region.REGIONS:
|
|
310
|
+
return explicit
|
|
311
|
+
doc = region.saved(env=active_env)
|
|
312
|
+
if doc is not None and doc.get("region") in region.REGIONS:
|
|
313
|
+
return str(doc["region"])
|
|
314
|
+
return "global"
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def hf_endpoints(
|
|
318
|
+
explicit_endpoint: str | None = None, *, env: Mapping[str, str] | None = None
|
|
319
|
+
) -> list[str]:
|
|
320
|
+
"""Read-only ordered HF-compatible API endpoints (zero state writes, zero speed probes)."""
|
|
321
|
+
active_env = os.environ if env is None else env
|
|
322
|
+
if explicit_endpoint:
|
|
323
|
+
ep = explicit_endpoint.rstrip("/")
|
|
324
|
+
if ep == region.HF_MIRROR:
|
|
325
|
+
return [region.HF_MIRROR, region.HF_API]
|
|
326
|
+
return [ep]
|
|
327
|
+
env_ep = active_env.get("HF_ENDPOINT", "").strip()
|
|
328
|
+
if env_ep:
|
|
329
|
+
parsed = urllib.parse.urlsplit(env_ep)
|
|
330
|
+
if parsed.scheme.lower() == "https" and parsed.hostname:
|
|
331
|
+
return [env_ep.rstrip("/")]
|
|
332
|
+
return region.prefer(_readonly_region(active_env), [region.HF_API], [region.HF_MIRROR])
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# --------------------------------------------------------------------------- spec & ID helpers
|
|
336
|
+
|
|
337
|
+
CUSTOM_MODEL_ID_MAX_LEN = 160
|
|
338
|
+
MODEL_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*:[A-Za-z0-9._-]+$")
|
|
339
|
+
_PART_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
|
|
340
|
+
_REVISION_SEG_RE = re.compile(r"^[A-Za-z0-9._-]+$")
|
|
341
|
+
_HF_NON_MODEL_PREFIXES = frozenset(
|
|
342
|
+
{"api", "datasets", "spaces", "organizations", "docs", "blog", "settings", "models"}
|
|
343
|
+
)
|
|
344
|
+
_SLUG_BAD_RE = re.compile(r"[^a-z0-9._-]+")
|
|
345
|
+
_VARIANT_BAD_RE = re.compile(r"[^A-Za-z0-9._-]+")
|
|
346
|
+
_PARAM_B_RE = re.compile(r"(?<![A-Za-z0-9.])(\d+(?:\.\d+)?)\s*[bB](?![A-Za-z0-9])")
|
|
347
|
+
_SUGGEST_STRIP_RE = re.compile(
|
|
348
|
+
r"(?:[-_](?:mlx|gguf|fp8|fp16|bf16|f16|awq|gptq|4bit|8bit|3bit|6bit|int4|int8))+$",
|
|
349
|
+
re.IGNORECASE,
|
|
350
|
+
)
|
|
351
|
+
_FAMILY_RULES: tuple[tuple[str, tuple[str, ...]], ...] = (
|
|
352
|
+
("qwen", ("qwen",)),
|
|
353
|
+
("gemma", ("gemma",)),
|
|
354
|
+
("llama", ("llama", "codellama")),
|
|
355
|
+
("deepseek", ("deepseek",)),
|
|
356
|
+
("mistral", ("mistral", "mixtral", "ministral", "devstral", "pixtral", "codestral")),
|
|
357
|
+
("phi", ("phi-", "phi3", "phi4", "phi_")),
|
|
358
|
+
("glm", ("glm", "chatglm")),
|
|
359
|
+
("kimi", ("kimi", "moonshot")),
|
|
360
|
+
("openai", ("gpt-oss", "openai")),
|
|
361
|
+
("claude", ("claude",)),
|
|
362
|
+
("grok", ("grok",)),
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
class ParsedRepoSpec(NamedTuple):
|
|
367
|
+
hub: CustomHub | None # None when --hub auto and target gave no hub prefix/URL
|
|
368
|
+
repo_id: str
|
|
369
|
+
revision: str | None
|
|
370
|
+
quant_hint: str | None
|
|
371
|
+
file_name: str | None
|
|
372
|
+
explicit_endpoint: str | None
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _validate_owner_repo(owner: str, name: str) -> str:
|
|
376
|
+
if (
|
|
377
|
+
not _PART_NAME_RE.fullmatch(owner)
|
|
378
|
+
or not _PART_NAME_RE.fullmatch(name)
|
|
379
|
+
or owner in (".", "..")
|
|
380
|
+
or name in (".", "..")
|
|
381
|
+
):
|
|
382
|
+
raise LibraryError("INVALID_REPO_SPEC", f"invalid repository identifier: {owner}/{name}")
|
|
383
|
+
return f"{owner}/{name}"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _validate_revision(rev: str | None) -> str | None:
|
|
387
|
+
if not rev:
|
|
388
|
+
return None
|
|
389
|
+
clean = rev.strip()
|
|
390
|
+
if not clean:
|
|
391
|
+
return None
|
|
392
|
+
segments = clean.split("/")
|
|
393
|
+
if any(
|
|
394
|
+
not seg or seg in (".", "..") or not _REVISION_SEG_RE.fullmatch(seg) for seg in segments
|
|
395
|
+
):
|
|
396
|
+
raise LibraryError("INVALID_REPO_SPEC", f"invalid revision identifier: {rev!r}")
|
|
397
|
+
return clean
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _parse_hf_url(url: urllib.parse.SplitResult) -> ParsedRepoSpec:
|
|
401
|
+
if url.scheme.lower() != "https":
|
|
402
|
+
raise LibraryError("INVALID_REPO_SPEC", "Hugging Face URL must use https://")
|
|
403
|
+
parts = [p for p in urllib.parse.unquote(url.path).split("/") if p]
|
|
404
|
+
if len(parts) < 2 or parts[0].lower() in _HF_NON_MODEL_PREFIXES:
|
|
405
|
+
raise LibraryError("INVALID_REPO_SPEC", "Hugging Face URL must point to a model repository")
|
|
406
|
+
repo_id = _validate_owner_repo(parts[0], parts[1])
|
|
407
|
+
rev = parts[3] if len(parts) >= 4 and parts[2] in ("blob", "resolve", "tree") else None
|
|
408
|
+
file_name = "/".join(parts[4:]) if len(parts) > 4 and parts[2] in ("blob", "resolve") else None
|
|
409
|
+
host = (url.hostname or "").lower()
|
|
410
|
+
explicit = f"https://{host}" if host in HF_MIRROR_HOSTS else None
|
|
411
|
+
return ParsedRepoSpec(
|
|
412
|
+
"huggingface", repo_id, _validate_revision(rev), None, file_name, explicit
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _parse_ms_url(url: urllib.parse.SplitResult) -> ParsedRepoSpec:
|
|
417
|
+
if url.scheme.lower() != "https":
|
|
418
|
+
raise LibraryError("INVALID_REPO_SPEC", "ModelScope URL must use https://")
|
|
419
|
+
parts = [p for p in urllib.parse.unquote(url.path).split("/") if p]
|
|
420
|
+
if len(parts) < 3 or parts[0].lower() != "models":
|
|
421
|
+
raise LibraryError(
|
|
422
|
+
"INVALID_REPO_SPEC", "ModelScope URL must follow https://modelscope.cn/models/<o>/<r>"
|
|
423
|
+
)
|
|
424
|
+
repo_id = _validate_owner_repo(parts[1], parts[2])
|
|
425
|
+
rev: str | None = None
|
|
426
|
+
file_name: str | None = None
|
|
427
|
+
if len(parts) >= 6 and parts[3:5] == ["file", "view"]:
|
|
428
|
+
rev, file_name = parts[5], ("/".join(parts[6:]) or None)
|
|
429
|
+
elif len(parts) >= 5 and parts[3] == "resolve":
|
|
430
|
+
rev, file_name = parts[4], ("/".join(parts[5:]) or None)
|
|
431
|
+
return ParsedRepoSpec("modelscope", repo_id, _validate_revision(rev), None, file_name, None)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _parse_shorthand(raw: str) -> ParsedRepoSpec:
|
|
435
|
+
hub: CustomHub | None = None
|
|
436
|
+
text = raw
|
|
437
|
+
for prefix, target_hub in (
|
|
438
|
+
("hf:", "huggingface"),
|
|
439
|
+
("ms:", "modelscope"),
|
|
440
|
+
("modelscope:", "modelscope"),
|
|
441
|
+
):
|
|
442
|
+
if text.lower().startswith(prefix):
|
|
443
|
+
hub, text = cast(CustomHub, target_hub), text[len(prefix) :]
|
|
444
|
+
break
|
|
445
|
+
if "/" not in text:
|
|
446
|
+
raise LibraryError(
|
|
447
|
+
"INVALID_REPO_SPEC", f"expected URL or owner/repo shorthand, got {raw!r}"
|
|
448
|
+
)
|
|
449
|
+
owner, tail = text.split("/", 1)
|
|
450
|
+
quant: str | None = None
|
|
451
|
+
rev: str | None = None
|
|
452
|
+
if "@" in tail and ":" in tail:
|
|
453
|
+
if tail.index(":") < tail.index("@"):
|
|
454
|
+
name, rest = tail.split(":", 1)
|
|
455
|
+
quant, rev = rest.split("@", 1)
|
|
456
|
+
else:
|
|
457
|
+
name, rest = tail.split("@", 1)
|
|
458
|
+
rev, quant = rest.split(":", 1)
|
|
459
|
+
elif "@" in tail:
|
|
460
|
+
name, rev = tail.split("@", 1)
|
|
461
|
+
elif ":" in tail:
|
|
462
|
+
name, quant = tail.split(":", 1)
|
|
463
|
+
else:
|
|
464
|
+
name = tail
|
|
465
|
+
if "/" in name or (quant and "/" in quant):
|
|
466
|
+
raise LibraryError(
|
|
467
|
+
"INVALID_REPO_SPEC", f"expected URL or owner/repo shorthand, got {raw!r}"
|
|
468
|
+
)
|
|
469
|
+
return ParsedRepoSpec(
|
|
470
|
+
hub,
|
|
471
|
+
_validate_owner_repo(owner, name),
|
|
472
|
+
_validate_revision(rev),
|
|
473
|
+
quant or None,
|
|
474
|
+
None,
|
|
475
|
+
None,
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def parse_repo_spec(
|
|
480
|
+
target: str, *, hub: str = "auto", revision: str | None = None, file_name: str | None = None
|
|
481
|
+
) -> ParsedRepoSpec:
|
|
482
|
+
"""Parse an HTTPS Hugging Face / ModelScope URL or ``owner/repo[:QUANT][@REV]`` shorthand."""
|
|
483
|
+
if hub not in ("auto", "huggingface", "modelscope"):
|
|
484
|
+
raise LibraryError("INVALID_REPO_SPEC", f"invalid hub {hub!r}")
|
|
485
|
+
raw = target.strip()
|
|
486
|
+
if not raw:
|
|
487
|
+
raise LibraryError("INVALID_REPO_SPEC", "target repository cannot be empty")
|
|
488
|
+
lower_raw = raw.lower()
|
|
489
|
+
if lower_raw.startswith("http://"):
|
|
490
|
+
raise LibraryError(
|
|
491
|
+
"INVALID_REPO_SPEC", "plaintext http:// repository URLs are rejected; use https://"
|
|
492
|
+
)
|
|
493
|
+
if lower_raw.startswith("https://"):
|
|
494
|
+
url = urllib.parse.urlsplit(raw)
|
|
495
|
+
host = (url.hostname or "").lower()
|
|
496
|
+
if host in HF_HOSTS:
|
|
497
|
+
parsed = _parse_hf_url(url)
|
|
498
|
+
elif host in MS_HOSTS:
|
|
499
|
+
parsed = _parse_ms_url(url)
|
|
500
|
+
else:
|
|
501
|
+
raise LibraryError("INVALID_REPO_SPEC", f"unsupported repository host {host!r}")
|
|
502
|
+
else:
|
|
503
|
+
parsed = _parse_shorthand(raw)
|
|
504
|
+
resolved_hub = parsed.hub
|
|
505
|
+
if hub != "auto":
|
|
506
|
+
req_hub = cast(CustomHub, hub)
|
|
507
|
+
if resolved_hub is not None and resolved_hub != req_hub:
|
|
508
|
+
raise LibraryError(
|
|
509
|
+
"INVALID_REPO_SPEC", f"target hub {resolved_hub!r} conflicts with {req_hub!r}"
|
|
510
|
+
)
|
|
511
|
+
resolved_hub = req_hub
|
|
512
|
+
final_rev = _validate_revision((revision or "").strip() or None) or parsed.revision
|
|
513
|
+
return ParsedRepoSpec(
|
|
514
|
+
resolved_hub,
|
|
515
|
+
parsed.repo_id,
|
|
516
|
+
final_rev,
|
|
517
|
+
parsed.quant_hint,
|
|
518
|
+
(file_name or "").strip() or parsed.file_name,
|
|
519
|
+
parsed.explicit_endpoint,
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _slug(text: str, *, fallback: str) -> str:
|
|
524
|
+
cleaned = _SLUG_BAD_RE.sub("-", text.strip().lower()).strip("-._")
|
|
525
|
+
return cleaned or fallback
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def variant_slug(text: str) -> str:
|
|
529
|
+
cleaned = _VARIANT_BAD_RE.sub("-", text.strip()).strip("-")
|
|
530
|
+
return cleaned or "default"
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def make_custom_model_id(hub: CustomHub, repo_id: str, variant_id: str) -> str:
|
|
534
|
+
"""Build deterministic custom model ID matching ``^[a-z0-9][a-z0-9._-]*:[A-Za-z0-9._-]+$``
|
|
535
|
+
with length <= 160 chars and SHA-256 suffix when truncated."""
|
|
536
|
+
hub_short = "hf" if hub == "huggingface" else "ms"
|
|
537
|
+
owner, _, name = repo_id.partition("/")
|
|
538
|
+
left = f"custom.{hub_short}.{_slug(owner, fallback='owner')}--{_slug(name, fallback='repo')}"
|
|
539
|
+
right = variant_slug(variant_id)
|
|
540
|
+
full = f"{left}:{right}"
|
|
541
|
+
if len(full) <= CUSTOM_MODEL_ID_MAX_LEN:
|
|
542
|
+
return full
|
|
543
|
+
digest = hashlib.sha256(full.encode("utf-8")).hexdigest()[:8]
|
|
544
|
+
if len(right) > 80:
|
|
545
|
+
right = f"{right[:71].rstrip('-')}-{digest}"
|
|
546
|
+
max_left = CUSTOM_MODEL_ID_MAX_LEN - 1 - len(right)
|
|
547
|
+
keep = max(len(f"custom.{hub_short}."), max_left - 9)
|
|
548
|
+
trimmed = left[:keep].rstrip(".-_")
|
|
549
|
+
return f"{trimmed}-{digest}:{right}"
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def infer_family(repo_id: str, tags: Sequence[str] = (), architecture: str | None = None) -> str:
|
|
553
|
+
haystack = " ".join([repo_id, architecture or "", *tags]).lower()
|
|
554
|
+
for family, needles in _FAMILY_RULES:
|
|
555
|
+
if any(needle in haystack for needle in needles):
|
|
556
|
+
return family
|
|
557
|
+
return "other"
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def infer_parameter_billions(text: str) -> float | None:
|
|
561
|
+
if match := _PARAM_B_RE.search(text):
|
|
562
|
+
val = float(match.group(1))
|
|
563
|
+
if 0.05 <= val <= 5000.0:
|
|
564
|
+
return round(val, 1)
|
|
565
|
+
return None
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def build_suggested_gguf_query(repo_id: str) -> str:
|
|
569
|
+
"""Build a clean GGUF search query from a non-GGUF repository ID."""
|
|
570
|
+
name = repo_id.rsplit("/", 1)[-1]
|
|
571
|
+
cleaned = _SUGGEST_STRIP_RE.sub("", name)
|
|
572
|
+
words = " ".join(re.split(r"[-_\s]+", cleaned)).strip()
|
|
573
|
+
return f"{words} GGUF" if words else "GGUF"
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def repo_web_url(hub: CustomHub, repo_id: str) -> str:
|
|
577
|
+
if hub == "huggingface":
|
|
578
|
+
return f"https://huggingface.co/{repo_id}"
|
|
579
|
+
return f"https://modelscope.cn/models/{repo_id}"
|