File size: 22,432 Bytes
930d2bf
 
8825dde
 
b0b482b
98513b1
b0b482b
930d2bf
 
 
 
 
9cbeea0
930d2bf
 
 
a473ccc
9cbeea0
930d2bf
 
 
 
9cbeea0
930d2bf
 
 
8825dde
930d2bf
 
 
 
 
0900021
bcf13ad
930d2bf
 
58afb3f
 
930d2bf
 
 
 
3d4bd9d
930d2bf
 
d2a4f08
930d2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
7e3f559
 
930d2bf
 
 
 
d2a4f08
930d2bf
 
 
 
 
 
 
d2a4f08
930d2bf
 
d2a4f08
 
930d2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2a4f08
 
 
 
930d2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acdee80
d2a4f08
 
 
 
 
 
930d2bf
d2a4f08
930d2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
772d8f9
930d2bf
 
 
 
 
 
 
 
 
acdee80
930d2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f20e72c
 
930d2bf
 
 
 
 
 
 
 
 
 
 
3bde292
930d2bf
 
3bde292
930d2bf
 
 
 
 
 
 
 
 
f20e72c
 
930d2bf
 
 
 
 
 
c32c5f8
 
 
 
 
930d2bf
 
a8ee64c
 
 
9786f72
a8ee64c
9786f72
5424b4d
 
930d2bf
 
 
3bde292
930d2bf
 
 
 
3bde292
930d2bf
 
 
 
3bde292
930d2bf
 
 
ca70817
930d2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0ba73a
815c82b
930d2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fc2689
883a41c
4fc2689
883a41c
4fc2689
 
 
 
 
3548df1
4fc2689
3548df1
883a41c
 
 
 
 
 
 
 
 
 
930d2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
c3e1066
98513b1
 
 
d2a4f08
98513b1
 
9923449
98513b1
 
d2a4f08
98513b1
 
0ea49c1
930d2bf
b0b482b
3035814
caa39b5
d2a4f08
3035814
 
adf50fc
 
 
b0b482b
930d2bf
d2a4f08
 
b0b482b
d2a4f08
 
 
 
 
 
adf50fc
 
d2a4f08
 
adf50fc
 
 
 
d2a4f08
adf50fc
 
 
d2a4f08
 
 
 
 
 
 
caa39b5
930d2bf
e462a63
930d2bf
8825dde
d2a4f08
7f4cac6
1977348
 
 
930d2bf
 
9cbeea0
2ce8608
d2a4f08
 
 
 
 
4fc2689
930d2bf
1977348
 
 
 
 
 
 
930d2bf
 
 
d8ec4d8
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
ini_content = {"username":"xovale7506","key":"502e30bafc004c02aa668a279df23f3e"}
frp_url = '47.237.156.222'
ssh_port = '7074'
st_url = f'http://{frp_url}:7073'
huggingface_name = 'xovale7506'
huggingface_Data_name = 'sillytavern2-data'

config_data = f"""
[common]
server_addr = {frp_url}
server_port = 7000

[safghass434]
type = tcp
local_ip = 127.0.0.1
local_port = 8000
remote_port = 7073
[safabssf545]
type = tcp
local_ip = 127.0.0.1
local_port = 22
remote_port = {ssh_port}
[ssafffg565]
type = tcp
local_ip = 127.0.0.1
local_port = 3000
remote_port = 7076
"""
config_data2 = """
[common]
server_addr = 8.137.94.137
server_port = 7000

[kjashdsh0144]
type = tcp
local_ip = 127.0.0.1
local_port = 8000
remote_port = 7073
"""

kaggle_metadata = {
    "title": "Your Dataset Title",
    "id": f"{huggingface_name}/{huggingface_Data_name}",
    "licenses": [{"name": "CC0-1.0"}]
}
st_status = True
import subprocess
import os
import sys
from IPython.display import clear_output
import urllib.request
from pathlib import Path
import requests
import json
import threading
import time
import pexpect
import glob  # 导入 glob 模块
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
os.system("rm -r /sync.sh")
os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
os.system("export LC_ALL=zh_CN.UTF-8")
# 更新软件包列表
def update():
    print('-----------更新软件包列表开始-------------')
    # os.system("sudo apt update")
    # 安装 Node.js 和 npm
    os.system("sudo apt install nodejs npm -y")
    # 全局安装 forever
    os.system("sudo npm install -g forever")
    # 安装 p7zip-full
    os.system("sudo apt install p7zip-full -y")
    os.system("pip install -U kaggle")
    # os.system("apt-get install inotify-tools")
    os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
    os.system("pip install pexpect")
    os.system('apt-get install pigz')
    os.system('apt-get install pv')
    print('-----------更新软件包列表结束-------------')
