wenjiao commited on
Commit
a0daf8e
·
verified ·
1 Parent(s): 535ac7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -113
app.py CHANGED
@@ -8,115 +8,100 @@ from huggingface_hub import HfApi
8
 
9
 
10
  # ============================================================
11
- # 需要你配置的内容
12
  # ============================================================
13
 
14
- # 方式1:推荐。Hugging Face Space 会自动提供 SPACE_ID,例如:
15
  # wenjiao/low_bit_open_llm_leaderboard_5
16
  SPACE_REPO_ID = os.getenv("SPACE_ID")
17
 
18
- # 方式2:如果 SPACE_ID 没拿到,就用你手动的这个。
19
- # 这里改成你自己的 Space repo id
20
  if not SPACE_REPO_ID:
21
- SPACE_REPO_ID = "wenjiao/timer"
22
 
23
- # 你手动创建的 Space Notifications discussion 编号。
24
- # discussion 链接是 /discussions/3,这里就是 3。
25
- DISCUSSION_NUM = int(os.getenv("DISCUSSION_NUM", "1"))
26
 
27
- # Hugging Face token,需要在 Space Settings -> Variables and secrets -> New secret 里配置。
28
- # secret 名字必须叫 HF_TOKEN
29
  HF_TOKEN = os.getenv("HF_TOKEN")
30
 
31
- api = HfApi()
32
-
33
 
34
  # ============================================================
35
- # Hugging Face 通知函数
36
  # ============================================================
37
 
38
- def notify_hf_user(
39
- hf_username: str,
40
- task_name: str,
41
- status: str = "success",
42
- detail: str = "",
43
- result_url: str | None = None,
44
- ):
45
- """
46
- 通过在 Space 的固定 Discussion 中评论并 @ 用户,触发 Hugging Face 原生 notification。
47
-
48
- 参数:
49
- hf_username: 目标 Hugging Face 用户名,不要带 @
50
- task_name: 任务名称
51
- status: success 或 failed
52
- detail: 额外说明
53
- result_url: 可选结果链接
54
- """
55
-
56
  if not HF_TOKEN:
57
  raise RuntimeError(
58
  "没有检测到 HF_TOKEN。请在 Space Settings -> Variables and secrets 里添加 Secret:HF_TOKEN"
59
  )
60
 
61
- if not SPACE_REPO_ID:
62
- raise RuntimeError(
63
- "没有检测到 SPACE_REPO_ID。请检查 SPACE_ID 环境变量,或者在 app.py 里手动填写 SPACE_REPO_ID。"
64
- )
 
 
 
 
65
 
66
- hf_username = hf_username.strip().lstrip("@")
 
67
 
68
  if not hf_username:
69
  raise ValueError("Hugging Face 用户名不能为空。")
70
 
 
 
71
  now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
72
 
73
  if status == "success":
74
- title_line = "✅ Space 任务已完成"
75
  else:
76
- title_line = "❌ Space 任务失败"
77
-
78
- comment = f"""@{hf_username}
79
-
80
- {title_line}
81
-
82
- **任务名称:** `{task_name}`
83
- **Space** `{SPACE_REPO_ID}`
84
- **时间** {now}
85
-
86
- {detail}
87
- """
 
88
 
89
  if result_url:
90
- comment += f"""
 
 
 
91
 
92
- **结果链接:** {result_url}
93
- """
94
 
95
  api.comment_discussion(
96
  repo_id=SPACE_REPO_ID,
97
  repo_type="space",
98
  discussion_num=DISCUSSION_NUM,
99
  comment=comment,
100
- token=HF_TOKEN,
101
  )
102
 
103
- discussion_url = f"https://huggingface.co/spaces/{SPACE_REPO_ID}/discussions/{DISCUSSION_NUM}"
104
  return discussion_url
105
 
106
 
107
  # ============================================================
108
- # 这里替换成你自己的真实任务逻辑
109
  # ============================================================
110
 
