TestNotication / app.py
lgccccc's picture
Create app.py
d88fd87 verified
Raw
History Blame Contribute Delete
1.53 kB
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()