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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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",
|
| 23 |
+
"ARGO_AUTH": "eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiMTlkZjEzNWMtZDE4My00MTg1LWJhOTMtOGVjMzBiMWNkNzU5IiwicyI6Ik1tVmtNVGMyTXpndFlUbGpOaTAwTldFekxUa3pNR010TkRabU16ZGpabVE0T0dNMyJ9",
|
| 24 |
+
"DASHBOARD_VERSION": "v1.13.2",
|
| 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,
|
| 179 |
+
"sdk": "docker"
|
| 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,"","","")
|