ha251 commited on
Commit
c5c3ca2
·
verified ·
1 Parent(s): 15a05ff

Upload 7 files

Browse files
Files changed (7) hide show
  1. app.py +774 -0
  2. content.py +65 -0
  3. gitattributes +34 -0
  4. gitignore +4 -0
  5. miniapp.py +71 -0
  6. miniapp_leaderboard.py +728 -0
  7. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import io
3
+ import json
4
+ import os
5
+ import re
6
+ import uuid
7
+ from urllib.parse import urlparse
8
+
9
+ import gradio as gr
10
+ import pandas as pd
11
+ import requests
12
+ from huggingface_hub import HfApi, hf_hub_download
13
+ from huggingface_hub.errors import RepositoryNotFoundError
14
+
15
+
16
+ APP_NAME = "miniapp"
17
+
18
+ # Space Secrets:
19
+ # - HF_TOKEN: Hugging Face access token with WRITE access to the dataset repo
20
+ # - LEADERBOARD_DATASET: dataset repo id like "ha251/miniapp-leaderboard"
21
+ HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
22
+ LEADERBOARD_DATASET = (os.environ.get("LEADERBOARD_DATASET") or "").strip()
23
+ MAX_ENTRIES = int(os.environ.get("MAX_ENTRIES", "500"))
24
+
25
+ ENTRIES_PREFIX = "entries/"
26
+
27
+ LEADERBOARD_COLUMNS = [
28
+ "Model name",
29
+ "Avg",
30
+ "Easy",
31
+ "Mid",
32
+ "Hard",
33
+ "Games",
34
+ "Science",
35
+ "Tools",
36
+ "Humanities",
37
+ "Viz",
38
+ "Lifestyle",
39
+ "Submitted at",
40
+ "Submitter",
41
+ ]
42
+
43
+ NUMERIC_COLS = [
44
+ "Avg",
45
+ "Easy",
46
+ "Mid",
47
+ "Hard",
48
+ "Games",
49
+ "Science",
50
+ "Tools",
51
+ "Humanities",
52
+ "Viz",
53
+ "Lifestyle",
54
+ ]
55
+
56
+ IN_SPACES = bool(
57
+ os.environ.get("SPACE_ID")
58
+ or os.environ.get("SPACE_REPO_NAME")
59
+ or os.environ.get("SPACE_AUTHOR_NAME")
60
+ or os.environ.get("system", "") == "spaces"
61
+ )
62
+
63
+
64
+ def _api() -> HfApi:
65
+ return HfApi(token=HF_TOKEN)
66
+
67
+
68
+ def _is_valid_http_url(url: str) -> bool:
69
+ try:
70
+ parsed = urlparse(url)
71
+ return parsed.scheme in ("http", "https") and bool(parsed.netloc)
72
+ except Exception:
73
+ return False
74
+
75
+
76
+ def _slug(s: str, max_len: int = 60) -> str:
77
+ s = (s or "").strip().lower()
78
+ s = re.sub(r"[^a-z0-9]+", "-", s)
79
+ s = re.sub(r"-{2,}", "-", s).strip("-")
80
+ return (s[:max_len] or "x")
81
+
82
+
83
+ def _empty_df() -> pd.DataFrame:
84
+ return pd.DataFrame(columns=LEADERBOARD_COLUMNS)
85
+
86
+
87
+ def _ensure_dataset_readable() -> tuple[bool, str]:
88
+ if not HF_TOKEN:
89
+ return False, "Space is missing HF_TOKEN (Secrets)."
90
+ if not LEADERBOARD_DATASET:
91
+ return False, "Space is missing LEADERBOARD_DATASET (Secrets)."
92
+ api = _api()
93
+ try:
94
+ api.repo_info(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
95
+ return True, ""
96
+ except RepositoryNotFoundError:
97
+ return False, (
98
+ f"Dataset repo not found: {LEADERBOARD_DATASET}. "
99
+ "Create it first (as a dataset) or fix LEADERBOARD_DATASET."
100
+ )
101
+ except Exception:
102
+ return False, "Cannot access the dataset repo. Check token permissions."
103
+
104
+
105
+ def _list_entry_files() -> list[str]:
106
+ ok, _ = _ensure_dataset_readable()
107
+ if not ok:
108
+ return []
109
+ api = _api()
110
+ try:
111
+ files = api.list_repo_files(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
112
+ except Exception:
113
+ return []
114
+
115
+ entry_files = [f for f in files if f.startswith(ENTRIES_PREFIX) and f.endswith(".json")]
116
+ entry_files.sort(reverse=True)
117
+ return entry_files[:MAX_ENTRIES]
118
+
119
+
120
+ def _load_entries_df() -> pd.DataFrame:
121
+ ok, _ = _ensure_dataset_readable()
122
+ if not ok:
123
+ return _empty_df()
124
+
125
+ rows: list[dict] = []
126
+ for filename in _list_entry_files():
127
+ try:
128
+ path = hf_hub_download(
129
+ repo_id=LEADERBOARD_DATASET,
130
+ repo_type="dataset",
131
+ filename=filename,
132
+ token=HF_TOKEN,
133
+ )
134
+ with open(path, "r", encoding="utf-8") as fp:
135
+ row = json.load(fp)
136
+ rows.append(row)
137
+ except Exception:
138
+ continue
139
+
140
+ if not rows:
141
+ return _empty_df()
142
+
143
+ df = pd.DataFrame(rows)
144
+ for c in LEADERBOARD_COLUMNS:
145
+ if c not in df.columns:
146
+ df[c] = ""
147
+ df = df[LEADERBOARD_COLUMNS]
148
+ for c in NUMERIC_COLS:
149
+ df[c] = pd.to_numeric(df[c], errors="coerce")
150
+ df = df.sort_values(by=["Submitted at"], ascending=False, kind="stable")
151
+ return df
152
+
153
+
154
+ def _apply_search_and_sort(
155
+ df: pd.DataFrame,
156
+ search_text: str,
157
+ search_in: str,
158
+ sort_by: str,
159
+ sort_order: str,
160
+ ) -> pd.DataFrame:
161
+ search_text = (search_text or "").strip().lower()
162
+ if search_text:
163
+ if search_in == "Model name":
164
+ df = df[df["Model name"].astype(str).str.lower().str.contains(search_text, na=False)]
165
+ elif search_in == "Submitter":
166
+ df = df[df["Submitter"].astype(str).str.lower().str.contains(search_text, na=False)]
167
+ else:
168
+ mask = (
169
+ df["Model name"].astype(str).str.lower().str.contains(search_text, na=False)
170
+ | df["Submitter"].astype(str).str.lower().str.contains(search_text, na=False)
171
+ )
172
+ df = df[mask]
173
+
174
+ ascending = sort_order == "Ascending"
175
+ if sort_by in df.columns:
176
+ df = df.sort_values(by=[sort_by], ascending=ascending, kind="stable", na_position="last")
177
+ return df
178
+
179
+
180
+ def refresh(search_text: str, search_in: str, sort_by: str, sort_order: str):
181
+ df = _load_entries_df()
182
+ return _apply_search_and_sort(df, search_text, search_in, sort_by, sort_order)
183
+
184
+
185
+ def _parse_hf_created_at(created_at: str) -> datetime.datetime | None:
186
+ try:
187
+ if created_at.endswith("Z"):
188
+ created_at = created_at[:-1] + "+00:00"
189
+ return datetime.datetime.fromisoformat(created_at)
190
+ except Exception:
191
+ return None
192
+
193
+
194
+ def _check_user_eligibility(username: str) -> tuple[bool, str]:
195
+ """
196
+ - Must be older than ~4 months (>= 120 days)
197
+ """
198
+ try:
199
+ r = requests.get(f"https://huggingface.co/api/users/{username}/overview", timeout=10)
200
+ r.raise_for_status()
201
+ created_at = r.json().get("createdAt")
202
+ if not created_at:
203
+ return False, "Cannot verify account creation date."
204
+ dt = _parse_hf_created_at(created_at)
205
+ if not dt:
206
+ return False, "Cannot parse account creation date."
207
+ now = datetime.datetime.now(datetime.timezone.utc)
208
+ if dt.tzinfo is None:
209
+ dt = dt.replace(tzinfo=datetime.timezone.utc)
210
+ age_days = (now - dt).days
211
+ if age_days < 120:
212
+ return False, "Account must be older than 4 months to submit."
213
+ return True, ""
214
+ except Exception:
215
+ return False, "Cannot verify Hugging Face account. Please try again later."
216
+
217
+
218
+ def _submitted_today(username: str) -> bool:
219
+ df = _load_entries_df()
220
+ if df.empty:
221
+ return False
222
+ today = datetime.datetime.utcnow().date().isoformat()
223
+ user_rows = df[df["Submitter"].astype(str) == username]
224
+ if user_rows.empty:
225
+ return False
226
+ return any(str(v).startswith(today) for v in user_rows["Submitted at"].tolist())
227
+
228
+
229
+ def submit(
230
+ model_name: str,
231
+ model_api: str,
232
+ api_key: str,
233
+ avg: float,
234
+ easy: float,
235
+ mid: float,
236
+ hard: float,
237
+ games: float,
238
+ science: float,
239
+ tools: float,
240
+ humanities: float,
241
+ viz: float,
242
+ lifestyle: float,
243
+ search_text: str,
244
+ search_in: str,
245
+ sort_by: str,
246
+ sort_order: str,
247
+ profile: gr.OAuthProfile | None,
248
+ ):
249
+ # Login required to submit (in Spaces)
250
+ if IN_SPACES and (profile is None or not getattr(profile, "username", None)):
251
+ return "You must log in to submit.", refresh(search_text, search_in, sort_by, sort_order)
252
+
253
+ submitter = (getattr(profile, "username", None) if profile is not None else "local") or "anonymous"
254
+
255
+ model_name = (model_name or "").strip()
256
+ model_api = (model_api or "").strip()
257
+ api_key = (api_key or "").strip()
258
+
259
+ if not model_name:
260
+ return "Model name is required.", refresh(search_text, search_in, sort_by, sort_order)
261
+ if not model_api:
262
+ return "Model API URL is required.", refresh(search_text, search_in, sort_by, sort_order)
263
+ if not _is_valid_http_url(model_api):
264
+ return "Model API must be a valid http(s) URL.", refresh(search_text, search_in, sort_by, sort_order)
265
+ if not api_key:
266
+ return "API key is required.", refresh(search_text, search_in, sort_by, sort_order)
267
+
268
+ ok, msg = _ensure_dataset_readable()
269
+ if not ok:
270
+ return msg, refresh(search_text, search_in, sort_by, sort_order)
271
+
272
+ if IN_SPACES:
273
+ ok, msg = _check_user_eligibility(submitter)
274
+ if not ok:
275
+ return msg, refresh(search_text, search_in, sort_by, sort_order)
276
+
277
+ if _submitted_today(submitter):
278
+ return "You have already submitted today. Please try again tomorrow.", refresh(search_text, search_in, sort_by, sort_order)
279
+
280
+ now = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
281
+ nonce = uuid.uuid4().hex[:8]
282
+ safe_model = _slug(model_name)
283
+ safe_user = _slug(submitter)
284
+ path_in_repo = f"{ENTRIES_PREFIX}{now[:10]}/{now}-{safe_user}-{safe_model}-{nonce}.json"
285
+
286
+ # NOTE: api_key is collected but NOT stored.
287
+ payload = {
288
+ "Model name": model_name,
289
+ "Avg": avg,
290
+ "Easy": easy,
291
+ "Mid": mid,
292
+ "Hard": hard,
293
+ "Games": games,
294
+ "Science": science,
295
+ "Tools": tools,
296
+ "Humanities": humanities,
297
+ "Viz": viz,
298
+ "Lifestyle": lifestyle,
299
+ "Submitted at": now,
300
+ "Submitter": submitter,
301
+ "Model API": model_api,
302
+ }
303
+
304
+ api = _api()
305
+ data = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
306
+ api.upload_file(
307
+ repo_id=LEADERBOARD_DATASET,
308
+ repo_type="dataset",
309
+ path_or_fileobj=io.BytesIO(data),
310
+ path_in_repo=path_in_repo,
311
+ commit_message=f"miniapp: submit {submitter}/{model_name}",
312
+ token=HF_TOKEN,
313
+ )
314
+
315
+ return "Submitted successfully.", refresh(search_text, search_in, sort_by, sort_order)
316
+
317
+
318
+ with gr.Blocks(title=f"{APP_NAME} leaderboard") as demo:
319
+ # Layout: Overview -> Leaderboard -> Submission instructions
320
+ gr.Markdown(
321
+ f"## {APP_NAME} leaderboard\n\n"
322
+ "### Overview\n"
323
+ "_Placeholder overview text. Replace this with your benchmark description, rules, and links._\n\n"
324
+ "### Leaderboard\n"
325
+ "_The leaderboard below supports sorting and searching._\n\n"
326
+ "### Submission\n"
327
+ "_Placeholder submission instructions. Requires login. One submission per user per day. "
328
+ "Account must be older than 4 months._\n"
329
+ )
330
+
331
+ with gr.Row():
332
+ with gr.Column(scale=3):
333
+ with gr.Row():
334
+ search_text = gr.Textbox(label="Search", placeholder="Model name or submitter")
335
+ search_in = gr.Dropdown(
336
+ label="Search in",
337
+ choices=["Both", "Model name", "Submitter"],
338
+ value="Both",
339
+ )
340
+ with gr.Row():
341
+ sort_by = gr.Dropdown(label="Sort by", choices=LEADERBOARD_COLUMNS, value="Avg")
342
+ sort_order = gr.Radio(label="Order", choices=["Descending", "Ascending"], value="Descending")
343
+ refresh_btn = gr.Button("Refresh")
344
+
345
+ leaderboard = gr.Dataframe(
346
+ label="Leaderboard",
347
+ value=_load_entries_df(),
348
+ interactive=False,
349
+ wrap=True,
350
+ )
351
+
352
+ with gr.Column(scale=2):
353
+ with gr.Accordion("Submit (login required)", open=True):
354
+ model_name = gr.Textbox(label="Model name (required)")
355
+ model_api = gr.Textbox(label="Model API (required)", placeholder="https://...")
356
+ api_key = gr.Textbox(label="API key (required)", type="password", placeholder="Will not be stored")
357
+
358
+ with gr.Row():
359
+ avg = gr.Number(label="Avg", value=0)
360
+ easy = gr.Number(label="Easy", value=0)
361
+ mid = gr.Number(label="Mid", value=0)
362
+ hard = gr.Number(label="Hard", value=0)
363
+
364
+ with gr.Row():
365
+ games = gr.Number(label="Games", value=0)
366
+ science = gr.Number(label="Science", value=0)
367
+ tools = gr.Number(label="Tools", value=0)
368
+
369
+ with gr.Row():
370
+ humanities = gr.Number(label="Humanities", value=0)
371
+ viz = gr.Number(label="Viz", value=0)
372
+ lifestyle = gr.Number(label="Lifestyle", value=0)
373
+
374
+ with gr.Row():
375
+ gr.LoginButton()
376
+ submit_btn = gr.Button("Submit", variant="primary")
377
+ status = gr.Markdown()
378
+
379
+ refresh_btn.click(refresh, inputs=[search_text, search_in, sort_by, sort_order], outputs=[leaderboard])
380
+ submit_btn.click(
381
+ submit,
382
+ inputs=[
383
+ model_name,
384
+ model_api,
385
+ api_key,
386
+ avg,
387
+ easy,
388
+ mid,
389
+ hard,
390
+ games,
391
+ science,
392
+ tools,
393
+ humanities,
394
+ viz,
395
+ lifestyle,
396
+ search_text,
397
+ search_in,
398
+ sort_by,
399
+ sort_order,
400
+ ],
401
+ outputs=[status, leaderboard],
402
+ )
403
+
404
+ demo.launch()
405
+
406
+ import datetime
407
+ import io
408
+ import json
409
+ import os
410
+ import re
411
+ import uuid
412
+ from urllib.parse import urlparse
413
+
414
+ import gradio as gr
415
+ import pandas as pd
416
+ from huggingface_hub import HfApi, hf_hub_download
417
+
418
+
419
+ APP_NAME = "miniapp"
420
+
421
+ # 在 Space 里通过 Secrets 配置:
422
+ # - HF_TOKEN: 具有写 dataset 权限的 token(Settings -> Variables and secrets -> Secrets)
423
+ # - LEADERBOARD_DATASET: 形如 "your-username/miniapp-leaderboard"(repo_type=dataset)
424
+ HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
425
+ LEADERBOARD_DATASET = os.environ.get("LEADERBOARD_DATASET", "").strip()
426
+ # Owner 审核口令(放到 Space Secrets;不要放到公开 Variables)
427
+ OWNER_REVIEW_TOKEN = os.environ.get("OWNER_REVIEW_TOKEN", "").strip()
428
+
429
+ # 判断是否运行在 Hugging Face Spaces
430
+ IN_SPACES = bool(
431
+ os.environ.get("SPACE_ID")
432
+ or os.environ.get("SPACE_REPO_NAME")
433
+ or os.environ.get("SPACE_AUTHOR_NAME")
434
+ or os.environ.get("system", "") == "spaces"
435
+ )
436
+
437
+ MAX_ENTRIES = int(os.environ.get("MAX_ENTRIES", "200"))
438
+
439
+ PENDING_PREFIX = "pending/"
440
+ APPROVED_PREFIX = "approved/"
441
+
442
+
443
+ def _is_valid_http_url(url: str) -> bool:
444
+ try:
445
+ parsed = urlparse(url)
446
+ return parsed.scheme in ("http", "https") and bool(parsed.netloc)
447
+ except Exception:
448
+ return False
449
+
450
+
451
+ def _slug(s: str, max_len: int = 60) -> str:
452
+ s = (s or "").strip().lower()
453
+ s = re.sub(r"[^a-z0-9]+", "-", s)
454
+ s = re.sub(r"-{2,}", "-", s).strip("-")
455
+ return (s[:max_len] or "model")
456
+
457
+
458
+ def _api() -> HfApi:
459
+ return HfApi(token=HF_TOKEN)
460
+
461
+
462
+ def _ensure_dataset_repo():
463
+ if not HF_TOKEN:
464
+ raise RuntimeError("未配置 HF_TOKEN(Space Secrets)。")
465
+ if not LEADERBOARD_DATASET:
466
+ raise RuntimeError("未配置 LEADERBOARD_DATASET(例如:your-username/miniapp-leaderboard)。")
467
+ api = _api()
468
+ try:
469
+ api.repo_info(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
470
+ except Exception:
471
+ # 不存在则创建(public dataset;你也可以手动创建并设为 private)
472
+ api.create_repo(repo_id=LEADERBOARD_DATASET, repo_type="dataset", private=False, exist_ok=True)
473
+
474
+
475
+ def _empty_df() -> pd.DataFrame:
476
+ return pd.DataFrame(columns=["submitted_at", "username", "model_name", "model_api", "notes"])
477
+
478
+
479
+ def _list_json_files(prefix: str) -> list[str]:
480
+ if not HF_TOKEN or not LEADERBOARD_DATASET:
481
+ return []
482
+
483
+ api = _api()
484
+ try:
485
+ files = api.list_repo_files(repo_id=LEADERBOARD_DATASET, repo_type="dataset")
486
+ except Exception:
487
+ return []
488
+
489
+ return sorted(
490
+ [f for f in files if f.startswith(prefix) and f.endswith(".json")],
491
+ reverse=True,
492
+ )[:MAX_ENTRIES]
493
+
494
+
495
+ def _load_entries_df(prefix: str, include_filename: bool) -> pd.DataFrame:
496
+ files = _list_json_files(prefix)
497
+ rows = []
498
+ for filename in files:
499
+ try:
500
+ path = hf_hub_download(
501
+ repo_id=LEADERBOARD_DATASET,
502
+ repo_type="dataset",
503
+ filename=filename,
504
+ token=HF_TOKEN,
505
+ )
506
+ with open(path, "r", encoding="utf-8") as fp:
507
+ row = json.load(fp)
508
+ if include_filename:
509
+ row["_filename"] = filename
510
+ rows.append(row)
511
+ except Exception:
512
+ continue
513
+
514
+ if not rows:
515
+ df = _empty_df()
516
+ if include_filename:
517
+ df["_filename"] = []
518
+ return df
519
+
520
+ df = pd.DataFrame(rows)
521
+ for col in ["submitted_at", "username", "model_name", "model_api", "notes"]:
522
+ if col not in df.columns:
523
+ df[col] = ""
524
+ cols = ["submitted_at", "username", "model_name", "model_api", "notes"]
525
+ if include_filename:
526
+ if "_filename" not in df.columns:
527
+ df["_filename"] = ""
528
+ cols = cols + ["_filename"]
529
+ df = df[cols]
530
+ df = df.sort_values(by=["submitted_at"], ascending=False, kind="stable")
531
+ return df
532
+
533
+
534
+ def refresh():
535
+ return _load_entries_df(APPROVED_PREFIX, include_filename=False)
536
+
537
+
538
+ def refresh_pending():
539
+ df = _load_entries_df(PENDING_PREFIX, include_filename=True)
540
+ choices = list(df["_filename"]) if "_filename" in df.columns else []
541
+ return df, gr.update(choices=choices, value=choices[0] if choices else None)
542
+
543
+
544
+ def submit(model_name: str, model_api: str, notes: str, username: str | None):
545
+ model_name = (model_name or "").strip()
546
+ model_api = (model_api or "").strip()
547
+ notes = (notes or "").strip()
548
+ username = (username or "").strip() or ("local" if not IN_SPACES else "anonymous")
549
+
550
+ if not model_name:
551
+ return "请填写 **模型名称**。", refresh()
552
+ if not model_api:
553
+ return "请填写 **模型 API**。", refresh()
554
+ if not _is_valid_http_url(model_api):
555
+ return "**模型 API** 需要是合法的 `http(s)://...` URL。", refresh()
556
+
557
+ if not HF_TOKEN:
558
+ return "Space 未配置 **HF_TOKEN**(Secrets),无法写入排行榜。", refresh()
559
+ if not LEADERBOARD_DATASET:
560
+ return "Space 未配置 **LEADERBOARD_DATASET**(例如:`your-username/miniapp-leaderboard`)。", refresh()
561
+
562
+ _ensure_dataset_repo()
563
+ api = _api()
564
+
565
+ now = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
566
+ safe_model = _slug(model_name)
567
+ safe_user = _slug(username)
568
+ nonce = uuid.uuid4().hex[:8]
569
+ path_in_repo = f"{PENDING_PREFIX}{now[:10]}/{now}-{safe_user}-{safe_model}-{nonce}.json"
570
+
571
+ payload = {
572
+ "submitted_at": now,
573
+ "username": username,
574
+ "model_name": model_name,
575
+ "model_api": model_api,
576
+ "notes": notes,
577
+ }
578
+ data = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
579
+ bio = io.BytesIO(data)
580
+
581
+ api.upload_file(
582
+ repo_id=LEADERBOARD_DATASET,
583
+ repo_type="dataset",
584
+ path_or_fileobj=bio,
585
+ path_in_repo=path_in_repo,
586
+ commit_message=f"miniapp: submit(pending) {username}/{model_name}",
587
+ token=HF_TOKEN,
588
+ )
589
+
590
+ return "已提交,等待 owner 审核后才会上榜。", refresh()
591
+
592
+
593
+ def approve(pending_filename: str | None, review_token: str | None):
594
+ pending_filename = (pending_filename or "").strip()
595
+ review_token = (review_token or "").strip()
596
+
597
+ if not pending_filename:
598
+ df, dd = refresh_pending()
599
+ return "请选择一条待审核提交。", df, dd, refresh()
600
+
601
+ if not OWNER_REVIEW_TOKEN:
602
+ df, dd = refresh_pending()
603
+ return "Space 未配置 **OWNER_REVIEW_TOKEN**(Secrets),无法启用审核。", df, dd, refresh()
604
+
605
+ if review_token != OWNER_REVIEW_TOKEN:
606
+ df, dd = refresh_pending()
607
+ return "审核口令不正确。", df, dd, refresh()
608
+
609
+ if not HF_TOKEN or not LEADERBOARD_DATASET:
610
+ df, dd = refresh_pending()
611
+ return "Space 未配置 HF 写入权限,无法审核。", df, dd, refresh()
612
+
613
+ api = _api()
614
+ try:
615
+ local_path = hf_hub_download(
616
+ repo_id=LEADERBOARD_DATASET,
617
+ repo_type="dataset",
618
+ filename=pending_filename,
619
+ token=HF_TOKEN,
620
+ )
621
+ with open(local_path, "r", encoding="utf-8") as fp:
622
+ payload = json.load(fp)
623
+ except Exception as e:
624
+ df, dd = refresh_pending()
625
+ return f"读取待审核文件失败:{e}", df, dd, refresh()
626
+
627
+ # 将文件复制到 approved 目录(保留原提交时间等字段)
628
+ base = pending_filename[len(PENDING_PREFIX) :] if pending_filename.startswith(PENDING_PREFIX) else pending_filename
629
+ approved_filename = f"{APPROVED_PREFIX}{base}"
630
+ data = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
631
+ bio = io.BytesIO(data)
632
+
633
+ try:
634
+ api.upload_file(
635
+ repo_id=LEADERBOARD_DATASET,
636
+ repo_type="dataset",
637
+ path_or_fileobj=bio,
638
+ path_in_repo=approved_filename,
639
+ commit_message=f"miniapp: approve {payload.get('username','')}/{payload.get('model_name','')}",
640
+ token=HF_TOKEN,
641
+ )
642
+ # 删除 pending 原文件(真正“上榜前审核”)
643
+ api.delete_file(
644
+ repo_id=LEADERBOARD_DATASET,
645
+ repo_type="dataset",
646
+ path_in_repo=pending_filename,
647
+ commit_message=f"miniapp: remove pending {pending_filename}",
648
+ token=HF_TOKEN,
649
+ )
650
+ except Exception as e:
651
+ df, dd = refresh_pending()
652
+ return f"审核写入失败:{e}", df, dd, refresh()
653
+
654
+ pending_df, pending_dd = refresh_pending()
655
+ approved_df = refresh()
656
+ return "已通过审核并更新榜单。", pending_df, pending_dd, approved_df
657
+
658
+
659
+ with gr.Blocks(title=f"{APP_NAME} leaderboard") as demo:
660
+ gr.Markdown(
661
+ f"## {APP_NAME} leaderboard\n\n"
662
+ "用户提交信息后会进入 **pending(待审核)**;owner 审核通过后才会进入 **approved(上榜)**。\n\n"
663
+ f"- 当前 `LEADERBOARD_DATASET`: `{LEADERBOARD_DATASET or '(未配置)'}`\n"
664
+ )
665
+
666
+ with gr.Row():
667
+ with gr.Column(scale=2):
668
+ model_name = gr.Textbox(label="模型名称(必填)", placeholder="例如:my-agent-v1")
669
+ model_api = gr.Textbox(
670
+ label="模型 API(必填)",
671
+ placeholder="例如:https://api.example.com/v1/chat/completions",
672
+ )
673
+ notes = gr.Textbox(label="备注(可选)", lines=4)
674
+ username = gr.Textbox(
675
+ label="用户名(可选)",
676
+ placeholder="建议填你的 HF 用户名(也可留空)",
677
+ value="" if IN_SPACES else "local",
678
+ )
679
+ submit_btn = gr.Button("提交", variant="primary")
680
+ status = gr.Markdown()
681
+ with gr.Column(scale=3):
682
+ leaderboard = gr.Dataframe(
683
+ label="Leaderboard(按提交时间倒序)",
684
+ value=_load_entries_df(APPROVED_PREFIX, include_filename=False),
685
+ interactive=False,
686
+ wrap=True,
687
+ )
688
+ refresh_btn = gr.Button("刷新")
689
+
690
+ submit_btn.click(
691
+ submit,
692
+ inputs=[model_name, model_api, notes, username],
693
+ outputs=[status, leaderboard],
694
+ )
695
+ refresh_btn.click(refresh, inputs=[], outputs=[leaderboard])
696
+
697
+ with gr.Accordion("Owner 审核(测试 demo)", open=False):
698
+ gr.Markdown(
699
+ "需要在 Space Secrets 中配置 `OWNER_REVIEW_TOKEN`。只有输入正确口令,才允许把 pending 放入榜单。"
700
+ )
701
+ review_token = gr.Textbox(label="审核口令", type="password", placeholder="OWNER_REVIEW_TOKEN")
702
+ pending_refresh_btn = gr.Button("刷新待审核列表")
703
+ pending_df = gr.Dataframe(
704
+ label="待审核(pending)",
705
+ value=_load_entries_df(PENDING_PREFIX, include_filename=True),
706
+ interactive=False,
707
+ wrap=True,
708
+ )
709
+ pending_pick = gr.Dropdown(
710
+ label="选择要通过的提交(文件)",
711
+ choices=_list_json_files(PENDING_PREFIX),
712
+ )
713
+ approve_btn = gr.Button("通过审核并上榜", variant="primary")
714
+ approve_status = gr.Markdown()
715
+
716
+ pending_refresh_btn.click(
717
+ refresh_pending,
718
+ inputs=[],
719
+ outputs=[pending_df, pending_pick],
720
+ )
721
+ approve_btn.click(
722
+ approve,
723
+ inputs=[pending_pick, review_token],
724
+ outputs=[approve_status, pending_df, pending_pick, leaderboard],
725
+ )
726
+
727
+ demo.launch()
728
+
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ huggingface-hub
3
+ pandas
4
+ requests