update()
from ruamel.yaml import YAML
clear_output(wait=True)  # 清除输出

def kill_frpc_processes():
    try:
        # 使用pkill命令结束所有frpc进程
        subprocess.run(['pkill', '-f', 'frpc'], check=True)
        print("所有frpc进程已被结束。")
    except subprocess.CalledProcessError as e:
        # 如果pkill命令失败,打印错误信息
        print(f"结束frpc进程时出错: {e}")
kill_frpc_processes()


# Oneapi中转
def Oneapi():
    print('-----------Oneapi中转开始-------------')
    # 删除旧的 one-api 文件夹(如果存在)
    os.system("rm -rf /one/one-api")  # 使用 -f 参数以避免错误
    os.system("mkdir -p /one")  # 创建目录
    # 下载 one-api 文件
    url = "https://github.com/songquanpeng/one-api/releases/download/v0.6.8/one-api"
    os.system(f"wget {url} -O /one/one-api")  # 正确下载并重命名为 /one/one-api
    # 修改文件权限,使其可执行
    os.system("chmod +x /one/one-api")
    # 设置环境变量
    os.environ["THEME"] = "berry"
    os.environ["TIKTOKEN_CACHE_DIR"] = os.getcwd()  # 使用Python的os.getcwd()获取当前工作目录
    # 设置MySQL数据库的环境变量
    db_user = "oneapi"
    db_password = "epBjK5ZKysCe6yr3"
    db_host = "106.52.51.116"
    db_port = "3306"
    db_name = "oneapi"
    dsn = f"{db_user}:{db_password}@tcp({db_host}:{db_port})/{db_name}"
    os.environ["SQL_DSN"] = dsn
    command = ['/one/one-api', '--port', '3000']
    process = subprocess.Popen(command)  # 启动程序并将其放到后台执行
    print(f"OneAPI程序已在后台启动,进程ID为:{process.pid}")
    print('-----------Oneapi中转结束-------------')
# Oneapi()

# SSH
def run_command(command):
    try:
        subprocess.run(command, check=True, shell=True)
    except subprocess.CalledProcessError as e:
        print(f"An error occurred: {e}")
def ssh():
    print('-----------SSH开始-------------')
    subprocess.run("apt update", check=True, shell=True)
    subprocess.run("apt install openssh-server -y", check=True, shell=True)
    subprocess.run("apt-get install vim -y", check=True, shell=True)
    
    config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
    subprocess.run(config_client_cmd, check=True, shell=True)
    config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
    subprocess.run(config_server_cmd, check=True, shell=True)
    run_command("systemctl restart ssh")

    os.system("/etc/init.d/ssh restart")
    os.system("echo 'root:qilan' | sudo chpasswd")
    os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
    os.system("service ssh restart ")
    os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
    print('-----------SSH结束-------------')
ssh()
clear_output()

import json
import os
import subprocess
import threading
import time

# 创建一个锁
lock = threading.Lock()
# data_folder = '/sillytavern/*'
# zip_file_path = '/a/sillytavern.zip'
data_folder = '/root//SillyTavern'  # 要压缩的目录
zip_file_path = '/a/sillytavern.tar.gz'  # 输出的 tar.gz 文件路径
metadata_file_path = '/a/dataset-metadata.json'
last_uploaded_size = -1

def update_last_uploaded_size(size):
    global last_uploaded_size
    last_uploaded_size = size

