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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ini_content = {"username":"xovale7506","key":"502e30bafc004c02aa668a279df23f3e"}
|
| 2 |
+
frp_url = '47.237.156.222'
|
| 3 |
+
ssh_port = '7072'
|
| 4 |
+
st_url = f'http://{frp_url}:7070'
|
| 5 |
+
config_data = f"""
|
| 6 |
+
[common]
|
| 7 |
+
server_addr = {frp_url}
|
| 8 |
+
server_port = 7000
|
| 9 |
+
|
| 10 |
+
[safgha]
|
| 11 |
+
type = tcp
|
| 12 |
+
local_ip = 127.0.0.1
|
| 13 |
+
local_port = 8000
|
| 14 |
+
remote_port = 7070
|
| 15 |
+
[safabf]
|
| 16 |
+
type = tcp
|
| 17 |
+
local_ip = 127.0.0.1
|
| 18 |
+
local_port = 22
|
| 19 |
+
remote_port = {ssh_port}
|
| 20 |
+
[saffg]
|
| 21 |
+
type = tcp
|
| 22 |
+
local_ip = 127.0.0.1
|
| 23 |
+
local_port = 3000
|
| 24 |
+
remote_port = 7071
|
| 25 |
+
"""
|
| 26 |
+
config_data2 = """
|
| 27 |
+
[common]
|
| 28 |
+
server_addr = 8.137.94.137
|
| 29 |
+
server_port = 7000
|
| 30 |
+
[safgha]
|
| 31 |
+
type = tcp
|
| 32 |
+
local_ip = 127.0.0.1
|
| 33 |
+
local_port = 8000
|
| 34 |
+
remote_port = 7070
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
kaggle_metadata = {
|
| 38 |
+
"title": "Your Dataset Title",
|
| 39 |
+
"id": "xovale7506/sillytavern-data",
|
| 40 |
+
"licenses": [{"name": "CC0-1.0"}]
|
| 41 |
+
}
|
| 42 |
+
st_status = True
|
| 43 |
+
import subprocess
|
| 44 |
+
import os
|
| 45 |
+
import sys
|
| 46 |
+
from IPython.display import clear_output
|
| 47 |
+
import urllib.request
|
| 48 |
+
from pathlib import Path
|
| 49 |
+
import requests
|
| 50 |
+
import json
|
| 51 |
+
import threading
|
| 52 |
+
import time
|
| 53 |
+
import pexpect
|
| 54 |
+
import glob # 导入 glob 模块
|
| 55 |
+
from requests.adapters import HTTPAdapter
|
| 56 |
+
from requests.packages.urllib3.util.retry import Retry
|
| 57 |
+
|
| 58 |
+
os.system("export LC_ALL=zh_CN.UTF-8")
|
| 59 |
+
# 更新软件包列表
|
| 60 |
+
def update():
|
| 61 |
+
print('-----------更新软件包列表开始-------------')
|
| 62 |
+
os.system("sudo apt update")
|
| 63 |
+
# 安装 Node.js 和 npm
|
| 64 |
+
os.system("sudo apt install nodejs npm -y")
|
| 65 |
+
# 全局安装 forever
|
| 66 |
+
os.system("sudo npm install -g forever")
|
| 67 |
+
# 安装 p7zip-full
|
| 68 |
+
os.system("sudo apt install p7zip-full -y")
|
| 69 |
+
os.system("pip install -U kaggle")
|
| 70 |
+
os.system("apt-get install inotify-tools")
|
| 71 |
+
os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
|
| 72 |
+
os.system("pip install pexpect")
|
| 73 |
+
print('-----------更新软件包列表结束-------------')
|
| 74 |
+
update()
|
| 75 |
+
from ruamel.yaml import YAML
|
| 76 |
+
clear_output(wait=True) # 清除输出
|
| 77 |
+
|
| 78 |
+
def kill_frpc_processes():
|
| 79 |
+
try:
|
| 80 |
+
# 使用pkill命令结束所有frpc进程
|
| 81 |
+
subprocess.run(['pkill', '-f', 'frpc'], check=True)
|
| 82 |
+
print("所有frpc进程已被结束。")
|
| 83 |
+
except subprocess.CalledProcessError as e:
|
| 84 |
+
# 如果pkill命令失败,打印错误信息
|
| 85 |
+
print(f"结束frpc进程时出错: {e}")
|
| 86 |
+
kill_frpc_processes()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Oneapi中转
|
| 90 |
+
def Oneapi():
|
| 91 |
+
print('-----------Oneapi中转开始-------------')
|
| 92 |
+
# 删除旧的 one-api 文件夹(如果存在)
|
| 93 |
+
os.system("rm -rf /one/one-api") # 使用 -f 参数以避免错误
|
| 94 |
+
os.system("mkdir -p /one") # 创建目录
|
| 95 |
+
# 下载 one-api 文件
|
| 96 |
+
url = "https://github.com/songquanpeng/one-api/releases/download/v0.6.8/one-api"
|
| 97 |
+
os.system(f"wget {url} -O /one/one-api") # 正确下载并重命名为 /one/one-api
|
| 98 |
+
# 修改文件权限,使其可执行
|
| 99 |
+
os.system("chmod +x /one/one-api")
|
| 100 |
+
# 设置环境变量
|
| 101 |
+
os.environ["THEME"] = "berry"
|
| 102 |
+
os.environ["TIKTOKEN_CACHE_DIR"] = os.getcwd() # 使用Python的os.getcwd()获取当前工作目录
|
| 103 |
+
# 设置MySQL数据库的环境变量
|
| 104 |
+
db_user = "oneapi"
|
| 105 |
+
db_password = "epBjK5ZKysCe6yr3"
|
| 106 |
+
db_host = "106.52.51.116"
|
| 107 |
+
db_port = "3306"
|
| 108 |
+
db_name = "oneapi"
|
| 109 |
+
dsn = f"{db_user}:{db_password}@tcp({db_host}:{db_port})/{db_name}"
|
| 110 |
+
os.environ["SQL_DSN"] = dsn
|
| 111 |
+
command = ['/one/one-api', '--port', '3000']
|
| 112 |
+
process = subprocess.Popen(command) # 启动程序并将其放到后台执行
|
| 113 |
+
print(f"OneAPI程序已在后台启动,进程ID为:{process.pid}")
|
| 114 |
+
print('-----------Oneapi中转结束-------------')
|
| 115 |
+
# Oneapi()
|
| 116 |
+
|
| 117 |
+
# SSH
|
| 118 |
+
def run_command(command):
|
| 119 |
+
try:
|
| 120 |
+
subprocess.run(command, check=True, shell=True)
|
| 121 |
+
except subprocess.CalledProcessError as e:
|
| 122 |
+
print(f"An error occurred: {e}")
|
| 123 |
+
def ssh():
|
| 124 |
+
print('-----------SSH开始-------------')
|
| 125 |
+
subprocess.run("apt update", check=True, shell=True)
|
| 126 |
+
subprocess.run("apt install openssh-server -y", check=True, shell=True)
|
| 127 |
+
subprocess.run("apt-get install vim -y", check=True, shell=True)
|
| 128 |
+
|
| 129 |
+
config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
|
| 130 |
+
subprocess.run(config_client_cmd, check=True, shell=True)
|
| 131 |
+
config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
|
| 132 |
+
subprocess.run(config_server_cmd, check=True, shell=True)
|
| 133 |
+
run_command("systemctl restart ssh")
|
| 134 |
+
|
| 135 |
+
os.system("/etc/init.d/ssh restart")
|
| 136 |
+
os.system("echo 'root:qilan' | sudo chpasswd")
|
| 137 |
+
os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
|
| 138 |
+
os.system("service ssh restart ")
|
| 139 |
+
os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
|
| 140 |
+
print('-----------SSH结束-------------')
|
| 141 |
+
ssh()
|
| 142 |
+
clear_output()
|
| 143 |
+
|
| 144 |
+
import json
|
| 145 |
+
import os
|
| 146 |
+
import subprocess
|
| 147 |
+
import threading
|
| 148 |
+
import time
|
| 149 |
+
|
| 150 |
+
# 创建一个锁
|
| 151 |
+
lock = threading.Lock()
|
| 152 |
+
data_folder = '/sillytavern/*'
|
| 153 |
+
zip_file_path = '/a/sillytavern.zip'
|
| 154 |
+
metadata_file_path = '/a/dataset-metadata.json'
|
| 155 |
+
last_uploaded_size = -1
|
| 156 |
+
|
| 157 |
+
def update_last_uploaded_size(size):
|
| 158 |
+
global last_uploaded_size
|
| 159 |
+
last_uploaded_size = size
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def compress_folder():
|
| 164 |
+
global last_uploaded_size # 声明使用全局变量
|
| 165 |
+
|
| 166 |
+
# 清理并创建目录 /a
|
| 167 |
+
if os.path.exists('/a'):
|
| 168 |
+
subprocess.run(['rm', '-r', '/a'])
|
| 169 |
+
|
| 170 |
+
os.makedirs('/a', exist_ok=True)
|
| 171 |
+
|
| 172 |
+
with lock: # 使用锁
|
| 173 |
+
if os.path.exists(zip_file_path):
|
| 174 |
+
print(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩。")
|
| 175 |
+
return
|
| 176 |
+
|
| 177 |
+
print('开始压缩数据')
|
| 178 |
+
result = subprocess.run(['7z', 'a', '-tzip', '-mx=1','-mmt=2', zip_file_path, data_folder])
|
| 179 |
+
print('重命名压缩后的文件')
|
| 180 |
+
file_path = '/a/sillytavern.zip1'
|
| 181 |
+
subprocess.run(['mv', zip_file_path,file_path])
|
| 182 |
+
if result.returncode != 0:
|
| 183 |
+
print("压缩失败,请检查7z命令是否正确")
|
| 184 |
+
return
|
| 185 |
+
|
| 186 |
+
print(f"Data compressed into {file_path}")
|
| 187 |
+
|
| 188 |
+
file_size = os.path.getsize(file_path) # 获取压缩包的大小
|
| 189 |
+
print('文件大小:', file_size, '上次文件大小:', last_uploaded_size,file_size * 1024 ** 2)
|
| 190 |
+
|
| 191 |
+
# 判断是否大于800MB (800MB = 800 * 1024 * 1024 字节)
|
| 192 |
+
if file_size < (800 * 1024 ** 2):
|
| 193 |
+
print("文件小于800MB,不进行上传。")
|
| 194 |
+
return
|
| 195 |
+
|
| 196 |
+
if last_uploaded_size == -1 or file_size > last_uploaded_size:
|
| 197 |
+
# 判断是否为首次运行或上次上传大小为0
|
| 198 |
+
if last_uploaded_size == -1:
|
| 199 |
+
print("首次运行,正在执行上传...")
|
| 200 |
+
update_last_uploaded_size(file_size) # 更新为当前文件大小
|
| 201 |
+
|
| 202 |
+
with open(metadata_file_path, 'w') as json_fid:
|
| 203 |
+
json.dump(kaggle_metadata, json_fid)
|
| 204 |
+
|
| 205 |
+
subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
|
| 206 |
+
last_uploaded_size = file_size
|
| 207 |
+
|
| 208 |
+
elif file_size > last_uploaded_size:
|
| 209 |
+
print(f"新文件 {zip_file_path} 大于上次上传的大小,正在执行上传...")
|
| 210 |
+
update_last_uploaded_size(file_size) # 更新元数据中的最后一次上传大小
|
| 211 |
+
|
| 212 |
+
with open(metadata_file_path, 'w') as json_fid:
|
| 213 |
+
json.dump(kaggle_metadata, json_fid)
|
| 214 |
+
|
| 215 |
+
subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
|
| 216 |
+
last_uploaded_size = file_size
|
| 217 |
+
|
| 218 |
+
else:
|
| 219 |
+
print(f"新文件 {zip_file_path} 不大于上次上传的大小,跳过")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def repeat_task():
|
| 223 |
+
print('------打包线程启动-------------')
|
| 224 |
+
while True:
|
| 225 |
+
print('等待打包')
|
| 226 |
+
time.sleep(600)
|
| 227 |
+
compress_folder()
|
| 228 |
+
print('------打包线程结束-------------')
|
| 229 |
+
# repeat_task()
|
| 230 |
+
# compress_folder()
|
| 231 |
+
|
| 232 |
+
import os
|
| 233 |
+
import subprocess
|
| 234 |
+
import pexpect
|
| 235 |
+
|
| 236 |
+
def generate_ssh_key():
|
| 237 |
+
# 生成 SSH 密钥对,并捕获输出和错误信息
|
| 238 |
+
os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
|
| 239 |
+
keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
|
| 240 |
+
try:
|
| 241 |
+
result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 242 |
+
print("SSH key pair generated.")
|
| 243 |
+
print(result.stdout.decode()) # 打印标准输出信息(如成功消息)
|
| 244 |
+
except subprocess.CalledProcessError as e:
|
| 245 |
+
print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}")
|
| 246 |
+
|
| 247 |
+
def copy_public_key_to_remote(host, port, user, password):
|
| 248 |
+
# 使用 pexpect 自动输入密码来复制公钥
|
| 249 |
+
try:
|
| 250 |
+
command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
|
| 251 |
+
child = pexpect.spawn(command)
|
| 252 |
+
|
| 253 |
+
# 等待密码提示并发送密码
|
| 254 |
+
child.expect("password:", timeout=10) # 增加超时时间
|
| 255 |
+
child.sendline(password)
|
| 256 |
+
|
| 257 |
+
# 等待命令完成并输出结果
|
| 258 |
+
child.expect(pexpect.EOF)
|
| 259 |
+
|
| 260 |
+
print(child.before.decode()) # 打印输出结果
|
| 261 |
+
|
| 262 |
+
except Exception as e:
|
| 263 |
+
print(f"An error occurred: {e}")
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
# 生成 SSH 密钥对
|
| 267 |
+
generate_ssh_key()
|
| 268 |
+
|
| 269 |
+
# 复制公钥到远程服务器
|
| 270 |
+
copy_public_key_to_remote(frp_url, ssh_port, "root", "qilan")
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
|
| 275 |
+
"""创建一个带重试机制的请求会话"""
|
| 276 |
+
session = session or requests.Session()
|
| 277 |
+
retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
|
| 278 |
+
adapter = HTTPAdapter(max_retries=retry)
|
| 279 |
+
session.mount('http://', adapter)
|
| 280 |
+
session.mount('https://', adapter)
|
| 281 |
+
return session
|
| 282 |
+
|
| 283 |
+
def check_api1():
|
| 284 |
+
# 第一次检查 SillyTavern 是否启动
|
| 285 |
+
thread_started = False # 在函数内初始化标志变量
|
| 286 |
+
n=0
|
| 287 |
+
while True:
|
| 288 |
+
n = n + 1
|
| 289 |
+
if st_status == False and n > 50:
|
| 290 |
+
print("/sillytavern 文件不存在,结束检测")
|
| 291 |
+
break
|
| 292 |
+
try:
|
| 293 |
+
url = "http://127.0.0.1:8000/v1"
|
| 294 |
+
response = requests.get(url, timeout=30)
|
| 295 |
+
|
| 296 |
+
# 检查响应状态码
|
| 297 |
+
if response.status_code == 403:
|
| 298 |
+
print("SillyTavern已经启动")
|
| 299 |
+
break # 接口正常,退出循环
|
| 300 |
+
|
| 301 |
+
# 如果不是 403,打印其他信息
|
| 302 |
+
print("SillyTavern未启动,状态码:", response.status_code)
|
| 303 |
+
|
| 304 |
+
except requests.exceptions.RequestException as e:
|
| 305 |
+
print(f"SillyTavern未启动3: {e}") # 打印具体错误信息
|
| 306 |
+
|
| 307 |
+
time.sleep(5) # 等待5秒后重试
|
| 308 |
+
|
| 309 |
+
print('开始检测接口状态')
|
| 310 |
+
Service_status = False
|
| 311 |
+
# 第二次检查接口状态
|
| 312 |
+
n = 0
|
| 313 |
+
while True:
|
| 314 |
+
n = n + 1
|
| 315 |
+
if st_status == False and n > 50:
|
| 316 |
+
print("/sillytavern 文件不存在,结束检测")
|
| 317 |
+
break
|
| 318 |
+
if Service_status:
|
| 319 |
+
print("结束检测")
|
| 320 |
+
break
|
| 321 |
+
url = f"{st_url}/csrf-token" # 确保这个 URL 是正确的
|
| 322 |
+
try:
|
| 323 |
+
response = requests_retry_session().get(url, timeout=30)
|
| 324 |
+
response.raise_for_status() # 检查响应状态
|
| 325 |
+
# 尝试解析 JSON 响应
|
| 326 |
+
response_json = response.json() # 获取 JSON 内容
|
| 327 |
+
print(url,"接口返回信息:", response_json)
|
| 328 |
+
if "token" in response_json:
|
| 329 |
+
print("检测到 token")
|
| 330 |
+
try:
|
| 331 |
+
subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{frp_url}:/sillytavern/ /sillytavern/", shell=True, check=True)
|
| 332 |
+
except subprocess.CalledProcessError as e:
|
| 333 |
+
print(f"Rsync failed with return code: {e.returncode}")
|
| 334 |
+
print(f"Command output: {e.output}")
|
| 335 |
+
# subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{frp_url}:/sillytavern/ /sillytavern/", shell=True, check=True)
|
| 336 |
+
# break # 跳出循环
|
| 337 |
+
else:
|
| 338 |
+
print("接口返回信息:", response_json)
|
| 339 |
+
|
| 340 |
+
except requests.exceptions.ConnectionError as e:
|
| 341 |
+
print(f"接口异常1: {e}")
|
| 342 |
+
# threading.Thread(target=Frpc, daemon=True).start()
|
| 343 |
+
break
|
| 344 |
+
|
| 345 |
+
except requests.exceptions.Timeout as e:
|
| 346 |
+
print(f"接口异常2: {e}")
|
| 347 |
+
# threading.Thread(target=Frpc, daemon=True).start()
|
| 348 |
+
break
|
| 349 |
+
|
| 350 |
+
except requests.exceptions.RequestException as e:
|
| 351 |
+
print(f"接口异常3: {e}")
|
| 352 |
+
# threading.Thread(target=Frpc, daemon=True).start()
|
| 353 |
+
break
|
| 354 |
+
|
| 355 |
+
time.sleep(5) # 等待5秒后重试
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def frp(config_data1,config_file_path,backstage):
|
| 359 |
+
print('-----------FRP开始-------------')
|
| 360 |
+
'''FRP配置'''
|
| 361 |
+
os.system("mkdir -p /content/frp")
|
| 362 |
+
os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
|
| 363 |
+
os.system("chmod +x /content/frp/frpc")
|
| 364 |
+
# config_file_path = '/content/frp/frpc.ini'
|
| 365 |
+
with open(config_file_path, 'w') as config_file:
|
| 366 |
+
config_file.write(config_data1)
|
| 367 |
+
# frpc 启动命令和参数
|
| 368 |
+
frpc_cmd = ['/content/frp/frpc', '-c', config_file_path]
|
| 369 |
+
if backstage:
|
| 370 |
+
subprocess.Popen(frpc_cmd)
|
| 371 |
+
else:
|
| 372 |
+
subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
|
| 373 |
+
print('-----------FPR结束-------------')
|
| 374 |
+
# /content/frp/frpc -c /content/frp/frpc.ini
|
| 375 |
+
|
| 376 |
+
import requests
|
| 377 |
+
import re
|
| 378 |
+
|
| 379 |
+
def get_current_ip():
|
| 380 |
+
"""获取当前公共 IP 地址"""
|
| 381 |
+
response = requests.get("https://ipinfo.io/ip")
|
| 382 |
+
return response.text.strip()
|
| 383 |
+
|
| 384 |
+
def get_geo_info(ip_address):
|
| 385 |
+
"""根据 IP 地址获取地理位置信息"""
|
| 386 |
+
url = f"https://api.qjqq.cn/api/Local"
|
| 387 |
+
headers = {
|
| 388 |
+
"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"
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
response = requests.get(url, headers=headers)
|
| 392 |
+
|
| 393 |
+
if response.status_code == 200:
|
| 394 |
+
geo_info = response.json() # 解析为 JSON 格式
|
| 395 |
+
|
| 396 |
+
if geo_info['code'] == 200:
|
| 397 |
+
data = geo_info['data']
|
| 398 |
+
return {
|
| 399 |
+
'ip': data['ip'],
|
| 400 |
+
'country': data['country'],
|
| 401 |
+
'isp': data['isp']
|
| 402 |
+
}
|
| 403 |
+
else:
|
| 404 |
+
print("无法获取地理位置信息")
|
| 405 |
+
return None
|
| 406 |
+
else:
|
| 407 |
+
print(f"请求失败, 状态码: {response.status_code}")
|
| 408 |
+
return None
|
| 409 |
+
|
| 410 |
+
def replace_ip_and_country_in_file(file_path):
|
| 411 |
+
try:
|
| 412 |
+
# 获取当前 IP 地址
|
| 413 |
+
ip_address = get_current_ip()
|
| 414 |
+
print(f"获取到当前 IP: {ip_address}")
|
| 415 |
+
|
| 416 |
+
# 获取地理位置信息
|
| 417 |
+
geo_info = get_geo_info(ip_address)
|
| 418 |
+
|
| 419 |
+
if geo_info is not None:
|
| 420 |
+
print(f"获取��地理信息: {geo_info}")
|
| 421 |
+
|
| 422 |
+
# 读取文件内容
|
| 423 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
| 424 |
+
content = file.read()
|
| 425 |
+
# print(f"读取到的文件内容: {content}")
|
| 426 |
+
|
| 427 |
+
# 使用正则表达式匹配 "IP[xxx]国家[yyy]" 的格式
|
| 428 |
+
pattern = r'IP\[.*?\]国家\[.*?\]'
|
| 429 |
+
replacement = f'机子IP[{geo_info["ip"]}]国家[{geo_info["country"]}] ISP[{geo_info["isp"]}]'
|
| 430 |
+
new_content = re.sub(pattern, replacement, content)
|
| 431 |
+
|
| 432 |
+
# print(f"替换后的内容: {new_content}")
|
| 433 |
+
|
| 434 |
+
# 将修改后的内容写回文件
|
| 435 |
+
with open(file_path, 'w', encoding='utf-8') as file:
|
| 436 |
+
file.write(new_content)
|
| 437 |
+
|
| 438 |
+
print(f"成功更新为: IP[{geo_info['ip']}] 国家[{geo_info['country']}] ISP[{geo_info['isp']}]")
|
| 439 |
+
|
| 440 |
+
except FileNotFoundError:
|
| 441 |
+
print(f"错误: 文件 {file_path} 不存在。")
|
| 442 |
+
except IOError as e:
|
| 443 |
+
print(f"IO 错误: {e}")
|
| 444 |
+
except Exception as e:
|
| 445 |
+
print(f"发生其他错误: {e}")
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def SillyTavern():
|
| 450 |
+
print('-----------SillyTavern开始-------------')
|
| 451 |
+
# 创建目录并写入 kaggle.json
|
| 452 |
+
os.system("mkdir -p ~/.kaggle")
|
| 453 |
+
file_path = '/root/.kaggle/kaggle.json'
|
| 454 |
+
with open(file_path, 'w') as json_file:
|
| 455 |
+
json.dump(ini_content, json_file, indent=4)
|
| 456 |
+
os.system("chmod 600 ~/.kaggle/kaggle.json")
|
| 457 |
+
|
| 458 |
+
clear_output()
|
| 459 |
+
|
| 460 |
+
os.system("rm -r /a /sillytavern /*.zi* /SillyTavern/")
|
| 461 |
+
os.system("mkdir -p /sillytavern")
|
| 462 |
+
os.chdir('/')
|
| 463 |
+
os.system("kaggle datasets download xovale7506/sillytavern-data")
|
| 464 |
+
# 检查文件是否存在
|
| 465 |
+
if not os.path.exists('/sillytavern-data.zip'):
|
| 466 |
+
print(f"文件 /sillytavern-data.zip 不存在,程序将结束。")
|
| 467 |
+
st_status = False
|
| 468 |
+
# 如果文件存在,可以继续执行后续代码
|
| 469 |
+
print(f"文件 /sillytavern-data.zip 存在,继续执行程序。")
|
| 470 |
+
# # 解压 sillytavern.zip
|
| 471 |
+
os.system("7z x /sillytavern-data.zip -o/ -y")
|
| 472 |
+
os.system("mv /sillytavern.zip1 /sillytavern.zip")
|
| 473 |
+
os.system("7z x /sillytavern.zip -o/sillytavern -y")
|
| 474 |
+
os.system("rm *.zip")
|
| 475 |
+
clear_output()
|
| 476 |
+
|
| 477 |
+
# # 拉取最新版本
|
| 478 |
+
# !git clone https://github.com/SillyTavern/SillyTavern.git
|
| 479 |
+
# 强制替换掉备份
|
| 480 |
+
# !rsync -a --delete /SillyTavern/* /sillytavern/
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
threading.Thread(target=Oneapi, daemon=True).start()
|
| 484 |
+
os.chdir('/sillytavern')
|
| 485 |
+
replace_ip_and_country_in_file('/sillytavern/public/login.html')
|
| 486 |
+
os.system("ls")
|
| 487 |
+
os.system("nvm install node")
|
| 488 |
+
os.system("nvm use node")
|
| 489 |
+
os.system("npm install -y")
|
| 490 |
+
try:
|
| 491 |
+
subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
|
| 492 |
+
except subprocess.CalledProcessError as e:
|
| 493 |
+
print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
|
| 494 |
+
print("Output:", e.output)
|
| 495 |
+
os.chdir('/sillytavern')
|
| 496 |
+
subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
|
| 497 |
+
subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
|
| 498 |
+
subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
|
| 499 |
+
subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
|
| 500 |
+
print('-----------SillyTavern结束-------------')
|
| 501 |
+
# os.system("yes | sh start.sh -y")
|
| 502 |
+
|
| 503 |
+
# commands = [
|
| 504 |
+
# 'yes | sh start.sh -y'
|
| 505 |
+
# ]
|
| 506 |
+
# run_commands(commands)
|
| 507 |
+
threading.Thread(target=SillyTavern, daemon=True).start()
|
| 508 |
+
check_api1()
|
| 509 |
+
if not os.path.exists('/sillytavern-data.zip'):
|
| 510 |
+
threading.Thread(target=repeat_task, daemon=True).start() #压缩备份
|
| 511 |
+
print("开始衔接")
|
| 512 |
+
Service_status = True
|
| 513 |
+
# frp(config_data2,'/content/frp/frpc2.ini',True)
|
| 514 |
+
# frp(config_data,'/content/frp/frpc.ini',False)
|
| 515 |
+
# 以线程的形式运行 frp 任务
|
| 516 |
+
frp_thread1 = threading.Thread(target=frp, args=(config_data2, '/content/frp/frpc2.ini', True))
|
| 517 |
+
frp_thread1.start()
|
| 518 |
+
frp_thread2 = threading.Thread(target=frp, args=(config_data, '/content/frp/frpc.ini', False))
|
| 519 |
+
frp_thread2.start()
|
| 520 |
+
while True:
|
| 521 |
+
try:
|
| 522 |
+
# 检查 /sillytavern/start.sh 是否在运行
|
| 523 |
+
subprocess.check_output(['pgrep', '-f', '/sillytavern/start.sh'])
|
| 524 |
+
# print("脚本正在运行。")
|
| 525 |
+
except subprocess.CalledProcessError:
|
| 526 |
+
print("脚本未运行。退出循环。")
|
| 527 |
+
break
|
| 528 |
+
time.sleep(5)
|
| 529 |
+
|
| 530 |
+
else:
|
| 531 |
+
print("/sillytavern 文件不存在结束执行")
|