infixspeed-cli 0.0.16__py3-none-any.whl
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.
- infix_cli/__init__.py +5 -0
- infix_cli/__main__.py +6 -0
- infix_cli/agent-guide.txt +71 -0
- infix_cli/cli_framework.py +96 -0
- infix_cli/command_contract.py +157 -0
- infix_cli/commands/__init__.py +1 -0
- infix_cli/commands/_artifacts.py +142 -0
- infix_cli/commands/_comparison.py +443 -0
- infix_cli/commands/_confirm.py +26 -0
- infix_cli/commands/_control.py +290 -0
- infix_cli/commands/_create.py +351 -0
- infix_cli/commands/_create_output.py +139 -0
- infix_cli/commands/_delete.py +288 -0
- infix_cli/commands/_download.py +459 -0
- infix_cli/commands/_fusion_common.py +191 -0
- infix_cli/commands/_fusion_config.py +394 -0
- infix_cli/commands/_fusion_feedback.py +319 -0
- infix_cli/commands/_fusion_tasks.py +507 -0
- infix_cli/commands/_fusion_tensorboard.py +132 -0
- infix_cli/commands/_jobs.py +312 -0
- infix_cli/commands/_logs.py +210 -0
- infix_cli/commands/_publish.py +123 -0
- infix_cli/commands/_register.py +600 -0
- infix_cli/commands/_register_output.py +231 -0
- infix_cli/commands/_storage_tree.py +62 -0
- infix_cli/commands/admin.py +668 -0
- infix_cli/commands/asset.py +2012 -0
- infix_cli/commands/auth.py +246 -0
- infix_cli/commands/deploy.py +850 -0
- infix_cli/commands/evaluation.py +360 -0
- infix_cli/commands/examples.py +138 -0
- infix_cli/commands/fusion.py +1842 -0
- infix_cli/commands/merge.py +709 -0
- infix_cli/commands/resource.py +127 -0
- infix_cli/commands/spark.py +347 -0
- infix_cli/commands/storage.py +329 -0
- infix_cli/commands/training.py +748 -0
- infix_cli/config.py +311 -0
- infix_cli/config_input.py +217 -0
- infix_cli/context.py +84 -0
- infix_cli/discovery.py +459 -0
- infix_cli/domain/__init__.py +1 -0
- infix_cli/domain/dto/__init__.py +6 -0
- infix_cli/domain/dto/admin.py +413 -0
- infix_cli/domain/dto/asset.py +390 -0
- infix_cli/domain/dto/common.py +136 -0
- infix_cli/domain/dto/evaluation.py +296 -0
- infix_cli/domain/dto/logs.py +98 -0
- infix_cli/domain/dto/resource.py +108 -0
- infix_cli/domain/dto/serving.py +156 -0
- infix_cli/domain/dto/spark.py +241 -0
- infix_cli/domain/dto/storage.py +75 -0
- infix_cli/domain/dto/training.py +272 -0
- infix_cli/domain/enums.py +359 -0
- infix_cli/domain/hyperparams.py +190 -0
- infix_cli/domain/refs.py +108 -0
- infix_cli/domain/resolve.py +619 -0
- infix_cli/errors.py +158 -0
- infix_cli/example_data/__init__.py +1 -0
- infix_cli/example_data/fusion/README.md +128 -0
- infix_cli/example_data/fusion/fusion.json +149 -0
- infix_cli/example_data/fusion/prompts/code.jsonl +16 -0
- infix_cli/example_data/fusion/prompts/math.jsonl +16 -0
- infix_cli/example_data/fusion.zip +0 -0
- infix_cli/example_data/merge/README.md +89 -0
- infix_cli/example_data/merge/merge.json +26 -0
- infix_cli/example_data/merge.zip +0 -0
- infix_cli/http/__init__.py +1 -0
- infix_cli/http/browser_auth.py +160 -0
- infix_cli/http/client.py +575 -0
- infix_cli/http/pagination.py +84 -0
- infix_cli/http/upload.py +254 -0
- infix_cli/main.py +432 -0
- infix_cli/pipeline_config_schema.py +122 -0
- infix_cli/render/__init__.py +79 -0
- infix_cli/render/json_out.py +123 -0
- infix_cli/render/progress.py +62 -0
- infix_cli/render/text.py +233 -0
- infix_cli/update_check.py +177 -0
- infix_cli/waiter.py +93 -0
- infix_cli/workspace.py +158 -0
- infixspeed_cli-0.0.16.dist-info/METADATA +58 -0
- infixspeed_cli-0.0.16.dist-info/RECORD +85 -0
- infixspeed_cli-0.0.16.dist-info/WHEEL +4 -0
- infixspeed_cli-0.0.16.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"""storage download: one file, or a folder fetched file by file.
|
|
2
|
+
|
|
3
|
+
Every download endpoint serves one file at a time — a folder is a 400 — so:
|
|
4
|
+
|
|
5
|
+
* a folder is walked with ``/storage/list`` and fetched file by file;
|
|
6
|
+
* progress totals come from the listing's sizes, not from the response;
|
|
7
|
+
* a complete file is reused only when its local fingerprint and remote ETag
|
|
8
|
+
still match the recorded download;
|
|
9
|
+
* each transfer writes to a private temporary file and publishes it atomically.
|
|
10
|
+
An interrupted file with a verified ETag can be resumed with Range and If-Range.
|
|
11
|
+
|
|
12
|
+
Bytes come from the platform's download service, not the backend: each file
|
|
13
|
+
gets a short-lived ticket from ``<endpoint>-ticket`` first (see ``_Source``).
|
|
14
|
+
Older backends without that endpoint are asked directly, as before.
|
|
15
|
+
|
|
16
|
+
Asset version downloads (``asset * download``) and training outputs share this
|
|
17
|
+
module; only the endpoint and its parameters differ.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import tempfile
|
|
26
|
+
import threading
|
|
27
|
+
from contextlib import suppress
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from infix_cli import render
|
|
33
|
+
from infix_cli.commands import _storage_tree
|
|
34
|
+
from infix_cli.commands._storage_tree import RemoteFile
|
|
35
|
+
from infix_cli.config import cache_dir
|
|
36
|
+
from infix_cli.errors import ApiError, CliError, NotFoundError, UsageError
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Outcome:
|
|
41
|
+
remote: str
|
|
42
|
+
local: Path
|
|
43
|
+
size: int | None
|
|
44
|
+
status: str # downloaded | skipped | failed
|
|
45
|
+
error: str = ""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def download(
|
|
49
|
+
run: Any,
|
|
50
|
+
path: str,
|
|
51
|
+
*,
|
|
52
|
+
dest: str | None,
|
|
53
|
+
owner: str | None,
|
|
54
|
+
overwrite: bool,
|
|
55
|
+
concurrency: int,
|
|
56
|
+
) -> None:
|
|
57
|
+
remote = _clean(path)
|
|
58
|
+
client = run.client()
|
|
59
|
+
target_dir = Path(dest or ".").expanduser()
|
|
60
|
+
|
|
61
|
+
# Paths on disk are relative to the named item's parent, so downloading
|
|
62
|
+
# Upload/data gives ./data/... and Upload/a.jsonl gives ./a.jsonl.
|
|
63
|
+
base = remote.rpartition("/")[0]
|
|
64
|
+
if owner:
|
|
65
|
+
# /storage/list browses only the caller's own tree, so another member's
|
|
66
|
+
# path cannot be walked or sized; it is fetched as a single file and the
|
|
67
|
+
# backend says so if it is a folder.
|
|
68
|
+
files = [RemoteFile(remote, None)]
|
|
69
|
+
else:
|
|
70
|
+
entry = _storage_tree.stat(client, remote, dir_size=False)
|
|
71
|
+
if entry is None:
|
|
72
|
+
raise NotFoundError(
|
|
73
|
+
f'Path "{remote}" does not exist.',
|
|
74
|
+
'Run "infix storage list" to browse.',
|
|
75
|
+
)
|
|
76
|
+
if entry.get("is_dir"):
|
|
77
|
+
files = list(_storage_tree.walk(client, remote))
|
|
78
|
+
if not files:
|
|
79
|
+
raise UsageError(f'Folder "{remote}" contains no files.')
|
|
80
|
+
else:
|
|
81
|
+
size = entry.get("size")
|
|
82
|
+
files = [RemoteFile(remote, int(size) if isinstance(size, int) else None)]
|
|
83
|
+
|
|
84
|
+
plan = [(f, target_dir / _relative(f.path, base)) for f in files]
|
|
85
|
+
run_plan(run, client, plan, params={"owner_user_id": owner},
|
|
86
|
+
overwrite=overwrite, concurrency=concurrency)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def run_plan(
|
|
90
|
+
run, client, plan, *,
|
|
91
|
+
endpoint: str = "/storage/download",
|
|
92
|
+
params: dict | None = None,
|
|
93
|
+
overwrite: bool,
|
|
94
|
+
concurrency: int,
|
|
95
|
+
) -> None:
|
|
96
|
+
"""Fetch ``(RemoteFile, local Path)`` pairs and report the outcome.
|
|
97
|
+
|
|
98
|
+
Each file is requested from ``endpoint`` with ``path`` set to its
|
|
99
|
+
``RemoteFile.path`` plus ``params``.
|
|
100
|
+
"""
|
|
101
|
+
outcomes = _fetch_all(run, client, plan, endpoint=endpoint, params=params or {},
|
|
102
|
+
overwrite=overwrite, concurrency=concurrency)
|
|
103
|
+
_report(run, outcomes)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _fetch_all(run, client, plan, *, endpoint, params, overwrite, concurrency) -> list[Outcome]:
|
|
107
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
108
|
+
|
|
109
|
+
single = len(plan) == 1
|
|
110
|
+
if not single:
|
|
111
|
+
total = sum(f.size or 0 for f, _ in plan)
|
|
112
|
+
from infix_cli.domain.dto.common import format_bytes
|
|
113
|
+
|
|
114
|
+
render.message(run, f"Downloading {len(plan)} files ({format_bytes(total)})...", symbol="")
|
|
115
|
+
|
|
116
|
+
# Ctrl-C only reaches the main thread. Without this, leaving the pool waits
|
|
117
|
+
# for every worker to finish its file, which for a model shard is minutes.
|
|
118
|
+
stop = threading.Event()
|
|
119
|
+
source = _Source(client, endpoint, params)
|
|
120
|
+
|
|
121
|
+
def fetch(item) -> Outcome:
|
|
122
|
+
remote_file, local = item
|
|
123
|
+
return _fetch_one(run, client, remote_file, local, source=source,
|
|
124
|
+
overwrite=overwrite, show_progress=single, stop=stop)
|
|
125
|
+
|
|
126
|
+
outcomes: list[Outcome] = []
|
|
127
|
+
pool = ThreadPoolExecutor(max_workers=1 if single else concurrency)
|
|
128
|
+
try:
|
|
129
|
+
for outcome in pool.map(fetch, plan):
|
|
130
|
+
outcomes.append(outcome)
|
|
131
|
+
if not single and run.output != "json" and not run.quiet:
|
|
132
|
+
if outcome.status == "downloaded":
|
|
133
|
+
print(f" {outcome.local}", flush=True)
|
|
134
|
+
except KeyboardInterrupt:
|
|
135
|
+
stop.set()
|
|
136
|
+
pool.shutdown(wait=True, cancel_futures=True)
|
|
137
|
+
raise
|
|
138
|
+
pool.shutdown()
|
|
139
|
+
return outcomes
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class _Source:
|
|
143
|
+
"""Where one file's bytes come from: the download service, or the backend itself.
|
|
144
|
+
|
|
145
|
+
Large files are not streamed by the backend: a slow client on a multi-GB
|
|
146
|
+
stream stalls every API behind the same gateway entry. Each file is asked
|
|
147
|
+
for a short-lived ticket (``<endpoint>-ticket``) and fetched from the
|
|
148
|
+
download service at the path it names. A backend without that endpoint
|
|
149
|
+
(older release, or storage it cannot hand to the download service) is
|
|
150
|
+
asked directly, as before; once one file finds that out, the rest of the
|
|
151
|
+
run does not ask again.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(self, client, endpoint: str, params: dict) -> None:
|
|
155
|
+
self._client = client
|
|
156
|
+
self._endpoint = endpoint
|
|
157
|
+
self._params = params
|
|
158
|
+
self._ticket_endpoint = endpoint + "-ticket" if endpoint.endswith("/download") else None
|
|
159
|
+
|
|
160
|
+
def locate(self, remote_path: str) -> tuple[str, dict]:
|
|
161
|
+
"""``(url or API path, query params)`` to GET for this file, right now.
|
|
162
|
+
|
|
163
|
+
Asked per file and per attempt: a ticket is short-lived, so a resumed
|
|
164
|
+
download gets a fresh one rather than reusing the last run's.
|
|
165
|
+
"""
|
|
166
|
+
query = {"path": remote_path, **self._params}
|
|
167
|
+
ticket_endpoint = self._ticket_endpoint
|
|
168
|
+
if ticket_endpoint is not None:
|
|
169
|
+
ticket = self._client.post_if_supported(ticket_endpoint, params=query)
|
|
170
|
+
if ticket is not None:
|
|
171
|
+
return self._client.base_url + ticket["path"], {}
|
|
172
|
+
self._ticket_endpoint = None
|
|
173
|
+
return self._endpoint, query
|
|
174
|
+
|
|
175
|
+
def cache_key(self, run: Any, remote_path: str, local: Path) -> str:
|
|
176
|
+
# 不使用短期票据作为文件标识,也不把凭据写入缓存。
|
|
177
|
+
profile = getattr(run, "profile", None)
|
|
178
|
+
identity = [
|
|
179
|
+
self._client.base_url, getattr(self._client, "workspace_id", ""),
|
|
180
|
+
getattr(profile, "api_key", ""), self._endpoint, self._params,
|
|
181
|
+
remote_path, str(local.absolute()),
|
|
182
|
+
]
|
|
183
|
+
return hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class _Stopped(BaseException):
|
|
187
|
+
"""Raised inside a worker between chunks once the user pressed Ctrl-C.
|
|
188
|
+
|
|
189
|
+
A BaseException, so no ``except Exception`` on the way out treats it as a
|
|
190
|
+
failed file and deletes the partial download the next run resumes from.
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _file_stamp(path: Path) -> list[int]:
|
|
195
|
+
try:
|
|
196
|
+
info = path.stat()
|
|
197
|
+
except FileNotFoundError:
|
|
198
|
+
return []
|
|
199
|
+
return [info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _strong_etag(value: str | None) -> str | None:
|
|
203
|
+
return value if isinstance(value, str) and value.startswith('"') and value.endswith('"') else None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _read_state(path: Path) -> dict:
|
|
207
|
+
try:
|
|
208
|
+
state = json.loads(path.read_text(encoding="utf-8"))
|
|
209
|
+
except (OSError, ValueError):
|
|
210
|
+
return {}
|
|
211
|
+
if not isinstance(state, dict) or not _strong_etag(state.get("etag")):
|
|
212
|
+
return {}
|
|
213
|
+
stamp = state.get("stamp")
|
|
214
|
+
return state if isinstance(stamp, list) and len(stamp) == 5 else {}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _publish(working: Path, target: Path, state_path: Path, *, etag: str | None, partial: bool) -> None:
|
|
218
|
+
before = _file_stamp(working)
|
|
219
|
+
working.replace(target)
|
|
220
|
+
if etag is None:
|
|
221
|
+
return
|
|
222
|
+
stamp = _file_stamp(target)
|
|
223
|
+
# 重命名会改变 ctime。其余字段匹配,才记录刚发布的那个文件。
|
|
224
|
+
if not stamp or stamp[:-1] != before[:-1]:
|
|
225
|
+
return
|
|
226
|
+
with suppress(OSError):
|
|
227
|
+
state_path.parent.mkdir(parents=True, exist_ok=True)
|
|
228
|
+
with tempfile.NamedTemporaryFile(
|
|
229
|
+
mode="w", encoding="utf-8", dir=state_path.parent, delete=False,
|
|
230
|
+
) as handle:
|
|
231
|
+
temporary = Path(handle.name)
|
|
232
|
+
try:
|
|
233
|
+
json.dump({"etag": etag, "partial": partial, "stamp": stamp}, handle)
|
|
234
|
+
handle.close()
|
|
235
|
+
temporary.replace(state_path)
|
|
236
|
+
finally:
|
|
237
|
+
temporary.unlink(missing_ok=True)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _fetch_one(run, client, remote_file: RemoteFile, local: Path, *, source: _Source,
|
|
241
|
+
overwrite, show_progress: bool, stop: threading.Event | None = None) -> Outcome:
|
|
242
|
+
from infix_cli.http.client import TransferInterrupted
|
|
243
|
+
from infix_cli.render import progress
|
|
244
|
+
|
|
245
|
+
expected = remote_file.size
|
|
246
|
+
try:
|
|
247
|
+
url, query = source.locate(remote_file.path)
|
|
248
|
+
except CliError as exc:
|
|
249
|
+
return Outcome(remote_file.path, local, expected, "failed", _reason(exc))
|
|
250
|
+
|
|
251
|
+
key = source.cache_key(run, remote_file.path, local)
|
|
252
|
+
state_path = cache_dir() / "downloads" / f"{key}.json"
|
|
253
|
+
partial = local.with_name(f".infix-{key}.part")
|
|
254
|
+
state = {} if overwrite else _read_state(state_path)
|
|
255
|
+
stamp = state.get("stamp")
|
|
256
|
+
offset = 0
|
|
257
|
+
etag = None
|
|
258
|
+
skipped = False
|
|
259
|
+
working = None
|
|
260
|
+
tracker = (
|
|
261
|
+
progress.tracker(run, local.name, expected, verb="Downloading")
|
|
262
|
+
if show_progress and expected else None
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
def on_etag(value: str | None) -> bool:
|
|
266
|
+
nonlocal etag, skipped
|
|
267
|
+
etag = _strong_etag(value)
|
|
268
|
+
skipped = bool(
|
|
269
|
+
etag and etag == state.get("etag") and state.get("partial") is False
|
|
270
|
+
and stamp == _file_stamp(local) and (expected is None or stamp[2] == expected)
|
|
271
|
+
)
|
|
272
|
+
return not skipped
|
|
273
|
+
|
|
274
|
+
def on_chunk(n: int) -> None:
|
|
275
|
+
if stop is not None and stop.is_set():
|
|
276
|
+
raise _Stopped
|
|
277
|
+
if tracker is not None:
|
|
278
|
+
tracker(n)
|
|
279
|
+
|
|
280
|
+
try:
|
|
281
|
+
local.parent.mkdir(parents=True, exist_ok=True)
|
|
282
|
+
fd, temporary = tempfile.mkstemp(prefix=".infix-download-", suffix=".part", dir=local.parent)
|
|
283
|
+
working = Path(temporary)
|
|
284
|
+
os.close(fd)
|
|
285
|
+
with suppress(FileNotFoundError):
|
|
286
|
+
# 原子取走断点,避免两个进程同时向它追加。
|
|
287
|
+
before = _file_stamp(partial)
|
|
288
|
+
partial.replace(working)
|
|
289
|
+
if state.get("partial") is True and stamp == before and _file_stamp(working)[:-1] == stamp[:-1]:
|
|
290
|
+
if stamp[2] > 0 and (expected is None or stamp[2] < expected):
|
|
291
|
+
offset = stamp[2]
|
|
292
|
+
etag = state["etag"]
|
|
293
|
+
if tracker is not None and offset:
|
|
294
|
+
tracker(offset)
|
|
295
|
+
with working.open("ab" if offset else "wb") as handle:
|
|
296
|
+
size = client.download(
|
|
297
|
+
url, handle, params=query, on_chunk=on_chunk, on_etag=on_etag,
|
|
298
|
+
offset=offset, if_range=etag,
|
|
299
|
+
)
|
|
300
|
+
if skipped:
|
|
301
|
+
return Outcome(remote_file.path, local, stamp[2], "skipped")
|
|
302
|
+
if expected is not None and size != expected:
|
|
303
|
+
return Outcome(
|
|
304
|
+
remote_file.path, local, expected, "failed",
|
|
305
|
+
f"received {size} bytes, expected {expected}",
|
|
306
|
+
)
|
|
307
|
+
_publish(working, local, state_path, etag=etag, partial=False)
|
|
308
|
+
except (TransferInterrupted, _Stopped) as exc:
|
|
309
|
+
if working is not None and etag:
|
|
310
|
+
with suppress(OSError):
|
|
311
|
+
if _file_stamp(working)[2]:
|
|
312
|
+
_publish(working, partial, state_path, etag=etag, partial=True)
|
|
313
|
+
if isinstance(exc, _Stopped):
|
|
314
|
+
raise
|
|
315
|
+
return Outcome(remote_file.path, local, expected, "failed", exc.message)
|
|
316
|
+
except CliError as exc:
|
|
317
|
+
return Outcome(remote_file.path, local, expected, "failed", _reason(exc))
|
|
318
|
+
except OSError as exc:
|
|
319
|
+
return Outcome(remote_file.path, local, expected, "failed", str(exc))
|
|
320
|
+
finally:
|
|
321
|
+
if working is not None:
|
|
322
|
+
with suppress(OSError):
|
|
323
|
+
working.unlink(missing_ok=True)
|
|
324
|
+
if tracker is not None:
|
|
325
|
+
progress.finish(run)
|
|
326
|
+
return Outcome(remote_file.path, local, size, "downloaded")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _reason(exc: CliError) -> str:
|
|
330
|
+
if "is a directory" in exc.message.lower():
|
|
331
|
+
return f"{exc.message} (another member's folder cannot be listed; download its files one by one)"
|
|
332
|
+
return exc.message
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _report(run, outcomes: list[Outcome]) -> None:
|
|
336
|
+
done = [o for o in outcomes if o.status == "downloaded"]
|
|
337
|
+
skipped = [o for o in outcomes if o.status == "skipped"]
|
|
338
|
+
failed = [o for o in outcomes if o.status == "failed"]
|
|
339
|
+
|
|
340
|
+
if run.output == "json":
|
|
341
|
+
from infix_cli.render import json_out
|
|
342
|
+
|
|
343
|
+
def row(o: Outcome) -> dict:
|
|
344
|
+
return {"remote_path": o.remote, "local_path": str(o.local), "size_bytes": o.size}
|
|
345
|
+
|
|
346
|
+
json_out.print_raw({
|
|
347
|
+
"downloaded": [row(o) for o in done],
|
|
348
|
+
"skipped": [row(o) for o in skipped],
|
|
349
|
+
"failed": [{**row(o), "error": o.error} for o in failed],
|
|
350
|
+
"total_files": len(done),
|
|
351
|
+
"total_bytes": sum(o.size or 0 for o in done),
|
|
352
|
+
})
|
|
353
|
+
else:
|
|
354
|
+
from infix_cli.domain.dto.common import format_bytes
|
|
355
|
+
from infix_cli.render import text
|
|
356
|
+
|
|
357
|
+
if len(outcomes) == 1 and done:
|
|
358
|
+
render.message(run, f"Downloaded {done[0].remote} → {done[0].local}")
|
|
359
|
+
elif done or skipped:
|
|
360
|
+
line = f"Downloaded {len(done)} file(s) ({format_bytes(sum(o.size or 0 for o in done))})"
|
|
361
|
+
if skipped:
|
|
362
|
+
line += f"; skipped {len(skipped)} already up to date"
|
|
363
|
+
render.message(run, line + ".")
|
|
364
|
+
for o in failed:
|
|
365
|
+
text.print_warning(run, f'Not downloaded: "{o.remote}" — {o.error}')
|
|
366
|
+
if failed:
|
|
367
|
+
raise ApiError(
|
|
368
|
+
f"{len(failed)} of {len(outcomes)} file(s) could not be downloaded.",
|
|
369
|
+
"Re-run the same command to retry; verified files can be reused.",
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _clean(path: str) -> str:
|
|
374
|
+
value = path.strip().strip("/")
|
|
375
|
+
if not value:
|
|
376
|
+
raise UsageError("Name a file or folder to download.")
|
|
377
|
+
if any(segment == ".." for segment in value.split("/")):
|
|
378
|
+
raise UsageError(f'Invalid path "{path}": path segments may not be "..".')
|
|
379
|
+
return value
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _relative(remote: str, base: str) -> str:
|
|
383
|
+
return remote[len(base):].lstrip("/") if base and remote.startswith(base + "/") else remote
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# ── asset versions ──────────────────────────────────────────────────────────
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def download_asset(
|
|
390
|
+
run: Any,
|
|
391
|
+
kind: str,
|
|
392
|
+
plain: str,
|
|
393
|
+
scope: str,
|
|
394
|
+
*,
|
|
395
|
+
version: str | None,
|
|
396
|
+
sub_path: str | None,
|
|
397
|
+
dest: str | None,
|
|
398
|
+
overwrite: bool,
|
|
399
|
+
concurrency: int,
|
|
400
|
+
) -> None:
|
|
401
|
+
"""``asset <kind> download``: one version's files, file by file.
|
|
402
|
+
|
|
403
|
+
Listed with the version's ``files`` endpoint and fetched from its
|
|
404
|
+
``files/download``, which serves whole files with Range support — so an
|
|
405
|
+
interrupted download of a large model resumes byte by byte.
|
|
406
|
+
"""
|
|
407
|
+
from infix_cli.domain import enums, resolve
|
|
408
|
+
|
|
409
|
+
client = run.client()
|
|
410
|
+
asset = resolve.find_asset(client, kind, plain, scope)
|
|
411
|
+
asset_id = str(asset["id"])
|
|
412
|
+
versions = resolve.list_versions(client, kind, asset_id)
|
|
413
|
+
if version:
|
|
414
|
+
target = next((v for v in versions if str(v.get("version_number")) == version), None)
|
|
415
|
+
if target is None:
|
|
416
|
+
raise NotFoundError(
|
|
417
|
+
f'{kind.capitalize()} "{plain}" has no version "{version}".',
|
|
418
|
+
f'See "infix asset {kind} versions {plain}".',
|
|
419
|
+
)
|
|
420
|
+
else:
|
|
421
|
+
target = next(
|
|
422
|
+
(v for v in versions if enums.ASSET_STATUS.to_cli(v.get("status")) == "available"),
|
|
423
|
+
None,
|
|
424
|
+
)
|
|
425
|
+
if target is None:
|
|
426
|
+
raise NotFoundError(
|
|
427
|
+
f'{kind.capitalize()} "{plain}" has no available version to download.',
|
|
428
|
+
f'See "infix asset {kind} versions {plain}".',
|
|
429
|
+
)
|
|
430
|
+
status = enums.ASSET_STATUS.to_cli(target.get("status"))
|
|
431
|
+
number = str(target.get("version_number") or "")
|
|
432
|
+
if status == "registering":
|
|
433
|
+
raise UsageError(
|
|
434
|
+
f'Version "{number}" of {kind} "{plain}" is still registering.',
|
|
435
|
+
f'Wait for it with "infix asset {kind} wait {plain} --version {number}".',
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
base = f"/assets/{resolve.asset_path(kind)}/{asset_id}/versions/{target['id']}/files"
|
|
439
|
+
sub = (sub_path or "").strip().strip("/")
|
|
440
|
+
if any(segment == ".." for segment in sub.split("/")):
|
|
441
|
+
raise UsageError(f'Invalid --path "{sub_path}": path segments may not be "..".')
|
|
442
|
+
entry = _storage_tree.stat(client, sub, dir_size=False, list_path=base) if sub else None
|
|
443
|
+
if sub and entry is None:
|
|
444
|
+
raise NotFoundError(
|
|
445
|
+
f'"{sub}" not found in version "{number}" of {kind} "{plain}".',
|
|
446
|
+
f'Browse it with "infix asset {kind} get {plain} --version {number}".',
|
|
447
|
+
)
|
|
448
|
+
if entry is not None and not entry.get("is_dir"):
|
|
449
|
+
size = entry.get("size")
|
|
450
|
+
files = [RemoteFile(sub, int(size) if isinstance(size, int) else None)]
|
|
451
|
+
else:
|
|
452
|
+
files = list(_storage_tree.walk(client, sub, list_path=base))
|
|
453
|
+
if not files:
|
|
454
|
+
raise UsageError(f'Nothing to download in version "{number}" of {kind} "{plain}".')
|
|
455
|
+
|
|
456
|
+
root = Path(dest or ".").expanduser() / f"{plain}-{number}"
|
|
457
|
+
plan = [(f, root / f.path) for f in files]
|
|
458
|
+
run_plan(run, client, plan, endpoint=f"{base}/download", overwrite=overwrite,
|
|
459
|
+
concurrency=concurrency)
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Merge/Fusion 共用引用解析、结果输出和执行状态处理。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from shlex import join as shell_join
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
from infix_cli import render
|
|
12
|
+
from infix_cli.domain import refs, resolve
|
|
13
|
+
from infix_cli.errors import CliError, JobFailed, UsageError
|
|
14
|
+
from infix_cli.waiter import parse_timeout, wait_until_terminal
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def segment(value):
|
|
18
|
+
return quote(str(value), safe="")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def request_key():
|
|
22
|
+
return str(uuid4())
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run_number(value):
|
|
26
|
+
if value is None:
|
|
27
|
+
return None
|
|
28
|
+
if not re.fullmatch(r"(?:run-)?[1-9][0-9]*", str(value)):
|
|
29
|
+
raise UsageError("--run must be a positive integer or run-N.")
|
|
30
|
+
return int(str(value).removeprefix("run-"))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def reference(client, value, *, kind="model", labels=None):
|
|
34
|
+
if isinstance(value, dict):
|
|
35
|
+
return value
|
|
36
|
+
if not isinstance(value, str):
|
|
37
|
+
raise UsageError("Asset references must be strings or typed reference objects.")
|
|
38
|
+
parsed = refs.parse_ref(value, kind=kind)
|
|
39
|
+
if isinstance(parsed, refs.StorageRef):
|
|
40
|
+
return {"path": parsed.path}
|
|
41
|
+
asset = resolve.resolve_asset(client, parsed)
|
|
42
|
+
if not asset.version_id:
|
|
43
|
+
raise UsageError("The asset has no usable fixed version.")
|
|
44
|
+
if labels is not None:
|
|
45
|
+
labels[asset.version_id] = (
|
|
46
|
+
f"official/{asset.name} (version {asset.version_number})"
|
|
47
|
+
if parsed.is_official
|
|
48
|
+
else f"workspace/{asset.name}:{asset.version_number}"
|
|
49
|
+
)
|
|
50
|
+
return {"asset": asset.version_id}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def comparison_reference(client, value, *, kind="model"):
|
|
54
|
+
parsed = refs.parse_ref(value, kind=kind)
|
|
55
|
+
if isinstance(parsed, refs.StorageRef):
|
|
56
|
+
if kind != "model":
|
|
57
|
+
raise UsageError(
|
|
58
|
+
"Register comparison datasets first; use official/ or workspace/ references."
|
|
59
|
+
)
|
|
60
|
+
return {"path": parsed.path, "label": value}
|
|
61
|
+
asset = resolve.resolve_asset(client, parsed)
|
|
62
|
+
return {
|
|
63
|
+
"asset_id": asset.asset_id,
|
|
64
|
+
"version_id": asset.version_id,
|
|
65
|
+
**({"label": value} if kind == "model" else {}),
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def read_config(path):
|
|
70
|
+
from infix_cli.config_input import read_document
|
|
71
|
+
|
|
72
|
+
return read_document(path)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parameters(values):
|
|
76
|
+
result = {}
|
|
77
|
+
for item in values or []:
|
|
78
|
+
name, separator, value = item.partition("=")
|
|
79
|
+
if not separator or not name:
|
|
80
|
+
raise UsageError("Use --set key=value; repeat it for multiple parameters.")
|
|
81
|
+
name = name.replace("-", "_")
|
|
82
|
+
if name in result:
|
|
83
|
+
raise UsageError(f"Parameter {name} is duplicated.")
|
|
84
|
+
try:
|
|
85
|
+
parsed = json.loads(
|
|
86
|
+
value,
|
|
87
|
+
parse_constant=lambda value: (_ for _ in ()).throw(
|
|
88
|
+
ValueError("non-finite")
|
|
89
|
+
),
|
|
90
|
+
)
|
|
91
|
+
json.dumps(parsed, allow_nan=False)
|
|
92
|
+
except json.JSONDecodeError:
|
|
93
|
+
parsed = value
|
|
94
|
+
except ValueError as exc:
|
|
95
|
+
raise UsageError(f"Parameter {name} must be a finite number.") from exc
|
|
96
|
+
result[name] = parsed
|
|
97
|
+
return result
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def output(run, payload, *, quiet_value=None):
|
|
101
|
+
scalar = (
|
|
102
|
+
quiet_value
|
|
103
|
+
if quiet_value is not None
|
|
104
|
+
else payload.get("name", payload.get("comparison", payload.get("id", "")))
|
|
105
|
+
)
|
|
106
|
+
rows = [
|
|
107
|
+
(key, str(payload[key]))
|
|
108
|
+
for key in (
|
|
109
|
+
"name",
|
|
110
|
+
"description",
|
|
111
|
+
"comparison",
|
|
112
|
+
"id",
|
|
113
|
+
"number",
|
|
114
|
+
"status",
|
|
115
|
+
"stop_reason",
|
|
116
|
+
"job_count",
|
|
117
|
+
"max_parallel",
|
|
118
|
+
"phase",
|
|
119
|
+
"url",
|
|
120
|
+
"stage_run_id",
|
|
121
|
+
"asset_id",
|
|
122
|
+
"version_id",
|
|
123
|
+
"version",
|
|
124
|
+
)
|
|
125
|
+
if payload.get(key) is not None
|
|
126
|
+
]
|
|
127
|
+
if not rows:
|
|
128
|
+
rows = [("Result", json.dumps(payload, ensure_ascii=False, indent=2))]
|
|
129
|
+
if isinstance(payload.get("plan"), dict):
|
|
130
|
+
from infix_cli.commands._fusion_feedback import plan_rows
|
|
131
|
+
rows.extend(plan_rows(
|
|
132
|
+
payload["plan"], config=payload.get("config"),
|
|
133
|
+
reference_labels=payload.get("reference_labels"),
|
|
134
|
+
))
|
|
135
|
+
render.render_object(run, payload, rows, quiet_value=str(scalar or ""))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def print_table(run, table):
|
|
139
|
+
from infix_cli.render.text import _console
|
|
140
|
+
|
|
141
|
+
console = _console(run)
|
|
142
|
+
natural = console.measure(
|
|
143
|
+
table, options=console.options.update_width(100000)
|
|
144
|
+
).maximum
|
|
145
|
+
if natural > console.width:
|
|
146
|
+
console = _console(run, width=natural)
|
|
147
|
+
console.print(table)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def wait_execution(run, client, task, execution, *, timeout=None, kind="fusion"):
|
|
151
|
+
path = f"/fusion-tasks/{segment(task)}/executions/{segment(execution['id'])}"
|
|
152
|
+
|
|
153
|
+
def fetch():
|
|
154
|
+
value = client.get(path)
|
|
155
|
+
return value["status"], value
|
|
156
|
+
|
|
157
|
+
query_argv = ["infix", kind, "get", str(task)]
|
|
158
|
+
if kind == "fusion":
|
|
159
|
+
query_argv += ["--run", str(execution["number"])]
|
|
160
|
+
query = shell_join(query_argv)
|
|
161
|
+
try:
|
|
162
|
+
_, result = wait_until_terminal(
|
|
163
|
+
fetch,
|
|
164
|
+
terminal=frozenset({"succeeded", "failed", "stopped"}),
|
|
165
|
+
ctx=run,
|
|
166
|
+
timeout=parse_timeout(timeout),
|
|
167
|
+
label=f"run-{execution['number']}",
|
|
168
|
+
recheck_hint=query,
|
|
169
|
+
)
|
|
170
|
+
except CliError as exc:
|
|
171
|
+
exc.details = {
|
|
172
|
+
**(exc.details if isinstance(exc.details, dict) else {"cause": exc.details}),
|
|
173
|
+
"task": task,
|
|
174
|
+
"execution_id": execution["id"],
|
|
175
|
+
"execution_number": execution["number"],
|
|
176
|
+
"query_argv": query_argv,
|
|
177
|
+
}
|
|
178
|
+
exc.hint = query
|
|
179
|
+
raise
|
|
180
|
+
return result
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def finish_execution(value, *, details=None, hint=None):
|
|
184
|
+
status = value.get("status")
|
|
185
|
+
if status == "failed":
|
|
186
|
+
messages = [str((slot.get("run") or {}).get("error_message")) for slot in (details or {}).get("stages", []) if (slot.get("run") or {}).get("error_message")]
|
|
187
|
+
raise JobFailed("; ".join(messages) or value.get("error_message") or "Execution failed.", hint, details={"execution": value, "details": details})
|
|
188
|
+
if status == "stopped" and value.get("stop_reason") != "awaiting_next_stage":
|
|
189
|
+
from infix_cli.errors import JobPaused
|
|
190
|
+
|
|
191
|
+
raise JobPaused("Execution stopped or requires a decision.", hint, details={"execution": value, "details": details})
|