def compress_folder():
    global last_uploaded_size  # 声明使用全局变量

    # 清理并创建目录 /a
    if os.path.exists('/a'):
        subprocess.run(['rm', '-r', '/a'])

    os.makedirs('/a', exist_ok=True)

    with lock:  # 使用锁
        if os.path.exists(zip_file_path):
            print(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩。")
            return
        
        print('开始压缩数据')
        result = subprocess.run(['7z', 'a', '-tzip', '-mx=1','-mmt=2', zip_file_path, data_folder])
        # 7z a -tzip -mx=1 -mmt=2 /a/sillytavern.zip /sillytavern/*
        # tar -cvf - /sillytavern | pigz -p 6 -1 > /a/sillytavern.tar.gz
        result = subprocess.run(
                f'tar -cvf - {data_folder} | pigz -p 6 -1 > {zip_file_path}',
                shell=True,
                check=True
        )
        print('重命名压缩后的文件')
        file_path = "/a/sillytavern.ctk"
        subprocess.run(['mv', zip_file_path,file_path])
        if result.returncode != 0:
            print("压缩失败,请检查7z命令是否正确")
            return
        
        print(f"Data compressed into {file_path}")
        
        file_size = os.path.getsize(file_path)  # 获取压缩包的大小
        print('文件大小:', file_size, '上次文件大小:', last_uploaded_size,file_size * 1024 ** 2)
        
        # 判断是否大于800MB (800MB = 800 * 1024 * 1024 字节)
        if file_size < (800 * 1024 ** 2):  
            print("文件小于800MB,不进行上传。")
            return
        
        if last_uploaded_size == -1 or file_size != last_uploaded_size:
            # 判断是否为首次运行或上次上传大小为0
            if last_uploaded_size == -1:
                print("首次运行,正在执行上传...")
                update_last_uploaded_size(file_size)  # 更新为当前文件大小

                with open(metadata_file_path, 'w') as json_fid:
                    json.dump(kaggle_metadata, json_fid)

                subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
                # kaggle datasets version -m 'new version message' -p /a
                last_uploaded_size = file_size
            
            elif file_size > last_uploaded_size:
                print(f"新文件 {zip_file_path} 大于上次上传的大小,正在执行上传...")
                update_last_uploaded_size(file_size)  # 更新元数据中的最后一次上传大小

                with open(metadata_file_path, 'w') as json_fid:
                    json.dump(kaggle_metadata, json_fid)

                subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
                last_uploaded_size = file_size
            
        else:
            print(f"新文件 {zip_file_path} 不大于上次上传的大小,跳过")


def repeat_task():
    print('------打包线程启动-------------')
    while True:
        print('等待打包')
        time.sleep(600)
        compress_folder()
    print('------打包线程结束-------------')
# repeat_task()
# compress_folder()

import os
import subprocess
import pexpect

def generate_ssh_key():
    # 生成 SSH 密钥对,并捕获输出和错误信息
    os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
    keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
    try:
        result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print("SSH key pair generated.")
        print(result.stdout.decode())   # 打印标准输出信息(如成功消息)
    except subprocess.CalledProcessError as e:
        print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}")

def copy_public_key_to_remote(host, port, user, password):
    # 使用 pexpect 自动输入密码来复制公钥
    try:
        command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
        child = pexpect.spawn(command)

        # 等待密码提示并发送密码
        child.expect("password:", timeout=10)  # 增加超时时间
        child.sendline(password)

        # 等待命令完成并输出结果
        child.expect(pexpect.EOF)
        
        print(child.before.decode())  # 打印输出结果
        
    except Exception as e:
        print(f"An error occurred: {e}")


# 生成 SSH 密钥对
generate_ssh_key()

# 复制公钥到远程服务器
copy_public_key_to_remote(frp_url, ssh_port, "root", "qilan")
 


def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
    """创建一个带重试机制的请求会话"""
    session = session or requests.Session()
    retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session

