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

Update nv1/app.py

Browse files
Files changed (1) hide show
  1. nv1/app.py +197 -15
nv1/app.py CHANGED
@@ -9,6 +9,8 @@ import psutil
9
  import glob
10
  import re
11
  import pytz
 
 
12
 
13
  N_PORT = os.environ.get('N_PORT', '8008') # N Z端口 默认8008
14
  ARGO_PORT = os.environ.get('ARGO_PORT', '8009') # Argo(nginx的反代端口)固定隧道端口,留空默认8009
@@ -17,7 +19,7 @@ ARGO_AUTH = os.environ.get('ARGO_AUTH', '') # Argo固定隧道密钥,留空即
17
  DASHBOARD_VERSION = os.environ.get('DASHBOARD_VERSION', 'v1.13.2')# 指定面板的版本,以 v0.00.00 的格式,后续将固定在该版本不会升级,不填则使用默认的 v1.13.2
18
  NZV1_VERSION = os.environ.get('NZV1_VERSION', 'v1.13.1')# 哪吒V1的版本默认v1.13.1
19
  BACKUP_TIME = os.environ.get('BACKUP_TIME', '3600')# 备份时间 10800秒 2小时
20
-
21
 
22
  HF_USER1 = os.environ.get('HF_USER1', '')# HF 备份仓库的用户名
23
  HF_REPO = os.environ.get('HF_REPO', '')#HF 备份的Models仓库名
@@ -234,15 +236,167 @@ def get_latest_local_package(directory, pattern='*.tar.gz'):
234
  print(f"获取最新包时发生错误: {e}")
235
  return None
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  def compress_folder(folder_path, output_dir, keep_count=3):
238
  try:
239
  # 确保输出目录存在
240
  os.makedirs(output_dir, exist_ok=True)
241
 
242
- # 使用 pytz 获取中国时区的当前时间戳(毫秒级)
243
- import pytz
244
- from datetime import datetime
245
-
246
  # 设置中国时区
247
  china_tz = pytz.timezone('Asia/Shanghai')
248
 
@@ -255,10 +409,11 @@ def compress_folder(folder_path, output_dir, keep_count=3):
255
 
256
  # 安全地提取时间戳
257
  def extract_timestamp(filename):
258
- # 提取文件名中的数字部分
259
  match = re.search(r'(\d+)\.tar\.gz$', filename)
260
  return int(match.group(1)) if match else 0
261
 
 
 
262
  # 如果压缩包数量超过保留数量,删除最旧的
263
  if len(existing_archives) >= keep_count:
264
  # 按时间戳排序(从小到大,最旧的在前面)
@@ -270,15 +425,31 @@ def compress_folder(folder_path, output_dir, keep_count=3):
270
  # 删除最旧的压缩包
271
  for i in range(delete_count):
272
  oldest_archive = existing_archives[i]
 
 
273
  try:
 
274
  os.remove(oldest_archive)
275
- print(f"删除最旧的压缩包:{os.path.basename(oldest_archive)}")
 
 
 
 
 
 
 
 
276
  except Exception as e:
277
  print(f"删除失败 {oldest_archive}: {e}")
278
 
 
 
 
 
 
279
  # tar.gz 压缩
280
  result = subprocess.run(
281
- ['tar', '-czvf', output_path, folder_path],
282
  capture_output=True,
283
  text=True
284
  )
@@ -297,7 +468,7 @@ def compress_folder(folder_path, output_dir, keep_count=3):
297
  print(f"保留策略:最多保留 {keep_count} 个备份包")
298
 
299
  # 返回压缩包名和大小信息
300
- return f"{os.path.basename(output_path)} MB{file_size:.2f} MB TIME{formatted_time}"
301
  else:
302
  print("压缩失败")
303
  print("错误信息:", result.stderr)
@@ -321,20 +492,31 @@ def github(type):
321
  os.system(f'git config --global user.name "{HF_USER1}"')
