admin commited on
Commit
7d11fa9
1 Parent(s): 8b93af5

support self activate

Browse files
Files changed (1) hide show
  1. app.py +40 -63
app.py CHANGED
@@ -2,29 +2,48 @@ import os
2
  import re
3
  import json
4
  import time
 
 
5
  import requests
6
  import schedule
7
  import gradio as gr
8
  import pandas as pd
9
  from tqdm import tqdm
10
  from functools import partial
11
- from bs4 import BeautifulSoup
12
  from datetime import datetime, timedelta
13
- from urllib.parse import urlparse
14
 
15
  TIMEOUT = 15
16
  DELAY = 1
17
 
18
 
19
- def fix_datetime(text: str):
20
- datetime_pattern = r"\b\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def add_six_hours(match):
23
- datetime_str = match.group(0)
24
- dt = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
25
- dt_plus_six = dt + timedelta(hours=6)
26
- return dt_plus_six.strftime("%Y-%m-%d %H:%M:%S")
27
 
 
 
 
28
  return re.sub(datetime_pattern, add_six_hours, text)
29
 
30
 
@@ -60,16 +79,12 @@ def get_studios(username: str):
60
 
61
  return studios
62
 
63
- except requests.exceptions.HTTPError as errh:
64
- print(f"HTTP错误发生: {errh}")
65
- except requests.exceptions.ConnectionError as errc:
66
- print(f"连接错误发生: {errc}")
67
  except requests.exceptions.Timeout as errt:
68
  print(f"请求超时: {errt}, retrying...")
69
  time.sleep(DELAY)
70
  return get_studios(username)
71
 
72
- except requests.exceptions.RequestException as err:
73
  print(f"请求发生错误: {err}")
74
 
75
  return []
@@ -93,19 +108,16 @@ def get_spaces(username: str):
93
  studios = []
94
  for space in spaces:
95
  if space["author"] == username:
96
- studios.append(f"https://huggingface.co/spaces/{space['id']}")
97
 
98
  return studios
99
 
100
- except requests.exceptions.HTTPError as errh:
101
- print(f"HTTP错误发生: {errh}")
102
-
103
  except requests.exceptions.Timeout as errt:
104
  print(f"请求超时: {errt}, retrying...")
105
  time.sleep(DELAY)
106
  return get_spaces(username)
107
 
108
- except requests.exceptions.RequestException as err:
109
  print(f"请求发生错误: {err}")
110
 
111
  return []
@@ -117,48 +129,13 @@ def activate_space(url: str):
117
  # 发送GET请求获取页面内容
118
  response = (
119
  requests.get(url, timeout=TIMEOUT)
120
- if "https://huggingface.co/spaces" in url
121
  else requests.put(url)
122
  )
123
- response.raise_for_status() # 确保请求成功
124
- web_page_content = response.text
125
-
126
- # 使用BeautifulSoup解析页面
127
- soup = BeautifulSoup(web_page_content, "html.parser")
128
-
129
- # 寻找class为btn-lg的按钮
130
- button = soup.find("button", class_="btn-lg")
131
- if not button:
132
- # print("未找到class为'btn-lg'的按钮。")
133
- return success
134
-
135
- # 获取表单的action属性和method属性
136
- form = button.find_parent("form")
137
- if not form:
138
- return "按钮未在表单内找到。"
139
-
140
- form_action = form.get("action")
141
- form_method = form.get("method", "GET").upper() # 默认为GET
142
- host = "https://" + urlparse(url).hostname
143
- if not host in form_action:
144
- form_action = host + form_action
145
-
146
- # 提取表单数据
147
- form_data = {
148
- input_tag.get("name"): input_tag.get("value")
149
- for input_tag in form.find_all("input")
150
- if input_tag.has_attr("name")
151
- }
152
-
153
- # 发送请求提交表单
154
- if form_method == "POST":
155
- response = requests.post(form_action, data=form_data)
156
- else:
157
- response = requests.get(form_action, params=form_data)
158
-
159
- # 打印响应内容
160
- print("提交表单后的页面内容:")
161
- print(response.text)
162
 
163
  except requests.exceptions.Timeout as errt:
164
  print(f"请求超时: {errt}, retrying...")
@@ -179,7 +156,7 @@ def activate(hf_users: str, ms_users: str):
179
  hf_users = os.getenv("hf_users")
180
 
181
  if not ms_users:
182
- ms_users = os.getenv("ms_users")
183
 
184
  hf_usernames = hf_users.split(";")
