Qilan2 commited on
Commit
c337930
·
verified ·
1 Parent(s): 2da1130

Create server10v.py

Browse files
Files changed (1) hide show
  1. server10v.py +557 -0
server10v.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 实时监控日志
2
+ #tail -f /data/server10.log
3
+ # 查找端口进程
4
+ #lsof -i :8000
5
+ # 查找server.py进程
6
+ #ps aux | grep server.py
7
+ huggingface_user="Qi28s"#
8
+ huggingface_id="1010"
9
+ huggingface_tokon="hf_bHdgZHDe QHDHtoMjyIgpKvICbNbWJcTDTG"
10
+
11
+ ini_content = {"username":"tmpysanneernier91","key":"fcffd91fcc8a94fb4a8d3a1b39ff652c"}
12
+ frp_url = '119.8.118.149'
13
+ ssh_port = '7082'
14
+ ssh_url = '45.32.68.209'
15
+ st_url = f'http://{frp_url}:7090'
16
+ huggingface_name = 'tmpysanneernier91'
17
+ huggingface_Data_name = 'qilan-st10'
18
+ data_folder = '/data/SillyTavern' # 要压缩的目录
19
+ zip_file_path = '/dev/shm/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
20
+ metadata_file_path = '/dev/shm/a/dataset-metadata.json'
21
+ configs = [
22
+ ("""
23
+ [common]
24
+ server_addr = 47.237.156.222
25
+ server_port = 7000
26
+
27
+ [safsa10]
28
+ type = tcp
29
+ local_ip = 127.0.0.1
30
+ local_port = 8000
31
+ remote_port = 7091
32
+ """, '/data/frp/frpc.ini'),
33
+ (f"""
34
+ [common]
35
+ server_addr = {frp_url}
36
+ server_port = 7000
37
+ token = qilan
38
+ [1kkjmk1010]
39
+ type = tcp
40
+ local_ip = 127.0.0.1
41
+ local_port = 8000
42
+ remote_port = 7090
43
+ """, '/data/frp/frpc1.ini'),
44
+ ("""
45
+ [common]
46
+ server_addr = 43.134.75.213
47
+ server_port = 7000
48
+ [2kjas9]
49
+ type = tcp
50
+ local_ip = 127.0.0.1
51
+ local_port = 8000
52
+ remote_port = 7079
53
+ """, '/data/frp/frpc2.ini'),
54
+ ("""
55
+ [common]
56
+ server_addr = 8.210.217.27
57
+ server_port = 7000
58
+ [3kja1sh9]
59
+ type = tcp
60
+ local_ip = 127.0.0.1
61
+ local_port = 8000
62
+ remote_port = 7079
63
+ """, '/data/frp/frpc3.ini'),
64
+ ("""
65
+ [common]
66
+ server_addr = 45.32.68.209
67
+ server_port=7000
68
+ [4kkji1mk9]
69
+ type=tcp
70
+ local_ip=127.0.0.1
71
+ local_port=8000
72
+ remote_port=7079
73
+ """, '/data/frp/frpc4.ini'),
74
+ (f"""
75
+ [common]
76
+ server_addr = {ssh_url}
77
+ server_port=7000
78
+ [5kkji1mk99]
79
+ type=tcp
80
+ local_ip=127.0.0.1
81
+ local_port=22
82
+ remote_port={ssh_port}
83
+ """, '/data/frp/frpc5.ini')
84
+ ]
85
+ kaggle_metadata = {
86
+ "title": "Your Dataset Title",
87
+ "id": f"{huggingface_name}/{huggingface_Data_name}",
88
+ "licenses": [{"name": "CC0-1.0"}]
89
+ }
90
+ st_status = True
91
+
92
+ import subprocess
93
+ import os
94
+ import sys
95
+ import configparser
96
+ from IPython.display import clear_output
97
+ import urllib.request
98
+ from pathlib import Path
99
+ import requests
100
+ import json
101
+ import threading
102
+ import time
103
+ import pexpect
104
+ import socket
105
+ import time
106
+ import glob # 导入 glob 模块
107
+ from requests.adapters import HTTPAdapter
108
+ from requests.packages.urllib3.util.retry import Retry
109
+ import logging
110
+ from datetime import datetime
111
+ import pytz
112
+ os.system("rm -r /sync.sh")
113
+ os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh" )
114
+ os.system("export LC_ALL=zh_CN.UTF-8")
115
+ # 创建 FRP 文件夹并下载 frpc 可执行文件。
116
+ os.system("mkdir -p /data/frp")
117
+ os.system("wget /data/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /data/frp/frpc")
118
+ os.system("chmod +x /data/frp/frpc")
119
+ os.system("wget https://huggingface.co/datasets/Qilan2/st-server/resolve/main/xugou-agent-linux-amd64?download=true -O /data/xugou-agent")
120
+ os.system("chmod +x /data/xugou-agent")
121
+ os.system('nohup /data/xugou-agent start --server "https://tz.282820.xyz" --token "xugou_meqz1qus_80244ac171f1d9cf3a1ead6be2ecf86f.7d4ae786cbb7e559" --interval "30" > /data/xugou-agent.log 2>&1 &')
122
+ os.system("wget https://huggingface.co/datasets/Qilan2/st-server/raw/main/ip_huggingface.py -O /data/ip_huggingface.py")
123
+
124
+ def kill_frpc_processes():
125
+ try:
126
+ # 使用pkill命令结束所有frpc进程
127
+ subprocess.run(['pkill', '-f', 'frpc'], check=True)
128
+ print("所有frpc进程已被结束。")
129
+ except subprocess.CalledProcessError as e:
130
+ # 如果pkill命令失败,打印错误信息
131
+ print(f"结束frpc进程时出错: {e}")
132
+ kill_frpc_processes()
133
+
134
+
135
+
136
+
137
+
138
+ # 创建一个锁
139
+ lock = threading.Lock()
140
+
141
+ last_uploaded_size = -1
142
+
143
+
144
+ def update_last_uploaded_size(size):
145
+ global last_uploaded_size
146
+ last_uploaded_size = size
147
+
148
+ def get_folder_size(folder):
149
+ """使用 du 命令获取文件夹的总大小(字节数)"""
150
+ result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
151
+ if result.returncode == 0:
152
+ size = result.stdout.split()[0] # 获取大小
153
+ return int(size)
154
+ else:
155
+ print(f"Error calculating size: {result.stderr.decode()}")
156
+ return 0
157
+
158
+ def compress_folder():
159
+ global last_uploaded_size # 声明使用全局变量
160
+
161
+ # 检查是否是中国时区早上5点
162
+ china_tz = pytz.timezone('Asia/Shanghai')
163
+ now = datetime.now(china_tz)
164
+ if now.hour == 5:
165
+ print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 早上5点,跳过备份操作")
166
+ return
167
+
168
+ # 清理并创建目录 /a
169
+ if os.path.exists('/dev/shm/a'):
170
+ subprocess.run(['rm', '-rf', '/dev/shm/a'])
171
+ os.makedirs('/dev/shm/a', exist_ok=True)
172
+ with lock: # 使用锁
173
+ # 获取当前文件夹的大小
174
+ current_folder_size = get_folder_size(data_folder)
175
+ print(f"当前文件夹大小: {current_folder_size} 字节")
176
+
177
+ # 判断文件夹大小是否大于 800MB (800MB = 800 * 1024 * 1024 字节)
178
+ if current_folder_size < (200 * 1024 ** 2):
179
+ print("文件夹小于800MB,不进行上传和压缩。")
180
+ return
181
+
182
+ # 如果是首次运行或者文件夹大小不同于上次上传,进行压缩
183
+ if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
184
+ print('开始压缩数据')
185
+ try:
186
+ # 执行压缩
187
+ result = subprocess.run(
188
+ f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
189
+ shell=True,
190
+ check=True,
191
+ stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
192
+ stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
193
+ )
194
+ except subprocess.CalledProcessError as e:
195
+ print(f"命令失败,返回代码: {e.returncode}")
196
+ return
197
+
198
+ print('压缩完成')
199
+ file_path = "/dev/shm/a/sillytavern.ctk"
200
+ subprocess.run(['mv', zip_file_path, file_path])
201
+ print(f"数据压缩为 {file_path}")
202
+
203
+ file_size = os.path.getsize(file_path) # 获取压缩包的大小
204
+ print('文件大小:', file_size)
205
+
206
+ if file_size < (200 * 1024 ** 2): # 判断压缩后的大小是否小于 800MB
207
+ print("压缩文件小于800MB,不进行上传。")
208
+ return
209
+
210
+ # 执行上传
211
+ if last_uploaded_size == -1:
212
+ print("首次运行,正在执行上传...")
213
+ update_last_uploaded_size(file_size)
214
+
215
+ with open(metadata_file_path, 'w') as json_fid:
216
+ json.dump(kaggle_metadata, json_fid)
217
+
218
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/dev/shm/a'])
219
+ #kaggle datasets version -m 'new version message' -p /dev/shm/a
220
+ last_uploaded_size = file_size
221
+ else:
222
+ print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...")
223
+ update_last_uploaded_size(file_size)
224
+
225
+ with open(metadata_file_path, 'w') as json_fid:
226
+ json.dump(kaggle_metadata, json_fid)
227
+
228
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/dev/shm/a'])
229
+ last_uploaded_size = file_size
230
+
231
+ else:
232
+ print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过")
233
+
234
+ def repeat_task():
235
+ print('------打包线程启动-------------')
236
+ while True:
237
+ print('等待打包')
238
+ time.sleep(18000)
239
+ compress_folder()
240
+ print('------打包线程结束-------------')
241
+
242
+
243
+ def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
244
+ """创建一个带重试机制的请求会话"""
245
+ session = session or requests.Session()
246
+ retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
247
+ adapter = HTTPAdapter(max_retries=retry)
248
+ session.mount('http://', adapter)
249
+ session.mount('https://', adapter)
250
+ return session
251
+
252
+
253
+
254
+ def check_api1():
255
+ # 第一次检查 SillyTavern 是否启动
256
+ thread_started = False
257
+ n = 0
258
+ while True:
259
+ n += 1
260
+ if not os.path.exists(data_folder):
261
+ logging.error(f"/sillytavern/ 文件不存在,结束检测")
262
+ break
263
+ try:
264
+ url = "http://127.0.0.1:8000/v1"
265
+ response = requests.get(url, timeout=30)
266
+
267
+ if response.status_code == 403:
268
+ print("SillyTavern已经启动")
269
+ break
270
+
271
+ print("SillyTavern未启动,状态码:", response.status_code, n)
272
+
273
+ except requests.exceptions.RequestException as e:
274
+ print(f"SillyTavern未启动3: {e}, 尝试次数: {n}")
275
+
276
+ time.sleep(5)
277
+
278
+ print('ST本地已经运行')
279
+
280
+ def frp(configs, backstage):
281
+ print('-----------FRP开始-------------')
282
+ # 遍历所有配置并启动 FRP。
283
+ for config_data, config_file_path in configs:
284
+ with open(config_file_path, 'w') as config_file:
285
+ config_file.write(config_data)
286
+ # 启动 frpc 命令和参数。
287
+ frpc_cmd=['/data/frp/frpc', '-c', config_file_path]
288
+
289
+ if backstage:
290
+ subprocess.Popen(frpc_cmd)
291
+ else:
292
+ subprocess.run(f'/data/frp/frpc -c {config_file_path}', shell=True, check=True)
293
+ print('-----------FRP结束-------------')
294
+
295
+
296
+
297
+ def monitor_port():
298
+ while True:
299
+ url = "http://127.0.0.1:8000/v1"
300
+ response = requests.get(url, timeout=30)
301
+ if response.status_code == 403:
302
+ print("SillyTavern运行中")
303
+ # break
304
+ else:
305
+ print("SillyTavern未运行,状态码:", response.status_code, n)
306
+ # 读取 config.ini 中的 monitor_port_enabled 配置项
307
+ config = configparser.ConfigParser()
308
+ config.read('/data/config.ini')
309
+ monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
310
+ if monitor_port_enabled:
311
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
312
+ backup_thread.start()
313
+ else:
314
+ print(f"monitor_port_enabled 为False跳过")
315
+
316
+
317
+ # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
318
+ # result = sock.connect_ex(('localhost', 8000))
319
+ # if result == 0:
320
+ # print(f"端口 8000 正在使用中")
321
+ # else:
322
+ # print(f"端口 8000 未被使用")
323
+ # # 读取 config.ini 中的 monitor_port_enabled 配置项
324
+ # config = configparser.ConfigParser()
325
+ # config.read('/data/config.ini')
326
+ # monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
327
+ # if monitor_port_enabled:
328
+ # backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
329
+ # backup_thread.start()
330
+ # else:
331
+ # print(f"monitor_port_enabled 为False跳过")
332
+
333
+ time.sleep(5) # 每5秒检查一次
334
+ def Run_SillyTavern():
335
+ os.chdir(data_folder)
336
+ try:
337
+ # 启动 Node.js 服务器,并将输出重定向到 /dev/null
338
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
339
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
340
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
341
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
342
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
343
+
344
+ print("已尝试启动 server.js")
345
+ except subprocess.CalledProcessError as e:
346
+ print(f"命令失败,返回码: {e.returncode}")
347
+ except Exception as e: # 捕获所有其他异常
348
+ print(f"发生异常: {e}")
349
+
350
+ def SillyTavern():
351
+ print('-----------SillyTavern开始-------------')
352
+ # 创建目录并写入 kaggle.json
353
+
354
+
355
+ # 打印当前工作目录和用户主目录
356
+ print("Current Working Directory:", os.getcwd())
357
+ print("Home Directory:", os.path.expanduser('~'))
358
+ kaggle_dir = os.path.expanduser('~/.kaggle')
359
+ kaggle_file_path = os.path.join(kaggle_dir, 'kaggle.json')
360
+
361
+ # 确保目录存在
362
+ os.makedirs(kaggle_dir, exist_ok=True)
363
+
364
+ # 显式写入并验证
365
+ try:
366
+ with open(kaggle_file_path, 'w') as json_file:
367
+ json.dump(ini_content, json_file, indent=4)
368
+
369
+ # 验证文件内容
370
+ with open(kaggle_file_path, 'r') as json_file:
371
+ print("文件内容:", json_file.read())
372
+
373
+ # 设置权限
374
+ os.chmod(kaggle_file_path, 0o600)
375
+
376
+ print(f"文件已写入: {kaggle_file_path}")
377
+ except Exception as e:
378
+ print(f"发生错误: {e}")
379
+
380
+
381
+
382
+ os.system(f"rm -rf /a /data/sillytavern /data/data /data/*.zip /data/*.ctk")
383
+ # os.system(f"mkdir -p {data_folder}")
384
+ os.chdir('/data')
385
+ os.system("ls")
386
+ print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
387
+ # os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
388
+ download_n = 0
389
+ while True:
390
+ # 执行下载命令
391
+ if download_n > 6:
392
+ break
393
+ os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /data")
394
+ # 检查文件是否存在
395
+ if os.path.exists(f'/data/{huggingface_Data_name}.zip'):
396
+ print(f"{huggingface_Data_name}.zip 下载成功!")
397
+ break # 跳出循环
398
+ print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
399
+ download_n += 1
400
+ time.sleep(300) # 等待一段时间再重试(例如5秒
401
+ # os.system('kaggle datasets download xovale7506/sillytavern-data2')
402
+ # 检查文件是否存在
403
+ if not os.path.exists(f'/data/{huggingface_Data_name}.zip'):
404
+ print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
405
+
406
+ else:
407
+
408
+ # 如果文件存在,可以继续执行后续代码
409
+ print(f"文件 /data/{huggingface_Data_name}.zip 存在,继续执行程序。")
410
+ # # 解压 sillytavern.zip
411
+ # os.system("rm *.zip")
412
+ os.system(f"7z x /data/{huggingface_Data_name}.zip -y")
413
+ os.system("mv /data/sillytavern.tck sillytavern.tar.gz")
414
+ os.system("mv /data/sillytavern.ctk sillytavern.tar.gz")
415
+ os.system("ls /data")
416
+ # os.system("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz")
417
+ os.system(f"tar -xvpf /data/sillytavern.tar.gz -C /data --use-compress-program=pigz > /dev/null")
418
+ # os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")
419
+ os.system("mv /data/data/SillyTavern /data/SillyTavern")
420
+
421
+ print('更新文件')
422
+ os.chdir('/data/SillyTavern')
423
+ os.system(f"ls {data_folder}")
424
+ os.system("nvm install node")
425
+ os.system("nvm use node")
426
+ os.system("npm install -y")
427
+ try:
428
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
429
+ except subprocess.CalledProcessError as e:
430
+ print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
431
+ print("Output:", e.output)
432
+ os.system(f"ls {data_folder}")
433
+ os.system("python /data/ip_huggingface.py")
434
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
435
+ backup_thread.start()
436
+ # os.system(f"rm -rf /a /data/sillytavern /data/data /data/*.zip /data/*.ctk")
437
+
438
+ print('-----------SillyTavern结束-------------')
439
+ import requests
440
+
441
+ def _reconstruct_token(partial_token):
442
+ """
443
+ 重构完整的 token
444
+
445
+ :param partial_token: 部分 token
446
+ :return: 完整的 token
447
+ """
448
+ return partial_token.replace(" ", "")
449
+
450
+ def restart_huggingface_space(space_name, space_id, partial_token):
451
+ """
452
+ 重启 Hugging Face Space
453
+
454
+ :param space_name: Space 的命名空间
455
+ :param space_id: Space 的 ID
456
+ :param partial_token: Hugging Face 部分访问令牌
457
+ :return: 响应结果字典
458
+ """
459
+ # 重构完整 token
460
+ token = _reconstruct_token(partial_token)
461
+
462
+ url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
463
+ headers = {
464
+ "Content-Type": "application/json",
465
+ "Authorization": f"Bearer {token}",
466
+ "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"
467
+ }
468
+
469
+ try:
470
+ response = requests.post(url, headers=headers, json={})
471
+ return {
472
+ "status_code": response.status_code,
473
+ "success": response.status_code == 200,
474
+ "message": response.text
475
+ }
476
+ except requests.RequestException as e:
477
+ return {
478
+ "status_code": None,
479
+ "success": False,
480
+ "message": str(e)
481
+ }
482
+
483
+ # 使用示例
484
+ import psutil
485
+
486
+ def check_system_resources():
487
+ # 获取CPU使用率
488
+ cpu_usage = psutil.cpu_percent(interval=1)
489
+
490
+ # 获取内存使用率
491
+ memory = psutil.virtual_memory()
492
+ memory_usage = memory.percent
493
+
494
+ # 检查CPU和内存占用是否超过85%
495
+ if cpu_usage >= 90 or memory_usage >= 90:
496
+ print("占用过高")
497
+ # 可选:打印具体的使用率
498
+ print(f"CPU使用率: {cpu_usage}%")
499
+ print(f"内存使用率: {memory_usage}%")
500
+ result = restart_huggingface_space(huggingface_user, huggingface_id, huggingface_tokon)
501
+ print(result)
502
+ time.sleep(6666666)
503
+ else:
504
+ print("系统资源正常")
505
+
506
+
507
+ # 调用函数
508
+
509
+
510
+ threading.Thread(target=SillyTavern, daemon=True).start()
511
+ # SillyTavern()
512
+ time.sleep(60)
513
+ check_api1()
514
+
515
+
516
+ # 创建 ConfigParser 对象
517
+ config = configparser.ConfigParser()
518
+ # 添加一个 'general' 部分
519
+ config.add_section('general')
520
+ # 设置 'monitor_port_enabled' 选项的值为 True
521
+ config.set('general', 'monitor_port_enabled', 'True')
522
+ # 将配置写入到 'config.ini' 文件中
523
+ with open('/data/config.ini', 'w') as configfile:
524
+ config.write(configfile)
525
+ if os.path.exists(f'/data/{huggingface_Data_name}.zip'):
526
+ os.system(f"rm -rf /a /data/data /data/*.zip /data/*.ctk /data/*.gz")
527
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)#压缩备份
528
+ backup_thread.start()
529
+ print("开始衔接")
530
+ Service_status = True
531
+ frp(configs, True)
532
+ threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
533
+ # check_system_resources()
534
+ # time.sleep(600)
535
+ while True:
536
+ # 检查是否是中国时区早上6点
537
+ china_tz = pytz.timezone('Asia/Shanghai')
538
+ now = datetime.now(china_tz)
539
+ if now.hour == 14 and now.minute < 2: # 6:00-6:05之间退出
540
+ print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 到达早上6点,退出循环")
541
+ break
542
+ else:
543
+ print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 未到达早上6点")
544
+
545
+ if backup_thread.is_alive():
546
+ print("备份线程仍在运行...")
547
+ else:
548
+ print("备份线程已停止.")
549
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)
550
+ backup_thread.start()
551
+ time.sleep(5)
552
+ else:
553
+ print(f'{data_folder}/start.sh 文件不存在结束执行')
554
+ compress_folder()
555
+ result = restart_huggingface_space(huggingface_user, huggingface_id, huggingface_tokon)
556
+ print(result)
557
+