Qilan2 commited on
Commit
584b5ec
·
verified ·
1 Parent(s): 9ee8ec4

Create server12.py

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