|
|
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 =''' { |
|
|
"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', '') |
|
|
def assign_vars_from_json(config: dict): |
|
|
for key, value in config.items(): |
|
|
globals()[key] = value |
|
|
|
|
|
if DATA_JSON: |
|
|
try: |
|
|
config_dict = json.loads(DATA_JSON) |
|
|
assign_vars_from_json(config_dict) |
|
|
except json.JSONDecodeError: |
|
|
raise ValueError("DATA_JSON 环境变量不是合法的 JSON 字符串") |
|
|
else: |
|
|
N_PORT = os.environ.get('N_PORT', '8008') |
|
|
ARGO_PORT = os.environ.get('ARGO_PORT', '8009') |
|
|
ARGO_DOMAIN = os.environ.get('ARGO_DOMAIN', '') |
|
|
ARGO_AUTH = os.environ.get('ARGO_AUTH', '') |
|
|
DASHBOARD_VERSION = os.environ.get('DASHBOARD_VERSION', 'v1.13.2') |
|
|
NZV1_VERSION = os.environ.get('NZV1_VERSION', 'v1.13.1') |
|
|
BACKUP_TIME = os.environ.get('BACKUP_TIME', '3600') |
|
|
RESTART_TIME = os.environ.get('RESTART_TIME', '14400') |
|
|
|
|
|
|
|
|
HF_USER1 = os.environ.get('HF_USER1', '') |
|
|
HF_REPO = os.environ.get('HF_REPO', '') |
|
|
HF_EMAIL = os.environ.get('HF_EMAIL', '') |
|
|
HF_TOKEN1 = os.environ.get('HF_TOKEN1', '') |
|
|
|
|
|
HF_USER2 = os.environ.get('HF_USER2', '') |
|
|
HF_ID = os.environ.get('HF_ID', '') |
|
|
HF_TOKEN2 = os.environ.get('HF_TOKEN2', '') |
|
|
|
|
|
CHAT_ID = os.environ.get('CHAT_ID', '') |
|
|
BOT_TOKEN = os.environ.get('BOT_TOKEN', '') |
|
|
|
|
|
def check_url_status(url, timeout=5): |
|
|
""" |
|
|
检查URL是否可以正常访问 |
|
|
|
|
|
参数: |
|
|
url (str): 要检查的URL地址 |
|
|
timeout (int): 请求超时时间,默认为5秒 |
|
|
|
|
|
返回: |
|
|
bool: 网站是否可以正常访问 |
|
|
""" |
|
|
try: |
|
|
|
|
|
response = requests.get(url, timeout=timeout) |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
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=""): |
|
|
|
|
|
workdir_root = "/workdir" |
|
|
try: |
|
|
os.makedirs(workdir_root, exist_ok=True) |
|
|
except Exception as e: |
|
|
print("无法创建 /workdir:", e) |
|
|
raise |
|
|
|
|
|
if type == 1: |
|
|
|
|
|
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: |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
try: |
|
|
|
|
|
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)} |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
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}" |
|
|
|
|
|
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) |
|
|
|
|
|
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) |
|
|
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,"","","") |