File size: 11,636 Bytes
8c6d807
 
 
 
 
 
 
4318959
dd9ec75
3913ae6
 
 
8c6d807
 
 
 
 
f9aa0da
676a0c7
8c6d807
 
 
 
 
4a7345b
ba634dc
4a7345b
ba634dc
4a7345b
c8ea464
d07d091
 
 
 
c8ea464
8c6d807
be70074
 
 
 
595ce3f
be70074
 
 
 
 
595ce3f
be70074
 
 
595ce3f
be70074
 
 
595ce3f
be70074
 
 
8c6d807
 
a310470
8c6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a310470
ef80a7f
8c6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
233a1b1
8c6d807
 
 
 
 
 
 
 
 
b31eeef
8c6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
9b25036
 
8c6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e049401
 
abd25cb
163b919
 
 
 
 
 
e049401
8c6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12412ba
8c6d807
12412ba
8c6d807
b31eeef
8c6d807
 
 
 
12412ba
8c6d807
12412ba
8c6d807
b31eeef
8c6d807
 
 
 
 
12412ba
8c6d807
12412ba
8c6d807
b31eeef
8c6d807
 
 
 
 
 
 
dd9ec75
7b55167
be70074
808e4ed
7b55167
def55e0
7b55167
8c6d807
4ad8453
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
import requests
import subprocess
import threading
import shutil
import zipfile
import os
import time
import json
from IPython.display import clear_output
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry



huggiingface_repo_id = 'Qi28/SD_QZ'  # Hugging Face 数据集 ID
huggiingface_path = 'frp'
download_path = '/tmp/code/frp' 
frp_status = True #是否启用frp, False 否 True 是
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'
nz_commands = [
    "curl -L https://slink.ltd/https://raw.githubusercontent.com/nezhahq/scripts/main/install.sh -o nezha.sh",
    "chmod +x nezha.sh",
    "y | ./nezha.sh install_agent nnzmb.qilan.cloudns.ch 16667 fTDSMw9zPZokP8DOiH"
]

os.system("rm -r /tmp/code/sd/stable-diffusion-webui/modules/api/api.py /tmp/code/sd/stable-diffusion-webui/modules/img2img.py /tmp/code/sd/stable-diffusion-webui/modules/txt2img.py")
os.system("wget -O /tmp/code/sd/stable-diffusion-webui/modules/api/api.py 'https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/modules/api.py'")
os.system("wget -O /tmp/code/sd/stable-diffusion-webui/modules/img2img.py 'https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/modules/img2img.py'")
os.system("wget -O /tmp/code/sd/stable-diffusion-webui/modules/txt2img.py 'https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/modules/txt2img.py'")

#!export CUDA_VISIBLE_DEVICES=0,1
# subprocess.run(["apt-get", "install", "-y", "pigz"])
# # 定义下载路径和解压路径
# download_path = "/tmp/code/venv.tar.gz"
# extract_path = "/tmp/code"

# # 检查 /tmp/code/venv 文件夹是否存在
# if not os.path.exists("/tmp/code/venv"):
#     # 如果不存在,则下载 venv.tar.gz 文件
#     print("开始下载venv...")
#     subprocess.run(["openi", "dataset", "download", "qilan2/SD-QL", "venv.tar.gz", "--cluster", "NPU", "--save_path", "/tmp/code"])

#     # 解压 venv.tar.gz 文件
#     print("开始解压venv...")
#     subprocess.run(["tar", "--use-compress-program=pigz", "-hxf", download_path, "-C", extract_path])

#     # 删除压缩包
#     print("删除 venv.tar.gz ...")
#     os.remove(download_path)

#     print("环境包下载完毕")
# else:
#     print("venv存在")

def Frpc():
    print("启动FRP")
    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():
    print("启动NPS")
    os.system(f"/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 ':') ")
    clear_output()

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_nezha():
    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"
    download_url = f"https://slink.ltd/https://github.com/nezhahq/agent/releases/download/v0.20.5/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)
        os.system("/tmp/code/nezha-agent -s mb2.cnmw.us.kg:16667 -p fTDSMw9zPZokP8DOiH -d --disable-auto-update --disable-force-update  --temperature --report-delay 4 --gpu")
        # subprocess.run(["/tmp/code/nezha-agent", "-s", "http://nnzmb.qilan.cloudns.ch:16666/", "-p", nezha_agent_key, "-d"], check=True)
        # for command in nz_commands:
        #     try:
        #         subprocess.run(command, check=True, shell=True)
        #         print(f"Executed: {command}")
        #     except subprocess.CalledProcessError as e:
        #         print(f"An error occurred while executing: {command}\nError: {e}")
        
    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:
                threading.Thread(target=Frpc, daemon=True).start()
            if nps_status:
                threading.Thread(target=NPS, daemon=True).start()
            threading.Thread(target=run_nezha).start()
            #threading.Thread(target=run_commands).start()
            break
        except requests.exceptions.Timeout as e:
            print(f"接口异常2: {e}")
            if frp_status:
                threading.Thread(target=Frpc, daemon=True).start()
            if nps_status:
                threading.Thread(target=NPS, daemon=True).start()
            threading.Thread(target=run_nezha).start()
            #threading.Thread(target=run_commands).start()
            break
            
        except requests.exceptions.RequestException as e:
            print(f"接口异常3: {e}")
            if frp_status:
                threading.Thread(target=Frpc, daemon=True).start()
            if nps_status:
                threading.Thread(target=NPS, daemon=True).start()
            threading.Thread(target=run_nezha).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).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("python3 /tmp/code/sd/stable-diffusion-webui/launch.py --api --api-auth QiLan:1415361185 --no-hashing  --no-gradio-queue --xformers")