Qilan2 commited on
Commit
1425ee0
·
verified ·
1 Parent(s): 557c1b6

Create server11.py

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