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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ini_content = {"username":"hdsg142saa","key":"2da57ac0c245c1ebba26017f161d5558"}
|
| 2 |
+
frp_url = '119.8.118.149'
|
| 3 |
+
ssh_port = '7078'
|
| 4 |
+
ssh_url = '43.135.135.22'
|
| 5 |
+
st_url = f'http://{frp_url}:7076'
|
| 6 |
+
huggingface_name = 'hdsg142saa'
|
| 7 |
+
huggingface_Data_name = 'qilan-st5'
|
| 8 |
+
configs = [
|
| 9 |
+
("""
|
| 10 |
+
[common]
|
| 11 |
+
server_addr = 47.237.156.222
|
| 12 |
+
server_port = 7000
|
| 13 |
+
|
| 14 |
+
[safsa55]
|
| 15 |
+
type = tcp
|
| 16 |
+
local_ip = 127.0.0.1
|
| 17 |
+
local_port = 8000
|
| 18 |
+
remote_port = 7080
|
| 19 |
+
|
| 20 |
+
[sascb2f55]
|
| 21 |
+
type = tcp
|
| 22 |
+
local_ip = 127.0.0.1
|
| 23 |
+
local_port = 22
|
| 24 |
+
remote_port = 7081
|
| 25 |
+
""", '/content/frp/frpc.ini'),
|
| 26 |
+
(f"""
|
| 27 |
+
[common]
|
| 28 |
+
server_addr = {frp_url}
|
| 29 |
+
server_port = 7000
|
| 30 |
+
token = qilan
|
| 31 |
+
[kkjmk5]
|
| 32 |
+
type = tcp
|
| 33 |
+
local_ip = 127.0.0.1
|
| 34 |
+
local_port = 8000
|
| 35 |
+
remote_port = 7076
|
| 36 |
+
""", '/content/frp/frpc1.ini'),
|
| 37 |
+
("""
|
| 38 |
+
[common]
|
| 39 |
+
server_addr = 47.237.78.158
|
| 40 |
+
server_port = 7000
|
| 41 |
+
[kjas2]
|
| 42 |
+
type = tcp
|
| 43 |
+
local_ip = 127.0.0.1
|
| 44 |
+
local_port = 8000
|
| 45 |
+
remote_port = 7075
|
| 46 |
+
""", '/content/frp/frpc2.ini'),
|
| 47 |
+
("""
|
| 48 |
+
[common]
|
| 49 |
+
server_addr = 45.94.69.159
|
| 50 |
+
server_port = 7000
|
| 51 |
+
[kja1sh5]
|
| 52 |
+
type = tcp
|
| 53 |
+
local_ip = 127.0.0.1
|
| 54 |
+
local_port = 8000
|
| 55 |
+
remote_port = 7075
|
| 56 |
+
""", '/content/frp/frpc3.ini'),
|
| 57 |
+
("""
|
| 58 |
+
[common]
|
| 59 |
+
server_addr = 43.128.135.88
|
| 60 |
+
server_port=7000
|
| 61 |
+
[kkji1mk5]
|
| 62 |
+
type=tcp
|
| 63 |
+
local_ip=127.0.0.1
|
| 64 |
+
local_port=8000
|
| 65 |
+
remote_port=7075
|
| 66 |
+
""", '/content/frp/frpc4.ini'),
|
| 67 |
+
(f"""
|
| 68 |
+
[common]
|
| 69 |
+
server_addr = {ssh_url}
|
| 70 |
+
server_port=7000
|
| 71 |
+
[kkji1mk5]
|
| 72 |
+
type=tcp
|
| 73 |
+
local_ip=127.0.0.1
|
| 74 |
+
local_port=22
|
| 75 |
+
remote_port={ssh_port}
|
| 76 |
+
""", '/content/frp/frpc5.ini')
|
| 77 |
+
]
|
| 78 |
+
kaggle_metadata = {
|
| 79 |
+
"title": "Your Dataset Title",
|
| 80 |
+
"id": f"{huggingface_name}/{huggingface_Data_name}",
|
| 81 |
+
"licenses": [{"name": "CC0-1.0"}]
|
| 82 |
+
}
|
| 83 |
+
st_status = True
|
| 84 |
+
|
| 85 |
+
# 导入必要的模块
|
| 86 |
+
import subprocess
|
| 87 |
+
import os
|
| 88 |
+
import sys
|
| 89 |
+
import logging
|
| 90 |
+
from IPython.display import clear_output
|
| 91 |
+
import urllib.request
|
| 92 |
+
from pathlib import Path
|
| 93 |
+
import requests
|
| 94 |
+
import json
|
| 95 |
+
import threading
|
| 96 |
+
import time
|
| 97 |
+
import pexpect
|
| 98 |
+
import glob
|
| 99 |
+
import socket
|
| 100 |
+
import re
|
| 101 |
+
from datetime import datetime, timedelta
|
| 102 |
+
import psutil
|
| 103 |
+
import pytz
|
| 104 |
+
import paramiko
|
| 105 |
+
from requests.adapters import HTTPAdapter
|
| 106 |
+
from requests.packages.urllib3.util.retry import Retry
|
| 107 |
+
from ruamel.yaml import YAML
|
| 108 |
+
|
| 109 |
+
# 配置日志
|
| 110 |
+
logging.basicConfig(
|
| 111 |
+
level=logging.INFO,
|
| 112 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 113 |
+
)
|
| 114 |
+
logger = logging.getLogger(__name__)
|
| 115 |
+
|
| 116 |
+
# 文件和目录设置
|
| 117 |
+
data_folder = '/root/SillyTavern' # 要压缩的目录
|
| 118 |
+
zip_file_path = '/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
|
| 119 |
+
metadata_file_path = '/a/dataset-metadata.json'
|
| 120 |
+
|
| 121 |
+
# 创建锁和共享变量
|
| 122 |
+
lock = threading.Lock()
|
| 123 |
+
last_uploaded_size = -1
|
| 124 |
+
service_status = False
|
| 125 |
+
|
| 126 |
+
# 初始设置
|
| 127 |
+
os.system("rm -r /sync.sh")
|
| 128 |
+
os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
|
| 129 |
+
os.system("export LC_ALL=zh_CN.UTF-8")
|
| 130 |
+
os.system("mkdir -p /content/frp")
|
| 131 |
+
os.system("wget https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
|
| 132 |
+
os.system("chmod +x /content/frp/frpc")
|
| 133 |
+
|
| 134 |
+
# 更新软件包列表
|
| 135 |
+
def is_installed(package):
|
| 136 |
+
"""检查软件包是否已安装"""
|
| 137 |
+
try:
|
| 138 |
+
subprocess.run(['dpkg', '-s', package],
|
| 139 |
+
stdout=subprocess.PIPE,
|
| 140 |
+
stderr=subprocess.PIPE,
|
| 141 |
+
check=True)
|
| 142 |
+
return True
|
| 143 |
+
except subprocess.CalledProcessError:
|
| 144 |
+
return False
|
| 145 |
+
|
| 146 |
+
def install_package(package):
|
| 147 |
+
"""使用apt安装软件包"""
|
| 148 |
+
logger.info(f"正在安装 {package}...")
|
| 149 |
+
subprocess.run(
|
| 150 |
+
f"sudo apt install {package} -y > /dev/null 2>&1",
|
| 151 |
+
shell=True,
|
| 152 |
+
check=False
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def update_packages():
|
| 156 |
+
"""更新和安装所需软件包"""
|
| 157 |
+
logger.info('开始更新软件包列表')
|
| 158 |
+
|
| 159 |
+
# 安装必要的系统依赖
|
| 160 |
+
packages = {
|
| 161 |
+
'system': ['nodejs', 'npm', 'pigz', 'pv', 'p7zip-full', 'openssh-server', 'vim'],
|
| 162 |
+
'python': ['kaggle==1.5.6', 'ruamel.yaml', 'pexpect', 'pytz', 'paramiko']
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
# 安装系统包
|
| 166 |
+
for pkg in packages['system']:
|
| 167 |
+
if not is_installed(pkg):
|
| 168 |
+
install_package(pkg)
|
| 169 |
+
|
| 170 |
+
# 安装Python包
|
| 171 |
+
for pkg in packages['python']:
|
| 172 |
+
if '==' in pkg:
|
| 173 |
+
pkg_name = pkg.split('==')[0]
|
| 174 |
+
pkg_version = pkg.split('==')[1]
|
| 175 |
+
os.system(f"pip uninstall -y {pkg_name} > /dev/null 2>&1")
|
| 176 |
+
os.system(f"pip install {pkg} > /dev/null 2>&1")
|
| 177 |
+
else:
|
| 178 |
+
os.system(f"pip install {pkg} > /dev/null 2>&1")
|
| 179 |
+
|
| 180 |
+
logger.info('软件包列表更新完成')
|
| 181 |
+
|
| 182 |
+
def kill_frpc_processes():
|
| 183 |
+
"""结束所有frpc进程"""
|
| 184 |
+
try:
|
| 185 |
+
subprocess.run(['pkill', '-f', 'frpc'], check=True)
|
| 186 |
+
logger.info("所有frpc进程已被结束")
|
| 187 |
+
except subprocess.CalledProcessError as e:
|
| 188 |
+
logger.error(f"结束frpc进程时出错: {e}")
|
| 189 |
+
|
| 190 |
+
# 运行系统更新
|
| 191 |
+
update_packages()
|
| 192 |
+
clear_output(wait=True) # 清除输出
|
| 193 |
+
|
| 194 |
+
# 关闭可能运行的frpc进程
|
| 195 |
+
kill_frpc_processes()
|
| 196 |
+
|
| 197 |
+
def run_command(cmd, check=True, shell=True, silent=False):
|
| 198 |
+
"""运行系统命令的通用函数"""
|
| 199 |
+
try:
|
| 200 |
+
kwargs = {
|
| 201 |
+
'shell': shell,
|
| 202 |
+
'check': check
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
if silent:
|
| 206 |
+
kwargs.update({
|
| 207 |
+
'stdout': subprocess.DEVNULL,
|
| 208 |
+
'stderr': subprocess.DEVNULL
|
| 209 |
+
})
|
| 210 |
+
|
| 211 |
+
return subprocess.run(cmd, **kwargs)
|
| 212 |
+
except subprocess.CalledProcessError as e:
|
| 213 |
+
logger.error(f"命令执行失败: {e}")
|
| 214 |
+
return None
|
| 215 |
+
|
| 216 |
+
# Oneapi中转
|
| 217 |
+
def Oneapi():
|
| 218 |
+
print('-----------Oneapi中转开始-------------')
|
| 219 |
+
# 删除旧的 one-api 文件夹(如果存在)
|
| 220 |
+
os.system("rm -rf /one/one-api") # 使用 -f 参数以避免错误
|
| 221 |
+
os.system("mkdir -p /one") # 创建目录
|
| 222 |
+
# 下载 one-api 文件
|
| 223 |
+
url = "https://github.com/songquanpeng/one-api/releases/download/v0.6.8/one-api"
|
| 224 |
+
os.system(f"wget {url} -O /one/one-api") # 正确下载并重命名为 /one/one-api
|
| 225 |
+
# 修改文件权限,使其可执行
|
| 226 |
+
os.system("chmod +x /one/one-api")
|
| 227 |
+
# 设置环境变量
|
| 228 |
+
os.environ["THEME"] = "berry"
|
| 229 |
+
os.environ["TIKTOKEN_CACHE_DIR"] = os.getcwd() # 使用Python的os.getcwd()获取当前工作目录
|
| 230 |
+
# 设置MySQL数据库的环境变量
|
| 231 |
+
db_user = "oneapi"
|
| 232 |
+
db_password = "epBjK5ZKysCe6yr3"
|
| 233 |
+
db_host = "106.52.51.116"
|
| 234 |
+
db_port = "3306"
|
| 235 |
+
db_name = "oneapi"
|
| 236 |
+
dsn = f"{db_user}:{db_password}@tcp({db_host}:{db_port})/{db_name}"
|
| 237 |
+
os.environ["SQL_DSN"] = dsn
|
| 238 |
+
command = ['/one/one-api', '--port', '3000']
|
| 239 |
+
process = subprocess.Popen(command) # 启动程序并将其放到后台执行
|
| 240 |
+
print(f"OneAPI程序已在后台启动,进程ID为:{process.pid}")
|
| 241 |
+
print('-----------Oneapi中转结束-------------')
|
| 242 |
+
# Oneapi()
|
| 243 |
+
|
| 244 |
+
# SSH相关功能
|
| 245 |
+
def ssh():
|
| 246 |
+
"""安装和配置SSH服务器"""
|
| 247 |
+
logger.info('开始配置SSH服务')
|
| 248 |
+
|
| 249 |
+
# 安装SSH服务器
|
| 250 |
+
run_command("apt update", silent=True)
|
| 251 |
+
run_command("apt install openssh-server -y", silent=True)
|
| 252 |
+
run_command("apt-get install vim -y", silent=True)
|
| 253 |
+
|
| 254 |
+
# 配置SSH
|
| 255 |
+
run_command("sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config")
|
| 256 |
+
run_command("sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config")
|
| 257 |
+
run_command("systemctl restart ssh")
|
| 258 |
+
run_command("/etc/init.d/ssh restart")
|
| 259 |
+
run_command("echo 'root:qilan' | sudo chpasswd")
|
| 260 |
+
run_command("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
|
| 261 |
+
run_command("service ssh restart")
|
| 262 |
+
run_command("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
|
| 263 |
+
|
| 264 |
+
logger.info('SSH服务配置完成')
|
| 265 |
+
|
| 266 |
+
def generate_ssh_key():
|
| 267 |
+
"""生成SSH密钥对"""
|
| 268 |
+
logger.info("生成SSH密钥对")
|
| 269 |
+
# 删除已有的SSH密钥
|
| 270 |
+
os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
|
| 271 |
+
|
| 272 |
+
# 生成新的SSH密钥
|
| 273 |
+
keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
|
| 274 |
+
try:
|
| 275 |
+
result = subprocess.run(
|
| 276 |
+
keygen_command,
|
| 277 |
+
shell=True,
|
| 278 |
+
check=True,
|
| 279 |
+
stdout=subprocess.PIPE,
|
| 280 |
+
stderr=subprocess.PIPE
|
| 281 |
+
)
|
| 282 |
+
logger.info("SSH密钥对已生成")
|
| 283 |
+
|
| 284 |
+
# 设置权限
|
| 285 |
+
os.system('chmod 600 ~/.ssh/id_rsa')
|
| 286 |
+
return True
|
| 287 |
+
except subprocess.CalledProcessError as e:
|
| 288 |
+
error_msg = e.stderr.decode() if e.stderr else str(e)
|
| 289 |
+
logger.error(f"SSH密钥生成失败: {error_msg}")
|
| 290 |
+
return False
|
| 291 |
+
|
| 292 |
+
def copy_public_key_to_remote(host, port, user, password):
|
| 293 |
+
"""将公钥复制到远程服务器"""
|
| 294 |
+
logger.info(f"正在将公钥复制到 {user}@{host}:{port}")
|
| 295 |
+
try:
|
| 296 |
+
command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
|
| 297 |
+
child = pexpect.spawn(command)
|
| 298 |
+
|
| 299 |
+
# 等待密码提示并发送密码
|
| 300 |
+
child.expect("password:", timeout=15)
|
| 301 |
+
child.sendline(password)
|
| 302 |
+
|
| 303 |
+
# 等待命令完成
|
| 304 |
+
child.expect(pexpect.EOF)
|
| 305 |
+
logger.info("公钥已成功复制到远程服务器")
|
| 306 |
+
return True
|
| 307 |
+
except Exception as e:
|
| 308 |
+
logger.error(f"复制公钥失败: {e}")
|
| 309 |
+
return False
|
| 310 |
+
|
| 311 |
+
def check_ssh_connection(host, port, username, password):
|
| 312 |
+
"""检查SSH连接是否可用"""
|
| 313 |
+
try:
|
| 314 |
+
client = paramiko.SSHClient()
|
| 315 |
+
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
| 316 |
+
client.connect(hostname=host, port=int(port), username=username, password=password, timeout=10)
|
| 317 |
+
client.close()
|
| 318 |
+
logger.info(f"SSH连接到 {username}@{host}:{port} 成功")
|
| 319 |
+
return True
|
| 320 |
+
except Exception as e:
|
| 321 |
+
logger.error(f"SSH连接失败: {e}")
|
| 322 |
+
return False
|
| 323 |
+
|
| 324 |
+
def write_rsyncd_conf(path, port=7071):
|
| 325 |
+
"""配置rsync守护进程"""
|
| 326 |
+
rsyncd_conf_content = f"""
|
| 327 |
+
port = {port}
|
| 328 |
+
[qilan]
|
| 329 |
+
path = {path}
|
| 330 |
+
comment = My rsync module
|
| 331 |
+
read only = no
|
| 332 |
+
list = yes
|
| 333 |
+
"""
|
| 334 |
+
with open('/etc/rsyncd.conf', 'w') as f:
|
| 335 |
+
f.write(rsyncd_conf_content.strip())
|
| 336 |
+
logger.info(f"已配置rsync守护进程,端口为 {port}")
|
| 337 |
+
|
| 338 |
+
# 启动rsync守护进程
|
| 339 |
+
run_command("sudo rsync --daemon")
|
| 340 |
+
run_command("ps aux | grep rsync", silent=True)
|
| 341 |
+
|
| 342 |
+
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
|
| 343 |
+
"""创建一个带重试机制的请求会话"""
|
| 344 |
+
session = session or requests.Session()
|
| 345 |
+
retry = Retry(
|
| 346 |
+
total=retries,
|
| 347 |
+
read=retries,
|
| 348 |
+
connect=retries,
|
| 349 |
+
backoff_factor=backoff_factor,
|
| 350 |
+
status_forcelist=status_forcelist,
|
| 351 |
+
)
|
| 352 |
+
adapter = HTTPAdapter(max_retries=retry)
|
| 353 |
+
session.mount('http://', adapter)
|
| 354 |
+
session.mount('https://', adapter)
|
| 355 |
+
return session
|
| 356 |
+
|
| 357 |
+
import os
|
| 358 |
+
import time
|
| 359 |
+
import requests
|
| 360 |
+
import subprocess
|
| 361 |
+
import logging
|
| 362 |
+
|
| 363 |
+
import paramiko
|
| 364 |
+
|
| 365 |
+
def monitor_port(port=8000, check_interval=5):
|
| 366 |
+
"""监控指定端口,如果未使用则重新启动SillyTavern"""
|
| 367 |
+
logger.info(f"开始监控端口 {port}")
|
| 368 |
+
while True:
|
| 369 |
+
try:
|
| 370 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
| 371 |
+
result = sock.connect_ex(('localhost', port))
|
| 372 |
+
if result == 0:
|
| 373 |
+
logger.info(f"端口 {port} 正在使用中")
|
| 374 |
+
else:
|
| 375 |
+
logger.warning(f"端口 {port} 未被使用,尝试重新启动SillyTavern")
|
| 376 |
+
threading.Thread(target=Run_SillyTavern, daemon=True).start()
|
| 377 |
+
except Exception as e:
|
| 378 |
+
logger.error(f"端口监控异常: {e}")
|
| 379 |
+
|
| 380 |
+
time.sleep(check_interval)
|
| 381 |
+
|
| 382 |
+
def Run_SillyTavern():
|
| 383 |
+
"""运行SillyTavern服务器"""
|
| 384 |
+
logger.info("尝试启动SillyTavern")
|
| 385 |
+
try:
|
| 386 |
+
# 确保在正确的目录中
|
| 387 |
+
os.chdir(data_folder)
|
| 388 |
+
|
| 389 |
+
# 多次尝试启动,提高成功率
|
| 390 |
+
for i in range(5):
|
| 391 |
+
logger.info(f"第{i+1}次尝试启动SillyTavern")
|
| 392 |
+
result = run_command(f'yes | sh {data_folder}/start.sh', silent=True)
|
| 393 |
+
if result and result.returncode == 0:
|
| 394 |
+
logger.info("SillyTavern已成功启动")
|
| 395 |
+
break
|
| 396 |
+
time.sleep(2)
|
| 397 |
+
|
| 398 |
+
logger.info("SillyTavern启动过程完成")
|
| 399 |
+
except Exception as e:
|
| 400 |
+
logger.error(f"启动SillyTavern时发生异常: {e}")
|
| 401 |
+
|
| 402 |
+
def check_api_status():
|
| 403 |
+
"""检查SillyTavern API是否正常运行"""
|
| 404 |
+
# 检查本地服务是否启动
|
| 405 |
+
max_retries = 30
|
| 406 |
+
retry_count = 0
|
| 407 |
+
|
| 408 |
+
# 第一步:检查本地API是否启动
|
| 409 |
+
logger.info("检查SillyTavern本地API是否启动")
|
| 410 |
+
while retry_count < max_retries:
|
| 411 |
+
retry_count += 1
|
| 412 |
+
|
| 413 |
+
if not os.path.exists(data_folder):
|
| 414 |
+
logger.error(f"数据目录 {data_folder} 不存在,终止检测")
|
| 415 |
+
return False
|
| 416 |
+
|
| 417 |
+
try:
|
| 418 |
+
url = "http://127.0.0.1:8000/v1"
|
| 419 |
+
response = requests.get(url, timeout=5)
|
| 420 |
+
|
| 421 |
+
if response.status_code == 403:
|
| 422 |
+
logger.info("SillyTavern本地API已启动")
|
| 423 |
+
break
|
| 424 |
+
|
| 425 |
+
logger.warning(f"SillyTavern未启动,状态码: {response.status_code},重试次数: {retry_count}")
|
| 426 |
+
except requests.exceptions.RequestException as e:
|
| 427 |
+
logger.warning(f"SillyTavern未启动: {e},重试次数: {retry_count}")
|
| 428 |
+
|
| 429 |
+
if retry_count >= max_retries:
|
| 430 |
+
logger.error("SillyTavern本地API启动检测超时")
|
| 431 |
+
return False
|
| 432 |
+
|
| 433 |
+
time.sleep(5)
|
| 434 |
+
|
| 435 |
+
# 第二步:检查远程API是否可访问
|
| 436 |
+
logger.info("本地API已启动,开始检测远程API状态")
|
| 437 |
+
retry_count = 0
|
| 438 |
+
retry_limit = 10
|
| 439 |
+
sync_attempts = 0
|
| 440 |
+
|
| 441 |
+
while retry_count < retry_limit:
|
| 442 |
+
retry_count += 1
|
| 443 |
+
|
| 444 |
+
if sync_attempts >= 3:
|
| 445 |
+
logger.error("同步尝试次数过多,终止检测")
|
| 446 |
+
break
|
| 447 |
+
|
| 448 |
+
url = f"{st_url}/csrf-token"
|
| 449 |
+
try:
|
| 450 |
+
response = requests_retry_session().get(url, timeout=10)
|
| 451 |
+
response.raise_for_status()
|
| 452 |
+
response_json = response.json()
|
| 453 |
+
|
| 454 |
+
logger.info(f"远程API返回信息: {response_json}")
|
| 455 |
+
|
| 456 |
+
if "token" in response_json:
|
| 457 |
+
logger.info("远程API正常,检测到token")
|
| 458 |
+
try:
|
| 459 |
+
# 使用rsync从远程同步数据
|
| 460 |
+
result = run_command(
|
| 461 |
+
f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",
|
| 462 |
+
check=True
|
| 463 |
+
)
|
| 464 |
+
if result and result.returncode == 0:
|
| 465 |
+
logger.info("数据同步成功")
|
| 466 |
+
return True
|
| 467 |
+
except Exception as e:
|
| 468 |
+
sync_attempts += 1
|
| 469 |
+
logger.error(f"数据同步失败: {e},尝试次数: {sync_attempts}")
|
| 470 |
+
if sync_attempts < 3:
|
| 471 |
+
# 重新生成SSH密钥重试
|
| 472 |
+
generate_ssh_key()
|
| 473 |
+
else:
|
| 474 |
+
logger.warning(f"远程API返回数据中没有token: {response_json}")
|
| 475 |
+
|
| 476 |
+
except requests.exceptions.ConnectionError as e:
|
| 477 |
+
logger.error(f"远程API连接异常: {e},重试次数: {retry_count}")
|
| 478 |
+
sync_attempts += 1
|
| 479 |
+
except requests.exceptions.Timeout as e:
|
| 480 |
+
logger.error(f"远程API超时: {e}")
|
| 481 |
+
break
|
| 482 |
+
except requests.exceptions.RequestException as e:
|
| 483 |
+
logger.error(f"远程API请求异常: {e}")
|
| 484 |
+
break
|
| 485 |
+
|
| 486 |
+
time.sleep(5)
|
| 487 |
+
|
| 488 |
+
return False
|
| 489 |
+
|
| 490 |
+
def frp(configs, backstage=True):
|
| 491 |
+
"""启动FRP代理客户端"""
|
| 492 |
+
logger.info('开始配置FRP客户端')
|
| 493 |
+
|
| 494 |
+
# 杀死之前可能运行的frpc进程
|
| 495 |
+
kill_frpc_processes()
|
| 496 |
+
|
| 497 |
+
# 遍历配置启动FRP
|
| 498 |
+
for idx, (config_data, config_file_path) in enumerate(configs):
|
| 499 |
+
# 写入配置文件
|
| 500 |
+
with open(config_file_path, 'w') as config_file:
|
| 501 |
+
config_file.write(config_data)
|
| 502 |
+
|
| 503 |
+
# 构建启动命令
|
| 504 |
+
frpc_cmd = ['/content/frp/frpc', '-c', config_file_path]
|
| 505 |
+
|
| 506 |
+
if backstage:
|
| 507 |
+
# 后台运行
|
| 508 |
+
process = subprocess.Popen(frpc_cmd)
|
| 509 |
+
logger.info(f"FRP客户端[{idx}]已在后台启动,PID: {process.pid}")
|
| 510 |
+
else:
|
| 511 |
+
# 前台运行(阻塞)
|
| 512 |
+
logger.info(f"FRP客户端[{idx}]正在前台启动")
|
| 513 |
+
run_command(f'/content/frp/frpc -c {config_file_path}', shell=True)
|
| 514 |
+
|
| 515 |
+
logger.info('所有FRP客户端已启动')
|
| 516 |
+
|
| 517 |
+
def get_current_ip():
|
| 518 |
+
"""获取当前公共IP地址"""
|
| 519 |
+
try:
|
| 520 |
+
response = requests.get("https://ipinfo.io/ip", timeout=10)
|
| 521 |
+
ip = response.text.strip()
|
| 522 |
+
logger.info(f"当前公共IP: {ip}")
|
| 523 |
+
return ip
|
| 524 |
+
except Exception as e:
|
| 525 |
+
logger.error(f"获取IP地址失败: {e}")
|
| 526 |
+
return "未知"
|
| 527 |
+
|
| 528 |
+
def get_geo_info(ip_address):
|
| 529 |
+
"""根据IP地址获取地理位置信息"""
|
| 530 |
+
url = "https://api.qjqq.cn/api/Local"
|
| 531 |
+
headers = {
|
| 532 |
+
"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"
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
try:
|
| 536 |
+
response = requests_retry_session().get(url, headers=headers, timeout=10)
|
| 537 |
+
|
| 538 |
+
if response.status_code == 200:
|
| 539 |
+
geo_info = response.json()
|
| 540 |
+
|
| 541 |
+
if geo_info.get('code') == 200:
|
| 542 |
+
data = geo_info.get('data', {})
|
| 543 |
+
result = {
|
| 544 |
+
'ip': data.get('ip', "未知"),
|
| 545 |
+
'country': data.get('country', "未知"),
|
| 546 |
+
'isp': data.get('isp', "未知")
|
| 547 |
+
}
|
| 548 |
+
logger.info(f"获取地理信息成功: {result}")
|
| 549 |
+
return result
|
| 550 |
+
|
| 551 |
+
logger.warning(f"获取地理信息失败,状态码: {response.status_code}")
|
| 552 |
+
return None
|
| 553 |
+
except Exception as e:
|
| 554 |
+
logger.error(f"获取地理信息时发生错误: {e}")
|
| 555 |
+
return None
|
| 556 |
+
|
| 557 |
+
def get_next_relay_time():
|
| 558 |
+
"""获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
|
| 559 |
+
try:
|
| 560 |
+
# 获取系统启动时间
|
| 561 |
+
boot_time = datetime.fromtimestamp(psutil.boot_time())
|
| 562 |
+
# 设置为UTC时区
|
| 563 |
+
utc = pytz.UTC
|
| 564 |
+
boot_time = utc.localize(boot_time)
|
| 565 |
+
# 转换为中国时区
|
| 566 |
+
china_tz = pytz.timezone('Asia/Shanghai')
|
| 567 |
+
boot_time_china = boot_time.astimezone(china_tz)
|
| 568 |
+
# 加上12小时
|
| 569 |
+
next_time = boot_time_china + timedelta(hours=12)
|
| 570 |
+
return next_time.strftime("%Y-%m-%d %H:%M:%S")
|
| 571 |
+
except Exception as e:
|
| 572 |
+
logger.error(f"计算下次接力时间失败: {e}")
|
| 573 |
+
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 574 |
+
|
| 575 |
+
def replace_info_in_file(file_path):
|
| 576 |
+
"""更新登录页面中的接力时间和IP信息"""
|
| 577 |
+
try:
|
| 578 |
+
# 检查文件是否存在
|
| 579 |
+
if not os.path.exists(file_path):
|
| 580 |
+
logger.error(f"文件{file_path}不存在,无法更新信息")
|
| 581 |
+
return False
|
| 582 |
+
|
| 583 |
+
# 获取当前IP地址和地理信息
|
| 584 |
+
ip_address = get_current_ip()
|
| 585 |
+
geo_info = get_geo_info(ip_address)
|
| 586 |
+
next_relay_time = get_next_relay_time()
|
| 587 |
+
|
| 588 |
+
if geo_info is None:
|
| 589 |
+
logger.error("无法获取地理信息,更新文件信息失败")
|
| 590 |
+
return False
|
| 591 |
+
|
| 592 |
+
# 读取文件内容
|
| 593 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
| 594 |
+
content = file.read()
|
| 595 |
+
|
| 596 |
+
# 替换接力时间
|
| 597 |
+
time_pattern = r'接力时间\[.*?\]'
|
| 598 |
+
time_replacement = f'接力时间[{next_relay_time}]'
|
| 599 |
+
content = re.sub(time_pattern, time_replacement, content)
|
| 600 |
+
|
| 601 |
+
# 替换IP信息
|
| 602 |
+
ip_pattern = r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]'
|
| 603 |
+
ip_replacement = f'IP[{geo_info["ip"]}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]'
|
| 604 |
+
content = re.sub(ip_pattern, ip_replacement, content)
|
| 605 |
+
|
| 606 |
+
# 写回文件
|
| 607 |
+
with open(file_path, 'w', encoding='utf-8') as file:
|
| 608 |
+
file.write(content)
|
| 609 |
+
|
| 610 |
+
logger.info("成功更新信息:")
|
| 611 |
+
logger.info(f"接力时间: {next_relay_time}")
|
| 612 |
+
logger.info(f"IP信息: IP[{geo_info['ip']}] 国家 [{geo_info['country']}] IPS[{geo_info['isp']}]")
|
| 613 |
+
return True
|
| 614 |
+
|
| 615 |
+
except Exception as e:
|
| 616 |
+
logger.error(f"更新文件信息时发生错误: {e}")
|
| 617 |
+
return False
|
| 618 |
+
|
| 619 |
+
def update_last_uploaded_size(size):
|
| 620 |
+
"""更新上次上传的文件大小"""
|
| 621 |
+
global last_uploaded_size
|
| 622 |
+
last_uploaded_size = size
|
| 623 |
+
logger.info(f"上次上传文件大小已更新为: {size} 字节")
|
| 624 |
+
|
| 625 |
+
def compress_folder():
|
| 626 |
+
"""压缩SillyTavern文件夹并上传到Kaggle"""
|
| 627 |
+
global last_uploaded_size # 声明使用全局变量
|
| 628 |
+
|
| 629 |
+
# 清理并创建目录 /a
|
| 630 |
+
if os.path.exists('/a'):
|
| 631 |
+
run_command('rm -r /a/')
|
| 632 |
+
|
| 633 |
+
os.makedirs('/a', exist_ok=True)
|
| 634 |
+
|
| 635 |
+
with lock: # 使用锁防止多线程冲突
|
| 636 |
+
# 检查文件是否已存在
|
| 637 |
+
if os.path.exists(zip_file_path):
|
| 638 |
+
logger.info(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩")
|
| 639 |
+
return
|
| 640 |
+
|
| 641 |
+
logger.info('开始压缩数据')
|
| 642 |
+
|
| 643 |
+
# 使用pigz进行多核压缩以提高效率
|
| 644 |
+
try:
|
| 645 |
+
result = run_command(
|
| 646 |
+
f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
|
| 647 |
+
shell=True,
|
| 648 |
+
check=True,
|
| 649 |
+
silent=True
|
| 650 |
+
)
|
| 651 |
+
except Exception as e:
|
| 652 |
+
logger.error(f"压缩命令失败: {e}")
|
| 653 |
+
return
|
| 654 |
+
|
| 655 |
+
logger.info('重命名压缩后的文件')
|
| 656 |
+
file_path = "/a/sillytavern.ctk"
|
| 657 |
+
|
| 658 |
+
run_command(['mv', zip_file_path, file_path], shell=False)
|
| 659 |
+
|
| 660 |
+
# 检查压缩是否成功
|
| 661 |
+
if not os.path.exists(file_path):
|
| 662 |
+
logger.error("压缩失败,文件不存在")
|
| 663 |
+
return
|
| 664 |
+
|
| 665 |
+
logger.info(f"数据已压缩到 {file_path}")
|
| 666 |
+
|
| 667 |
+
# 获取文件大小
|
| 668 |
+
file_size = os.path.getsize(file_path)
|
| 669 |
+
logger.info(f'文件大小: {file_size} 字节, 上次文件大小: {last_uploaded_size} 字节')
|
| 670 |
+
|
| 671 |
+
# 文件大小必须超过400MB才会上传
|
| 672 |
+
min_size = 400 * 1024 * 1024 # 400MB
|
| 673 |
+
if file_size < min_size:
|
| 674 |
+
logger.info(f"文件小于{min_size/(1024*1024)}MB,不进行上传")
|
| 675 |
+
return
|
| 676 |
+
|
| 677 |
+
# 检查是否需要上传
|
| 678 |
+
if last_uploaded_size == -1 or file_size > last_uploaded_size:
|
| 679 |
+
# 首次运行或文件变大
|
| 680 |
+
if last_uploaded_size == -1:
|
| 681 |
+
logger.info("首次运行,准备上传...")
|
| 682 |
+
else:
|
| 683 |
+
logger.info(f"新文件 {file_path} 大于上次上传的大小,准备上传...")
|
| 684 |
+
|
| 685 |
+
# 更新上传大小记录
|
| 686 |
+
update_last_uploaded_size(file_size)
|
| 687 |
+
|
| 688 |
+
# 创建元数据文件
|
| 689 |
+
with open(metadata_file_path, 'w') as json_fid:
|
| 690 |
+
json.dump(kaggle_metadata, json_fid)
|
| 691 |
+
|
| 692 |
+
# 上传到Kaggle
|
| 693 |
+
logger.info("开始上传到Kaggle...")
|
| 694 |
+
os.system("kaggle datasets version -m 'new version message' -p /a")
|
| 695 |
+
logger.info("上传完成")
|
| 696 |
+
else:
|
| 697 |
+
logger.info(f"新文件 {file_path} 不大于上次上传的大小,跳过上传")
|
| 698 |
+
|
| 699 |
+
def repeat_task():
|
| 700 |
+
"""定期压缩和上传的后台任务"""
|
| 701 |
+
logger.info('打包备份线程已启动')
|
| 702 |
+
try:
|
| 703 |
+
while True:
|
| 704 |
+
logger.info('等待下一次打包时间...')
|
| 705 |
+
time.sleep(18000) # 5小时执行一次
|
| 706 |
+
compress_folder()
|
| 707 |
+
except Exception as e:
|
| 708 |
+
logger.error(f"打包线程异常: {e}")
|
| 709 |
+
logger.info('打包线程已结束')
|
| 710 |
+
|
| 711 |
+
def setup_tavern_environment():
|
| 712 |
+
"""设置SillyTavern运行环境"""
|
| 713 |
+
logger.info("设置SillyTavern运行环境")
|
| 714 |
+
|
| 715 |
+
try:
|
| 716 |
+
# 切换到SillyTavern目录
|
| 717 |
+
os.chdir(data_folder)
|
| 718 |
+
|
| 719 |
+
# 安装Node.js环境
|
| 720 |
+
run_command("nvm install node", silent=True)
|
| 721 |
+
run_command("nvm use node", silent=True)
|
| 722 |
+
|
| 723 |
+
# 安装依赖
|
| 724 |
+
run_command("npm install -y", silent=True)
|
| 725 |
+
|
| 726 |
+
# 首次运行SillyTavern
|
| 727 |
+
try:
|
| 728 |
+
run_command(f'yes | sh {data_folder}/start.sh', check=False, silent=True)
|
| 729 |
+
logger.info("SillyTavern环境设置完成")
|
| 730 |
+
return True
|
| 731 |
+
except Exception as e:
|
| 732 |
+
logger.error(f"首次启动SillyTavern失败: {e}")
|
| 733 |
+
return False
|
| 734 |
+
except Exception as e:
|
| 735 |
+
logger.error(f"设置SillyTavern环境时出错: {e}")
|
| 736 |
+
return False
|
| 737 |
+
|
| 738 |
+
def SillyTavern():
|
| 739 |
+
"""安装和配置SillyTavern"""
|
| 740 |
+
logger.info('开始安装SillyTavern')
|
| 741 |
+
|
| 742 |
+
# 设置Kaggle凭证
|
| 743 |
+
setup_kaggle()
|
| 744 |
+
|
| 745 |
+
# 清除输出
|
| 746 |
+
clear_output()
|
| 747 |
+
|
| 748 |
+
# 清理旧文件
|
| 749 |
+
run_command(f"rm -rf /a /sillytavern /*.zi* {data_folder}", silent=True)
|
| 750 |
+
run_command(f"mkdir -p {data_folder}", silent=True)
|
| 751 |
+
|
| 752 |
+
# 切换到根目录
|
| 753 |
+
os.chdir('/')
|
| 754 |
+
|
| 755 |
+
# 尝试从Kaggle下载
|
| 756 |
+
download_success = download_from_kaggle()
|
| 757 |
+
|
| 758 |
+
if not download_success:
|
| 759 |
+
logger.warning("从Kaggle下载失败,尝试使用rsync同步")
|
| 760 |
+
# 使用SSH同步备份方案
|
| 761 |
+
generate_ssh_key()
|
| 762 |
+
copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
|
| 763 |
+
|
| 764 |
+
try:
|
| 765 |
+
run_command(
|
| 766 |
+
f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",
|
| 767 |
+
check=True
|
| 768 |
+
)
|
| 769 |
+
logger.info("通过rsync成功同步数据")
|
| 770 |
+
except Exception as e:
|
| 771 |
+
logger.error(f"rsync同步失败: {e}")
|
| 772 |
+
return False
|
| 773 |
+
else:
|
| 774 |
+
# 如果下载成功,解压数据
|
| 775 |
+
extract_success = extract_tavern_data()
|
| 776 |
+
if not extract_success:
|
| 777 |
+
logger.error("解压SillyTavern数据失败")
|
| 778 |
+
return False
|
| 779 |
+
|
| 780 |
+
# 设置环境并启动
|
| 781 |
+
setup_success = setup_tavern_environment()
|
| 782 |
+
if not setup_success:
|
| 783 |
+
logger.error("设置SillyTavern环境失败")
|
| 784 |
+
return False
|
| 785 |
+
|
| 786 |
+
# 在后台启动SillyTavern
|
| 787 |
+
backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
|
| 788 |
+
backup_thread.start()
|
| 789 |
+
|
| 790 |
+
logger.info('SillyTavern安装和配置完成')
|
| 791 |
+
return True
|
| 792 |
+
|
| 793 |
+
# 主函数
|
| 794 |
+
if __name__ == "__main__":
|
| 795 |
+
# 安装SSH服务
|
| 796 |
+
ssh()
|
| 797 |
+
|
| 798 |
+
# 生成SSH密钥
|
| 799 |
+
generate_ssh_key()
|
| 800 |
+
|
| 801 |
+
# 复制SSH公钥到远程服务器
|
| 802 |
+
copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
|
| 803 |
+
|
| 804 |
+
# 配置rsync
|
| 805 |
+
write_rsyncd_conf(data_folder)
|
| 806 |
+
|
| 807 |
+
# 启动SillyTavern
|
| 808 |
+
tavern_thread = threading.Thread(target=SillyTavern, daemon=True)
|
| 809 |
+
tavern_thread.start()
|
| 810 |
+
tavern_thread.join(timeout=60) # 等待最多60秒
|
| 811 |
+
|
| 812 |
+
# 检查API状态
|
| 813 |
+
api_status = check_api_status()
|
| 814 |
+
|
| 815 |
+
# 如果SillyTavern已安装成功
|
| 816 |
+
if os.path.exists(f'{data_folder}/start.sh'):
|
| 817 |
+
# 更新登录页面信息
|
| 818 |
+
replace_info_in_file(f'{data_folder}/public/login.html')
|
| 819 |
+
|
| 820 |
+
# 启动备份线程
|
| 821 |
+
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 822 |
+
backup_thread.start()
|
| 823 |
+
|
| 824 |
+
logger.info("开始配置网络连接")
|
| 825 |
+
# 服务状态设为可用
|
| 826 |
+
st_status = True
|
| 827 |
+
|
| 828 |
+
# 启动FRP代理
|
| 829 |
+
frp(configs, True)
|
| 830 |
+
|
| 831 |
+
# 启动端口监控
|
| 832 |
+
threading.Thread(target=monitor_port, daemon=True).start()
|
| 833 |
+
|
| 834 |
+
# 监控备份线程状态
|
| 835 |
+
while True:
|
| 836 |
+
if backup_thread.is_alive():
|
| 837 |
+
logger.info("备份线程正在运行...")
|
| 838 |
+
else:
|
| 839 |
+
logger.warning("备份线程已停止,重新启动")
|
| 840 |
+
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 841 |
+
backup_thread.start()
|
| 842 |
+
break
|
| 843 |
+
time.sleep(30) # 每30秒检查一次
|
| 844 |
+
|
| 845 |
+
# 运行一次压缩备份
|
| 846 |
+
compress_folder()
|
| 847 |
+
else:
|
| 848 |
+
logger.error(f"{data_folder} 文件夹不存在,安装失败")
|
| 849 |
+
|
| 850 |
+
def setup_kaggle():
|
| 851 |
+
"""设置Kaggle API凭证"""
|
| 852 |
+
logger.info("设置Kaggle API凭证")
|
| 853 |
+
# 创建目录并写入kaggle.json
|
| 854 |
+
os.makedirs("~/.kaggle", exist_ok=True)
|
| 855 |
+
|
| 856 |
+
file_path = '/root/.kaggle/kaggle.json'
|
| 857 |
+
with open(file_path, 'w') as json_file:
|
| 858 |
+
json.dump(ini_content, json_file, indent=4)
|
| 859 |
+
|
| 860 |
+
# 设置权限
|
| 861 |
+
os.system("chmod 600 ~/.kaggle/kaggle.json")
|
| 862 |
+
logger.info("Kaggle凭证设置完成")
|
| 863 |
+
|
| 864 |
+
def download_from_kaggle():
|
| 865 |
+
"""从Kaggle下载SillyTavern数据"""
|
| 866 |
+
logger.info(f"开始从Kaggle下载数据集 {huggingface_name}/{huggingface_Data_name}")
|
| 867 |
+
|
| 868 |
+
max_attempts = 6
|
| 869 |
+
for attempt in range(1, max_attempts + 1):
|
| 870 |
+
logger.info(f"第{attempt}次尝试下载")
|
| 871 |
+
|
| 872 |
+
# 执行下载命令
|
| 873 |
+
run_command(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /", silent=True)
|
| 874 |
+
|
| 875 |
+
# 检查文件是否存在
|
| 876 |
+
if os.path.exists(f'/{huggingface_Data_name}.zip'):
|
| 877 |
+
logger.info(f"{huggingface_Data_name}.zip 下载成功")
|
| 878 |
+
return True
|
| 879 |
+
|
| 880 |
+
logger.warning(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
|
| 881 |
+
|
| 882 |
+
if attempt < max_attempts:
|
| 883 |
+
logger.info(f"等待5分钟后重试...")
|
| 884 |
+
time.sleep(300) # 等待5分钟再重试
|
| 885 |
+
|
| 886 |
+
logger.error("多次尝试下载失败")
|
| 887 |
+
return False
|
| 888 |
+
|
| 889 |
+
def extract_tavern_data():
|
| 890 |
+
"""解压SillyTavern数据"""
|
| 891 |
+
logger.info("开始解压SillyTavern数据")
|
| 892 |
+
|
| 893 |
+
# 检查目标文件
|
| 894 |
+
zip_path = f'/{huggingface_Data_name}.zip'
|
| 895 |
+
if not os.path.exists(zip_path):
|
| 896 |
+
logger.error(f"文件 {zip_path} 不存在,无法解压")
|
| 897 |
+
return False
|
| 898 |
+
|
| 899 |
+
try:
|
| 900 |
+
# 解压缩文件
|
| 901 |
+
run_command(f"7z x {zip_path} -o/ -y", silent=True)
|
| 902 |
+
|
| 903 |
+
# 重命名解压后的文件
|
| 904 |
+
if os.path.exists('/sillytavern.tck'):
|
| 905 |
+
run_command("mv /sillytavern.tck sillytavern.tar.gz")
|
| 906 |
+
|
| 907 |
+
if os.path.exists('/sillytavern.ctk'):
|
| 908 |
+
run_command("mv /sillytavern.ctk sillytavern.tar.gz")
|
| 909 |
+
|
| 910 |
+
# 使用pigz解压tar.gz文件
|
| 911 |
+
if os.path.exists('/sillytavern.tar.gz'):
|
| 912 |
+
run_command("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null", silent=True)
|
| 913 |
+
logger.info("SillyTavern数据解压完成")
|
| 914 |
+
|
| 915 |
+
# 清理下载和临时文件
|
| 916 |
+
run_command(f"rm -r {zip_path} /sillytavern.tar.gz", silent=True)
|
| 917 |
+
return True
|
| 918 |
+
else:
|
| 919 |
+
logger.error("解压后的tar.gz文件不存在")
|
| 920 |
+
return False
|
| 921 |
+
except Exception as e:
|
| 922 |
+
logger.error(f"解压SillyTavern数据时出错: {e}")
|
| 923 |
+
return False
|