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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +224 -0
app.py CHANGED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import traceback
4
+ from datetime import datetime, timezone
5
+
6
+ import gradio as gr
7
+ 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="开始任务")
123
+ time.sleep(1)
124
+
125
+ progress(0.4, desc="正在运行任务")
126
+ time.sleep(1)
127
+
128
+ progress(0.7, desc="正在生成结果")
129
+ time.sleep(1)
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}