SorrowTea commited on
Commit
224a69a
·
1 Parent(s): adb9650

Fix blank leaderboard, unify metric scale to percent, document eligibility rules

Browse files
Files changed (6) hide show
  1. README.md +2 -0
  2. app.py +13 -5
  3. src/about.py +20 -0
  4. src/evaluator.py +10 -1
  5. src/leaderboard_manager.py +40 -4
  6. src/storage.py +9 -4
README.md CHANGED
@@ -19,6 +19,8 @@ tags:
19
 
20
  Agent-only leaderboard for PhotoBench-Protected, where only partial captions, embeddings, and metadata are provided.
21
 
 
 
22
  ## Quick Start
23
 
24
  1. Download the protected dataset from [PhotoBench-Protected Dataset](https://huggingface.co/datasets/SorrowTea/PhotoBench-Protected)
 
19
 
20
  Agent-only leaderboard for PhotoBench-Protected, where only partial captions, embeddings, and metadata are provided.
21
 
22
+ > **🎓 The PhotoBench paper has been accepted to KDD 2026 Datasets and Benchmarks Track!**
23
+
24
  ## Quick Start
25
 
26
  1. Download the protected dataset from [PhotoBench-Protected Dataset](https://huggingface.co/datasets/SorrowTea/PhotoBench-Protected)
app.py CHANGED
@@ -7,6 +7,7 @@ import gradio as gr
7
  import pandas as pd
8
 
9
  from src.about import (
 
10
  EVALUATION_INFO,
11
  INTRODUCTION,
12
  NAVIGATION,
@@ -176,17 +177,23 @@ with gr.Blocks(css=custom_css, title="PhotoBench-Protected Leaderboard") as demo
176
  gr.Markdown(INTRODUCTION, elem_classes="markdown-text")
177
 
178
  with gr.Tabs(elem_classes="tab-buttons"):
179
- # === Tab 1: Leaderboard ===
180
  with gr.TabItem("🏅 Leaderboard"):
181
- with gr.Row():
182
- with gr.Column(scale=3):
 
 
 
 
 
 
183
  sort_by = gr.Dropdown(
184
  choices=ALL_METRIC_COLS,
185
  value="Recall@10",
186
  label="Sort by",
187
  )
188
- with gr.Column(scale=1):
189
- refresh_btn = gr.Button("Refresh", variant="primary", elem_classes=["refresh-btn"])
190
  leaderboard_table = gr.DataFrame(
191
  label="Top 30",
192
  interactive=False,
@@ -247,6 +254,7 @@ with gr.Blocks(css=custom_css, title="PhotoBench-Protected Leaderboard") as demo
247
  # === Tab 3: About ===
248
  with gr.TabItem("ℹ️ About"):
249
  gr.Markdown(EVALUATION_INFO, elem_classes="markdown-text")
 
250
 
251
 
252
  demo.launch()
 
7
  import pandas as pd
8
 
9
  from src.about import (
10
+ ELIGIBILITY_INFO,
11
  EVALUATION_INFO,
12
  INTRODUCTION,
13
  NAVIGATION,
 
177
  gr.Markdown(INTRODUCTION, elem_classes="markdown-text")
178
 
179
  with gr.Tabs(elem_classes="tab-buttons"):
180
+ # === Tab 1: Leaderboard ===
181
  with gr.TabItem("🏅 Leaderboard"):
182
+ with gr.Row(elem_classes="leaderboard-controls"):
183
+ with gr.Column(scale=2):
184
+ method_filter = gr.Dropdown(
185
+ choices=["All", "Embedding", "Caption", "Agent"],
186
+ value="All",
187
+ label="Method",
188
+ )
189
+ with gr.Column(scale=2):
190
  sort_by = gr.Dropdown(
191
  choices=ALL_METRIC_COLS,
192
  value="Recall@10",
193
  label="Sort by",
194
  )
195
+ with gr.Column(scale=0, min_width=10):
196
+ refresh_btn = gr.Button("Refresh", variant="secondary", scale=0, elem_classes=["refresh-btn"])
197
  leaderboard_table = gr.DataFrame(
198
  label="Top 30",
199
  interactive=False,
 
254
  # === Tab 3: About ===
255
  with gr.TabItem("ℹ️ About"):
256
  gr.Markdown(EVALUATION_INFO, elem_classes="markdown-text")
257
+ gr.Markdown(ELIGIBILITY_INFO, elem_classes="markdown-text")
258
 
259
 
260
  demo.launch()
src/about.py CHANGED
@@ -135,6 +135,26 @@ Supported k values: **1, 5, 10, 20, 50, 100**
135
  Results are averaged across all evaluated queries per album, then averaged across albums for the final leaderboard score.
136
  """
137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  custom_css = """
139
  /* Grass-green clean theme */
140
  body {
 
135
  Results are averaged across all evaluated queries per album, then averaged across albums for the final leaderboard score.
136
  """
137
 
138
+ ELIGIBILITY_INFO = """
139
+ ### Why Isn't My Submission on the Leaderboard?
140
+
141
+ Evaluation and leaderboard ranking are two separate steps. **Every well-formed submission is fully evaluated and receives its metric scores** — no exceptions. However, **only complete submissions are eligible for the public leaderboard**. To be ranked, a submission must satisfy all three conditions:
142
+
143
+ 1. **Cover all 3 albums** (album 1, 2, and 3). Missing any album disqualifies the entry.
144
+ 2. **Answer every query.** The system matches each submitted item against the ground truth by `query_en`; only matched queries count. If any ground-truth queries are missing from your file, the submission is marked as *partial* and cannot be ranked. Extra queries (e.g., from an outdated `test.json`) are simply ignored — a few of them do not affect eligibility.
145
+ 3. **Opt in to publish.** If "Publish to public leaderboard" is unchecked, your result is recorded privately and never appears on the board.
146
+
147
+ Why so strict? Leaderboard numbers must be comparable. If two methods answered different sets of queries, comparing their average scores would be meaningless — so only results that answer **every query in every album** are ranked.
148
+
149
+ If your submission does not appear on the leaderboard, the returned result tells you why, for example:
150
+
151
+ > Result saved but NOT eligible for leaderboard: incomplete submission (850/900 queries). Only full submissions across all 3 albums are ranked.
152
+
153
+ This is **not** a failure — your metrics are still computed and returned to you. Simply fill in the missing queries and resubmit (note: each email may submit once per hour).
154
+
155
+ Finally, for repeated submissions under the same email and model name, only the best-scoring entry is kept.
156
+ """
157
+
158
  custom_css = """
159
  /* Grass-green clean theme */
160
  body {
src/evaluator.py CHANGED
@@ -9,13 +9,19 @@ import numpy as np
9
  logger = logging.getLogger(__name__)
10
 
11
  GT_DIR = Path("/data") / "gt"
 
12
 
13
  K_VALUES = [1, 5, 10, 20, 50, 100]
14
 
15
 
16
  class Evaluator:
17
  def __init__(self, gt_dir: str | Path | None = None):
18
- self.gt_dir = Path(gt_dir) if gt_dir else GT_DIR
 
 
 
 
 
19
  self._gt_cache: Dict[str, list] = {}
20
 
21
  def _load_gt(self, album_id: str) -> list:
@@ -171,6 +177,9 @@ class Evaluator:
171
  total_gt = sum(alb["total_gt_queries"] for alb in per_album.values())
172
  total_extraneous = sum(alb.get("extraneous_queries", 0) for alb in per_album.values())
173
 
 
 
 
174
  result = {
175
  "per_album": per_album,
176
  "global_metrics": avg_metrics,
 
9
  logger = logging.getLogger(__name__)
10
 
11
  GT_DIR = Path("/data") / "gt"
12
+ BUNDLED_GT_DIR = Path(__file__).parent.parent / "data" / "gt"
13
 
14
  K_VALUES = [1, 5, 10, 20, 50, 100]
15
 
16
 
17
  class Evaluator:
18
  def __init__(self, gt_dir: str | Path | None = None):
19
+ if gt_dir:
20
+ self.gt_dir = Path(gt_dir)
21
+ elif GT_DIR.exists():
22
+ self.gt_dir = GT_DIR
23
+ else:
24
+ self.gt_dir = BUNDLED_GT_DIR
25
  self._gt_cache: Dict[str, list] = {}
26
 
27
  def _load_gt(self, album_id: str) -> list:
 
177
  total_gt = sum(alb["total_gt_queries"] for alb in per_album.values())
178
  total_extraneous = sum(alb.get("extraneous_queries", 0) for alb in per_album.values())
179
 
180
+ # 完整性判定:提交按 query_en 与 GT 逐条匹配,只有能对上的题目才计入
181
+ # evaluated_queries;缺少任何 GT 题目即为不完整提交(partial),不能上榜。
182
+ # 多出来的 query(不在 GT 中,如旧版 test.json 残留)会被自动忽略。
183
  result = {
184
  "per_album": per_album,
185
  "global_metrics": avg_metrics,
src/leaderboard_manager.py CHANGED
@@ -1,6 +1,6 @@
1
  import hashlib
2
  import json
3
- from datetime import datetime, timedelta
4
  from typing import Any
5
 
6
  import pandas as pd
@@ -40,6 +40,27 @@ class LeaderboardManager:
40
  def _load(self):
41
  raw = load_leaderboard()
42
  self._entries = raw
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  def _save(self):
45
  save_leaderboard(self._entries)
@@ -67,6 +88,8 @@ class LeaderboardManager:
67
  ts_str = e.get("timestamp", "")
68
  try:
69
  ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
 
 
70
  except Exception:
71
  ts = datetime.utcnow()
72
 
@@ -90,12 +113,25 @@ class LeaderboardManager:
90
  global_metrics: dict,
91
  ) -> dict | None:
92
  """Add a new evaluation result. Returns entry if added, None if not eligible."""
93
- # Must be a full submission (all 3 albums, all queries matched)
 
 
 
 
 
 
94
  if set(albums) != {"1", "2", "3"}:
95
  return None
96
  if evaluated_queries < total_gt_queries:
97
  return None
98
 
 
 
 
 
 
 
 
99
  submission_id = make_id(email, model_name)
100
  entry = {
101
  "submission_id": submission_id,
@@ -105,7 +141,7 @@ class LeaderboardManager:
105
  "model_name": model_name,
106
  "albums": ",".join(albums),
107
  "is_paper_data": False,
108
- **{k: round(v, 4) for k, v in global_metrics.items() if k in ALL_METRIC_COLS or k in ("Recall", "NDCG")},
109
  }
110
 
111
  # Keep best score per (email, model_name)
@@ -118,7 +154,7 @@ class LeaderboardManager:
118
 
119
  if existing_idx is not None:
120
  old = self._entries[existing_idx]
121
- if global_metrics.get(_DEFAULT_SORT, 0) >= old.get(_DEFAULT_SORT, 0):
122
  self._entries[existing_idx] = entry
123
  else:
124
  self._entries.append(entry)
 
1
  import hashlib
2
  import json
3
+ from datetime import datetime, timedelta, timezone
4
  from typing import Any
5
 
6
  import pandas as pd
 
40
  def _load(self):
41
  raw = load_leaderboard()
42
  self._entries = raw
43
+ self._normalize_scales()
44
+
45
+ def _normalize_scales(self):
46
+ """Convert non-paper entries stored as fractions (0-1) to percent (0-100)."""
47
+ changed = False
48
+ for e in self._entries:
49
+ if e.get("is_paper_data"):
50
+ continue
51
+ vals = [e.get(k) for k in ALL_METRIC_COLS if isinstance(e.get(k), (int, float))]
52
+ if vals and max(vals) <= 1.5:
53
+ for k in ALL_METRIC_COLS + ["Recall", "NDCG"]:
54
+ v = e.get(k)
55
+ if isinstance(v, (int, float)):
56
+ e[k] = round(v * 100, 1)
57
+ changed = True
58
+ if changed:
59
+ print("[MIGRATE] Converted fraction-scale entries to percent scale")
60
+ try:
61
+ self._save()
62
+ except Exception as ex:
63
+ print(f"[WARN] Failed to save migrated leaderboard: {ex}")
64
 
65
  def _save(self):
66
  save_leaderboard(self._entries)
 
88
  ts_str = e.get("timestamp", "")
89
  try:
90
  ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
91
+ if ts.tzinfo is not None:
92
+ ts = ts.astimezone(timezone.utc).replace(tzinfo=None)
93
  except Exception:
94
  ts = datetime.utcnow()
95
 
 
113
  global_metrics: dict,
114
  ) -> dict | None:
115
  """Add a new evaluation result. Returns entry if added, None if not eligible."""
116
+ # 上榜资格判定:评测与上榜是两个独立环节。任何格式合法的提交都会被正常
117
+ # 评测并返回完整指标;但只有"完整提交"才有资格进入公开排行榜,需同时满足:
118
+ # 1. 覆盖全部 3 个相册(album_id 集合为 {"1", "2", "3"})
119
+ # 2. 所有 GT 题目都有有效作答(evaluated_queries >= total_gt_queries)
120
+ # 3. 提交时勾选了公开发布(由 app.py 在调用本方法前判断 opt_in)
121
+ # 不完整提交不上榜的原因:排行榜数字必须可比,若各方法作答的题目集合不同,
122
+ # 直接比较平均分没有意义。
123
  if set(albums) != {"1", "2", "3"}:
124
  return None
125
  if evaluated_queries < total_gt_queries:
126
  return None
127
 
128
+ # Evaluator returns fractions (0-1); leaderboard stores percent (0-100)
129
+ scaled_metrics = {
130
+ k: round(v * 100, 1)
131
+ for k, v in global_metrics.items()
132
+ if k in ALL_METRIC_COLS or k in ("Recall", "NDCG")
133
+ }
134
+
135
  submission_id = make_id(email, model_name)
136
  entry = {
137
  "submission_id": submission_id,
 
141
  "model_name": model_name,
142
  "albums": ",".join(albums),
143
  "is_paper_data": False,
144
+ **scaled_metrics,
145
  }
146
 
147
  # Keep best score per (email, model_name)
 
154
 
155
  if existing_idx is not None:
156
  old = self._entries[existing_idx]
157
+ if scaled_metrics.get(_DEFAULT_SORT, 0) >= old.get(_DEFAULT_SORT, 0):
158
  self._entries[existing_idx] = entry
159
  else:
160
  self._entries.append(entry)
src/storage.py CHANGED
@@ -24,8 +24,12 @@ def _seed_leaderboard():
24
  return
25
  if SEED_LEADERBOARD.exists():
26
  import shutil
27
- shutil.copy(SEED_LEADERBOARD, LEADERBOARD_FILE)
28
- print(f"[SEED] Copied leaderboard data from {SEED_LEADERBOARD} to {LEADERBOARD_FILE}")
 
 
 
 
29
 
30
 
31
  def save_submission(submission_id: str, payload: dict) -> str:
@@ -56,10 +60,11 @@ def list_submissions() -> list[dict]:
56
  def load_leaderboard() -> list[dict]:
57
  """Load current leaderboard data from local storage."""
58
  _seed_leaderboard()
59
- if not LEADERBOARD_FILE.exists():
 
60
  return []
61
  entries = []
62
- with open(LEADERBOARD_FILE, "r", encoding="utf-8") as f:
63
  for line in f:
64
  line = line.strip()
65
  if line:
 
24
  return
25
  if SEED_LEADERBOARD.exists():
26
  import shutil
27
+ try:
28
+ ensure_dirs()
29
+ shutil.copy(SEED_LEADERBOARD, LEADERBOARD_FILE)
30
+ print(f"[SEED] Copied leaderboard data from {SEED_LEADERBOARD} to {LEADERBOARD_FILE}")
31
+ except OSError as e:
32
+ print(f"[WARN] Cannot seed leaderboard at {LEADERBOARD_FILE}: {e}. Using bundled seed read-only.")
33
 
34
 
35
  def save_submission(submission_id: str, payload: dict) -> str:
 
60
  def load_leaderboard() -> list[dict]:
61
  """Load current leaderboard data from local storage."""
62
  _seed_leaderboard()
63
+ source = LEADERBOARD_FILE if LEADERBOARD_FILE.exists() else SEED_LEADERBOARD
64
+ if not source.exists():
65
  return []
66
  entries = []
67
+ with open(source, "r", encoding="utf-8") as f:
68
  for line in f:
69
  line = line.strip()
70
  if line: