Qilan2 commited on
Commit
b5b576b
·
verified ·
1 Parent(s): 6aec0a3

Update ff.py

Browse files
Files changed (1) hide show
  1. ff.py +232 -36
ff.py CHANGED
@@ -9,26 +9,27 @@ import psutil
9
  import glob
10
  import re
11
  import pytz
 
12
 
 
 
 
 
 
 
 
 
 
13
 
14
- BACKUP_TIME = os.environ.get('BACKUP_TIME', '1200')# 备份时间 10800秒 2小时
15
- BACKUP_TIME = 30
16
- HF_USER1 = os.environ.get('HF_USER1', '')# HF 备份仓库的用户名
17
- HF_REPO = os.environ.get('HF_REPO', '')#HF 备份的Models仓库名
18
- HF_EMAIL = os.environ.get('HF_EMAIL', '') #HF的邮箱
19
- HF_TOKEN1 = os.environ.get('HF_TOKEN1', '')#HF备份账号的TOKEN
20
 
21
- HF_USER2 = os.environ.get('HF_USER2', '')# huggingface 用户名
22
- HF_ID = os.environ.get('HF_ID', '')# huggingface space 名
23
- HF_TOKEN2 = os.environ.get('HF_TOKON2', '')# huggingface TOKEN
24
- #JUPYTER_TOKEN
25
  def cf():
26
  os.system("rm -r /data/cf")
27
  os.system("wget -O '/data/cf' -q 'https://github.com/cloudflare/cloudflared/releases/download/2025.9.0/cloudflared-linux-amd64'")
28
  os.system("chmod +x /data/cf")
29
  # hf-ff.ql02.ggff.net
30
- os.system('/data/cf tunnel run --token eyJhIjoiZWM1MTk5ZTYwZGYxYWI2YmM2OTdhMGYzMTAzYzY4NTUiLCJ0IjoiOTY0NDIwODgtN2RkOS00Y2IwLThhMDEtYTI1YzZmMjAwZjBlIiwicyI6Ik9XSmpNVFpsTjJZdE5UWTRNQzAwTW1VMkxUaGxaREV0T1RRNU1EZzROVFV3T0dFeiJ9')
31
- threading.Thread(target=cf, daemon=True).start()
 
32
  def get_latest_local_package(directory, pattern='*.tar.gz'):
33
  try:
34
  # 构建完整的搜索路径
@@ -50,15 +51,169 @@ def get_latest_local_package(directory, pattern='*.tar.gz'):
50
  except Exception as e:
51
  print(f"获取最新包时发生错误: {e}")
52
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def compress_folder(folder_path, output_dir, keep_count=3):
54
  try:
55
  # 确保输出目录存在
56
  os.makedirs(output_dir, exist_ok=True)
57
 
58
- # 使用 pytz 获取中国时区的当前时间戳(毫秒级)
59
- import pytz
60
- from datetime import datetime
61
-
62
  # 设置中国时区
63
  china_tz = pytz.timezone('Asia/Shanghai')
64
 
@@ -71,10 +226,11 @@ def compress_folder(folder_path, output_dir, keep_count=3):
71
 
72
  # 安全地提取时间戳
73
  def extract_timestamp(filename):
74
- # 提取文件名中的数字部分
75
  match = re.search(r'(\d+)\.tar\.gz$', filename)
76
  return int(match.group(1)) if match else 0
77
 
 
 
78
  # 如果压缩包数量超过保留数量,删除最旧的
79
  if len(existing_archives) >= keep_count:
80
  # 按时间戳排序(从小到大,最旧的在前面)
@@ -86,15 +242,31 @@ def compress_folder(folder_path, output_dir, keep_count=3):
86
  # 删除最旧的压缩包
87
  for i in range(delete_count):
88
  oldest_archive = existing_archives[i]
 
 
89
  try:
 
90
  os.remove(oldest_archive)
91
- print(f"删除最旧的压缩包:{os.path.basename(oldest_archive)}")
 
 
 
 
 
 
 
 
92
  except Exception as e:
93
  print(f"删除失败 {oldest_archive}: {e}")
94
 
 
 
 
 
 
95
  # tar.gz 压缩
