Qilan2 commited on
Commit
c98aeba
·
verified ·
1 Parent(s): d59438e

Create fff.py

Browse files
Files changed (1) hide show
  1. fff.py +344 -0
fff.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ DATA_JSON =''' {
20
+ "BACKUP_TIME": "1200",
21
+ "HF_USER1": "qilanqi",
22
+ "HF_REPO": "ff2",
23
+ "HF_EMAIL": "HermanBrand@mffac.com",
24
+ "HF_TOKEN1": "hf_vFdlQdHyRONKbniDwsukVaTe",
25
+ "HF_USER2": "cdddwwer",
26
+ "HF_EMAIL2": "HermanNorris@mffac.com",
27
+ "HF_ID": "dasdw",
28
+ "HF_TOKON2": "hf_lSPmCUGQHIHYYcgF",
29
+ "UUID": "a488076d-0ced-4a83-91c4-c498fce00cff",
30
+ "N_SERVER": "z.282820.xyz:443",
31
+ "CHAT_ID": "-4829459058",
32
+ "BOT_TOKEN": "8259739796:AAGZY4tboUxJ3jnMi1GTpGtV3_-Tf2rMT7I"
33
+ }
34
+ '''
35
+ ff_url = "https://ff1.vv9.dpdns.org/"
36
+ HF_SPACES_NAME = os.environ.get('HF_SPACES_NAME', '')# 上个spaces名
37
+ def assign_vars_from_json(config: dict):
38
+ for key, value in config.items():
39
+ globals()[key] = value
40
+
41
+ if DATA_JSON: # 如果 DATA_JSON 有值
42
+ try:
43
+ config_dict = json.loads(DATA_JSON) # 解析 JSON 字符串
44
+ assign_vars_from_json(config_dict)
45
+ except json.JSONDecodeError:
46
+ raise ValueError("DATA_JSON 环境变量不是合法的 JSON 字符串")
47
+ else: # 如果 DATA_JSON 为空,就从单独的环境变量里取
48
+ BACKUP_TIME = os.environ.get('BACKUP_TIME', '1200') # 备份时间 10800秒 2小时
49
+ HF_USER1 = os.environ.get('HF_USER1', '') # HF 备份仓库的用户名
50
+ HF_REPO = os.environ.get('HF_REPO', '') # HF 备份的Models仓库名
51
+ HF_EMAIL = os.environ.get('HF_EMAIL', '') # HF的邮箱
52
+ HF_TOKEN1 = os.environ.get('HF_TOKEN1', '') # HF备份账号的TOKEN
53
+
54
+ HF_USER2 = os.environ.get('HF_USER2', '') # huggingface 用户名
55
+ HF_ID = os.environ.get('HF_ID', '') # huggingface space 名
56
+ HF_TOKON2 = os.environ.get('HF_TOKON2', '') # huggingface TOKEN
57
+ HF_EMAIL2 = os.environ.get('HF_EMAIL2', '') # HF的邮箱
58
+
59
+ UUID = os.environ.get('UUID', 'a488076d-0ced-4a83-91c4-c498fce00cff') # UUID,如使用v1,在不同的平台部署需要修改,否则会覆盖
60
+ N_SERVER = os.environ.get('N_SERVER', 'z.282820.xyz:443')# N面板域名或ip,
61
+
62
+ CHAT_ID = os.environ.get('CHAT_ID', '')# Telegram chat_id,推送通知
63
+ BOT_TOKEN = os.environ.get('BOT_TOKEN', '')# Telegram bot_token
64
+
65
+ def check_url_status(url, timeout=5):
66
+ """
67
+ 检查URL是否可以正常访问
68
+
69
+ 参数:
70
+ url (str): 要检查的URL地址
71
+ timeout (int): 请求超时时间,默认为5秒
72
+
73
+ 返回:
74
+ bool: 网站是否可以正常访问
75
+ """
76
+ try:
77
+ # 发送GET请求
78
+ response = requests.get(url, timeout=timeout)
79
+
80
+ # 检查响应状态码是否在200-299范围内
81
+ return 200 <= response.status_code < 300
82
+
83
+ except requests.RequestException:
84
+ # 捕获所有请求相关的异常,包括连接错误、超时等
85
+ return False
86
+
87
+ # 使用示例
88
+
89
+
90
+ def random_name(length=8):
91
+ return ''.join(random.choices(string.ascii_lowercase, k=length))
92
+
93
+ def update_value(data: dict, key: str, new_value: str) -> dict:
94
+ if key in data:
95
+ data[key] = new_value
96
+ else:
97
+ print(f"!!! Key '{key}' ON")
98
+ return data
99
+ def telegram_message(bot_token: str, chat_id: str, message: str):
100
+ try:
101
+ # 转义特殊字符,避免MarkdownV2解析错误
102
+ def escape_markdown(text):
103
+ escape_chars = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
104
+ return ''.join('\\' + char if char in escape_chars else char for char in text)
105
+
106
+ # 对消息进行转义
107
+ escaped_message = escape_markdown(message)
108
+
109
+ url = f"https://tgbotapi.9.c.5.b.0.d.0.0.1.0.a.2.ip6.arpa/bot{bot_token}/sendMessage"
110
+
111
+ # 详细的请求参数
112
+ params = {
113
+ "chat_id": chat_id,
114
+ "text": escaped_message,
115
+ "parse_mode": "MarkdownV2"
116
+ }
117
+
118
+ # 禁用不安全请求警告
119
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
120
+
121
+ # 增加超时和详细日志
122
+ response = requests.post(
123
+ url,
124
+ params=params,
125
+ verify=False,
126
+ timeout=10 # 设置超时时间
127
+ )
128
+
129
+ # 打印完整的响应信息
130
+ print(f"Response Status Code: {response.status_code}")
131
+ print(f"Response Content: {response.text}")
132
+
133
+ # 检查响应
134
+ if response.status_code == 200:
135
+ return response.json()
136
+ else:
137
+ return {
138
+ "status_code": response.status_code,
139
+ "text": response.text
140
+ }
141
+
142
+ except requests.exceptions.RequestException as e:
143
+ print(f"请求异常: {e}")
144
+ return {"error": str(e)}
145
+ except Exception as e:
146
+ print(f"未知异常: {e}")
147
+ return {"error": str(e)}
148
+
149
+ def create_space(type,key = "", value = "",name = ""):
150
+ if type == 1:
151
+ # 创建spaces
152
+ url = "https://huggingface.co/api/repos/create"
153
+ headers = {
154
+ "Content-Type": "application/json",
155
+ "Authorization": f"Bearer {HF_TOKON2}"
156
+ }
157
+ name = random_name()
158
+ payload = {
159
+ "name": name,
160
+ "type": "space",
161
+ "private": True,
162
+ "sleepTimeSeconds": 172800,
163
+ # "template": "SpacesExamples/jupyterlab",
164
+ "sdk": "docker"
165
+ }
166
+ # "template": "SpacesExamples/jupyterlab",
167
+ response = requests.post(url, headers=headers, json=payload)
168
+ return response.json()
169
+ if type == 2:
170
+ # 删除spaces
171
+ url = "https://huggingface.co/api/repos/delete"
172
+ headers = {
173
+ "Content-Type": "application/json",
174
+ "Authorization": f"Bearer {HF_TOKON2}"
175
+ }
176
+ payload = {
177
+ "organization": HF_USER2,
178
+ "name": name,
179
+ "type": "space"
180
+ }
181
+ response = requests.delete(url, headers=headers, json=payload)
182
+ return response.text
183
+ if type == 3:
184
+ # 创建spaces 变量
185
+ url = f"https://huggingface.co/api/spaces/{HF_USER2}/{name}/secrets"
186
+ headers = {
187
+ "Content-Type": "application/json",
188
+ "Authorization": f"Bearer {HF_TOKON2}"
189
+ }
190
+ payload = {
191
+ "key": key,
192
+ "value": value,
193
+ "description": ""
194
+ }
195
+ response = requests.post(url, headers=headers, json=payload)
196
+ return response.text
197
+ if type == 4:
198
+ file_path = f"/workdir/{name}/Dockerfile"
199
+ os.system("rm -rf {HF_SPACES_NAME}")
200
+ git = f"git clone https://{HF_USER2}:{HF_TOKON2}@huggingface.co/spaces/{HF_USER2}/{name} /workdir/{name}"
201
+ url = "https://huggingface.co/datasets/Qilan2/ff/raw/main/Dockerfile"
202
+ print(git)
203
+ os.system(git)
204
+ os.system(f'git config --global user.email "{HF_EMAIL2}"')
205
+ os.system(f'git config --global user.name "{HF_USER2}"')
206
+ os.chdir(f'/workdir/{name}')
207
+ os.system(f"rm -rf {file_path}")
208
+ time.sleep(3)
209
+ # 如果文件已存在,先删除
210
+ if os.path.exists(file_path):
211
+ print(f"文件已存在,删除: {file_path}")
212
+ os.remove(file_path)
213
+ print(f"正在下载 {url} 到 {file_path}")
214
+ response = requests.get(url)
215
+ if response.status_code == 200:
216
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
217
+ with open(file_path, "wb") as f:
218
+ f.write(response.content)
219
+ print("下载完成 ✅")
220
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}下载Dockerfile 结果:下载完成 ✅")
221
+ else:
222
+ print(f"下载失败,状态码: {response.status_code}")
223
+ # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}下载Dockerfile下载失败,状态码: {response.status_code}")
224
+
225
+ # os.system(f"wget -O '/data/{tmp_name}/Dockerfile' https://huggingface.co/datasets/Qilan2/ff/raw/main/Dockerfile")
226
+ repo_path = f"//workdir/{name}"
227
+ subprocess.run(["git", "-C", repo_path, "add", "."], check=True)
228
+ subprocess.run(["git", "-C", repo_path, "commit", "-m", "0"], check=True)
229
+ subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True)
230
+ # os.system('git add .')
231
+ # os.system('git commit -m "0"')
232
+ # push_result = os.system('git push origin main')
233
+ # if push_result != 0:
234
+ # print("推送失败,可能有冲突,尝试拉取并合并...")
235
+ # os.system('git pull origin main --rebase')
236
+ # os.system('git push origin main')
237
+ if type == 5:
238
+ # 获取用户的所有空间
239
+ headers = {
240
+ "Authorization": f"Bearer {HF_TOKON2}"
241
+ }
242
+
243
+ # 获取用户的所有空间列表
244
+ response = requests.get(f"https://huggingface.co/api/spaces?author={HF_USER2}", headers=headers)
245
+
246
+ if response.status_code != 200:
247
+ print(f"获取空间列表失败:{response.status_code}")
248
+ return
249
+
250
+ spaces = response.json()
251
+
252
+ # 按创建时间排序
253
+ spaces_sorted = sorted(spaces, key=lambda x: x['createdAt'], reverse=True)
254
+
255
+ # 保留最新的空间
256
+ if len(spaces_sorted) > 1:
257
+ latest_space = spaces_sorted[0]
258
+
259
+ # 遍历并删除其他旧空间
260
+ for space in spaces_sorted[1:]:
261
+ full_name = space['id']
262
+ space_id = full_name.split("/")[-1]
263
+ # 删除spaces
264
+ url = "https://huggingface.co/api/repos/delete"
265
+ headers = {
266
+ "Content-Type": "application/json",
267
+ "Authorization": f"Bearer {HF_TOKON2}"
268
+ }
269
+ payload = {
270
+ "organization": HF_USER2,
271
+ "name": space_id,
272
+ "type": "space"
273
+ }
274
+ delete_response = requests.delete(url, headers=headers, json=payload)
275
+ if delete_response.status_code == 200:
276
+ print(f"成功删除空间:{space_id}")
277
+ telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=OK")
278
+ else:
279
+ print(f"删除空间 {space_id} 失败:{delete_response.status_code}")
280
+ telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=ON")
281
+ def _reconstruct_token(partial_token):
282
+ return partial_token.replace(" ", "")
283
+ def restart_huggingface_space(space_name, space_id, partial_token):
284
+ token = _reconstruct_token(partial_token)
285
+ url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
286
+ headers = {
287
+ "Content-Type": "application/json",
288
+ "Authorization": f"Bearer {token}",
289
+ "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"
290
+ }
291
+ try:
292
+ response = requests.post(url, headers=headers, json={})
293
+ return {
294
+ "status_code": response.status_code,
295
+ "success": response.status_code == 200,
296
+ "message": response.text
297
+ }
298
+ except requests.RequestException as e:
299
+ return {
300
+ "status_code": None,
301
+ "success": False,
302
+ "message": str(e)
303
+ }
304
+
305
+ def run():
306
+ response = create_space(1)
307
+ url = response["url"]
308
+ full_name = response["name"]
309
+ tmp_name = full_name.split("/")[-1]
310
+ log = f"“原始创建Space返回:{response} name字段:{full_name} Space 名称{tmp_name}"
311
+ # log = f"Original create Space response: {url} | name field: {full_name} | Space name: {tmp_name}"
312
+ telegram_message(BOT_TOKEN, CHAT_ID, log)
313
+ print(log)
314
+ create_space(3,"BACKUP_TIME",BACKUP_TIME,tmp_name)
315
+ create_space(3,"HF_USER1",HF_USER1,tmp_name)
316
+ create_space(3,"HF_REPO",HF_REPO,tmp_name)
317
+ create_space(3,"HF_EMAIL",HF_EMAIL,tmp_name)
318
+ create_space(3,"HF_TOKEN1",HF_TOKEN1,tmp_name)
319
+ create_space(3,"HF_USER2",HF_USER2,tmp_name)
320
+ create_space(3,"HF_EMAIL2",HF_EMAIL2,tmp_name)
321
+ create_space(3,"HF_ID",tmp_name,tmp_name)
322
+ create_space(3,"HF_TOKON2",HF_TOKON2,tmp_name)
323
+ create_space(3,"UUID",UUID,tmp_name)
324
+ create_space(3,"N_SERVER","z.282820.xyz:443",tmp_name)
325
+ create_space(3,"CHAT_ID",CHAT_ID,tmp_name)
326
+ create_space(3,"BOT_TOKEN",BOT_TOKEN,tmp_name)
327
+ create_space(3,"HF_SPACES_NAME",HF_ID,tmp_name)
328
+ time.sleep(2)
329
+ create_space(4,"","",tmp_name)
330
+ time.sleep(2)
331
+ result = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKON2)
332
+ print(f"{tmp_name}重启结果:",result)
333
+ telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} 重启结果:{result}")
334
+ os.system(f"rm -rf /workdir/{tmp_name}")
335
+ is_accessible = check_url_status(ff_url)
336
+ print(f"网站 {ff_url} 是否可访问: {is_accessible}")
337
+
338
+ while True:
339
+ time.sleep(1200)#21600 = 6小时 14400 = 4小时
340
+ telegram_message(BOT_TOKEN, CHAT_ID, f"网站 {url} 是否可访问: {is_accessible}")
341
+ is_accessible = check_url_status(ff_url)
342
+ print(f"网站 {url} 是否可访问: {is_accessible}")
343
+ if not is_accessible:
344
+ run()