File size: 9,226 Bytes
9b69df9
 
 
 
 
d7768e6
9b69df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
 
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d1372a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b69df9
 
 
 
9d1372a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b69df9
 
 
 
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7768e6
9b69df9
 
 
 
 
d7768e6
9b69df9
 
 
 
 
 
 
 
 
 
 
 
 
 
d7768e6
 
9b69df9
d7768e6
9b69df9
 
9d1372a
9b69df9
 
 
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
9d1372a
9b69df9
 
 
 
d7768e6
 
9b69df9
9d1372a
 
9b69df9
 
 
9d1372a
9b69df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d1372a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import os
import glob
import json
from typing import Dict, Literal, Tuple, List, Optional

import pandas as pd
import matplotlib.pyplot as plt
import gradio as gr

RESULTS_DIR = "./worldlens-results"

METRICS_MIN_BETTER = [
    "Depth Discrepancy", "Perceptual Discrepancy",
    "Photometric Error", "Geometric Discrepancy",
    "Novel-View Discrepancy",
    "Displacement Error",
]

METRICS_MAX_BETTER = [
    "Subject Fidelity", "Subject Coherence", "Subject Consistency",
    "Temporal Consistency", "Semantic Consistency",
    "View Consistency",
    "Novel-View Quality",
    "Open-Loop Adherence", "Route Completion", "Closed-Loop Adherence",
    "Map Segmentation", "3D Object Detection", "3D Object Tracking",
    "Occupancy Prediction",
]

METRIC_BETTER: Dict[str, Literal["min", "max"]] = {
    m: "min" for m in METRICS_MIN_BETTER
}
METRIC_BETTER.update({m: "max" for m in METRICS_MAX_BETTER})

METRIC_CHOICES: List[str] = sorted(set(METRICS_MIN_BETTER + METRICS_MAX_BETTER))
DEFAULT_METRIC = "Subject Fidelity" if "Subject Fidelity" in METRIC_CHOICES else METRIC_CHOICES[0]

df_all: Optional[pd.DataFrame] = None


def load_results() -> pd.DataFrame:

    rows = []

    json_files = sorted(glob.glob(os.path.join(RESULTS_DIR, "*.json")))
    if not json_files:
        return pd.DataFrame()

    for path in json_files:
        with open(path, "r") as f:
            data = json.load(f)

        model_name = os.path.splitext(os.path.basename(path))[0]
        venue = data.get("venue", "")
        date = data.get("date", "")

        row = {
            "Model": model_name,
            "venue": venue,
            "date": date,
        }

        metrics = data.get("Metrics", {})
        for category, metric_dict in metrics.items():
            if not isinstance(metric_dict, dict):
                continue
            for metric_name, value in metric_dict.items():
                row[metric_name] = value

        rows.append(row)

    df = pd.DataFrame(rows)

    meta_cols = ["Model", "venue", "date"]
    metric_cols = [c for c in df.columns if c not in meta_cols]
    df = df[meta_cols + metric_cols]

    return df


def get_venue_choices(df: pd.DataFrame) -> List[str]:
    if "venue" not in df.columns:
        return ["All"]
    venues = sorted([v for v in df["venue"].dropna().unique() if v != ""])
    return ["All"] + venues


def update_leaderboard(
    metric: str,
    top_k: int,
    model_filter: str,
    venue_filter: str,
    sort_mode: str,
    selected_metrics: Optional[List[str]],
) -> Tuple[pd.DataFrame, plt.Figure]:

    global df_all

    if df_all is None or df_all.empty:
        fig, ax = plt.subplots(figsize=(6, 3))
        ax.text(0.5, 0.5, "No results found in ./worldlens-results",
                ha="center", va="center")
        ax.axis("off")
        return pd.DataFrame(), fig

    df = df_all.copy()

    if model_filter:
        df = df[df["Model"].str.contains(model_filter, case=False, regex=False)]

    if venue_filter and venue_filter != "All":
        df = df[df["venue"] == venue_filter]

    if metric not in df.columns:
        fig, ax = plt.subplots(figsize=(6, 3))
        ax.text(0.5, 0.5, f"Metric '{metric}' not found in current data.", ha="center", va="center")
        ax.axis("off")
        return pd.DataFrame(), fig

    better = METRIC_BETTER.get(metric, "max")
    if sort_mode == "Auto":
        ascending = (better == "min")
    elif sort_mode == "Ascending (small → large)":
        ascending = True
    else:
        ascending = False

    df_sorted = df.sort_values(metric, ascending=ascending)

    df_top = df_sorted.head(top_k).copy()
    cols = ["Model", "venue", "date"]

    if selected_metrics is None:
        selected_metrics = []

    for m in selected_metrics:
        if m in df_top.columns and m not in cols:
            cols.append(m)

    if metric in df_top.columns and metric not in cols:
        cols.append(metric)

    table_df = df_top[cols].round(3)

    # =========================
    # Dark-theme leaderboard plot
    # =========================
    bg_color = "#0e1117"        # HF 深色背景
    panel_color = "#161b22"     # 面板背景
    bar_color = "#4cc9f0"       # 主色(青蓝)
    grid_color = "#30363d"
    text_color = "#c9d1d9"

    fig, ax = plt.subplots(figsize=(10, 4.5))
    fig.patch.set_facecolor(bg_color)
    ax.set_facecolor(panel_color)

    values = df_top[metric].values
    models = table_df["Model"].values
    bars = ax.barh(models, values, color=bar_color, height=0.6)

    if ascending:
        ax.invert_yaxis()

    ax.set_xlabel(metric, color=text_color, fontsize=11, labelpad=6)
    ax.set_title(
        f"Leaderboard · {metric}",
        fontsize=13,
        color=text_color,
        pad=10,
        fontweight="bold"
    )

    ax.xaxis.grid(True, linestyle="--", linewidth=0.6, color=grid_color, alpha=0.7)
    ax.yaxis.grid(False)

    for spine in ["top", "right", "left"]:
        ax.spines[spine].set_visible(False)
    ax.spines["bottom"].set_color(grid_color)

    ax.tick_params(axis="x", colors=text_color, labelsize=10)
    ax.tick_params(axis="y", colors=text_color, labelsize=10)

    for bar, value in zip(bars, values):
        ax.text(
            bar.get_width() * 1.01,
            bar.get_y() + bar.get_height() / 2,
            f"{value:.2f}",
            va="center",
            ha="left",
            fontsize=9.5,
            color=text_color
        )

    plt.tight_layout()

    return table_df, fig


