Qilan2 commited on
Commit
67a8c41
·
verified ·
1 Parent(s): 8a32955

Update nv1/nv1.py

Browse files
Files changed (1) hide show
  1. nv1/nv1.py +290 -292
nv1/nv1.py CHANGED
@@ -1,22 +1,55 @@
1
  import subprocess
2
  import os
3
- import threading
4
  import time
5
- import yaml
6
- from datetime import datetime
7
- import signal
8
- import psutil
9
- import glob
10
- import re
11
- import pytz
12
- import requests
13
  import json
14
  import random
15
  import string
 
16
  import urllib3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- # DATA_JSON = os.environ.get('DATA_JSON', '')
19
- DATA_JSON =''' {
20
  "N_PORT": "7860",
21
  "ARGO_PORT": "8009",
22
  "ARGO_DOMAIN": "z.282820.xyz",
@@ -25,154 +58,114 @@ DATA_JSON =''' {
25
  "NZV1_VERSION": "v1.13.1",
26
  "BACKUP_TIME": "3600",
27
  "RESTART_TIME":"99999999",
28
- "HF_USER1": "qilanqi",
29
  "HF_REPO": "hf-nv1",
30
- "HF_EMAIL": "HermanBrand@mffac.com",
31
- "HF_TOKEN1": "hf_vF dlQdHyROFvdXzMOvocNKbniDwsukVaTe",
32
- "HF_USER2": "bcvbrer",
33
- "HF_ID": "fsawpot",
34
- "HF_EMAIL2": "o4e3aqv9@nqmo.com",
35
- "HF_TOKEN2": "hf_hM GFvOurTJWjECuJdRwmpjKmNrRQSjpUEE",
36
- "CHAT_ID": "-4829459058",
37
- "BOT_TOKEN": "8259739796:AAGZY4tboUxJ3jnMi1GTpGtV3_-Tf2rMT7I"
38
  }