96
  result = subprocess.run(
97
- ['tar', '-czvf', output_path, folder_path],
98
  capture_output=True,
99
  text=True
100
  )
@@ -124,8 +296,6 @@ def compress_folder(folder_path, output_dir, keep_count=3):
124
  return None
125
 
126
 
127
- # 调用函数
128
- # new_archive = compress_folder('/data/dv1', 'nezha-hf')
129
  def github(type):
130
  if type == 1:
131
  os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data')
@@ -138,33 +308,56 @@ def github(type):
138
  os.system("ls")
139
  latest_package = get_latest_local_package(f'/data/{HF_REPO}')
140
  print(f"最新压缩包路径: {latest_package}")
141
- # tar -xzvf /data/firefox/1760199222945.tar.gz -C /data
142
- os.system(f"tar -xzf {latest_package} -C /data")
143
- os.system("mv /data/f/ff /data/")
144
- os.system("mv /data/data/f/ff /data/")
145
- os.system("rm -rf /data/data /data/f")
146
 
147
  if type == 2:
148
  print(f"开始备份上传HF仓库:{HF_REPO}")
149
  os.system("mkdir -p /data/f")
150
  os.system("cp -rf /data/ff /data/f")
 
 
 
 
 
 
 
 
 
 
 
151
  os.system('git lfs prune')
 
 
152
  # 备份上传仓库
153
- new_archive_info = compress_folder('/data/f', f'/data/{HF_REPO}', keep_count=3)
154
  if new_archive_info:
155
  new_archive, file_size_info = new_archive_info.split(' MB:')
156
- os.chdir(f'/data/{HF_REPO}')
157
  os.system("pwd")
158
  os.system(f'git add .')
159
  os.system(f'git commit -m "{file_size_info}"')
160
- # os.system('git push -u origin main')
161
- os.system('git push -f origin main')
162
- os.system('git gc --prune=now')
 
 
 
 
 
 
 
 
163
  else:
164
  print("压缩失败,无法提交")
165
 
 
166
  def _reconstruct_token(partial_token):
167
  return partial_token.replace(" ", "")
 
168
  def restart_huggingface_space(space_name, space_id, partial_token):
169
  token = _reconstruct_token(partial_token)
170
  url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
@@ -186,25 +379,28 @@ def restart_huggingface_space(space_name, space_id, partial_token):
186
  "success": False,
187
  "message": str(e)
188
  }
 
 
189
  def check_system_resources():
190
  time.sleep(120)
191
  cpu_usage = psutil.cpu_percent(interval=1)
192
  memory = psutil.virtual_memory()
193
  memory_usage = memory.percent
194
- # if cpu_usage >= 90:
195
  if cpu_usage >= 90 or memory_usage >= 95:
196
  print("占用过高")
197
- result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
198
  print(result)
199
  else:
200
  print("系统资源正常")
201
-
 
202
  def repeat_task():
203
  print('备份线程启动')
204
  while True:
205
  print(f"打包时间:{BACKUP_TIME} 秒")
206
- time.sleep(int(BACKUP_TIME))# 2小时
207
  github(2)
 
208
  github(1)
209
 
210
  if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('/data/ff/.mozilla/firefox/profiles.ini'):
