Qilan2 commited on
Commit
8b23d86
·
verified ·
1 Parent(s): c0355ac

Upload ff2.py

Browse files
Files changed (1) hide show
  1. ff2.py +761 -0
ff2.py ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/cf")
52
+ os.system("wget -O '/data/cf' -q 'https://github.com/cloudflare/cloudflared/releases/download/2025.9.0/cloudflared-linux-amd64'")
53
+ os.system("chmod +x /data/cf")
54
+ # https://ff1.vv9.dpdns.org
55
+ os.system('/data/cf tunnel run --token eyJhIjoiZWM1MTk5ZTYwZGYxYWI2YmM2OTdhMGYzMTAzYzY4NTUiLCJ0IjoiNDBmNjFiZGQtMzQyYS00MDYzLWJlZTQtZGU4ZjEyNDk2NTAwIiwicyI6Ik9HVXdNR0UyTWpVdFlUVmpOUzAwTlRCbExUZzRabVl0TldRNU9USTFNR1F3TjJabSJ9')
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
+ current_time = datetime.now(china_tz)
446
+ timestamp = str(int(current_time.timestamp() * 1000))
447
+ current_date = current_time.strftime('%Y-%m-%d')
448
+ output_path = os.path.join(output_dir, f'{timestamp}.tar.gz')
449
+
450
+ # 获取所有压缩包
451
+ existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz'))
452
+
453
+ # 安全地提取时间戳和日期
454
+ def extract_timestamp(filename):
455
+ match = re.search(r'(\d+)\.tar\.gz$', filename)
456
+ return int(match.group(1)) if match else 0
457
+
458
+ def get_date_from_timestamp(ts):
459
+ dt = datetime.fromtimestamp(ts/1000, china_tz)
460
+ return dt.strftime('%Y-%m-%d')
461
+
462
+ # 按日期和时间戳整理已有的备份
463
+ date_archives = {}
464
+ for archive in existing_archives:
465
+ ts = extract_timestamp(archive)
466
+ if ts == 0:
467
+ continue
468
+ date = get_date_from_timestamp(ts)
469
+ if date not in date_archives:
470
+ date_archives[date] = []
471
+ date_archives[date].append((archive, ts))
472
+
473
+ files_to_cleanup = []
474
+
475
+ # 对于每个日期,只保留最新的备份
476
+ for date, archives in date_archives.items():
477
+ if len(archives) > 1:
478
+ # 按时间戳排序(从小到大)
479
+ archives.sort(key=lambda x: x[1])
480
+ # 删除同一天的旧备份,只保留最新的
481
+ for archive, _ in archives[:-1]:
482
+ oldest_filename = os.path.basename(archive)
483
+ try:
484
+ # 删除本地文件
485
+ os.remove(archive)
486
+ print(f"删除同一天的旧备份:{oldest_filename}")
487
+
488
+ # 记录需要清理的文件名
489
+ files_to_cleanup.append(oldest_filename)
490
+
491
+ # 删除Hugging Face LFS文件记录
492
+ print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
493
+ delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
494
+ except Exception as e:
495
+ print(f"删除失败 {archive}: {e}")
496
+
497
+ # 更新日期存档字典(只包含每天最新的备份)
498
+ for date in date_archives:
499
+ if date_archives[date]:
500
+ date_archives[date] = [date_archives[date][-1]]
501
+
502
+ # 保持最近三天的备份,删除更早的
503
+ sorted_dates = sorted(date_archives.keys(), reverse=True)
504
+ if len(sorted_dates) > keep_count:
505
+ for old_date in sorted_dates[keep_count:]:
506
+ for archive, _ in date_archives[old_date]:
507
+ oldest_filename = os.path.basename(archive)
508
+ try:
509
+ # 删除本地文件
510
+ os.remove(archive)
511
+ print(f"删除超过{keep_count}天的旧备份:{oldest_filename}")
512
+
513
+ # 记录需要清理的文件名
514
+ files_to_cleanup.append(oldest_filename)
515
+
516
+ # 删除Hugging Face LFS文件记录
517
+ print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
518
+ delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
519
+ except Exception as e:
520
+ print(f"删除失败 {archive}: {e}")
521
+
522
+ # 如果有文件需要从Git历史中清理,执行安全清理
523
+ if files_to_cleanup:
524
+ print(f"执行安全Git清理: {files_to_cleanup}")
525
+ safe_git_cleanup(output_dir, files_to_cleanup)
526
+
527
+ # tar.gz 压缩
528
+ result = subprocess.run(
529
+ ['tar', '-czf', output_path, folder_path],
530
+ capture_output=True,
531
+ text=True
532
+ )
533
+
534
+ if result.returncode == 0:
535
+ # 计算压缩包大小
536
+ file_size = os.path.getsize(output_path) / 1024 / 1024
537
+
538
+ # 格式化中国时区的时间
539
+ china_time = datetime.now(china_tz)
540
+ formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S')
541
+
542
+ print(f"压缩成功:{output_path}")
543
+ print(f"压缩大小:{file_size:.2f} MB")
544
+ print(f"压缩时间:{formatted_time}")
545
+ print(f"保留策略:每天一个,最多保留 {keep_count} 天备份")
546
+
547
+ # 如果有当天的旧备份,删除
548
+ if current_date in date_archives and date_archives[current_date]:
549
+ for old_archive_info in date_archives[current_date]:
550
+ old_archive, old_ts = old_archive_info
551
+ old_filename = os.path.basename(old_archive)
552
+ if os.path.exists(old_archive) and old_filename != os.path.basename(output_path):
553
+ try:
554
+ os.remove(old_archive)
555
+ print(f"删除当天的旧备份:{old_filename}")
556
+ delete_huggingface_lfs_file(old_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
557
+ files_to_cleanup.append(old_filename)
558
+ except Exception as e:
559
+ print(f"删除当天旧备份失败 {old_archive}: {e}")
560
+
561
+ # 返回压缩包名和大小信息
562
+ return f"{os.path.basename(output_path)} MB:{file_size:.2f} MB TIME:{formatted_time}"
563
+ else:
564
+ print("压缩失败")
565
+ print("错误信息:", result.stderr)
566
+ return None
567
+
568
+ except Exception as e:
569
+ print(f"压缩出错: {e}")
570
+ return None
571
+
572
+
573
+ def github(type):
574
+ if type == 1:
575
+ os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data')
576
+ if not os.path.exists(f'/data/{HF_REPO}'):
577
+ git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}"
578
+ print(git)
579
+ os.system(git)
580
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
581
+ os.system(f'git config --global user.name "{HF_USER1}"')
582
+ os.system("ls")
583
+ latest_package = get_latest_local_package(f'/data/{HF_REPO}')
584
+ print(f"最新压缩包路径: {latest_package}")
585
+ if latest_package:
586
+ os.system(f"tar -xzf {latest_package} -C /data")
587
+ os.system("mv /data/f/ff /data/")
588
+ os.system("mv /data/data/f/ff /data/")
589
+ os.system("rm -rf /data/data /data/f")
590
+ threading.Thread(target=repeat_task, daemon=True).start()
591
+
592
+ if type == 2:
593
+ print(f"开始备份上传HF仓库:{HF_REPO}")
594
+ os.system("mkdir -p /data/f")
595
+ os.system("cp -rf /data/ff /data/f")
596
+
597
+ # 检查本地仓库是否为空
598
+ if not os.path.exists("/data/f/ff") or not os.listdir("/data/f/ff"):
599
+ print("本地仓库为空,跳过备份上传")
600
+ telegram_message(BOT_TOKEN, CHAT_ID, f"Warning: {HF_ID} backup repository {HF_REPO} is empty, skipping backup upload")
601
+ return
602
+
603
+ repo_path = f'/data/{HF_REPO}'
604
+ repo_id = f"{HF_USER1}/{HF_REPO}"
605
+
606
+ # 切换到仓库目录
607
+ os.chdir(repo_path)
608
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
609
+ os.system(f'git config --global user.name "{HF_USER1}"')
610
+
611
+ # 先清理孤儿LFS引用
612
+ cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
613
+
614
+ # 执行Git清理(不影响现有文件)
615
+ os.system('git lfs prune')
616
+ os.system('git gc --auto')
617
+
618
+ # 备份上���仓库
619
+ new_archive_info = compress_folder('/data/f', repo_path, keep_count=3)
620
+ if new_archive_info:
621
+ new_archive, file_size_info = new_archive_info.split(' MB:')
622
+
623
+ os.system("pwd")
624
+ os.system(f'git add .')
625
+ os.system(f'git commit -m "{file_size_info}"')
626
+
627
+ # 正常推送(不再需要强制推送)
628
+ push_result = os.system('git push origin main')
629
+ if push_result != 0:
630
+ print("推送失败,可能有冲突,尝试拉取并合并...")
631
+ os.system('git pull origin main --rebase')
632
+ os.system('git push origin main')
633
+
634
+ # 轻度清理
635
+ os.system('git gc --auto')
636
+ os.system('git lfs prune')
637
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}提交仓库{HF_REPO}结果:{file_size_info}")
638
+ telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} pushed repository {HF_REPO} result: {file_size_info}")
639
+
640
+ else:
641
+ telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} pushed repository {HF_REPO} result: compression failed, unable to submit")
642
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}提交仓库{HF_REPO}结果:压缩失败,无法提交")
643
+ print("压缩失败,无法提交")
644
+
645
+
646
+ def _reconstruct_token(partial_token):
647
+ return partial_token.replace(" ", "")
648
+
649
+ def restart_huggingface_space(space_name, space_id, partial_token):
650
+ token = _reconstruct_token(partial_token)
651
+ url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
652
+ headers = {
653
+ "Content-Type": "application/json",
654
+ "Authorization": f"Bearer {token}",
655
+ "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"
656
+ }
657
+ try:
658
+ response = requests.post(url, headers=headers, json={})
659
+ return {
660
+ "status_code": response.status_code,
661
+ "success": response.status_code == 200,
662
+ "message": response.text
663
+ }
664
+ except requests.RequestException as e:
665
+ return {
666
+ "status_code": None,
667
+ "success": False,
668
+ "message": str(e)
669
+ }
670
+
671
+
672
+ def check_system_resources():
673
+ time.sleep(120)
674
+ cpu_usage = psutil.cpu_percent(interval=1)
675
+ memory = psutil.virtual_memory()
676
+ memory_usage = memory.percent
677
+ if cpu_usage >= 90 or memory_usage >= 95:
678
+ print("占用过高")
679
+ telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}CUP 内存占用过高,开始重启")
680
+ response = create_space(1)
681
+ full_name = response["name"]
682
+ tmp_name = full_name.split("/")[-1]
683
+ # log = f"“原始创建Space返回:{response} name字段:{full_name} Space 名称{tmp_name}"
684
+ log = f"Original create Space response: {response} | name field: {full_name} | Space name: {tmp_name}"
685
+ telegram_message(BOT_TOKEN, CHAT_ID, log)
686
+ print(log)
687
+ create_space(3,"BACKUP_TIME",BACKUP_TIME,tmp_name)
688
+ create_space(3,"HF_USER1",HF_USER1,tmp_name)
689
+ create_space(3,"HF_REPO",HF_REPO,tmp_name)
690
+ create_space(3,"HF_EMAIL",HF_EMAIL,tmp_name)
691
+ create_space(3,"HF_TOKEN1",HF_TOKEN1,tmp_name)
692
+ create_space(3,"HF_USER2",HF_USER2,tmp_name)
693
+ create_space(3,"HF_EMAIL2",HF_EMAIL2,tmp_name)
694
+ create_space(3,"HF_ID",tmp_name,tmp_name)
695
+ create_space(3,"HF_TOKON2",HF_TOKON2,tmp_name)
696
+ create_space(3,"UUID",UUID,tmp_name)
697
+ create_space(3,"N_SERVER","z.282820.xyz:443",tmp_name)
698
+ create_space(3,"CHAT_ID",CHAT_ID,tmp_name)
699
+ create_space(3,"BOT_TOKEN",BOT_TOKEN,tmp_name)
700
+ create_space(3,"HF_SPACES_NAME",HF_ID,tmp_name)
701
+ time.sleep(2)
702
+ result = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKON2)
703
+ print(f"{tmp_name}重启结果:",result)
704
+ # create_space(4,"","",CHAT_ID)
705
+ # result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
706
+ # print(result)
707
+ else:
708
+ print("系统资源正常")
709
+
710
+
711
+ def repeat_task():
712
+ print('备份线程启动aa')
713
+ while True:
714
+ print(f"打包时间:{BACKUP_TIME} 秒")
715
+ time.sleep(int(BACKUP_TIME))
716
+ github(2)
717
+ # telegram_message(BOT_TOKEN, CHAT_ID, "开始")
718
+ github(1)
719
+
720
+ if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('/data/ff/.mozilla/firefox/profiles.ini'):
721
+ # threading.Thread(target=repeat_task, daemon=True).start()
722
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}开始启动")
723
+ while True:
724
+ print("检测到Firefox配置,启动定期重启循环...")
725
+ create_space(5,"","",HF_SPACES_NAME)
726
+ time.sleep(14400)#21600 = 6小时 14400 = 4小时
727
+ github(2)
728
+ response = create_space(1)
729
+ url = response["url"]
730
+ full_name = response["name"]
731
+ tmp_name = full_name.split("/")[-1]
732
+ # log = f"“原始创建Space返回:{response} name字段:{full_name} Space 名称{tmp_name}"
733
+ log = f"Original create Space response: {url} | name field: {full_name} | Space name: {tmp_name}"
734
+ telegram_message(BOT_TOKEN, CHAT_ID, log)
735
+ print(log)
736
+ create_space(3,"BACKUP_TIME",BACKUP_TIME,tmp_name)
737
+ create_space(3,"HF_USER1",HF_USER1,tmp_name)
738
+ create_space(3,"HF_REPO",HF_REPO,tmp_name)
739
+ create_space(3,"HF_EMAIL",HF_EMAIL,tmp_name)
740
+ create_space(3,"HF_TOKEN1",HF_TOKEN1,tmp_name)
741
+ create_space(3,"HF_USER2",HF_USER2,tmp_name)
742
+ create_space(3,"HF_EMAIL2",HF_EMAIL2,tmp_name)
743
+ create_space(3,"HF_ID",tmp_name,tmp_name)
744
+ create_space(3,"HF_TOKON2",HF_TOKON2,tmp_name)
745
+ create_space(3,"UUID",UUID,tmp_name)
746
+ create_space(3,"N_SERVER","z.282820.xyz:443",tmp_name)
747
+ create_space(3,"CHAT_ID",CHAT_ID,tmp_name)
748
+ create_space(3,"BOT_TOKEN",BOT_TOKEN,tmp_name)
749
+ create_space(3,"HF_SPACES_NAME",HF_ID,tmp_name)
750
+ time.sleep(2)
751
+ create_space(4,"","",tmp_name)
752
+ time.sleep(2)
753
+ result = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKON2)
754
+ print(f"{tmp_name}重启结果:",result)
755
+ telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} startup finished")
756
+ # create_space(4,"","",CHAT_ID)
757
+ # result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
758
+ # print(result)
759
+ break
760
+ # github(2)
761
+ # nv1_agent()