Qilan2 commited on
Commit
f79d821
·
verified ·
1 Parent(s): 5b14c13

Update server9-bf.py

Browse files
Files changed (1) hide show
  1. server9-bf.py +587 -339
server9-bf.py CHANGED
@@ -1,58 +1,10 @@
1
- import os
2
- import sys
3
- import time
4
- import json
5
- import yaml
6
- import glob
7
- import pexpect
8
- import socket
9
- import logging
10
- import threading
11
- import subprocess
12
- import configparser
13
- import urllib.request
14
- import re
15
- from pathlib import Path
16
- from datetime import datetime, timedelta
17
- import psutil
18
- import pytz
19
- import requests
20
- from requests.adapters import HTTPAdapter
21
- from requests.packages.urllib3.util.retry import Retry
22
- from IPython.display import clear_output
23
-
24
- # ==========================================
25
- # 0. 配置日志输出格式
26
- # ==========================================
27
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
28
-
29
- # ==========================================
30
- # 1. 全局配置参数
31
- # ==========================================
32
- ini_content = {"username": "natclghpe", "key": "21e32070151c7fe0fbd5af3287d7e489"}
33
- cf_token = 'eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiNjMyNTRkZjYtNWY0ZC00YjM2LTlmZjMtY2M1MzMxMzQ1ODUyIiwicyI6IlpXSTFNV1JsTkRndFlqWmhZUzAwWW1VNUxUZzFOemN0Wm1GbE1tUTFNREZrTldSaiJ9'
34
- cf_jg = 'https://jg9-cf.qilan.sbs'
35
- cf_ssh = 'jg9-ssh.qilan.sbs'
36
  frp_url = '119.8.118.149'
37
  ssh_port = '7082'
38
  ssh_url = '45.32.68.209'
39
  st_url = f'http://{frp_url}:7082'
40
-
41
  huggingface_name = 'natclghpe'
42
  huggingface_Data_name = 'qilan-st9'
