File size: 13,301 Bytes
c98aeba |
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 |
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 =''' {
"BACKUP_TIME": "1200",
"HF_USER1": "qilanqi",
"HF_REPO": "ff2",
"HF_EMAIL": "HermanBrand@mffac.com",
"HF_TOKEN1": "hf_vFdlQdHyRONKbniDwsukVaTe",
"HF_USER2": "cdddwwer",
"HF_EMAIL2": "HermanNorris@mffac.com",
"HF_ID": "dasdw",
"HF_TOKON2": "hf_lSPmCUGQHIHYYcgF",
"UUID": "a488076d-0ced-4a83-91c4-c498fce00cff",
"N_SERVER": "z.282820.xyz:443",
"CHAT_ID": "-4829459058",
"BOT_TOKEN": "8259739796:AAGZY4tboUxJ3jnMi1GTpGtV3_-Tf2rMT7I"
}
'''
ff_url = "https://ff1.vv9.dpdns.org/"
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 为空,就从单独的环境变量里取
BACKUP_TIME = os.environ.get('BACKUP_TIME', '1200') # 备份时间 10800秒 2小时
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_TOKON2 = os.environ.get('HF_TOKON2', '') # huggingface TOKEN
HF_EMAIL2 = os.environ.get('HF_EMAIL2', '') # HF的邮箱
UUID = os.environ.get('UUID', 'a488076d-0ced-4a83-91c4-c498fce00cff') # UUID,如使用v1,在不同的平台部署需要修改,否则会覆盖
N_SERVER = os.environ.get('N_SERVER', 'z.282820.xyz:443')# N面板域名或ip,
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)}
def create_space(type,key = "", value = "",name = ""):
if type == 1:
# 创建spaces
url = "https://huggingface.co/api/repos/create"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {HF_TOKON2}"
}
name = random_name()
payload = {
"name": name,
"type": "space",
"private": True,
"sleepTimeSeconds": 172800,
# "template": "SpacesExamples/jupyterlab",
"sdk": "docker"
}
# "template": "SpacesExamples/jupyterlab",
response = requests.post(url, headers=headers, json=payload)
return response.json()
if type == 2:
# 删除spaces
url = "https://huggingface.co/api/repos/delete"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {HF_TOKON2}"
}
payload = {
"organization": HF_USER2,
"name": name,
"type": "space"
}
response = requests.delete(url, headers=headers, json=payload)
return response.text
if type == 3:
# 创建spaces 变量
url = f"https://huggingface.co/api/spaces/{HF_USER2}/{name}/secrets"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {HF_TOKON2}"
}
payload = {
"key": key,
"value": value,
"description": ""
}
response = requests.post(url, headers=headers, json=payload)
return response.text
if type == 4:
file_path = f"/workdir/{name}/Dockerfile"
os.system("rm -rf {HF_SPACES_NAME}")
git = f"git clone https://{HF_USER2}:{HF_TOKON2}@huggingface.co/spaces/{HF_USER2}/{name} /workdir/{name}"
url = "https://huggingface.co/datasets/Qilan2/ff/raw/main/Dockerfile"
print(git)
os.system(git)
os.system(f'git config --global user.email "{HF_EMAIL2}"')
os.system(f'git config --global user.name "{HF_USER2}"')
os.chdir(f'/workdir/{name}')
os.system(f"rm -rf {file_path}")
time.sleep(3)
# 如果文件已存在,先删除
if os.path.exists(file_path):
print(f"文件已存在,删除: {file_path}")
os.remove(file_path)
print(f"正在下载 {url} 到 {file_path}")
response = requests.get(url)
if response.status_code == 200:
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "wb") as f:
f.write(response.content)
print("下载完成 ✅")
# telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}下载Dockerfile 结果:下载完成 ✅")
else:
print(f"下载失败,状态码: {response.status_code}")
# telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}下载Dockerfile下载失败,状态码: {response.status_code}")
# os.system(f"wget -O '/data/{tmp_name}/Dockerfile' https://huggingface.co/datasets/Qilan2/ff/raw/main/Dockerfile")
repo_path = f"//workdir/{name}"
subprocess.run(["git", "-C", repo_path, "add", "."], check=True)
subprocess.run(["git", "-C", repo_path, "commit", "-m", "0"], check=True)
subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True)
# os.system('git add .')
# os.system('git commit -m "0"')
# push_result = os.system('git push origin main')
# if push_result != 0:
# print("推送失败,可能有冲突,尝试拉取并合并...")
# os.system('git pull origin main --rebase')
# os.system('git push origin main')
if type == 5:
# 获取用户的所有空间
headers = {
"Authorization": f"Bearer {HF_TOKON2}"
}
# 获取用户的所有空间列表
response = requests.get(f"https://huggingface.co/api/spaces?author={HF_USER2}", headers=headers)
if response.status_code != 200:
print(f"获取空间列表失败:{response.status_code}")
return
spaces = response.json()
# 按创建时间排序
spaces_sorted = sorted(spaces, key=lambda x: x['createdAt'], reverse=True)
# 保留最新的空间
if len(spaces_sorted) > 1:
latest_space = spaces_sorted[0]
# 遍历并删除其他旧空间
for space in spaces_sorted[1:]:
full_name = space['id']
space_id = full_name.split("/")[-1]
# 删除spaces
url = "https://huggingface.co/api/repos/delete"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {HF_TOKON2}"
}
payload = {
"organization": HF_USER2,
"name": space_id,
"type": "space"
}
delete_response = requests.delete(url, headers=headers, json=payload)
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")
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,"BACKUP_TIME",BACKUP_TIME,tmp_name)
create_space(3,"HF_USER1",HF_USER1,tmp_name)
create_space(3,"HF_REPO",HF_REPO,tmp_name)
create_space(3,"HF_EMAIL",HF_EMAIL,tmp_name)
create_space(3,"HF_TOKEN1",HF_TOKEN1,tmp_name)
create_space(3,"HF_USER2",HF_USER2,tmp_name)
create_space(3,"HF_EMAIL2",HF_EMAIL2,tmp_name)
create_space(3,"HF_ID",tmp_name,tmp_name)
create_space(3,"HF_TOKON2",HF_TOKON2,tmp_name)
create_space(3,"UUID",UUID,tmp_name)
create_space(3,"N_SERVER","z.282820.xyz:443",tmp_name)
create_space(3,"CHAT_ID",CHAT_ID,tmp_name)
create_space(3,"BOT_TOKEN",BOT_TOKEN,tmp_name)
create_space(3,"HF_SPACES_NAME",HF_ID,tmp_name)
time.sleep(2)
create_space(4,"","",tmp_name)
time.sleep(2)
result = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKON2)
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}")
while True:
time.sleep(1200)#21600 = 6小时 14400 = 4小时
telegram_message(BOT_TOKEN, CHAT_ID, f"网站 {url} 是否可访问: {is_accessible}")
is_accessible = check_url_status(ff_url)
print(f"网站 {url} 是否可访问: {is_accessible}")
if not is_accessible:
run() |