def check_api1():
    # 第一次检查 SillyTavern 是否启动
    thread_started = False  # 在函数内初始化标志变量
    n=0
    while True:
        n = n + 1
        if not os.path.exists('/sillytavern/'):
            print(f"/sillytavern/ 文件不存在,结束检测")
            break
        try:
            url = "http://127.0.0.1:8000/v1"
            response = requests.get(url, timeout=30)

            # 检查响应状态码
            if response.status_code == 403:
                print("SillyTavern已经启动")
                break  # 接口正常,退出循环
            
            # 如果不是 403,打印其他信息
            print("SillyTavern未启动,状态码:", response.status_code,n)

        except requests.exceptions.RequestException as e:
            print(f"SillyTavern未启动3: {e}",n)  # 打印具体错误信息
        
        time.sleep(5)  # 等待5秒后重试
    
    print('开始检测接口状态')
    Service_status = False
    # 第二次检查接口状态
    n = 0
    while True:
        n = n + 1
        if not os.path.exists('/sillytavern/'):#
            print(f"/sillytavern/ 文件不存在,结束检测")
            break
        if Service_status:
            print("结束检测")
            break
        url = f"{st_url}/csrf-token"  # 确保这个 URL 是正确的   
        try:
            response = requests_retry_session().get(url, timeout=30)
            response.raise_for_status()  # 检查响应状态
            # 尝试解析 JSON 响应
            response_json = response.json()  # 获取 JSON 内容
            print(url,"接口返回信息:", response_json)
            if "token" in response_json:
                print("检测到 token")
                try:
                    subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{frp_url}:/sillytavern/ /sillytavern/", shell=True, check=True)
                except subprocess.CalledProcessError as e:
                    print(f"Rsync 失败,返回码: {e.returncode}")
                    print(f"Command output: {e.output}")
                    generate_ssh_key()
                # subprocess.run(f"bash /sync.sh -p {ssh_port} -s {frp_url}", shell=True, check=True)
                # break  # 跳出循环
            else:
                print("接口返回信息:", response_json)
        except requests.exceptions.ConnectionError as e:
            print(f"接口异常1: {e}",n)
            # threading.Thread(target=Frpc, daemon=True).start()
            break
        
        except requests.exceptions.Timeout as e:
            print(f"接口异常2: {e}",n)
            # threading.Thread(target=Frpc, daemon=True).start()
            break
            
        except requests.exceptions.RequestException as e:
           print(f"接口异常3: {e}",n)
           # threading.Thread(target=Frpc, daemon=True).start()
           break
        
        time.sleep(2)  # 等待5秒后重试


def frp(config_data1,config_file_path,backstage):
    print('-----------FRP开始-------------')
    '''FRP配置'''
    os.system("mkdir -p /content/frp")
    os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
    os.system("chmod +x /content/frp/frpc")
    # config_file_path = '/content/frp/frpc.ini'
    with open(config_file_path, 'w') as config_file:
        config_file.write(config_data1)
    # frpc 启动命令和参数
    frpc_cmd = ['/content/frp/frpc', '-c', config_file_path]
    if backstage:
        subprocess.Popen(frpc_cmd)
    else:
        subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
    print('-----------FPR结束-------------')
    # /content/frp/frpc -c /content/frp/frpc.ini
    
import requests
import re

def get_current_ip():
    """获取当前公共 IP 地址"""
    response = requests.get("https://ipinfo.io/ip")
    return response.text.strip()

def get_geo_info(ip_address):
    """根据 IP 地址获取地理位置信息"""
    url = f"https://api.qjqq.cn/api/Local"
    headers = {
        "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"
    }
    
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        geo_info = response.json()  # 解析为 JSON 格式
        
        if geo_info['code'] == 200:
            data = geo_info['data']
            return {
                'ip': data['ip'],
                'country': data['country'],
                'isp': data['isp']
            }
        else:
            print("无法获取地理位置信息")
            return None
    else:
        print(f"请求失败, 状态码: {response.status_code}")
        return None

def replace_ip_and_country_in_file(file_path):
    try:
        # 获取当前 IP 地址
        ip_address = get_current_ip()
        print(f"获取到当前 IP: {ip_address}")
        
        # 获取地理位置信息
        geo_info = get_geo_info(ip_address)
        
        if geo_info is not None:
            print(f"获取到地理信息: {geo_info}")
            
            # 读取文件内容
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()
                # print(f"读取到的文件内容: {content}")
            
            # 使用正则表达式匹配 "IP[xxx]国家[yyy]" 的格式
            pattern = r'IP\[.*?\]国家\[.*?\]ISP\[.*?\]'
            replacement = f'IP[{geo_info["ip"]}]国家[{geo_info["country"]}]ISP[{geo_info["isp"]}]'
            new_content = re.sub(pattern, replacement, content)
            
            # print(f"替换后的内容: {new_content}")
            
            # 将修改后的内容写回文件
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(new_content)
            
            print(f"成功更新为: IP[{geo_info['ip']}] 国家[{geo_info['country']}] ISP[{geo_info['isp']}]")
    
    except FileNotFoundError:
        print(f"错误: 文件 {file_path} 不存在。")
    except IOError as e:
        print(f"IO 错误: {e}")
    except Exception as e:
        print(f"发生其他错误: {e}")

import socket
import subprocess
import time

