kdev-cli 0.1.3__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.
- kdev/__init__.py +7 -0
- kdev/__main__.py +3 -0
- kdev/api.py +408 -0
- kdev/auth.py +115 -0
- kdev/bootstrap.py +510 -0
- kdev/cli.py +162 -0
- kdev/cloudflared.py +179 -0
- kdev/commands/__init__.py +5 -0
- kdev/commands/_common.py +51 -0
- kdev/commands/account.py +148 -0
- kdev/commands/box.py +694 -0
- kdev/commands/doctor.py +127 -0
- kdev/commands/home.py +92 -0
- kdev/commands/settings.py +164 -0
- kdev/commands/tunnel.py +78 -0
- kdev/commands/workspace.py +210 -0
- kdev/config.py +181 -0
- kdev/errors.py +25 -0
- kdev/kdev_box.py +538 -0
- kdev/notebook.py +261 -0
- kdev/persistence.py +314 -0
- kdev/quota.py +102 -0
- kdev/safety.py +72 -0
- kdev/session.py +284 -0
- kdev/sshcfg.py +72 -0
- kdev/tunnel.py +259 -0
- kdev/ui.py +666 -0
- kdev/wizard.py +251 -0
- kdev_cli-0.1.3.dist-info/METADATA +598 -0
- kdev_cli-0.1.3.dist-info/RECORD +33 -0
- kdev_cli-0.1.3.dist-info/WHEEL +4 -0
- kdev_cli-0.1.3.dist-info/entry_points.txt +2 -0
- kdev_cli-0.1.3.dist-info/licenses/LICENSE +21 -0
kdev/ui.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
"""kdev's design system. Every command builds its output from these parts only.
|
|
2
|
+
|
|
3
|
+
Not a full-screen app, on purpose: `kdev up` ends by handing you a shell, and a
|
|
4
|
+
UI you have to quit first would be in the way. The references, and what each
|
|
5
|
+
contributed:
|
|
6
|
+
|
|
7
|
+
Docker Compose the status board -- a line per step, each with its own clock
|
|
8
|
+
fly / vercel the result card -- the few facts that matter, and the command
|
|
9
|
+
to copy
|
|
10
|
+
gh glyph-and-gutter status lines, and data on stdout
|
|
11
|
+
Charm a quiet palette where colour carries meaning, not decoration
|
|
12
|
+
|
|
13
|
+
Tokens
|
|
14
|
+
accent cyan the brand, and commands you can run next
|
|
15
|
+
ok green done, reachable, enough quota
|
|
16
|
+
warn yellow needs attention, still works
|
|
17
|
+
err red failed
|
|
18
|
+
muted grey labels, secondary facts, hints
|
|
19
|
+
bold the values that matter: hosts, names, counts
|
|
20
|
+
|
|
21
|
+
Glyphs ✓ done ! attention ✗ failed ● live ○ idle/pending › step
|
|
22
|
+
|
|
23
|
+
Components
|
|
24
|
+
header(title, facts) one line: what this command is acting on
|
|
25
|
+
ok / warn / err a status line; `hint` sits indented beneath
|
|
26
|
+
facts(rows) aligned label/value pairs
|
|
27
|
+
card(title, rows) the one bordered block a command may print: its result
|
|
28
|
+
table(...) borderless, muted uppercase headers
|
|
29
|
+
Stages the live board for long operations
|
|
30
|
+
next_steps(cmds) what to run next, commands in accent
|
|
31
|
+
spinner(text) "doing something…", always present tense and lowercase
|
|
32
|
+
|
|
33
|
+
Voice
|
|
34
|
+
Sentence case. No trailing full stop on a one-line status. Labels lowercase.
|
|
35
|
+
A command, when shown, is the literal thing to type. Durations like 9h or
|
|
36
|
+
2m04s, clock times like 14:05. One card per command at most.
|
|
37
|
+
|
|
38
|
+
It degrades: without a TTY, boards become plain lines and prompts never
|
|
39
|
+
appear; NO_COLOR is honoured; a terminal that cannot draw the glyphs gets ASCII.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import json
|
|
45
|
+
import os
|
|
46
|
+
import sys
|
|
47
|
+
import time
|
|
48
|
+
from collections.abc import Iterable, Iterator, Sequence
|
|
49
|
+
from contextlib import contextmanager
|
|
50
|
+
from dataclasses import dataclass
|
|
51
|
+
|
|
52
|
+
import questionary
|
|
53
|
+
from questionary import Choice
|
|
54
|
+
from rich.console import Console, Group
|
|
55
|
+
from rich.live import Live
|
|
56
|
+
from rich.padding import Padding
|
|
57
|
+
from rich.panel import Panel
|
|
58
|
+
from rich.table import Table
|
|
59
|
+
from rich.text import Text
|
|
60
|
+
from rich.theme import Theme
|
|
61
|
+
|
|
62
|
+
from .errors import Cancelled
|
|
63
|
+
|
|
64
|
+
ACCENT = "#00b8d4"
|
|
65
|
+
MUTED = "grey58"
|
|
66
|
+
|
|
67
|
+
THEME = Theme(
|
|
68
|
+
{
|
|
69
|
+
"kdev.accent": ACCENT,
|
|
70
|
+
"kdev.muted": MUTED,
|
|
71
|
+
"kdev.ok": "green",
|
|
72
|
+
"kdev.warn": "yellow",
|
|
73
|
+
"kdev.err": "red",
|
|
74
|
+
"kdev.head": f"bold {ACCENT}",
|
|
75
|
+
"kdev.cmd": f"bold {ACCENT}",
|
|
76
|
+
}
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _no_colour() -> bool:
|
|
81
|
+
"""NO_COLOR is a standard, and piping into a file should stay readable."""
|
|
82
|
+
return bool(os.environ.get("NO_COLOR")) or os.environ.get("TERM") == "dumb"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
console = Console(theme=THEME, no_color=_no_colour(), soft_wrap=False)
|
|
86
|
+
#: Failures go to stderr, so `kdev status --json | jq` never sees them.
|
|
87
|
+
errconsole = Console(theme=THEME, no_color=_no_colour(), soft_wrap=False, stderr=True)
|
|
88
|
+
|
|
89
|
+
_GLYPHS = {
|
|
90
|
+
"ok": ("✓", "+"),
|
|
91
|
+
"warn": ("!", "!"),
|
|
92
|
+
"err": ("✗", "x"),
|
|
93
|
+
"live": ("●", "*"),
|
|
94
|
+
"pending": ("○", "-"),
|
|
95
|
+
"bullet": ("·", "."),
|
|
96
|
+
"full": ("█", "#"),
|
|
97
|
+
"empty": ("░", "."),
|
|
98
|
+
"prompt": ("›", ">"),
|
|
99
|
+
"arrow": ("→", "->"),
|
|
100
|
+
}
|
|
101
|
+
_SPINNERS = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏", "|/-\\")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _ascii_only() -> bool:
|
|
105
|
+
encoding = (getattr(sys.stdout, "encoding", "") or "").lower()
|
|
106
|
+
return not ("utf" in encoding or encoding in ("", "cp65001"))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def g(name: str) -> str:
|
|
110
|
+
"""The right glyph for this terminal."""
|
|
111
|
+
return _GLYPHS[name][1 if _ascii_only() else 0]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _spinner_frames() -> str:
|
|
115
|
+
return _SPINNERS[1 if _ascii_only() else 0]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
STYLE = questionary.Style(
|
|
119
|
+
[
|
|
120
|
+
("qmark", f"fg:{ACCENT} bold"),
|
|
121
|
+
("question", "bold"),
|
|
122
|
+
("answer", f"fg:{ACCENT} bold"),
|
|
123
|
+
("pointer", f"fg:{ACCENT} bold"),
|
|
124
|
+
("highlighted", f"fg:{ACCENT} bold"),
|
|
125
|
+
("selected", f"fg:{ACCENT}"),
|
|
126
|
+
("separator", "fg:#6c6c6c"),
|
|
127
|
+
("instruction", "fg:#6c6c6c"),
|
|
128
|
+
("disabled", "fg:#6c6c6c italic"),
|
|
129
|
+
]
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def interactive() -> bool:
|
|
134
|
+
"""Only prompt when a human can answer; otherwise flags and defaults win."""
|
|
135
|
+
return sys.stdin.isatty() and sys.stdout.isatty()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# --- lines --------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
GUTTER = 2
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _line(target: Console, glyph: str, style: str, msg: str | Text) -> None:
|
|
144
|
+
target.print(Text.assemble((f"{glyph:<{GUTTER}}", style), msg))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def ok(msg: str | Text, hint_text: str = "") -> None:
|
|
148
|
+
_line(console, g("ok"), "kdev.ok", msg)
|
|
149
|
+
if hint_text:
|
|
150
|
+
hint(hint_text)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def warn(msg: str | Text, hint_text: str = "") -> None:
|
|
154
|
+
_line(console, g("warn"), "kdev.warn", msg)
|
|
155
|
+
if hint_text:
|
|
156
|
+
hint(hint_text)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def err(msg: str | Text, hint_text: str = "") -> None:
|
|
160
|
+
_line(errconsole, g("err"), "kdev.err", msg)
|
|
161
|
+
if hint_text:
|
|
162
|
+
errconsole.print(
|
|
163
|
+
Padding(Text(hint_text, style="kdev.muted"), (0, 0, 0, GUTTER), expand=False)
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def hint(msg: str | Text) -> None:
|
|
168
|
+
# Padding rather than a literal prefix: a long hint that wraps keeps its
|
|
169
|
+
# indent on the continuation lines instead of falling back to column 0.
|
|
170
|
+
text = msg if isinstance(msg, Text) else Text(msg, style="kdev.muted")
|
|
171
|
+
console.print(Padding(text, (0, 0, 0, GUTTER), expand=False))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def blank() -> None:
|
|
175
|
+
console.print()
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def header(title: str = "", context: Sequence[tuple[str, str]] = ()) -> None:
|
|
179
|
+
"""What this command is acting on, in one line (two on a narrow terminal)."""
|
|
180
|
+
from . import __version__
|
|
181
|
+
|
|
182
|
+
line = Text.assemble(("kdev", "kdev.head"))
|
|
183
|
+
if title:
|
|
184
|
+
line.append(f" {g('bullet')} ", style="kdev.muted")
|
|
185
|
+
line.append(title, style="bold")
|
|
186
|
+
line.append(f" v{__version__}", style="kdev.muted")
|
|
187
|
+
console.print(line)
|
|
188
|
+
if context:
|
|
189
|
+
row = Text(" ")
|
|
190
|
+
for i, (label, value) in enumerate(context):
|
|
191
|
+
if i:
|
|
192
|
+
row.append(f" {g('bullet')} ", style="kdev.muted")
|
|
193
|
+
row.append(f"{label} ", style="kdev.muted")
|
|
194
|
+
row.append(value)
|
|
195
|
+
if row.cell_len <= console.width:
|
|
196
|
+
console.print(row)
|
|
197
|
+
else:
|
|
198
|
+
# A hostname broken across two lines is unreadable and un-copyable.
|
|
199
|
+
width = max(len(label) for label, _ in context)
|
|
200
|
+
for label, value in context:
|
|
201
|
+
console.print(
|
|
202
|
+
Text.assemble((" ", ""), (f"{label:>{width}} ", "kdev.muted"), value)
|
|
203
|
+
)
|
|
204
|
+
console.print()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def facts(rows: Sequence[tuple[str, object]], indent: int = GUTTER) -> Table:
|
|
208
|
+
"""Aligned label/value pairs. Labels muted and right-aligned."""
|
|
209
|
+
grid = Table.grid(padding=(0, 2))
|
|
210
|
+
grid.add_column(style="kdev.muted", justify="right")
|
|
211
|
+
grid.add_column()
|
|
212
|
+
for label, value in rows:
|
|
213
|
+
grid.add_row(label, value if isinstance(value, Text) else Text(str(value)))
|
|
214
|
+
return Padding(grid, (0, 0, 0, indent), expand=False) # type: ignore[return-value]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def card(title: str | Text, rows: Sequence[tuple[str, object]], tone: str = "muted") -> None:
|
|
218
|
+
"""The one bordered block a command may print: its result."""
|
|
219
|
+
body = Table.grid(padding=(0, 2))
|
|
220
|
+
body.add_column(style="kdev.muted", justify="right")
|
|
221
|
+
body.add_column()
|
|
222
|
+
for label, value in rows:
|
|
223
|
+
body.add_row(label, value if isinstance(value, Text) else Text(str(value)))
|
|
224
|
+
border = {"ok": "kdev.ok", "warn": "kdev.warn", "err": "kdev.err"}.get(tone, MUTED)
|
|
225
|
+
console.print(
|
|
226
|
+
Panel(
|
|
227
|
+
body, title=title, title_align="left", border_style=border, padding=(1, 2), expand=False
|
|
228
|
+
)
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def table(
|
|
233
|
+
columns: Sequence[tuple[str, str]], rows: Iterable[Sequence[object]], title: str = ""
|
|
234
|
+
) -> Table:
|
|
235
|
+
"""Borderless; columns are (header, justify)."""
|
|
236
|
+
# pad_edge puts the first column on the same two-space gutter as every
|
|
237
|
+
# other line kdev prints.
|
|
238
|
+
t = Table(
|
|
239
|
+
box=None,
|
|
240
|
+
expand=False,
|
|
241
|
+
padding=(0, 2),
|
|
242
|
+
header_style="kdev.muted",
|
|
243
|
+
title=title or None,
|
|
244
|
+
title_style="bold",
|
|
245
|
+
title_justify="left",
|
|
246
|
+
pad_edge=True,
|
|
247
|
+
)
|
|
248
|
+
for name, justify in columns:
|
|
249
|
+
t.add_column(name.upper(), justify=justify) # type: ignore[arg-type]
|
|
250
|
+
for row in rows:
|
|
251
|
+
t.add_row(*[c if isinstance(c, Text) else Text(str(c)) for c in row])
|
|
252
|
+
return t
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def next_steps(steps: Sequence[tuple[str, str]]) -> None:
|
|
256
|
+
"""What to run next. Commands in accent, aligned, one per line."""
|
|
257
|
+
if not steps:
|
|
258
|
+
return
|
|
259
|
+
width = max(len(cmd) for cmd, _ in steps)
|
|
260
|
+
for cmd, what in steps:
|
|
261
|
+
hint(Text.assemble((f"{cmd:<{width}}", "kdev.cmd"), (" " + what, "kdev.muted")))
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def cmd(text: str) -> Text:
|
|
265
|
+
"""A command the user can type, styled as one."""
|
|
266
|
+
return Text(text, style="kdev.cmd")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def live_dot(is_live: bool) -> Text:
|
|
270
|
+
return Text(
|
|
271
|
+
g("live") if is_live else g("pending"), style="kdev.ok" if is_live else "kdev.muted"
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@contextmanager
|
|
276
|
+
def spinner(text: str) -> Iterator[object]:
|
|
277
|
+
"""A transient spinner. Present tense, lowercase, ends in an ellipsis."""
|
|
278
|
+
if not interactive():
|
|
279
|
+
yield _NullStatus()
|
|
280
|
+
return
|
|
281
|
+
with console.status(Text(text, style="kdev.muted"), spinner="dots") as status:
|
|
282
|
+
yield status
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class _NullStatus:
|
|
286
|
+
def update(self, *_a, **_k) -> None:
|
|
287
|
+
pass
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def emit_json(data: object) -> None:
|
|
291
|
+
"""Machine-readable output: plain JSON on stdout, nothing else."""
|
|
292
|
+
sys.stdout.write(json.dumps(data, indent=2, sort_keys=True, default=str) + "\n")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def bar(fraction: float, width: int = 14) -> Text:
|
|
296
|
+
"""A quota bar. Colour is the signal; the number beside it is the detail."""
|
|
297
|
+
fraction = max(0.0, min(1.0, fraction))
|
|
298
|
+
filled = round(fraction * width)
|
|
299
|
+
colour = "green" if fraction > 0.5 else "yellow" if fraction > 0.15 else "red"
|
|
300
|
+
t = Text(g("full") * filled, style=colour)
|
|
301
|
+
t.append(g("empty") * (width - filled), style=MUTED)
|
|
302
|
+
return t
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _fmt_elapsed(seconds: float) -> str:
|
|
306
|
+
seconds = int(seconds)
|
|
307
|
+
if seconds < 60:
|
|
308
|
+
return f"{seconds}s"
|
|
309
|
+
return f"{seconds // 60}m{seconds % 60:02d}s"
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def fmt_hours(seconds: float) -> str:
|
|
313
|
+
return f"{seconds / 3600:.1f}h"
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# --- accounts -----------------------------------------------------------------
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@dataclass
|
|
320
|
+
class ProfileRow:
|
|
321
|
+
name: str
|
|
322
|
+
username: str
|
|
323
|
+
gpu_left: int
|
|
324
|
+
gpu_total: int
|
|
325
|
+
tpu_left: int = 0
|
|
326
|
+
tpu_total: int = 0
|
|
327
|
+
active: bool = False
|
|
328
|
+
error: str = ""
|
|
329
|
+
|
|
330
|
+
@property
|
|
331
|
+
def fraction(self) -> float:
|
|
332
|
+
return self.gpu_left / self.gpu_total if self.gpu_total else 0.0
|
|
333
|
+
|
|
334
|
+
@property
|
|
335
|
+
def hours(self) -> str:
|
|
336
|
+
return fmt_hours(self.gpu_left)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def accounts_table(rows: Sequence[ProfileRow]) -> Table:
|
|
340
|
+
t = table(
|
|
341
|
+
[
|
|
342
|
+
("", "left"),
|
|
343
|
+
("account", "left"),
|
|
344
|
+
("kaggle user", "left"),
|
|
345
|
+
("gpu this week", "left"),
|
|
346
|
+
("left", "right"),
|
|
347
|
+
("tpu", "right"),
|
|
348
|
+
],
|
|
349
|
+
[],
|
|
350
|
+
)
|
|
351
|
+
t.columns[0].width = 1
|
|
352
|
+
for r in rows:
|
|
353
|
+
marker = Text(g("live") if r.active else " ", style="kdev.accent")
|
|
354
|
+
name = Text(r.name, style="bold")
|
|
355
|
+
if r.error:
|
|
356
|
+
t.add_row(
|
|
357
|
+
marker,
|
|
358
|
+
name,
|
|
359
|
+
Text(r.username, style="kdev.muted"),
|
|
360
|
+
Text(r.error, style="kdev.err"),
|
|
361
|
+
Text("—"),
|
|
362
|
+
Text("—"),
|
|
363
|
+
)
|
|
364
|
+
else:
|
|
365
|
+
t.add_row(
|
|
366
|
+
marker,
|
|
367
|
+
name,
|
|
368
|
+
Text(r.username, style="kdev.muted"),
|
|
369
|
+
bar(r.fraction),
|
|
370
|
+
Text(r.hours),
|
|
371
|
+
Text(fmt_hours(r.tpu_left), style="kdev.muted"),
|
|
372
|
+
)
|
|
373
|
+
return t
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def pick_profile(rows: Sequence[ProfileRow], need_hours: float) -> str:
|
|
377
|
+
"""Account picker with quota inline, most quota first."""
|
|
378
|
+
usable = [r for r in rows if not r.error]
|
|
379
|
+
if not usable:
|
|
380
|
+
from .errors import KdevError
|
|
381
|
+
|
|
382
|
+
raise KdevError(
|
|
383
|
+
"Could not read quota for any account.", "Check they are signed in: kdev account"
|
|
384
|
+
)
|
|
385
|
+
usable.sort(key=lambda r: r.gpu_left, reverse=True)
|
|
386
|
+
width = max(len(r.name) for r in usable)
|
|
387
|
+
choices = []
|
|
388
|
+
for r in usable:
|
|
389
|
+
meter = "".join(g("full") if j < round(r.fraction * 10) else g("empty") for j in range(10))
|
|
390
|
+
note = "" if r.gpu_left >= need_hours * 3600 else " short for this session"
|
|
391
|
+
choices.append(
|
|
392
|
+
Choice(title=f"{r.name:<{width}} {meter} {r.hours:>6} left{note}", value=r.name)
|
|
393
|
+
)
|
|
394
|
+
return select("Which account should run it?", choices)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
# --- prompts ------------------------------------------------------------------
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def select(question: str, choices: list[Choice]) -> str:
|
|
401
|
+
answer = questionary.select(
|
|
402
|
+
question, choices=choices, style=STYLE, qmark=g("prompt"), instruction=" "
|
|
403
|
+
).ask()
|
|
404
|
+
if answer is None:
|
|
405
|
+
raise Cancelled()
|
|
406
|
+
return answer
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
# Kept for callers that pass plain (value, label) pairs.
|
|
410
|
+
_select = select
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def choose(question: str, options: Iterable[tuple[str, str]]) -> str:
|
|
414
|
+
return select(question, [Choice(title=label, value=value) for value, label in options])
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def confirm(question: str, default: bool = True) -> bool:
|
|
418
|
+
"""Without a terminal nobody can answer: take the default, which is "no"
|
|
419
|
+
wherever saying yes would lose something."""
|
|
420
|
+
if not interactive():
|
|
421
|
+
return default
|
|
422
|
+
answer = questionary.confirm(question, default=default, style=STYLE, qmark=g("prompt")).ask()
|
|
423
|
+
if answer is None:
|
|
424
|
+
raise Cancelled()
|
|
425
|
+
return answer
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def ask(question: str, default: str = "", secret: bool = False) -> str:
|
|
429
|
+
fn = questionary.password if secret else questionary.text
|
|
430
|
+
kwargs = {} if secret else {"default": default}
|
|
431
|
+
answer = fn(question, style=STYLE, qmark=g("prompt"), **kwargs).ask()
|
|
432
|
+
if answer is None:
|
|
433
|
+
raise Cancelled()
|
|
434
|
+
return answer.strip()
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
GPU_CHOICES = [
|
|
438
|
+
("t4", "T4 ×2", "2× Tesla T4 · 29 GB RAM · the default"),
|
|
439
|
+
("p100", "P100", "1× Tesla P100 · 29 GB RAM · better fp64"),
|
|
440
|
+
("none", "CPU only", "4 cores · 30 GB RAM · uses no GPU quota"),
|
|
441
|
+
("tpu", "TPU v3-8", "96 cores · 330 GB RAM · 9h cap"),
|
|
442
|
+
]
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def gpu_label(key: str) -> str:
|
|
446
|
+
return {k: label for k, label, _ in GPU_CHOICES}.get(key, key)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def pick_gpu() -> str:
|
|
450
|
+
return select(
|
|
451
|
+
"Accelerator?",
|
|
452
|
+
[Choice(title=f"{label:<10} {desc}", value=key) for key, label, desc in GPU_CHOICES],
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def pick_hours(gpu: str, quota_hours: float) -> float:
|
|
457
|
+
cap = 9.0 if gpu == "tpu" else 12.0
|
|
458
|
+
options = [h for h in (2.0, 4.0, 9.0, 12.0) if h <= cap]
|
|
459
|
+
choices = []
|
|
460
|
+
for h in options:
|
|
461
|
+
note = f" more than the {quota_hours:.1f}h left" if h > quota_hours else ""
|
|
462
|
+
choices.append(Choice(title=f"{h:g} hours{note}", value=h))
|
|
463
|
+
choices.append(Choice(title="Custom…", value=0.0))
|
|
464
|
+
answer = select(f"Session length? (Kaggle stops it at {cap:g}h)", choices)
|
|
465
|
+
if answer == 0.0:
|
|
466
|
+
raw = questionary.text("Hours:", default="6", style=STYLE, qmark=g("prompt")).ask()
|
|
467
|
+
if raw is None:
|
|
468
|
+
raise Cancelled()
|
|
469
|
+
from .errors import KdevError
|
|
470
|
+
|
|
471
|
+
try:
|
|
472
|
+
answer = min(float(raw), cap)
|
|
473
|
+
except ValueError as e:
|
|
474
|
+
raise KdevError(f"{raw!r} is not a number of hours.") from e
|
|
475
|
+
if answer <= 0:
|
|
476
|
+
raise KdevError("Session length must be more than zero.")
|
|
477
|
+
return answer
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
# --- the status board ---------------------------------------------------------
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
@dataclass
|
|
484
|
+
class _Stage:
|
|
485
|
+
key: str
|
|
486
|
+
label: str
|
|
487
|
+
started: float = 0.0
|
|
488
|
+
ended: float = 0.0
|
|
489
|
+
failed: bool = False
|
|
490
|
+
|
|
491
|
+
@property
|
|
492
|
+
def elapsed(self) -> float:
|
|
493
|
+
if not self.started:
|
|
494
|
+
return 0.0
|
|
495
|
+
return (self.ended or time.monotonic()) - self.started
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
class Stages:
|
|
499
|
+
"""Live board, modelled on Docker Compose's: each step keeps its own line
|
|
500
|
+
and clock, so a slow step is visibly slow rather than indistinguishable
|
|
501
|
+
from a hung one. Plain appended lines when stdout is not a terminal."""
|
|
502
|
+
|
|
503
|
+
def __init__(self, stages: Sequence[tuple[str, str]], head: str = ""):
|
|
504
|
+
self._stages = [_Stage(k, text) for k, text in stages]
|
|
505
|
+
self._by_key = {s.key: s for s in self._stages}
|
|
506
|
+
self.head = head
|
|
507
|
+
self.current: str | None = None
|
|
508
|
+
self.detail = ""
|
|
509
|
+
self.tick = 0
|
|
510
|
+
self.started = time.monotonic()
|
|
511
|
+
self._live: Live | None = None
|
|
512
|
+
|
|
513
|
+
@property
|
|
514
|
+
def done(self) -> list[str]:
|
|
515
|
+
return [s.key for s in self._stages if s.ended and not s.failed]
|
|
516
|
+
|
|
517
|
+
def __enter__(self) -> Stages:
|
|
518
|
+
if interactive():
|
|
519
|
+
self._live = Live(
|
|
520
|
+
self._render(), console=console, refresh_per_second=12, transient=False
|
|
521
|
+
)
|
|
522
|
+
self._live.__enter__()
|
|
523
|
+
elif self.head:
|
|
524
|
+
console.print(Text(" " + self.head, style="kdev.muted"))
|
|
525
|
+
return self
|
|
526
|
+
|
|
527
|
+
def __exit__(self, *exc) -> None:
|
|
528
|
+
if self._live:
|
|
529
|
+
self._live.update(self._render(final=True))
|
|
530
|
+
self._live.__exit__(*exc)
|
|
531
|
+
|
|
532
|
+
def _marks(self, stage: _Stage, final: bool) -> tuple[Text, Text]:
|
|
533
|
+
running = stage.key == self.current and not stage.ended and not final
|
|
534
|
+
if stage.failed:
|
|
535
|
+
glyph, style, label_style = g("err"), "kdev.err", "kdev.err"
|
|
536
|
+
elif stage.ended or (stage.key == self.current and final):
|
|
537
|
+
glyph, style, label_style = g("ok"), "kdev.ok", ""
|
|
538
|
+
elif running:
|
|
539
|
+
frames = _spinner_frames()
|
|
540
|
+
glyph, style, label_style = frames[self.tick % len(frames)], "kdev.accent", "bold"
|
|
541
|
+
else:
|
|
542
|
+
glyph, style, label_style = g("pending"), "kdev.muted", "kdev.muted"
|
|
543
|
+
return Text(glyph, style=style), Text(stage.label, style=label_style)
|
|
544
|
+
|
|
545
|
+
def _render(self, final: bool = False) -> Group:
|
|
546
|
+
self.tick += 1
|
|
547
|
+
lines = []
|
|
548
|
+
if self.head:
|
|
549
|
+
head = Text(" " + self.head, style="kdev.muted")
|
|
550
|
+
head.append(f" {_fmt_elapsed(time.monotonic() - self.started)}", style="kdev.muted")
|
|
551
|
+
lines.append(head)
|
|
552
|
+
board = Table.grid(padding=(0, 1))
|
|
553
|
+
board.add_column(width=2)
|
|
554
|
+
board.add_column(width=1)
|
|
555
|
+
board.add_column(ratio=1)
|
|
556
|
+
board.add_column(justify="right")
|
|
557
|
+
for stage in self._stages:
|
|
558
|
+
glyph, label = self._marks(stage, final)
|
|
559
|
+
clock = _fmt_elapsed(stage.elapsed) if stage.started else ""
|
|
560
|
+
board.add_row("", glyph, label, Text(clock, style="kdev.muted"))
|
|
561
|
+
# A failed stage keeps its detail on the final frame: the reason it
|
|
562
|
+
# failed is the whole point of the line.
|
|
563
|
+
if self.detail and stage.key == self.current and (not final or stage.failed):
|
|
564
|
+
board.add_row("", "", Text(self.detail, style="kdev.muted"), "")
|
|
565
|
+
lines.append(board)
|
|
566
|
+
return Group(*lines)
|
|
567
|
+
|
|
568
|
+
def _refresh(self) -> None:
|
|
569
|
+
if self._live:
|
|
570
|
+
self._live.update(self._render())
|
|
571
|
+
|
|
572
|
+
def advance(self, key: str) -> None:
|
|
573
|
+
now = time.monotonic()
|
|
574
|
+
if self.current and self.current != key:
|
|
575
|
+
previous = self._by_key.get(self.current)
|
|
576
|
+
if previous and not previous.ended:
|
|
577
|
+
previous.ended = now
|
|
578
|
+
if key == self.current:
|
|
579
|
+
return
|
|
580
|
+
stage = self._by_key.get(key)
|
|
581
|
+
if stage is None:
|
|
582
|
+
return # the remote side talking, not a step
|
|
583
|
+
self.current = key
|
|
584
|
+
stage.started = stage.started or now
|
|
585
|
+
stage.ended = 0.0
|
|
586
|
+
self.detail = ""
|
|
587
|
+
if not self._live:
|
|
588
|
+
console.print(f" {g('prompt')} {stage.label}")
|
|
589
|
+
else:
|
|
590
|
+
self._refresh()
|
|
591
|
+
|
|
592
|
+
def fail(self, message: str = "") -> None:
|
|
593
|
+
stage = self._by_key.get(self.current or "")
|
|
594
|
+
if stage:
|
|
595
|
+
stage.failed = True
|
|
596
|
+
stage.ended = stage.ended or time.monotonic()
|
|
597
|
+
if message:
|
|
598
|
+
self.detail = message[:96]
|
|
599
|
+
if not self._live:
|
|
600
|
+
err(message or "failed")
|
|
601
|
+
else:
|
|
602
|
+
self._refresh()
|
|
603
|
+
|
|
604
|
+
def note(self, text: str) -> None:
|
|
605
|
+
self.detail = text[:96]
|
|
606
|
+
self._refresh()
|
|
607
|
+
|
|
608
|
+
def finish(self) -> None:
|
|
609
|
+
stage = self._by_key.get(self.current or "")
|
|
610
|
+
if stage and not stage.ended:
|
|
611
|
+
stage.ended = time.monotonic()
|
|
612
|
+
if self._live:
|
|
613
|
+
self._live.update(self._render(final=True))
|
|
614
|
+
|
|
615
|
+
def refresh(self) -> None:
|
|
616
|
+
self._refresh()
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def ready_card(alias: str, host: str, hours: float, gpu: str, account: str, note: str = "") -> None:
|
|
620
|
+
"""How `up` ends: the facts about the box, and how to get in."""
|
|
621
|
+
ends = time.localtime(time.time() + hours * 3600)
|
|
622
|
+
rows: list[tuple[str, object]] = [
|
|
623
|
+
("host", Text(host, style="bold")),
|
|
624
|
+
("account", account),
|
|
625
|
+
("accelerator", gpu),
|
|
626
|
+
("ends", f"{time.strftime('%H:%M', ends)} ({hours:g}h from now)"),
|
|
627
|
+
]
|
|
628
|
+
if note:
|
|
629
|
+
rows.append(("files", note))
|
|
630
|
+
rows += [
|
|
631
|
+
("", ""),
|
|
632
|
+
("connect", cmd(f"ssh {alias}")),
|
|
633
|
+
("vs code", Text(f"Remote-SSH {g('arrow')} {alias}", style="kdev.muted")),
|
|
634
|
+
("stop", cmd("kdev down")),
|
|
635
|
+
]
|
|
636
|
+
card(Text.assemble((g("ok") + " ", "kdev.ok"), ("ready", "kdev.ok")), rows, tone="ok")
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def download(label: str, installer) -> object:
|
|
640
|
+
"""Run an installer that reports (done, total) bytes, with a progress bar."""
|
|
641
|
+
from rich.progress import (
|
|
642
|
+
BarColumn,
|
|
643
|
+
DownloadColumn,
|
|
644
|
+
Progress,
|
|
645
|
+
SpinnerColumn,
|
|
646
|
+
TextColumn,
|
|
647
|
+
TransferSpeedColumn,
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
if not interactive():
|
|
651
|
+
return installer(None)
|
|
652
|
+
with Progress(
|
|
653
|
+
SpinnerColumn(style="kdev.accent"),
|
|
654
|
+
TextColumn("[progress.description]{task.description}"),
|
|
655
|
+
BarColumn(complete_style=ACCENT, finished_style="green"),
|
|
656
|
+
DownloadColumn(),
|
|
657
|
+
TransferSpeedColumn(),
|
|
658
|
+
console=console,
|
|
659
|
+
transient=True,
|
|
660
|
+
) as bars:
|
|
661
|
+
task = bars.add_task(f"fetching {label}", total=None)
|
|
662
|
+
|
|
663
|
+
def on_progress(done: int, total: int) -> None:
|
|
664
|
+
bars.update(task, completed=done, total=total or None)
|
|
665
|
+
|
|
666
|
+
return installer(on_progress)
|