185
  ms_usernames = ms_users.split(";")
@@ -213,7 +190,7 @@ def monitor(hf_users: str, ms_users: str, period=3):
213
  hf_users = os.getenv("hf_users")
214
 
215
  if not ms_users:
216
- ms_users = os.getenv("ms_users")
217
 
218
  print(f"监控开启中...每 {period} 小时触发")
219
  fixed_activate = partial(activate, hf_users=hf_users, ms_users=ms_users)
@@ -234,7 +211,7 @@ def list_tasks():
234
  return "None"
235
 
236
 
237
- with gr.Blocks() as iface:
238
  gr.Interface(
239
  title="Start keeping all spaces active periodically",
240
  fn=monitor,
@@ -275,4 +252,4 @@ with gr.Blocks() as iface:
275
  allow_flagging="never",
276
  )
277
 
278
- iface.launch()
 
2
  import re
3
  import json
4
  import time
5
+ import random
6
+ import string
7
  import requests
8
  import schedule
9
  import gradio as gr
10
  import pandas as pd
11
  from tqdm import tqdm
12
  from functools import partial
 
13
  from datetime import datetime, timedelta
 
14
 
15
  TIMEOUT = 15
16
  DELAY = 1
17
 
18
 
19
+ def start_monitor(url: str):
20
+ payload = {
21
+ "data": ["", ""],
22
+ "event_data": None, # 使用None来表示null
23
+ "fn_index": 0,
24
+ "trigger_id": 11,
25
+ "session_hash": "".join(
26
+ random.choice(string.ascii_lowercase) for _ in range(11)
27
+ ),
28
+ }
29
+ response = requests.post(f"{url}/queue/join?", json=payload)
30
+ # 检查请求是否成功
31
+ if response.status_code == 200:
32
+ print("请求成功")
33
+ return response.text
34
+
35
+ return None
36
+
37
 
38
+ def add_six_hours(match):
39
+ datetime_str = match.group(0)
40
+ dt = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
41
+ dt_plus_six = dt + timedelta(hours=6)
42
+ return dt_plus_six.strftime("%Y-%m-%d %H:%M:%S")
43
 
44
+
45
+ def fix_datetime(text: str):
46
+ datetime_pattern = r"\b\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b"
47
  return re.sub(datetime_pattern, add_six_hours, text)
48
 
49
 
 
79
 
80
  return studios
81
 
 
 
 
 
82
  except requests.exceptions.Timeout as errt:
83
  print(f"请求超时: {errt}, retrying...")
84
  time.sleep(DELAY)
85
  return get_studios(username)
86
 
87
+ except Exception as err:
88
  print(f"请求发生错误: {err}")
89
 
90
  return []
 
108
  studios = []
109
  for space in spaces:
110
  if space["author"] == username:
111
+ studios.append(f"https://{username}-{space['id']}.hf.space")
112
 
113
  return studios
114
 
 
 
 
115
  except requests.exceptions.Timeout as errt:
116
  print(f"请求超时: {errt}, retrying...")
117
  time.sleep(DELAY)
118
  return get_spaces(username)
119
 
120
+ except Exception as err:
121
  print(f"请求发生错误: {err}")
122
 
123
  return []
 
129
  # 发送GET请求获取页面内容
130
  response = (
131
  requests.get(url, timeout=TIMEOUT)
132
+ if ".hf.space" in url
133
  else requests.put(url)
134
  )
135
+ response.raise_for_status()
136
+
137
+ if "-keep-spaces-active.hf.space" in url:
138
+ start_monitor(url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  except requests.exceptions.Timeout as errt:
141
  print(f"请求超时: {errt}, retrying...")
 
156
  hf_users = os.getenv("hf_users")
157
 
158
  if not ms_users:
159
+ ms_users = hf_users
160
 
161
  hf_usernames = hf_users.split(";")
162
  ms_usernames = ms_users.split(";")
 
190
  hf_users = os.getenv("hf_users")
191
 
192
  if not ms_users:
193
+ ms_users = hf_users
194
 
195
  print(f"监控开启中...每 {period} 小时触发")
196
  fixed_activate = partial(activate, hf_users=hf_users, ms_users=ms_users)
 
211
  return "None"
212
 
213
 
214
+ with gr.Blocks() as demo:
215
  gr.Interface(
216
  title="Start keeping all spaces active periodically",
217
  fn=monitor,
 
252
  allow_flagging="never",
253
  )
254
 
255
+ demo.launch()