322
  os.chdir(f'/data/{HF_REPO}')
323
  if type == 2:
 
 
324
  os.chdir(f'/data/{HF_REPO}')
325
  print("开始备份上传HF")
326
- # 清理 LFS 存储
 
 
327
  os.system('git lfs prune')
 
328
  # 备份上传仓库
329
  new_archive_info = compress_folder('/data/dv1', f'/data/{HF_REPO}', keep_count=3)
330
  if new_archive_info:
331
- new_archive, file_size_info = new_archive_info.split(' MB')
332
  os.system(f'git add .')
333
  os.system(f'git commit -m "{file_size_info}"')
334
- # os.system('git push -u origin main')
335
- # 使用强制推送并清理
336
- os.system('git push -f origin main')
337
- os.system('git gc --prune=now')
 
 
 
 
 
 
338
  else:
339
  print("压缩失败,无法提交")
340
  def nginx():
 
9
  import glob
10
  import re
11
  import pytz
12
+ import requests
13
+
14
 
15
  N_PORT = os.environ.get('N_PORT', '8008') # N Z端口 默认8008
16
  ARGO_PORT = os.environ.get('ARGO_PORT', '8009') # Argo(nginx的反代端口)固定隧道端口,留空默认8009
 
19
  DASHBOARD_VERSION = os.environ.get('DASHBOARD_VERSION', 'v1.13.2')# 指定面板的版本,以 v0.00.00 的格式,后续将固定在该版本不会升级,不填则使用默认的 v1.13.2
20
  NZV1_VERSION = os.environ.get('NZV1_VERSION', 'v1.13.1')# 哪吒V1的版本默认v1.13.1
21
  BACKUP_TIME = os.environ.get('BACKUP_TIME', '3600')# 备份时间 10800秒 2小时
22
+ BACKUP_TIME = 30
23
 
24
  HF_USER1 = os.environ.get('HF_USER1', '')# HF 备份仓库的用户名
25
  HF_REPO = os.environ.get('HF_REPO', '')#HF 备份的Models仓库名
 
236
  print(f"获取最新包时发生错误: {e}")
237
  return None
238
 
