Qilan2 commited on
Commit
ba9fd0a
·
verified ·
1 Parent(s): 9729c6e

Create ff1.py

Browse files
Files changed (1) hide show
  1. ff1.py +200 -0
ff1.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
13
+
14
+ BACKUP_TIME = os.environ.get('BACKUP_TIME', '120')# 备份时间 10800秒 2小时
15
+
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
+
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
+ def compress_folder(folder_path, output_dir):
48
+ try:
49
+ # 确保输出目录存在
50
+ os.makedirs(output_dir, exist_ok=True)
51
+
52
+ # 使用 pytz 获取中国时区的当前时间戳(毫秒级)
53
+ import pytz
54
+ from datetime import datetime
55
+
56
+ # 设置中国时区
57
+ china_tz = pytz.timezone('Asia/Shanghai')
58
+
59
+ # 获取当前中国时间的时间戳
60
+ timestamp = str(int(datetime.now(china_tz).timestamp() * 1000))
61
+ output_path = os.path.join(output_dir, f'{timestamp}.tar.gz')
62
+
63
+ # 获取已存在的压缩包
64
+ existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz'))
65
+
66
+ # 安全地提取时间戳
67
+ def extract_timestamp(filename):
68
+ # 提取文件名中的数字部分
69
+ match = re.search(r'(\d+)\.tar\.gz$', filename)
70
+ return int(match.group(1)) if match else 0
71
+
72
+ # 如果压缩包数量超过5个,删除最旧的
73
+ if len(existing_archives) >= 3:
74
+ # 按时间戳排序
75
+ existing_archives.sort(key=extract_timestamp)
76
+
77
+ # 删除最旧的压缩包
78
+ oldest_archive = existing_archives[0]
79
+ os.remove(oldest_archive)
80
+ print(f"删除最旧的压缩包:{oldest_archive}")
81
+
82
+ # tar.gz 压缩
83
+ result = subprocess.run(
84
+ ['tar', '-czvf', output_path, folder_path],
85
+ capture_output=True,
86
+ text=True
87
+ )
88
+
89
+ if result.returncode == 0:
90
+ # 计算压缩包大小
91
+ file_size = os.path.getsize(output_path) / 1024 / 1024
92
+
93
+ # 格式化中国时区的时间
94
+ china_time = datetime.now(china_tz)
95
+ formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S')
96
+
97
+ print(f"压缩成功:{output_path}")
98
+ print(f"压缩大小:{file_size:.2f} MB")
99
+ print(f"压缩时间:{formatted_time}")
100
+
101
+ # 返回压缩包名和大小信息
102
+ return f"{os.path.basename(output_path)} 压缩大小:{file_size:.2f} MB 压缩时间:{formatted_time}"
103
+ else:
104
+ print("压缩失败")
105
+ print("错误信息:", result.stderr)
106
+ return None
107
+
108
+ except Exception as e:
109
+ print(f"压缩出错: {e}")
110
+ return None
111
+
112
+
113
+ # 调用函数
114
+ # new_archive = compress_folder('/data/dv1', 'nezha-hf')
115
+ def github(type):
116
+ if type == 1:
117
+ os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data')
118
+ if not os.path.exists(f'/data/{HF_REPO}'):
119
+ git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}"
120
+ print(git)
121
+ os.system(git)
122
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
123
+ os.system(f'git config --global user.name "{HF_USER1}"')
124
+ os.system("ls")
125
+ latest_package = get_latest_local_package(f'/data/{HF_REPO}')
126
+ print(f"最新压缩包路径: {latest_package}")
127
+ # tar -xzvf /data/firefox/1760199222945.tar.gz -C /data
128
+ os.system(f"tar -xzvf {latest_package} -C /data")
129
+ os.system("mv /data/f/ff /data/")
130
+ os.system("rm -rf /data/data /data/f")
131
+
132
+ if type == 2:
133
+ print("开始备份上传HF")
134
+ os.system("mkdir -p /data/f")
135
+ os.system("cp -rf /data/ff /data/f")
136
+ # 备份上传仓库
137
+ new_archive_info = compress_folder('/data/f', f'/data/{HF_REPO}')
138
+ if new_archive_info:
139
+ new_archive, file_size_info = new_archive_info.split(' 压缩大小:')
140
+ os.system(f'git add .')
141
+ os.system(f'git commit -m "{file_size_info}"')
142
+ # os.system('git push -u origin main')
143
+ os.system('git push -f origin main')
144
+ else:
145
+ print("压缩失败,无法提交")
146
+
147
+ def _reconstruct_token(partial_token):
148
+ return partial_token.replace(" ", "")
149
+ def restart_huggingface_space(space_name, space_id, partial_token):
150
+ token = _reconstruct_token(partial_token)
151
+ url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
152
+ headers = {
153
+ "Content-Type": "application/json",
154
+ "Authorization": f"Bearer {token}",
155
+ "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"
156
+ }
157
+ try:
158
+ response = requests.post(url, headers=headers, json={})
159
+ return {
160
+ "status_code": response.status_code,
161
+ "success": response.status_code == 200,
162
+ "message": response.text
163
+ }
164
+ except requests.RequestException as e:
165
+ return {
166
+ "status_code": None,
167
+ "success": False,
168
+ "message": str(e)
169
+ }
170
+ def check_system_resources():
171
+ time.sleep(120)
172
+ cpu_usage = psutil.cpu_percent(interval=1)
173
+ memory = psutil.virtual_memory()
174
+ memory_usage = memory.percent
175
+ if cpu_usage >= 90:
176
+ # if cpu_usage >= 90 or memory_usage >= 90:
177
+ print("占用过高")
178
+ result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
179
+ print(result)
180
+ else:
181
+ print("系统资源正常")
182
+
183
+ def repeat_task():
184
+ print('备份线程启动')
185
+ while True:
186
+ print(f"打包时间:{BACKUP_TIME} 秒")
187
+ time.sleep(int(BACKUP_TIME))# 2小时
188
+ github(2)
189
+ github(1)
190
+
191
+ if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('/data/ff/.mozilla/firefox/profiles.ini'):
192
+ while True:
193
+ print("检测到Firefox配置,启动定期重启循环...")
194
+ time.sleep(21600)# 6小时
195
+ github(2)
196
+ result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
197
+ print(result)
198
+ # break
199
+ github(2)
200
+ # nv1_agent()