def reload_data():

    global df_all
    df_all = load_results()

    if df_all is None or df_all.empty:
        msg = "No JSON files found in ./worldlens-results. Please upload some results."
        dummy_fig, ax = plt.subplots(figsize=(6, 3))
        ax.text(0.5, 0.5, msg, ha="center", va="center")
        ax.axis("off")

        venue_update = gr.update(choices=["All"], value="All")

        return msg, venue_update, pd.DataFrame(), dummy_fig

    venue_choices = get_venue_choices(df_all)
    msg = f"Loaded {len(df_all)} models from {RESULTS_DIR}"

    default_selected = ["Subject Fidelity", "Temporal Consistency", "Map Segmentation"]
    default_selected = [m for m in default_selected if m in METRIC_CHOICES]

    table_df, fig = update_leaderboard(
        metric=DEFAULT_METRIC,
        top_k=10,
        model_filter="",
        venue_filter="All",
        sort_mode="Auto",
        selected_metrics=default_selected,
    )

    venue_update = gr.update(
        choices=venue_choices,
        value="All",
        interactive=True,
    )

    return msg, venue_update, table_df, fig


with gr.Blocks(css="""
#title {
  text-align: center;
}
""") as demo:
    gr.Markdown(
        """
# 🌍 WorldLens Leaderboard
        """,
        elem_id="title"
    )

    status_box = gr.Markdown("Loading results...", elem_id="status")

    with gr.Row():
        metric_dropdown = gr.Dropdown(
            label="Metric (for ranking)",
            choices=METRIC_CHOICES,           # 固定 choices,避免动态更新不兼容
            value=DEFAULT_METRIC,
            interactive=True,
        )
        sort_mode_radio = gr.Radio(
            label="Sort mode",
            choices=[
                "Auto",
                "Ascending (small → large)",
                "Descending (large → small)",
            ],
            value="Auto",
            interactive=True,
        )
        topk_slider = gr.Slider(
            label="Top-K",
            minimum=3,
            maximum=50,
            value=10,
            step=1,
            interactive=True,
        )

    # 新增:表格中展示的多个指标
    metrics_select = gr.CheckboxGroup(
        label="Metrics to show in table",
        choices=METRIC_CHOICES,
        value=["Subject Fidelity", "Temporal Consistency", "Map Segmentation"],
        interactive=True,
    )

    with gr.Row():
        model_filter_box = gr.Textbox(
            label="Filter by model name",
            placeholder="magic, dream, ...",
            interactive=True,
        )
        venue_dropdown = gr.Dropdown(
            label="Filter by venue",
            choices=["All"],
            value="All",
            interactive=True,
        )

    with gr.Row():
        reload_button = gr.Button("🔄 Reload JSONs", variant="secondary")
        update_button = gr.Button("✅ Update leaderboard", variant="primary")

    leaderboard_table = gr.DataFrame(
        label="Leaderboard",
        interactive=False,
    )
    leaderboard_plot = gr.Plot(label="Metric comparison", format="png")

    reload_button.click(
        fn=reload_data,
        inputs=[],
        outputs=[status_box, venue_dropdown, leaderboard_table, leaderboard_plot],
    )

    update_button.click(
        fn=update_leaderboard,
        inputs=[
            metric_dropdown,
            topk_slider,
            model_filter_box,
            venue_dropdown,
            sort_mode_radio,
            metrics_select,
        ],
        outputs=[leaderboard_table, leaderboard_plot],
    )

    demo.load(
        fn=reload_data,
        inputs=[],
        outputs=[status_box, venue_dropdown, leaderboard_table, leaderboard_plot],
    )


if __name__ == "__main__":
    demo.launch()