239
+ def delete_huggingface_lfs_file(filename, repo_id, token):
240
+ """
241
+ 通过Hugging Face API删除LFS文件记录
242
+ """
243
+ try:
244
+ # 1. 查询LFS文件列表
245
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
246
+ headers = {
247
+ "content-type": "application/json",
248
+ "Authorization": f"Bearer {token}",
249
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
250
+ }
251
+
252
+ response = requests.get(url, headers=headers)
253
+ if response.status_code != 200:
254
+ print(f"查询LFS文件失败: {response.status_code} - {response.text}")
255
+ return False
256
+
257
+ lfs_files = response.json()
258
+
259
+ # 2. 查找匹配的文件
260
+ file_to_delete = None
261
+ for file_info in lfs_files:
262
+ if file_info.get('filename') == filename:
263
+ file_to_delete = file_info
264
+ break
265
+
266
+ if not file_to_delete:
267
+ print(f"未找到对应的LFS文件记录: {filename}")
268
+ return False
269
+
270
+ # 3. 删除LFS文件记录
271
+ file_oid = file_to_delete['fileOid']
272
+ delete_url = f"https://huggingface.co/api/models/{repo_id}/lfs-files/{file_oid}?rewriteHistory=true"
273
+
274
+ delete_response = requests.delete(delete_url, headers=headers)
275
+ if delete_response.status_code == 200:
276
+ print(f"成功删除LFS文件记录: {filename} (OID: {file_oid})")
277
+ return True
278
+ else:
279
+ print(f"删除LFS文件记录失败: {delete_response.status_code} - {delete_response.text}")
280
+ return False
281
+
282
+ except Exception as e:
283
+ print(f"删除LFS文件记录时出错: {e}")
284
+ return False
285
+
286
+
287
+ def safe_git_cleanup(repo_path, files_to_remove):
288
+ """
289
+ 安全的Git清理,不会影响现有的备份文件
290
+ """
291
+ try:
292
+ original_dir = os.getcwd()
293
+ os.chdir(repo_path)
294
+
295
+ print(f"执行安全Git清理: {files_to_remove}")
296
+
297
+ # 1. 首先确保工作目录是干净的
298
+ result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
299
+ if result.stdout.strip():
300
+ print("工作目录有未提交的更改,先提交...")
301
+ subprocess.run(['git', 'add', '.'], capture_output=True)
302
+ subprocess.run(['git', 'commit', '-m', '自动提交: 清理前的更改'], capture_output=True)
303
+
304
+ # 2. 只从Git索引中删除指定的文件,但不影响工作目录中的文件
305
+ for filename in files_to_remove:
306
+ if os.path.exists(filename):
307
+ print(f"从Git索引中删除 {filename} (文件仍保留在工作目录)")
308
+ subprocess.run(['git', 'rm', '--cached', filename], capture_output=True)
309
+ else:
310
+ print(f"文件 {filename} 不存在于工作目录,只清理Git引用")
311
+
312
+ # 3. 提交删除操作
313
+ if files_to_remove:
314
+ subprocess.run(['git', 'commit', '-m', f'清理已删除的文件: {", ".join(files_to_remove)}'], capture_output=True)
315
+
316
+ # 4. 执行GC清理但不删除最近的文件
317
+ subprocess.run(['git', 'gc', '--auto'], capture_output=True)
318
+ subprocess.run(['git', 'lfs', 'prune'], capture_output=True)
319
+
320
+ print("安全Git清理完成")
321
+ os.chdir(original_dir)
322
+ return True
323
+
324
+ except Exception as e:
325
+ print(f"安全Git清理时出错: {e}")
326
+ os.chdir(original_dir)
327
+ return False
328
+
329
+
330
+ def get_remote_lfs_files(repo_id, token):
331
+ """
332
+ 获取远程所有的LFS文件列表
333
+ """
334
+ try:
335
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
336
+ headers = {
337
+ "content-type": "application/json",
338
+ "Authorization": f"Bearer {token}",
339
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
340
+ }
341
+
342
+ response = requests.get(url, headers=headers)
343
+ if response.status_code == 200:
344
+ return response.json()
345
+ else:
346
+ print(f"获取远程LFS文件失败: {response.status_code}")
347
+ return []
348
+ except Exception as e:
349
+ print(f"获取远程LFS文件时出错: {e}")
350
+ return []
351
+
352
+
353
+ def cleanup_orphaned_lfs_references(repo_path, repo_id, token, keep_count=3):
354
+ """
355
+ 清理孤儿LFS引用:删除远程存在但本地不存在的文件引用
356
+ """
357
+ try:
358
+ original_dir = os.getcwd()
359
+ os.chdir(repo_path)
360
+
361
+ print("检查孤儿LFS引用...")
362
+
363
+ # 获取远程LFS文件
364
+ remote_files = get_remote_lfs_files(repo_id, token)
365
+ if not remote_files:
366
+ print("无法获取远程LFS文件列表")
367
+ return
368
+
369
+ # 获取本地文件
370
+ local_files = set(glob.glob('*.tar.gz'))
371
+
372
+ # 找出远程存在但本地不存在的文件
373
+ orphaned_files = []
374
+ for remote_file in remote_files:
375
+ filename = remote_file.get('filename')
376
+ if filename and filename not in local_files:
377
+ orphaned_files.append(filename)
378
+
379
+ if orphaned_files:
380
+ print(f"发现孤儿LFS引用: {orphaned_files}")
381
+
382
+ # 删除这些孤儿引用
383
+ for filename in orphaned_files:
384
+ print(f"删除孤儿LFS引用: {filename}")
385
+ delete_huggingface_lfs_file(filename, repo_id, token)
386
+
387
+ print("孤儿LFS引用清理完成")
388
+ os.chdir(original_dir)
389
+
390
+ except Exception as e:
391
+ print(f"清理孤儿LFS引用时出错: {e}")
392
+ os.chdir(original_dir)
393
+
394
+
395
  def compress_folder(folder_path, output_dir, keep_count=3):
