Qilan2 commited on
Commit
a6a46b5
·
verified ·
1 Parent(s): e179d97

Create bf1.py

Browse files
Files changed (1) hide show
  1. bf1.py +354 -0
bf1.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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_TOKON2 = os.environ.get('HF_TOKON2', '') # huggingface TOKEN
23
+
24
+
25
+
26
+ def get_latest_local_package(directory, pattern='*.tar.gz'):
27
+ try:
28
+ # 构建完整的搜索路径
29
+ search_pattern = os.path.join(directory, pattern)
30
+
31
+ # 查找所有匹配的文件
32
+ files = glob.glob(search_pattern)
33
+
34
+ if not files:
35
+ print("未找到匹配的 nezha-hf 压缩包")
36
+ return None
37
+
38
+ # 获取最新的文件
39
+ latest_file = max(files, key=os.path.getmtime)
40
+
41
+ print(f"找到最新的包: {latest_file}")
42
+ return latest_file
43
+
44
+ except Exception as e:
45
+ print(f"获取最新包时发生错误: {e}")
46
+ return None
47
+
48
+
49
+ def delete_huggingface_lfs_file(filename, repo_id, token):
50
+ """
51
+ 通过Hugging Face API删除LFS文件记录
52
+ """
53
+ try:
54
+ # 1. 查询LFS文件列表
55
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
56
+ headers = {
57
+ "content-type": "application/json",
58
+ "Authorization": f"Bearer {token}",
59
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
60
+ }
61
+
62
+ response = requests.get(url, headers=headers)
63
+ if response.status_code != 200:
64
+ print(f"查询LFS文件失败: {response.status_code} - {response.text}")
65
+ return False
66
+
67
+ lfs_files = response.json()
68
+
69
+ # 2. 查找匹配的文件
70
+ file_to_delete = None
71
+ for file_info in lfs_files:
72
+ if file_info.get('filename') == filename:
73
+ file_to_delete = file_info
74
+ break
75
+
76
+ if not file_to_delete:
77
+ print(f"未找到对应的LFS文件记录: {filename}")
78
+ return False
79
+
80
+ # 3. 删除LFS文件记录
81
+ file_oid = file_to_delete['fileOid']
82
+ delete_url = f"https://huggingface.co/api/models/{repo_id}/lfs-files/{file_oid}?rewriteHistory=true"
83
+
84
+ delete_response = requests.delete(delete_url, headers=headers)
85
+ if delete_response.status_code == 200:
86
+ print(f"成功删除LFS文件记录: {filename} (OID: {file_oid})")
87
+ return True
88
+ else:
89
+ print(f"删除LFS文件记录失败: {delete_response.status_code} - {delete_response.text}")
90
+ return False
91
+
92
+ except Exception as e:
93
+ print(f"删除LFS文件记录时出错: {e}")
94
+ return False
95
+
96
+
97
+ def safe_git_cleanup(repo_path, files_to_remove):
98
+ """
99
+ 安全的Git清理,不会影响现有的备份文件
100
+ """
101
+ try:
102
+ original_dir = os.getcwd()
103
+ os.chdir(repo_path)
104
+
105
+ print(f"执行安全Git清理: {files_to_remove}")
106
+
107
+ # 1. 首先确保工作目录是干净的
108
+ result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
109
+ if result.stdout.strip():
110
+ print("工作目录有未提交的更改,先提交...")
111
+ subprocess.run(['git', 'add', '.'], capture_output=True)
112
+ subprocess.run(['git', 'commit', '-m', '自动提交: 清理前的更改'], capture_output=True)
113
+
114
+ # 2. 只从Git索引中删除指定的文件,但不影响工作目录中的文件
115
+ for filename in files_to_remove:
116
+ if os.path.exists(filename):
117
+ print(f"从Git索引中删除 {filename} (文件仍保留在工作目录)")
118
+ subprocess.run(['git', 'rm', '--cached', filename], capture_output=True)
119
+ else:
120
+ print(f"文件 {filename} 不存在于工作目录,只清理Git引用")
121
+
122
+ # 3. 提交删除操作
123
+ if files_to_remove:
124
+ subprocess.run(['git', 'commit', '-m', f'清理已删除的文件: {", ".join(files_to_remove)}'], capture_output=True)
125
+
126
+ # 4. 执行GC清理但不删除最近的文件
127
+ subprocess.run(['git', 'gc', '--auto'], capture_output=True)
128
+ subprocess.run(['git', 'lfs', 'prune'], capture_output=True)
129
+
130
+ print("安全Git清理完成")
131
+ os.chdir(original_dir)
132
+ return True
133
+
134
+ except Exception as e:
135
+ print(f"安全Git清理时出错: {e}")
136
+ os.chdir(original_dir)
137
+ return False
138
+
139
+
140
+ def get_remote_lfs_files(repo_id, token):
141
+ """
142
+ 获取远程所有的LFS文件列表
143
+ """
144
+ try:
145
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
146
+ headers = {
147
+ "content-type": "application/json",
148
+ "Authorization": f"Bearer {token}",
149
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
150
+ }
151
+
152
+ response = requests.get(url, headers=headers)
153
+ if response.status_code == 200:
154
+ return response.json()
155
+ else:
156
+ print(f"获取远程LFS文件失败: {response.status_code}")
157
+ return []
158
+ except Exception as e:
159
+ print(f"获取远程LFS文件时出错: {e}")
160
+ return []
161
+
162
+
163
+ def cleanup_orphaned_lfs_references(repo_path, repo_id, token, keep_count=3):
164
+ """
165
+ 清理孤儿LFS引用:删除远程存在但本地不存在的文件引用
166
+ """
167
+ try:
168
+ original_dir = os.getcwd()
169
+ os.chdir(repo_path)
170
+
171
+ print("检查孤儿LFS引用...")
172
+
173
+ # 获取远程LFS文件
174
+ remote_files = get_remote_lfs_files(repo_id, token)
175
+ if not remote_files:
176
+ print("无法获取远程LFS文件列表")
177
+ return
178
+
179
+ # 获取本地文件
180
+ local_files = set(glob.glob('*.tar.gz'))
181
+
182
+ # 找出远程存在但本地不存在的文件
183
+ orphaned_files = []
184
+ for remote_file in remote_files:
185
+ filename = remote_file.get('filename')
186
+ if filename and filename not in local_files:
187
+ orphaned_files.append(filename)
188
+
189
+ if orphaned_files:
190
+ print(f"发现孤儿LFS引用: {orphaned_files}")
191
+
192
+ # 删除这些孤儿引用
193
+ for filename in orphaned_files:
194
+ print(f"删除孤儿LFS引用: {filename}")
195
+ delete_huggingface_lfs_file(filename, repo_id, token)
196
+
197
+ print("孤儿LFS引用清理完成")
198
+ os.chdir(original_dir)
199
+
200
+ except Exception as e:
201
+ print(f"清理孤儿LFS引用时出错: {e}")
202
+ os.chdir(original_dir)
203
+
204
+
205
+ def compress_folder(folder_path, output_dir, keep_count=3):
206
+ try:
207
+ # 确保输出目录存在
208
+ os.makedirs(output_dir, exist_ok=True)
209
+
210
+ # 设置中国时区
211
+ china_tz = pytz.timezone('Asia/Shanghai')
212
+
213
+ # 获取当前中国时间的时间戳
214
+ timestamp = str(int(datetime.now(china_tz).timestamp() * 1000))
215
+ output_path = os.path.join(output_dir, f'{timestamp}.tar.gz')
216
+
217
+ # 获取所有压缩包
218
+ existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz'))
219
+
220
+ # 安全地提取时间戳
221
+ def extract_timestamp(filename):
222
+ match = re.search(r'(\d+)\.tar\.gz$', filename)
223
+ return int(match.group(1)) if match else 0
224
+
225
+ files_to_cleanup = []
226
+
227
+ # 如果压缩包数量超过保留数量,删除最旧的
228
+ if len(existing_archives) >= keep_count:
229
+ # 按时间戳排序(从小到大,最旧的在前面)
230
+ existing_archives.sort(key=extract_timestamp)
231
+
232
+ # 计算需要删除的数量
233
+ delete_count = len(existing_archives) - keep_count + 1
234
+
235
+ # 删除最旧的压缩包
236
+ for i in range(delete_count):
237
+ oldest_archive = existing_archives[i]
238
+ oldest_filename = os.path.basename(oldest_archive)
239
+
240
+ try:
241
+ # 删除本地文件
242
+ os.remove(oldest_archive)
243
+ print(f"删除最旧的压缩包:{oldest_filename}")
244
+
245
+ # 记录需要清理的文件名
246
+ files_to_cleanup.append(oldest_filename)
247
+
248
+ # 删除Hugging Face LFS文件记录
249
+ print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
250
+ delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
251
+
252
+ except Exception as e:
253
+ print(f"删除失败 {oldest_archive}: {e}")
254
+
255
+ # 如果有文件需要从Git历史中清理,执行安全清理
256
+ if files_to_cleanup:
257
+ print(f"执行安全Git清理: {files_to_cleanup}")
258
+ safe_git_cleanup(output_dir, files_to_cleanup)
259
+
260
+ # tar.gz 压缩
261
+ result = subprocess.run(
262
+ ['tar', '-czf', output_path, folder_path],
263
+ capture_output=True,
264
+ text=True
265
+ )
266
+
267
+ if result.returncode == 0:
268
+ # 计算压缩包大小
269
+ file_size = os.path.getsize(output_path) / 1024 / 1024
270
+
271
+ # 格式化中国时区的时间
272
+ china_time = datetime.now(china_tz)
273
+ formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S')
274
+
275
+ print(f"压缩成功:{output_path}")
276
+ print(f"压缩大小:{file_size:.2f} MB")
277
+ print(f"压缩时间:{formatted_time}")
278
+ print(f"保留策略:最多保留 {keep_count} 个备份包")
279
+
280
+ # 返回压缩包名和大小信息
281
+ return f"{os.path.basename(output_path)} MB:{file_size:.2f} MB TIME:{formatted_time}"
282
+ else:
283
+ print("压缩失败")
284
+ print("错误信息:", result.stderr)
285
+ return None
286
+
287
+ except Exception as e:
288
+ print(f"压缩出错: {e}")
289
+ return None
290
+
291
+
292
+ def github(type):
293
+ if type == 1:
294
+ os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data')
295
+ if not os.path.exists(f'/data/{HF_REPO}'):
296
+ git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}"
297
+ print(git)
298
+ os.system(git)
299
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
300
+ os.system(f'git config --global user.name "{HF_USER1}"')
301
+ os.system("ls")
302
+ latest_package = get_latest_local_package(f'/data/{HF_REPO}')
303
+ print(f"最新压缩包路径: {latest_package}")
304
+ if latest_package:
305
+ os.system(f"tar -xzf {latest_package} -C /data")
306
+ os.system("mv /data/f/ff /data/")
307
+ os.system("mv /data/data/f/ff /data/")
308
+ os.system("rm -rf /data/data /data/f")
309
+
310
+ if type == 2:
311
+ print(f"开始备份上传HF仓库:{HF_REPO}")
312
+ os.system("mkdir -p /data/f")
313
+ os.system("cp -rf /data/ff /data/f")
314
+
315
+ repo_path = f'/data/{HF_REPO}'
316
+ repo_id = f"{HF_USER1}/{HF_REPO}"
317
+
318
+ # 切换到仓库目录
319
+ os.chdir(repo_path)
320
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
321
+ os.system(f'git config --global user.name "{HF_USER1}"')
322
+
323
+ # 先清理孤儿LFS引用
324
+ cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
325
+
326
+ # 执行Git清理(不影响现有文件)
327
+ os.system('git lfs prune')
328
+ os.system('git gc --auto')
329
+
330
+ # 备份上传仓库
331
+ new_archive_info = compress_folder('/data/f', repo_path, keep_count=3)
332
+ if new_archive_info:
333
+ new_archive, file_size_info = new_archive_info.split(' MB:')
334
+
335
+ os.system("pwd")
336
+ os.system(f'git add .')
337
+ os.system(f'git commit -m "{file_size_info}"')
338
+
339
+ # 正常推送(不再需要强制推送)
340
+ push_result = os.system('git push origin main')
341
+ if push_result != 0:
342
+ print("推送失败,可能有冲突,尝试拉取并合并...")
343
+ os.system('git pull origin main --rebase')
344
+ os.system('git push origin main')
345
+
346
+ # 轻度清理
347
+ os.system('git gc --auto')
348
+ os.system('git lfs prune')
349
+ else:
350
+ print("压缩失败,无法提交")
351
+
352
+ def _reconstruct_token(partial_token):
353
+ return partial_token.replace(" ", "")
354
+ github(2)