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.
@@ -0,0 +1,924 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+ from datetime import datetime, timezone
9
+ from typing import Callable, Optional
10
+
11
+ from cloudgpu.errors import AdapterError
12
+ from cloudgpu.models import AdapterCapabilities, GpuOffer
13
+
14
+ Fetch = Callable[[str, str, dict, Optional[dict], float], object]
15
+
16
+ BASE_URL = "https://api-cloud.gpugeek.com"
17
+ MARKET_URL = "https://gpugeek.com/computing-power-list"
18
+ MARKET_PATH = "/api/v1/compute/market"
19
+
20
+
21
+ class GPUGeekAdapter:
22
+ platform = "gpugeek"
23
+ BASE_URL = BASE_URL
24
+ MARKET_URL = MARKET_URL
25
+ MARKET_PATH = MARKET_PATH
26
+ BMS_PATH = "/api/v1/compute/market/bms"
27
+ MARKET_TAGS_PATH = "/api/v1/compute/market/tags"
28
+ BMS_TAGS_PATH = "/api/v1/compute/market/bms/tags"
29
+ capabilities = AdapterCapabilities(
30
+ read_only=True,
31
+ machine_level=False,
32
+ region=True,
33
+ price=True,
34
+ total=True,
35
+ )
36
+
37
+ def __init__(
38
+ self,
39
+ timeout: float = 15.0,
40
+ fetch: Optional[Fetch] = None,
41
+ clock=None,
42
+ ) -> None:
43
+ self.timeout = timeout
44
+ self._fetch = fetch or _http_json
45
+ self._clock = clock or (lambda: datetime.now(timezone.utc))
46
+
47
+ def list_offers(
48
+ self,
49
+ *,
50
+ gpu_model=None,
51
+ region=None,
52
+ min_free: int = 1,
53
+ max_price=None,
54
+ min_vram_gb=None,
55
+ min_ram_gb=None,
56
+ page_size: int = 100,
57
+ max_pages: int = 20,
58
+ ) -> list:
59
+ if page_size < 1:
60
+ raise ValueError("page_size 必须大于 0")
61
+ if max_pages < 1:
62
+ raise ValueError("max_pages 必须大于 0")
63
+ if min_free < 0:
64
+ raise ValueError("min_free 不能为负数")
65
+ for name, value in (
66
+ ("max_price", max_price),
67
+ ("min_vram_gb", min_vram_gb),
68
+ ("min_ram_gb", min_ram_gb),
69
+ ):
70
+ if value is not None and value < 0:
71
+ raise ValueError(f"{name} 不能为负数")
72
+
73
+ items, total, discount = self._fetch_all(
74
+ self.MARKET_PATH, page_size, max_pages
75
+ )
76
+ checked_at = _format_time(self._clock())
77
+ offers = []
78
+ seen = set()
79
+ for item in items:
80
+ offer = self._cloud_offer(item, discount, checked_at)
81
+ if offer.machine_id in seen:
82
+ raise AdapterError(
83
+ f"GPUGeek 分页出现重复规格 {offer.machine_id}"
84
+ )
85
+ seen.add(offer.machine_id)
86
+ if not _matches_cloud(
87
+ offer,
88
+ gpu_model=gpu_model,
89
+ region=region,
90
+ min_free=min_free,
91
+ max_price=max_price,
92
+ min_vram_gb=min_vram_gb,
93
+ min_ram_gb=min_ram_gb,
94
+ ):
95
+ continue
96
+ offers.append(offer)
97
+
98
+ offers.sort(
99
+ key=lambda offer: (
100
+ offer.price_per_hour is None,
101
+ offer.price_per_hour or 0,
102
+ offer.gpu_model,
103
+ offer.region or "",
104
+ offer.machine_id or "",
105
+ )
106
+ )
107
+ return offers
108
+
109
+ def list_bms(
110
+ self,
111
+ *,
112
+ gpu_model=None,
113
+ region=None,
114
+ min_available: int = 1,
115
+ max_price=None,
116
+ min_vram_gb=None,
117
+ min_ram_gb=None,
118
+ page_size: int = 100,
119
+ max_pages: int = 20,
120
+ ) -> list:
121
+ if page_size < 1:
122
+ raise ValueError("page_size 必须大于 0")
123
+ if max_pages < 1:
124
+ raise ValueError("max_pages 必须大于 0")
125
+ if min_available < 0:
126
+ raise ValueError("min_available 不能为负数")
127
+ for name, value in (
128
+ ("max_price", max_price),
129
+ ("min_vram_gb", min_vram_gb),
130
+ ("min_ram_gb", min_ram_gb),
131
+ ):
132
+ if value is not None and value < 0:
133
+ raise ValueError(f"{name} 不能为负数")
134
+
135
+ items, total, _ = self._fetch_all(
136
+ self.BMS_PATH, page_size, max_pages
137
+ )
138
+ rows = []
139
+ for item in items:
140
+ row = _bms_row(item)
141
+ if not _matches_bms(
142
+ row,
143
+ gpu_model=gpu_model,
144
+ region=region,
145
+ min_available=min_available,
146
+ max_price=max_price,
147
+ min_vram_gb=min_vram_gb,
148
+ min_ram_gb=min_ram_gb,
149
+ ):
150
+ continue
151
+ rows.append(row)
152
+
153
+ rows.sort(
154
+ key=lambda row: (
155
+ row["price_per_month"] is None,
156
+ row["price_per_month"] or 0,
157
+ row["gpu_name"],
158
+ row["region"],
159
+ row["dc_id"],
160
+ row["disk"] or "",
161
+ )
162
+ )
163
+ return rows
164
+
165
+ def list_models(self, *, kind: str = "cloud") -> list:
166
+ if kind not in ("cloud", "bms"):
167
+ raise ValueError(f"未知 GPUGeek 市场类型: {kind}")
168
+ entries = {}
169
+ if kind == "cloud":
170
+ offers = self.list_offers(min_free=0)
171
+ for offer in offers:
172
+ entry = entries.setdefault(
173
+ offer.gpu_model,
174
+ {
175
+ "name": offer.gpu_model,
176
+ "count": 0,
177
+ "min_price": None,
178
+ },
179
+ )
180
+ entry["count"] += 1
181
+ if offer.price_per_hour is not None and (
182
+ entry["min_price"] is None
183
+ or offer.price_per_hour < entry["min_price"]
184
+ ):
185
+ entry["min_price"] = offer.price_per_hour
186
+ tags = self._fetch_tags(self.MARKET_TAGS_PATH)
187
+ else:
188
+ rows = self.list_bms(min_available=0)
189
+ for row in rows:
190
+ entry = entries.setdefault(
191
+ row["gpu_name"],
192
+ {
193
+ "name": row["gpu_name"],
194
+ "count": 0,
195
+ "min_price": None,
196
+ },
197
+ )
198
+ entry["count"] += 1
199
+ if row["price_per_month"] is not None and (
200
+ entry["min_price"] is None
201
+ or row["price_per_month"] < entry["min_price"]
202
+ ):
203
+ entry["min_price"] = row["price_per_month"]
204
+ tags = self._fetch_tags(self.BMS_TAGS_PATH)
205
+
206
+ for name in tags["models"]:
207
+ entries.setdefault(
208
+ name,
209
+ {"name": name, "count": 0, "min_price": None},
210
+ )
211
+ return sorted(entries.values(), key=lambda item: item["name"])
212
+
213
+ def list_regions(self, *, kind: str = "cloud") -> list:
214
+ if kind not in ("cloud", "bms"):
215
+ raise ValueError(f"未知 GPUGeek 市场类型: {kind}")
216
+ counts = {}
217
+ if kind == "cloud":
218
+ offers = self.list_offers(min_free=0)
219
+ for offer in offers:
220
+ name = offer.region or "未知"
221
+ counts[name] = counts.get(name, 0) + 1
222
+ tags = self._fetch_tags(self.MARKET_TAGS_PATH)
223
+ else:
224
+ rows = self.list_bms(min_available=0)
225
+ for row in rows:
226
+ name = row["region"] or "未知"
227
+ counts[name] = counts.get(name, 0) + 1
228
+ tags = self._fetch_tags(self.BMS_TAGS_PATH)
229
+
230
+ for name in tags["regions"]:
231
+ counts.setdefault(name, 0)
232
+ return [
233
+ {"name": name, "count": count}
234
+ for name, count in sorted(counts.items())
235
+ ]
236
+
237
+ def _fetch_tags(self, path: str) -> dict:
238
+ url = f"{self.BASE_URL}{path}"
239
+ headers = {
240
+ "User-Agent": "cloudgpu/0.1",
241
+ "Referer": self.MARKET_URL,
242
+ "Accept": "application/json",
243
+ }
244
+ try:
245
+ response = self._fetch(
246
+ "GET", url, headers, None, self.timeout
247
+ )
248
+ except AdapterError:
249
+ raise
250
+ except Exception as exc:
251
+ raise AdapterError(
252
+ f"请求 GPUGeek 失败: {type(exc).__name__}"
253
+ ) from None
254
+ return _parse_tags(response)
255
+
256
+ def _fetch_all(self, path, page_size: int, max_pages: int):
257
+ items, total, discount = self._fetch_page(
258
+ path, 1, page_size
259
+ )
260
+ if total > page_size * max_pages:
261
+ raise AdapterError(
262
+ f"GPUGeek 共 {total} 条,分页 {max_pages} 页上限不足"
263
+ )
264
+
265
+ all_items = list(items)
266
+ seen_pages = {_page_fingerprint(items)}
267
+ page_number = 1
268
+ while len(all_items) < total:
269
+ page_number += 1
270
+ if page_number > max_pages:
271
+ raise AdapterError(
272
+ f"GPUGeek 分页超过上限 {max_pages}"
273
+ )
274
+ next_items, next_total, next_discount = (
275
+ self._fetch_page(path, page_number, page_size)
276
+ )
277
+ fingerprint = _page_fingerprint(next_items)
278
+ if fingerprint in seen_pages:
279
+ raise AdapterError(
280
+ "GPUGeek 分页出现重复页"
281
+ )
282
+ seen_pages.add(fingerprint)
283
+ if next_total != total:
284
+ raise AdapterError(
285
+ "GPUGeek 分页期间总数发生变化"
286
+ )
287
+ if next_discount != discount:
288
+ raise AdapterError(
289
+ "GPUGeek 分页期间折扣发生变化"
290
+ )
291
+ all_items.extend(next_items)
292
+
293
+ if len(all_items) != total:
294
+ raise AdapterError(
295
+ f"GPUGeek 分页结果不完整:预期 {total} 条,"
296
+ f"实得 {len(all_items)} 条"
297
+ )
298
+ return all_items, total, discount
299
+
300
+ def _fetch_page(self, path, page_number: int, page_size: int):
301
+ params = {
302
+ "pn": page_number,
303
+ "ps": page_size,
304
+ "sort": "0",
305
+ }
306
+ url = (
307
+ f"{self.BASE_URL}{path}?"
308
+ f"{urllib.parse.urlencode(params)}"
309
+ )
310
+ headers = {
311
+ "User-Agent": "cloudgpu/0.1",
312
+ "Referer": self.MARKET_URL,
313
+ "Accept": "application/json",
314
+ }
315
+ try:
316
+ response = self._fetch(
317
+ "GET", url, headers, None, self.timeout
318
+ )
319
+ except AdapterError:
320
+ raise
321
+ except Exception as exc:
322
+ raise AdapterError(
323
+ f"请求 GPUGeek 失败: {type(exc).__name__}"
324
+ ) from None
325
+ return _validate_page(
326
+ response, path, page_number, page_size
327
+ )
328
+
329
+ def _cloud_offer(self, item, discount, checked_at: str) -> GpuOffer:
330
+ if not isinstance(item, dict):
331
+ raise AdapterError(
332
+ "GPUGeek 响应格式异常: 列表项不是对象"
333
+ )
334
+ gpu_name = item.get("gpuName")
335
+ if not isinstance(gpu_name, str) or not gpu_name.strip():
336
+ raise AdapterError(
337
+ "GPUGeek 响应格式异常: gpuName 非法"
338
+ )
339
+ dc_id = item.get("dcId")
340
+ if not isinstance(dc_id, str) or not dc_id.strip():
341
+ raise AdapterError(
342
+ "GPUGeek 响应格式异常: dcId 非法"
343
+ )
344
+ gpu_num = _as_int(item.get("gpuNum"), "gpuNum", gpu_name)
345
+ used = _as_int(
346
+ item.get("gpuUsedNum"), "gpuUsedNum", gpu_name
347
+ )
348
+ if gpu_num < 0 or used < 0 or used > gpu_num:
349
+ raise AdapterError(
350
+ f"GPUGeek 响应格式异常: {gpu_name} 卡数非法"
351
+ )
352
+ free = gpu_num - used
353
+
354
+ region = (
355
+ item.get("dcName")
356
+ or item.get("regionName")
357
+ or dc_id
358
+ )
359
+ if not isinstance(region, str) or not region.strip():
360
+ raise AdapterError(
361
+ f"GPUGeek 响应格式异常: {gpu_name} 地区为空"
362
+ )
363
+ cpu_name = item.get("cpuName")
364
+ if cpu_name is not None and not isinstance(cpu_name, str):
365
+ raise AdapterError(
366
+ f"GPUGeek 响应格式异常: {gpu_name}.cpuName 非法"
367
+ )
368
+ cpu_cores = item.get("cpuCoreNum")
369
+ if cpu_cores is not None:
370
+ cpu_cores = _as_int(
371
+ cpu_cores, "cpuCoreNum", gpu_name
372
+ )
373
+ if cpu_cores < 0:
374
+ raise AdapterError(
375
+ f"GPUGeek 响应格式异常: {gpu_name}.cpuCoreNum 为负"
376
+ )
377
+
378
+ memory_bytes = item.get("memorySize")
379
+ if memory_bytes is not None:
380
+ memory_bytes = _as_optional_float(
381
+ memory_bytes, "memorySize", gpu_name
382
+ )
383
+ if memory_bytes is not None and memory_bytes < 0:
384
+ raise AdapterError(
385
+ f"GPUGeek 响应格式异常: {gpu_name}.memorySize 为负"
386
+ )
387
+ memory_gb = (
388
+ round(memory_bytes / 1024**3, 1)
389
+ if memory_bytes is not None
390
+ else None
391
+ )
392
+
393
+ vram_gb = _as_optional_float(
394
+ item.get("vRam"), "vRam", gpu_name
395
+ )
396
+ if vram_gb is not None and vram_gb < 0:
397
+ raise AdapterError(
398
+ f"GPUGeek 响应格式异常: {gpu_name}.vRam 为负"
399
+ )
400
+ price = _as_optional_float(
401
+ item.get("price"), "price", gpu_name
402
+ )
403
+ if price is not None and price < 0:
404
+ raise AdapterError(
405
+ f"GPUGeek 响应格式异常: {gpu_name}.price 为负"
406
+ )
407
+ price_per_hour = (
408
+ None
409
+ if price is None
410
+ else round(price * discount, 2)
411
+ )
412
+
413
+ spec_id = (
414
+ f"{dc_id}|{gpu_name}|{cpu_name or ''}|"
415
+ f"{cpu_cores or 0}c|{_num(memory_gb)}g|"
416
+ f"{_num(vram_gb)}g"
417
+ )
418
+
419
+ return GpuOffer(
420
+ platform=self.platform,
421
+ service_kind="cloud",
422
+ gpu_model=gpu_name,
423
+ display_name=gpu_name,
424
+ description=cpu_name or "",
425
+ gpu_memory_gb=(
426
+ round(vram_gb) if vram_gb is not None else None
427
+ ),
428
+ free=free,
429
+ total=gpu_num,
430
+ region=region,
431
+ machine_id=spec_id,
432
+ price_per_hour=price_per_hour,
433
+ charge_type="payg",
434
+ url=self.MARKET_URL,
435
+ checked_at=checked_at,
436
+ extra={
437
+ "dc_id": dc_id,
438
+ "region_name": item.get("regionName"),
439
+ "cpu_name": cpu_name,
440
+ "cpu_core_num": cpu_cores,
441
+ "memory_bytes": memory_bytes,
442
+ "memory_gb": memory_gb,
443
+ "vram_gb": vram_gb,
444
+ "instance_discount": discount,
445
+ "original_price": price,
446
+ "discounted_price": price_per_hour,
447
+ "label_id": item.get("labelId"),
448
+ "label_name": item.get("labelName"),
449
+ "icon_url": item.get("iconUrl"),
450
+ "created_at": item.get("createdAt"),
451
+ "raw": dict(item),
452
+ },
453
+ )
454
+
455
+
456
+ def _page_fingerprint(items) -> str:
457
+ return json.dumps(items, sort_keys=True, ensure_ascii=False)
458
+
459
+
460
+ def _parse_tags(response) -> dict:
461
+ if not isinstance(response, dict):
462
+ raise AdapterError("GPUGeek 标签响应异常: 顶层不是对象")
463
+ code = response.get("code")
464
+ if isinstance(code, bool) or code != 0:
465
+ raise AdapterError(
466
+ f"GPUGeek 返回错误 code={code!r}: "
467
+ f"{response.get('message') or ''}"
468
+ )
469
+ data = response.get("data")
470
+ if not isinstance(data, dict):
471
+ raise AdapterError("GPUGeek 标签响应异常: 缺少 data")
472
+ tags = data.get("tags")
473
+ if not isinstance(tags, dict):
474
+ raise AdapterError("GPUGeek 标签响应异常: 缺少 tags")
475
+
476
+ gpu_types = tags.get("GpuType")
477
+ if not isinstance(gpu_types, list):
478
+ raise AdapterError(
479
+ "GPUGeek 标签响应异常: GpuType 不是数组"
480
+ )
481
+ models = []
482
+ for item in gpu_types:
483
+ if (
484
+ not isinstance(item, dict)
485
+ or not isinstance(item.get("name"), str)
486
+ or not item["name"].strip()
487
+ ):
488
+ raise AdapterError(
489
+ "GPUGeek 标签响应异常: GpuType 名称非法"
490
+ )
491
+ models.append(item["name"])
492
+
493
+ dc_info = tags.get("dcInfo")
494
+ if not isinstance(dc_info, list):
495
+ raise AdapterError(
496
+ "GPUGeek 标签响应异常: dcInfo 不是数组"
497
+ )
498
+ regions = []
499
+ for item in dc_info:
500
+ if (
501
+ not isinstance(item, dict)
502
+ or not isinstance(item.get("dcName"), str)
503
+ or not item["dcName"].strip()
504
+ ):
505
+ raise AdapterError(
506
+ "GPUGeek 标签响应异常: dcInfo 名称非法"
507
+ )
508
+ if item["dcName"] not in regions:
509
+ regions.append(item["dcName"])
510
+
511
+ groups = tags.get("dcGroups")
512
+ if groups is not None:
513
+ if not isinstance(groups, list):
514
+ raise AdapterError(
515
+ "GPUGeek 标签响应异常: dcGroups 不是数组"
516
+ )
517
+ for group in groups:
518
+ if not isinstance(group, dict):
519
+ raise AdapterError(
520
+ "GPUGeek 标签响应异常: dcGroups 项非法"
521
+ )
522
+ datacenters = group.get("datacenters")
523
+ if not isinstance(datacenters, list):
524
+ raise AdapterError(
525
+ "GPUGeek 标签响应异常: datacenters 不是数组"
526
+ )
527
+ for dc in datacenters:
528
+ if (
529
+ not isinstance(dc, dict)
530
+ or not isinstance(dc.get("dcName"), str)
531
+ or not dc["dcName"].strip()
532
+ ):
533
+ raise AdapterError(
534
+ "GPUGeek 标签响应异常: 数据中心名称非法"
535
+ )
536
+ if dc["dcName"] not in regions:
537
+ regions.append(dc["dcName"])
538
+
539
+ return {"models": models, "regions": regions}
540
+
541
+
542
+ def _bms_row(item) -> dict:
543
+ if not isinstance(item, dict):
544
+ raise AdapterError(
545
+ "GPUGeek 响应格式异常: BMS 列表项不是对象"
546
+ )
547
+ gpu_name = item.get("gpuName")
548
+ if not isinstance(gpu_name, str) or not gpu_name.strip():
549
+ raise AdapterError(
550
+ "GPUGeek 响应格式异常: BMS gpuName 非法"
551
+ )
552
+ dc_id = item.get("dcId")
553
+ if not isinstance(dc_id, str) or not dc_id.strip():
554
+ raise AdapterError(
555
+ f"GPUGeek 响应格式异常: {gpu_name}.dcId 非法"
556
+ )
557
+ region = (
558
+ item.get("dcName")
559
+ or item.get("regionName")
560
+ or dc_id
561
+ )
562
+ if not isinstance(region, str) or not region.strip():
563
+ raise AdapterError(
564
+ f"GPUGeek 响应格式异常: {gpu_name} 地区为空"
565
+ )
566
+
567
+ gpu_num = _as_int(item.get("gpuNum"), "gpuNum", gpu_name)
568
+ if gpu_num < 0:
569
+ raise AdapterError(
570
+ f"GPUGeek 响应格式异常: {gpu_name}.gpuNum 为负"
571
+ )
572
+ if "count" not in item:
573
+ raise AdapterError(
574
+ f"GPUGeek 响应格式异常: {gpu_name}.count 缺失"
575
+ )
576
+ available = _as_int(item.get("count"), "count", gpu_name)
577
+ if available < 0:
578
+ raise AdapterError(
579
+ f"GPUGeek 响应格式异常: {gpu_name}.count 为负"
580
+ )
581
+
582
+ cpu_name = _optional_str(
583
+ item.get("cpuName"), "cpuName", gpu_name
584
+ )
585
+ cpu_cores = item.get("cpuCoreNum")
586
+ if cpu_cores is not None:
587
+ cpu_cores = _as_int(
588
+ cpu_cores, "cpuCoreNum", gpu_name
589
+ )
590
+ if cpu_cores < 0:
591
+ raise AdapterError(
592
+ f"GPUGeek 响应格式异常: {gpu_name}.cpuCoreNum 为负"
593
+ )
594
+
595
+ memory_gb = _as_optional_float(
596
+ item.get("memorySize"), "memorySize", gpu_name
597
+ )
598
+ if memory_gb is not None and memory_gb < 0:
599
+ raise AdapterError(
600
+ f"GPUGeek 响应格式异常: {gpu_name}.memorySize 为负"
601
+ )
602
+ vram_gb = _as_optional_float(
603
+ item.get("vRam"), "vRam", gpu_name
604
+ )
605
+ if vram_gb is not None and vram_gb < 0:
606
+ raise AdapterError(
607
+ f"GPUGeek 响应格式异常: {gpu_name}.vRam 为负"
608
+ )
609
+ price = _as_optional_float(
610
+ item.get("price"), "price", gpu_name
611
+ )
612
+ if price is not None and price < 0:
613
+ raise AdapterError(
614
+ f"GPUGeek 响应格式异常: {gpu_name}.price 为负"
615
+ )
616
+
617
+ return {
618
+ "gpu_name": gpu_name,
619
+ "gpu_num": gpu_num,
620
+ "available": available,
621
+ "price_per_month": price,
622
+ "cpu_name": cpu_name,
623
+ "cpu_cores": cpu_cores,
624
+ "memory_gb": memory_gb,
625
+ "vram_gb": vram_gb,
626
+ "disk": _optional_str(
627
+ item.get("diskDesc"), "diskDesc", gpu_name
628
+ ),
629
+ "nic": _optional_str(
630
+ item.get("nicDesc"), "nicDesc", gpu_name
631
+ ),
632
+ "region": region,
633
+ "dc_id": dc_id,
634
+ "channel": _optional_str(
635
+ item.get("channel"), "channel", gpu_name
636
+ ),
637
+ "label_name": _optional_str(
638
+ item.get("labelName"), "labelName", gpu_name
639
+ ),
640
+ "raw": dict(item),
641
+ }
642
+
643
+
644
+ def _matches_bms(
645
+ row,
646
+ *,
647
+ gpu_model,
648
+ region,
649
+ min_available,
650
+ max_price,
651
+ min_vram_gb,
652
+ min_ram_gb,
653
+ ) -> bool:
654
+ if (
655
+ gpu_model
656
+ and gpu_model.casefold() not in row["gpu_name"].casefold()
657
+ ):
658
+ return False
659
+ if region:
660
+ haystack = (
661
+ f"{row['region']} "
662
+ f"{row['raw'].get('regionName') or ''} "
663
+ f"{row['dc_id']}"
664
+ ).casefold()
665
+ if region.casefold() not in haystack:
666
+ return False
667
+ if row["available"] < min_available:
668
+ return False
669
+ if max_price is not None:
670
+ if (
671
+ row["price_per_month"] is None
672
+ or row["price_per_month"] > max_price
673
+ ):
674
+ return False
675
+ if min_vram_gb is not None:
676
+ if (
677
+ row["vram_gb"] is None
678
+ or row["vram_gb"] < min_vram_gb
679
+ ):
680
+ return False
681
+ if min_ram_gb is not None:
682
+ gpu_num = row["gpu_num"]
683
+ memory_gb = row["memory_gb"]
684
+ if (
685
+ memory_gb is None
686
+ or not gpu_num
687
+ or gpu_num <= 0
688
+ or memory_gb / gpu_num < min_ram_gb
689
+ ):
690
+ return False
691
+ return True
692
+
693
+
694
+ def _matches_cloud(
695
+ offer,
696
+ *,
697
+ gpu_model,
698
+ region,
699
+ min_free,
700
+ max_price,
701
+ min_vram_gb,
702
+ min_ram_gb,
703
+ ) -> bool:
704
+ if (
705
+ gpu_model
706
+ and gpu_model.casefold() not in offer.gpu_model.casefold()
707
+ ):
708
+ return False
709
+ if region:
710
+ extra = offer.extra or {}
711
+ haystack = (
712
+ f"{offer.region or ''} "
713
+ f"{extra.get('region_name') or ''} "
714
+ f"{extra.get('dc_id') or ''}"
715
+ ).casefold()
716
+ if region.casefold() not in haystack:
717
+ return False
718
+ if offer.free < min_free:
719
+ return False
720
+ if max_price is not None:
721
+ if (
722
+ offer.price_per_hour is None
723
+ or offer.price_per_hour > max_price
724
+ ):
725
+ return False
726
+ if min_vram_gb is not None:
727
+ if (
728
+ offer.gpu_memory_gb is None
729
+ or offer.gpu_memory_gb < min_vram_gb
730
+ ):
731
+ return False
732
+ if min_ram_gb is not None:
733
+ memory_gb = (offer.extra or {}).get("memory_gb")
734
+ if (
735
+ memory_gb is None
736
+ or not offer.total
737
+ or offer.total <= 0
738
+ or memory_gb / offer.total < min_ram_gb
739
+ ):
740
+ return False
741
+ return True
742
+
743
+
744
+ def _validate_page(response, path, page_number, page_size):
745
+ if not isinstance(response, dict):
746
+ raise AdapterError("GPUGeek 响应格式异常: 顶层不是对象")
747
+ code = response.get("code")
748
+ if isinstance(code, bool) or code != 0:
749
+ raise AdapterError(
750
+ f"GPUGeek 返回错误 code={code!r}: "
751
+ f"{response.get('message') or ''}"
752
+ )
753
+ data = response.get("data")
754
+ if not isinstance(data, dict):
755
+ raise AdapterError("GPUGeek 响应格式异常: 缺少 data")
756
+ total = _as_int(data.get("total"), "total", "data")
757
+ if total < 0:
758
+ raise AdapterError("GPUGeek 响应格式异常: total 为负")
759
+ pn = _as_int(data.get("pn"), "pn", "data")
760
+ ps = _as_int(data.get("ps"), "ps", "data")
761
+ if pn != page_number:
762
+ raise AdapterError(
763
+ f"GPUGeek 分页异常: 请求第 {page_number} 页,返回第 {pn} 页"
764
+ )
765
+ if ps != page_size:
766
+ raise AdapterError(
767
+ f"GPUGeek 分页异常: 请求每页 {page_size} 条,返回 {ps} 条"
768
+ )
769
+ items = data.get("list")
770
+ if not isinstance(items, list):
771
+ raise AdapterError("GPUGeek 响应格式异常: list 不是数组")
772
+ if total == 0 and items:
773
+ raise AdapterError(
774
+ "GPUGeek 响应格式异常: total 为 0 但仍有列表项"
775
+ )
776
+ if total > 0 and not items:
777
+ raise AdapterError(
778
+ "GPUGeek 响应格式异常: total 大于 0 但列表为空"
779
+ )
780
+ discount = _discount(data.get("instanceDiscount"))
781
+ return items, total, discount
782
+
783
+
784
+ def _discount(value) -> float:
785
+ if value in (None, ""):
786
+ return 1.0
787
+ number = _as_optional_float(
788
+ value, "instanceDiscount", "data"
789
+ )
790
+ if number is None:
791
+ return 1.0
792
+ if number < 0:
793
+ raise AdapterError(
794
+ "GPUGeek 响应格式异常: instanceDiscount 为负"
795
+ )
796
+ return 1.0 if number == 0 else number
797
+
798
+
799
+ def _as_int(value, field: str, context: str) -> int:
800
+ if isinstance(value, bool):
801
+ raise AdapterError(
802
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
803
+ )
804
+ if isinstance(value, int):
805
+ return value
806
+ if isinstance(value, float) and value.is_integer():
807
+ return int(value)
808
+ if isinstance(value, str):
809
+ try:
810
+ number = float(value.strip())
811
+ except ValueError:
812
+ raise AdapterError(
813
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
814
+ ) from None
815
+ if not number.is_integer():
816
+ raise AdapterError(
817
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
818
+ )
819
+ return int(number)
820
+ raise AdapterError(
821
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
822
+ )
823
+
824
+
825
+ def _as_optional_float(value, field: str, context: str):
826
+ if value in (None, ""):
827
+ return None
828
+ if isinstance(value, bool):
829
+ raise AdapterError(
830
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
831
+ )
832
+ if isinstance(value, (int, float)):
833
+ number = float(value)
834
+ elif isinstance(value, str):
835
+ try:
836
+ number = float(value.strip())
837
+ except ValueError:
838
+ raise AdapterError(
839
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
840
+ ) from None
841
+ else:
842
+ raise AdapterError(
843
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
844
+ )
845
+ if not math.isfinite(number):
846
+ raise AdapterError(
847
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
848
+ )
849
+ return number
850
+
851
+
852
+ def _optional_str(value, field: str, context: str):
853
+ if value in (None, ""):
854
+ return None
855
+ if not isinstance(value, str):
856
+ raise AdapterError(
857
+ f"GPUGeek 响应格式异常: {context}.{field} 非法"
858
+ )
859
+ return value
860
+
861
+
862
+ def _num(value) -> str:
863
+ if value is None:
864
+ return ""
865
+ return f"{value:g}"
866
+
867
+
868
+ def _format_time(value: datetime) -> str:
869
+ if value.tzinfo is None:
870
+ value = value.replace(tzinfo=timezone.utc)
871
+ return value.astimezone(timezone.utc).strftime(
872
+ "%Y-%m-%dT%H:%M:%SZ"
873
+ )
874
+
875
+
876
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
877
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
878
+ raise AdapterError(
879
+ f"GPUGeek 返回重定向 HTTP {code},已拒绝跟随"
880
+ )
881
+
882
+
883
+ def _http_json(
884
+ method: str,
885
+ url: str,
886
+ headers: dict,
887
+ payload: Optional[dict],
888
+ timeout: float,
889
+ ) -> object:
890
+ body = None
891
+ if payload is not None:
892
+ body = json.dumps(payload, ensure_ascii=False).encode(
893
+ "utf-8"
894
+ )
895
+ request = urllib.request.Request(
896
+ url,
897
+ data=body,
898
+ headers=headers,
899
+ method=method,
900
+ )
901
+ opener = urllib.request.build_opener(_NoRedirect)
902
+ try:
903
+ with opener.open(request, timeout=timeout) as response:
904
+ raw = response.read()
905
+ except urllib.error.HTTPError as exc:
906
+ if exc.code == 429:
907
+ raise AdapterError("GPUGeek 请求被限流") from None
908
+ raise AdapterError(
909
+ f"请求 GPUGeek 失败: HTTP {exc.code}"
910
+ ) from None
911
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
912
+ reason = getattr(exc, "reason", None) or type(
913
+ exc
914
+ ).__name__
915
+ raise AdapterError(
916
+ f"请求 GPUGeek 失败: {reason}"
917
+ ) from None
918
+
919
+ try:
920
+ return json.loads(raw.decode("utf-8"))
921
+ except (UnicodeDecodeError, json.JSONDecodeError):
922
+ raise AdapterError(
923
+ "GPUGeek 响应不是合法 JSON"
924
+ ) from None