Qilan2 commited on
Commit
1a051a0
·
verified ·
1 Parent(s): c9395f7

Create hf/server9-bf.py

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