111
- def run_real_task(task_name: str, progress=gr.Progress()):
112
  """
113
  这里现在是模拟任务。
114
- 你后面把这里替换成
115
- - 模型推理
116
- - eval 评测
117
- - leaderboard 更新
118
- - 文件生成
119
- - 任何你想跑完后通知用户的任务
120
  """
121
 
122
  progress(0.1, desc="开始任务")
@@ -130,95 +115,125 @@ def run_real_task(task_name: str, progress=gr.Progress()):
130
 
131
  progress(1.0, desc="任务完成")
132
 
133
- result_text = f"任务 `{task_name}` 已经成功完成。"
134
- return result_text
135
 
136
 
137
  # ============================================================
138
- # Gradio 按钮回调
139
  # ============================================================
140
 
141
- def run_and_notify(task_name: str, hf_username: str, result_url: str, progress=gr.Progress()):
142
- task_name = task_name.strip() or "未命名任务"
143
- hf_username = hf_username.strip().lstrip("@")
144
- result_url = result_url.strip()
 
 
 
145
 
146
  if not hf_username:
147
- return "❌ 请输入 Hugging Face 用户名,例如wenjiao,不要写邮箱。"
 
 
 
148
 
149
  try:
150
- # 1. 先跑真实任务
151
  result_text = run_real_task(task_name, progress=progress)
152
 
153
- # 2. 任务成功后触发 Hugging Face 原生通知
154
  discussion_url = notify_hf_user(
155
  hf_username=hf_username,
156
  task_name=task_name,
157
  status="success",
158
  detail=result_text,
159
- result_url=result_url or f"https://huggingface.co/spaces/{SPACE_REPO_ID}",
160
  )
161
 
162
- return f"""✅ 任务完成,并已尝试通过 Hugging Face @ 通知 @{hf_username}
163
-
164
- 任务结果:
165
- {result_text}
166
-
167
- 通知位置:
168
- {discussion_url}
169
- """
170
 
171
  except Exception as e:
172
- error_detail = traceback.format_exc()
173
 
174
- # 任务失败时,也尝试通知用户
175
  try:
176
  discussion_url = notify_hf_user(
177
  hf_username=hf_username,
178
  task_name=task_name,
179
  status="failed",
180
- detail=f"错误信息:\n```text\n{str(e)}\n```",
181
- result_url=result_url or f"https://huggingface.co/spaces/{SPACE_REPO_ID}",
182
  )
183
 
184
- return f"""❌ 任务失败,但已尝试通过 Hugging Face @ 通知 @{hf_username}
 
 
 
 
 
 
 
 
185
 
186
- 错误信息:
187
- {str(e)}
 
 
 
 
 
 
 
 
188
 
189
- 通知位置:
190
- {discussion_url}
191
 
192
- 完整错误:
193
- {error_detail}
194
- """
195
 
196
- except Exception as notify_error:
197
- return f"""❌ 任务失败,并且发送 Hugging Face 通知也失败了。
 
 
 
 
 
198
 
199
- 任务错误:
200
- {str(e)}
201
 
202
- 通知错误:
203
- {str(notify_error)}
 
 
 
 
204
 
205
- 完整错误:
206
- {error_detail}
207
- """
 
208
 
 
 
 
 
209
 
210
- # ============================================================
211
- # Gradio UI
212
- # ============================================================
213
 
