cloudgpu 0.1.0__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.
cloudgpu/snapshot.py ADDED
@@ -0,0 +1,136 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, replace
4
+ from datetime import datetime, timezone
5
+
6
+ from cloudgpu.errors import AdapterError
7
+ from cloudgpu.jobs import build_jobs
8
+ from cloudgpu.models import GpuOffer, filter_offers
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class SnapshotItem:
13
+ target: str
14
+ offer: GpuOffer
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SnapshotError:
19
+ target: str
20
+ platform: str
21
+ error: str
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Snapshot:
26
+ items: tuple
27
+ errors: tuple
28
+ checked_at: str
29
+ targets_ok: int
30
+ targets_total: int
31
+
32
+
33
+ class _NullNotifier:
34
+ def send(self, event) -> None:
35
+ pass
36
+
37
+
38
+ def _null_builder(names):
39
+ return _NullNotifier()
40
+
41
+
42
+ def collect_snapshot(
43
+ config,
44
+ *,
45
+ adapters=None,
46
+ env=None,
47
+ clock=None,
48
+ platforms=None,
49
+ ) -> Snapshot:
50
+ targets = tuple(
51
+ target
52
+ for target in config.targets
53
+ if not platforms or target.platform in platforms
54
+ )
55
+ now = (
56
+ clock()
57
+ if clock is not None
58
+ else datetime.now(timezone.utc)
59
+ )
60
+ checked_at = _format_time(now)
61
+
62
+ items = []
63
+ errors = []
64
+ seen = set()
65
+ targets_ok = 0
66
+
67
+ for target in targets:
68
+ single = replace(config, targets=(target,))
69
+ try:
70
+ jobs = build_jobs(
71
+ single,
72
+ adapters=adapters,
73
+ notifier_builder=_null_builder,
74
+ env=env,
75
+ )
76
+ job = jobs[0]
77
+ target_offers = []
78
+ for kind in job.kinds:
79
+ fetched = job.fetch_offers(kind)
80
+ target_offers.extend(
81
+ filter_offers(
82
+ fetched,
83
+ job.gpu_patterns,
84
+ job.min_free,
85
+ )
86
+ )
87
+ except (AdapterError, ValueError) as exc:
88
+ errors.append(
89
+ SnapshotError(
90
+ target=target.name,
91
+ platform=target.platform,
92
+ error=str(exc),
93
+ )
94
+ )
95
+ continue
96
+
97
+ targets_ok += 1
98
+ for offer in target_offers:
99
+ key = (
100
+ offer.platform,
101
+ offer.service_kind,
102
+ offer.region,
103
+ offer.gpu_model,
104
+ offer.machine_id,
105
+ )
106
+ if key in seen:
107
+ continue
108
+ seen.add(key)
109
+ items.append(SnapshotItem(target.name, offer))
110
+
111
+ items.sort(
112
+ key=lambda item: (
113
+ item.offer.price_per_hour is None,
114
+ item.offer.price_per_hour or 0,
115
+ -item.offer.free,
116
+ item.offer.platform,
117
+ item.offer.gpu_model,
118
+ item.offer.region or "",
119
+ item.offer.machine_id or "",
120
+ )
121
+ )
122
+ return Snapshot(
123
+ items=tuple(items),
124
+ errors=tuple(errors),
125
+ checked_at=checked_at,
126
+ targets_ok=targets_ok,
127
+ targets_total=len(targets),
128
+ )
129
+
130
+
131
+ def _format_time(value: datetime) -> str:
132
+ if value.tzinfo is None:
133
+ value = value.replace(tzinfo=timezone.utc)
134
+ return value.astimezone(timezone.utc).strftime(
135
+ "%Y-%m-%dT%H:%M:%SZ"
136
+ )
cloudgpu/tui.py ADDED
@@ -0,0 +1,513 @@
1
+ from __future__ import annotations
2
+
3
+ import threading
4
+ import unicodedata
5
+ from dataclasses import dataclass
6
+
7
+ from cloudgpu.dashboard import (
8
+ DashboardService,
9
+ format_free,
10
+ format_price,
11
+ snapshot_rows,
12
+ )
13
+
14
+ SORTS = ("price-asc", "price-desc", "free-desc", "target")
15
+
16
+
17
+ @dataclass
18
+ class TuiView:
19
+ platform: object = None
20
+ target: object = None
21
+ search: str = ""
22
+ min_free: int = 0
23
+ max_price: object = None
24
+ sort: str = "price-asc"
25
+ scroll: int = 0
26
+ help: bool = False
27
+
28
+
29
+ def cell_width(char: str) -> int:
30
+ if unicodedata.combining(char):
31
+ return 0
32
+ if unicodedata.category(char) in ("Mn", "Me", "Cf"):
33
+ return 0
34
+ if unicodedata.east_asian_width(char) in ("W", "F"):
35
+ return 2
36
+ return 1
37
+
38
+
39
+ def display_width(text: str) -> int:
40
+ return sum(cell_width(char) for char in text)
41
+
42
+
43
+ def truncate_cells(text: str, width: int) -> str:
44
+ if width <= 0:
45
+ return ""
46
+ result = []
47
+ used = 0
48
+ for char in text:
49
+ size = cell_width(char)
50
+ if used + size > width:
51
+ break
52
+ result.append(char)
53
+ used += size
54
+ return "".join(result)
55
+
56
+
57
+ def pad_cells(text: str, width: int, align: str = "left") -> str:
58
+ text = truncate_cells(text, width)
59
+ padding = max(0, width - display_width(text))
60
+ if align == "right":
61
+ return " " * padding + text
62
+ if align == "center":
63
+ left = padding // 2
64
+ return " " * left + text + " " * (padding - left)
65
+ return text + " " * padding
66
+
67
+
68
+ def filter_rows(rows, view: TuiView) -> list:
69
+ search = view.search.strip().casefold()
70
+ result = []
71
+ for row in rows:
72
+ if view.platform and row["platform"] != view.platform:
73
+ continue
74
+ if view.target and row["target"] != view.target:
75
+ continue
76
+ if search:
77
+ haystack = (
78
+ f"{row['gpu_model']} {row['region'] or ''}"
79
+ ).casefold()
80
+ if search not in haystack:
81
+ continue
82
+ if row["free"] < view.min_free:
83
+ continue
84
+ if view.max_price is not None:
85
+ if (
86
+ row["price_per_hour"] is None
87
+ or row["price_per_hour"] > view.max_price
88
+ ):
89
+ continue
90
+ result.append(row)
91
+ return result
92
+
93
+
94
+ def sort_rows(rows, key: str) -> list:
95
+ result = list(rows)
96
+
97
+ def price_asc(row):
98
+ value = row["price_per_hour"]
99
+ return (
100
+ value is None,
101
+ value if value is not None else 0,
102
+ row["target"],
103
+ row["gpu_model"],
104
+ )
105
+
106
+ def price_desc(row):
107
+ value = row["price_per_hour"]
108
+ return (
109
+ value is None,
110
+ -(value if value is not None else 0),
111
+ row["target"],
112
+ row["gpu_model"],
113
+ )
114
+
115
+ if key == "price-desc":
116
+ result.sort(key=price_desc)
117
+ elif key == "free-desc":
118
+ result.sort(
119
+ key=lambda row: (
120
+ -row["free"],
121
+ row["target"],
122
+ row["gpu_model"],
123
+ )
124
+ )
125
+ elif key == "target":
126
+ result.sort(
127
+ key=lambda row: (
128
+ row["target"],
129
+ row["platform"],
130
+ row["gpu_model"],
131
+ )
132
+ )
133
+ else:
134
+ result.sort(key=price_asc)
135
+ return result
136
+
137
+
138
+ def visible_rows(rows, view: TuiView, height: int):
139
+ total = len(rows)
140
+ height = max(1, height)
141
+ max_scroll = max(0, total - height)
142
+ scroll = min(max(0, view.scroll), max_scroll)
143
+ view.scroll = scroll
144
+ return rows[scroll : scroll + height], scroll, total
145
+
146
+
147
+ def table_height(height: int, state) -> int:
148
+ snapshot = state.snapshot
149
+ errors = len(snapshot.errors) if snapshot else 0
150
+ reserved = 4 + 2 + 1
151
+ if errors:
152
+ reserved += 2 + min(3, errors)
153
+ if state.last_error:
154
+ reserved += 2
155
+ return max(1, height - reserved)
156
+
157
+
158
+ def render_tui(
159
+ state, view=None, *, width, height, config_path
160
+ ) -> list:
161
+ view = view or TuiView()
162
+ if width < 20:
163
+ width = 20
164
+ snapshot = state.snapshot
165
+ error_count = len(snapshot.errors) if snapshot else 0
166
+ ok = snapshot.targets_ok if snapshot else 0
167
+ total = snapshot.targets_total if snapshot else 0
168
+ finished = state.last_finished_at or "-"
169
+ status = (
170
+ "已暂停" if state.paused
171
+ else "数据已过期" if state.stale
172
+ else ("刷新中" if state.refreshing else "")
173
+ )
174
+ lines = [
175
+ f"cloudgpu {config_path}",
176
+ f"更新 {finished} target {ok}/{total} "
177
+ f"错误 {error_count} {status}".rstrip(),
178
+ f"筛选 平台={view.platform or '-'} "
179
+ f"target={view.target or '-'} "
180
+ f"搜索={view.search or '-'} "
181
+ f"min={view.min_free} "
182
+ f"max={view.max_price if view.max_price is not None else '-'} "
183
+ f"排序={view.sort}",
184
+ "",
185
+ ]
186
+
187
+ if view.help:
188
+ lines.extend(_help_lines())
189
+ return _finish(lines, width, height)
190
+
191
+ lines.extend(
192
+ [
193
+ _header_line(),
194
+ "-" * min(width, 90),
195
+ ]
196
+ )
197
+
198
+ if not snapshot:
199
+ lines.append("等待第一次刷新...")
200
+ lines.append("行 0/0")
201
+ else:
202
+ rows = sort_rows(
203
+ filter_rows(snapshot_rows(snapshot), view),
204
+ view.sort,
205
+ )
206
+ window, start, count = visible_rows(
207
+ rows, view, table_height(height, state)
208
+ )
209
+ if not rows:
210
+ lines.append("没有符合条件的空闲资源")
211
+ else:
212
+ lines.extend(_row_line(row) for row in window)
213
+ lines.append(
214
+ f"行 {start + 1 if window else 0}-"
215
+ f"{start + len(window)} / {count}"
216
+ )
217
+
218
+ if snapshot and snapshot.errors:
219
+ lines.append("")
220
+ lines.append("错误:")
221
+ lines.extend(
222
+ f" {pad_cells(error.target, 16)} "
223
+ f"({error.platform}): {error.error}"
224
+ for error in snapshot.errors[:3]
225
+ )
226
+ if state.last_error:
227
+ lines.append("")
228
+ lines.append(f"刷新失败: {state.last_error}")
229
+ return _finish(lines, width, height)
230
+
231
+
232
+ def _header_line() -> str:
233
+ return (
234
+ f"{pad_cells('TARGET', 16)} "
235
+ f"{pad_cells('PLATFORM', 10)} "
236
+ f"{pad_cells('GPU', 24)} "
237
+ f"{pad_cells('REGION', 12)} "
238
+ f"{pad_cells('FREE', 7, 'right')} "
239
+ f"{pad_cells('PRICE', 8, 'right')} "
240
+ f"{pad_cells('VRAM', 6, 'right')}"
241
+ )
242
+
243
+
244
+ def _row_line(row) -> str:
245
+ vram = (
246
+ f"{row['gpu_memory_gb']}G"
247
+ if row["gpu_memory_gb"] is not None
248
+ else "-"
249
+ )
250
+ return (
251
+ f"{pad_cells(row['target'], 16)} "
252
+ f"{pad_cells(row['platform'], 10)} "
253
+ f"{pad_cells(row['gpu_model'], 24)} "
254
+ f"{pad_cells(row['region'] or '-', 12)} "
255
+ f"{pad_cells(format_free(row['free'], row['total']), 7, 'right')} "
256
+ f"{pad_cells(format_price(row['price_per_hour']), 8, 'right')} "
257
+ f"{pad_cells(vram, 6, 'right')}"
258
+ )
259
+
260
+
261
+ def _help_lines() -> list:
262
+ return [
263
+ "按键帮助",
264
+ " q 退出 r 立即刷新 p 暂停/恢复",
265
+ " s 切换排序 / 搜索型号/地区 c 清空筛选",
266
+ " f 平台筛选 t target 筛选",
267
+ " ↑/↓ 滚动 PgUp/PgDn 翻页 Home/End 顶部/底部",
268
+ " ? 关闭帮助",
269
+ ]
270
+
271
+
272
+ def _finish(lines, width, height) -> list:
273
+ lines = [truncate_cells(line, width) for line in lines]
274
+ if len(lines) > height:
275
+ visible = max(0, height - 1)
276
+ lines = lines[:visible] + [
277
+ f"... 还有 {len(lines) - visible} 行"
278
+ ]
279
+ return lines
280
+
281
+
282
+ def run_tui(
283
+ config,
284
+ *,
285
+ config_path=None,
286
+ adapters=None,
287
+ env=None,
288
+ view=None,
289
+ ) -> int:
290
+ try:
291
+ import curses
292
+ except ImportError:
293
+ import sys
294
+
295
+ print(
296
+ "错误: 当前平台没有 curses,请使用 "
297
+ "cloudgpu web 或桌面程序",
298
+ file=sys.stderr,
299
+ )
300
+ return 2
301
+
302
+ service = DashboardService(
303
+ config, adapters=adapters, env=env
304
+ )
305
+ service.start()
306
+ label = str(config_path) if config_path else "config"
307
+ active_view = view or TuiView()
308
+ try:
309
+ curses.wrapper(_loop, service, label, active_view)
310
+ except curses.error as exc:
311
+ import sys
312
+
313
+ print(
314
+ f"错误: 无法启动终端界面: {exc};"
315
+ "请使用 cloudgpu web 或桌面程序",
316
+ file=sys.stderr,
317
+ )
318
+ return 2
319
+ finally:
320
+ service.stop()
321
+ return 0
322
+
323
+
324
+ def _loop(stdscr, service, label, view) -> None:
325
+ import curses
326
+
327
+ try:
328
+ curses.curs_set(0)
329
+ except curses.error:
330
+ pass
331
+ stdscr.nodelay(True)
332
+ stdscr.timeout(500)
333
+ while True:
334
+ height, width = stdscr.getmaxyx()
335
+ lines = render_tui(
336
+ service.state(),
337
+ view,
338
+ width=width,
339
+ height=height,
340
+ config_path=label,
341
+ )
342
+ stdscr.erase()
343
+ for index, line in enumerate(lines[:height]):
344
+ try:
345
+ stdscr.addstr(
346
+ index, 0, line[: max(0, width - 1)]
347
+ )
348
+ except curses.error:
349
+ pass
350
+ stdscr.refresh()
351
+ try:
352
+ key = stdscr.getch()
353
+ except curses.error:
354
+ key = -1
355
+ if should_dismiss_help(
356
+ view.help, key, curses.KEY_RESIZE
357
+ ):
358
+ view.help = False
359
+ continue
360
+ if key in (ord("q"), ord("Q")):
361
+ break
362
+ if key in (ord("r"), ord("R")):
363
+ threading.Thread(
364
+ target=service.refresh, daemon=True
365
+ ).start()
366
+ elif key in (ord("p"), ord("P")):
367
+ service.set_paused(
368
+ not service.state().paused
369
+ )
370
+ elif key in (ord("s"), ord("S")):
371
+ index = (
372
+ SORTS.index(view.sort)
373
+ if view.sort in SORTS else 0
374
+ )
375
+ view.sort = SORTS[(index + 1) % len(SORTS)]
376
+ view.scroll = 0
377
+ elif key in (ord("c"), ord("C")):
378
+ view.platform = None
379
+ view.target = None
380
+ view.search = ""
381
+ view.min_free = 0
382
+ view.max_price = None
383
+ view.scroll = 0
384
+ elif key in (ord("f"), ord("F")):
385
+ _cycle_choice(
386
+ view, "platform", _platforms(service)
387
+ )
388
+ elif key in (ord("t"), ord("T")):
389
+ _cycle_choice(
390
+ view, "target", _targets(service)
391
+ )
392
+ elif key in (ord("/"),):
393
+ result = _prompt(
394
+ stdscr, "搜索: ", view.search
395
+ )
396
+ if result is not None:
397
+ view.search = result
398
+ view.scroll = 0
399
+ elif key in (ord("?"),):
400
+ view.help = True
401
+ elif key in (
402
+ curses.KEY_UP,
403
+ curses.KEY_DOWN,
404
+ curses.KEY_PPAGE,
405
+ curses.KEY_NPAGE,
406
+ curses.KEY_HOME,
407
+ curses.KEY_END,
408
+ ):
409
+ _scroll(service, view, key, height)
410
+
411
+
412
+ def should_dismiss_help(
413
+ help_open, key, resize_key
414
+ ) -> bool:
415
+ return (
416
+ help_open
417
+ and key != -1
418
+ and key != resize_key
419
+ )
420
+
421
+
422
+ def _platforms(service) -> list:
423
+ snapshot = service.state().snapshot
424
+ if snapshot is None:
425
+ return []
426
+ return sorted(
427
+ {
428
+ item.offer.platform
429
+ for item in snapshot.items
430
+ }
431
+ )
432
+
433
+
434
+ def _targets(service) -> list:
435
+ snapshot = service.state().snapshot
436
+ if snapshot is None:
437
+ return []
438
+ return sorted({item.target for item in snapshot.items})
439
+
440
+
441
+ def _cycle_choice(view, field, values) -> None:
442
+ choices = [None] + list(values)
443
+ current = getattr(view, field)
444
+ try:
445
+ index = choices.index(current)
446
+ except ValueError:
447
+ index = 0
448
+ setattr(view, field, choices[(index + 1) % len(choices)])
449
+ view.scroll = 0
450
+
451
+
452
+ def _scroll(service, view, key, height) -> None:
453
+ import curses
454
+
455
+ state = service.state()
456
+ snapshot = state.snapshot
457
+ rows = []
458
+ if snapshot is not None:
459
+ rows = sort_rows(
460
+ filter_rows(snapshot_rows(snapshot), view),
461
+ view.sort,
462
+ )
463
+ visible = table_height(height, state)
464
+ max_scroll = max(0, len(rows) - visible)
465
+ if key == curses.KEY_UP:
466
+ view.scroll -= 1
467
+ elif key == curses.KEY_DOWN:
468
+ view.scroll += 1
469
+ elif key == curses.KEY_PPAGE:
470
+ view.scroll -= visible
471
+ elif key == curses.KEY_NPAGE:
472
+ view.scroll += visible
473
+ elif key == curses.KEY_HOME:
474
+ view.scroll = 0
475
+ elif key == curses.KEY_END:
476
+ view.scroll = max_scroll
477
+ view.scroll = min(max(0, view.scroll), max_scroll)
478
+
479
+
480
+ def _prompt(stdscr, label, initial="") -> str:
481
+ import curses
482
+
483
+ text = list(initial)
484
+ stdscr.nodelay(False)
485
+ stdscr.timeout(-1)
486
+ try:
487
+ while True:
488
+ height, width = stdscr.getmaxyx()
489
+ prompt = label + "".join(text)
490
+ stdscr.move(height - 1, 0)
491
+ stdscr.clrtoeol()
492
+ stdscr.addstr(
493
+ height - 1,
494
+ 0,
495
+ truncate_cells(prompt, max(0, width - 1)),
496
+ )
497
+ stdscr.refresh()
498
+ try:
499
+ key = stdscr.get_wch()
500
+ except curses.error:
501
+ continue
502
+ if key in ("\n", "\r"):
503
+ return "".join(text)
504
+ if key == "\x1b":
505
+ return None
506
+ if key in ("\b", "\x7f", curses.KEY_BACKSPACE):
507
+ if text:
508
+ text.pop()
509
+ elif isinstance(key, str) and key.isprintable():
510
+ text.append(key)
511
+ finally:
512
+ stdscr.nodelay(True)
513
+ stdscr.timeout(500)