SD_QZ / server.py
Qi28's picture
Update server.py
dd9ec75 verified
raw
history blame
9.42 kB
import requests
import subprocess
import threading
import shutil
import zipfile
import os
import time
import json
from IPython.display import clear_output
huggiingface_repo_id = 'Qi28/SD_QZ' # Hugging Face 数据集 ID
huggiingface_path = 'frp'
download_path = '/tmp/code/frp'
frp_status = False #是否启用frp, 0 否 1 是
nps_status = True #是否启用nps, 0 否 1 是
sd_url = 'http://119.8.118.149:8000'
NPS_key = 'q9wj1cnlek4j3hg5'
NPS_server = '119.8.118.149:7001'
nezha_agent_key = 'L3USpU8bbpHRV90uuC'
nezha_agent_url = 'nzzz.nwb.lol:5555'
#!export CUDA_VISIBLE_DEVICES=0,1
def Frpc():
os.system('rm /tmp/code/frp/*.ini')
# 定义 Hugging Face 数据集 ID
api_url = f'https://hf-mirror.com/api/datasets/{huggiingface_repo_id}/tree/main/{huggiingface_path}'
# 获取文件列表
response = requests.get(api_url)
if response.status_code != 200:
print(f'Error: Failed to fetch file list from {api_url}')
response.raise_for_status()
file_list = response.json()
yun_files = [file['path'] for file in file_list if file['type'] == 'file']
# 下载文件
for yun_file in yun_files:
url = f'https://hf-mirror.com/datasets/{huggiingface_repo_id}/resolve/main/{yun_file}'
response = requests.head(url)
if response.status_code == 200:
result = subprocess.run(['wget', '-O', os.path.join(download_path, os.path.basename(yun_file)), url, '-q'], capture_output=True)
if result.returncode != 0:
print(f'Error: Failed to download {yun_file} from {url}')
else:
print(f'Error: Invalid URL {url}')
frpc_executable = '/tmp/code/frp/frpc'
subprocess.run(['chmod', '+x', frpc_executable], check=True)
# 启动 frpc 实例
for yun_file in yun_files:
frpini_path = os.path.join(download_path, os.path.basename(yun_file))
print(f'运行FRP配置: {frpini_path}')
subprocess.Popen([frpc_executable, '-c', frpini_path])
def NPS():
os.system("/tmp/code/nps/npc -server={NPS_server} -vkey={NPS_key} -type=tcp")
def run_commands():
run_command("apt update")
run_command("apt install openssh-server -y")
run_command("apt-get install vim -y")
config_client_cmd = "sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
run_command(config_client_cmd)
config_server_cmd = "sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
run_command(config_server_cmd)
run_command("systemctl restart ssh")
os.system("echo 'root:qilan' | chpasswd")
os.system("echo 'PermitRootLogin yes' | tee -a /etc/ssh/sshd_config")
os.system("service ssh restart")
os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
def run_command(command):
try:
subprocess.run(command, check=True, shell=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred: {e}")
def run_script():
os.system('rm -r /tmp/code/nezha-agent')
# GitHub项目名和API URL
project_name = "nezhahq/agent"
releases_api_url = f"https://api.github.com/repos/{project_name}/releases"
# 获取最新版本的信息
response = requests.get(releases_api_url)
if response.status_code == 200:
releases = response.json()
latest_version = releases[0]['tag_name'] # 假设最新版本是列表中的第一个
print(f"Latest version: {latest_version}")
else:
print("Failed to fetch releases information.")
exit()
# 构造下载链接
download_url = f"https://slink.ltd/https://github.com/{project_name}/releases/download/{latest_version}/nezha-agent_linux_amd64.zip"
# 指定下载文件的保存路径
zip_file_path = "/tmp/code/nezha-agent.zip" # 临时ZIP文件路径
# 确保下载目录存在
os.makedirs(os.path.dirname(zip_file_path), exist_ok=True)
# 发送HTTP GET请求下载文件
response = requests.get(download_url, stream=True)
# 检查请求是否成功
if response.status_code == 200:
# 打开文件进行写入
with open(zip_file_path, 'wb') as file:
for chunk in response.iter_content(chunk_size=128):
file.write(chunk)
print(f"Download completed. File saved to {zip_file_path}")
# 解压ZIP文件
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall("/tmp/code/")
print("Extraction completed.")
os.remove(zip_file_path)
print(f"Removed temporary zip file: {zip_file_path}")
else:
print(f"Failed to download the file. Status code: {response.status_code}")
print('启动哪吒面板')
try:
subprocess.run(["chmod", "+x", "/tmp/code/nezha-agent"], check=True)
subprocess.run(["/tmp/code/nezha-agent", "-s", "nzzz.nwb.lol:5555", "-p", nezha_agent_key, "-d"], check=True)
except subprocess.CalledProcessError as e:
print(f"启动哪吒面板失败,错误内容: {e}")
# 等待启动穿透
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
session = session or requests.Session()
retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def check_api1():
while True:
try:
url = "http://127.0.0.1:7860/sdapi/v1/txt2img"
response = requests.get(url, timeout=30)
try:
response_json = response.json()
if response_json.get("detail") in ("Method Not Allowed", "Not Found"):
print("SD已经启动")
break # 接口正常,退出循环
else:
print("SD未启动" )
except json.JSONDecodeError:
# 如果响应内容不是有效的 JSON,打印错误信息
print("SD未启动2")
except requests.exceptions.RequestException as e:
print("SD未启动3")
time.sleep(5)
print('开始检测接口状态')
while True:
url = f"{sd_url}/sdapi/v1/txt2img"
try:
response = requests_retry_session().get(url, timeout=30)
response.raise_for_status()
response_json = response.json()
if "detail" in response_json and response_json["detail"] in ("Method Not Allowed", "Not Found"):
print("接口正常")
else:
print("接口返回信息:", response_json)
except requests.exceptions.HTTPError as e:
print("接口正常2")
except requests.exceptions.ConnectionError as e:
print(f"接口异常1: {e}")
if frp_status:
print("启动FRP")
threading.Thread(target=Frpc, daemon=True).start()
if nps_status:
print("启动NPS")
threading.Thread(target=NPS, daemon=True).start()
# threading.Thread(target=run_script).start()
#threading.Thread(target=run_commands).start()
break
except requests.exceptions.Timeout as e:
print(f"接口异常2: {e}")
if frp_status:
print("启动FRP")
threading.Thread(target=Frpc, daemon=True).start()
if nps_status:
print("启动NPS")
threading.Thread(target=NPS, daemon=True).start()
# threading.Thread(target=run_script).start()
#threading.Thread(target=run_commands).start()
break
except requests.exceptions.RequestException as e:
print(f"接口异常3: {e}")
if frp_status:
print("启动FRP")
threading.Thread(target=Frpc, daemon=True).start()
if nps_status:
print("启动NPS")
threading.Thread(target=NPS, daemon=True).start()
# threading.Thread(target=run_script).start()
#threading.Thread(target=run_commands).start()
break
time.sleep(5)
threading.Thread(target=check_api1, daemon=True).start()
def comfyui():
subprocess.run(["python", "/tmp/code/sd/ComfyUI/main.py"], check=True)
clear_output()
threading.Thread(target=run_commands).start()
threading.Thread(target=comfyui, daemon=True).start()
os.system('rm /tmp/code/sd/stable-diffusion-webui/config.json /tmp/code/sd/stable-diffusion-webui/ui-config.json /tmp/code/*.log')
os.system("wget -O /tmp/code/sd/stable-diffusion-webui/config.json 'https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/comfig/sd_config.json'")
os.system("wget -O /tmp/code/sd/stable-diffusion-webui/ui-config.json 'https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/comfig/sd_ui-config.json'")
# python /tmp/code/sd/stable-diffusion-webui/launch.py --api --api-auth QiLan:1415361185 --no-hashing --enable-insecure-extension-access --no-gradio-queue --no-half-vae --port 7860 --xformers
os.system("python /tmp/code/sd/stable-diffusion-webui/launch.py --api --api-auth QiLan:1415361185 --no-hashing --enable-insecure-extension-access --no-gradio-queue --no-half-vae --port 7860 --xformers")