Spaces:
Runtime error
Runtime error
File size: 1,533 Bytes
d88fd87 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | from __future__ import annotations
import os
import gradio as gr
from huggingface_hub import HfApi
HF_TOKEN = os.getenv("HF_TOKEN")
SPACE_ID = os.getenv("SPACE_ID") # Hugging Face Spaces 内置环境变量,例如 username/space-name
DISCUSSION_NUM = int(os.getenv("DISCUSSION_NUM", "3")) # 改成你的 discussion 编号
api = HfApi(token=HF_TOKEN)
def send_hf_notification(message: str, profile: gr.OAuthProfile | None) -> str:
if profile is None:
return "请先点击上面的 Sign in with Hugging Face 登录。"
if not HF_TOKEN:
return "错误:没有配置 HF_TOKEN secret。"
if not SPACE_ID:
return "错误:没有找到 SPACE_ID。请确认代码运行在 Hugging Face Space 上。"
username = profile.username # HF username,例如 abidlabs
comment = f"""@{username}
你的任务已经完成:
{message}
"""
api.comment_discussion(
repo_id=SPACE_ID,
repo_type="space",
discussion_num=DISCUSSION_NUM,
comment=comment,
)
return f"已发送 Hugging Face notification 给 @{username}。"
with gr.Blocks() as demo:
gr.Markdown("## Hugging Face Notification Demo")
gr.LoginButton()
msg = gr.Textbox(
label="通知内容",
value="你的任务已经完成,请回到 Space 查看结果。",
)
btn = gr.Button("发送 HF Notification")
out = gr.Textbox(label="结果")
btn.click(
fn=send_hf_notification,
inputs=msg,
outputs=out,
)
demo.launch() |