39
  '''
 
 
 
 
 
40
  ff_url = "https://z.282820.xyz/"
41
- HF_SPACES_NAME = os.environ.get('HF_SPACES_NAME', '')# 上个spaces名
42
  def assign_vars_from_json(config: dict):
43
  for key, value in config.items():
44
  globals()[key] = value
45
 
46
- if DATA_JSON: # 如果 DATA_JSON 有值
47
  try:
48
- config_dict = json.loads(DATA_JSON) # 解析 JSON 字符串
49
  assign_vars_from_json(config_dict)
50
  except json.JSONDecodeError:
51
- raise ValueError("DATA_JSON 环境变量不是合法的 JSON 字符串")
52
- else: # 如果 DATA_JSON 为空,就从单独的环境变量里取
53
- N_PORT = os.environ.get('N_PORT', '8008') # N Z端口 默认8008
54
- ARGO_PORT = os.environ.get('ARGO_PORT', '8009') # Argo(nginx的反代端口)固定隧道端口,留空默认8009
55
- ARGO_DOMAIN = os.environ.get('ARGO_DOMAIN', '') # Argo固定隧道域名,留空即使用临时隧道
56
- ARGO_AUTH = os.environ.get('ARGO_AUTH', '') # Argo固定隧道密钥,留空即使用临时隧道
57
- DASHBOARD_VERSION = os.environ.get('DASHBOARD_VERSION', 'v1.13.2')# 指定面板的版本,以 v0.00.00 的格式,后续将固定在该版本不会升级,不填则使用默认的 v1.13.2
58
- NZV1_VERSION = os.environ.get('NZV1_VERSION', 'v1.13.1')# 哪吒V1的版本默认v1.13.1
59
- BACKUP_TIME = os.environ.get('BACKUP_TIME', '3600')# 备份时间 10800秒 2小时
60
- RESTART_TIME = os.environ.get('RESTART_TIME', '14400')# 重启时间 4小时 14400 6小时 21600
61
-
62
-
63
- HF_USER1 = os.environ.get('HF_USER1', '')# HF 备份仓库的用户名
64
- HF_REPO = os.environ.get('HF_REPO', '')#HF 备份的Models仓库名
65
- HF_EMAIL = os.environ.get('HF_EMAIL', '') #HF的邮箱
66
- HF_TOKEN1 = os.environ.get('HF_TOKEN1', '')#HF备份账号的TOKEN
67
-
68
- HF_USER2 = os.environ.get('HF_USER2', '')# huggingface 用户名
69
- HF_ID = os.environ.get('HF_ID', '')# huggingface space 名
70
- HF_TOKEN2 = os.environ.get('HF_TOKEN2', '')# huggingface TOKEN
71
 
72
- CHAT_ID = os.environ.get('CHAT_ID', '')# Telegram chat_id,推送通知
73
- BOT_TOKEN = os.environ.get('BOT_TOKEN', '')# Telegram bot_token
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  def check_url_status(url, timeout=5):
76
- """
77
- 检查URL是否可以正常访问
78
-
79
- 参数:
80
- url (str): 要检查的URL地址
81
- timeout (int): 请求超时时间,默认为5秒
82
-
83
- 返回:
84
- bool: 网站是否可以正常访问
85
- """
86
  try:
87
- # 发送GET请求
88
- response = requests.get(url, timeout=timeout)
89
-
90
- # 检查响应状态码是否在200-299范围内
91
  return 200 <= response.status_code < 300
92
-
93
  except requests.RequestException:
94
- # 捕获所有请求相关的异常,包括连接错误、超时等
95
  return False
96
 
97
- # 使用示例
98
-
99
-
100
  def random_name(length=8):
101
  return ''.join(random.choices(string.ascii_lowercase, k=length))
102
 
103
- def update_value(data: dict, key: str, new_value: str) -> dict:
104
- if key in data:
105
- data[key] = new_value
106
- else:
107
- print(f"!!! Key '{key}' ON")
108
- return data
109
  def telegram_message(bot_token: str, chat_id: str, message: str):
 
 
110
  try:
111
- # 转义特殊字符,避免MarkdownV2解析错误
112
  def escape_markdown(text):
113
  escape_chars = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
114
  return ''.join('\\' + char if char in escape_chars else char for char in text)
115
 
116
- # 对消息进行转义
117
- escaped_message = escape_markdown(message)
118
 
119
- url = f"https://tgbotapi.9.c.5.b.0.d.0.0.1.0.a.2.ip6.arpa/bot{bot_token}/sendMessage"
120
-
121
- # 详细的请求参数
122
  params = {
123
  "chat_id": chat_id,
124
- "text": escaped_message,
125
  "parse_mode": "MarkdownV2"
126
  }
127
 
128
- # 禁用不安全请求警告
129
- urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
130
-
131
- # 增加超时和详细日志
132
- response = requests.post(
133
- url,
134
- params=params,
135
- verify=False,
136
- timeout=10 # 设置超时时间
137
- )
138
-
139
- # 打印完整的响应信息
140
- print(f"Response Status Code: {response.status_code}")
141
- print(f"Response Content: {response.text}")
142
-
143
- # 检查响应
144
- if response.status_code == 200:
145
- return response.json()
146
- else:
147
- return {
148
- "status_code": response.status_code,
149
- "text": response.text
150
- }
151
-
152
- except requests.exceptions.RequestException as e:
153
- print(f"请求异常: {e}")
154
- return {"error": str(e)}
155
  except Exception as e:
156
- print(f"未知异常: {e}")
157
- return {"error": str(e)}
158
 
159
- # 创建、删除、设置 secrets、修改 Dockerfile 等操作
160
- def create_space(type, key="", value="", name=""):
161
- # 确保 /workdir 存在
162
  workdir_root = "/workdir"
163
  try:
164
  os.makedirs(workdir_root, exist_ok=True)
165
- except Exception as e:
166
- print("无法创建 /workdir:", e)
167
- raise
168
 
169
- if type == 1:
170
- # 创建 space
 
 
171
  url = "https://huggingface.co/api/repos/create"
172
  headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
173
- name = random_name(10)
174
  payload = {
175
- "name": name,
176
  "type": "space",
177
  "private": True,
178
  "sleepTimeSeconds": 172800,
@@ -180,212 +173,217 @@ def create_space(type, key="", value="", name=""):
180
  }
181
  try:
182
  resp = requests.post(url, headers=headers, json=payload, timeout=15)
 
 
 
183
  resp.raise_for_status()
184
  return resp.json()
185
  except requests.RequestException as e:
186
- print("创建 space 失败:", e)
187
- return {"error": str(e)}
 
 
 
 
 
 
188
 
189
- if type == 2:
 
190
  url = "https://huggingface.co/api/repos/delete"
191
- headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
192
  payload = {"organization": HF_USER2, "name": name, "type": "space"}
193
  try:
194
  resp = requests.delete(url, headers=headers, json=payload, timeout=15)
195
- return {"status_code": resp.status_code, "text": resp.text}
196
- except requests.RequestException as e:
197
- return {"error": str(e)}
198
 
199
- if type == 3:
 
200
  url = f"https://huggingface.co/api/spaces/{HF_USER2}/{name}/secrets"
201
- headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
202
- payload = {"key": key, "value": value, "description": ""}
203
  try:
204
- resp = requests.post(url, headers=headers, json=payload, timeout=15)
205
- return {"status_code": resp.status_code, "text": resp.text}
206
- except requests.RequestException as e:
207
- return {"error": str(e)}
208
 
209
- if type == 4:
210
- # 下载并替换 Dockerfile,然后提交到空间仓库
211
  repo_path = f"/workdir/{name}"
212
- dockerfile_path = os.path.join(repo_path, "Dockerfile")
213
-
214
- # 克隆仓库前确保目标父目录存在
215
- os.makedirs(repo_path, exist_ok=True)
216
-
217
- git_url = f"https://{HF_USER2}:{HF_TOKEN2}@huggingface.co/spaces/{HF_USER2}/{name}"
218
- print("git clone 命令:", git_url, "->", repo_path)
219
-
220
- # 使用 subprocess.run 执行 git clone(捕获错误)
221
  try:
222
- # 如果目录为空(刚创建),直接 clone 会写入 repo_path;如果已存在 .git 则跳过 clone
223
- if not os.path.exists(os.path.join(repo_path, ".git")):
224
- subprocess.run(["git", "clone", git_url, repo_path], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
225
- else:
226
- print("目标已有 .git,跳过 clone,改为 git pull")
227
- subprocess.run(["git", "-C", repo_path, "pull"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
228
- except subprocess.CalledProcessError as e:
229
- print("git clone/pull 失败:", e.stderr.decode() if e.stderr else e)
230
- return {"error": "git clone/pull failed", "detail": str(e)}
231
-
232
- # 配置 git 用户信息(repo 内 global 配置可能覆盖)
233
- try:
234
- subprocess.run(["git", "-C", repo_path, "config", "user.email", HF_EMAIL2], check=True)
235
- subprocess.run(["git", "-C", repo_path, "config", "user.name", HF_USER2], check=True)
236
- except subprocess.CalledProcessError as e:
237
- print("git config 失败:", e)
238
- # 继续执行,不致命
239
-
240
- # 下载 Dockerfile(示例来源 URL)
241
- url = "https://huggingface.co/datasets/Qilan2/ff/raw/main/nv1/Dockerfile"
242
- try:
243
- r = requests.get(url, timeout=15)
244
  if r.status_code == 200:
245
- # 确保目录存在
246
- os.makedirs(os.path.dirname(dockerfile_path), exist_ok=True)
247
- with open(dockerfile_path, "wb") as f:
 
 
248
  f.write(r.content)
249
- print("Dockerfile 下载并写入:", dockerfile_path)
250
- else:
251
- print("下载 Dockerfile 失败,状态码:", r.status_code)
252
- return {"error": "download Dockerfile failed", "status": r.status_code}
253
- except requests.RequestException as e:
254
- print("下载 Dockerfile 时发生异常:", e)
255
- return {"error": str(e)}
256
-
257
- # 提交并推送变更
258
- try:
259
- subprocess.run(["git", "-C", repo_path, "add", "."], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
260
- subprocess.run(["git", "-C", repo_path, "commit", "-m", "update Dockerfile"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
261
- except subprocess.CalledProcessError as e:
262
- # 如果没有变更,git commit 会返回非0,我们可以忽略
263
- stderr = e.stderr.decode() if e.stderr else str(e)
264
- if "nothing to commit" in stderr.lower() or "nothing to commit" in stderr:
265
- print("没有需要提交的变更")
266
- else:
267
- print("git add/commit 失败:", stderr)
268
- # 继续尝试 push 也许无效
269
- # push
270
- try:
271
- subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
272
- print("git push 成功")
273
- except subprocess.CalledProcessError as e:
274
- stderr = e.stderr.decode() if e.stderr else str(e)
275
- print("git push 失败:", stderr)
276
- # 尝试拉取并合并再 push(rebase)
277
- try:
278
- subprocess.run(["git", "-C", repo_path, "pull", "origin", "main", "--rebase"], check=True)
279
  subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True)
280
- print("rebase 后 push 成功")
281
- except subprocess.CalledProcessError as e2:
282
- print("rebase 或再次 push 失败:", e2)
283
- return {"error": "git push failed", "detail": stderr}
284
-
285
- return {"status": "ok", "repo": repo_path}
286
 
287
- if type == 5:
 
288
  headers = {"Authorization": f"Bearer {HF_TOKEN2}"}
289
  try:
290
  resp = requests.get(f"https://huggingface.co/api/spaces?author={HF_USER2}", headers=headers, timeout=15)
291
- resp.raise_for_status()
292
  spaces = resp.json()
293
- except requests.RequestException as e:
294
- print("获取空间列表失败:", e)
295
- return {"error": str(e)}
 
 
 
 
 
 
296
 
297
- spaces_sorted = sorted(spaces, key=lambda x: x.get('createdAt', ''), reverse=True)
298
- if len(spaces_sorted) <= 1:
299
- print("空间数量 <=1,无需删除")
300
- return {"status": "no_action"}
301
- latest_space = spaces_sorted[0]
302
- for space in spaces_sorted[1:]:
303
- full_name = space.get('id', '')
304
- space_id = full_name.split("/")[-1]
305
- url = "https://huggingface.co/api/repos/delete"
306
- headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
307
- payload = {"organization": HF_USER2, "name": space_id, "type": "space"}
308
- try:
309
- delete_response = requests.delete(url, headers=headers, json=payload, timeout=15)
310
- if delete_response.status_code == 200:
311
- print(f"成功删除空间:{space_id}")
312
- telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=OK")
313
- else:
314
- print(f"删除空间 {space_id} 失败:{delete_response.status_code}")
315
- telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=ON")
316
- except requests.RequestException as e:
317
- print("删除空间异常:", e)
318
- telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=ERROR")
319
- return {"status": "done"}
320
- def _reconstruct_token(partial_token):
321
- return partial_token.replace(" ", "")
322
  def restart_huggingface_space(space_name, space_id, partial_token):
323
- token = _reconstruct_token(partial_token)
324
  url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
325
- headers = {
326
- "Content-Type": "application/json",
327
- "Authorization": f"Bearer {token}",
328
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
329
- }
330
  try:
331
- response = requests.post(url, headers=headers, json={})
332
- return {
333
- "status_code": response.status_code,
334
- "success": response.status_code == 200,
335
- "message": response.text
336
- }
337
- except requests.RequestException as e:
338
- return {
339
- "status_code": None,
340
- "success": False,
341
- "message": str(e)
342
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
 
344
  def run():
 
345
  response = create_space(1)
346
- url = response["url"]
347
- full_name = response["name"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  tmp_name = full_name.split("/")[-1]
349
- log = f"“原始创建Space返回:{response} name字段:{full_name} Space 名称{tmp_name}"
350
- # log = f"Original create Space response: {url} | name field: {full_name} | Space name: {tmp_name}"
351
- telegram_message(BOT_TOKEN, CHAT_ID, log)
352
- print(log)
353
- create_space(3,"N_PORT",N_PORT,tmp_name)
354
- create_space(3,"ARGO_PORT",ARGO_PORT,tmp_name)
355
- create_space(3,"ARGO_DOMAIN",ARGO_DOMAIN,tmp_name)
356
- create_space(3,"ARGO_AUTH",ARGO_AUTH,tmp_name)
357
- create_space(3,"DASHBOARD_VERSION",DASHBOARD_VERSION,tmp_name)
358
- create_space(3,"NZV1_VERSION",NZV1_VERSION,tmp_name)
359
- create_space(3,"BACKUP_TIME",BACKUP_TIME,tmp_name)
360
- create_space(3,"RESTART_TIME",RESTART_TIME,tmp_name)
361
- create_space(3,"HF_USER1",HF_USER1,tmp_name)
362
- create_space(3,"HF_TOKEN1",HF_TOKEN1,tmp_name)
363
- create_space(3,"HF_REPO",HF_REPO,tmp_name)
364
- create_space(3,"HF_EMAIL",HF_EMAIL,tmp_name)
365
- create_space(3,"HF_ID",tmp_name,tmp_name)
366
- create_space(3,"HF_EMAIL2",HF_EMAIL2,tmp_name)
367
- create_space(3,"HF_TOKEN2",HF_TOKEN2,tmp_name)
368
- create_space(3,"CHAT_ID",CHAT_ID,tmp_name)
369
- create_space(3,"BOT_TOKEN",BOT_TOKEN,tmp_name)
370
- # create_space(3,"DATA_JSON",DATA_JSON,tmp_name)
371
- time.sleep(2)
372
- create_space(4,"","",tmp_name)
373
  time.sleep(2)
374
- result = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKEN2)
375
- print(f"{tmp_name}重启结果:",result)
376
- telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} 重启果:{result}")
 
 
377
  os.system(f"rm -rf /workdir/{tmp_name}")
378
- is_accessible = check_url_status(ff_url)
379
- print(f"网站 {ff_url} 是否可访问: {is_accessible}")
380
- if not is_accessible:
381
- telegram_message(BOT_TOKEN, CHAT_ID, f"站 {ff_url} 是否可访问: {is_accessible}")
382
- run()
383
- create_space(5,"","","")
384
- while True:
385
- time.sleep(1200)#21600 = 6小时 14400 = 4小时
386
- is_accessible = check_url_status(ff_url)
387
- print(f"网站 {ff_url} 是否可访问: {is_accessible}")
388
- if not is_accessible:
389
- telegram_message(BOT_TOKEN, CHAT_ID, f"网站 {ff_url} 是否可访问: {is_accessible}")
390
  run()
391
- create_space(5,"","","")
 
 
 
 
 
1
  import subprocess
2
  import os
 
3
  import time
 
 
 
 
 
 
 
 
4
  import json
5
  import random
6
  import string
7
+ import requests
8
  import urllib3
9
+ from datetime import datetime
10
+ import pytz
11
+
12
+ # 禁用 urllib3 的安全警告
13
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
14
+
15
+ # ================= 0. 日志与代理设置 =================
16
+
17
+ # 格式化日志输出函数
18
+ def sys_log(level, message):
19
+ try:
20
+ # 尝试使用上海时区,如果没有 pytz 则回退到本地时间
21
+ tz = pytz.timezone('Asia/Shanghai')
22
+ current_time = datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')
23
+ except:
24
+ current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
25
+
26
+ icons = {
27
+ "INFO": "ℹ️",
28
+ "SUCCESS": "✅",
29
+ "WARNING": "⚠️",
30
+ "ERROR": "❌",
31
+ "TG": "✈️"
32
+ }
33
+ icon = icons.get(level, "🔹")
34
+ print(f"[{current_time}] {icon} [{level}] {message}")
35
+
36
+ # 代理开关:设置为 True 开启代理,设置为 False 关闭代理
37
+ USE_PROXY = True
38
+ PROXY_URL = "socks5://10.0.8.2:3332"
39
+
40
+ if USE_PROXY:
41
+ os.environ['http_proxy'] = PROXY_URL
42
+ os.environ['https_proxy'] = PROXY_URL
43
+ os.environ['all_proxy'] = PROXY_URL
44
+ sys_log("INFO", f"全局代理已开启: {PROXY_URL}")
45
+ else:
46
+ os.environ.pop('http_proxy', None)
47
+ os.environ.pop('https_proxy', None)
48
+ os.environ.pop('all_proxy', None)
49
+ sys_log("INFO", "全局代理未开启 (直连模式)")
50
 
51
+ # ================= 1. 默认配置区域 =================
52
+ DATA_JSON_DEFAULT = ''' {
53
  "N_PORT": "7860",
54
  "ARGO_PORT": "8009",
55
  "ARGO_DOMAIN": "z.282820.xyz",
 
58
  "NZV1_VERSION": "v1.13.1",
59
  "BACKUP_TIME": "3600",
60
  "RESTART_TIME":"99999999",
61
+ "HF_USER1": "qiqi",
62
  "HF_REPO": "hf-nv1",
63
+ "HF_EMAIL": "HermanBr@mffac.com",
64
+ "HF_TOKEN1": "hf_d ZXxuseNaflIndsunaD",
65
+ "HF_USER2": "uyt",
66
+ "HF_ID": "fsawt",
67
+ "HF_EMAIL2": "nhhppw7019+x2s2tt6qn",
68
+ "HF_TOKEN2": "hf_j DJgQHkPqHrKZnlVGaffdUV",
69
+ "CHAT_ID": "-48258",
70
+ "BOT_TOKEN": "8259739796:AAGZY4tboUxJ3jnMi1GTI"
71
  }