43
- data_folder = '/root/SillyTavern'
44
- zip_file_path = '/a/sillytavern.tar.gz'
45
- metadata_file_path = '/a/dataset-metadata.json'
46
-
47
- kaggle_metadata = {
48
- "title": "Your Dataset Title",
49
- "id": f"{huggingface_name}/{huggingface_Data_name}",
50
- "licenses": [{"name": "CC0-1.0"}]
51
- }
52
-
53
- last_uploaded_size = -1
54
- lock = threading.Lock()
55
-
56
  configs = [
57
  ("""
58
  [common]
@@ -143,344 +95,640 @@ configs = [
143
  remote_port={ssh_port}
144
  """, '/content/frp/frpc5.ini')
145
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
- # ==========================================
148
- # 2. 核心通用工具函数
149
- # ==========================================
150
- def run_cmd(command, ignore_errors=False, quiet=False):
151
  try:
152
- stdout = subprocess.DEVNULL if quiet else None
153
- stderr = subprocess.DEVNULL if quiet else None
154
- subprocess.run(command, shell=True, check=not ignore_errors, stdout=stdout, stderr=stderr)
155
  except subprocess.CalledProcessError as e:
156
- if not ignore_errors:
157
- logging.error(f"命令执行失败: {command}\n误码: {e.returncode}")
 
158
 
159
- def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
160
- session = session or requests.Session()
161
- retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
162
- adapter = HTTPAdapter(max_retries=retry)
163
- session.mount('http://', adapter)
164
- session.mount('https://', adapter)
165
- return session
166
 
167
- def is_installed(package):
 
168
  try:
169
- subprocess.run(['dpkg', '-s', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
170
- return True
171
- except subprocess.CalledProcessError:
172
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
- def install_package(package):
175
- logging.info(f"正在安装 {package}...")
176
- run_cmd(f"sudo apt install {package} -y", quiet=True)
177
-
178
- # ==========================================
179
- # 3. 环境初始化与基础设置
180
- # ==========================================
181
- def init_environment():
182
- logging.info('-----------更新软件包列表开始-------------')
183
- run_cmd("rm -r /sync.sh", ignore_errors=True, quiet=True)
184
- run_cmd("wget -q -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
185
- run_cmd("export LC_ALL=zh_CN.UTF-8")
186
- run_cmd("mkdir -p /content/frp")
187
- run_cmd("wget -q https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
188
- run_cmd("chmod +x /content/frp/frpc")
189
- if not is_installed('nodejs'): install_package('nodejs')
190
- if not is_installed('npm'): install_package('npm')
191
- run_cmd("pip uninstall requests urllib3 -y", quiet=True)
192
- run_cmd("pip install requests urllib3 ruamel.yaml pexpect pytz", quiet=True)
193
- run_cmd("apt-get install -y sshpass p7zip-full pigz pv", quiet=True)
194
- logging.info('-----------更新软件包列表结束-------------')
195
-
196
- def setup_cloudflared(install_ssh_config=True):
197
- if install_ssh_config:
198
- run_cmd("sudo mkdir -p --mode=0755 /usr/share/keyrings")
199
- run_cmd("curl -fsSL https://pkg.cloudflare.com/cloudflare-public-v2.gpg | sudo tee /usr/share/keyrings/cloudflare-public-v2.gpg >/dev/null")
200
- run_cmd("echo 'deb [signed-by=/usr/share/keyrings/cloudflare-public-v2.gpg] https://pkg.cloudflare.com/cloudflared any main' | sudo tee /etc/apt/sources.list.d/cloudflared.list")
201
- run_cmd("sudo apt-get update && sudo apt-get install cloudflared -y", quiet=True)
202
- ssh_dir = os.path.expanduser("~/.ssh")
203
- os.makedirs(ssh_dir, exist_ok=True)
204
- ssh_config_content = f"Host {cf_ssh}\n ProxyCommand cloudflared access ssh --hostname %h\n StrictHostKeyChecking no\n"
205
- config_path = os.path.join(ssh_dir, "config")
206
- with open(config_path, "w") as f: f.write(ssh_config_content)
207
- os.chmod(config_path, 0o600)
208
- else:
209
- run_cmd(f"sudo cloudflared service install {cf_token}", quiet=True)
210
-
211
- def setup_ssh():
212
- logging.info('-----------SSH配置开始-------------')
213
- run_cmd("apt update && apt install openssh-server vim -y", quiet=True)
214
- run_cmd("sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config")
215
- run_cmd("sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config")
216
- run_cmd("echo 'root:qilan' | sudo chpasswd")
217
- run_cmd("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
218
- run_cmd("service ssh restart", quiet=True)
219
- run_cmd("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
220
 
221
  def generate_ssh_key():
222
- run_cmd("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub", quiet=True)
223
- run_cmd("ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''", quiet=True)
224
- run_cmd('chmod 600 ~/.ssh/id_rsa')
 
 
 
 
 
 
225
 
226
  def copy_public_key_to_remote(host, port, user, password):
 
227
  try:
228
  command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
229
  child = pexpect.spawn(command)
230
- child.expect("password:", timeout=10)
 
 
231
  child.sendline(password)
 
 
232
  child.expect(pexpect.EOF)
 
 
 
233
  except Exception as e:
234
- logging.error(f"复制公钥失败: {e}")
235
 
236
- # ==========================================
237
- # 4. 接力信息修改模块 (IP与接力时间)
238
- # ==========================================
239
- def get_current_ip():
240
- try: return requests.get("https://ipinfo.io/ip", timeout=5).text.strip()
241
- except: return "Unknown IP"
242
 
243
- def get_geo_info(ip_address):
244
- try:
245
- response = requests.get("https://api.qjqq.cn/api/Local", headers={"User-Agent": "Mozilla/5.0"}, timeout=5)
246
- if response.status_code == 200 and response.json().get('code') == 200:
247
- data = response.json()['data']
248
- return {'ip': data['ip'], 'country': data['country'], 'isp': data['isp']}
249
- except: pass
250
- return None
251
 
252
- def get_next_relay_time():
253
- try:
254
- boot_time = datetime.fromtimestamp(psutil.boot_time())
255
- china_tz = pytz.timezone('Asia/Shanghai')
256
- next_time = pytz.UTC.localize(boot_time).astimezone(china_tz) + timedelta(hours=12)
257
- return next_time.strftime("%Y-%m-%d %H:%M:%S")
258
- except: return "未知时间"
259
 
260
- def replace_info_in_file(file_path):
261
- try:
262
- if not os.path.exists(file_path): return
263
- ip_address, geo_info, next_relay_time = get_current_ip(), get_geo_info(get_current_ip()), get_next_relay_time()
264
- if geo_info:
265
- with open(file_path, 'r', encoding='utf-8') as f: content = f.read()
266
- content = re.sub(r'接力时间\[.*?\]', f'接力时间[{next_relay_time}]', content)
267
- content = re.sub(r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]', f'IP[{ip_address}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]', content)
268
- with open(file_path, 'w', encoding='utf-8') as f: f.write(content)
269
- logging.info(f"前端页面更新成功: 接力时间[{next_relay_time}], IP[{ip_address}]")
270
- except Exception as e: logging.error(f"替换前端信息发生错误: {e}")
271
-
272
- # ==========================================
273
- # 5. 双机接力 rsync 数据同步核心
274
- # ==========================================
275
- def sync_data_via_rsync():
276
- """首次初始化阻断式同步"""
277
- logging.info("------ 开始执行首次双机接力同步检测 ------")
278
- retry_n = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  while True:
280
- if not os.path.exists(data_folder): return
 
 
 
281
  try:
282
- if requests.get("http://127.0.0.1:8000/v1", timeout=10).status_code == 403:
283
- logging.info("SillyTavern 本地接口已启动!")
 
 
 
284
  break
285
- except requests.exceptions.RequestException: pass
286
- if (retry_n := retry_n + 1) % 12 == 0: logging.info("等待本地 ST 启动中...")
 
 
 
 
287
  time.sleep(5)
288
 
289
- fail_count = 0
290
- while fail_count <= 5:
291
- if not os.path.exists(data_folder): break
 
 
 
 
 
 
 
 
 
 
 
 
292
  try:
293
- response = requests_retry_session().get(f"{cf_jg}/csrf-token", timeout=15)
294
- if response.status_code == 200 and "token" in response.json():
295
- logging.info("成功探测到旧机器,执行首次全面接力拉取...")
296
- # 注意这里加了 -u 参数,保护本地可能存在的新数据不被覆盖
297
- subprocess.run(
298
- f"sshpass -p 'qilan' rsync -avzu --timeout=600 -e 'ssh -p 22 -o StrictHostKeyChecking=no' root@{cf_ssh}:{data_folder}/ {data_folder}/",
299
- shell=True, check=True
300
- )
301
- logging.info("首次拉取成功,旧机器数据已接管。")
 
 
 
 
 
 
 
 
 
 
 
302
  break
303
- else: fail_count += 1
304
- except Exception as e:
305
- fail_count += 1
306
- if fail_count > 5: logging.warning("未检测到前置机器,可能已宕机,将使用本地数据。")
 
 
 
307
  time.sleep(5)
308
 
309
- def continuous_sync_task():
310
- """后台常驻:重叠期间每5分钟持续增量拉取旧机器数据"""
311
- logging.info("------ 后台持续增量同步守护线程已启动 ------")
312
- fail_count = 0
313
- while fail_count < 5:
314
- time.sleep(300) # 每5分钟探测拉取一次
315
- try:
316
- response = requests_retry_session().get(f"{cf_jg}/csrf-token", timeout=15)
317
- if response.status_code == 200 and "token" in response.json():
318
- logging.info("【接力中】探测到旧机器仍在运行,执行后台增量同步...")
319
- # 核心:使用 -u (--update) 保证新机器上你产生的新聊天记录不会被旧机器覆盖!
320
- subprocess.run(
321
- f"sshpass -p 'qilan' rsync -avzu --timeout=600 -e 'ssh -p 22 -o StrictHostKeyChecking=no' root@{cf_ssh}:{data_folder}/ {data_folder}/",
322
- shell=True, check=True, stdout=subprocess.DEVNULL
323
- )
324
- fail_count = 0 # 只要成功一次,就重置失败计数
325
- else:
326
- fail_count += 1
327
- except Exception as e:
328
- fail_count += 1
329
- logging.info(f"探测旧机器异常,可能已关机。失败次数: {fail_count}/5")
330
-
331
- logging.info("------ 旧机器已彻底离线,后台接力同步任务圆满结束 ------")
332
 
333
- # ==========================================
334
- # 6. 后台备份、FRP 与进程守护
335
- # ==========================================
336
- def compress_folder():
337
- global last_uploaded_size
338
- run_cmd('rm -rf /a/', ignore_errors=True, quiet=True)
339
- os.makedirs('/a', exist_ok=True)
340
- with lock:
341
- try:
342
- size_out = subprocess.run(['du', '-sb', data_folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
343
- current_folder_size = int(size_out.stdout.split()[0]) if size_out.returncode == 0 else 0
344
- except: return
345
-
346
- if current_folder_size < (800 * 1024 ** 2): return
347
 
348
- if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
349
- logging.info('开始压缩打包数据用于备份...')
350
- run_cmd(f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path}', quiet=True)
351
- run_cmd(f'mv {zip_file_path} /a/sillytavern.ctk', ignore_errors=True)
352
- if not os.path.exists("/a/sillytavern.ctk"): return
353
-
354
- file_size = os.path.getsize("/a/sillytavern.ctk")
355
- if file_size < (800 * 1024 ** 2): return
356
 
357
- logging.info("准备将压缩包上传至 Kaggle...")
358
- with open(metadata_file_path, 'w') as f: json.dump(kaggle_metadata, f)
359
- run_cmd('kaggle datasets version -m "Auto Backup Update" -p /a')
360
- last_uploaded_size = file_size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
- def repeat_task():
363
- logging.info('------后台定时打包备份线程已启动-------------')
364
- while True:
365
- time.sleep(18000)
366
- compress_folder()
367
 
368
- def kill_frpc_processes():
369
- try: subprocess.run(['pkill', '-f', 'frpc'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
370
- except subprocess.CalledProcessError: pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
 
372
- def frp(configs, backstage):
373
- logging.info('-----------启动 FRP 内网穿透-------------')
374
- for config_data, config_file_path in configs:
375
- with open(config_file_path, 'w') as config_file: config_file.write(config_data)
376
- if backstage: subprocess.Popen(['/content/frp/frpc', '-c', config_file_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
377
- else: run_cmd(f'/content/frp/frpc -c {config_file_path}', quiet=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
 
379
- def Run_SillyTavern():
380
- os.chdir(data_folder)
381
- try: run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
382
- except Exception as e: logging.error(f"SillyTavern 启动失败: {e}")
383
 
384
  def monitor_port():
385
  while True:
386
  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
387
- if sock.connect_ex(('localhost', 8000)) != 0:
 
 
 
 
 
388
  config = configparser.ConfigParser()
389
  config.read('/config.ini')
390
- if config.getboolean('general', 'monitor_port_enabled', fallback=False):
391
- threading.Thread(target=Run_SillyTavern, daemon=True).start()
392
- time.sleep(5)
393
-
394
- # ==========================================
395
- # 7. 主程序部署流程
396
- # ==========================================
397
- def setup_sillytavern():
398
- logging.info('-----------SillyTavern 基础数据部署开始-------------')
399
- os.makedirs(os.path.expanduser("~/.kaggle"), exist_ok=True)
400
- with open('/root/.kaggle/kaggle.json', 'w') as json_file: json.dump(ini_content, json_file, indent=4)
401
- run_cmd("chmod 600 ~/.kaggle/kaggle.json")
402
- run_cmd(f"rm -rf /a /sillytavern /*.zi* {data_folder}", ignore_errors=True, quiet=True)
403
- os.makedirs(data_folder, exist_ok=True)
404
- os.chdir('/')
405
-
406
- for _ in range(7):
407
- run_cmd(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
408
- if os.path.exists(f'/{huggingface_Data_name}.zip'): break
409
- time.sleep(5)
410
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  if not os.path.exists(f'/{huggingface_Data_name}.zip'):
 
412
  generate_ssh_key()
413
- copy_public_key_to_remote(cf_ssh, 22, "root", "qilan")
414
- run_cmd(f"sshpass -p 'qilan' rsync -avz --timeout=600 -e 'ssh -p 22 -o StrictHostKeyChecking=no' root@{cf_ssh}:{data_folder}/ {data_folder}/")
415
  else:
416
- run_cmd(f"7z x /{huggingface_Data_name}.zip -o/ -y", quiet=True)
417
- run_cmd("mv /sillytavern.tck sillytavern.tar.gz", ignore_errors=True, quiet=True)
418
- run_cmd("mv /sillytavern.ctk sillytavern.tar.gz", ignore_errors=True, quiet=True)
419
- run_cmd("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null")
420
-
421
- run_cmd("rm -f ip.py", quiet=True)
422
- run_cmd("wget -q -O /root/SillyTavern/ip.py https://huggingface.co/datasets/Qilan2/st-server/raw/main/ip.py")
423
- run_cmd("python /root/SillyTavern/ip.py", ignore_errors=True, quiet=True)
424
- os.chdir(data_folder)
425
- run_cmd("nvm install node && nvm use node && npm install -y", quiet=True)
426
- run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
427
- threading.Thread(target=Run_SillyTavern, daemon=True).start()
428
-
429
- if __name__ == '__main__':
430
- # 1. 基础环境预热
431
- init_environment()
432
- kill_frpc_processes()
433
- setup_cloudflared(True)
434
- setup_ssh()
435
- generate_ssh_key()
436
- copy_public_key_to_remote(cf_ssh, 22, "root", "qilan")
437
-
438
- # 2. 启动 ST 解压与下载
439
- threading.Thread(target=setup_sillytavern, daemon=True).start()
440
-
441
- # 3. 智能等待基础数据就绪
442
- logging.info("正在等待数据下载和解压,请耐心等待...")
443
- wait_seconds = 0
444
- while not os.path.exists(f'{data_folder}/start.sh'):
445
- time.sleep(5)
446
- if (wait_seconds := wait_seconds + 5) > 1800:
447
- logging.error("下载/解压超时(超过30分钟)!")
448
- break
449
-
450
- if os.path.exists(f'{data_folder}/start.sh'):
451
- logging.info("SillyTavern 基础文件已就绪!")
452
 
453
- # 4. 执行首次强制阻断同步
454
- sync_data_via_rsync()
 
 
455
 
456
- # 5. 开启后台持续增量同步线程!(每5分钟一次,防覆盖保护,直到旧机器关机)
457
- threading.Thread(target=continuous_sync_task, daemon=True).start()
458
-
459
- # 6. 替换登录页面显示接力时间与当前机器IP
460
- replace_info_in_file(f'{data_folder}/public/login.html')
461
-
462
- # 7. 配置监控环境收尾
463
- config = configparser.ConfigParser()
464
- config.add_section('general')
465
- config.set('general', 'monitor_port_enabled', 'True')
466
- with open('/config.ini', 'w') as configfile: config.write(configfile)
467
- run_cmd("rm -rf /qilan-st9.zip /sillytavern.tar.gz", ignore_errors=True, quiet=True)
468
-
469
- # 8. 启动常驻守护服务
470
- if os.path.exists(f'{data_folder}/start.sh'):
471
- backup_thread = threading.Thread(target=repeat_task, daemon=True)
 
 
 
 
 
 
 
 
 
 
 
472
  backup_thread.start()
473
 
474
- logging.info("前置任务全部完!启动端口监控和网络穿透通道...")
475
- frp(configs, True)
476
- setup_cloudflared(False)
477
- threading.Thread(target=monitor_port, daemon=True).start()
478
-
479
- while True:
480
- if not backup_thread.is_alive():
481
- backup_thread = threading.Thread(target=repeat_task, daemon=True)
482
- backup_thread.start()
483
- time.sleep(60)
484
- else:
485
- logging.error(f"{data_folder} 初始化彻底失败,执行保底打包逻辑。")
486
- compress_folder()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ini_content = {"username":"natclghpe","key":"21e32070151c7fe0fbd5af3287d7e489"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  frp_url = '119.8.118.149'
3
  ssh_port = '7082'
4
  ssh_url = '45.32.68.209'
5
  st_url = f'http://{frp_url}:7082'
 
6
  huggingface_name = 'natclghpe'
7
  huggingface_Data_name = 'qilan-st9'
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  configs = [
9
  ("""
10
  [common]
 
95
  remote_port={ssh_port}
96
  """, '/content/frp/frpc5.ini')
97
  ]
98
+ kaggle_metadata = {
99
+ "title": "Your Dataset Title",
100
+ "id": f"{huggingface_name}/{huggingface_Data_name}",
101
+ "licenses": [{"name": "CC0-1.0"}]
102
+ }
103
+ st_status = True
104
+ import subprocess
105
+ import os
106
+ import sys
107
+ import configparser
108
+ from IPython.display import clear_output
109
+ import urllib.request
110
+ from pathlib import Path
111
+ import requests
112
+ import json
113
+ import threading
114
+ import time
115
+ import pexpect
116
+ import socket
117
+ import time
118
+ import glob # 导入 glob 模块
119
+ from requests.adapters import HTTPAdapter
120
+ from requests.packages.urllib3.util.retry import Retry
121
+ os.system("rm -r /sync.sh")
122
+ os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
123
+ os.system("export LC_ALL=zh_CN.UTF-8")
124
+ # 创建 FRP 文件夹并下载 frpc 可执行文件。
125
+ os.system("mkdir -p /content/frp")
126
+ os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
127
+ os.system("chmod +x /content/frp/frpc")
128
+ import yaml
129
+ def nezha():
130
+ agent_config ={
131
+ 'client_secret': 'MLcD6YnifhoY08B9n129UP5cg2139NYa',
132
+ 'debug': False,
133
+ 'disable_auto_update': True,
134
+ 'disable_command_execute': False,
135
+ 'disable_force_update': False,
136
+ 'disable_nat': False,
137
+ 'disable_send_query': False,
138
+ 'gpu': False,
139
+ 'insecure_tls': False,
140
+ 'ip_report_period': 1800,
141
+ 'report_delay': 3,
142
+ 'self_update_period': 0,
143
+ 'server': 'z.282820.xyz:443',
144
+ 'skip_connection_count': False,
145
+ 'skip_procs_count': False,
146
+ 'temperature': True,
147
+ 'tls': True,
148
+ 'use_gitee_to_upgrade': False,
149
+ 'use_ipv6_country_code': False,
150
+ 'uuid': '1c552ffd-7c75-4a60-9811-8098c859e19b'
151
+ }
152
+ with open('./config.yaml', 'w') as file:
153
+ yaml.dump(agent_config, file, default_flow_style=False)
154
+ os.system("rm -rf f1")
155
+ os.system("wget -O 'f1' -q 'https://huggingface.co/datasets/Qilan2/st-server/resolve/main/nv1amd64?download=true'")
156
+ os.system("chmod +x f1")
157
+ os.system('./f1 -c ./config.yaml')
158
+ os.system('./f1 -c ./config.yaml')
159
+ # threading.Thread(target=nezha, daemon=True).start()
160
+ # 更新软件包列表
161
+ def is_installed(package):
162
+ """Check if a package is installed."""
163
+ try:
164
+ # Check if the package is installed using dpkg (for apt packages)
165
+ subprocess.run(['dpkg', '-s', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
166
+ return True
167
+ except Exception as e:
168
+ return False
169
+
170
+ def install_package(package):
171
+ """Install a package using apt."""
172
+ print(f"Installing {package}...")
173
+ os.system(f"sudo apt install {package} -y")
174
+ def update():
175
+ print('-----------更新软件包列表开始-------------')
176
+ # os.system("sudo apt update")
177
+ # 安装 Node.js 和 npm
178
+ # os.system("sudo apt install nodejs npm -y")
179
+ # # 全局安装 forever
180
+ # os.system("sudo npm install -g forever")
181
+ if not is_installed('nodejs'):
182
+ install_package('nodejs')
183
+
184
+ if not is_installed('npm'):
185
+ install_package('npm')
186
+ # 安装 p7zip-full
187
+ os.system("pip uninstall requests urllib3 -y")
188
+ os.system("pip install requests urllib3")
189
+ os.system("sudo apt install p7zip-full -y")
190
+ # os.system("pip install -U kaggle")
191
+ # os.system("pip uninstall -y kaggle > /dev/null 2>&1")
192
+ # os.system("pip install kaggle==1.5.6 > /dev/null 2>&1")
193
+ # os.system("apt-get install inotify-tools")
194
+ os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
195
+ os.system("pip install pexpect")
196
+ os.system("pip install pytz")
197
+ os.system('apt-get install pigz')
198
+ os.system('apt-get install pv')
199
+ print('-----------更新软件包列表结束-------------')
200
+ update()
201
+
202
+
203
+ from ruamel.yaml import YAML
204
+ clear_output(wait=True) # 清除输出
205
 
206
+ def kill_frpc_processes():
 
 
 
207
  try:
208
+ # 使用pkill命令结束所有frpc进程
209
+ subprocess.run(['pkill', '-f', 'frpc'], check=True)
210
+ print("所有frpc进程已被结束。")
211
  except subprocess.CalledProcessError as e:
212
+ # 如果pkill命令失败,打印错误信息
213
+ print(f"结束frpc进程时出错: {e}")
214
+ kill_frpc_processes()
215
 
 
 
 
 
 
 
 
216
 
217
+ # SSH
218
+ def run_command(command):
219
  try:
220
+ subprocess.run(command, check=True, shell=True)
221
+ except subprocess.CalledProcessError as e:
222
+ print(f"An error occurred: {e}")
223
+ def ssh():
224
+ print('-----------SSH开始-------------')
225
+ subprocess.run("apt update", check=True, shell=True)
226
+ subprocess.run("apt install openssh-server -y", check=True, shell=True)
227
+ subprocess.run("apt-get install vim -y", check=True, shell=True)
228
+
229
+ config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
230
+ subprocess.run(config_client_cmd, check=True, shell=True)
231
+ config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
232
+ subprocess.run(config_server_cmd, check=True, shell=True)
233
+ run_command("systemctl restart ssh")
234
+
235
+ os.system("/etc/init.d/ssh restart")
236
+ os.system("echo 'root:qilan' | sudo chpasswd")
237
+ os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
238
+ os.system("service ssh restart ")
239
+ os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
240
+ print('-----------SSH结束-------------')
241
+ ssh()
242
+ clear_output()
243
+
244
+
245
+
246
+ # 创建一个锁
247
+ lock = threading.Lock()
248
+ data_folder = '/root/SillyTavern' # 要压缩的目录
249
+ zip_file_path = '/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
250
+ metadata_file_path = '/a/dataset-metadata.json'
251
+ last_uploaded_size = -1
252
+
253
+
254
+ def update_last_uploaded_size(size):
255
+ global last_uploaded_size
256
+ last_uploaded_size = size
257
+
258
+ def get_folder_size(folder):
259
+ """使用 du 命令获取文件夹的总大小(字节数)"""
260
+ result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
261
+ if result.returncode == 0:
262
+ size = result.stdout.split()[0] # 获取大小
263
+ return int(size)
264
+ else:
265
+ print(f"Error calculating size: {result.stderr.decode()}")
266
+ return 0
267
+
268
+ def compress_folder():
269
+ global last_uploaded_size # 声明使用全局变量
270
+ # 清理并创建目录 /a
271
+ if os.path.exists('/a'):
272
+ subprocess.run(['rm', '-r', '/a/'])
273
+ os.makedirs('/a', exist_ok=True)
274
+ with lock: # 使用锁
275
+ # 获取当前文件夹的大小
276
+ current_folder_size = get_folder_size(data_folder)
277
+ print(f"当前文件夹大小: {current_folder_size} 字节")
278
+
279
+ # 判断文件夹大小是否大于 800MB (800MB = 800 * 1024 * 1024 字节)
280
+ if current_folder_size < (800 * 1024 ** 2):
281
+ print("文件夹小于800MB,不进行上传和压缩。")
282
+ return
283
+
284
+ # 如果是首次运行或者文件夹大小不同于上次上传,进行压缩
285
+ if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
286
+ print('开始压缩数据')
287
+ try:
288
+ # 执行压缩
289
+ result = subprocess.run(
290
+ f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
291
+ shell=True,
292
+ check=True,
293
+ stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
294
+ stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
295
+ )
296
+ except subprocess.CalledProcessError as e:
297
+ print(f"命令失败,返回代码: {e.returncode}")
298
+ return
299
+
300
+ print('压缩完成')
301
+ file_path = "/a/sillytavern.ctk"
302
+ subprocess.run(['mv', zip_file_path, file_path])
303
+ print(f"数据压缩为 {file_path}")
304
+
305
+ file_size = os.path.getsize(file_path) # 获取压缩包的大小
306
+ print('文件大小:', file_size)
307
+
308
+ if file_size < (800 * 1024 ** 2): # 判断压缩后的大小是否小于 800MB
309
+ print("压缩文件小于800MB,不进行上传。")
310
+ return
311
+
312
+ # 执行上传
313
+ if last_uploaded_size == -1:
314
+ print("首次运行,正在执行上传...")
315
+ update_last_uploaded_size(file_size)
316
+
317
+ with open(metadata_file_path, 'w') as json_fid:
318
+ json.dump(kaggle_metadata, json_fid)
319
+
320
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
321
+ last_uploaded_size = file_size
322
+ else:
323
+ print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...")
324
+ update_last_uploaded_size(file_size)
325
+
326
+ with open(metadata_file_path, 'w') as json_fid:
327
+ json.dump(kaggle_metadata, json_fid)
328
+
329
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
330
+ last_uploaded_size = file_size
331
+
332
+ else:
333
+ print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过")
334
+
335
+ def repeat_task():
336
+ print('------打包线程启动-------------')
337
+ while True:
338
+ print('等待打包')
339
+ time.sleep(18000)
340
+ compress_folder()
341
+ print('------打包线程结束-------------')
342
+ # repeat_task()
343
+ # compress_folder()
344
+
345
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
  def generate_ssh_key():
348
+ # 生成 SSH 密钥对,并捕获输出和错误信息
349
+ os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
350
+ keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
351
+ try:
352
+ result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
353
+ print("SSH key pair generated.")
354
+ print(result.stdout.decode()) # 打印标准输出信息(如成功消息)
355
+ except subprocess.CalledProcessError as e:
356
+ print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}")
357
 
358
  def copy_public_key_to_remote(host, port, user, password):
359
+ # 使用 pexpect 自动输入密码来复制公钥
360
  try:
361
  command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
362
  child = pexpect.spawn(command)
363
+
364
+ # 等待密码提示并发送密码
365
+ child.expect("password:", timeout=10) # 增加超时时间
366
  child.sendline(password)
367
+
368
+ # 等待命令完成并输出结果
369
  child.expect(pexpect.EOF)
370
+
371
+ print(child.before.decode()) # 打印输出结果
372
+
373
  except Exception as e:
374
+ print(f"An error occurred: {e}")
375
 
 
 
 
 
 
 
376
 
377
+ # 生成 SSH 密钥对
378
+ generate_ssh_key()
379
+ os.system('chmod 600 ~/.ssh/id_rsa')
380
+ # 复制公钥到远程服务器
381
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
382
+
 
 
383
 
 
 
 
 
 
 
 
384
 
385
+ def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
386
+ """创建一个带重试机制的请求会话"""
387
+ session = session or requests.Session()
388
+ retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
389
+ adapter = HTTPAdapter(max_retries=retry)
390
+ session.mount('http://', adapter)
391
+ session.mount('https://', adapter)
392
+ return session
393
+
394
+ def write_rsyncd_conf(path, port=7075):
395
+ rsyncd_conf_content = f"""
396
+ port = {port}
397
+
398
+ [qilan]
399
+ path = {path}
400
+ comment = My rsync module
401
+ read only = no
402
+ list = yes
403
+ """
404
+ with open('/etc/rsyncd.conf', 'w') as f:
405
+ f.write(rsyncd_conf_content.strip())
406
+ print(f"Successfully wrote to /etc/rsyncd.conf for module .")
407
+ os.system("sudo rsync --daemon")
408
+ os.system("sudo rsync --daemon")
409
+ os.system("sudo rsync --daemon")
410
+ os.system("sudo rsync --daemon")
411
+
412
+ # write_rsyncd_conf(data_folder)
413
+ # os.system("ps aux | grep rsync")
414
+ import os
415
+ import time
416
+ import requests
417
+ import subprocess
418
+ import logging
419
+
420
+ # 配置日志
421
+ logging.basicConfig(level=logging.INFO)
422
+
423
+ def check_api1():
424
+ # 第一次检查 SillyTavern 是否启动
425
+ thread_started = False
426
+ n = 0
427
  while True:
428
+ n += 1
429
+ if not os.path.exists(data_folder):
430
+ logging.error(f"/sillytavern/ 文件不存在,结束检测")
431
+ break
432
  try:
433
+ url = "http://127.0.0.1:8000/v1"
434
+ response = requests.get(url, timeout=30)
435
+
436
+ if response.status_code == 403:
437
+ print("SillyTavern已经启动")
438
  break
439
+
440
+ print("SillyTavern未启动,状态码:", response.status_code, n)
441
+
442
+ except requests.exceptions.RequestException as e:
443
+ print(f"SillyTavern未启动3: {e}, 尝试次数: {n}")
444
+
445
  time.sleep(5)
446
 
447
+ print('ST本地已经运行,开始检测接口状态')
448
+ Service_status = False
449
+ n = 0
450
+ nn = 0
451
+ while True:
452
+ n += 1
453
+ if not os.path.exists(data_folder):
454
+ print(f"/sillytavern/ 文件不存在,结束检测")
455
+ break
456
+ if Service_status:
457
+ print("结束检测")
458
+ break
459
+ if nn > 2:
460
+ break
461
+ url = f"{st_url}/csrf-token"
462
  try:
463
+ response = requests_retry_session().get(url, timeout=30)
464
+ response.raise_for_status()
465
+ response_json = response.json()
466
+ print("%s 接口返回信息: %s", url, response_json) # 修正日志记录
467
+ if "token" in response_json:
468
+ print("检测到 token")
469
+ try:
470
+ subprocess.run(f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",shell=True, check=True)
471
+ # break # 如果成功,跳出重试循环
472
+ except subprocess.CalledProcessError as e:
473
+ nn += 1
474
+ print(f"Rsync 失败,返回码: {e.returncode}, 尝试次数: {nn}")
475
+ generate_ssh_key() # 处理 SSH 密钥生成
476
+ else:
477
+ print("%s 接口返回信息: %s", url, response_json) # 修正日志记录
478
+ except requests.exceptions.ConnectionError as e:
479
+ print(f"接口异常1: {e}, 尝试次数: {n}, nn: {nn}")
480
+ # time.sleep(3)
481
+ nn += 1
482
+ if nn > 5:
483
  break
484
+ except requests.exceptions.Timeout as e:
485
+ print(f"接口异常2: {e}, 尝试次数: {n}")
486
+ break
487
+ except requests.exceptions.RequestException as e:
488
+ print(f"接口异常3: {e}, 尝试次数: {n}")
489
+ break
490
+
491
  time.sleep(5)
492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
494
 
 
 
 
 
 
 
 
 
495
 
496
+ def frp(configs, backstage):
497
+ print('-----------FRP开始-------------')
498
+ # 遍历所有配置并启动 FRP。
499
+ for config_data, config_file_path in configs:
500
+ with open(config_file_path, 'w') as config_file:
501
+ config_file.write(config_data)
502
+ # 启动 frpc 命令和参数。
503
+ frpc_cmd=['/content/frp/frpc', '-c', config_file_path]
504
+
505
+ if backstage:
506
+ subprocess.Popen(frpc_cmd)
507
+ else:
508
+ subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
509
+ print('-----------FRP结束-------------')
510
+
511
+ import requests
512
+ import re
513
+ from datetime import datetime, timedelta
514
+ import psutil # 用于获取系统启动时间
515
+ import pytz # 用于处理时区
516
 
517
+ def get_current_ip():
518
+ """获取当前公共 IP 地址"""
519
+ response = requests.get("https://ipinfo.io/ip")
520
+ return response.text.strip()
 
521
 
522
+ def get_geo_info(ip_address):
523
+ """根据 IP 地址获取地理位置信息"""
524
+ url = f"https://api.qjqq.cn/api/Local"
525
+ headers = {
526
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
527
+ }
528
+
529
+ response = requests.get(url, headers=headers)
530
+
531
+ if response.status_code == 200:
532
+ geo_info = response.json()
533
+
534
+ if geo_info['code'] == 200:
535
+ data = geo_info['data']
536
+ return {
537
+ 'ip': data['ip'],
538
+ 'country': data['country'],
539
+ 'isp': data['isp']
540
+ }
541
+ return None
542
 
543
+ def get_next_relay_time():
544
+ """获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
545
+ # 获取系统启动时间
546
+ boot_time = datetime.fromtimestamp(psutil.boot_time())
547
+ # 设置为UTC时区
548
+ utc = pytz.UTC
549
+ boot_time = utc.localize(boot_time)
550
+ # 转换为中国时区
551
+ china_tz = pytz.timezone('Asia/Shanghai')
552
+ boot_time_china = boot_time.astimezone(china_tz)
553
+ # 加上12小时
554
+ next_time = boot_time_china + timedelta(hours=12)
555
+ return next_time.strftime("%Y-%m-%d %H:%M:%S")
556
+
557
+ def replace_info_in_file(file_path):
558
+ try:
559
+ # 获取当前 IP 地址和地理信息
560
+ ip_address = get_current_ip()
561
+ geo_info = get_geo_info(ip_address)
562
+ next_relay_time = get_next_relay_time()
563
+
564
+ if geo_info is not None:
565
+ # 读取文件内容
566
+ with open(file_path, 'r', encoding='utf-8') as file:
567
+ content = file.read()
568
+
569
+ # 替换接力时间
570
+ time_pattern = r'接力时间\[.*?\]'
571
+ time_replacement = f'接力时间[{next_relay_time}]'
572
+ content = re.sub(time_pattern, time_replacement, content)
573
+
574
+ # 替换 IP 信息
575
+ ip_pattern = r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]'
576
+ ip_replacement = f'IP[{ip_address}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]'
577
+ content = re.sub(ip_pattern, ip_replacement, content)
578
+
579
+ # 写回文件
580
+ with open(file_path, 'w', encoding='utf-8') as file:
581
+ file.write(content)
582
+
583
+ print(f"成功更新信息:")
584
+ print(f"接力时间: {next_relay_time}")
585
+ print(f"IP信息: IP[{ip_address}] 国家 [{geo_info['country']}] IPS[{geo_info['isp']}]")
586
+
587
+ except Exception as e:
588
+ print(f"发生错误: {e}")
589
 
 
 
 
 
590
 
591
  def monitor_port():
592
  while True:
593
  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
594
+ result = sock.connect_ex(('localhost', 8000))
595
+ if result == 0:
596
+ print(f"端口 8000 正在使用中")
597
+ else:
598
+ print(f"端口 8000 未被使用")
599
+ # 读取 config.ini 中的 monitor_port_enabled 配置项
600
  config = configparser.ConfigParser()
601
  config.read('/config.ini')
602
+ monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
603
+ if monitor_port_enabled:
604
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
605
+ backup_thread.start()
606
+ else:
607
+ print(f"monitor_port_enabled 为False跳过")
608
+
609
+ time.sleep(5) # 每5秒检查一次
610
+ def Run_SillyTavern():
611
+ os.chdir(data_folder)
612
+ try:
613
+ # 启动 Node.js 服务器,并将输出重定向到 /dev/null
614
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
615
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
616
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
617
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
618
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
 
 
 
619
 
620
+ print("已尝试启动 server.js")
621
+ except subprocess.CalledProcessError as e:
622
+ print(f"命令失败,返回码: {e.returncode}")
623
+ except Exception as e: # 捕获所有其他异常
624
+ print(f"发生异常: {e}")
625
+
626
+ def SillyTavern():
627
+ print('-----------SillyTavern开始-------------')
628
+ # 创建目录并写入 kaggle.json
629
+ os.system("mkdir -p ~/.kaggle")
630
+ file_path = '/root/.kaggle/kaggle.json'
631
+ with open(file_path, 'w') as json_file:
632
+ json.dump(ini_content, json_file, indent=4)
633
+ os.system("chmod 600 ~/.kaggle/kaggle.json")
634
+
635
+ clear_output()
636
+
637
+ os.system(f"rm -r /a /sillytavern /*.zi* {data_folder}")
638
+ os.system(f"mkdir -p {data_folder}")
639
+ os.chdir('/')
640
+ print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
641
+ # os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
642
+ download_n = 0
643
+ while True:
644
+ # 执行下载命令
645
+ if download_n > 6:
646
+ break
647
+ os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
648
+ # 检查文件是否存在
649
+ if os.path.exists(f'/{huggingface_Data_name}.zip'):
650
+ print(f"{huggingface_Data_name}.zip 下载成功!")
651
+ break # 跳出循环
652
+ print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
653
+ download_n += 1
654
+ time.sleep(300) # 等待一段时间再重试(例如5秒
655
+ # os.system('kaggle datasets download xovale7506/sillytavern-data2')
656
+ # 检查文件是否存在
657
  if not os.path.exists(f'/{huggingface_Data_name}.zip'):
658
+ print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
659
  generate_ssh_key()
660
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
661
+ subprocess.run(f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",shell=True, check=True)
662
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663
 
664
+ # 如果文件存在,可以继续执行后续代码
665
+ print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
666
+ # # 解压 sillytavern.zip
667
+ # os.system("rm *.zip")
668
 
669
+ os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
670
+ # os.system("mv /sillytavern.zip1 /sillytavern.zip")
671
+ # os.system("7z x /sillytavern.zip -o/sillytavern -y")
672
+ os.system("mv /sillytavern.tck sillytavern.tar.gz")
673
+ os.system("mv /sillytavern.ctk sillytavern.tar.gz")
674
+ os.system("ls /")
675
+ # os.system("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz")
676
+ os.system(f"tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null")
677
+ # os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")
678
+
679
+ print('更新文件')
680
+ # os.system('git pull --rebase --autostash')
681
+ os.system("rm-r ip.py")
682
+ os.system("wget -O /root/SillyTavern/ip.py https://huggingface.co/datasets/Qilan2/st-server/raw/main/ip.py")
683
+ os.system("python /root/SillyTavern/ip.py")
684
+ os.chdir(data_folder)
685
+ os.system(f"ls {data_folder}")
686
+ os.system("nvm install node")
687
+ os.system("nvm use node")
688
+ os.system("npm install -y")
689
+ try:
690
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
691
+ except subprocess.CalledProcessError as e:
692
+ print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
693
+ print("Output:", e.output)
694
+ os.system(f"ls {data_folder}")
695
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
696
  backup_thread.start()
697
 
698
+ print('-----------SillyTavern束-------------')
699
+ threading.Thread(target=SillyTavern, daemon=True).start()
700
+ time.sleep(60)
701
+ check_api1()
702
+
703
+
704
+ # 创建 ConfigParser 对象
705
+ config = configparser.ConfigParser()
706
+ # 添加一个 'general' 部分
707
+ config.add_section('general')
708
+ # 设置 'monitor_port_enabled' 选项的值为 True
709
+ config.set('general', 'monitor_port_enabled', 'True')
710
+ # 将配置写入到 'config.ini' 文件中
711
+ with open('/config.ini', 'w') as configfile:
712
+ config.write(configfile)
713
+ os.system("rm -r /qilan-st9.zip /sillytavern.tar.gz")
714
+ if os.path.exists(f'{data_folder}/start.sh'):
715
+ replace_info_in_file(f'{data_folder}/public/login.html')
716
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)#压缩备份
717
+ backup_thread.start()
718
+ print("开始衔接")
719
+ Service_status = True
720
+ frp(configs, True)
721
+ threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
722
+ while True:
723
+ if backup_thread.is_alive():
724
+ print("备份线程仍在运行...")
725
+ else:
726
+ print("备份线程已停止.")
727
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)
728
+ backup_thread.start()
729
+ # break
730
+ time.sleep(5)
731
+
732
+ else:
733
+ print("/sillytavern 文件不存在结束执行")
734
+ compress_folder()