ff / nv1 /nv1.py
Qilan2's picture
Create nv1.py
8fed6ad verified
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,"","","")