396
  try:
397
  # 确保输出目录存在
398
  os.makedirs(output_dir, exist_ok=True)
399
 
 
 
 
 
400
  # 设置中国时区
401
  china_tz = pytz.timezone('Asia/Shanghai')
402
 
 
409
 
410
  # 安全地提取时间戳
411
  def extract_timestamp(filename):
 
412
  match = re.search(r'(\d+)\.tar\.gz$', filename)
413
  return int(match.group(1)) if match else 0
414
 
415
+ files_to_cleanup = []
416
+
417
  # 如果压缩包数量超过保留数量,删除最旧的
418
  if len(existing_archives) >= keep_count:
419
  # 按时间戳排序(从小到大,最旧的在前面)
 
425
  # 删除最旧的压缩包
426
  for i in range(delete_count):
427
  oldest_archive = existing_archives[i]
428
+ oldest_filename = os.path.basename(oldest_archive)
429
+
430
  try:
431
+ # 删除本地文件
432
  os.remove(oldest_archive)
433
+ print(f"删除最旧的压缩包:{oldest_filename}")
434
+
435
+ # 记录需要清理的文件名
436
+ files_to_cleanup.append(oldest_filename)
437
+
438
+ # 删除Hugging Face LFS文件记录
439
+ print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
440
+ delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
441
+
442
  except Exception as e:
443
  print(f"删除失败 {oldest_archive}: {e}")
444
 
445
+ # 如果有文件需要从Git历史中清理,执行安全清理
446
+ if files_to_cleanup:
447
+ print(f"执行安全Git清理: {files_to_cleanup}")
448
+ safe_git_cleanup(output_dir, files_to_cleanup)
449
+
450
  # tar.gz 压缩
451
  result = subprocess.run(
452
+ ['tar', '-czf', output_path, folder_path],
453
  capture_output=True,
454
  text=True
455
  )
 
468
  print(f"保留策略:最多保留 {keep_count} 个备份包")
469
 
470
  # 返回压缩包名和大小信息
471
+ return f"{os.path.basename(output_path)} MB:{file_size:.2f}MB TIME:{formatted_time}"
472
  else:
473
  print("压缩失败")
474
  print("错误信息:", result.stderr)
 
492
  os.system(f'git config --global user.name "{HF_USER1}"')
493
  os.chdir(f'/data/{HF_REPO}')
494
  if type == 2:
495
+ repo_path = f'/data/{HF_REPO}'
496
+ repo_id = f"{HF_USER1}/{HF_REPO}"
497
  os.chdir(f'/data/{HF_REPO}')
498
  print("开始备份上传HF")
499
+ #清理孤儿LFS引用
500
+ cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
501
+ # 执行Git清理(不影响现有文件)
502
  os.system('git lfs prune')
503
+ os.system('git gc --auto')
504
  # 备份上传仓库
505
  new_archive_info = compress_folder('/data/dv1', f'/data/{HF_REPO}', keep_count=3)
506
  if new_archive_info:
507
+ new_archive, file_size_info = new_archive_info.split('MB:')
508
  os.system(f'git add .')
509
  os.system(f'git commit -m "{file_size_info}"')
510
+ # 正常推送(不再需要强制推送)
511
+ push_result = os.system('git push origin main')
512
+ if push_result != 0:
513
+ print("推送失败,可能有冲突,尝试拉取并合并...")
514
+ os.system('git pull origin main --rebase')
515
+ os.system('git push origin main')
516
+
517
+ # 轻度清理
518
+ os.system('git gc --auto')
519
+ os.system('git lfs prune')
520
  else:
521
  print("压缩失败,无法提交")
522
  def nginx():