File size: 16,956 Bytes
8fed6ad |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
import subprocess
import os
import threading
import time
import yaml
from datetime import datetime
import signal
import psutil
import glob
import re
import pytz
import requests
import json
import random
import string
import urllib3
# DATA_JSON = os.environ.get('DATA_JSON', '')
DATA_JSON =''' {
"N_PORT": "7860",
"ARGO_PORT": "8009",
"ARGO_DOMAIN": "z.282820.xyz",
"ARGO_AUTH": "eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiMTlkZjEzNWMtZDE4My00MTg1LWJhOTMtOGVjMzBiMWNkNzU5IiwicyI6Ik1tVmtNVGMyTXpndFlUbGpOaTAwTldFekxUa3pNR010TkRabU16ZGpabVE0T0dNMyJ9",
"DASHBOARD_VERSION": "v1.13.2",
"NZV1_VERSION": "v1.13.1",
"BACKUP_TIME": "3600",
"RESTART_TIME":"99999999",
"HF_USER1": "qilanqi",
"HF_REPO": "hf-nv1",
"HF_EMAIL": "HermanBrand@mffac.com",
"HF_TOKEN1": "hf_vF dlQdHyROFvdXzMOvocNKbniDwsukVaTe",
"HF_USER2": "bcvbrer",
"HF_ID": "fsawpot",
"HF_EMAIL2": "o4e3aqv9@nqmo.com",
"HF_TOKEN2": "hf_hM GFvOurTJWjECuJdRwmpjKmNrRQSjpUEE",
"CHAT_ID": "-4829459058",
"BOT_TOKEN": "8259739796:AAGZY4tboUxJ3jnMi1GTpGtV3_-Tf2rMT7I"
}
'''
ff_url = "https://z.282820.xyz/"
HF_SPACES_NAME = os.environ.get('HF_SPACES_NAME', '')# 上个spaces名
def assign_vars_from_json(config: dict):
for key, value in config.items():
globals()[key] = value
if DATA_JSON: # 如果 DATA_JSON 有值
try:
config_dict = json.loads(DATA_JSON) # 解析 JSON 字符串
assign_vars_from_json(config_dict)
except json.JSONDecodeError:
raise ValueError("DATA_JSON 环境变量不是合法的 JSON 字符串")
else: # 如果 DATA_JSON 为空,就从单独的环境变量里取
N_PORT = os.environ.get('N_PORT', '8008') # N Z端口 默认8008
ARGO_PORT = os.environ.get('ARGO_PORT', '8009') # Argo(nginx的反代端口)固定隧道端口,留空默认8009
ARGO_DOMAIN = os.environ.get('ARGO_DOMAIN', '') # Argo固定隧道域名,留空即使用临时隧道
ARGO_AUTH = os.environ.get('ARGO_AUTH', '') # Argo固定隧道密钥,留空即使用临时隧道
DASHBOARD_VERSION = os.environ.get('DASHBOARD_VERSION', 'v1.13.2')# 指定面板的版本,以 v0.00.00 的格式,后续将固定在该版本不会升级,不填则使用默认的 v1.13.2
NZV1_VERSION = os.environ.get('NZV1_VERSION', 'v1.13.1')# 哪吒V1的版本默认v1.13.1
BACKUP_TIME = os.environ.get('BACKUP_TIME', '3600')# 备份时间 10800秒 2小时
RESTART_TIME = os.environ.get('RESTART_TIME', '14400')# 重启时间 4小时 14400 6小时 21600
HF_USER1 = os.environ.get('HF_USER1', '')# HF 备份仓库的用户名
HF_REPO = os.environ.get('HF_REPO', '')#HF 备份的Models仓库名
HF_EMAIL = os.environ.get('HF_EMAIL', '') #HF的邮箱
HF_TOKEN1 = os.environ.get('HF_TOKEN1', '')#HF备份账号的TOKEN
HF_USER2 = os.environ.get('HF_USER2', '')# huggingface 用户名
HF_ID = os.environ.get('HF_ID', '')# huggingface space 名
HF_TOKEN2 = os.environ.get('HF_TOKEN2', '')# huggingface TOKEN
CHAT_ID = os.environ.get('CHAT_ID', '')# Telegram chat_id,推送通知
BOT_TOKEN = os.environ.get('BOT_TOKEN', '')# Telegram bot_token
def check_url_status(url, timeout=5):
"""
检查URL是否可以正常访问
参数:
url (str): 要检查的URL地址
timeout (int): 请求超时时间,默认为5秒
返回:
bool: 网站是否可以正常访问
"""
try:
# 发送GET请求
response = requests.get(url, timeout=timeout)
# 检查响应状态码是否在200-299范围内
return 200 <= response.status_code < 300
except requests.RequestException:
# 捕获所有请求相关的异常,包括连接错误、超时等
return False
# 使用示例
def random_name(length=8):
return ''.join(random.choices(string.ascii_lowercase, k=length))
def update_value(data: dict, key: str, new_value: str) -> dict:
if key in data:
data[key] = new_value
else:
print(f"!!! Key '{key}' ON")
return data
def telegram_message(bot_token: str, chat_id: str, message: str):
try:
# 转义特殊字符,避免MarkdownV2解析错误
def escape_markdown(text):
escape_chars = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
return ''.join('\\' + char if char in escape_chars else char for char in text)
# 对消息进行转义
escaped_message = escape_markdown(message)
url = f"https://tgbotapi.9.c.5.b.0.d.0.0.1.0.a.2.ip6.arpa/bot{bot_token}/sendMessage"
# 详细的请求参数
params = {
"chat_id": chat_id,
"text": escaped_message,
"parse_mode": "MarkdownV2"
}
# 禁用不安全请求警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 增加超时和详细日志
response = requests.post(
url,
params=params,
verify=False,
timeout=10 # 设置超时时间
)
# 打印完整的响应信息
print(f"Response Status Code: {response.status_code}")
print(f"Response Content: {response.text}")
# 检查响应
if response.status_code == 200:
return response.json()
else:
return {
"status_code": response.status_code,
"text": response.text
}
except requests.exceptions.RequestException as e:
print(f"请求异常: {e}")
return {"error": str(e)}
except Exception as e:
print(f"未知异常: {e}")
return {"error": str(e)}
# 创建、删除、设置 secrets、修改 Dockerfile 等操作
def create_space(type, key="", value="", name=""):
# 确保 /workdir 存在
workdir_root = "/workdir"
try:
os.makedirs(workdir_root, exist_ok=True)
except Exception as e:
print("无法创建 /workdir:", e)
raise
if type == 1:
# 创建 space
url = "https://huggingface.co/api/repos/create"
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
name = random_name(10)
payload = {
"name": name,
"type": "space",
"private": True,
"sleepTimeSeconds": 172800,
"sdk": "docker"
}
try:
resp = requests.post(url, headers=headers, json=payload, timeout=15)
resp.raise_for_status()
return resp.json()
except requests.RequestException as e:
print("创建 space 失败:", e)
return {"error": str(e)}
if type == 2:
url = "https://huggingface.co/api/repos/delete"
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
payload = {"organization": HF_USER2, "name": name, "type": "space"}
try:
resp = requests.delete(url, headers=headers, json=payload, timeout=15)
return {"status_code": resp.status_code, "text": resp.text}
except requests.RequestException as e:
return {"error": str(e)}
if type == 3:
url = f"https://huggingface.co/api/spaces/{HF_USER2}/{name}/secrets"
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
payload = {"key": key, "value": value, "description": ""}
try:
resp = requests.post(url, headers=headers, json=payload, timeout=15)
return {"status_code": resp.status_code, "text": resp.text}
except requests.RequestException as e:
return {"error": str(e)}
if type == 4:
# 下载并替换 Dockerfile,然后提交到空间仓库
repo_path = f"/workdir/{name}"
dockerfile_path = os.path.join(repo_path, "Dockerfile")
# 克隆仓库前确保目标父目录存在
os.makedirs(repo_path, exist_ok=True)
git_url = f"https://{HF_USER2}:{HF_TOKEN2}@huggingface.co/spaces/{HF_USER2}/{name}"
print("git clone 命令:", git_url, "->", repo_path)
# 使用 subprocess.run 执行 git clone(捕获错误)
try:
# 如果目录为空(刚创建),直接 clone 会写入 repo_path;如果已存在 .git 则跳过 clone
if not os.path.exists(os.path.join(repo_path, ".git")):
subprocess.run(["git", "clone", git_url, repo_path], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
print("目标已有 .git,跳过 clone,改为 git pull")
subprocess.run(["git", "-C", repo_path, "pull"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
print("git clone/pull 失败:", e.stderr.decode() if e.stderr else e)
return {"error": "git clone/pull failed", "detail": str(e)}
# 配置 git 用户信息(repo 内 global 配置可能覆盖)
try:
subprocess.run(["git", "-C", repo_path, "config", "user.email", HF_EMAIL2], check=True)
subprocess.run(["git", "-C", repo_path, "config", "user.name", HF_USER2], check=True)
except subprocess.CalledProcessError as e:
print("git config 失败:", e)
# 继续执行,不致命
# 下载 Dockerfile(示例来源 URL)
url = "https://huggingface.co/datasets/Qilan2/ff/raw/main/nv1/Dockerfile"
try:
r = requests.get(url, timeout=15)
if r.status_code == 200:
# 确保目录存在
os.makedirs(os.path.dirname(dockerfile_path), exist_ok=True)
with open(dockerfile_path, "wb") as f:
f.write(r.content)
print("Dockerfile 下载并写入:", dockerfile_path)
else:
print("下载 Dockerfile 失败,状态码:", r.status_code)
return {"error": "download Dockerfile failed", "status": r.status_code}
except requests.RequestException as e:
print("下载 Dockerfile 时发生异常:", e)
return {"error": str(e)}
# 提交并推送变更
try:
subprocess.run(["git", "-C", repo_path, "add", "."], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
subprocess.run(["git", "-C", repo_path, "commit", "-m", "update Dockerfile"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
# 如果没有变更,git commit 会返回非0,我们可以忽略
stderr = e.stderr.decode() if e.stderr else str(e)
if "nothing to commit" in stderr.lower() or "nothing to commit" in stderr:
print("没有需要提交的变更")
else:
print("git add/commit 失败:", stderr)
# 继续尝试 push 也许无效
# push
try:
subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("git push 成功")
except subprocess.CalledProcessError as e:
stderr = e.stderr.decode() if e.stderr else str(e)
print("git push 失败:", stderr)
# 尝试拉取并合并再 push(rebase)
try:
subprocess.run(["git", "-C", repo_path, "pull", "origin", "main", "--rebase"], check=True)
subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True)
print("rebase 后 push 成功")
except subprocess.CalledProcessError as e2:
print("rebase 或再次 push 失败:", e2)
return {"error": "git push failed", "detail": stderr}
return {"status": "ok", "repo": repo_path}
if type == 5:
headers = {"Authorization": f"Bearer {HF_TOKEN2}"}
try:
resp = requests.get(f"https://huggingface.co/api/spaces?author={HF_USER2}", headers=headers, timeout=15)
resp.raise_for_status()
spaces = resp.json()
except requests.RequestException as e:
print("获取空间列表失败:", e)
return {"error": str(e)}
spaces_sorted = sorted(spaces, key=lambda x: x.get('createdAt', ''), reverse=True)
if len(spaces_sorted) <= 1:
print("空间数量 <=1,无需删除")
return {"status": "no_action"}
latest_space = spaces_sorted[0]
for space in spaces_sorted[1:]:
full_name = space.get('id', '')
space_id = full_name.split("/")[-1]
url = "https://huggingface.co/api/repos/delete"
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {HF_TOKEN2}"}
payload = {"organization": HF_USER2, "name": space_id, "type": "space"}
try:
delete_response = requests.delete(url, headers=headers, json=payload, timeout=15)
if delete_response.status_code == 200:
print(f"成功删除空间:{space_id}")
telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=OK")
else:
print(f"删除空间 {space_id} 失败:{delete_response.status_code}")
telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=ON")
except requests.RequestException as e:
print("删除空间异常:", e)
telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=ERROR")
return {"status": "done"}
def _reconstruct_token(partial_token):
return partial_token.replace(" ", "")
def restart_huggingface_space(space_name, space_id, partial_token):
token = _reconstruct_token(partial_token)
url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
"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"
}
try:
response = requests.post(url, headers=headers, json={})
return {
"status_code": response.status_code,
"success": response.status_code == 200,
"message": response.text
}
except requests.RequestException as e:
return {
"status_code": None,
"success": False,
"message": str(e)
}
def run():
response = create_space(1)
url = response["url"]
full_name = response["name"]
tmp_name = full_name.split("/")[-1]
log = f"“原始创建Space返回:{response} name字段:{full_name} Space 名称{tmp_name}"
# log = f"Original create Space response: {url} | name field: {full_name} | Space name: {tmp_name}"
telegram_message(BOT_TOKEN, CHAT_ID, log)
print(log)
create_space(3,"N_PORT",N_PORT,tmp_name)
create_space(3,"ARGO_PORT",ARGO_PORT,tmp_name)
create_space(3,"ARGO_DOMAIN",ARGO_DOMAIN,tmp_name)
create_space(3,"ARGO_AUTH",ARGO_AUTH,tmp_name)
create_space(3,"DASHBOARD_VERSION",DASHBOARD_VERSION,tmp_name)
create_space(3,"NZV1_VERSION",NZV1_VERSION,tmp_name)
create_space(3,"BACKUP_TIME",BACKUP_TIME,tmp_name)
create_space(3,"RESTART_TIME",RESTART_TIME,tmp_name)
create_space(3,"HF_USER1",HF_USER1,tmp_name)
create_space(3,"HF_TOKEN1",HF_TOKEN1,tmp_name)
create_space(3,"HF_REPO",HF_REPO,tmp_name)
create_space(3,"HF_EMAIL",HF_EMAIL,tmp_name)
create_space(3,"HF_ID",tmp_name,tmp_name)
create_space(3,"HF_EMAIL2",HF_EMAIL2,tmp_name)
create_space(3,"HF_TOKEN2",HF_TOKEN2,tmp_name)
create_space(3,"CHAT_ID",CHAT_ID,tmp_name)
create_space(3,"BOT_TOKEN",BOT_TOKEN,tmp_name)
# create_space(3,"DATA_JSON",DATA_JSON,tmp_name)
time.sleep(2)
create_space(4,"","",tmp_name)
time.sleep(2)
result = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKEN2)
print(f"{tmp_name}重启结果:",result)
telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} 重启结果:{result}")
os.system(f"rm -rf /workdir/{tmp_name}")
is_accessible = check_url_status(ff_url)
print(f"网站 {ff_url} 是否可访问: {is_accessible}")
if not is_accessible:
telegram_message(BOT_TOKEN, CHAT_ID, f"网站 {ff_url} 是否可访问: {is_accessible}")
run()
create_space(5,"","","")
while True:
time.sleep(1200)#21600 = 6小时 14400 = 4小时
is_accessible = check_url_status(ff_url)
print(f"网站 {ff_url} 是否可访问: {is_accessible}")
if not is_accessible:
telegram_message(BOT_TOKEN, CHAT_ID, f"网站 {ff_url} 是否可访问: {is_accessible}")
run()
create_space(5,"","","") |