@@ -215,6 +411,6 @@ if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('
215
  github(2)
216
  result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
217
  print(result)
218
- # break
219
  # github(2)
220
  # nv1_agent()
 
9
  import glob
10
  import re
11
  import pytz
12
+ import requests
13
 
14
+ BACKUP_TIME = os.environ.get('BACKUP_TIME', '1200') # 备份时间 10800秒 2小时
15
+ HF_USER1 = os.environ.get('HF_USER1', '') # HF 备份仓库的用户名
16
+ HF_REPO = os.environ.get('HF_REPO', '') # HF 备份的Models仓库名
17
+ HF_EMAIL = os.environ.get('HF_EMAIL', '') # HF的邮箱
18
+ HF_TOKEN1 = os.environ.get('HF_TOKEN1', '') # HF备份账号的TOKEN
19
+
20
+ HF_USER2 = os.environ.get('HF_USER2', '') # huggingface 用户名
21
+ HF_ID = os.environ.get('HF_ID', '') # huggingface space 名
22
+ HF_TOKEN2 = os.environ.get('HF_TOKON2', '') # huggingface TOKEN
23
 
 
 
 
 
 
 
24
 
 
 
 
 
25
  def cf():
26
  os.system("rm -r /data/cf")
27
  os.system("wget -O '/data/cf' -q 'https://github.com/cloudflare/cloudflared/releases/download/2025.9.0/cloudflared-linux-amd64'")
28
  os.system("chmod +x /data/cf")
29
  # hf-ff.ql02.ggff.net
30
+ os.system('/data/cf tunnel run --token eyJhIjoiZWM1MTk5ZTYwZGYxYWI2YmM2OTdhMGYzMTA3YzY4NTUiLCJ0IjoiOTY0NDIwODgtN2RkOS00Y2IwLThhMDEtYTI1YzZmMjAwZjBlIiwicyI6Ik9XSmpNVFpsTjJZdE5UWTRNQzAwTW1VMkxUaGxaREV0T1RRNU1EZzROVFV3T0dFeiJ9')
31
+
32
+
33
  def get_latest_local_package(directory, pattern='*.tar.gz'):
34
  try:
35
  # 构建完整的搜索路径
 
51
  except Exception as e:
52
  print(f"获取最新包时发生错误: {e}")
53
  return None
54
+
55
+
56
+ def delete_huggingface_lfs_file(filename, repo_id, token):
57
+ """
58
+ 通过Hugging Face API删除LFS文件记录
59
+ """
60
+ try:
61
+ # 1. 查询LFS文件列表
62
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
63
+ headers = {
64
+ "content-type": "application/json",
65
+ "Authorization": f"Bearer {token}",
66
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
67
+ }
68
+
69
+ response = requests.get(url, headers=headers)
70
+ if response.status_code != 200:
71
+ print(f"查询LFS文件失败: {response.status_code} - {response.text}")
72
+ return False
73
+
74
+ lfs_files = response.json()
75
+
76
+ # 2. 查找匹配的文件
77
+ file_to_delete = None
78
+ for file_info in lfs_files:
79
+ if file_info.get('filename') == filename:
80
+ file_to_delete = file_info
81
+ break
82
+
83
+ if not file_to_delete:
84
+ print(f"未找到对应的LFS文件记录: {filename}")
85
+ return False
86
+
87
+ # 3. 删除LFS文件记录
88
+ file_oid = file_to_delete['fileOid']
89
+ delete_url = f"https://huggingface.co/api/models/{repo_id}/lfs-files/{file_oid}?rewriteHistory=true"
90
+
91
+ delete_response = requests.delete(delete_url, headers=headers)
92
+ if delete_response.status_code == 200:
93
+ print(f"成功删除LFS文件记录: {filename} (OID: {file_oid})")
94
+ return True
95
+ else:
96
+ print(f"删除LFS文件记录失败: {delete_response.status_code} - {delete_response.text}")
97
+ return False
98
+
99
+ except Exception as e:
100
+ print(f"删除LFS文件记录时出错: {e}")
101
+ return False
102
+
103
+
104
+ def safe_git_cleanup(repo_path, files_to_remove):
105
+ """
106
+ 安全的Git清理,不会影响现有的备份文件
107
+ """
108
+ try:
109
+ original_dir = os.getcwd()
110
+ os.chdir(repo_path)
111
+
112
+ print(f"执行安全Git清理: {files_to_remove}")
113
+
114
+ # 1. 首先确保工作目录是干净的
115
+ result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
116
+ if result.stdout.strip():
117
+ print("工作目录有未提交的更改,先提交...")
118
+ subprocess.run(['git', 'add', '.'], capture_output=True)
119
+ subprocess.run(['git', 'commit', '-m', '自动提交: 清理前的更改'], capture_output=True)
120
+
121
+ # 2. 只从Git索引中删除指定的文件,但不影响工作目录中的文件
122
+ for filename in files_to_remove:
123
+ if os.path.exists(filename):
124
+ print(f"从Git索引中删除 {filename} (文件仍保留在工作目录)")
125
+ subprocess.run(['git', 'rm', '--cached', filename], capture_output=True)
126
+ else:
127
+ print(f"文件 {filename} 不存在于工作目录,只清理Git引用")
128
+
129
+ # 3. 提交删除操作
130
+ if files_to_remove:
131
+ subprocess.run(['git', 'commit', '-m', f'清理已删除的文件: {", ".join(files_to_remove)}'], capture_output=True)
132
+
133
+ # 4. 执行GC清理但不删除最近的文件
134
+ subprocess.run(['git', 'gc', '--auto'], capture_output=True)
135
+ subprocess.run(['git', 'lfs', 'prune'], capture_output=True)
136
+
137
+ print("安全Git清理完成")
138
+ os.chdir(original_dir)
139
+ return True
140
+
141
+ except Exception as e:
142
+ print(f"安全Git清理时出错: {e}")
143
+ os.chdir(original_dir)
144
+ return False
145
+
146
+
147
+ def get_remote_lfs_files(repo_id, token):
148
+ """
149
+ 获取远程所有的LFS文件列表
150
+ """
151
+ try:
152
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
153
+ headers = {
154
+ "content-type": "application/json",
155
+ "Authorization": f"Bearer {token}",
156
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
157
+ }
158
+
159
+ response = requests.get(url, headers=headers)
160
+ if response.status_code == 200:
161
+ return response.json()
162
+ else:
163
+ print(f"获取远程LFS文件失败: {response.status_code}")
164
+ return []
165
+ except Exception as e:
166
+ print(f"获取远程LFS文件时出错: {e}")
167
+ return []
168
+
169
+
170
+ def cleanup_orphaned_lfs_references(repo_path, repo_id, token, keep_count=3):
171
+ """
172
+ 清理孤儿LFS引用:删除远程存在但本地不存在的文件引用
173
+ """
174
+ try:
175
+ original_dir = os.getcwd()
176
+ os.chdir(repo_path)
177
+
178
+ print("检查孤儿LFS引用...")
179
+
180
+ # 获取远程LFS文件
181
+ remote_files = get_remote_lfs_files(repo_id, token)
182
+ if not remote_files:
183
+ print("无法获取远程LFS文件列表")
184
+ return
185
+
186
+ # 获取本地文件
187
+ local_files = set(glob.glob('*.tar.gz'))
188
+
189
+ # 找出远程存在但本地不存在的文件
190
+ orphaned_files = []
191
+ for remote_file in remote_files:
192
+ filename = remote_file.get('filename')
193
+ if filename and filename not in local_files:
194
+ orphaned_files.append(filename)
195
+
196
+ if orphaned_files:
197
+ print(f"发现孤儿LFS引用: {orphaned_files}")
198
+
199
+ # 删除这些孤儿引用
200
+ for filename in orphaned_files:
201
+ print(f"删除孤儿LFS引用: {filename}")
202
+ delete_huggingface_lfs_file(filename, repo_id, token)
203
+
204
+ print("孤儿LFS引用清理完成")
205
+ os.chdir(original_dir)
206
+
207
+ except Exception as e:
208
+ print(f"清理孤儿LFS引用时出错: {e}")
209
+ os.chdir(original_dir)
210
+
211
+
212
  def compress_folder(folder_path, output_dir, keep_count=3):
213
  try:
214
  # 确保输出目录存在
215
  os.makedirs(output_dir, exist_ok=True)
216
 
 
 
 
 
217
  # 设置中国时区
218
  china_tz = pytz.timezone('Asia/Shanghai')
219
 
 
226
 
227
  # 安全地提取时间戳
228
  def extract_timestamp(filename):
 
229
  match = re.search(r'(\d+)\.tar\.gz$', filename)
230
  return int(match.group(1)) if match else 0
231
 
232
+ files_to_cleanup = []
233
+
234
  # 如果压缩包数量超过保留数量,删除最旧的
235
  if len(existing_archives) >= keep_count:
236
  # 按时间戳排序(从小到大,最旧的在前面)
 
242
  # 删除最旧的压缩包
243
  for i in range(delete_count):
244
  oldest_archive = existing_archives[i]
245
+ oldest_filename = os.path.basename(oldest_archive)
246
+
247
  try:
248
+ # 删除本地文件
249
  os.remove(oldest_archive)
250
+ print(f"删除最旧的压缩包:{oldest_filename}")
251
+
252
+ # 记录需要清理的文件名
253
+ files_to_cleanup.append(oldest_filename)
254
+
255
+ # 删除Hugging Face LFS文件记录
256
+ print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
257
+ delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
258
+
259
  except Exception as e:
260
  print(f"删除失败 {oldest_archive}: {e}")
261
 
262
+ # 如果有文件需要从Git历史中清理,执行安全清理
263
+ if files_to_cleanup:
264
+ print(f"执行安全Git清理: {files_to_cleanup}")
265
+ safe_git_cleanup(output_dir, files_to_cleanup)
266
+
267
  # tar.gz 压缩
268
  result = subprocess.run(
269
+ ['tar', '-czf', output_path, folder_path],
270
  capture_output=True,
271
  text=True
272
  )
 
296
  return None
297
 
298
 
 
 
299
  def github(type):
300
  if type == 1:
301
  os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data')
 
308
  os.system("ls")
309
  latest_package = get_latest_local_package(f'/data/{HF_REPO}')
310
  print(f"最新压缩包路径: {latest_package}")
311
+ if latest_package:
312
+ os.system(f"tar -xzf {latest_package} -C /data")
313
+ os.system("mv /data/f/ff /data/")
314
+ os.system("mv /data/data/f/ff /data/")
315
+ os.system("rm -rf /data/data /data/f")
316
 
317
  if type == 2:
318
  print(f"开始备份上传HF仓库:{HF_REPO}")
319
  os.system("mkdir -p /data/f")
320
  os.system("cp -rf /data/ff /data/f")
321
+
322
+ repo_path = f'/data/{HF_REPO}'
323
+ repo_id = f"{HF_USER1}/{HF_REPO}"
324
+
325
+ # 切换到仓库目录
326
+ os.chdir(repo_path)
327
+
328
+ # 先清理孤儿LFS引用
329
+ cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
330
+
331
+ # 执行Git清理(不影响现有文件)
332
  os.system('git lfs prune')
333
+ os.system('git gc --auto')
334
+
335
  # 备份上传仓库
336
+ new_archive_info = compress_folder('/data/f', repo_path, keep_count=3)
337
  if new_archive_info:
338
  new_archive, file_size_info = new_archive_info.split(' MB:')
339
+
340
  os.system("pwd")
341
  os.system(f'git add .')
342
  os.system(f'git commit -m "{file_size_info}"')
343
+
344
+ # 正常推送(不再需要强制推送)
345
+ push_result = os.system('git push origin main')
346
+ if push_result != 0:
347
+ print("推送失败,可能有冲突,尝试拉取并合并...")
348
+ os.system('git pull origin main --rebase')
349
+ os.system('git push origin main')
350
+
351
+ # 轻度清理
352
+ os.system('git gc --auto')
353
+ os.system('git lfs prune')
354
  else:
355
  print("压缩失败,无法提交")
356
 
357
+
358
  def _reconstruct_token(partial_token):
359
  return partial_token.replace(" ", "")
360
+
361
  def restart_huggingface_space(space_name, space_id, partial_token):
362
  token = _reconstruct_token(partial_token)
363
  url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
 
379
  "success": False,
380
  "message": str(e)
381
  }
382
+
383
+
384
  def check_system_resources():
385
  time.sleep(120)
386
  cpu_usage = psutil.cpu_percent(interval=1)
387
  memory = psutil.virtual_memory()
388
  memory_usage = memory.percent
 
389
  if cpu_usage >= 90 or memory_usage >= 95:
390
  print("占用过高")
391
+ result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKEN2)
392
  print(result)
393
  else:
394
  print("系统资源正常")
395
+
396
+
397
  def repeat_task():
398
  print('备份线程启动')
399
  while True:
400
  print(f"打包时间:{BACKUP_TIME} 秒")
401
+ time.sleep(int(BACKUP_TIME))
402
  github(2)
403
+
404
  github(1)
405
 
406
  if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('/data/ff/.mozilla/firefox/profiles.ini'):
 
411
  github(2)
412
  result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
413
  print(result)
414
+ break
415
  # github(2)
416
  # nv1_agent()