File size: 25,887 Bytes
1425ee0 7bdaeaf 9ee8ec4 1425ee0 2efdbd3 5536ee6 2efdbd3 dbf65d9 2efdbd3 5536ee6 1425ee0 1321b01 1425ee0 33f3911 1425ee0 33f3911 1425ee0 1321b01 c398bf8 1321b01 1425ee0 8cdb843 1425ee0 8cdb843 1425ee0 46e33eb 1425ee0 8cdb843 1425ee0 |
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 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 |
# 实时监控日志
#tail -f /data/server10.log
# 查找端口进程
#lsof -i :8000
# 查找server.py进程
#ps aux | grep server.py
#source /opt/venv/bin/activate
#python a.py
huggingface_user="sadww"#
huggingface_id="xxrys11"
huggingface_tokon="hf_DRZCztytLEC uYjUVsFWIMxqnFgZIiVDERM"
ini_content = {"username":"rvbpm6lm","key":"3c17fa4e8261ab5fe7ddea63f2560516"}
frp_url = '119.8.118.149'
ssh_port = '7082'
ssh_url = '45.32.68.209'
st_url = f'http://{frp_url}:7092'
huggingface_name = 'rvbpm6lm'
huggingface_Data_name = 'qilan-st11'
data_folder = '/data/SillyTavern' # 要压缩的目录
zip_file_path = '/dev/shm/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
metadata_file_path = '/dev/shm/a/dataset-metadata.json'
configs = [
("""
[common]
server_addr = 47.237.156.222
server_port = 7000
[safsa11]
type = tcp
local_ip = 127.0.0.1
local_port = 8000
remote_port = 7092
""", '/data/frp/frpc.ini'),
("""
[common]
server_addr = 47.74.57.131
server_port=7000
[4kxdde11]
type=tcp
local_ip=127.0.0.1
local_port=8000
remote_port=7092
""", '/data/frp/frpc6.ini'),
("""
[common]
server_addr = 8.219.236.184
server_port=7000
[safsa11]
type=tcp
local_ip=127.0.0.1
local_port=8000
remote_port=7092
""", '/data/frp/frpc8.ini'),
("""
[common]
server_addr = 43.159.47.227
server_port=7000
[safsa11]
type=tcp
local_ip=127.0.0.1
local_port=8000
remote_port=7092
""", '/data/frp/frpc9.ini'),
("""
[common]
server_addr = 47.243.129.107
server_port=7000
[4kktyuu11]
type=tcp
local_ip=127.0.0.1
local_port=8000
remote_port=7092
""", '/data/frp/frpc7.ini')
]
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
import configparser
# from IPython.display import clear_output
import urllib.request
from pathlib import Path
import requests
import json
import threading
import time
import pexpect
import socket
import time
import glob # 导入 glob 模块
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import logging
from datetime import datetime
import psutil
from typing import List, Dict
import pytz
# 创建 FRP 文件夹并下载 frpc 可执行文件。
os.system("wget -q https://huggingface.co/datasets/Qilan2/st-server/raw/main/ip_huggingface.py -O /data/ip_huggingface.py")
os.system("wget -q https://huggingface.co/datasets/Qilan2/st-server/resolve/main/ipn.py?download=true -O /data/ipn.py")
os.system("wget -q https://huggingface.co/datasets/Qilan2/st-server/resolve/main/hf-jg/11.py?download=true -O /data/sbx.py")
os.system("mkdir -p /data/frp")
os.system("wget /data/frp/frpc -q https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /data/frp/frpc")
os.system("chmod +x /data/frp/frpc")
os.system("wget -q https://huggingface.co/datasets/Qilan2/st-server/resolve/main/xugou-agent-linux-amd64?download=true -O /data/xugou-agent")
os.system("chmod +x /data/xugou-agent")
# os.system('nohup /data/xugou-agent start --server "https://tz.282820.xyz" --token "xugou_meqz1qus_80244ac171f1d9cf3a1ead6be2ecf86f.7d4ae786cbb7e559" --interval "30" > /data/xugou-agent.log 2>&1 &')
# os.system("wget -O '/data/nezha-agent-amd64' 'https://huggingface.co/datasets/Qilan2/st-server/resolve/main/nezha-agent-v0.17.6?download=true'")
# os.system("chmod +x /data/nezha-agent-amd64")
# os.system('nohup /data/nezha-agent-amd64 -s tzz.282820.xyz:443 -p aLLlygYqAXgjq9Anln --tls --debug --temperature --disable-force-update --disable-auto-update > nezha-agent-amd64.log 2>&1 &')
# os.system('/data/nezha-agent-amd64 -s tzz.282820.xyz:443 -p aLLlygYqAXgjq9Anln --tls --debug --temperature --disable-force-update --disable-auto-update')
import yaml
def nezha():
agent_config ={
'client_secret': 'MLcD6YnifhoY08B9n129UP5cg2139NYa',
'debug': False,
'disable_auto_update': True,
'disable_command_execute': False,
'disable_force_update': False,
'disable_nat': False,
'disable_send_query': False,
'gpu': False,
'insecure_tls': False,
'ip_report_period': 1800,
'report_delay': 3,
'self_update_period': 0,
'server': 'z.282820.xyz:443',
'skip_connection_count': False,
'skip_procs_count': False,
'temperature': True,
'tls': True,
'use_gitee_to_upgrade': False,
'use_ipv6_country_code': False,
'uuid': '172528d0-a303-4096-b8d3-df117b8e1c4b'
}
with open('./config.yaml', 'w') as file:
yaml.dump(agent_config, file, default_flow_style=False)
os.system("rm -rf f1")
os.system("wget -O 'f1' -q 'https://huggingface.co/datasets/Qilan2/st-server/resolve/main/nv1amd64?download=true'")
os.system("chmod +x f1")
os.system('./f1 -c ./config.yaml')
os.system('./f1 -c ./config.yaml')
def cloudflared():
os.system("rm -r /data/cloudflared-linux-amd64")
os.system("wget -O '/data/cloudflared-linux-amd64' -q 'https://github.com/cloudflare/cloudflared/releases/download/2025.9.0/cloudflared-linux-amd64'")
os.system("chmod +x /data/cloudflared-linux-amd64")
os.system('/data/cloudflared-linux-amd64 tunnel run --token eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiMzg0OWFhNjgtMDJhMS00YWYyLWEzMTMtYzQ3ZmRiYTRjNzE3IiwicyI6IlpUTTRZemRsT1RFdE5tVXhOUzAwTlRVeUxUbGhZbUV0TmpFM09UWm1NR1ExTkdJMCJ9')
def sbx():
os.system("python /data/sbx.py")
threading.Thread(target=nezha, daemon=True).start()
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()
# 创建一个锁
lock = threading.Lock()
last_uploaded_size = -1
def update_last_uploaded_size(size):
global last_uploaded_size
last_uploaded_size = size
def get_folder_size(folder):
"""使用 du 命令获取文件夹的总大小(字节数)"""
result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0:
size = result.stdout.split()[0] # 获取大小
return int(size)
else:
print(f"Error calculating size: {result.stderr.decode()}")
return 0
def compress_folder():
global last_uploaded_size # 声明使用全局变量
# 检查是否是中国时区早上5点
china_tz = pytz.timezone('Asia/Shanghai')
now = datetime.now(china_tz)
if now.hour == 5:
print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 早上5点,跳过备份操作")
return
# 清理并创建目录 /a
if os.path.exists('/dev/shm/a'):
subprocess.run(['rm', '-rf', '/dev/shm/a'])
os.makedirs('/dev/shm/a', exist_ok=True)
with lock: # 使用锁
# 获取当前文件夹的大小
current_folder_size = get_folder_size(data_folder)
print(f"当前文件夹大小: {current_folder_size} 字节")
# 判断文件夹大小是否大于 800MB (800MB = 800 * 1024 * 1024 字节)
if current_folder_size < (200 * 1024 ** 2):
print("文件夹小于800MB,不进行上传和压缩。")
return
# 如果是首次运行或者文件夹大小不同于上次上传,进行压缩
if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
print('开始压缩数据')
try:
# 执行压缩
result = subprocess.run(
# tar -cvf - /data/SillyTavern | pigz -p 2 -1 > /dev/shm/a/sillytavern.tar.gz 2> /dev/null
f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
shell=True,
check=True,
stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
)
except subprocess.CalledProcessError as e:
print(f"命令失败,返回代码: {e.returncode}")
return
print('压缩完成')
file_path = "/dev/shm/a/sillytavern.ctk"
subprocess.run(['mv', zip_file_path, file_path])
print(f"数据压缩为 {file_path}")
file_size = os.path.getsize(file_path) # 获取压缩包的大小
print('文件大小:', file_size)
if file_size < (200 * 1024 ** 2): # 判断压缩后的大小是否小于 800MB
print("压缩文件小于800MB,不进行上传。")
return
# 执行上传
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', '/dev/shm/a'])
#kaggle datasets version -m 'new version message' -p /dev/shm/a
last_uploaded_size = file_size
else:
print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...")
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', '/dev/shm/a'])
last_uploaded_size = file_size
else:
print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过")
def repeat_task():
print('------打包线程启动-------------')
while True:
print('等待打包')
# time.sleep(600)
time.sleep(10800)# 2小时
compress_folder()
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 kill_processes_on_port(port: int = 8000) -> Dict[str, List[int]]:
"""
结束指定端口的所有相关进程
Args:
port (int): 要处理的端口号,默认为8000
Returns:
Dict[str, List[int]]: 结束的进程信息
"""
killed_processes = {
'success': [],
'failed': []
}
try:
# 遍历所有进程
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
# 检查进程的连接
connections = proc.net_connections()
# 检查是否有指定端口的连接
port_matches = [
conn for conn in connections
if conn.laddr.port == port
]
if port_matches:
pid = proc.pid
name = proc.name()
print(f"找到端口 {port} 相关进程: PID {pid}, 名称 {name}")
try:
# 尝试优雅地终止进程
parent = psutil.Process(pid)
# 终止进程及其所有子进程
for child_proc in parent.children(recursive=True):
try:
child_proc.terminate()
print(f"终止子进程: PID {child_proc.pid}")
except Exception as child_err:
print(f"无法终止子进程 {child_proc.pid}: {child_err}")
parent.terminate()
# 等待进程结束
gone, alive = psutil.wait_procs([parent], timeout=3)
for p in alive:
print(f"强制杀死进程: PID {p.pid}")
p.kill()
killed_processes['success'].append(pid)
print(f"成功终止进程 {pid}")
except psutil.NoSuchProcess:
print(f"进程 {pid} 已不存在")
except psutil.AccessDenied:
print(f"没有权限终止进程 {pid}")
killed_processes['failed'].append(pid)
except Exception as e:
print(f"终止进程 {pid} 时发生错误: {e}")
killed_processes['failed'].append(pid)
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception as e:
print(f"搜索进程时发生错误: {e}")
# 打印总结报告
print("--- 进程终止报告 ---")
print(f"成功终止进程数: {len(killed_processes['success'])}")
print(f"终止失败进程数: {len(killed_processes['failed'])}")
if killed_processes['success']:
print(f"成功终止的进程 PID: {killed_processes['success']}")
if killed_processes['failed']:
print(f"终止失败的进程 PID: {killed_processes['failed']}")
return killed_processes
def check_api1():
# 第一次检查 SillyTavern 是否启动
thread_started = False
n = 0
while True:
n += 1
if not os.path.exists(data_folder):
logging.error(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
print("SillyTavern未启动,状态码:", response.status_code, n)
except requests.exceptions.RequestException as e:
print(f"SillyTavern未启动3: {e}, 尝试次数: {n}")
time.sleep(5)
print('ST本地已经运行')
def frp(configs, backstage):
print('-----------FRP开始-------------')
# 遍历所有配置并启动 FRP。
for config_data, config_file_path in configs:
with open(config_file_path, 'w') as config_file:
config_file.write(config_data)
# 启动 frpc 命令和参数。
frpc_cmd=['/data/frp/frpc', '-c', config_file_path]
if backstage:
subprocess.Popen(frpc_cmd)
else:
subprocess.run(f'/data/frp/frpc -c {config_file_path}', shell=True, check=True)
print('-----------FRP结束-------------')
def monitor_port():
while True:
url = "http://127.0.0.1:8000/v1"
response = requests.get(url, timeout=30)
if response.status_code != 403:
print("SillyTavern未运行,状态码:", response.status_code, n)
# 读取 config.ini 中的 monitor_port_enabled 配置项
config = configparser.ConfigParser()
config.read('/data/config.ini')
monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
if monitor_port_enabled:
kill_processes_on_port()
backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
backup_thread.start()
else:
print(f"monitor_port_enabled 为False跳过")
time.sleep(15) # 每5秒检查一次
def Run_SillyTavern():
try:
os.chdir('/data/SillyTavern')
# 启动 Node.js 服务器,并将输出重定向到 /dev/null
print('-----启动st-----')
os.system("yes | sh ./start.sh")
os.system("yes | sh ./start.sh")
os.system("yes | sh ./start.sh")
os.system("yes | sh ./start.sh")
os.system("yes | sh ./start.sh")
# subprocess.run(f'yes | sh ./start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
# subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
# subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
# subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
# subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
print("已尝试启动 server.js")
except subprocess.CalledProcessError as e:
print(f"命令失败,返回码: {e.returncode}")
except Exception as e: # 捕获所有其他异常
print(f"发生异常: {e}")
def SillyTavern():
print('-----------SillyTavern开始-------------')
# 创建目录并写入 kaggle.json
# 打印当前工作目录和用户主目录
print("Current Working Directory:", os.getcwd())
print("Home Directory:", os.path.expanduser('~'))
kaggle_dir = os.path.expanduser('~/.kaggle')
kaggle_file_path = os.path.join(kaggle_dir, 'kaggle.json')
# 确保目录存在
os.makedirs(kaggle_dir, exist_ok=True)
# 显式写入并验证
try:
with open(kaggle_file_path, 'w') as json_file:
json.dump(ini_content, json_file, indent=4)
# 验证文件内容
with open(kaggle_file_path, 'r') as json_file:
print("文件内容:", json_file.read())
# 设置权限
os.chmod(kaggle_file_path, 0o600)
print(f"文件已写入: {kaggle_file_path}")
except Exception as e:
print(f"发生错误: {e}")
os.system(f"rm -rf /a /data/sillytavern /data/data /data/*.zip /data/*.ctk")
# os.system(f"mkdir -p {data_folder}")
print('----当前文件夹路径--------')
os.system('pwd')
print('----进入/data--------')
os.chdir('/data')
print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
# os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
download_n = 0
while True:
# 执行下载命令
if download_n > 6:
break
os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /data")
# 检查文件是否存在
if os.path.exists(f'/data/{huggingface_Data_name}.zip'):
print(f"{huggingface_Data_name}.zip 下载成功!")
break # 跳出循环
print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
download_n += 1
time.sleep(300) # 等待一段时间再重试(例如5秒
# os.system('kaggle datasets download xovale7506/sillytavern-data2')
# 检查文件是否存在
if not os.path.exists(f'/data/{huggingface_Data_name}.zip'):
print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
else:
os.chdir('/data')
# 如果文件存在,可以继续执行后续代码
print('----/data文件夹内容--------')
# os.system("ls")
print(f"文件 /data/{huggingface_Data_name}.zip 存在,继续执行程序。")
# # 解压 sillytavern.zip
# os.system("rm *.zip")
os.system(f"7z x /data/{huggingface_Data_name}.zip -y")
# os.system("mv /data/sillytavern.tck sillytavern.tar.gz")
os.system("mv /data/sillytavern.ctk sillytavern.tar.gz")
# os.system("ls /data")
# os.system("tar -xvpf ./sillytavern.tar.gz -C / --use-compress-program=pigz")
# 使用标准 tar 解压
os.system("tar -xzf sillytavern.tar.gz --strip-components=1 -C /data")
# os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")
# os.system("mv /data/data/SillyTavern /data/SillyTavern")
print('更新npm')
print('----进入/data/SillyTavern--------')
os.chdir('/data/SillyTavern')
os.system("pwd")
# print('----/data/SillyTavern内容--------')
os.system(f"ls {data_folder}")
os.system("nvm install node")
os.system("nvm use node")
os.system("npm install -y")
# os.system("yes | sh ./start.sh")
# 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}")
# Run_SillyTavern()
backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
backup_thread.start()
# os.system(f"rm -rf /a /data/sillytavern /data/data /data/*.zip /data/*.ctk")
# os.system("ls /data/")
print('-----------SillyTavern结束-------------')
import requests
def _reconstruct_token(partial_token):
"""
重构完整的 token
:param partial_token: 部分 token
:return: 完整的 token
"""
return partial_token.replace(" ", "")
def restart_huggingface_space(space_name, space_id, partial_token):
"""
重启 Hugging Face Space
:param space_name: Space 的命名空间
:param space_id: Space 的 ID
:param partial_token: Hugging Face 部分访问令牌
:return: 响应结果字典
"""
# 重构完整 token
token = _reconstruct_token(partial_token)
url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
}
try:
response = requests.post(url, headers=headers, json={})
return {
"status_code": response.status_code,
"success": response.status_code == 200,
"message": response.text
}
except requests.RequestException as e:
return {
"status_code": None,
"success": False,
"message": str(e)
}
# 使用示例
import psutil
def check_system_resources():
print("查看CPU占用情况")
time.sleep(120)
# 获取CPU使用率
cpu_usage = psutil.cpu_percent(interval=1)
# 获取内存使用率
memory = psutil.virtual_memory()
memory_usage = memory.percent
# 检查CPU和内存占用是否超过85%
# if cpu_usage >= 90:
if cpu_usage >= 90 or memory_usage >= 95:
print("占用过高")
# 可选:打印具体的使用率
print(f"CPU使用率: {cpu_usage}%")
print(f"内存使用率: {memory_usage}%")
result = restart_huggingface_space(huggingface_user, huggingface_id, huggingface_tokon)
print(result)
# time.sleep(6666666)
else:
print("系统资源正常")
# 调用函数
threading.Thread(target=SillyTavern, daemon=True).start()
# SillyTavern()
time.sleep(60)
check_api1()
# compress_folder()
# 创建 ConfigParser 对象
config = configparser.ConfigParser()
# 添加一个 'general' 部分
config.add_section('general')
# 设置 'monitor_port_enabled' 选项的值为 True
config.set('general', 'monitor_port_enabled', 'True')
# 将配置写入到 'config.ini' 文件中
with open('/data/config.ini', 'w') as configfile:
config.write(configfile)
if os.path.exists(f'/data/{huggingface_Data_name}.zip'):
os.system(f"rm -rf /a /data/data /data/*.zip /data/*.ctk /data/*.gz")
backup_thread = threading.Thread(target=repeat_task, daemon=True)#压缩备份
backup_thread.start()
print("开始衔接")
Service_status = True
frp(configs, True)
threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
threading.Thread(target=check_system_resources, daemon=True).start()#检测CPU内存状态
threading.Thread(target=sbx, daemon=True).start()
os.system("python /data/ip_huggingface.py")
os.system("python /data/ipn.py")
# time.sleep(600)
while True:
# 检查是否是中国时区早上6点
china_tz = pytz.timezone('Asia/Shanghai')
now = datetime.now(china_tz)
if now.hour == 6 and now.minute < 5: # 6:00-6:05之间退出
print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 到达早上6点,退出循环")
break
# else:
# print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 未到达早上6点")
if backup_thread.is_alive() == False:
print("备份线程已停止.")
backup_thread = threading.Thread(target=repeat_task, daemon=True)
backup_thread.start()
time.sleep(5)
else:
print(f'{data_folder}/start.sh 文件不存在结束执行')
compress_folder()
result = restart_huggingface_space(huggingface_user, huggingface_id, huggingface_tokon)
print(result) |