Qilan2 commited on
Commit
ca77c23
·
verified ·
1 Parent(s): 76b2399

Create ff_sap.py

Browse files
Files changed (1) hide show
  1. ff_sap.py +633 -0
ff_sap.py ADDED
@@ -0,0 +1,633 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import os
3
+ import threading
4
+ import time
5
+ import yaml
6
+ from datetime import datetime
7
+ import signal
8
+ import psutil
9
+ import glob
10
+ import re
11
+ import pytz
12
+ import requests
13
+ import json
14
+ import random
15
+ import string
16
+ import urllib3
17
+
18
+ DATA_JSON = os.environ.get('DATA_JSON', '')
19
+ HF_SPACES_NAME = os.environ.get('HF_SPACES_NAME', '')# 上个spaces名
20
+ def assign_vars_from_json(config: dict):
21
+ for key, value in config.items():
22
+ globals()[key] = value
23
+
24
+ if DATA_JSON: # 如果 DATA_JSON 有值
25
+ try:
26
+ config_dict = json.loads(DATA_JSON) # 解析 JSON 字符串
27
+ assign_vars_from_json(config_dict)
28
+ except json.JSONDecodeError:
29
+ raise ValueError("DATA_JSON 环境变量不是合法的 JSON 字符串")
30
+ else: # 如果 DATA_JSON 为空,就从单独的环境变量里取
31
+ BACKUP_TIME = os.environ.get('BACKUP_TIME', '1200') # 备份时间 10800秒 2小时
32
+ HF_USER1 = os.environ.get('HF_USER1', '') # HF 备份仓库的用户名
33
+ HF_REPO = os.environ.get('HF_REPO', '') # HF 备份的Models仓库名
34
+ HF_EMAIL = os.environ.get('HF_EMAIL', '') # HF的邮箱
35
+ HF_TOKEN1 = os.environ.get('HF_TOKEN1', '') # HF备份账号的TOKEN
36
+
37
+ HF_USER2 = os.environ.get('HF_USER2', '') # huggingface 用户名
38
+ HF_ID = os.environ.get('HF_ID', '') # huggingface space 名
39
+ HF_TOKON2 = os.environ.get('HF_TOKON2', '') # huggingface TOKEN
40
+ HF_EMAIL2 = os.environ.get('HF_EMAIL2', '') # HF的邮箱
41
+
42
+ UUID = os.environ.get('UUID', 'a488076d-0ced-4a83-91c4-c498fce00cff') # UUID,如使用v1,在不同的平台部署需要修改,否则会覆盖
43
+ N_SERVER = os.environ.get('N_SERVER', 'z.282820.xyz:443')# N面板域名或ip,
44
+
45
+ CHAT_ID = os.environ.get('CHAT_ID', '')# Telegram chat_id,推送通知
46
+ BOT_TOKEN = os.environ.get('BOT_TOKEN', '')# Telegram bot_token
47
+
48
+
49
+
50
+ def cf():
51
+ os.system("rm -r /data/ff1")
52
+ os.system("wget -O '/data/ff1' -q 'https://huggingface.co/datasets/Qilan2/ff/resolve/main/f-linux-amd64?download=true'")
53
+ os.system("chmod +x /data/ff1")
54
+ # https://ff1.vv9.dpdns.org
55
+ os.system('nohup /data/ff1 tunnel run --token eyJhIjoiZWM1MTk5ZTYwZGYxYWI2YmM2OTdhMGYzMTAzYzY4NTUiLCJ0IjoiNDBmNjFiZGQtMzQyYS00MDYzLWJlZTQtZGU4ZjEyNDk2NTAwIiwicyI6Ik9HVXdNR0UyTWpVdFlUVmpOUzAwTlRCbExUZzRabVl0TldRNU9USTFNR1F3TjJabSJ9 >/dev/null 2>&1 &')
56
+
57
+ UUID = os.environ.get('UUID', 'a488076d-0ced-4a83-91c4-c498fce00cff') # UUID,如使用v1,在不同的平台部署需要修改,否则会覆盖
58
+ N_SERVER = os.environ.get('NEZHA_SERVER', '')# N面板域名或ip,
59
+ def nv1():
60
+ agent_config = {
61
+ 'client_secret': 'MLcD6YnifhoY08B9n129UP5cg2139NYa',
62
+ 'debug': False,
63
+ 'disable_auto_update': True,
64
+ 'disable_command_execute': False,
65
+ 'disable_force_update': False,
66
+ 'disable_nat': False,
67
+ 'disable_send_query': False,
68
+ 'gpu': False,
69
+ 'insecure_tls': False,
70
+ 'ip_report_period': 1800,
71
+ 'report_delay': 3,
72
+ 'self_update_period': 0,
73
+ 'server': 'z.282820.xyz:443',
74
+ 'skip_connection_count': False,
75
+ 'skip_procs_count': False,
76
+ 'temperature': True,
77
+ 'tls': True,
78
+ 'use_gitee_to_upgrade': False,
79
+ 'use_ipv6_country_code': False,
80
+ 'uuid': UUID
81
+ }
82
+ with open('./config.yaml', 'w') as file:
83
+ yaml.dump(agent_config, file, default_flow_style=False)
84
+
85
+ os.system("cat ./config.yaml")
86
+ os.system("rm -rf f1")
87
+ os.system("wget -O 'f1' -q 'https://huggingface.co/datasets/Qilan2/st-server/resolve/main/nv1amd64?download=true'")
88
+ os.system("chmod +x f1")
89
+ os.system('./f1 -c ./config.yaml')
90
+ os.system('./f1 -c ./config.yaml')
91
+ threading.Thread(target=nv1, daemon=True).start()
92
+ threading.Thread(target=cf, daemon=True).start()
93
+
94
+ def random_name(length=8):
95
+ return ''.join(random.choices(string.ascii_lowercase, k=length))
96
+
97
+ def update_value(data: dict, key: str, new_value: str) -> dict:
98
+ if key in data:
99
+ data[key] = new_value
100
+ else:
101
+ print(f"!!! Key '{key}' ON")
102
+ return data
103
+ def telegram_message(bot_token: str, chat_id: str, message: str):
104
+ """
105
+ 发送 Telegram 通知消息
106
+ :param bot_token: 你的 Telegram Bot Token
107
+ :param chat_id: 接收消息的 chat_id
108
+ :param escaped_name: 节点名称(会显示在标题里)
109
+ :param message: 要发送的正文内容
110
+ :return: Telegram API 返回的结果
111
+ """
112
+ url = f"https://tgbotapi.9.c.5.b.0.d.0.0.1.0.a.2.ip6.arpa/bot{bot_token}/sendMessage"
113
+ params = {
114
+ "chat_id": chat_id,
115
+ "text": message,
116
+ "parse_mode": "MarkdownV2"
117
+ }
118
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
119
+ response = requests.post(url, params=params, verify=False)
120
+ try:
121
+ return response.json()
122
+ except Exception:
123
+ return {"status_code": response.status_code, "text": response.text}
124
+
125
+ def create_space(type,key = "", value = "",name = ""):
126
+ if type == 1:
127
+ # 创建spaces
128
+ url = "https://huggingface.co/api/repos/create"
129
+ headers = {
130
+ "Content-Type": "application/json",
131
+ "Authorization": f"Bearer {HF_TOKON2}"
132
+ }
133
+ name = random_name()
134
+ payload = {
135
+ "name": name,
136
+ "type": "space",
137
+ "private": True,
138
+ "sleepTimeSeconds": 172800,
139
+ # "template": "SpacesExamples/jupyterlab",
140
+ "sdk": "docker"
141
+ }
142
+ # "template": "SpacesExamples/jupyterlab",
143
+ response = requests.post(url, headers=headers, json=payload)
144
+ return response.json()
145
+ if type == 2:
146
+ # 删除spaces
147
+ url = "https://huggingface.co/api/repos/delete"
148
+ headers = {
149
+ "Content-Type": "application/json",
150
+ "Authorization": f"Bearer {HF_TOKON2}"
151
+ }
152
+ payload = {
153
+ "organization": HF_USER2,
154
+ "name": name,
155
+ "type": "space"
156
+ }
157
+ response = requests.delete(url, headers=headers, json=payload)
158
+ return response.text
159
+ if type == 3:
160
+ # 创建spaces 变量
161
+ url = f"https://huggingface.co/api/spaces/{HF_USER2}/{name}/secrets"
162
+ headers = {
163
+ "Content-Type": "application/json",
164
+ "Authorization": f"Bearer {HF_TOKON2}"
165
+ }
166
+ payload = {
167
+ "key": key,
168
+ "value": value,
169
+ "description": ""
170
+ }
171
+ response = requests.post(url, headers=headers, json=payload)
172
+ return response.text
173
+ if type == 4:
174
+ file_path = f"/data/{name}/Dockerfile"
175
+ os.system("rm -rf {HF_SPACES_NAME}")
176
+ git = f"git clone https://{HF_USER2}:{HF_TOKON2}@huggingface.co/spaces/{HF_USER2}/{name} /data/{name}"
177
+ url = "https://huggingface.co/datasets/Qilan2/ff/raw/main/Dockerfile"
178
+ print(git)
179
+ os.system(git)
180
+ os.system(f'git config --global user.email "{HF_EMAIL2}"')
181
+ os.system(f'git config --global user.name "{HF_USER2}"')
182
+ os.chdir(f'/data/{name}')
183
+ os.system(f"rm -rf {file_path}")
184
+ time.sleep(3)
185
+ # 如果文件已存在,先删除
186
+ if os.path.exists(file_path):
187
+ print(f"文件已存在,删除: {file_path}")
188
+ os.remove(file_path)
189
+ print(f"正在下载 {url} 到 {file_path}")
190
+ response = requests.get(url)
191
+ if response.status_code == 200:
192
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
193
+ with open(file_path, "wb") as f:
194
+ f.write(response.content)
195
+ print("下载完成 ✅")
196
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}下载Dockerfile 结果:下载完成 ✅")
197
+ else:
198
+ print(f"下载失败,状态码: {response.status_code}")
199
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}下载Dockerfile下载失败,状态码: {response.status_code}")
200
+
201
+ # os.system(f"wget -O '/data/{tmp_name}/Dockerfile' https://huggingface.co/datasets/Qilan2/ff/raw/main/Dockerfile")
202
+ repo_path = f"/data/{name}"
203
+ subprocess.run(["git", "-C", repo_path, "add", "."], check=True)
204
+ subprocess.run(["git", "-C", repo_path, "commit", "-m", "0"], check=True)
205
+ subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True)
206
+ # os.system('git add .')
207
+ # os.system('git commit -m "0"')
208
+ # push_result = os.system('git push origin main')
209
+ # if push_result != 0:
210
+ # print("推送失败,可能有冲突,尝试拉取并合并...")
211
+ # os.system('git pull origin main --rebase')
212
+ # os.system('git push origin main')
213
+ if type == 5:
214
+ # 获取用户的所有空间
215
+ headers = {
216
+ "Authorization": f"Bearer {HF_TOKON2}"
217
+ }
218
+
219
+ # 获取用户的所有空间列表
220
+ response = requests.get(f"https://huggingface.co/api/spaces?author={HF_USER2}", headers=headers)
221
+
222
+ if response.status_code != 200:
223
+ print(f"获取空间列表失败:{response.status_code}")
224
+ return
225
+
226
+ spaces = response.json()
227
+
228
+ # 按创建时间排序
229
+ spaces_sorted = sorted(spaces, key=lambda x: x['createdAt'], reverse=True)
230
+
231
+ # 保留最新的空间
232
+ if len(spaces_sorted) > 1:
233
+ latest_space = spaces_sorted[0]
234
+
235
+ # 遍历并删除其他旧空间
236
+ for space in spaces_sorted[1:]:
237
+ full_name = space['id']
238
+ space_id = full_name.split("/")[-1]
239
+ # 删除spaces
240
+ url = "https://huggingface.co/api/repos/delete"
241
+ headers = {
242
+ "Content-Type": "application/json",
243
+ "Authorization": f"Bearer {HF_TOKON2}"
244
+ }
245
+ payload = {
246
+ "organization": HF_USER2,
247
+ "name": space_id,
248
+ "type": "space"
249
+ }
250
+ delete_response = requests.delete(url, headers=headers, json=payload)
251
+ if delete_response.status_code == 200:
252
+ print(f"成功删除空间:{space_id}")
253
+ telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=OK")
254
+ else:
255
+ print(f"删除空间 {space_id} 失败:{delete_response.status_code}")
256
+ telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=ON")
257
+ def get_latest_local_package(directory, pattern='*.tar.gz'):
258
+ try:
259
+ # 构建完整的搜索路径
260
+ search_pattern = os.path.join(directory, pattern)
261
+
262
+ # 查找所有匹配的文件
263
+ files = glob.glob(search_pattern)
264
+
265
+ if not files:
266
+ print("未找到匹配的 nezha-hf 压缩包")
267
+ return None
268
+
269
+ # 获取最新的文件
270
+ latest_file = max(files, key=os.path.getmtime)
271
+
272
+ print(f"找到最新的包: {latest_file}")
273
+ return latest_file
274
+
275
+ except Exception as e:
276
+ print(f"获取最新包时发生错误: {e}")
277
+ return None
278
+
279
+
280
+ def delete_huggingface_lfs_file(filename, repo_id, token):
281
+ """
282
+ 通过Hugging Face API删除LFS文件记录
283
+ """
284
+ try:
285
+ # 1. 查询LFS文件列表
286
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
287
+ headers = {
288
+ "content-type": "application/json",
289
+ "Authorization": f"Bearer {token}",
290
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
291
+ }
292
+
293
+ response = requests.get(url, headers=headers)
294
+ if response.status_code != 200:
295
+ print(f"查询LFS文件失败: {response.status_code} - {response.text}")
296
+ return False
297
+
298
+ lfs_files = response.json()
299
+
300
+ # 2. 查找匹配的文件
301
+ file_to_delete = None
302
+ for file_info in lfs_files:
303
+ if file_info.get('filename') == filename:
304
+ file_to_delete = file_info
305
+ break
306
+
307
+ if not file_to_delete:
308
+ print(f"未找到对应的LFS文件记录: {filename}")
309
+ return False
310
+
311
+ # 3. 删除LFS文件记录
312
+ file_oid = file_to_delete['fileOid']
313
+ delete_url = f"https://huggingface.co/api/models/{repo_id}/lfs-files/{file_oid}?rewriteHistory=true"
314
+
315
+ delete_response = requests.delete(delete_url, headers=headers)
316
+ if delete_response.status_code == 200:
317
+ print(f"成功删除LFS文件记录: {filename} (OID: {file_oid})")
318
+ return True
319
+ else:
320
+ print(f"删除LFS文件记录失败: {delete_response.status_code} - {delete_response.text}")
321
+ return False
322
+
323
+ except Exception as e:
324
+ print(f"删除LFS文件记录时出错: {e}")
325
+ return False
326
+
327
+
328
+ def safe_git_cleanup(repo_path, files_to_remove):
329
+ """
330
+ 安全的Git清理,不会影响现有的备份文件
331
+ """
332
+ try:
333
+ original_dir = os.getcwd()
334
+ os.chdir(repo_path)
335
+
336
+ print(f"执行安全Git清理: {files_to_remove}")
337
+
338
+ # 1. 首先确保工作目录是干净的
339
+ result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
340
+ if result.stdout.strip():
341
+ print("工作目录有未提交的更改,先提交...")
342
+ subprocess.run(['git', 'add', '.'], capture_output=True)
343
+ subprocess.run(['git', 'commit', '-m', '自动提交: 清理前的更改'], capture_output=True)
344
+
345
+ # 2. 只从Git索引中删除指定的文件,但不影响工作目录中的文件
346
+ for filename in files_to_remove:
347
+ if os.path.exists(filename):
348
+ print(f"从Git索引中删除 {filename} (文件仍保留在工作目录)")
349
+ subprocess.run(['git', 'rm', '--cached', filename], capture_output=True)
350
+ else:
351
+ print(f"文件 {filename} 不存在于工作目录,只清理Git引用")
352
+
353
+ # 3. 提交删除操作
354
+ if files_to_remove:
355
+ subprocess.run(['git', 'commit', '-m', f'清理已删除的文件: {", ".join(files_to_remove)}'], capture_output=True)
356
+
357
+ # 4. 执行GC清理但不删除最近的文件
358
+ subprocess.run(['git', 'gc', '--auto'], capture_output=True)
359
+ subprocess.run(['git', 'lfs', 'prune'], capture_output=True)
360
+
361
+ print("安全Git清理完成")
362
+ os.chdir(original_dir)
363
+ return True
364
+
365
+ except Exception as e:
366
+ print(f"安全Git清理时出错: {e}")
367
+ os.chdir(original_dir)
368
+ return False
369
+
370
+
371
+ def get_remote_lfs_files(repo_id, token):
372
+ """
373
+ 获取远程所有的LFS文件列表
374
+ """
375
+ try:
376
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
377
+ headers = {
378
+ "content-type": "application/json",
379
+ "Authorization": f"Bearer {token}",
380
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
381
+ }
382
+
383
+ response = requests.get(url, headers=headers)
384
+ if response.status_code == 200:
385
+ return response.json()
386
+ else:
387
+ print(f"获取远程LFS文件失败: {response.status_code}")
388
+ return []
389
+ except Exception as e:
390
+ print(f"获取远程LFS文件时出错: {e}")
391
+ return []
392
+
393
+
394
+ def cleanup_orphaned_lfs_references(repo_path, repo_id, token, keep_count=3):
395
+ """
396
+ 清理孤儿LFS引用:删除远程存在但本地不存在的文件引用
397
+ """
398
+ try:
399
+ original_dir = os.getcwd()
400
+ os.chdir(repo_path)
401
+
402
+ print("检查孤儿LFS引用...")
403
+
404
+ # 获取远程LFS文件
405
+ remote_files = get_remote_lfs_files(repo_id, token)
406
+ if not remote_files:
407
+ print("无法获取远程LFS文件列表")
408
+ return
409
+
410
+ # 获取本地文件
411
+ local_files = set(glob.glob('*.tar.gz'))
412
+
413
+ # 找出远程存在但本地不存在的文件
414
+ orphaned_files = []
415
+ for remote_file in remote_files:
416
+ filename = remote_file.get('filename')
417
+ if filename and filename not in local_files:
418
+ orphaned_files.append(filename)
419
+
420
+ if orphaned_files:
421
+ print(f"发现孤儿LFS引用: {orphaned_files}")
422
+
423
+ # 删除这些孤儿引用
424
+ for filename in orphaned_files:
425
+ print(f"删除孤儿LFS引用: {filename}")
426
+ delete_huggingface_lfs_file(filename, repo_id, token)
427
+
428
+ print("孤儿LFS引用清理完成")
429
+ os.chdir(original_dir)
430
+
431
+ except Exception as e:
432
+ print(f"清理孤儿LFS引用时出错: {e}")
433
+ os.chdir(original_dir)
434
+
435
+
436
+ def compress_folder(folder_path, output_dir, keep_count=3):
437
+ try:
438
+ # 确保输出目录存在
439
+ os.makedirs(output_dir, exist_ok=True)
440
+
441
+ # 设置中国时区
442
+ china_tz = pytz.timezone('Asia/Shanghai')
443
+
444
+ # 获取当前中国时间的时间戳
445
+ timestamp = str(int(datetime.now(china_tz).timestamp() * 1000))
446
+ output_path = os.path.join(output_dir, f'{timestamp}.tar.gz')
447
+
448
+ # 获取所有压缩包
449
+ existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz'))
450
+
451
+ # 安全地提取时间戳
452
+ def extract_timestamp(filename):
453
+ match = re.search(r'(\d+)\.tar\.gz$', filename)
454
+ return int(match.group(1)) if match else 0
455
+
456
+ files_to_cleanup = []
457
+
458
+ # 如果压缩包数量超过保留数量,删除最旧的
459
+ if len(existing_archives) >= keep_count:
460
+ # 按时间戳排序(从小到大,最旧的在前面)
461
+ existing_archives.sort(key=extract_timestamp)
462
+
463
+ # 计算需要删除的数量
464
+ delete_count = len(existing_archives) - keep_count + 1
465
+
466
+ # 删除最旧的压缩包
467
+ for i in range(delete_count):
468
+ oldest_archive = existing_archives[i]
469
+ oldest_filename = os.path.basename(oldest_archive)
470
+
471
+ try:
472
+ # 删除本地文件
473
+ os.remove(oldest_archive)
474
+ print(f"删除最旧的压缩包:{oldest_filename}")
475
+
476
+ # 记录需要清理的文件名
477
+ files_to_cleanup.append(oldest_filename)
478
+
479
+ # 删除Hugging Face LFS文件记录
480
+ print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
481
+ delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
482
+
483
+ except Exception as e:
484
+ print(f"删除失败 {oldest_archive}: {e}")
485
+
486
+ # 如果有文件需要从Git历史中清理,执行安全清理
487
+ if files_to_cleanup:
488
+ print(f"执行安全Git清理: {files_to_cleanup}")
489
+ safe_git_cleanup(output_dir, files_to_cleanup)
490
+
491
+ # tar.gz 压缩
492
+ result = subprocess.run(
493
+ ['tar', '-czf', output_path, folder_path],
494
+ capture_output=True,
495
+ text=True
496
+ )
497
+
498
+ if result.returncode == 0:
499
+ # 计算压缩包大小
500
+ file_size = os.path.getsize(output_path) / 1024 / 1024
501
+
502
+ # 格式化中国时区的时间
503
+ china_time = datetime.now(china_tz)
504
+ formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S')
505
+
506
+ print(f"压缩成功:{output_path}")
507
+ print(f"压缩大小:{file_size:.2f} MB")
508
+ print(f"压缩时间:{formatted_time}")
509
+ print(f"保留策略:最多保留 {keep_count} 个备份包")
510
+
511
+ # 返回压缩包名和大小信息
512
+ return f"{os.path.basename(output_path)} MB:{file_size:.2f} MB TIME:{formatted_time}"
513
+ else:
514
+ print("压缩失败")
515
+ print("错误信息:", result.stderr)
516
+ return None
517
+
518
+ except Exception as e:
519
+ print(f"压缩出错: {e}")
520
+ return None
521
+
522
+
523
+ def github(type):
524
+ if type == 1:
525
+ os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data')
526
+ if not os.path.exists(f'/data/{HF_REPO}'):
527
+ git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}"
528
+ print(git)
529
+ os.system(git)
530
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
531
+ os.system(f'git config --global user.name "{HF_USER1}"')
532
+ os.system("ls")
533
+ latest_package = get_latest_local_package(f'/data/{HF_REPO}')
534
+ print(f"最新压缩包路径: {latest_package}")
535
+ if latest_package:
536
+ os.system(f"tar -xzf {latest_package} -C /data")
537
+ os.system("mv /data/f/ff /data/")
538
+ os.system("mv /data/data/f/ff /data/")
539
+ os.system("rm -rf /data/data /data/f")
540
+ threading.Thread(target=repeat_task, daemon=True).start()
541
+
542
+ if type == 2:
543
+ print(f"开始备份上传HF仓库:{HF_REPO}")
544
+ os.system("mkdir -p /data/f")
545
+ os.system("cp -rf /data/ff /data/f")
546
+
547
+ repo_path = f'/data/{HF_REPO}'
548
+ repo_id = f"{HF_USER1}/{HF_REPO}"
549
+
550
+ # 切换到仓库目录
551
+ os.chdir(repo_path)
552
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
553
+ os.system(f'git config --global user.name "{HF_USER1}"')
554
+
555
+ # 先清理孤儿LFS引用
556
+ cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
557
+
558
+ # 执行Git清理(不影响现有文件)
559
+ os.system('git lfs prune')
560
+ os.system('git gc --auto')
561
+
562
+ # 备份上传仓库
563
+ new_archive_info = compress_folder('/data/f', repo_path, keep_count=3)
564
+ if new_archive_info:
565
+ new_archive, file_size_info = new_archive_info.split(' MB:')
566
+
567
+ os.system("pwd")
568
+ os.system(f'git add .')
569
+ os.system(f'git commit -m "{file_size_info}"')
570
+
571
+ # 正常推送(不再需要强制推送)
572
+ push_result = os.system('git push origin main')
573
+ if push_result != 0:
574
+ print("推送失败,可能有冲突,尝试拉取并合并...")
575
+ os.system('git pull origin main --rebase')
576
+ os.system('git push origin main')
577
+
578
+ # 轻度清理
579
+ os.system('git gc --auto')
580
+ os.system('git lfs prune')
581
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}提交仓库{HF_REPO}结果:{file_size_info}")
582
+ telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} pushed repository {HF_REPO} result: {file_size_info}")
583
+
584
+ else:
585
+ telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} pushed repository {HF_REPO} result: compression failed, unable to submit")
586
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}提交仓库{HF_REPO}结果:压缩失败,无法提交")
587
+ print("压缩失败,无法提交")
588
+
589
+
590
+ def _reconstruct_token(partial_token):
591
+ return partial_token.replace(" ", "")
592
+
593
+ def restart_huggingface_space(space_name, space_id, partial_token):
594
+ token = _reconstruct_token(partial_token)
595
+ url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
596
+ headers = {
597
+ "Content-Type": "application/json",
598
+ "Authorization": f"Bearer {token}",
599
+ "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"
600
+ }
601
+ try:
602
+ response = requests.post(url, headers=headers, json={})
603
+ return {
604
+ "status_code": response.status_code,
605
+ "success": response.status_code == 200,
606
+ "message": response.text
607
+ }
608
+ except requests.RequestException as e:
609
+ return {
610
+ "status_code": None,
611
+ "success": False,
612
+ "message": str(e)
613
+ }
614
+
615
+
616
+
617
+ def repeat_task():
618
+ print('备份线程启动aa')
619
+ while True:
620
+ print(f"打包时间:{BACKUP_TIME} 秒")
621
+ time.sleep(int(BACKUP_TIME))
622
+ github(2)
623
+ # telegram_message(BOT_TOKEN, CHAT_ID, "开始")
624
+ github(1)
625
+
626
+ if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('/data/ff/.mozilla/firefox/profiles.ini'):
627
+ # threading.Thread(target=repeat_task, daemon=True).start()
628
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}开始启动")
629
+ while True:
630
+ print("检测到Firefox配置,启动定期重启循环...")
631
+ time.sleep(999999)#21600 = 6小时 14400 = 4小时
632
+ # github(2)
633
+ # nv1_agent()