214
- with gr.Blocks(title="HF Space Notification Demo") as demo:
215
- gr.Markdown(
216
- f"""
217
- # Hugging Face Space 原生通知测试
218
 
219
- 这个 Space 会在任务结束后,自动往固定 Discussion 里评论,并 `@目标用户`。
 
 
 
 
220
 
221
- 当前 Space Repo ID:
222
 
223
- ```text
224
- {SPACE_REPO_ID}
 
8
 
9
 
10
  # ============================================================
11
+ # 基础配置
12
  # ============================================================
13
 
14
+ # Hugging Face Space 通常会自动提供 SPACE_ID,例如:
15
  # wenjiao/low_bit_open_llm_leaderboard_5
16
  SPACE_REPO_ID = os.getenv("SPACE_ID")
17
 
18
+ # 如果 SPACE_ID 没拿到,就用你手动的这个。
19
+ # 这里改成你的 Space 名字
20
  if not SPACE_REPO_ID:
21
+ SPACE_REPO_ID = "wenjiao/low_bit_open_llm_leaderboard_5"
22
 
23
+ # 你的 Space Notifications discussion 编号。
24
+ # 如链接是 /discussions/3,这里就是 3。
25
+ DISCUSSION_NUM = int(os.getenv("DISCUSSION_NUM", "3"))
26
 
27
+ # 在 Space Settings -> Variables and secrets -> New secret 里添加:
28
+ # HF_TOKEN=hf_xxx
29
  HF_TOKEN = os.getenv("HF_TOKEN")
30
 
 
 
31
 
32
  # ============================================================
33
+ # 工具函数
34
  # ============================================================
35
 
36
+ def get_hf_api():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  if not HF_TOKEN:
38
  raise RuntimeError(
39
  "没有检测到 HF_TOKEN。请在 Space Settings -> Variables and secrets 里添加 Secret:HF_TOKEN"
40
  )
41
 
42
+ return HfApi(token=HF_TOKEN)
43
+
44
+
45
+ def clean_hf_username(hf_username):
46
+ hf_username = str(hf_username or "").strip()
47
+ hf_username = hf_username.lstrip("@")
48
+ return hf_username
49
+
50
 
51
+ def notify_hf_user(hf_username, task_name, status, detail, result_url=None):
52
+ hf_username = clean_hf_username(hf_username)
53
 
54
  if not hf_username:
55
  raise ValueError("Hugging Face 用户名不能为空。")
56
 
57
+ api = get_hf_api()
58
+
59
  now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
60
 
61
  if status == "success":
62
+ status_text = "✅ Space 任务已完成"
63
  else:
64
+ status_text = "❌ Space 任务失败"
65
+
66
+ comment_lines = [
67
+ "@" + hf_username,
68
+ "",
69
+ status_text,
70
+ "",
71
+ "任务名称" + str(task_name),
72
+ "Space" + str(SPACE_REPO_ID),
73
+ "时间:" + now,
74
+ "",
75
+ str(detail),
76
+ ]
77
 
78
  if result_url:
79
+ comment_lines.extend([
80
+ "",
81
+ "结果链接:" + str(result_url),
82
+ ])
83
 
84
+ comment = "\n".join(comment_lines)
 
85
 
86
  api.comment_discussion(
87
  repo_id=SPACE_REPO_ID,
88
  repo_type="space",
89
  discussion_num=DISCUSSION_NUM,
90
  comment=comment,
 
91
  )
92
 
93
+ discussion_url = "https://huggingface.co/spaces/" + SPACE_REPO_ID + "/discussions/" + str(DISCUSSION_NUM)
94
  return discussion_url
95
 
96
 
97
  # ============================================================
98
+ # 这里替换成你自己的真实任务
99
  # ============================================================
100
 
101
+ def run_real_task(task_name, progress=gr.Progress()):
102
  """
103
  这里现在是模拟任务。
104
+ 你后面可以 time.sleep 几行换成你的模型推理、评测、排行榜更新等代码。
 
 
 
 
 
105
  """
106
 
107
  progress(0.1, desc="开始任务")
 
115
 
116
  progress(1.0, desc="任务完成")
117
 
118
+ return "任务 " + str(task_name) + " 已经成功完成。"
 
119
 
120
 
121
  # ============================================================
122
+ # Gradio 回调函数
123
  # ============================================================
124
 
125
+ def run_and_notify(task_name, hf_username, result_url, progress=gr.Progress()):
126
+ task_name = str(task_name or "").strip()
127
+ hf_username = clean_hf_username(hf_username)
128
+ result_url = str(result_url or "").strip()
129
+
130
+ if not task_name:
131
+ task_name = "未命名任务"
132
 
133
  if not hf_username:
134
+ return "❌ 请输入 Hugging Face 用户名,例如 wenjiao,不要写邮箱。"
135
+
136
+ if not result_url:
137
+ result_url = "https://huggingface.co/spaces/" + SPACE_REPO_ID
138
 
139
  try:
 
140
  result_text = run_real_task(task_name, progress=progress)
141
 
 
142
  discussion_url = notify_hf_user(
143
  hf_username=hf_username,
144
  task_name=task_name,
145
  status="success",
146
  detail=result_text,
147
+ result_url=result_url,
148
  )
149
 
150
+ return (
151
+ "✅ 任务完成,并已尝试通过 Hugging Face @ 通知 @" + hf_username + "\n\n"
152
+ + "任务结果:\n"
153
+ + result_text
154
+ + "\n\n通知位置:\n"
155
+ + discussion_url
156
+ )
 
157
 
158
  except Exception as e:
159
+ error_text = traceback.format_exc()
160
 
 
161
  try:
162
  discussion_url = notify_hf_user(
163
  hf_username=hf_username,
164
  task_name=task_name,
165
  status="failed",
166
+ detail="错误信息:" + str(e),
167
+ result_url=result_url,
168
  )
169
 
170
+ return (
171
+ "❌ 任务失败,但已尝试通过 Hugging Face @ 通知 @" + hf_username + "\n\n"
172
+ + "错误信息:\n"
173
+ + str(e)
174
+ + "\n\n通知位置:\n"
175
+ + discussion_url
176
+ + "\n\n完整错误:\n"
177
+ + error_text
178
+ )
179
 
180
+ except Exception as notify_error:
181
+ return (
182
+ "❌ 任务失败,并且发送 Hugging Face 通知也失败了。\n\n"
183
+ + "任务错误:\n"
184
+ + str(e)
185
+ + "\n\n通知错误:\n"
186
+ + str(notify_error)
187
+ + "\n\n完整错误:\n"
188
+ + error_text
189
+ )
190
 
 
 
191
 
192
+ # ============================================================
193
+ # Gradio 页面
194
+ # ============================================================
195
 
196
+ description_text = (
197
+ "# Hugging Face Space 原生通知测试\n\n"
198
+ + "点击按钮后,Space 会模拟运行一个任务。任务结束后,会自动往固定 Discussion 里评论,并 @ 目标用户。\n\n"
199
+ + "当前 Space Repo ID:`" + str(SPACE_REPO_ID) + "`\n\n"
200
+ + "当前 Discussion Num:`" + str(DISCUSSION_NUM) + "`\n\n"
201
+ + "请确认你已经在 Space Settings 里添加 Secret:`HF_TOKEN=你的 Hugging Face token`。\n"
202
+ )
203
 
204
+ with gr.Blocks(title="HF Space Notification Demo") as demo:
205
+ gr.Markdown(description_text)
206
 
207
+ with gr.Row():
208
+ task_name_input = gr.Textbox(
209
+ label="任务名称",
210
+ value="test-eval-job",
211
+ placeholder="例如:llm-eval-run-001",
212
+ )
213
 
214
+ hf_username_input = gr.Textbox(
215
+ label="要通知的 Hugging Face 用户名",
216
+ placeholder="例如:wenjiao,不要带 @,不要写邮箱",
217
+ )
218
 
219
+ result_url_input = gr.Textbox(
220
+ label="结果链接,可不填",
221
+ placeholder="https://huggingface.co/spaces/" + str(SPACE_REPO_ID),
222
+ )
223
 
224
+ run_button = gr.Button("运行任务并触发 Hugging Face 通知", variant="primary")
 
 
225
 
226
+ output = gr.Textbox(
227
+ label="运行状态",
228
+ lines=12,
229
+ )
230
 
231
+ run_button.click(
232
+ fn=run_and_notify,
233
+ inputs=[task_name_input, hf_username_input, result_url_input],
234
+ outputs=output,
235
+ )
236
 
 
237
 
238
+ demo.queue()
239
+ demo.launch()