def monitor_port():
    while True:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            result = sock.connect_ex(('localhost', 8000))
            if result == 0:
                print(f"端口 8000 正在使用中")
            else:
                print(f"端口 8000 未被使用")
                # 启动脚本并在后台运行
                try:
                    process = subprocess.Popen('yes | sh /sillytavern/start.sh', shell=True)
                    print("已尝试启动 /sillytavern/start.sh")
                    time.sleep(20)
                except Exception as e:  # 捕获所有异常
                    print(f"命令失败: {e}")
        
        time.sleep(5)  # 每5秒检查一次

def SillyTavern():
    print('-----------SillyTavern开始-------------')
    # 创建目录并写入 kaggle.json
    os.system("mkdir -p ~/.kaggle")
    file_path = '/root/.kaggle/kaggle.json'
    with open(file_path, 'w') as json_file:
        json.dump(ini_content, json_file, indent=4)
    os.system("chmod 600 ~/.kaggle/kaggle.json")

    clear_output()

    os.system("rm -r /a /sillytavern /*.zi* /SillyTavern/")
    os.system("mkdir -p /sillytavern")
    os.chdir('/')
    print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
    # os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
    while True:
        # 执行下载命令
        os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
        # 检查文件是否存在
        if os.path.exists(f'/{huggingface_Data_name}.zip'):
            print(f"{huggingface_Data_name}.zip 下载成功!")
            break  # 跳出循环
    
        print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
    
        time.sleep(5)  # 等待一段时间再重试(例如5秒
    # os.system('kaggle datasets download xovale7506/sillytavern-data2')
    # 检查文件是否存在
    if not os.path.exists(f'/{huggingface_Data_name}.zip'):
        print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
        generate_ssh_key()
        copy_public_key_to_remote(frp_url, ssh_port, "root", "qilan")
        subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{frp_url}:/sillytavern/ /sillytavern/", shell=True, check=True)
        # sys.exit()
    else:
        
        # 如果文件存在,可以继续执行后续代码
        print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
    # # 解压 sillytavern.zip
        # os.system("rm *.zip")
        os.system("ls /")
        os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
        # os.system("mv /sillytavern.zip1 /sillytavern.zip")
        # os.system("7z x /sillytavern.zip -o/sillytavern -y")
        os.system("mv /sillytavern.ctk sillytavern.tar.gz")
        # os.system("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz")
        os.system(f"tar -xvpf /sillytavern.tar.gz -C {data_folder} --use-compress-program=pigz > /dev/null")
        # os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")

        threading.Thread(target=Oneapi, daemon=True).start()
        os.chdir(data_folder)
        os.system(f"ls {data_folder}")
        os.system("nvm install node")
        os.system("nvm use node")
        os.system("npm install -y")
        try:
            subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
        except subprocess.CalledProcessError as e:
            print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
            print("Output:", e.output)
        os.system(f"ls {data_folder}")
        print('更新文件')
        os.system('git pull')
        subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
        subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
        subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
        subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
    print('-----------SillyTavern结束-------------')  
threading.Thread(target=SillyTavern, daemon=True).start()
time.sleep(60)
check_api1()

if os.path.exists(f'{data_folder}/start.sh'):
    replace_ip_and_country_in_file('/sillytavern/public/login.html')
    # threading.Thread(target=repeat_task, daemon=True).start() #压缩备份
    backup_thread = threading.Thread(target=repeat_task, daemon=True)
    backup_thread.start()
    print("开始衔接")
    Service_status = True
    frp(config_data2,'/content/frp/frpc2.ini',True)
    frp(config_data,'/content/frp/frpc.ini',True)
    # 以线程的形式运行 frp 任务
    # frp_thread1 = threading.Thread(target=frp, args=(config_data2, '/content/frp/frpc2.ini', True))
    # frp_thread1.start()
    # frp_thread2 = threading.Thread(target=frp, args=(config_data, '/content/frp/frpc.ini', False))
    # frp_thread2.start()
    threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
    while True:
        if backup_thread.is_alive():
            print("备份线程仍在运行...")
        else:
            print("备份线程已停止.")
            backup_thread = threading.Thread(target=repeat_task, daemon=True)
            backup_thread.start()
            # break
        time.sleep(5)

else:
    print("/sillytavern 文件不存在结束执行")
compress_folder()