72
  '''
73
+ # ↑↑↑ 请确保上方 HF_TOKEN2 已填写且有 Write 权限 ↑↑↑
74
+
75
+ # ================= 2. 环境变量处理 =================
76
+ raw_data_json = os.environ.get('DATA_JSON')
77
+ DATA_JSON = raw_data_json if raw_data_json else DATA_JSON_DEFAULT
78
  ff_url = "https://z.282820.xyz/"
79
+
80
  def assign_vars_from_json(config: dict):
81
  for key, value in config.items():
82
  globals()[key] = value
83
 
84
+ if DATA_JSON:
85
  try:
86
+ config_dict = json.loads(DATA_JSON)
87
  assign_vars_from_json(config_dict)
88
  except json.JSONDecodeError:
89
+ sys_log("WARNING", "DATA_JSON 格式解析失败,回退使用默认配置")
90
+ try:
91
+ config_dict = json.loads(DATA_JSON_DEFAULT)
92
+ assign_vars_from_json(config_dict)
93
+ except:
94
+ pass
95
+
96
+ # 变量兜底逻辑
97
+ N_PORT = globals().get('N_PORT', os.environ.get('N_PORT', '8008'))
98
+ ARGO_PORT = globals().get('ARGO_PORT', os.environ.get('ARGO_PORT', '8009'))
99
+ ARGO_DOMAIN = globals().get('ARGO_DOMAIN', os.environ.get('ARGO_DOMAIN', ''))
100
+ ARGO_AUTH = globals().get('ARGO_AUTH', os.environ.get('ARGO_AUTH', ''))
101
+ DASHBOARD_VERSION = globals().get('DASHBOARD_VERSION', os.environ.get('DASHBOARD_VERSION', 'v1.13.2'))
102
+ NZV1_VERSION = globals().get('NZV1_VERSION', os.environ.get('NZV1_VERSION', 'v1.13.1'))
103
+ BACKUP_TIME = globals().get('BACKUP_TIME', os.environ.get('BACKUP_TIME', '3600'))
104
+ RESTART_TIME = globals().get('RESTART_TIME', os.environ.get('RESTART_TIME', '14400'))
 
 
 
 
105
 
106
+ HF_USER1 = globals().get('HF_USER1', os.environ.get('HF_USER1', ''))
107
+ HF_REPO = globals().get('HF_REPO', os.environ.get('HF_REPO', ''))
108
+ HF_EMAIL = globals().get('HF_EMAIL', os.environ.get('HF_EMAIL', ''))
109
+ HF_TOKEN1 = globals().get('HF_TOKEN1', os.environ.get('HF_TOKEN1', ''))
110
+
111
+ HF_USER2 = globals().get('HF_USER2', os.environ.get('HF_USER2', ''))
112
+ HF_ID = globals().get('HF_ID', os.environ.get('HF_ID', ''))
113
+ HF_TOKEN2 = globals().get('HF_TOKEN2', os.environ.get('HF_TOKEN2', ''))
114
+
115
+ CHAT_ID = globals().get('CHAT_ID', os.environ.get('CHAT_ID', ''))
116
+ BOT_TOKEN = globals().get('BOT_TOKEN', os.environ.get('BOT_TOKEN', ''))
117
+
118
+ # ================= 3. 工具函数 =================
119
 
120
  def check_url_status(url, timeout=5):
 
 
 
 
 
 
 
 
 
 
121
  try:
122
+ response = requests.get(url, timeout=timeout, verify=False)
 
 
 
123
  return 200 <= response.status_code < 300
 
124
  except requests.RequestException:
 
125
  return False
126
 
 
 
 
127
  def random_name(length=8):
128
  return ''.join(random.choices(string.ascii_lowercase, k=length))
129
 
 
 
 
 
 
 
130
  def telegram_message(bot_token: str, chat_id: str, message: str):
131
+ if not bot_token or not chat_id:
132
+ return {}
133
  try:
 
134
  def escape_markdown(text):
135
  escape_chars = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
136
  return ''.join('\\' + char if char in escape_chars else char for char in text)
137
 
138
+ # 使用官方 API 以避免代理环境下的 SSL 错误
139
+ url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
140
 
 
 
 
141
  params = {
142
  "chat_id": chat_id,
143
+ "text": escape_markdown(message),
144
  "parse_mode": "MarkdownV2"
145
  }
146
 
147
+ response = requests.post(url, params=params, verify=False, timeout=10)
148
+ sys_log("TG", f"消息推送完毕 | 状态码: {response.status_code}")
149
+ return response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  except Exception as e:
151
+ sys_log("ERROR", f"Telegram 推送异常: {e}")
152
+ return {}
153
 
154
+ def create_space(action_type, key="", value="", name=""):
 
 
155
  workdir_root = "/workdir"
156
  try:
157
  os.makedirs(workdir_root, exist_ok=True)
158
+ except:
159
+ pass
 
160
 
161
+ # 1. 创建 Space
162
+ if action_type == 1:
163
+ if not HF_TOKEN2:
164
+ return {"error": "HF_TOKEN2 凭据未设置"}
165
  url = "https://huggingface.co/api/repos/create"
166
  headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
 
167
  payload = {
168
+ "name": random_name(10),
169
  "type": "space",
170
  "private": True,
171
  "sleepTimeSeconds": 172800,
 
173
  }
174
  try:
175
  resp = requests.post(url, headers=headers, json=payload, timeout=15)
176
+ if resp.status_code == 429:
177
+ return {"error": "触发接口限流 (429)", "status_code": 429, "msg": resp.text}
178
+
179
  resp.raise_for_status()
180
  return resp.json()
181
  except requests.RequestException as e:
182
+ err_msg = str(e)
183
+ if hasattr(e, 'response') and e.response is not None:
184
+ if e.response.status_code == 401:
185
+ return {"error": "认证失败 (401) - 请检查 HF_TOKEN2 是否有效且具备 Write 权限"}
186
+ if e.response.status_code == 429:
187
+ return {"error": "触发接口限流 (429)", "status_code": 429, "msg": e.response.text}
188
+ err_msg += f" | 服务器返回: {e.response.text}"
189
+ return {"error": err_msg}
190
 
191
+ # 2. 删除 Space
192
+ if action_type == 2:
193
  url = "https://huggingface.co/api/repos/delete"
194
+ headers = {"Authorization": f"Bearer {HF_TOKEN2}"}
195
  payload = {"organization": HF_USER2, "name": name, "type": "space"}
196
  try:
197
  resp = requests.delete(url, headers=headers, json=payload, timeout=15)
198
+ return {"status": resp.status_code}
199
+ except:
200
+ return {"error": "空间删除失败"}
201
 
202
+ # 3. 设置 Secrets
203
+ if action_type == 3:
204
  url = f"https://huggingface.co/api/spaces/{HF_USER2}/{name}/secrets"
205
+ headers = {"Authorization": f"Bearer {HF_TOKEN2}"}
206
+ payload = {"key": key, "value": value}
207
  try:
208
+ requests.post(url, headers=headers, json=payload, timeout=15)
209
+ except:
210
+ pass
 
211
 
212
+ # 4. 上传 Dockerfile
213
+ if action_type == 4:
214
  repo_path = f"/workdir/{name}"
215
+ df_url = "https://huggingface.co/datasets/Qilan2/ff/raw/main/nv1/Dockerfile"
 
 
 
 
 
 
 
 
216
  try:
217
+ r = requests.get(df_url, timeout=15)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  if r.status_code == 200:
219
+ git_url = f"https://{HF_USER2}:{HF_TOKEN2}@huggingface.co/spaces/{HF_USER2}/{name}"
220
+ if os.path.exists(repo_path):
221
+ subprocess.run(["rm", "-rf", repo_path], check=False)
222
+ subprocess.run(["git", "clone", git_url, repo_path], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
223
+ with open(os.path.join(repo_path, "Dockerfile"), "wb") as f:
224
  f.write(r.content)
225
+ subprocess.run(["git", "-C", repo_path, "config", "user.email", HF_EMAIL2], check=True)
226
+ subprocess.run(["git", "-C", repo_path, "config", "user.name", HF_USER2], check=True)
227
+ subprocess.run(["git", "-C", repo_path, "add", "."], check=True)
228
+ subprocess.run(["git", "-C", repo_path, "commit", "-m", "初始部署 Dockerfile"], check=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True)
230
+ return {"status": "ok"}
231
+ except Exception as e:
232
+ sys_log("ERROR", f"Git 代码同步失败: {e}")
233
+ return {"error": str(e)}
 
 
234
 
235
+ # 5. 清理旧 Space (保留最新的1个)
236
+ if action_type == 5:
237
  headers = {"Authorization": f"Bearer {HF_TOKEN2}"}
238
  try:
239
  resp = requests.get(f"https://huggingface.co/api/spaces?author={HF_USER2}", headers=headers, timeout=15)
 
240
  spaces = resp.json()
241
+ if isinstance(spaces, list):
242
+ spaces_sorted = sorted(spaces, key=lambda x: x.get('createdAt', ''), reverse=True)
243
+ if len(spaces_sorted) > 1:
244
+ for space in spaces_sorted[1:]:
245
+ sid = space.get('id', '').split("/")[-1]
246
+ sys_log("INFO", f"正在执行自动清理,删除旧版空间: {sid}")
247
+ create_space(2, name=sid)
248
+ except:
249
+ pass
250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  def restart_huggingface_space(space_name, space_id, partial_token):
252
+ token = partial_token.replace(" ", "")
253
  url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
254
+ headers = {"Authorization": f"Bearer {token}"}
 
 
 
 
255
  try:
256
+ resp = requests.post(url, headers=headers, json={}, verify=False)
257
+ return {"code": resp.status_code}
258
+ except Exception as e:
259
+ return {"error": str(e)}
260
+
261
+ # ================= 4. 核心逻辑:自动复活 =================
262
+ def recover_latest_space():
263
+ sys_log("WARNING", "开始执行【灾备复活流程】...")
264
+ headers = {"Authorization": f"Bearer {HF_TOKEN2}"}
265
+ try:
266
+ resp = requests.get(f"https://huggingface.co/api/spaces?author={HF_USER2}", headers=headers, timeout=15)
267
+ spaces = resp.json()
268
+ if not spaces or isinstance(spaces, dict):
269
+ sys_log("ERROR", "未能获取到历史空间列表,复活流程终止。")
270
+ return
271
+ except:
272
+ return
273
+
274
+ # 按创建时间倒序,取第一个
275
+ spaces_sorted = sorted(spaces, key=lambda x: x.get('createdAt', ''), reverse=True)
276
+ if not spaces_sorted:
277
+ sys_log("ERROR", "当前账户下没有任何空间可供复活。")
278
+ return
279
+
280
+ latest_space = spaces_sorted[0]
281
+ full_name = latest_space.get('id')
282
+ tmp_name = full_name.split("/")[-1]
283
+
284
+ sys_log("INFO", f"已锁定最新历史空间 [{tmp_name}],正在下发配置覆写...")
285
+
286
+ vars_to_set = {
287
+ "N_PORT": N_PORT, "ARGO_PORT": ARGO_PORT, "ARGO_DOMAIN": ARGO_DOMAIN,
288
+ "ARGO_AUTH": ARGO_AUTH, "DASHBOARD_VERSION": DASHBOARD_VERSION,
289
+ "NZV1_VERSION": NZV1_VERSION, "BACKUP_TIME": BACKUP_TIME,
290
+ "RESTART_TIME": RESTART_TIME, "HF_USER1": HF_USER1, "HF_TOKEN1": HF_TOKEN1,
291
+ "HF_REPO": HF_REPO, "HF_EMAIL": HF_EMAIL, "HF_ID": tmp_name,
292
+ "HF_EMAIL2": HF_EMAIL2, "HF_TOKEN2": HF_TOKEN2, "CHAT_ID": CHAT_ID,
293
+ "BOT_TOKEN": BOT_TOKEN
294
+ }
295
+
296
+ for key, val in vars_to_set.items():
297
+ create_space(3, key, str(val), tmp_name)
298
+ time.sleep(0.5)
299
+
300
+ sys_log("INFO", "正在同步最新代码仓库...")
301
+ create_space(4, name=tmp_name)
302
+
303
+ sys_log("INFO", "正在发送实例重启指令...")
304
+ time.sleep(2)
305
+ res = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKEN2)
306
+
307
+ sys_log("SUCCESS", f"空间复活操作完成 | API 响应: {res}")
308
+ telegram_message(BOT_TOKEN, CHAT_ID, f"✅ **灾备恢复成功**\n\n**空间名称**: `{tmp_name}`\n**状态**: 已重新部署并唤醒")
309
+
310
+ os.system(f"rm -rf /workdir/{tmp_name}")
311
 
312
  def run():
313
+ sys_log("INFO", "正在向 Hugging Face 申请创建全新应用空间...")
314
  response = create_space(1)
315
+
316
+ if "error" in response:
317
+ err_val = str(response['error'])
318
+ # 处理 429 限流错误
319
+ if "429" in err_val or "Rate Limit" in err_val or response.get("status_code") == 429:
320
+ hf_detail = response.get("msg", "")
321
+ hf_hint = ""
322
+ try:
323
+ err_json = json.loads(hf_detail)
324
+ hf_hint = err_json.get("error", hf_detail)
325
+ except:
326
+ hf_hint = hf_detail if hf_detail else "未知限流状态"
327
+
328
+ sys_log("WARNING", f"触发平台限流规则 | 官方提示: {hf_hint}")
329
+
330
+ tg_msg = f"⚠️ **空间创建受限 (HTTP 429)**\n\n💬 **官方拦截原因**:\n`{hf_hint}`\n\n🔄 系统已自动转入历史实例复活模式..."
331
+ telegram_message(BOT_TOKEN, CHAT_ID, tg_msg)
332
+
333
+ recover_latest_space()
334
+ return
335
+ else:
336
+ # 处理其他异常(如 401 凭证错误等)
337
+ sys_log("ERROR", f"空间创建任务异常中止: {err_val}")
338
+ telegram_message(BOT_TOKEN, CHAT_ID, f"❌ **部署任务失败**\n\n**错误详情**:\n`{err_val}`\n\n请检查脚本配置及 HF Token 权限。")
339
+ return
340
+
341
+ full_name = response.get("name")
342
+ if not full_name: return
343
+
344
  tmp_name = full_name.split("/")[-1]
345
+
346
+ sys_log("SUCCESS", f"空间创建成功,已分配唯一标识: {tmp_name}")
347
+ sys_log("INFO", "正在执行环境变量挂载...")
348
+
349
+ telegram_message(BOT_TOKEN, CHAT_ID, f"🚀 **全新空间已就绪**\n\n**空间标识**: `{tmp_name}`\n**部署进度**: 正在配置环境与同步代码...")
350
+
351
+ vars_to_set = {
352
+ "N_PORT": N_PORT, "ARGO_PORT": ARGO_PORT, "ARGO_DOMAIN": ARGO_DOMAIN,
353
+ "ARGO_AUTH": ARGO_AUTH, "DASHBOARD_VERSION": DASHBOARD_VERSION,
354
+ "NZV1_VERSION": NZV1_VERSION, "BACKUP_TIME": BACKUP_TIME,
355
+ "RESTART_TIME": RESTART_TIME, "HF_USER1": HF_USER1, "HF_TOKEN1": HF_TOKEN1,
356
+ "HF_REPO": HF_REPO, "HF_EMAIL": HF_EMAIL, "HF_ID": tmp_name,
357
+ "HF_EMAIL2": HF_EMAIL2, "HF_TOKEN2": HF_TOKEN2, "CHAT_ID": CHAT_ID,
358
+ "BOT_TOKEN": BOT_TOKEN
359
+ }
360
+
361
+ for key, val in vars_to_set.items():
362
+ create_space(3, key, str(val), tmp_name)
363
+ time.sleep(0.5)
364
+
365
+ sys_log("INFO", "环境变量挂载完毕,开始推送核心业务代码...")
366
+ create_space(4, name=tmp_name)
367
+
368
+ sys_log("INFO", "代码推送完成,提交重启指令激活实例...")
369
  time.sleep(2)
370
+ restart_huggingface_space(HF_USER2, tmp_name, HF_TOKEN2)
371
+
372
+ sys_log("SUCCESS", "全自动化部署流程圆满束!")
373
+ telegram_message(BOT_TOKEN, CHAT_ID, f"🌐 **服务上线通知**\n\n**节点**: `{tmp_name}`\n**状态**: 部署成功,服务启动指令已发送。")
374
+
375
  os.system(f"rm -rf /workdir/{tmp_name}")
376
+
377
+ # ================= 5. 主程序入口 =================
378
+ if __name__ == "__main__":
379
+ sys_log("INFO", f"启动系统巡检模块,目标点: {ff_url}")
380
+
381
+ if not check_url_status(ff_url):
382
+ sys_log("WARNING", "未检测到主站响应,心跳异常!触发自动化重建协议...")
383
+ telegram_message(BOT_TOKEN, CHAT_ID, f"📡 **监控告警**\n\n**目标站点**: `{ff_url}`\n**状态**: 无法访问 (Down)\n**动作**: 系统正在执行全自动重建流程...")
 
 
 
 
384
  run()
385
+
386
+ sys_log("INFO", "正在执行收尾工作,清理历史遗留环境...")
387
+ create_space(5)
388
+ else:
389
+ sys_log("SUCCESS", "主站网络连通性良好,服务运行平稳,无需干预。")