Update ff1.py
Browse files
ff1.py
CHANGED
|
@@ -9,19 +9,78 @@ import psutil
|
|
| 9 |
import glob
|
| 10 |
import re
|
| 11 |
import pytz
|
|
|
|
|
|
|
| 12 |
|
|
|
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
def get_latest_local_package(directory, pattern='*.tar.gz'):
|
| 27 |
try:
|
|
@@ -45,15 +104,168 @@ def get_latest_local_package(directory, pattern='*.tar.gz'):
|
|
| 45 |
print(f"获取最新包时发生错误: {e}")
|
| 46 |
return None
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
def compress_folder(folder_path, output_dir, keep_count=3):
|
| 49 |
try:
|
| 50 |
# 确保输出目录存在
|
| 51 |
os.makedirs(output_dir, exist_ok=True)
|
| 52 |
|
| 53 |
-
# 使用 pytz 获取中国时区的当前时间戳(毫秒级)
|
| 54 |
-
import pytz
|
| 55 |
-
from datetime import datetime
|
| 56 |
-
|
| 57 |
# 设置中国时区
|
| 58 |
china_tz = pytz.timezone('Asia/Shanghai')
|
| 59 |
|
|
@@ -66,10 +278,11 @@ def compress_folder(folder_path, output_dir, keep_count=3):
|
|
| 66 |
|
| 67 |
# 安全地提取时间戳
|
| 68 |
def extract_timestamp(filename):
|
| 69 |
-
# 提取文件名中的数字部分
|
| 70 |
match = re.search(r'(\d+)\.tar\.gz$', filename)
|
| 71 |
return int(match.group(1)) if match else 0
|
| 72 |
|
|
|
|
|
|
|
| 73 |
# 如果压缩包数量超过保留数量,删除最旧的
|
| 74 |
if len(existing_archives) >= keep_count:
|
| 75 |
# 按时间戳排序(从小到大,最旧的在前面)
|
|
@@ -81,15 +294,31 @@ def compress_folder(folder_path, output_dir, keep_count=3):
|
|
| 81 |
# 删除最旧的压缩包
|
| 82 |
for i in range(delete_count):
|
| 83 |
oldest_archive = existing_archives[i]
|
|
|
|
|
|
|
| 84 |
try:
|
|
|
|
| 85 |
os.remove(oldest_archive)
|
| 86 |
-
print(f"删除最旧的压缩包:{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
except Exception as e:
|
| 88 |
print(f"删除失败 {oldest_archive}: {e}")
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
# tar.gz 压缩
|
| 91 |
result = subprocess.run(
|
| 92 |
-
['tar', '-
|
| 93 |
capture_output=True,
|
| 94 |
text=True
|
| 95 |
)
|
|
@@ -119,8 +348,6 @@ def compress_folder(folder_path, output_dir, keep_count=3):
|
|
| 119 |
return None
|
| 120 |
|
| 121 |
|
| 122 |
-
# 调用函数
|
| 123 |
-
# new_archive = compress_folder('/data/dv1', 'nezha-hf')
|
| 124 |
def github(type):
|
| 125 |
if type == 1:
|
| 126 |
os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data')
|
|
@@ -133,33 +360,58 @@ def github(type):
|
|
| 133 |
os.system("ls")
|
| 134 |
latest_package = get_latest_local_package(f'/data/{HF_REPO}')
|
| 135 |
print(f"最新压缩包路径: {latest_package}")
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
|
| 142 |
if type == 2:
|
| 143 |
print(f"开始备份上传HF仓库:{HF_REPO}")
|
| 144 |
os.system("mkdir -p /data/f")
|
| 145 |
os.system("cp -rf /data/ff /data/f")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
os.system('git lfs prune')
|
|
|
|
|
|
|
| 147 |
# 备份上传仓库
|
| 148 |
-
new_archive_info = compress_folder('/data/f',
|
| 149 |
if new_archive_info:
|
| 150 |
new_archive, file_size_info = new_archive_info.split(' MB:')
|
| 151 |
-
|
| 152 |
os.system("pwd")
|
| 153 |
os.system(f'git add .')
|
| 154 |
os.system(f'git commit -m "{file_size_info}"')
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
os.system('git
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
else:
|
| 159 |
print("压缩失败,无法提交")
|
| 160 |
|
|
|
|
| 161 |
def _reconstruct_token(partial_token):
|
| 162 |
return partial_token.replace(" ", "")
|
|
|
|
| 163 |
def restart_huggingface_space(space_name, space_id, partial_token):
|
| 164 |
token = _reconstruct_token(partial_token)
|
| 165 |
url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
|
|
@@ -181,25 +433,28 @@ def restart_huggingface_space(space_name, space_id, partial_token):
|
|
| 181 |
"success": False,
|
| 182 |
"message": str(e)
|
| 183 |
}
|
|
|
|
|
|
|
| 184 |
def check_system_resources():
|
| 185 |
time.sleep(120)
|
| 186 |
cpu_usage = psutil.cpu_percent(interval=1)
|
| 187 |
memory = psutil.virtual_memory()
|
| 188 |
memory_usage = memory.percent
|
| 189 |
-
# if cpu_usage >= 90:
|
| 190 |
if cpu_usage >= 90 or memory_usage >= 95:
|
| 191 |
print("占用过高")
|
| 192 |
result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
|
| 193 |
print(result)
|
| 194 |
else:
|
| 195 |
print("系统资源正常")
|
| 196 |
-
|
|
|
|
| 197 |
def repeat_task():
|
| 198 |
print('备份线程启动')
|
| 199 |
while True:
|
| 200 |
print(f"打包时间:{BACKUP_TIME} 秒")
|
| 201 |
-
time.sleep(int(BACKUP_TIME))
|
| 202 |
github(2)
|
|
|
|
| 203 |
github(1)
|
| 204 |
|
| 205 |
if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('/data/ff/.mozilla/firefox/profiles.ini'):
|
|
@@ -210,6 +465,6 @@ if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('
|
|
| 210 |
github(2)
|
| 211 |
result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
|
| 212 |
print(result)
|
| 213 |
-
|
| 214 |
-
github(2)
|
| 215 |
# nv1_agent()
|
|
|
|
| 9 |
import glob
|
| 10 |
import re
|
| 11 |
import pytz
|
| 12 |
+
import requests
|
| 13 |
+
import json
|
| 14 |
|
| 15 |
+
DATA_JSON = os.environ.get('DATA_JSON', '')
|
| 16 |
|
| 17 |
+
def assign_vars_from_json(config: dict):
|
| 18 |
+
for key, value in config.items():
|
| 19 |
+
globals()[key] = value
|
| 20 |
|
| 21 |
+
if DATA_JSON: # 如果 DATA_JSON 有值
|
| 22 |
+
try:
|
| 23 |
+
config_dict = json.loads(DATA_JSON) # 解析 JSON 字符串
|
| 24 |
+
assign_vars_from_json(config_dict)
|
| 25 |
+
except json.JSONDecodeError:
|
| 26 |
+
raise ValueError("DATA_JSON 环境变量不是合法的 JSON 字符串")
|
| 27 |
+
else: # 如果 DATA_JSON 为空,就从单独的环境变量里取
|
| 28 |
+
BACKUP_TIME = os.environ.get('BACKUP_TIME', '1200') # 备份时间 10800秒 2小时
|
| 29 |
+
HF_USER1 = os.environ.get('HF_USER1', '') # HF 备份仓库的用户名
|
| 30 |
+
HF_REPO = os.environ.get('HF_REPO', '') # HF 备份的Models仓库名
|
| 31 |
+
HF_EMAIL = os.environ.get('HF_EMAIL', '') # HF的邮箱
|
| 32 |
+
HF_TOKEN1 = os.environ.get('HF_TOKEN1', '') # HF备份账号的TOKEN
|
| 33 |
+
|
| 34 |
+
HF_USER2 = os.environ.get('HF_USER2', '') # huggingface 用户名
|
| 35 |
+
HF_ID = os.environ.get('HF_ID', '') # huggingface space 名
|
| 36 |
+
HF_TOKON2 = os.environ.get('HF_TOKON2', '') # huggingface TOKEN
|
| 37 |
+
|
| 38 |
+
UUID = os.environ.get('UUID', 'a488076d-0ced-4a83-91c4-c498fce00cff') # UUID,如使用v1,在不同的平台部署需要修改,否则会覆盖
|
| 39 |
+
N_SERVER = os.environ.get('N_SERVER', 'z.282820.xyz:443')# N面板域名或ip,
|
| 40 |
|
| 41 |
+
|
| 42 |
+
def cf():
|
| 43 |
+
os.system("rm -r /data/cf")
|
| 44 |
+
os.system("wget -O '/data/cf' -q 'https://github.com/cloudflare/cloudflared/releases/download/2025.9.0/cloudflared-linux-amd64'")
|
| 45 |
+
os.system("chmod +x /data/cf")
|
| 46 |
+
# hf-ff.ql02.ggff.net
|
| 47 |
+
os.system('/data/cf tunnel run --token eyJhIjoiZWM1MTk5ZTYwZGYxYWI2YmM2OTdhMGYzMTA3YzY4NTUiLCJ0IjoiOTY0NDIwODgtN2RkOS00Y2IwLThhMDEtYTI1YzZmMjAwZjBlIiwicyI6Ik9XSmpNVFpsTjJZdE5UWTRNQzAwTW1VMkxUaGxaREV0T1RRNU1EZzROVFV3T0dFeiJ9')
|
| 48 |
+
|
| 49 |
+
UUID = os.environ.get('UUID', 'a488076d-0ced-4a83-91c4-c498fce00cff') # UUID,如使用v1,在不同的平台部署需要修改,否则会覆盖
|
| 50 |
+
N_SERVER = os.environ.get('NEZHA_SERVER', '')# N面板域名或ip,
|
| 51 |
+
def nv1():
|
| 52 |
+
agent_config = {
|
| 53 |
+
'client_secret': 'MLcD6YnifhoY08B9n129UP5cg2139NYa',
|
| 54 |
+
'debug': False,
|
| 55 |
+
'disable_auto_update': True,
|
| 56 |
+
'disable_command_execute': False,
|
| 57 |
+
'disable_force_update': False,
|
| 58 |
+
'disable_nat': False,
|
| 59 |
+
'disable_send_query': False,
|
| 60 |
+
'gpu': False,
|
| 61 |
+
'insecure_tls': False,
|
| 62 |
+
'ip_report_period': 1800,
|
| 63 |
+
'report_delay': 3,
|
| 64 |
+
'self_update_period': 0,
|
| 65 |
+
'server': 'z.282820.xyz:443',
|
| 66 |
+
'skip_connection_count': False,
|
| 67 |
+
'skip_procs_count': False,
|
| 68 |
+
'temperature': True,
|
| 69 |
+
'tls': True,
|
| 70 |
+
'use_gitee_to_upgrade': False,
|
| 71 |
+
'use_ipv6_country_code': False,
|
| 72 |
+
'uuid': UUID
|
| 73 |
+
}
|
| 74 |
+
with open('./config.yaml', 'w') as file:
|
| 75 |
+
yaml.dump(agent_config, file, default_flow_style=False)
|
| 76 |
+
|
| 77 |
+
os.system("cat ./config.yaml")
|
| 78 |
+
os.system("rm -rf f1")
|
| 79 |
+
os.system("wget -O 'f1' -q 'https://huggingface.co/datasets/Qilan2/st-server/resolve/main/nv1amd64?download=true'")
|
| 80 |
+
os.system("chmod +x f1")
|
| 81 |
+
os.system('./f1 -c ./config.yaml')
|
| 82 |
+
os.system('./f1 -c ./config.yaml')
|
| 83 |
+
threading.Thread(target=nv1, daemon=True).start()
|
| 84 |
|
| 85 |
def get_latest_local_package(directory, pattern='*.tar.gz'):
|
| 86 |
try:
|
|
|
|
| 104 |
print(f"获取最新包时发生错误: {e}")
|
| 105 |
return None
|
| 106 |
|
| 107 |
+
|
| 108 |
+
def delete_huggingface_lfs_file(filename, repo_id, token):
|
| 109 |
+
"""
|
| 110 |
+
通过Hugging Face API删除LFS文件记录
|
| 111 |
+
"""
|
| 112 |
+
try:
|
| 113 |
+
# 1. 查询LFS文件列表
|
| 114 |
+
url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
|
| 115 |
+
headers = {
|
| 116 |
+
"content-type": "application/json",
|
| 117 |
+
"Authorization": f"Bearer {token}",
|
| 118 |
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
response = requests.get(url, headers=headers)
|
| 122 |
+
if response.status_code != 200:
|
| 123 |
+
print(f"查询LFS文件失败: {response.status_code} - {response.text}")
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
lfs_files = response.json()
|
| 127 |
+
|
| 128 |
+
# 2. 查找匹配的文件
|
| 129 |
+
file_to_delete = None
|
| 130 |
+
for file_info in lfs_files:
|
| 131 |
+
if file_info.get('filename') == filename:
|
| 132 |
+
file_to_delete = file_info
|
| 133 |
+
break
|
| 134 |
+
|
| 135 |
+
if not file_to_delete:
|
| 136 |
+
print(f"未找到对应的LFS文件记录: {filename}")
|
| 137 |
+
return False
|
| 138 |
+
|
| 139 |
+
# 3. 删除LFS文件记录
|
| 140 |
+
file_oid = file_to_delete['fileOid']
|
| 141 |
+
delete_url = f"https://huggingface.co/api/models/{repo_id}/lfs-files/{file_oid}?rewriteHistory=true"
|
| 142 |
+
|
| 143 |
+
delete_response = requests.delete(delete_url, headers=headers)
|
| 144 |
+
if delete_response.status_code == 200:
|
| 145 |
+
print(f"成功删除LFS文件记录: {filename} (OID: {file_oid})")
|
| 146 |
+
return True
|
| 147 |
+
else:
|
| 148 |
+
print(f"删除LFS文件记录失败: {delete_response.status_code} - {delete_response.text}")
|
| 149 |
+
return False
|
| 150 |
+
|
| 151 |
+
except Exception as e:
|
| 152 |
+
print(f"删除LFS文件记录时出错: {e}")
|
| 153 |
+
return False
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def safe_git_cleanup(repo_path, files_to_remove):
|
| 157 |
+
"""
|
| 158 |
+
安全的Git清理,不会影响现有的备份文件
|
| 159 |
+
"""
|
| 160 |
+
try:
|
| 161 |
+
original_dir = os.getcwd()
|
| 162 |
+
os.chdir(repo_path)
|
| 163 |
+
|
| 164 |
+
print(f"执行安全Git清理: {files_to_remove}")
|
| 165 |
+
|
| 166 |
+
# 1. 首先确保工作目录是干净的
|
| 167 |
+
result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
|
| 168 |
+
if result.stdout.strip():
|
| 169 |
+
print("工作目录有未提交的更改,先提交...")
|
| 170 |
+
subprocess.run(['git', 'add', '.'], capture_output=True)
|
| 171 |
+
subprocess.run(['git', 'commit', '-m', '自动提交: 清理前的更改'], capture_output=True)
|
| 172 |
+
|
| 173 |
+
# 2. 只从Git索引中删除指定的文件,但不影响工作目录中的文件
|
| 174 |
+
for filename in files_to_remove:
|
| 175 |
+
if os.path.exists(filename):
|
| 176 |
+
print(f"从Git索引中删除 {filename} (文件仍保留在工作目录)")
|
| 177 |
+
subprocess.run(['git', 'rm', '--cached', filename], capture_output=True)
|
| 178 |
+
else:
|
| 179 |
+
print(f"文件 {filename} 不存在于工作目录,只清理Git引用")
|
| 180 |
+
|
| 181 |
+
# 3. 提交删除操作
|
| 182 |
+
if files_to_remove:
|
| 183 |
+
subprocess.run(['git', 'commit', '-m', f'清理已删除的文件: {", ".join(files_to_remove)}'], capture_output=True)
|
| 184 |
+
|
| 185 |
+
# 4. 执行GC清理但不删除最近的文件
|
| 186 |
+
subprocess.run(['git', 'gc', '--auto'], capture_output=True)
|
| 187 |
+
subprocess.run(['git', 'lfs', 'prune'], capture_output=True)
|
| 188 |
+
|
| 189 |
+
print("安全Git清理完成")
|
| 190 |
+
os.chdir(original_dir)
|
| 191 |
+
return True
|
| 192 |
+
|
| 193 |
+
except Exception as e:
|
| 194 |
+
print(f"安全Git清理时出错: {e}")
|
| 195 |
+
os.chdir(original_dir)
|
| 196 |
+
return False
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_remote_lfs_files(repo_id, token):
|
| 200 |
+
"""
|
| 201 |
+
获取远程所有的LFS文件列表
|
| 202 |
+
"""
|
| 203 |
+
try:
|
| 204 |
+
url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
|
| 205 |
+
headers = {
|
| 206 |
+
"content-type": "application/json",
|
| 207 |
+
"Authorization": f"Bearer {token}",
|
| 208 |
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
response = requests.get(url, headers=headers)
|
| 212 |
+
if response.status_code == 200:
|
| 213 |
+
return response.json()
|
| 214 |
+
else:
|
| 215 |
+
print(f"获取远程LFS文件失败: {response.status_code}")
|
| 216 |
+
return []
|
| 217 |
+
except Exception as e:
|
| 218 |
+
print(f"获取远程LFS文件时出错: {e}")
|
| 219 |
+
return []
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def cleanup_orphaned_lfs_references(repo_path, repo_id, token, keep_count=3):
|
| 223 |
+
"""
|
| 224 |
+
清理孤儿LFS引用:删除远程存在但本地不存在的文件引用
|
| 225 |
+
"""
|
| 226 |
+
try:
|
| 227 |
+
original_dir = os.getcwd()
|
| 228 |
+
os.chdir(repo_path)
|
| 229 |
+
|
| 230 |
+
print("检查孤儿LFS引用...")
|
| 231 |
+
|
| 232 |
+
# 获取远程LFS文件
|
| 233 |
+
remote_files = get_remote_lfs_files(repo_id, token)
|
| 234 |
+
if not remote_files:
|
| 235 |
+
print("无法获取远程LFS文件列表")
|
| 236 |
+
return
|
| 237 |
+
|
| 238 |
+
# 获取本地文件
|
| 239 |
+
local_files = set(glob.glob('*.tar.gz'))
|
| 240 |
+
|
| 241 |
+
# 找出远程存在但本地不存在的文件
|
| 242 |
+
orphaned_files = []
|
| 243 |
+
for remote_file in remote_files:
|
| 244 |
+
filename = remote_file.get('filename')
|
| 245 |
+
if filename and filename not in local_files:
|
| 246 |
+
orphaned_files.append(filename)
|
| 247 |
+
|
| 248 |
+
if orphaned_files:
|
| 249 |
+
print(f"发现孤儿LFS引用: {orphaned_files}")
|
| 250 |
+
|
| 251 |
+
# 删除这些孤儿引用
|
| 252 |
+
for filename in orphaned_files:
|
| 253 |
+
print(f"删除孤儿LFS引用: {filename}")
|
| 254 |
+
delete_huggingface_lfs_file(filename, repo_id, token)
|
| 255 |
+
|
| 256 |
+
print("孤儿LFS引用清理完成")
|
| 257 |
+
os.chdir(original_dir)
|
| 258 |
+
|
| 259 |
+
except Exception as e:
|
| 260 |
+
print(f"清理孤儿LFS引用时出错: {e}")
|
| 261 |
+
os.chdir(original_dir)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
def compress_folder(folder_path, output_dir, keep_count=3):
|
| 265 |
try:
|
| 266 |
# 确保输出目录存在
|
| 267 |
os.makedirs(output_dir, exist_ok=True)
|
| 268 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
# 设置中国时区
|
| 270 |
china_tz = pytz.timezone('Asia/Shanghai')
|
| 271 |
|
|
|
|
| 278 |
|
| 279 |
# 安全地提取时间戳
|
| 280 |
def extract_timestamp(filename):
|
|
|
|
| 281 |
match = re.search(r'(\d+)\.tar\.gz$', filename)
|
| 282 |
return int(match.group(1)) if match else 0
|
| 283 |
|
| 284 |
+
files_to_cleanup = []
|
| 285 |
+
|
| 286 |
# 如果压缩包数量超过保留数量,删除最旧的
|
| 287 |
if len(existing_archives) >= keep_count:
|
| 288 |
# 按时间戳排序(从小到大,最旧的在前面)
|
|
|
|
| 294 |
# 删除最旧的压缩包
|
| 295 |
for i in range(delete_count):
|
| 296 |
oldest_archive = existing_archives[i]
|
| 297 |
+
oldest_filename = os.path.basename(oldest_archive)
|
| 298 |
+
|
| 299 |
try:
|
| 300 |
+
# 删除本地文件
|
| 301 |
os.remove(oldest_archive)
|
| 302 |
+
print(f"删除最旧的压缩包:{oldest_filename}")
|
| 303 |
+
|
| 304 |
+
# 记录需要清理的文件名
|
| 305 |
+
files_to_cleanup.append(oldest_filename)
|
| 306 |
+
|
| 307 |
+
# 删除Hugging Face LFS文件记录
|
| 308 |
+
print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
|
| 309 |
+
delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
|
| 310 |
+
|
| 311 |
except Exception as e:
|
| 312 |
print(f"删除失败 {oldest_archive}: {e}")
|
| 313 |
|
| 314 |
+
# 如果有文件需要从Git历史中清理,执行安全清理
|
| 315 |
+
if files_to_cleanup:
|
| 316 |
+
print(f"执行安全Git清理: {files_to_cleanup}")
|
| 317 |
+
safe_git_cleanup(output_dir, files_to_cleanup)
|
| 318 |
+
|
| 319 |
# tar.gz 压缩
|
| 320 |
result = subprocess.run(
|
| 321 |
+
['tar', '-czf', output_path, folder_path],
|
| 322 |
capture_output=True,
|
| 323 |
text=True
|
| 324 |
)
|
|
|
|
| 348 |
return None
|
| 349 |
|
| 350 |
|
|
|
|
|
|
|
| 351 |
def github(type):
|
| 352 |
if type == 1:
|
| 353 |
os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data')
|
|
|
|
| 360 |
os.system("ls")
|
| 361 |
latest_package = get_latest_local_package(f'/data/{HF_REPO}')
|
| 362 |
print(f"最新压缩包路径: {latest_package}")
|
| 363 |
+
if latest_package:
|
| 364 |
+
os.system(f"tar -xzf {latest_package} -C /data")
|
| 365 |
+
os.system("mv /data/f/ff /data/")
|
| 366 |
+
os.system("mv /data/data/f/ff /data/")
|
| 367 |
+
os.system("rm -rf /data/data /data/f")
|
| 368 |
|
| 369 |
if type == 2:
|
| 370 |
print(f"开始备份上传HF仓库:{HF_REPO}")
|
| 371 |
os.system("mkdir -p /data/f")
|
| 372 |
os.system("cp -rf /data/ff /data/f")
|
| 373 |
+
|
| 374 |
+
repo_path = f'/data/{HF_REPO}'
|
| 375 |
+
repo_id = f"{HF_USER1}/{HF_REPO}"
|
| 376 |
+
|
| 377 |
+
# 切换到仓库目录
|
| 378 |
+
os.chdir(repo_path)
|
| 379 |
+
os.system(f'git config --global user.email "{HF_EMAIL}"')
|
| 380 |
+
os.system(f'git config --global user.name "{HF_USER1}"')
|
| 381 |
+
|
| 382 |
+
# 先清理孤儿LFS引用
|
| 383 |
+
cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
|
| 384 |
+
|
| 385 |
+
# 执行Git清理(不影响现有文件)
|
| 386 |
os.system('git lfs prune')
|
| 387 |
+
os.system('git gc --auto')
|
| 388 |
+
|
| 389 |
# 备份上传仓库
|
| 390 |
+
new_archive_info = compress_folder('/data/f', repo_path, keep_count=3)
|
| 391 |
if new_archive_info:
|
| 392 |
new_archive, file_size_info = new_archive_info.split(' MB:')
|
| 393 |
+
|
| 394 |
os.system("pwd")
|
| 395 |
os.system(f'git add .')
|
| 396 |
os.system(f'git commit -m "{file_size_info}"')
|
| 397 |
+
|
| 398 |
+
# 正常推送(不再需要强制推送)
|
| 399 |
+
push_result = os.system('git push origin main')
|
| 400 |
+
if push_result != 0:
|
| 401 |
+
print("推送失败,可能有冲突,尝试拉取并合并...")
|
| 402 |
+
os.system('git pull origin main --rebase')
|
| 403 |
+
os.system('git push origin main')
|
| 404 |
+
|
| 405 |
+
# 轻度清理
|
| 406 |
+
os.system('git gc --auto')
|
| 407 |
+
os.system('git lfs prune')
|
| 408 |
else:
|
| 409 |
print("压缩失败,无法提交")
|
| 410 |
|
| 411 |
+
|
| 412 |
def _reconstruct_token(partial_token):
|
| 413 |
return partial_token.replace(" ", "")
|
| 414 |
+
|
| 415 |
def restart_huggingface_space(space_name, space_id, partial_token):
|
| 416 |
token = _reconstruct_token(partial_token)
|
| 417 |
url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
|
|
|
|
| 433 |
"success": False,
|
| 434 |
"message": str(e)
|
| 435 |
}
|
| 436 |
+
|
| 437 |
+
|
| 438 |
def check_system_resources():
|
| 439 |
time.sleep(120)
|
| 440 |
cpu_usage = psutil.cpu_percent(interval=1)
|
| 441 |
memory = psutil.virtual_memory()
|
| 442 |
memory_usage = memory.percent
|
|
|
|
| 443 |
if cpu_usage >= 90 or memory_usage >= 95:
|
| 444 |
print("占用过高")
|
| 445 |
result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
|
| 446 |
print(result)
|
| 447 |
else:
|
| 448 |
print("系统资源正常")
|
| 449 |
+
|
| 450 |
+
|
| 451 |
def repeat_task():
|
| 452 |
print('备份线程启动')
|
| 453 |
while True:
|
| 454 |
print(f"打包时间:{BACKUP_TIME} 秒")
|
| 455 |
+
time.sleep(int(BACKUP_TIME))
|
| 456 |
github(2)
|
| 457 |
+
|
| 458 |
github(1)
|
| 459 |
|
| 460 |
if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('/data/ff/.mozilla/firefox/profiles.ini'):
|
|
|
|
| 465 |
github(2)
|
| 466 |
result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
|
| 467 |
print(result)
|
| 468 |
+
break
|
| 469 |
+
# github(2)
|
| 470 |
# nv1_agent()
|