@simplexai/localmodels-win32-x64 0.1.0-dev.110 → 0.1.0-dev.112
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/README.md +1 -1
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +52 -52
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/catalog.json +482 -103
- package/modules/localmodels/catalog_recipes.py +10 -1
- package/modules/localmodels/custom_hub.py +66 -2
- package/modules/localmodels/custom_hub_http.py +18 -0
- package/modules/localmodels/deploy.py +70 -5
- package/modules/localmodels/download-mirrors.json +70 -0
- package/modules/localmodels/engine_adapters/strata_poly.py +20 -4
- package/modules/localmodels/engine_adapters/suite_plan.py +7 -0
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.10.json +132 -0
- package/modules/localmodels/engines.json +96 -91
- package/modules/localmodels/engines.py +9 -2
- package/modules/localmodels/http_local.py +46 -0
- package/modules/localmodels/library_cli.py +2 -1
- package/modules/localmodels/library_custom.py +73 -0
- package/modules/localmodels/library_jobs.py +47 -23
- package/modules/localmodels/library_model.py +3 -1
- package/modules/localmodels/library_poly.py +78 -33
- package/modules/localmodels/library_presentation.py +28 -0
- package/modules/localmodels/library_pricing.py +125 -20
- package/modules/localmodels/library_serve.py +90 -27
- package/modules/localmodels/library_smoke.py +1 -1
- package/modules/localmodels/library_state.py +23 -1
- package/modules/localmodels/library_status.py +57 -56
- package/modules/localmodels/mirrors.py +217 -21
- package/modules/localmodels/npm_transport.py +46 -35
- package/modules/localmodels/plan_envelope.py +8 -1
- package/modules/localmodels/region.py +90 -23
- package/modules/localmodels/remote_ops_common.py +1 -0
- package/modules/localmodels/remote_ops_download.py +583 -126
- package/modules/localmodels/remote_ops_prepare.py +8 -2
- package/modules/localmodels/remote_ops_ranges.py +80 -44
- package/modules/localmodels/remote_ops_redirect.py +3 -1
- package/modules/localmodels/remote_ops_remove.py +4 -2
- package/modules/localmodels/runtime_index.py +3 -1
- package/modules/localmodels/stack.py +1 -6
- package/modules/localmodels/stack_suite.py +15 -2
- package/modules/localmodels/{strata-poly-serve-0.2.20-poly.9.txt → strata-poly-serve-0.2.20-poly.10.txt} +1 -1
- package/modules/localmodels/suite.py +110 -8
- package/modules/localmodels/web/view/i18n.js +1 -1
- package/modules/localmodels/web/view/view.js +11 -3
- package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/RECORD +48 -48
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +0 -132
- /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/licenses/LICENSE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -8,9 +8,11 @@ and never write raw proxy URLs or credentials to disk (only a SHA-256 fingerprin
|
|
|
8
8
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
|
+
import contextlib
|
|
11
12
|
import datetime as dt
|
|
12
13
|
import hashlib
|
|
13
14
|
import http.client
|
|
15
|
+
import sys
|
|
14
16
|
import threading
|
|
15
17
|
import time
|
|
16
18
|
import urllib.error
|
|
@@ -18,7 +20,8 @@ import urllib.parse
|
|
|
18
20
|
import urllib.request
|
|
19
21
|
from collections.abc import Callable, Mapping, Sequence
|
|
20
22
|
from dataclasses import dataclass
|
|
21
|
-
from
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Literal, TypedDict
|
|
22
25
|
|
|
23
26
|
from localmodels import npm_transport
|
|
24
27
|
|
|
@@ -30,7 +33,26 @@ PROBE_MAX_BYTES = 128 << 10 # 128 KiB: enough to measure throughput, fast on sl
|
|
|
30
33
|
PROBE_READ_BYTES = 32 << 10
|
|
31
34
|
PROXY_ENV_NAMES = frozenset({"http_proxy", "https_proxy", "all_proxy", "no_proxy"})
|
|
32
35
|
HOST_ALIASES: dict[str, str] = {"pypi.mirrors.ustc.edu.cn": "mirrors.ustc.edu.cn"}
|
|
33
|
-
VALID_METHODS = frozenset({"env", "probe", "fallback"})
|
|
36
|
+
VALID_METHODS = frozenset({"env", "probe", "fallback", "user"})
|
|
37
|
+
PYPI_PROBE_BYTES = 65536
|
|
38
|
+
MODEL_HUB_PROBE_BYTES = 262144
|
|
39
|
+
# Catalog pin (same SHA-256 on Hugging Face and ModelScope master). A 256 KiB Range follows the
|
|
40
|
+
# weight redirect onto the data-plane CDN (*.hf.co / cdn-lfs-cn-*.modelscope.cn), not the JSON API.
|
|
41
|
+
_HUB_PROBE_REPO = "unsloth/DeepSeek-V4-Flash-0731-GGUF"
|
|
42
|
+
_HUB_PROBE_REV = "fbbb5b93fb787c21338159b0af3318bb3f4d9768"
|
|
43
|
+
_HUB_PROBE_PATH = "UD-Q4_K_XL/DeepSeek-V4-Flash-0731-UD-Q4_K_XL-00001-of-00005.gguf"
|
|
44
|
+
_GLOBAL_BOUNCE_HOSTS = (
|
|
45
|
+
"huggingface.co",
|
|
46
|
+
"hf.co",
|
|
47
|
+
"registry.npmjs.org",
|
|
48
|
+
"nodejs.org",
|
|
49
|
+
"files.pythonhosted.org",
|
|
50
|
+
"pypi.org",
|
|
51
|
+
"proxy.golang.org",
|
|
52
|
+
"static.rust-lang.org",
|
|
53
|
+
"formulae.brew.sh",
|
|
54
|
+
)
|
|
55
|
+
_BOUNCED_HOSTS: set[tuple[str, str]] = set()
|
|
34
56
|
|
|
35
57
|
|
|
36
58
|
@dataclass(frozen=True)
|
|
@@ -51,6 +73,8 @@ class ProbeResult:
|
|
|
51
73
|
bytes_per_second: float
|
|
52
74
|
latency_ms: float
|
|
53
75
|
bytes_read: int
|
|
76
|
+
final_host: str = ""
|
|
77
|
+
bounced: bool = False
|
|
54
78
|
|
|
55
79
|
|
|
56
80
|
@dataclass(frozen=True)
|
|
@@ -83,30 +107,35 @@ ECOSYSTEMS: dict[EcosystemName, tuple[MirrorCandidate, ...]] = {
|
|
|
83
107
|
side="global",
|
|
84
108
|
base_url="https://pypi.org/simple/",
|
|
85
109
|
probe_url="https://pypi.org/simple/pip/",
|
|
110
|
+
probe_bytes=PYPI_PROBE_BYTES,
|
|
86
111
|
),
|
|
87
112
|
MirrorCandidate(
|
|
88
113
|
name="pypi-tsinghua",
|
|
89
114
|
side="cn",
|
|
90
115
|
base_url="https://pypi.tuna.tsinghua.edu.cn/simple/",
|
|
91
116
|
probe_url="https://pypi.tuna.tsinghua.edu.cn/simple/pip/",
|
|
117
|
+
probe_bytes=PYPI_PROBE_BYTES,
|
|
92
118
|
),
|
|
93
119
|
MirrorCandidate(
|
|
94
120
|
name="pypi-aliyun",
|
|
95
121
|
side="cn",
|
|
96
122
|
base_url="https://mirrors.aliyun.com/pypi/simple/",
|
|
97
123
|
probe_url="https://mirrors.aliyun.com/pypi/simple/pip/",
|
|
124
|
+
probe_bytes=PYPI_PROBE_BYTES,
|
|
98
125
|
),
|
|
99
126
|
MirrorCandidate(
|
|
100
127
|
name="pypi-ustc",
|
|
101
128
|
side="cn",
|
|
102
129
|
base_url="https://pypi.mirrors.ustc.edu.cn/simple/",
|
|
103
130
|
probe_url="https://pypi.mirrors.ustc.edu.cn/simple/pip/",
|
|
131
|
+
probe_bytes=PYPI_PROBE_BYTES,
|
|
104
132
|
),
|
|
105
133
|
MirrorCandidate(
|
|
106
134
|
name="pypi-tencent",
|
|
107
135
|
side="cn",
|
|
108
136
|
base_url="https://mirrors.cloud.tencent.com/pypi/simple/",
|
|
109
137
|
probe_url="https://mirrors.cloud.tencent.com/pypi/simple/pip/",
|
|
138
|
+
probe_bytes=PYPI_PROBE_BYTES,
|
|
110
139
|
),
|
|
111
140
|
),
|
|
112
141
|
"npm": (
|
|
@@ -150,22 +179,30 @@ ECOSYSTEMS: dict[EcosystemName, tuple[MirrorCandidate, ...]] = {
|
|
|
150
179
|
name="huggingface",
|
|
151
180
|
side="global",
|
|
152
181
|
base_url="https://huggingface.co",
|
|
153
|
-
probe_url=
|
|
154
|
-
|
|
182
|
+
probe_url=(
|
|
183
|
+
f"https://huggingface.co/{_HUB_PROBE_REPO}/resolve/{_HUB_PROBE_REV}/"
|
|
184
|
+
f"{_HUB_PROBE_PATH}"
|
|
185
|
+
),
|
|
186
|
+
probe_bytes=MODEL_HUB_PROBE_BYTES,
|
|
155
187
|
),
|
|
156
188
|
MirrorCandidate(
|
|
157
189
|
name="hf-mirror",
|
|
158
190
|
side="cn",
|
|
159
191
|
base_url="https://hf-mirror.com",
|
|
160
|
-
probe_url=
|
|
161
|
-
|
|
192
|
+
probe_url=(
|
|
193
|
+
f"https://hf-mirror.com/{_HUB_PROBE_REPO}/resolve/{_HUB_PROBE_REV}/"
|
|
194
|
+
f"{_HUB_PROBE_PATH}"
|
|
195
|
+
),
|
|
196
|
+
probe_bytes=MODEL_HUB_PROBE_BYTES,
|
|
162
197
|
),
|
|
163
198
|
MirrorCandidate(
|
|
164
199
|
name="modelscope",
|
|
165
200
|
side="cn",
|
|
166
201
|
base_url="https://modelscope.cn",
|
|
167
|
-
probe_url=
|
|
168
|
-
|
|
202
|
+
probe_url=(
|
|
203
|
+
f"https://modelscope.cn/models/{_HUB_PROBE_REPO}/resolve/master/{_HUB_PROBE_PATH}"
|
|
204
|
+
),
|
|
205
|
+
probe_bytes=MODEL_HUB_PROBE_BYTES,
|
|
169
206
|
),
|
|
170
207
|
),
|
|
171
208
|
"go": (
|
|
@@ -245,7 +282,7 @@ def canonical_host(url_or_host: str) -> str:
|
|
|
245
282
|
host = (
|
|
246
283
|
urllib.parse.urlsplit(url_or_host).hostname if "://" in url_or_host else url_or_host
|
|
247
284
|
) or ""
|
|
248
|
-
low = host.lower()
|
|
285
|
+
low = host.lower().rstrip(".")
|
|
249
286
|
return HOST_ALIASES.get(low, low)
|
|
250
287
|
|
|
251
288
|
|
|
@@ -286,6 +323,107 @@ def network_fingerprint(env: Mapping[str, str]) -> str:
|
|
|
286
323
|
return "proxy:" + hashlib.sha256(canonical).hexdigest()[:16]
|
|
287
324
|
|
|
288
325
|
|
|
326
|
+
def _host_of(url_or_host: str) -> str:
|
|
327
|
+
return canonical_host(url_or_host)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _global_bounce_host(host: str) -> bool:
|
|
331
|
+
return any(host == item or host.endswith("." + item) for item in _GLOBAL_BOUNCE_HOSTS)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _cn_probe_hosts() -> frozenset[str]:
|
|
335
|
+
found: set[str] = set()
|
|
336
|
+
for items in ECOSYSTEMS.values():
|
|
337
|
+
for item in items:
|
|
338
|
+
if item.side != "cn":
|
|
339
|
+
continue
|
|
340
|
+
found.add(_host_of(item.base_url))
|
|
341
|
+
found.add(_host_of(item.probe_url))
|
|
342
|
+
found.discard("")
|
|
343
|
+
return frozenset(found)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def bounced_to_global(original_url: str, final_url: str) -> bool:
|
|
347
|
+
"""True when a China mirror's final host is a global upstream (for example hf-mirror 308).
|
|
348
|
+
|
|
349
|
+
A China CDN redirect (modelscope.cn to cdn-lfs-cn-*.modelscope.cn) is not a bounce.
|
|
350
|
+
"""
|
|
351
|
+
original = _host_of(original_url)
|
|
352
|
+
final = _host_of(final_url)
|
|
353
|
+
if not original or not final or original == final:
|
|
354
|
+
return False
|
|
355
|
+
if original not in _cn_probe_hosts():
|
|
356
|
+
return False
|
|
357
|
+
return _global_bounce_host(final)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def bounced_hosts() -> frozenset[tuple[str, str]]:
|
|
361
|
+
"""(original host, final host) pairs discarded as cross-region bounces. Hosts only."""
|
|
362
|
+
return frozenset(_BOUNCED_HOSTS)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def host_network_fingerprint() -> str:
|
|
366
|
+
"""16-hex digest of the default route and resolver, or "" when neither can be read.
|
|
367
|
+
|
|
368
|
+
Raw gateway, interface address and nameserver bytes are hashed and never returned. A failure
|
|
369
|
+
returns "" so a missing reading cannot invalidate a cache.
|
|
370
|
+
"""
|
|
371
|
+
parts: list[str] = []
|
|
372
|
+
route = _default_route_token()
|
|
373
|
+
if route:
|
|
374
|
+
parts.append("route:" + route)
|
|
375
|
+
dns = _resolver_token()
|
|
376
|
+
if dns:
|
|
377
|
+
parts.append("dns:" + dns)
|
|
378
|
+
if not parts:
|
|
379
|
+
return ""
|
|
380
|
+
return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest()[:16]
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _default_route_token() -> str:
|
|
384
|
+
if sys.platform != "linux":
|
|
385
|
+
return ""
|
|
386
|
+
try:
|
|
387
|
+
text = Path("/proc/net/route").read_text(encoding="utf-8", errors="replace")
|
|
388
|
+
except OSError:
|
|
389
|
+
return ""
|
|
390
|
+
routes: list[tuple[int, str, str]] = []
|
|
391
|
+
for line in text.splitlines()[1:]:
|
|
392
|
+
cols = line.split()
|
|
393
|
+
if len(cols) < 8 or cols[1] != "00000000" or cols[7] != "00000000":
|
|
394
|
+
continue
|
|
395
|
+
try:
|
|
396
|
+
flags = int(cols[3], 16)
|
|
397
|
+
metric = int(cols[6])
|
|
398
|
+
except ValueError:
|
|
399
|
+
continue
|
|
400
|
+
if not (flags & 0x1):
|
|
401
|
+
continue
|
|
402
|
+
iface, gateway = cols[0], cols[2].lower()
|
|
403
|
+
if not (iface and gateway and all(ch.isalnum() or ch in "._-" for ch in iface)):
|
|
404
|
+
continue
|
|
405
|
+
routes.append((metric, iface, gateway))
|
|
406
|
+
if not routes:
|
|
407
|
+
return ""
|
|
408
|
+
routes.sort()
|
|
409
|
+
return ",".join(f"{metric}:{iface}:{gateway}" for metric, iface, gateway in routes)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _resolver_token() -> str:
|
|
413
|
+
try:
|
|
414
|
+
text = Path("/etc/resolv.conf").read_text(encoding="utf-8", errors="replace")
|
|
415
|
+
except OSError:
|
|
416
|
+
return ""
|
|
417
|
+
servers: list[str] = []
|
|
418
|
+
for line in text.splitlines():
|
|
419
|
+
parts = line.split()
|
|
420
|
+
if len(parts) >= 2 and parts[0] == "nameserver" and parts[1] not in servers:
|
|
421
|
+
servers.append(parts[1])
|
|
422
|
+
if len(servers) == 4:
|
|
423
|
+
break
|
|
424
|
+
return ",".join(servers)
|
|
425
|
+
|
|
426
|
+
|
|
289
427
|
def is_loopback_http(url: str) -> bool:
|
|
290
428
|
parts = urllib.parse.urlsplit(url)
|
|
291
429
|
return parts.scheme == "http" and parts.hostname in ("127.0.0.1", "localhost", "::1")
|
|
@@ -305,6 +443,49 @@ def _safe_opener(url: str, *, allow_local_http: bool) -> urllib.request.OpenerDi
|
|
|
305
443
|
return npm_transport.https_opener()
|
|
306
444
|
|
|
307
445
|
|
|
446
|
+
def _response_final_url(response: object, default: str) -> str:
|
|
447
|
+
geturl = getattr(response, "geturl", None)
|
|
448
|
+
if not callable(geturl):
|
|
449
|
+
return default
|
|
450
|
+
try:
|
|
451
|
+
return str(geturl() or default)
|
|
452
|
+
except (TypeError, ValueError):
|
|
453
|
+
return default
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _read_probe_body(response: Any, limit: int, deadline: float) -> tuple[int, bytes]:
|
|
457
|
+
got = 0
|
|
458
|
+
head = b""
|
|
459
|
+
read_fn = getattr(response, "read1", response.read)
|
|
460
|
+
sock = getattr(getattr(getattr(response, "fp", None), "raw", None), "_sock", None)
|
|
461
|
+
while got < limit:
|
|
462
|
+
remaining = deadline - time.monotonic()
|
|
463
|
+
if remaining <= 0:
|
|
464
|
+
break
|
|
465
|
+
if sock is not None:
|
|
466
|
+
with contextlib.suppress(OSError):
|
|
467
|
+
sock.settimeout(max(0.05, remaining))
|
|
468
|
+
chunk = read_fn(min(PROBE_READ_BYTES, limit - got))
|
|
469
|
+
if not chunk:
|
|
470
|
+
break
|
|
471
|
+
if len(head) < 64:
|
|
472
|
+
head += chunk[: 64 - len(head)]
|
|
473
|
+
got += len(chunk)
|
|
474
|
+
return got, head
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _valid_probe_payload(head: bytes, got: int, *, is_gguf: bool, is_binary: bool) -> bool:
|
|
478
|
+
if got <= 0:
|
|
479
|
+
return False
|
|
480
|
+
if is_gguf:
|
|
481
|
+
expected = b"GGUF"[: min(4, got)]
|
|
482
|
+
if head[: len(expected)] != expected:
|
|
483
|
+
return False
|
|
484
|
+
return not (
|
|
485
|
+
is_binary and head.lstrip()[:15].lower().startswith((b"<!doctype html", b"<html", b"<?xml"))
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
|
|
308
489
|
def probe_url(
|
|
309
490
|
url: str,
|
|
310
491
|
max_bytes: int = PROBE_MAX_BYTES,
|
|
@@ -316,6 +497,9 @@ def probe_url(
|
|
|
316
497
|
limit = max(1, max_bytes)
|
|
317
498
|
start = time.monotonic()
|
|
318
499
|
deadline = start + max(0.1, timeout_s)
|
|
500
|
+
url_path = urllib.parse.urlsplit(url).path.lower()
|
|
501
|
+
is_gguf = url_path.endswith(".gguf")
|
|
502
|
+
is_binary = is_gguf or url_path.endswith(".tgz")
|
|
319
503
|
request = urllib.request.Request(
|
|
320
504
|
url,
|
|
321
505
|
headers={
|
|
@@ -329,27 +513,36 @@ def probe_url(
|
|
|
329
513
|
status = getattr(response, "status", 200)
|
|
330
514
|
if not 200 <= status < 300:
|
|
331
515
|
return None
|
|
516
|
+
final_url = _response_final_url(response, url)
|
|
517
|
+
final_host = _host_of(final_url)
|
|
518
|
+
if bounced_to_global(url, final_url):
|
|
519
|
+
_BOUNCED_HOSTS.add((_host_of(url), final_host))
|
|
520
|
+
return None
|
|
521
|
+
if is_gguf and status != 206:
|
|
522
|
+
return None
|
|
523
|
+
ctype = str(getattr(response, "headers", {}).get("Content-Type", "")).lower()
|
|
524
|
+
if is_binary and ("text/html" in ctype or "application/xhtml" in ctype):
|
|
525
|
+
return None
|
|
332
526
|
first_byte_at = time.monotonic()
|
|
333
|
-
got =
|
|
334
|
-
read_fn = getattr(response, "read1", response.read)
|
|
335
|
-
while got < limit and time.monotonic() < deadline:
|
|
336
|
-
chunk = read_fn(min(PROBE_READ_BYTES, limit - got))
|
|
337
|
-
if not chunk:
|
|
338
|
-
break
|
|
339
|
-
got += len(chunk)
|
|
527
|
+
got, head = _read_probe_body(response, limit, deadline)
|
|
340
528
|
except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
|
|
341
529
|
return None
|
|
342
|
-
if got
|
|
530
|
+
if not _valid_probe_payload(head, got, is_gguf=is_gguf, is_binary=is_binary):
|
|
343
531
|
return None
|
|
344
|
-
|
|
532
|
+
total_s = max(1e-3, time.monotonic() - start)
|
|
345
533
|
latency_ms = max(0.0, (first_byte_at - start) * 1000.0)
|
|
346
534
|
return ProbeResult(
|
|
347
|
-
bytes_per_second=got /
|
|
535
|
+
bytes_per_second=got / total_s,
|
|
348
536
|
latency_ms=latency_ms,
|
|
349
537
|
bytes_read=got,
|
|
538
|
+
final_host=final_host,
|
|
350
539
|
)
|
|
351
540
|
|
|
352
541
|
|
|
542
|
+
# Stable alias: tests replace ``probe_url`` so offline runs never leave the machine.
|
|
543
|
+
measure_probe = probe_url
|
|
544
|
+
|
|
545
|
+
|
|
353
546
|
def probe_candidates(
|
|
354
547
|
candidates: Sequence[MirrorCandidate],
|
|
355
548
|
*,
|
|
@@ -380,8 +573,11 @@ def probe_candidates(
|
|
|
380
573
|
|
|
381
574
|
ranked: list[tuple[float, int, MeasuredCandidate]] = []
|
|
382
575
|
for index, (item, result) in enumerate(zip(candidates, results, strict=False)):
|
|
383
|
-
if result is
|
|
384
|
-
|
|
576
|
+
if result is None or result.bounced or result.bytes_per_second <= 0:
|
|
577
|
+
if result is not None and result.bounced:
|
|
578
|
+
_BOUNCED_HOSTS.add((_host_of(item.probe_url), result.final_host or "global"))
|
|
579
|
+
continue
|
|
580
|
+
ranked.append((-result.bytes_per_second, index, MeasuredCandidate(item, result)))
|
|
385
581
|
ranked.sort(key=lambda entry: (entry[0], entry[1]))
|
|
386
582
|
return [entry[2] for entry in ranked]
|
|
387
583
|
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import contextlib
|
|
5
6
|
import http.client
|
|
6
7
|
import os
|
|
7
8
|
import queue
|
|
@@ -61,6 +62,7 @@ def _redirect_target(url: str, location: str, hops: int) -> str:
|
|
|
61
62
|
class HttpsRedirect(urllib.request.HTTPRedirectHandler):
|
|
62
63
|
max_redirections = 5
|
|
63
64
|
max_repeats = 5
|
|
65
|
+
http_error_308 = urllib.request.HTTPRedirectHandler.http_error_307
|
|
64
66
|
|
|
65
67
|
def redirect_request(
|
|
66
68
|
self,
|
|
@@ -73,7 +75,8 @@ class HttpsRedirect(urllib.request.HTTPRedirectHandler):
|
|
|
73
75
|
) -> urllib.request.Request | None:
|
|
74
76
|
hops = getattr(req, "_npm_redirect_hops", 0)
|
|
75
77
|
target = _redirect_target(req.full_url, newurl, hops)
|
|
76
|
-
|
|
78
|
+
super_code = 307 if code == 308 and req.get_method() in ("GET", "HEAD") else code
|
|
79
|
+
redirected = super().redirect_request(req, fp, super_code, msg, headers, target)
|
|
77
80
|
if redirected is not None:
|
|
78
81
|
redirected.__dict__["_npm_redirect_hops"] = hops + 1
|
|
79
82
|
return redirected
|
|
@@ -122,45 +125,53 @@ def package_url(name: str, version: str, region: str, env: Mapping[str, str]) ->
|
|
|
122
125
|
|
|
123
126
|
|
|
124
127
|
def _probe(url: str, results: queue.Queue[bool]) -> None:
|
|
128
|
+
"""Read 256 KiB through ``https_opener`` so ``HTTP_PROXY`` / ``HTTPS_PROXY`` / ``NO_PROXY`` apply."""
|
|
125
129
|
deadline = time.monotonic() + 5
|
|
126
130
|
try:
|
|
127
131
|
check_url(url)
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
132
|
+
remaining = deadline - time.monotonic()
|
|
133
|
+
if remaining <= 0:
|
|
134
|
+
results.put(False)
|
|
135
|
+
return
|
|
136
|
+
request = urllib.request.Request(
|
|
137
|
+
url,
|
|
138
|
+
headers={"Range": "bytes=0-262143", "User-Agent": "localmodels-npm-probe"},
|
|
139
|
+
)
|
|
140
|
+
with https_opener().open(request, timeout=remaining) as response:
|
|
141
|
+
status = getattr(response, "status", 200)
|
|
142
|
+
if not 200 <= status < 300:
|
|
143
|
+
results.put(False)
|
|
144
|
+
return
|
|
145
|
+
ctype = str(getattr(response, "headers", {}).get("Content-Type", "")).lower()
|
|
146
|
+
if "text/html" in ctype or "application/xhtml" in ctype:
|
|
147
|
+
results.put(False)
|
|
148
|
+
return
|
|
149
|
+
size = 0
|
|
150
|
+
eof = False
|
|
151
|
+
head = b""
|
|
152
|
+
read_fn = getattr(response, "read1", response.read)
|
|
153
|
+
sock = getattr(getattr(getattr(response, "fp", None), "raw", None), "_sock", None)
|
|
154
|
+
while size < 262144:
|
|
155
|
+
remaining = deadline - time.monotonic()
|
|
156
|
+
if remaining <= 0:
|
|
157
|
+
break
|
|
158
|
+
if sock is not None:
|
|
159
|
+
with contextlib.suppress(OSError):
|
|
160
|
+
sock.settimeout(max(0.05, remaining))
|
|
161
|
+
chunk = read_fn(min(65536, 262144 - size))
|
|
162
|
+
if not chunk:
|
|
163
|
+
eof = True
|
|
147
164
|
break
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
if connection.sock:
|
|
154
|
-
connection.sock.settimeout(remaining)
|
|
155
|
-
chunk = response.read1(min(65536, 262144 - size))
|
|
156
|
-
if not chunk:
|
|
157
|
-
break
|
|
158
|
-
size += len(chunk)
|
|
159
|
-
results.put(True)
|
|
165
|
+
if len(head) < 64:
|
|
166
|
+
head += chunk[: 64 - len(head)]
|
|
167
|
+
size += len(chunk)
|
|
168
|
+
if head.lstrip()[:15].lower().startswith((b"<!doctype html", b"<html", b"<?xml")):
|
|
169
|
+
results.put(False)
|
|
160
170
|
return
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
171
|
+
ok = size >= 262144 or (eof and size > 0 and time.monotonic() < deadline)
|
|
172
|
+
results.put(ok)
|
|
173
|
+
return
|
|
174
|
+
except (OSError, http.client.HTTPException, urllib.error.URLError, ValueError, UnsafeRedirect):
|
|
164
175
|
pass
|
|
165
176
|
results.put(False)
|
|
166
177
|
|
|
@@ -130,7 +130,14 @@ def hub_get(
|
|
|
130
130
|
raise HubUnreachableError(failures) from exc
|
|
131
131
|
raise
|
|
132
132
|
if index:
|
|
133
|
-
region.
|
|
133
|
+
target_side = region.side_of_endpoint(endpoint)
|
|
134
|
+
# hf-mirror is not an independent CN source; failing over from hf-mirror to
|
|
135
|
+
# huggingface.co in cn must not flip the download region to global.
|
|
136
|
+
only_hf_mirror_failed = target_side == "global" and all(
|
|
137
|
+
prev.rstrip("/") == region.HF_MIRROR for prev in endpoints[:index]
|
|
138
|
+
)
|
|
139
|
+
if not only_hf_mirror_failed:
|
|
140
|
+
region.fallback_to(target_side)
|
|
134
141
|
return doc
|
|
135
142
|
raise AssertionError("unreachable Hub loop")
|
|
136
143
|
|