Spaces:
Running
Running
Upload 8 files
Browse files- README.md +31 -0
- app.py +774 -0
- content.py +65 -0
- gitattributes +34 -0
- gitignore +4 -0
- miniapp.py +71 -0
- miniapp_leaderboard.py +200 -0
- requirements.txt +3 -0
README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: miniapp
|
| 3 |
+
emoji: 🦾
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
app_file: miniapp_leaderboard.py
|
| 8 |
+
pinned: true
|
| 9 |
+
license: apache-2.0
|
| 10 |
+
hf_oauth: false
|
| 11 |
+
failure_strategy: rollback
|
| 12 |
+
tags:
|
| 13 |
+
- leaderboard
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## 部署到 Hugging Face Spaces
|
| 17 |
+
|
| 18 |
+
这个 Space 会把每次提交写入一个 Hugging Face **Dataset**(避免 Space 重启丢数据)。
|
| 19 |
+
|
| 20 |
+
在 Space 的 **Settings → Variables and secrets → Secrets** 里配置:
|
| 21 |
+
|
| 22 |
+
- **HF_TOKEN**: 具有写入 dataset 权限的 token
|
| 23 |
+
- **LEADERBOARD_DATASET**: 目标 dataset repo id,例如 `your-username/miniapp-leaderboard`
|
| 24 |
+
|
| 25 |
+
可选:
|
| 26 |
+
|
| 27 |
+
- **MAX_ENTRIES**: 页面最多加载多少条提交(默认 200)
|
| 28 |
+
|
| 29 |
+
然后 Space 启动后即可使用。
|
| 30 |
+
|
| 31 |
+
(配置参考:`https://huggingface.co/docs/hub/spaces-config-reference`)
|
app.py
ADD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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
from urllib.parse import urlparse
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
APP_NAME = "miniapp"
|
| 14 |
+
|
| 15 |
+
# 在 Space 里通过 Secrets 配置:
|
| 16 |
+
# - HF_TOKEN: 具有写 dataset 权限的 token(Settings -> Variables and secrets -> Secrets)
|
| 17 |
+
# - LEADERBOARD_DATASET: 形如 "your-username/miniapp-leaderboard"(repo_type=dataset)
|
| 18 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
|
| 19 |
+
LEADERBOARD_DATASET = os.environ.get("LEADERBOARD_DATASET", "").strip()
|
| 20 |
+
|
| 21 |
+
# 判断是否运行在 Hugging Face Spaces
|
| 22 |
+
IN_SPACES = bool(
|
| 23 |
+
os.environ.get("SPACE_ID")
|
| 24 |
+
or os.environ.get("SPACE_REPO_NAME")
|
| 25 |
+
or os.environ.get("SPACE_AUTHOR_NAME")
|
| 26 |
+
or os.environ.get("system", "") == "spaces"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
MAX_ENTRIES = int(os.environ.get("MAX_ENTRIES", "200"))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _is_valid_http_url(url: str) -> bool:
|
| 33 |
+
try:
|
| 34 |
+
parsed = urlparse(url)
|
| 35 |
+
return parsed.scheme in ("http", "https") and bool(parsed.netloc)
|
| 36 |
+
except Exception:
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _slug(s: str, max_len: int = 60) -> str:
|
| 41 |
+
s = (s or "").strip().lower()
|
| 42 |
+
s = re.sub(r"[^a-z0-9]+", "-", s)
|
| 43 |
+
s = re.sub(r"-{2,}", "-", s).strip("-")
|
| 44 |
+
return (s[:max_len] or "model")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _api() -> HfApi:
|
| 48 |
+
return HfApi(token=HF_TOKEN)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _ensure_dataset_repo():
|
| 52 |
+
if not HF_TOKEN:
|
| 53 |
+
raise RuntimeError("未配置 HF_TOKEN(Space Secrets)。")
|
| 54 |
+
if not LEADERBOARD_DATASET:
|
| 55 |
+
raise RuntimeError("未配置 LEADERBOARD_DATASET(例如:your-username/miniapp-leaderboard)。")
|
| 56 |
+
api = _api()
|
| 57 |
+
try:
|
| 58 |
+
api.repo_info(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
|
| 59 |
+
except Exception:
|
| 60 |
+
# 不存在则创建(public dataset;你也可以手动创建并设为 private)
|
| 61 |
+
api.create_repo(repo_id=LEADERBOARD_DATASET, repo_type="dataset", private=False, exist_ok=True)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _empty_df() -> pd.DataFrame:
|
| 65 |
+
return pd.DataFrame(columns=["submitted_at", "username", "model_name", "model_api", "notes"])
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _load_submissions_df() -> pd.DataFrame:
|
| 69 |
+
if not HF_TOKEN or not LEADERBOARD_DATASET:
|
| 70 |
+
return _empty_df()
|
| 71 |
+
|
| 72 |
+
api = _api()
|
| 73 |
+
try:
|
| 74 |
+
files = api.list_repo_files(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
|
| 75 |
+
except Exception:
|
| 76 |
+
return _empty_df()
|
| 77 |
+
|
| 78 |
+
sub_files = sorted(
|
| 79 |
+
[f for f in files if f.startswith("submissions/") and f.endswith(".json")],
|
| 80 |
+
reverse=True,
|
| 81 |
+
)[:MAX_ENTRIES]
|
| 82 |
+
|
| 83 |
+
rows = []
|
| 84 |
+
for filename in sub_files:
|
| 85 |
+
try:
|
| 86 |
+
path = hf_hub_download(
|
| 87 |
+
repo_id=LEADERBOARD_DATASET,
|
| 88 |
+
repo_type="dataset",
|
| 89 |
+
filename=filename,
|
| 90 |
+
token=HF_TOKEN,
|
| 91 |
+
)
|
| 92 |
+
with open(path, "r", encoding="utf-8") as fp:
|
| 93 |
+
rows.append(json.load(fp))
|
| 94 |
+
except Exception:
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
if not rows:
|
| 98 |
+
return _empty_df()
|
| 99 |
+
|
| 100 |
+
df = pd.DataFrame(rows)
|
| 101 |
+
for col in ["submitted_at", "username", "model_name", "model_api", "notes"]:
|
| 102 |
+
if col not in df.columns:
|
| 103 |
+
df[col] = ""
|
| 104 |
+
df = df[["submitted_at", "username", "model_name", "model_api", "notes"]]
|
| 105 |
+
df = df.sort_values(by=["submitted_at"], ascending=False, kind="stable")
|
| 106 |
+
return df
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def refresh():
|
| 110 |
+
return _load_submissions_df()
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def submit(model_name: str, model_api: str, notes: str, username: str | None):
|
| 114 |
+
model_name = (model_name or "").strip()
|
| 115 |
+
model_api = (model_api or "").strip()
|
| 116 |
+
notes = (notes or "").strip()
|
| 117 |
+
username = (username or "").strip() or "anonymous"
|
| 118 |
+
|
| 119 |
+
if not model_name:
|
| 120 |
+
return "请填写 **模型名称**。", _load_submissions_df()
|
| 121 |
+
if not model_api:
|
| 122 |
+
return "请填写 **模型 API**。", _load_submissions_df()
|
| 123 |
+
if not _is_valid_http_url(model_api):
|
| 124 |
+
return "**模型 API** 需要是合法的 `http(s)://...` URL。", _load_submissions_df()
|
| 125 |
+
|
| 126 |
+
if not HF_TOKEN:
|
| 127 |
+
return "Space 未配置 **HF_TOKEN**(Secrets),无法写入排行榜。", _load_submissions_df()
|
| 128 |
+
if not LEADERBOARD_DATASET:
|
| 129 |
+
return "Space 未配置 **LEADERBOARD_DATASET**(例如:`your-username/miniapp-leaderboard`)。", _load_submissions_df()
|
| 130 |
+
|
| 131 |
+
_ensure_dataset_repo()
|
| 132 |
+
api = _api()
|
| 133 |
+
|
| 134 |
+
now = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
|
| 135 |
+
safe_model = _slug(model_name)
|
| 136 |
+
safe_user = _slug(username)
|
| 137 |
+
path_in_repo = f"submissions/{now[:10]}/{now}-{safe_user}-{safe_model}.json"
|
| 138 |
+
|
| 139 |
+
payload = {
|
| 140 |
+
"submitted_at": now,
|
| 141 |
+
"username": username,
|
| 142 |
+
"model_name": model_name,
|
| 143 |
+
"model_api": model_api,
|
| 144 |
+
"notes": notes,
|
| 145 |
+
}
|
| 146 |
+
data = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
| 147 |
+
bio = io.BytesIO(data)
|
| 148 |
+
|
| 149 |
+
api.upload_file(
|
| 150 |
+
repo_id=LEADERBOARD_DATASET,
|
| 151 |
+
repo_type="dataset",
|
| 152 |
+
path_or_fileobj=bio,
|
| 153 |
+
path_in_repo=path_in_repo,
|
| 154 |
+
commit_message=f"miniapp: submit {username}/{model_name}",
|
| 155 |
+
token=HF_TOKEN,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
return "已提交并写入 leaderboard。", _load_submissions_df()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def build_demo() -> gr.Blocks:
|
| 162 |
+
with gr.Blocks(title=f"{APP_NAME} leaderboard") as demo:
|
| 163 |
+
gr.Markdown(
|
| 164 |
+
f"## {APP_NAME} leaderboard\n\n"
|
| 165 |
+
"提交你的模型信息后,会写入一个 Hugging Face **Dataset**,并在下方表格展示。\n\n"
|
| 166 |
+
f"- 当前 `LEADERBOARD_DATASET`: `{LEADERBOARD_DATASET or '(未配置)'}`\n"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
with gr.Row():
|
| 170 |
+
with gr.Column(scale=2):
|
| 171 |
+
model_name = gr.Textbox(label="模型名称(必填)", placeholder="例如:my-agent-v1")
|
| 172 |
+
model_api = gr.Textbox(
|
| 173 |
+
label="模型 API(必填)",
|
| 174 |
+
placeholder="例如:https://api.example.com/v1/chat/completions",
|
| 175 |
+
)
|
| 176 |
+
notes = gr.Textbox(label="备注(可选)", lines=4)
|
| 177 |
+
|
| 178 |
+
# 纯前端版:不强制 OAuth;如果你想“只能登录用户提交”,后续再加 LoginButton
|
| 179 |
+
if IN_SPACES:
|
| 180 |
+
username = gr.Textbox(
|
| 181 |
+
label="用户名(可选)",
|
| 182 |
+
placeholder="建议填你的 HF 用户名(也可留空)",
|
| 183 |
+
)
|
| 184 |
+
else:
|
| 185 |
+
username = gr.Textbox(label="用户名(本地调试用)", value="local")
|
| 186 |
+
|
| 187 |
+
submit_btn = gr.Button("提交", variant="primary")
|
| 188 |
+
status = gr.Markdown()
|
| 189 |
+
|
| 190 |
+
with gr.Column(scale=3):
|
| 191 |
+
leaderboard = gr.Dataframe(
|
| 192 |
+
label="Leaderboard(按提交时间倒序)",
|
| 193 |
+
value=_load_submissions_df(),
|
| 194 |
+
interactive=False,
|
| 195 |
+
wrap=True,
|
| 196 |
+
)
|
| 197 |
+
refresh_btn = gr.Button("刷新")
|
| 198 |
+
|
| 199 |
+
submit_btn.click(
|
| 200 |
+
submit,
|
| 201 |
+
inputs=[model_name, model_api, notes, username],
|
| 202 |
+
outputs=[status, leaderboard],
|
| 203 |
+
)
|
| 204 |
+
refresh_btn.click(refresh, inputs=[], outputs=[leaderboard])
|
| 205 |
+
|
| 206 |
+
return demo
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
demo = build_demo()
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def main():
|
| 213 |
+
demo.launch()
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
main()
|
| 218 |
+
|
| 219 |
+
import datetime
|
| 220 |
+
import io
|
| 221 |
+
import json
|
| 222 |
+
import os
|
| 223 |
+
import re
|
| 224 |
+
from urllib.parse import urlparse
|
| 225 |
+
|
| 226 |
+
import gradio as gr
|
| 227 |
+
import pandas as pd
|
| 228 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
APP_NAME = "miniapp"
|
| 232 |
+
|
| 233 |
+
# 在 Space 里通过 Secrets 配置:
|
| 234 |
+
# - HF_TOKEN: 具有写 dataset 权限的 token(Settings -> Variables and secrets -> Secrets)
|
| 235 |
+
# - LEADERBOARD_DATASET: 形如 "your-username/miniapp-leaderboard"(repo_type=dataset)
|
| 236 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
|
| 237 |
+
LEADERBOARD_DATASET = os.environ.get("LEADERBOARD_DATASET", "").strip()
|
| 238 |
+
|
| 239 |
+
# 判断是否运行在 Hugging Face Spaces
|
| 240 |
+
IN_SPACES = bool(
|
| 241 |
+
os.environ.get("SPACE_ID")
|
| 242 |
+
or os.environ.get("SPACE_REPO_NAME")
|
| 243 |
+
or os.environ.get("SPACE_AUTHOR_NAME")
|
| 244 |
+
or os.environ.get("system", "") == "spaces"
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
MAX_ENTRIES = int(os.environ.get("MAX_ENTRIES", "200"))
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _is_valid_http_url(url: str) -> bool:
|
| 251 |
+
try:
|
| 252 |
+
parsed = urlparse(url)
|
| 253 |
+
return parsed.scheme in ("http", "https") and bool(parsed.netloc)
|
| 254 |
+
except Exception:
|
| 255 |
+
return False
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _slug(s: str, max_len: int = 60) -> str:
|
| 259 |
+
s = (s or "").strip().lower()
|
| 260 |
+
s = re.sub(r"[^a-z0-9]+", "-", s)
|
| 261 |
+
s = re.sub(r"-{2,}", "-", s).strip("-")
|
| 262 |
+
return (s[:max_len] or "model")
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _api() -> HfApi:
|
| 266 |
+
return HfApi(token=HF_TOKEN)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _ensure_dataset_repo():
|
| 270 |
+
if not HF_TOKEN:
|
| 271 |
+
raise RuntimeError("未配置 HF_TOKEN(Space Secrets)。")
|
| 272 |
+
if not LEADERBOARD_DATASET:
|
| 273 |
+
raise RuntimeError("未配置 LEADERBOARD_DATASET(例如:your-username/miniapp-leaderboard)。")
|
| 274 |
+
api = _api()
|
| 275 |
+
try:
|
| 276 |
+
api.repo_info(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
|
| 277 |
+
except Exception:
|
| 278 |
+
# 不存在则创建(public dataset;你也可以手动创建并设为 private)
|
| 279 |
+
api.create_repo(repo_id=LEADERBOARD_DATASET, repo_type="dataset", private=False, exist_ok=True)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _load_submissions_df() -> pd.DataFrame:
|
| 283 |
+
if not HF_TOKEN or not LEADERBOARD_DATASET:
|
| 284 |
+
return pd.DataFrame(columns=["submitted_at", "username", "model_name", "model_api", "notes"])
|
| 285 |
+
|
| 286 |
+
api = _api()
|
| 287 |
+
try:
|
| 288 |
+
files = api.list_repo_files(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
|
| 289 |
+
except Exception:
|
| 290 |
+
return pd.DataFrame(columns=["submitted_at", "username", "model_name", "model_api", "notes"])
|
| 291 |
+
|
| 292 |
+
sub_files = sorted(
|
| 293 |
+
[f for f in files if f.startswith("submissions/") and f.endswith(".json")],
|
| 294 |
+
reverse=True,
|
| 295 |
+
)[:MAX_ENTRIES]
|
| 296 |
+
|
| 297 |
+
rows = []
|
| 298 |
+
for filename in sub_files:
|
| 299 |
+
try:
|
| 300 |
+
path = hf_hub_download(
|
| 301 |
+
repo_id=LEADERBOARD_DATASET,
|
| 302 |
+
repo_type="dataset",
|
| 303 |
+
filename=filename,
|
| 304 |
+
token=HF_TOKEN,
|
| 305 |
+
)
|
| 306 |
+
with open(path, "r", encoding="utf-8") as fp:
|
| 307 |
+
rows.append(json.load(fp))
|
| 308 |
+
except Exception:
|
| 309 |
+
continue
|
| 310 |
+
|
| 311 |
+
if not rows:
|
| 312 |
+
return pd.DataFrame(columns=["submitted_at", "username", "model_name", "model_api", "notes"])
|
| 313 |
+
|
| 314 |
+
df = pd.DataFrame(rows)
|
| 315 |
+
# 统一列顺序
|
| 316 |
+
for col in ["submitted_at", "username", "model_name", "model_api", "notes"]:
|
| 317 |
+
if col not in df.columns:
|
| 318 |
+
df[col] = ""
|
| 319 |
+
df = df[["submitted_at", "username", "model_name", "model_api", "notes"]]
|
| 320 |
+
df = df.sort_values(by=["submitted_at"], ascending=False, kind="stable")
|
| 321 |
+
return df
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def refresh():
|
| 325 |
+
return _load_submissions_df()
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def submit(model_name: str, model_api: str, notes: str, username: str | None):
|
| 329 |
+
model_name = (model_name or "").strip()
|
| 330 |
+
model_api = (model_api or "").strip()
|
| 331 |
+
notes = (notes or "").strip()
|
| 332 |
+
username = (username or "").strip() or "anonymous"
|
| 333 |
+
|
| 334 |
+
if not model_name:
|
| 335 |
+
return "请填写 **模型名称**。", _load_submissions_df()
|
| 336 |
+
if not model_api:
|
| 337 |
+
return "请填写 **模型 API**。", _load_submissions_df()
|
| 338 |
+
if not _is_valid_http_url(model_api):
|
| 339 |
+
return "**模型 API** 需要是合法的 `http(s)://...` URL。", _load_submissions_df()
|
| 340 |
+
|
| 341 |
+
if not HF_TOKEN:
|
| 342 |
+
return "Space 未配置 **HF_TOKEN**(Secrets),无法写入排行榜。", _load_submissions_df()
|
| 343 |
+
if not LEADERBOARD_DATASET:
|
| 344 |
+
return "Space 未配置 **LEADERBOARD_DATASET**(例如:`your-username/miniapp-leaderboard`)。", _load_submissions_df()
|
| 345 |
+
|
| 346 |
+
_ensure_dataset_repo()
|
| 347 |
+
api = _api()
|
| 348 |
+
|
| 349 |
+
now = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
|
| 350 |
+
safe_model = _slug(model_name)
|
| 351 |
+
safe_user = _slug(username)
|
| 352 |
+
path_in_repo = f"submissions/{now[:10]}/{now}-{safe_user}-{safe_model}.json"
|
| 353 |
+
|
| 354 |
+
payload = {
|
| 355 |
+
"submitted_at": now,
|
| 356 |
+
"username": username,
|
| 357 |
+
"model_name": model_name,
|
| 358 |
+
"model_api": model_api,
|
| 359 |
+
"notes": notes,
|
| 360 |
+
}
|
| 361 |
+
data = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
| 362 |
+
bio = io.BytesIO(data)
|
| 363 |
+
|
| 364 |
+
api.upload_file(
|
| 365 |
+
repo_id=LEADERBOARD_DATASET,
|
| 366 |
+
repo_type="dataset",
|
| 367 |
+
path_or_fileobj=bio,
|
| 368 |
+
path_in_repo=path_in_repo,
|
| 369 |
+
commit_message=f"miniapp: submit {username}/{model_name}",
|
| 370 |
+
token=HF_TOKEN,
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
return "已提交并写入 leaderboard。", _load_submissions_df()
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
with gr.Blocks(title=f"{APP_NAME} leaderboard") as demo:
|
| 377 |
+
gr.Markdown(
|
| 378 |
+
f"## {APP_NAME} leaderboard\n\n"
|
| 379 |
+
"提交你的模型信息后,会写入一个 Hugging Face **Dataset**,并在下方表格展示。\n\n"
|
| 380 |
+
f"- 当前 `LEADERBOARD_DATASET`: `{LEADERBOARD_DATASET or '(未配置)'}`\n"
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
with gr.Row():
|
| 384 |
+
with gr.Column(scale=2):
|
| 385 |
+
model_name = gr.Textbox(label="模型名称(必填)", placeholder="例如:my-agent-v1")
|
| 386 |
+
model_api = gr.Textbox(
|
| 387 |
+
label="模型 API(必填)",
|
| 388 |
+
placeholder="例如:https://api.example.com/v1/chat/completions",
|
| 389 |
+
)
|
| 390 |
+
notes = gr.Textbox(label="备注(可选)", lines=4)
|
| 391 |
+
|
| 392 |
+
# 纯前端版:不强制 OAuth;在 Space 里建议你自己加 LoginButton 做鉴权
|
| 393 |
+
if IN_SPACES:
|
| 394 |
+
username = gr.Textbox(
|
| 395 |
+
label="用户名(可选)",
|
| 396 |
+
placeholder="建议填你的 HF 用户名(也可留空)",
|
| 397 |
+
)
|
| 398 |
+
else:
|
| 399 |
+
username = gr.Textbox(label="用户名(本地调试用)", value="local")
|
| 400 |
+
|
| 401 |
+
submit_btn = gr.Button("提交", variant="primary")
|
| 402 |
+
status = gr.Markdown()
|
| 403 |
+
with gr.Column(scale=3):
|
| 404 |
+
leaderboard = gr.Dataframe(
|
| 405 |
+
label="Leaderboard(按提交时间倒序)",
|
| 406 |
+
value=_load_submissions_df(),
|
| 407 |
+
interactive=False,
|
| 408 |
+
wrap=True,
|
| 409 |
+
)
|
| 410 |
+
refresh_btn = gr.Button("刷新")
|
| 411 |
+
|
| 412 |
+
submit_btn.click(
|
| 413 |
+
submit,
|
| 414 |
+
inputs=[model_name, model_api, notes, username],
|
| 415 |
+
outputs=[status, leaderboard],
|
| 416 |
+
)
|
| 417 |
+
refresh_btn.click(refresh, inputs=[], outputs=[leaderboard])
|
| 418 |
+
|
| 419 |
+
def main():
|
| 420 |
+
demo.launch()
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
if __name__ == "__main__":
|
| 424 |
+
main()
|
| 425 |
+
|
| 426 |
+
# Display the results
|
| 427 |
+
if HAS_TOKEN and not LOCAL_DEBUG:
|
| 428 |
+
try:
|
| 429 |
+
eval_results = load_dataset(
|
| 430 |
+
RESULTS_DATASET,
|
| 431 |
+
YEAR_VERSION,
|
| 432 |
+
token=TOKEN,
|
| 433 |
+
download_mode="force_redownload",
|
| 434 |
+
verification_mode=VerificationMode.NO_CHECKS,
|
| 435 |
+
)
|
| 436 |
+
except Exception as e:
|
| 437 |
+
print(e)
|
| 438 |
+
eval_results = None
|
| 439 |
+
|
| 440 |
+
try:
|
| 441 |
+
contact_infos = load_dataset(
|
| 442 |
+
CONTACT_DATASET,
|
| 443 |
+
YEAR_VERSION,
|
| 444 |
+
token=TOKEN,
|
| 445 |
+
download_mode="force_redownload",
|
| 446 |
+
verification_mode=VerificationMode.NO_CHECKS,
|
| 447 |
+
)
|
| 448 |
+
except Exception as e:
|
| 449 |
+
print(e)
|
| 450 |
+
contact_infos = None
|
| 451 |
+
else:
|
| 452 |
+
eval_results = None
|
| 453 |
+
contact_infos = None
|
| 454 |
+
|
| 455 |
+
def get_dataframe_from_results(eval_results, split):
|
| 456 |
+
if eval_results is None:
|
| 457 |
+
return pd.DataFrame(columns=EMPTY_LEADERBOARD_COLUMNS)
|
| 458 |
+
local_df = eval_results[split]
|
| 459 |
+
local_df = local_df.map(lambda row: {"model": model_hyperlink(row["url"], row["model"])})
|
| 460 |
+
local_df = local_df.remove_columns(["system_prompt", "url"])
|
| 461 |
+
local_df = local_df.rename_column("model", "Agent name")
|
| 462 |
+
local_df = local_df.rename_column("model_family", "Model family")
|
| 463 |
+
local_df = local_df.rename_column("score", "Average score (%)")
|
| 464 |
+
for i in [1, 2, 3]:
|
| 465 |
+
local_df = local_df.rename_column(f"score_level{i}", f"Level {i} score (%)")
|
| 466 |
+
local_df = local_df.rename_column("date", "Submission date")
|
| 467 |
+
df = pd.DataFrame(local_df)
|
| 468 |
+
df = df.sort_values(by=["Average score (%)"], ascending=False)
|
| 469 |
+
|
| 470 |
+
numeric_cols = [c for c in local_df.column_names if "score" in c]
|
| 471 |
+
df[numeric_cols] = df[numeric_cols].multiply(100).round(decimals=2)
|
| 472 |
+
#df = df.style.format("{:.2%}", subset=numeric_cols)
|
| 473 |
+
|
| 474 |
+
return df
|
| 475 |
+
|
| 476 |
+
#eval_dataframe_val = get_dataframe_from_results(eval_results=eval_results, split="validation")
|
| 477 |
+
eval_dataframe_test = get_dataframe_from_results(eval_results=eval_results, split="test")
|
| 478 |
+
|
| 479 |
+
# Gold answers
|
| 480 |
+
if HAS_TOKEN and not LOCAL_DEBUG:
|
| 481 |
+
gold_dataset = load_dataset(
|
| 482 |
+
INTERNAL_DATA_DATASET,
|
| 483 |
+
f"{YEAR_VERSION}_all",
|
| 484 |
+
token=TOKEN,
|
| 485 |
+
)
|
| 486 |
+
gold_results = {
|
| 487 |
+
split: {row["task_id"]: row for row in gold_dataset[split]}
|
| 488 |
+
for split in ["test", "validation"]
|
| 489 |
+
}
|
| 490 |
+
else:
|
| 491 |
+
gold_results = {"test": {}, "validation": {}}
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def restart_space():
|
| 495 |
+
if IN_SPACES and HAS_TOKEN:
|
| 496 |
+
api.restart_space(repo_id=LEADERBOARD_PATH, token=TOKEN)
|
| 497 |
+
|
| 498 |
+
TYPES = ["markdown", "number", "number", "number", "number", "str", "str", "str"]
|
| 499 |
+
|
| 500 |
+
def add_new_eval(
|
| 501 |
+
#val_or_test: str,
|
| 502 |
+
model: str,
|
| 503 |
+
model_family: str,
|
| 504 |
+
system_prompt: str,
|
| 505 |
+
url: str,
|
| 506 |
+
path_to_file: str,
|
| 507 |
+
organisation: str,
|
| 508 |
+
mail: str,
|
| 509 |
+
profile: gr.OAuthProfile,
|
| 510 |
+
):
|
| 511 |
+
val_or_test = "test"
|
| 512 |
+
try:
|
| 513 |
+
if not HAS_TOKEN or LOCAL_DEBUG:
|
| 514 |
+
return format_error(
|
| 515 |
+
"Submissions are disabled in local mode. Set env TOKEN (Hugging Face token) and rerun to enable submissions."
|
| 516 |
+
)
|
| 517 |
+
# Was the profile created less than 2 month ago?
|
| 518 |
+
user_data = requests.get(f"https://huggingface.co/api/users/{profile.username}/overview")
|
| 519 |
+
creation_date = json.loads(user_data.content)["createdAt"]
|
| 520 |
+
if datetime.datetime.now() - datetime.datetime.strptime(creation_date, '%Y-%m-%dT%H:%M:%S.%fZ') < datetime.timedelta(days=60):
|
| 521 |
+
return format_error("This account is not authorized to submit on GAIA.")
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
contact_infos = load_dataset(CONTACT_DATASET, YEAR_VERSION, token=TOKEN, download_mode="force_redownload", verification_mode=VerificationMode.NO_CHECKS, trust_remote_code=True)
|
| 525 |
+
user_submission_dates = sorted(row["date"] for row in contact_infos[val_or_test] if row["username"] == profile.username)
|
| 526 |
+
if len(user_submission_dates) > 0 and user_submission_dates[-1] == datetime.datetime.today().strftime('%Y-%m-%d'):
|
| 527 |
+
return format_error("You already submitted once today, please try again tomorrow.")
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
is_validation = val_or_test == "validation"
|
| 531 |
+
# Very basic email parsing
|
| 532 |
+
_, parsed_mail = parseaddr(mail)
|
| 533 |
+
if not "@" in parsed_mail:
|
| 534 |
+
return format_warning("Please provide a valid email adress.")
|
| 535 |
+
|
| 536 |
+
print("Adding new eval")
|
| 537 |
+
|
| 538 |
+
# Check if the combination model/org already exists and prints a warning message if yes
|
| 539 |
+
if model.lower() in set([m.lower() for m in eval_results[val_or_test]["model"]]) and organisation.lower() in set([o.lower() for o in eval_results[val_or_test]["organisation"]]):
|
| 540 |
+
return format_warning("This model has been already submitted.")
|
| 541 |
+
|
| 542 |
+
if path_to_file is None:
|
| 543 |
+
return format_warning("Please attach a file.")
|
| 544 |
+
|
| 545 |
+
# SAVE UNSCORED SUBMISSION
|
| 546 |
+
if LOCAL_DEBUG:
|
| 547 |
+
print("mock uploaded submission")
|
| 548 |
+
else:
|
| 549 |
+
api.upload_file(
|
| 550 |
+
repo_id=SUBMISSION_DATASET,
|
| 551 |
+
path_or_fileobj=path_to_file.name,
|
| 552 |
+
path_in_repo=f"{organisation}/{model}/{YEAR_VERSION}_{val_or_test}_raw_{datetime.datetime.today()}.jsonl",
|
| 553 |
+
repo_type="dataset",
|
| 554 |
+
token=TOKEN
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
# SAVE CONTACT
|
| 558 |
+
contact_info = {
|
| 559 |
+
"model": model,
|
| 560 |
+
"model_family": model_family,
|
| 561 |
+
"url": url,
|
| 562 |
+
"organisation": organisation,
|
| 563 |
+
"username": profile.username,
|
| 564 |
+
"mail": mail,
|
| 565 |
+
"date": datetime.datetime.today().strftime('%Y-%m-%d')
|
| 566 |
+
}
|
| 567 |
+
contact_infos[val_or_test]= contact_infos[val_or_test].add_item(contact_info)
|
| 568 |
+
if LOCAL_DEBUG:
|
| 569 |
+
print("mock uploaded contact info")
|
| 570 |
+
else:
|
| 571 |
+
contact_infos.push_to_hub(CONTACT_DATASET, config_name = YEAR_VERSION, token=TOKEN)
|
| 572 |
+
|
| 573 |
+
# SCORE SUBMISSION
|
| 574 |
+
file_path = path_to_file.name
|
| 575 |
+
scores = {"all": 0, 1: 0, 2: 0, 3: 0}
|
| 576 |
+
num_questions = {"all": 0, 1: 0, 2: 0, 3: 0}
|
| 577 |
+
task_ids = []
|
| 578 |
+
with open(f"scored/{organisation}_{model}.jsonl", "w") as scored_file:
|
| 579 |
+
with open(file_path, 'r') as f:
|
| 580 |
+
for ix, line in enumerate(f):
|
| 581 |
+
try:
|
| 582 |
+
task = json.loads(line)
|
| 583 |
+
except Exception:
|
| 584 |
+
return format_error(f"Line {ix} is incorrectly formatted. Please fix it and resubmit your file.")
|
| 585 |
+
|
| 586 |
+
if "model_answer" not in task:
|
| 587 |
+
return format_error(f"Line {ix} contains no model_answer key. Please fix it and resubmit your file.")
|
| 588 |
+
answer = task["model_answer"]
|
| 589 |
+
task_id = task["task_id"]
|
| 590 |
+
try:
|
| 591 |
+
level = int(gold_results[val_or_test][task_id]["Level"])
|
| 592 |
+
except KeyError:
|
| 593 |
+
return format_error(f"{task_id} not found in split {val_or_test}. Are you sure you submitted the correct file?")
|
| 594 |
+
|
| 595 |
+
score = question_scorer(task['model_answer'], gold_results[val_or_test][task_id]["Final answer"])
|
| 596 |
+
|
| 597 |
+
scored_file.write(
|
| 598 |
+
json.dumps({
|
| 599 |
+
"id": task_id,
|
| 600 |
+
"model_answer": answer,
|
| 601 |
+
"score": score,
|
| 602 |
+
"level": level
|
| 603 |
+
}) + "\n"
|
| 604 |
+
)
|
| 605 |
+
task_ids.append(task_id)
|
| 606 |
+
|
| 607 |
+
scores["all"] += score
|
| 608 |
+
scores[level] += score
|
| 609 |
+
num_questions["all"] += 1
|
| 610 |
+
num_questions[level] += 1
|
| 611 |
+
|
| 612 |
+
# Check if there's any duplicate in the submission
|
| 613 |
+
if len(task_ids) != len(set(task_ids)):
|
| 614 |
+
return format_error("There are duplicates in your submission. Please check your file and resubmit it.")
|
| 615 |
+
|
| 616 |
+
if any([num_questions[level] != ref_level_len[val_or_test][level] for level in [1, 2, 3]]):
|
| 617 |
+
return format_error(f"Your submission has {num_questions[1]} questions for level 1, {num_questions[2]} for level 2, and {num_questions[3]} for level 3, but it should have {ref_level_len[val_or_test][1]}, {ref_level_len[val_or_test][2]}, and {ref_level_len[val_or_test][3]} respectively. Please check your submission.")
|
| 618 |
+
|
| 619 |
+
# SAVE SCORED SUBMISSION
|
| 620 |
+
if LOCAL_DEBUG:
|
| 621 |
+
print("mock uploaded scored submission")
|
| 622 |
+
else:
|
| 623 |
+
api.upload_file(
|
| 624 |
+
repo_id=SUBMISSION_DATASET,
|
| 625 |
+
path_or_fileobj=f"scored/{organisation}_{model}.jsonl",
|
| 626 |
+
path_in_repo=f"{organisation}/{model}/{YEAR_VERSION}_{val_or_test}_scored_{datetime.datetime.today()}.jsonl",
|
| 627 |
+
repo_type="dataset",
|
| 628 |
+
token=TOKEN
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
# Save scored file
|
| 632 |
+
if is_validation:
|
| 633 |
+
api.upload_file(
|
| 634 |
+
repo_id=SUBMISSION_DATASET_PUBLIC,
|
| 635 |
+
path_or_fileobj=f"scored/{organisation}_{model}.jsonl",
|
| 636 |
+
path_in_repo=f"{organisation}/{model}/{YEAR_VERSION}_{val_or_test}_scored_{datetime.datetime.today()}.jsonl",
|
| 637 |
+
repo_type="dataset",
|
| 638 |
+
token=TOKEN
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
# SAVE TO LEADERBOARD DATA
|
| 642 |
+
eval_entry = {
|
| 643 |
+
"model": model,
|
| 644 |
+
"model_family": model_family,
|
| 645 |
+
"system_prompt": system_prompt,
|
| 646 |
+
"url": url,
|
| 647 |
+
"organisation": organisation,
|
| 648 |
+
"score": scores["all"]/ref_scores_len[val_or_test],
|
| 649 |
+
"score_level1": scores[1]/num_questions[1],
|
| 650 |
+
"score_level2": scores[2]/num_questions[2],
|
| 651 |
+
"score_level3": scores[3]/num_questions[3],
|
| 652 |
+
"date": datetime.datetime.today().strftime('%Y-%m-%d')
|
| 653 |
+
}
|
| 654 |
+
if num_questions[1] + num_questions[2] + num_questions[3] != ref_scores_len[val_or_test]:
|
| 655 |
+
return format_error(f"Your submission has {len(scores['all'])} questions for the {val_or_test} set, but it should have {ref_scores_len[val_or_test]}. Please check your submission.")
|
| 656 |
+
# Catching spam submissions of 100%
|
| 657 |
+
if all((eval_entry[k] == 1 for k in ["score_level1", "score_level2", "score_level3"])):
|
| 658 |
+
return format_error(f"There was a problem with your submission. Please open a discussion.")
|
| 659 |
+
|
| 660 |
+
# Testing for duplicates - to see if we want to add something like it as it would allow people to try to see the content of other submissions
|
| 661 |
+
#eval_entry_no_date = {k: v for k, v in eval_entry if k != "date"}
|
| 662 |
+
#columns_no_date = [c for c in eval_results[val_or_test].column_names if c != "date"]
|
| 663 |
+
#if eval_entry_no_date in eval_results[val_or_test].select_columns(columns_no_date):
|
| 664 |
+
# return format_error(f"Your submission is an exact duplicate from an existing submission.")
|
| 665 |
+
|
| 666 |
+
eval_results[val_or_test] = eval_results[val_or_test].add_item(eval_entry)
|
| 667 |
+
print(eval_results)
|
| 668 |
+
if LOCAL_DEBUG:
|
| 669 |
+
print("mock uploaded results to lb")
|
| 670 |
+
else:
|
| 671 |
+
eval_results.push_to_hub(RESULTS_DATASET, config_name = YEAR_VERSION, token=TOKEN)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
return format_log(f"Model {model} submitted by {organisation} successfully.\nPlease wait a few hours and refresh the leaderboard to see your score displayed.")
|
| 675 |
+
except Exception as e:
|
| 676 |
+
print(e)
|
| 677 |
+
return format_error(f"An error occurred, please open a discussion and indicate at what time you encountered the error.\n")
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
def refresh():
|
| 681 |
+
if HAS_TOKEN and not LOCAL_DEBUG:
|
| 682 |
+
try:
|
| 683 |
+
eval_results = load_dataset(
|
| 684 |
+
RESULTS_DATASET,
|
| 685 |
+
YEAR_VERSION,
|
| 686 |
+
token=TOKEN,
|
| 687 |
+
download_mode="force_redownload",
|
| 688 |
+
verification_mode=VerificationMode.NO_CHECKS,
|
| 689 |
+
)
|
| 690 |
+
except Exception as e:
|
| 691 |
+
print(e)
|
| 692 |
+
eval_results = None
|
| 693 |
+
else:
|
| 694 |
+
eval_results = None
|
| 695 |
+
return get_dataframe_from_results(eval_results=eval_results, split="test")
|
| 696 |
+
|
| 697 |
+
def upload_file(files):
|
| 698 |
+
file_paths = [file.name for file in files]
|
| 699 |
+
return file_paths
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
demo = gr.Blocks()
|
| 703 |
+
with demo:
|
| 704 |
+
gr.HTML(TITLE)
|
| 705 |
+
gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
|
| 706 |
+
|
| 707 |
+
with gr.Row():
|
| 708 |
+
with gr.Accordion("📙 Citation", open=False):
|
| 709 |
+
citation_button = gr.Textbox(
|
| 710 |
+
value=CITATION_BUTTON_TEXT,
|
| 711 |
+
label=CITATION_BUTTON_LABEL,
|
| 712 |
+
elem_id="citation-button",
|
| 713 |
+
) #.style(show_copy_button=True)
|
| 714 |
+
|
| 715 |
+
gr.Markdown("Results: Test")
|
| 716 |
+
leaderboard_table_test = gr.components.Dataframe(
|
| 717 |
+
value=eval_dataframe_test, datatype=TYPES, interactive=False,
|
| 718 |
+
column_widths=["20%"]
|
| 719 |
+
)
|
| 720 |
+
#with gr.Tab("Results: Validation"):
|
| 721 |
+
# leaderboard_table_val = gr.components.Dataframe(
|
| 722 |
+
# value=eval_dataframe_val, datatype=TYPES, interactive=False,
|
| 723 |
+
# column_widths=["20%"]
|
| 724 |
+
# )
|
| 725 |
+
|
| 726 |
+
refresh_button = gr.Button("Refresh")
|
| 727 |
+
refresh_button.click(
|
| 728 |
+
refresh,
|
| 729 |
+
inputs=[],
|
| 730 |
+
outputs=[
|
| 731 |
+
#leaderboard_table_val,
|
| 732 |
+
leaderboard_table_test,
|
| 733 |
+
],
|
| 734 |
+
)
|
| 735 |
+
with gr.Accordion("Submit a new model for evaluation"):
|
| 736 |
+
with gr.Row():
|
| 737 |
+
gr.Markdown(SUBMISSION_TEXT, elem_classes="markdown-text")
|
| 738 |
+
with gr.Row():
|
| 739 |
+
with gr.Column():
|
| 740 |
+
#level_of_test = gr.Radio(["test"], value="test", label="Split")
|
| 741 |
+
model_name_textbox = gr.Textbox(label="Agent name")
|
| 742 |
+
model_family_textbox = gr.Textbox(label="Model family")
|
| 743 |
+
system_prompt_textbox = gr.Textbox(label="System prompt example")
|
| 744 |
+
url_textbox = gr.Textbox(label="Url to model information")
|
| 745 |
+
with gr.Column():
|
| 746 |
+
organisation = gr.Textbox(label="Organisation")
|
| 747 |
+
mail = gr.Textbox(label="Contact email (will be stored privately, & used if there is an issue with your submission)")
|
| 748 |
+
file_output = gr.File()
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
with gr.Row():
|
| 752 |
+
gr.LoginButton()
|
| 753 |
+
submit_button = gr.Button("Submit Eval On Test")
|
| 754 |
+
submission_result = gr.Markdown()
|
| 755 |
+
submit_button.click(
|
| 756 |
+
add_new_eval,
|
| 757 |
+
[
|
| 758 |
+
#level_of_test,
|
| 759 |
+
model_name_textbox,
|
| 760 |
+
model_family_textbox,
|
| 761 |
+
system_prompt_textbox,
|
| 762 |
+
url_textbox,
|
| 763 |
+
file_output,
|
| 764 |
+
organisation,
|
| 765 |
+
mail
|
| 766 |
+
],
|
| 767 |
+
submission_result,
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
if IN_SPACES and HAS_TOKEN:
|
| 771 |
+
scheduler = BackgroundScheduler()
|
| 772 |
+
scheduler.add_job(restart_space, "interval", seconds=3600)
|
| 773 |
+
scheduler.start()
|
| 774 |
+
demo.launch(debug=True)
|
content.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
TITLE = """<h1 align="center" id="space-title">GAIA Leaderboard</h1>"""
|
| 2 |
+
|
| 3 |
+
INTRODUCTION_TEXT = """
|
| 4 |
+
GAIA is a benchmark which aims at evaluating next-generation LLMs (LLMs with augmented capabilities due to added tooling, efficient prompting, access to search, etc). (See our [paper](https://arxiv.org/abs/2311.12983) for more details.)
|
| 5 |
+
|
| 6 |
+
## Data
|
| 7 |
+
GAIA is made of more than 450 non-trivial question with an unambiguous answer, requiring different levels of tooling and autonomy to solve.
|
| 8 |
+
It is therefore divided in 3 levels, where level 1 should be breakable by very good LLMs, and level 3 indicate a strong jump in model capabilities. Each level is divided into a fully public dev set for validation, and a test set with private answers and metadata.
|
| 9 |
+
|
| 10 |
+
GAIA data can be found in [this dataset](https://huggingface.co/datasets/gaia-benchmark/GAIA). Questions are contained in `metadata.jsonl`. Some questions come with an additional file, that can be found in the same folder and whose id is given in the field `file_name`.
|
| 11 |
+
|
| 12 |
+
**Please do not repost the public dev set, nor use it in training data for your models.**
|
| 13 |
+
|
| 14 |
+
## Leaderboard
|
| 15 |
+
Submission made by our team are labelled "GAIA authors". While we report average scores over different runs when possible in our paper, we only report the best run in the leaderboard.
|
| 16 |
+
|
| 17 |
+
See below for submissions.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
SUBMISSION_TEXT = """
|
| 21 |
+
## Submissions
|
| 22 |
+
Results can be submitted for the test set (we closed the validation leaderboard, as it was no longer informative). Scores are expressed as the percentage of correct answers for a given split.
|
| 23 |
+
|
| 24 |
+
Each question calls for an answer that is either a string (one or a few words), a number, or a comma separated list of strings or floats, unless specified otherwise. There is only one correct answer.
|
| 25 |
+
Hence, evaluation is done via quasi exact match between a model’s answer and the ground truth (up to some normalization that is tied to the “type” of the ground truth).
|
| 26 |
+
|
| 27 |
+
In our evaluation, we use a system prompt to instruct the model about the required format:
|
| 28 |
+
```
|
| 29 |
+
You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
| 30 |
+
```
|
| 31 |
+
We advise you to use the system prompt provided in the paper to ensure your agents answer using the correct and expected format. In practice, GPT4 level models easily follow it.
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
We expect submissions to be json-line files with the following format. The first two fields are mandatory, `reasoning_trace` is optional:
|
| 35 |
+
```
|
| 36 |
+
{"task_id": "task_id_1", "model_answer": "Answer 1 from your model", "reasoning_trace": "The different steps by which your model reached answer 1"}
|
| 37 |
+
{"task_id": "task_id_2", "model_answer": "Answer 2 from your model", "reasoning_trace": "The different steps by which your model reached answer 2"}
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Our scoring function can be found [here](https://huggingface.co/spaces/gaia-benchmark/leaderboard/blob/main/scorer.py).
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
|
| 44 |
+
CITATION_BUTTON_TEXT = r"""@misc{mialon2023gaia,
|
| 45 |
+
title={GAIA: a benchmark for General AI Assistants},
|
| 46 |
+
author={Grégoire Mialon and Clémentine Fourrier and Craig Swift and Thomas Wolf and Yann LeCun and Thomas Scialom},
|
| 47 |
+
year={2023},
|
| 48 |
+
eprint={2311.12983},
|
| 49 |
+
archivePrefix={arXiv},
|
| 50 |
+
primaryClass={cs.CL}
|
| 51 |
+
}"""
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def format_error(msg):
|
| 55 |
+
return f"<p style='color: red; font-size: 20px; text-align: center;'>{msg}</p>"
|
| 56 |
+
|
| 57 |
+
def format_warning(msg):
|
| 58 |
+
return f"<p style='color: orange; font-size: 20px; text-align: center;'>{msg}</p>"
|
| 59 |
+
|
| 60 |
+
def format_log(msg):
|
| 61 |
+
return f"<p style='color: green; font-size: 20px; text-align: center;'>{msg}</p>"
|
| 62 |
+
|
| 63 |
+
def model_hyperlink(link, model_name):
|
| 64 |
+
return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
|
| 65 |
+
|
gitattributes
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.vscode
|
| 2 |
+
__pycache__/*
|
| 3 |
+
# Local results
|
| 4 |
+
scored/*
|
miniapp.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
from urllib.parse import urlparse
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
APP_NAME = "miniapp"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _is_valid_http_url(url: str) -> bool:
|
| 11 |
+
try:
|
| 12 |
+
parsed = urlparse(url)
|
| 13 |
+
return parsed.scheme in ("http", "https") and bool(parsed.netloc)
|
| 14 |
+
except Exception:
|
| 15 |
+
return False
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def submit(model_name: str, model_api: str, notes: str):
|
| 19 |
+
model_name = (model_name or "").strip()
|
| 20 |
+
model_api = (model_api or "").strip()
|
| 21 |
+
notes = (notes or "").strip()
|
| 22 |
+
|
| 23 |
+
if not model_name:
|
| 24 |
+
return "请填写 **模型名称**。", None
|
| 25 |
+
if not model_api:
|
| 26 |
+
return "请填写 **模型 API**。", None
|
| 27 |
+
if not _is_valid_http_url(model_api):
|
| 28 |
+
return "**模型 API** 需要是合法的 `http(s)://...` URL。", None
|
| 29 |
+
|
| 30 |
+
payload = {
|
| 31 |
+
"model_name": model_name,
|
| 32 |
+
"model_api": model_api,
|
| 33 |
+
"notes": notes,
|
| 34 |
+
"submitted_at": datetime.datetime.now().isoformat(timespec="seconds"),
|
| 35 |
+
}
|
| 36 |
+
return "已收到提交(仅前端回显;未做评测/未写入排行榜)。", payload
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
with gr.Blocks(title=APP_NAME) as demo:
|
| 40 |
+
gr.Markdown(
|
| 41 |
+
f"## {APP_NAME}\n\n"
|
| 42 |
+
"纯前端信息收集页:填写模型名称与 API 地址,点击提交后回显。\n\n"
|
| 43 |
+
"- 不需要 Hugging Face 登录\n"
|
| 44 |
+
"- 不依赖 scorer\n"
|
| 45 |
+
"- 不读写任何 leaderboard 数据\n"
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
with gr.Row():
|
| 49 |
+
with gr.Column(scale=2):
|
| 50 |
+
model_name = gr.Textbox(label="模型名称(必填)", placeholder="例如:my-agent-v1")
|
| 51 |
+
model_api = gr.Textbox(
|
| 52 |
+
label="模型 API(必填)",
|
| 53 |
+
placeholder="例如:https://api.example.com/v1/chat/completions",
|
| 54 |
+
)
|
| 55 |
+
notes = gr.Textbox(
|
| 56 |
+
label="备注(可选)",
|
| 57 |
+
lines=4,
|
| 58 |
+
placeholder="例如:鉴权方式、限流说明、模型简介等",
|
| 59 |
+
)
|
| 60 |
+
submit_btn = gr.Button("提交", variant="primary")
|
| 61 |
+
with gr.Column(scale=3):
|
| 62 |
+
status = gr.Markdown()
|
| 63 |
+
submission_json = gr.JSON(label="提交内容(回显)")
|
| 64 |
+
|
| 65 |
+
submit_btn.click(
|
| 66 |
+
submit,
|
| 67 |
+
inputs=[model_name, model_api, notes],
|
| 68 |
+
outputs=[status, submission_json],
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
demo.launch()
|
miniapp_leaderboard.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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import datetime
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
from urllib.parse import urlparse
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
APP_NAME = "miniapp"
|
| 14 |
+
|
| 15 |
+
# 在 Space 里通过 Secrets 配置:
|
| 16 |
+
# - HF_TOKEN: 具有写 dataset 权限的 token(Settings -> Variables and secrets -> Secrets)
|
| 17 |
+
# - LEADERBOARD_DATASET: 形如 "your-username/miniapp-leaderboard"(repo_type=dataset)
|
| 18 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
|
| 19 |
+
LEADERBOARD_DATASET = os.environ.get("LEADERBOARD_DATASET", "").strip()
|
| 20 |
+
|
| 21 |
+
# 判断是否运行在 Hugging Face Spaces
|
| 22 |
+
IN_SPACES = bool(
|
| 23 |
+
os.environ.get("SPACE_ID")
|
| 24 |
+
or os.environ.get("SPACE_REPO_NAME")
|
| 25 |
+
or os.environ.get("SPACE_AUTHOR_NAME")
|
| 26 |
+
or os.environ.get("system", "") == "spaces"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
MAX_ENTRIES = int(os.environ.get("MAX_ENTRIES", "200"))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _is_valid_http_url(url: str) -> bool:
|
| 33 |
+
try:
|
| 34 |
+
parsed = urlparse(url)
|
| 35 |
+
return parsed.scheme in ("http", "https") and bool(parsed.netloc)
|
| 36 |
+
except Exception:
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _slug(s: str, max_len: int = 60) -> str:
|
| 41 |
+
s = (s or "").strip().lower()
|
| 42 |
+
s = re.sub(r"[^a-z0-9]+", "-", s)
|
| 43 |
+
s = re.sub(r"-{2,}", "-", s).strip("-")
|
| 44 |
+
return (s[:max_len] or "model")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _api() -> HfApi:
|
| 48 |
+
return HfApi(token=HF_TOKEN)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _ensure_dataset_repo():
|
| 52 |
+
if not HF_TOKEN:
|
| 53 |
+
raise RuntimeError("未配置 HF_TOKEN(Space Secrets)。")
|
| 54 |
+
if not LEADERBOARD_DATASET:
|
| 55 |
+
raise RuntimeError("未配置 LEADERBOARD_DATASET(例如:your-username/miniapp-leaderboard)。")
|
| 56 |
+
api = _api()
|
| 57 |
+
try:
|
| 58 |
+
api.repo_info(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
|
| 59 |
+
except Exception:
|
| 60 |
+
# 不存在则创建(public dataset;你也可以手动创建并设为 private)
|
| 61 |
+
api.create_repo(repo_id=LEADERBOARD_DATASET, repo_type="dataset", private=False, exist_ok=True)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _empty_df() -> pd.DataFrame:
|
| 65 |
+
return pd.DataFrame(columns=["submitted_at", "username", "model_name", "model_api", "notes"])
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _load_submissions_df() -> pd.DataFrame:
|
| 69 |
+
if not HF_TOKEN or not LEADERBOARD_DATASET:
|
| 70 |
+
return _empty_df()
|
| 71 |
+
|
| 72 |
+
api = _api()
|
| 73 |
+
try:
|
| 74 |
+
files = api.list_repo_files(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
|
| 75 |
+
except Exception:
|
| 76 |
+
return _empty_df()
|
| 77 |
+
|
| 78 |
+
sub_files = sorted(
|
| 79 |
+
[f for f in files if f.startswith("submissions/") and f.endswith(".json")],
|
| 80 |
+
reverse=True,
|
| 81 |
+
)[:MAX_ENTRIES]
|
| 82 |
+
|
| 83 |
+
rows = []
|
| 84 |
+
for filename in sub_files:
|
| 85 |
+
try:
|
| 86 |
+
path = hf_hub_download(
|
| 87 |
+
repo_id=LEADERBOARD_DATASET,
|
| 88 |
+
repo_type="dataset",
|
| 89 |
+
filename=filename,
|
| 90 |
+
token=HF_TOKEN,
|
| 91 |
+
)
|
| 92 |
+
with open(path, "r", encoding="utf-8") as fp:
|
| 93 |
+
rows.append(json.load(fp))
|
| 94 |
+
except Exception:
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
if not rows:
|
| 98 |
+
return _empty_df()
|
| 99 |
+
|
| 100 |
+
df = pd.DataFrame(rows)
|
| 101 |
+
for col in ["submitted_at", "username", "model_name", "model_api", "notes"]:
|
| 102 |
+
if col not in df.columns:
|
| 103 |
+
df[col] = ""
|
| 104 |
+
df = df[["submitted_at", "username", "model_name", "model_api", "notes"]]
|
| 105 |
+
df = df.sort_values(by=["submitted_at"], ascending=False, kind="stable")
|
| 106 |
+
return df
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def refresh():
|
| 110 |
+
return _load_submissions_df()
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def submit(model_name: str, model_api: str, notes: str, username: str | None):
|
| 114 |
+
model_name = (model_name or "").strip()
|
| 115 |
+
model_api = (model_api or "").strip()
|
| 116 |
+
notes = (notes or "").strip()
|
| 117 |
+
username = (username or "").strip() or ("local" if not IN_SPACES else "anonymous")
|
| 118 |
+
|
| 119 |
+
if not model_name:
|
| 120 |
+
return "请填写 **模型名称**。", _load_submissions_df()
|
| 121 |
+
if not model_api:
|
| 122 |
+
return "请填写 **模型 API**。", _load_submissions_df()
|
| 123 |
+
if not _is_valid_http_url(model_api):
|
| 124 |
+
return "**模型 API** 需要是合法的 `http(s)://...` URL。", _load_submissions_df()
|
| 125 |
+
|
| 126 |
+
if not HF_TOKEN:
|
| 127 |
+
return "Space 未配置 **HF_TOKEN**(Secrets),无法写入排行榜。", _load_submissions_df()
|
| 128 |
+
if not LEADERBOARD_DATASET:
|
| 129 |
+
return "Space 未配置 **LEADERBOARD_DATASET**(例如:`your-username/miniapp-leaderboard`)。", _load_submissions_df()
|
| 130 |
+
|
| 131 |
+
_ensure_dataset_repo()
|
| 132 |
+
api = _api()
|
| 133 |
+
|
| 134 |
+
now = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
|
| 135 |
+
safe_model = _slug(model_name)
|
| 136 |
+
safe_user = _slug(username)
|
| 137 |
+
path_in_repo = f"submissions/{now[:10]}/{now}-{safe_user}-{safe_model}.json"
|
| 138 |
+
|
| 139 |
+
payload = {
|
| 140 |
+
"submitted_at": now,
|
| 141 |
+
"username": username,
|
| 142 |
+
"model_name": model_name,
|
| 143 |
+
"model_api": model_api,
|
| 144 |
+
"notes": notes,
|
| 145 |
+
}
|
| 146 |
+
data = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
| 147 |
+
bio = io.BytesIO(data)
|
| 148 |
+
|
| 149 |
+
api.upload_file(
|
| 150 |
+
repo_id=LEADERBOARD_DATASET,
|
| 151 |
+
repo_type="dataset",
|
| 152 |
+
path_or_fileobj=bio,
|
| 153 |
+
path_in_repo=path_in_repo,
|
| 154 |
+
commit_message=f"miniapp: submit {username}/{model_name}",
|
| 155 |
+
token=HF_TOKEN,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
return "已提交并写入 leaderboard。", _load_submissions_df()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
with gr.Blocks(title=f"{APP_NAME} leaderboard") as demo:
|
| 162 |
+
gr.Markdown(
|
| 163 |
+
f"## {APP_NAME} leaderboard\n\n"
|
| 164 |
+
"提交你的模型信息后,会写入一个 Hugging Face **Dataset**,并在下方表格展示。\n\n"
|
| 165 |
+
f"- 当前 `LEADERBOARD_DATASET`: `{LEADERBOARD_DATASET or '(未配置)'}`\n"
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
with gr.Row():
|
| 169 |
+
with gr.Column(scale=2):
|
| 170 |
+
model_name = gr.Textbox(label="模型名称(必填)", placeholder="例如:my-agent-v1")
|
| 171 |
+
model_api = gr.Textbox(
|
| 172 |
+
label="模型 API(必填)",
|
| 173 |
+
placeholder="例如:https://api.example.com/v1/chat/completions",
|
| 174 |
+
)
|
| 175 |
+
notes = gr.Textbox(label="备注(可选)", lines=4)
|
| 176 |
+
username = gr.Textbox(
|
| 177 |
+
label="用户名(可选)",
|
| 178 |
+
placeholder="建议填你的 HF 用户名(也可留空)",
|
| 179 |
+
value="" if IN_SPACES else "local",
|
| 180 |
+
)
|
| 181 |
+
submit_btn = gr.Button("提交", variant="primary")
|
| 182 |
+
status = gr.Markdown()
|
| 183 |
+
with gr.Column(scale=3):
|
| 184 |
+
leaderboard = gr.Dataframe(
|
| 185 |
+
label="Leaderboard(按提交时间倒序)",
|
| 186 |
+
value=_load_submissions_df(),
|
| 187 |
+
interactive=False,
|
| 188 |
+
wrap=True,
|
| 189 |
+
)
|
| 190 |
+
refresh_btn = gr.Button("刷新")
|
| 191 |
+
|
| 192 |
+
submit_btn.click(
|
| 193 |
+
submit,
|
| 194 |
+
inputs=[model_name, model_api, notes, username],
|
| 195 |
+
outputs=[status, leaderboard],
|
| 196 |
+
)
|
| 197 |
+
refresh_btn.click(refresh, inputs=[], outputs=[leaderboard])
|
| 198 |
+
|
| 199 |
+
demo.launch()
|
| 200 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
huggingface-hub
|
| 3 |
+
pandas
|