Fancy-yousa commited on
Commit
cbfbcc2
·
verified ·
1 Parent(s): 26d150c

Upload app.py

Browse files
Files changed (1) hide show
  1. Webapp/app.py +1295 -0
Webapp/app.py ADDED
@@ -0,0 +1,1295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import datetime
5
+ import math
6
+ try:
7
+ import scipy.io
8
+ except ImportError:
9
+ scipy = None
10
+ try:
11
+ import numpy as np
12
+ except ImportError:
13
+ np = None
14
+ try:
15
+ import pandas as pd
16
+ except ImportError:
17
+ pd = None
18
+ from flask import Flask, jsonify, request, render_template, send_from_directory
19
+ from dash import Dash, html, dcc, dash_table, Input, Output, State, callback_context
20
+ from dash.dependencies import ALL
21
+ import dash_mantine_components as dmc
22
+ import plotly.graph_objects as go
23
+
24
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
25
+ from leaderboard import rank_results
26
+ try:
27
+ from complex_com import algorithms as ALGO_COMPLEXITY
28
+ except ImportError:
29
+ ALGO_COMPLEXITY = {}
30
+
31
+ base_dir = os.getcwd()
32
+ if not os.path.isdir(os.path.join(base_dir, "results")):
33
+ base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
34
+ PROJECT_ROOT = base_dir
35
+ RESULT_DIR = os.path.join(PROJECT_ROOT, "results")
36
+ DATA_DIR = os.path.join(PROJECT_ROOT, "data")
37
+ PDF_DIR = os.path.join(PROJECT_ROOT, "pdf")
38
+ ALGO_LINKS_PATH = os.path.join(PROJECT_ROOT, "algorithm_links.json")
39
+
40
+ os.makedirs(RESULT_DIR, exist_ok=True)
41
+
42
+ server = Flask(__name__)
43
+
44
+ RESULT_CACHE = {}
45
+ try:
46
+ with open(ALGO_LINKS_PATH, "r", encoding="utf-8") as f:
47
+ ALGORITHM_LINKS = json.load(f)
48
+ except Exception:
49
+ ALGORITHM_LINKS = {}
50
+
51
+
52
+ def save_result_json(dataset, results):
53
+ path = os.path.join(RESULT_DIR, f"{dataset}.json")
54
+ with open(path, "w", encoding="utf-8") as f:
55
+ json.dump(results, f, indent=4)
56
+
57
+
58
+ def load_result_json(dataset):
59
+ path = os.path.join(RESULT_DIR, f"{dataset}.json")
60
+ if not os.path.exists(path):
61
+ return None
62
+ with open(path, "r", encoding="utf-8") as f:
63
+ return json.load(f)
64
+
65
+
66
+ def list_available_datasets():
67
+ datasets = set()
68
+ for f in os.listdir(RESULT_DIR):
69
+ if f.endswith(".json"):
70
+ datasets.add(f.replace(".json", ""))
71
+ datasets.add("Authorship")
72
+ return sorted(datasets)
73
+
74
+
75
+ def run_agent_for_dataset(dataset):
76
+ return []
77
+
78
+
79
+ def build_dataset_metadata():
80
+ datasets = {}
81
+ for name in list_available_datasets():
82
+ last_updated = datetime.datetime.fromtimestamp(1707382400).strftime("%Y-%m-%d")
83
+ num_samples = None
84
+ total_features = None
85
+ if scipy:
86
+ mat_path = os.path.join(DATA_DIR, f"{name}.mat")
87
+ if os.path.exists(mat_path):
88
+ try:
89
+ mat = scipy.io.loadmat(mat_path)
90
+ if "X" in mat:
91
+ X = mat["X"]
92
+ num_samples, total_features = X.shape
93
+ except Exception:
94
+ num_samples = None
95
+ total_features = None
96
+ datasets[name] = {
97
+ "name": name,
98
+ "last_updated": last_updated,
99
+ "num_samples": num_samples,
100
+ "total_features": total_features,
101
+ }
102
+ return datasets
103
+
104
+
105
+ DATASET_METADATA = build_dataset_metadata()
106
+
107
+
108
+ def build_complexity_display():
109
+ display_complexity = {}
110
+ for algo, comp in ALGO_COMPLEXITY.items():
111
+ t = comp.get("time", "")
112
+ s = comp.get("space", "")
113
+ t_disp = t.replace("**", "^").replace(" * ", "")
114
+ if "O(" not in t_disp:
115
+ t_disp = f"O({t_disp})" if t_disp else ""
116
+ s_disp = s.replace("**", "^").replace(" * ", "")
117
+ if "O(" not in s_disp:
118
+ s_disp = f"O({s_disp})" if s_disp else ""
119
+ display_complexity[algo] = {"time": t_disp, "space": s_disp}
120
+ return display_complexity
121
+
122
+
123
+ DISPLAY_COMPLEXITY = build_complexity_display()
124
+
125
+ VIEW_CONFIG = {
126
+ "overall": [
127
+ {"key": "mean_f1", "label": "Mean F1"},
128
+ {"key": "mean_auc", "label": "Mean AUC"},
129
+ ],
130
+ "classifiers-f1": [
131
+ {"key": "metrics.nb.f1", "label": "NB F1"},
132
+ {"key": "metrics.svm.f1", "label": "SVM F1"},
133
+ {"key": "metrics.rf.f1", "label": "RF F1"},
134
+ ],
135
+ "classifiers-auc": [
136
+ {"key": "metrics.nb.auc", "label": "NB AUC"},
137
+ {"key": "metrics.svm.auc", "label": "SVM AUC"},
138
+ {"key": "metrics.rf.auc", "label": "RF AUC"},
139
+ ],
140
+ }
141
+
142
+
143
+ def get_results_for_dataset(dataset):
144
+ if dataset in RESULT_CACHE:
145
+ leaderboard = rank_results(RESULT_CACHE[dataset])
146
+ else:
147
+ results = load_result_json(dataset)
148
+ if results is None:
149
+ results = run_agent_for_dataset(dataset)
150
+ if results:
151
+ save_result_json(dataset, results)
152
+ RESULT_CACHE[dataset] = results or []
153
+ leaderboard = rank_results(results or [])
154
+ if not isinstance(leaderboard, list):
155
+ if hasattr(leaderboard, "to_dict"):
156
+ leaderboard = leaderboard.to_dict(orient="records")
157
+ else:
158
+ leaderboard = list(leaderboard)
159
+ return leaderboard
160
+
161
+
162
+ def get_metric_value(row, key):
163
+ value = row
164
+ for part in key.split("."):
165
+ if isinstance(value, dict):
166
+ value = value.get(part)
167
+ else:
168
+ return None
169
+ return value
170
+
171
+
172
+ def get_feature_count(row):
173
+ num_features = row.get("num_features")
174
+ if isinstance(num_features, (int, float)):
175
+ return int(num_features)
176
+ selected = row.get("selected_features")
177
+ if isinstance(selected, list):
178
+ return len(selected)
179
+ return 0
180
+
181
+
182
+ def apply_filters(results, dataset_meta, min_f1, max_features, del_range, complexity, selected_algos):
183
+ total_features = dataset_meta.get("total_features") if dataset_meta else None
184
+ filtered = []
185
+ min_del = (del_range[0] if del_range else 0) / 100
186
+ max_del = (del_range[1] if del_range else 100) / 100
187
+ min_f1 = min_f1 if min_f1 is not None else 0
188
+ max_features = max_features if max_features is not None else float("inf")
189
+ selected_algos = selected_algos if selected_algos else None
190
+ for r in results:
191
+ algo = r.get("algorithm")
192
+ if selected_algos and algo not in selected_algos:
193
+ continue
194
+ raw_f1 = r.get("mean_f1")
195
+ try:
196
+ f1 = float(raw_f1) if raw_f1 is not None else 0
197
+ except (TypeError, ValueError):
198
+ f1 = 0
199
+ if f1 < min_f1:
200
+ continue
201
+ feats = get_feature_count(r)
202
+ if feats > max_features:
203
+ continue
204
+ if isinstance(total_features, (int, float)) and total_features > 0:
205
+ del_rate = 1 - (feats / total_features)
206
+ if del_rate < min_del or del_rate > max_del:
207
+ continue
208
+ if complexity and complexity != "all":
209
+ comp = DISPLAY_COMPLEXITY.get(algo, {}).get("time")
210
+ if comp != complexity:
211
+ continue
212
+ filtered.append(r)
213
+ return filtered
214
+
215
+
216
+ def build_score_figure(results, view_mode):
217
+ if not results:
218
+ fig = go.Figure()
219
+ fig.add_annotation(
220
+ text="No Data Available",
221
+ x=0.5,
222
+ y=0.5,
223
+ xref="paper",
224
+ yref="paper",
225
+ showarrow=False,
226
+ font=dict(size=16, color="#999"),
227
+ )
228
+ fig.update_layout(
229
+ xaxis=dict(visible=False),
230
+ yaxis=dict(visible=False),
231
+ margin=dict(l=20, r=20, t=20, b=20),
232
+ )
233
+ return fig
234
+ top = results[:20]
235
+ labels = [r.get("algorithm") for r in top]
236
+ fig = go.Figure()
237
+ if view_mode == "overall":
238
+ fig.add_trace(go.Bar(
239
+ name="Mean F1",
240
+ y=labels,
241
+ x=[r.get("mean_f1") for r in top],
242
+ orientation="h",
243
+ marker_color="rgba(52, 152, 219, 0.7)",
244
+ ))
245
+ fig.add_trace(go.Bar(
246
+ name="Mean AUC",
247
+ y=labels,
248
+ x=[r.get("mean_auc") for r in top],
249
+ orientation="h",
250
+ marker_color="rgba(46, 204, 113, 0.7)",
251
+ ))
252
+ elif view_mode == "classifiers-f1":
253
+ for idx, clf in enumerate(["nb", "svm", "rf"]):
254
+ fig.add_trace(go.Bar(
255
+ name=clf.upper(),
256
+ y=labels,
257
+ x=[get_metric_value(r, f"metrics.{clf}.f1") for r in top],
258
+ orientation="h",
259
+ marker_color=f"hsla({200 + idx * 40}, 70%, 60%, 0.7)",
260
+ ))
261
+ else:
262
+ for idx, clf in enumerate(["nb", "svm", "rf"]):
263
+ fig.add_trace(go.Bar(
264
+ name=clf.upper(),
265
+ y=labels,
266
+ x=[get_metric_value(r, f"metrics.{clf}.auc") for r in top],
267
+ orientation="h",
268
+ marker_color=f"hsla({100 + idx * 40}, 70%, 60%, 0.7)",
269
+ ))
270
+ fig.update_layout(
271
+ barmode="group",
272
+ margin=dict(l=20, r=20, t=20, b=20),
273
+ legend=dict(orientation="h"),
274
+ yaxis=dict(autorange="reversed"),
275
+ )
276
+ return fig
277
+
278
+
279
+ def build_pareto_figure(results):
280
+ # Prepare data
281
+ points = []
282
+ for r in results:
283
+ x = get_feature_count(r)
284
+ y = r.get("mean_f1")
285
+ if x is None or y is None:
286
+ continue
287
+ algo = r.get("algorithm") or "Unknown"
288
+ t = r.get("time")
289
+ try:
290
+ y = float(y)
291
+ except Exception:
292
+ continue
293
+ points.append({"x": int(x), "y": y, "algo": algo, "time": t})
294
+ fig = go.Figure()
295
+ if not points:
296
+ fig.update_layout(
297
+ margin=dict(l=20, r=20, t=20, b=20),
298
+ xaxis_title="Selected Features",
299
+ yaxis_title="Mean F1",
300
+ )
301
+ fig.add_annotation(text="No data", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(color="#999"))
302
+ return fig
303
+
304
+ # Normalize time to bubble size (faster -> larger)
305
+ times = [p["time"] for p in points if isinstance(p["time"], (int, float))]
306
+ tmin = min(times) if times else 0.0
307
+ tmax = max(times) if times else 1.0
308
+ trange = (tmax - tmin) if (tmax - tmin) != 0 else 1.0
309
+ def bubble_size(t):
310
+ if not isinstance(t, (int, float)):
311
+ return 10
312
+ rel = 1.0 - ((t - tmin) / trange)
313
+ return 10 + 12 * max(0.0, min(1.0, rel))
314
+
315
+ # Color by algorithm
316
+ palette = [
317
+ "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
318
+ "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"
319
+ ]
320
+ algos = sorted({p["algo"] for p in points})
321
+ color_map = {a: palette[i % len(palette)] for i, a in enumerate(algos)}
322
+
323
+ # Scatter per algorithm
324
+ for algo in algos:
325
+ ap = [p for p in points if p["algo"] == algo]
326
+ if not ap:
327
+ continue
328
+ fig.add_trace(go.Scatter(
329
+ x=[p["x"] for p in ap],
330
+ y=[p["y"] for p in ap],
331
+ mode="markers",
332
+ name=algo,
333
+ marker=dict(
334
+ color=color_map[algo],
335
+ size=[bubble_size(p["time"]) for p in ap],
336
+ opacity=0.8,
337
+ line=dict(color="rgba(0,0,0,0.1)", width=1)
338
+ ),
339
+ hovertemplate="<b>%{text}</b><br>Features: %{x}<br>Mean F1: %{y:.4f}<br>" +
340
+ "Time: %{customdata:.2f}s" +
341
+ "<extra></extra>",
342
+ text=[algo for _ in ap],
343
+ customdata=[p["time"] if isinstance(p["time"], (int, float)) else None for p in ap],
344
+ ))
345
+
346
+ # Compute Pareto frontier (min x, max y)
347
+ pts_sorted = sorted(points, key=lambda p: (p["x"], -p["y"]))
348
+ frontier = []
349
+ best_y = -1.0
350
+ for p in pts_sorted:
351
+ if p["y"] >= best_y:
352
+ frontier.append(p)
353
+ best_y = p["y"]
354
+ if len(frontier) >= 2:
355
+ fig.add_trace(go.Scatter(
356
+ x=[p["x"] for p in frontier],
357
+ y=[p["y"] for p in frontier],
358
+ mode="lines+markers",
359
+ name="Pareto Front",
360
+ line=dict(color="#2c3e50", width=2, dash="dash"),
361
+ marker=dict(symbol="diamond", size=6, color="#2c3e50"),
362
+ hoverinfo="skip"
363
+ ))
364
+
365
+ fig.update_layout(
366
+ margin=dict(l=20, r=20, t=20, b=20),
367
+ xaxis_title="Selected Features (fewer is better)",
368
+ yaxis_title="Mean F1 (higher is better)",
369
+ legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
370
+ )
371
+ fig.update_xaxes(gridcolor="rgba(0,0,0,0.05)", zeroline=False)
372
+ fig.update_yaxes(gridcolor="rgba(0,0,0,0.05)", range=[0, 1], zeroline=False)
373
+ fig.add_annotation(
374
+ xref="paper", yref="paper", x=0.02, y=1.08,
375
+ showarrow=False,
376
+ text="Bubble size ∝ speed (faster = larger), color = algorithm",
377
+ font=dict(size=12, color="#666")
378
+ )
379
+ return fig
380
+
381
+
382
+ def build_table(results, view_mode):
383
+ config = VIEW_CONFIG[view_mode]
384
+ headers = ["Rank", "Algorithm"] + [c["label"] for c in config] + ["Selected Features"]
385
+ col_keys = [c["key"] for c in config]
386
+ max_map = {}
387
+ for key in col_keys:
388
+ vals = []
389
+ for r in results:
390
+ v = get_metric_value(r, key)
391
+ try:
392
+ v = float(v) if v is not None else None
393
+ except Exception:
394
+ v = None
395
+ if v is not None:
396
+ vals.append(v)
397
+ max_map[key] = max(vals) if vals else 0
398
+ thead = html.Thead(
399
+ html.Tr([html.Th(h, className="cth") for h in headers], className="chead")
400
+ )
401
+ rows = []
402
+ if not results:
403
+ empty_cells = [html.Td("", className="ctd")] * (len(headers) - 2)
404
+ rows.append(
405
+ html.Tr(
406
+ [html.Td("", className="ctd"), html.Td("No Data Available", className="ctd")]+empty_cells,
407
+ className="crow"
408
+ )
409
+ )
410
+ else:
411
+ for idx, r in enumerate(results):
412
+ rank = idx + 1
413
+ medal = {1: "🥇", 2: "🥈", 3: "🥉"}.get(rank, str(rank))
414
+ row_class = (
415
+ "crow crow-gold" if rank == 1 else
416
+ "crow crow-silver" if rank == 2 else
417
+ "crow crow-bronze" if rank == 3 else
418
+ "crow"
419
+ )
420
+ algo = r.get("algorithm") or "Unknown"
421
+ algo_url = (ALGORITHM_LINKS.get(algo) or "").strip()
422
+ if algo_url:
423
+ algo_cell = html.A(algo, href=algo_url, target="_blank", rel="noopener", className="algo-link", title="Open paper/link in a new tab")
424
+ else:
425
+ algo_cell = html.Span(algo, className="calgo")
426
+ metric_tds = []
427
+ for c in config:
428
+ key = c["key"]
429
+ raw = get_metric_value(r, key)
430
+ try:
431
+ val = float(raw) if raw is not None else 0.0
432
+ except Exception:
433
+ val = 0.0
434
+ m = max_map.get(key) or 0.0
435
+ pct = (val / m * 100.0) if m > 0 else 0
436
+ is_max = (m > 0 and abs(val - m) < 1e-12)
437
+ bar = html.Div(
438
+ [
439
+ html.Div(className="bar-track", children=html.Div(className="bar-fill", style={"width": f"{pct:.2f}%"})),
440
+ html.Span(f"{val:.4f}", className=("bar-text is-max" if is_max else "bar-text")),
441
+ ],
442
+ className="bar-cell",
443
+ title=f"max={m:.4f}" if is_max else None,
444
+ )
445
+ cell = html.Td(bar, className="ctd cnum")
446
+ metric_tds.append(cell)
447
+ selected = r.get("selected_features")
448
+ feat_count = get_feature_count(r)
449
+ if isinstance(selected, list):
450
+ features_title = ", ".join(str(s) for s in selected)
451
+ else:
452
+ features_title = "N/A"
453
+ feature_btn = html.Button(
454
+ f"{feat_count} features",
455
+ id={"type": "feature-link", "index": idx},
456
+ n_clicks=0,
457
+ className="link-like",
458
+ title=features_title,
459
+ )
460
+ feature_td = html.Td(feature_btn, className="ctd cfeat", style={"whiteSpace": "nowrap"})
461
+ row = html.Tr(
462
+ [html.Td(medal, className="ctd crank"), html.Td(algo_cell, className="ctd calgo")] + metric_tds + [feature_td],
463
+ className=row_class,
464
+ )
465
+ rows.append(row)
466
+ tbody = html.Tbody(rows)
467
+ table = html.Table([thead, tbody], className="custom-table")
468
+ return html.Div(className="table-container", children=table)
469
+
470
+
471
+ dataset_options = [{"label": name, "value": name} for name in sorted(DATASET_METADATA.keys())]
472
+ default_dataset = "Authorship" if "Authorship" in DATASET_METADATA else (dataset_options[0]["value"] if dataset_options else "Authorship")
473
+
474
+ complexity_options = sorted({v.get("time") for v in DISPLAY_COMPLEXITY.values() if v.get("time")})
475
+ complexity_data = [{"label": "All Complexities", "value": "all"}] + [
476
+ {"label": c, "value": c} for c in complexity_options
477
+ ]
478
+
479
+ dash_app = Dash(__name__, server=server, url_base_pathname="/")
480
+ app = dash_app
481
+
482
+ css = """
483
+ :root {
484
+ --primary-color: #3498db;
485
+ --secondary-color: #2c3e50;
486
+ --background-color: #f8f9fa;
487
+ --text-color: #333;
488
+ --border-color: #dee2e6;
489
+ --hover-color: #f1f1f1;
490
+ --accent-color: #e67e22;
491
+ --sidebar-width: 280px;
492
+ }
493
+ body {
494
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
495
+ margin: 0;
496
+ padding: 0;
497
+ background-color: var(--background-color);
498
+ color: var(--text-color);
499
+ }
500
+ .app-shell {
501
+ display: flex;
502
+ min-height: 100vh;
503
+ }
504
+ .sidebar {
505
+ width: var(--sidebar-width);
506
+ background-color: var(--secondary-color);
507
+ color: white;
508
+ position: fixed;
509
+ height: 100vh;
510
+ overflow-y: auto;
511
+ padding: 20px;
512
+ box-sizing: border-box;
513
+ left: 0;
514
+ top: 0;
515
+ z-index: 100;
516
+ display: flex;
517
+ flex-direction: column;
518
+ gap: 20px;
519
+ }
520
+ .sidebar h2 {
521
+ font-size: 1.1em;
522
+ margin-bottom: 10px;
523
+ color: #ecf0f1;
524
+ border-bottom: 1px solid #34495e;
525
+ padding-bottom: 5px;
526
+ }
527
+ .main-content {
528
+ margin-left: var(--sidebar-width);
529
+ padding: 24px;
530
+ width: calc(100% - var(--sidebar-width));
531
+ box-sizing: border-box;
532
+ }
533
+ .stats-grid {
534
+ display: grid;
535
+ grid-template-columns: 1fr;
536
+ gap: 10px;
537
+ }
538
+ .stat-card {
539
+ background: rgba(255,255,255,0.1);
540
+ padding: 10px;
541
+ border-radius: 6px;
542
+ text-align: center;
543
+ }
544
+ .stat-value {
545
+ font-size: 1.2em;
546
+ font-weight: 600;
547
+ color: var(--accent-color);
548
+ }
549
+ .stat-label {
550
+ font-size: 0.8em;
551
+ color: #bdc3c7;
552
+ }
553
+ .card {
554
+ background: white;
555
+ padding: 16px;
556
+ border-radius: 8px;
557
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
558
+ }
559
+ .chart-card {
560
+ background: white;
561
+ padding: 16px;
562
+ border-radius: 8px;
563
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
564
+ height: 420px;
565
+ display: flex;
566
+ flex-direction: column;
567
+ }
568
+ .chart-card .dash-graph {
569
+ flex: 1;
570
+ }
571
+ .table-container {
572
+ background: white;
573
+ padding: 12px;
574
+ border-radius: 8px;
575
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
576
+ }
577
+ .nav-links {
578
+ list-style: none;
579
+ padding: 0;
580
+ margin: 0;
581
+ }
582
+ .nav-links li a {
583
+ display: block;
584
+ padding: 8px;
585
+ color: #bdc3c7;
586
+ text-decoration: none;
587
+ border-radius: 4px;
588
+ }
589
+ .nav-links li a:hover {
590
+ background: rgba(255,255,255,0.1);
591
+ color: white;
592
+ }
593
+
594
+ /* Custom Table Styles */
595
+ .custom-table-wrapper {
596
+ overflow-x: auto;
597
+ overflow-y: auto;
598
+ max-height: 520px;
599
+ background: #fff;
600
+ border: 1px solid #eee;
601
+ border-radius: 8px;
602
+ box-shadow: 0 1px 3px rgba(0,0,0,0.06);
603
+ }
604
+ .custom-table {
605
+ width: 100%;
606
+ border-collapse: separate;
607
+ border-spacing: 0;
608
+ table-layout: fixed;
609
+ }
610
+ .custom-table thead th {
611
+ text-align: left;
612
+ border-bottom: 2px solid var(--border-color);
613
+ padding: 10px;
614
+ }
615
+ .custom-table tbody td {
616
+ padding: 8px 10px;
617
+ border-bottom: 1px solid #eee;
618
+ vertical-align: middle;
619
+ }
620
+ .custom-table tbody tr:hover {
621
+ background: #fafafa;
622
+ transition: background 0.2s ease;
623
+ }
624
+ .custom-table tbody tr:nth-child(even) { background: #fcfcfc; }
625
+ .custom-table thead th {
626
+ position: sticky;
627
+ top: 0;
628
+ background: #fff;
629
+ z-index: 1;
630
+ }
631
+ .cnum { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; text-align: right; }
632
+ .is-max { font-weight: 600; color: var(--accent-color); }
633
+ .crow-gold { background: rgba(255,215,0,0.12); }
634
+ .crow-silver { background: rgba(192,192,192,0.12); }
635
+ .crow-bronze { background: rgba(205,127,50,0.12); }
636
+ .crank { width: 56px; text-align: center; }
637
+ .calgo { font-weight: 500; }
638
+ .cth { background: var(--background-color); }
639
+ .cfeat { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
640
+ .algo-link { color: #2c7be5; text-decoration: none; border-bottom: 1px dashed rgba(44,123,229,0.35); }
641
+ .algo-link:hover { color: #1a68d1; border-color: rgba(26,104,209,0.6); }
642
+ .link-like { color: var(--accent-color); background: none; border: none; padding: 0; cursor: pointer; text-decoration: underline; font-family: inherit; }
643
+
644
+ /* In-cell Data Bars */
645
+ .bar-cell {
646
+ position: relative;
647
+ height: 26px;
648
+ display: flex;
649
+ align-items: center;
650
+ justify-content: flex-end;
651
+ }
652
+ .bar-track {
653
+ position: absolute;
654
+ left: 6px;
655
+ right: 6px;
656
+ height: 60%;
657
+ background: #f4f7fb;
658
+ border: 1px solid #e6eef7;
659
+ border-radius: 6px;
660
+ overflow: hidden;
661
+ }
662
+ .bar-fill {
663
+ height: 100%;
664
+ background: linear-gradient(90deg, #7db9e8 0%, #3498db 100%);
665
+ opacity: 0.35;
666
+ transition: width 200ms ease;
667
+ }
668
+ .bar-text {
669
+ position: relative;
670
+ z-index: 1;
671
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
672
+ padding: 0 6px;
673
+ line-height: 1;
674
+ }
675
+
676
+ /* Tags in modal */
677
+ .tag {
678
+ display: inline-block;
679
+ padding: 4px 8px;
680
+ background: #f1f5fb;
681
+ color: #2c3e50;
682
+ border: 1px solid #e2e8f0;
683
+ border-radius: 12px;
684
+ font-size: 12px;
685
+ }
686
+ """
687
+
688
+ dash_app.index_string = f"""
689
+ <!DOCTYPE html>
690
+ <html>
691
+ <head>
692
+ {{%metas%}}
693
+ <title>AutoFS Leaderboard</title>
694
+ {{%favicon%}}
695
+ {{%css%}}
696
+ <style>{css}</style>
697
+ </head>
698
+ <body>
699
+ {{%app_entry%}}
700
+ <footer>
701
+ {{%config%}}
702
+ {{%scripts%}}
703
+ {{%renderer%}}
704
+ </footer>
705
+ </body>
706
+ </html>
707
+ """
708
+
709
+ dash_app.layout = dmc.MantineProvider(
710
+ children=html.Div(
711
+ className="app-shell",
712
+ children=[
713
+ html.Aside(
714
+ className="sidebar",
715
+ children=[
716
+ html.Div(
717
+ [
718
+ html.H1("AutoFS", style={"fontSize": "1.5em", "margin": 0, "color": "white"}),
719
+ html.Div("Feature Selection Leaderboard", style={"fontSize": "0.8em", "color": "#bdc3c7"}),
720
+ ],
721
+ style={"textAlign": "center", "marginBottom": "10px"},
722
+ ),
723
+ html.Div(
724
+ className="stats-grid",
725
+ children=[
726
+ html.Div([html.Div("-", id="stat-count", className="stat-value"), html.Div("Methods", className="stat-label")], className="stat-card"),
727
+ html.Div([html.Div("-", id="stat-best", className="stat-value"), html.Div("Best F1", className="stat-label")], className="stat-card"),
728
+ html.Div([html.Div("-", id="stat-updated", className="stat-value"), html.Div("Updated", className="stat-label")], className="stat-card"),
729
+ ],
730
+ ),
731
+ html.Div(
732
+ [
733
+ html.H2("Navigation"),
734
+ html.Ul(
735
+ className="nav-links",
736
+ children=[
737
+ html.Li(html.A("📊 Overview", href="#overview")),
738
+ html.Li(html.A("🏆 Leaderboard", href="#main-table")),
739
+ html.Li(html.A("📈 Charts", href="#charts")),
740
+ html.Li(html.A("ℹ️ Details", href="#details")),
741
+ html.Li(html.A("🌍 Global Rankings", href="/global")),
742
+ html.Li(html.A("📤 Submit Data/Method", href="/submit")),
743
+ ],
744
+ ),
745
+ ]
746
+ ),
747
+ html.Div(
748
+ [
749
+ html.H2("Global Controls"),
750
+ dmc.Select(
751
+ id="view-mode",
752
+ data=[
753
+ {"label": "Overall (Mean)", "value": "overall"},
754
+ {"label": "F1 by Classifier", "value": "classifiers-f1"},
755
+ {"label": "AUC by Classifier", "value": "classifiers-auc"},
756
+ ],
757
+ value="overall",
758
+ clearable=False,
759
+ style={"marginBottom": "10px"},
760
+ ),
761
+ ]
762
+ ),
763
+ html.Div(
764
+ [
765
+ html.H2("Filters"),
766
+ dmc.Select(
767
+ id="dataset-select",
768
+ data=dataset_options,
769
+ value="Authorship",
770
+ clearable=False,
771
+ style={"marginBottom": "10px"},
772
+ ),
773
+ html.Div(
774
+ [
775
+ html.Div(
776
+ [
777
+ html.Span("Min F1 Score: "),
778
+ html.Span("0.0000", id="val-f1", style={"color": "var(--accent-color)"}),
779
+ ],
780
+ style={"marginBottom": "6px", "color": "#bdc3c7"},
781
+ ),
782
+ dmc.Slider(id="filter-f1", min=0, max=1, step=0.0001, value=0),
783
+ ],
784
+ style={"marginBottom": "12px"},
785
+ ),
786
+ html.Div(
787
+ [
788
+ html.Div(
789
+ [
790
+ html.Span("Del. Rate: "),
791
+ html.Span("0% - 100%", id="val-del-rate", style={"color": "var(--accent-color)"}),
792
+ ],
793
+ style={"marginBottom": "6px", "color": "#bdc3c7"},
794
+ ),
795
+ dmc.RangeSlider(id="filter-del-rate", min=0, max=100, value=[0, 100], step=1),
796
+ ],
797
+ style={"marginBottom": "12px"},
798
+ ),
799
+ html.Div(
800
+ [
801
+ html.Div(
802
+ [
803
+ html.Span("Max Features: "),
804
+ html.Span("All", id="val-feats", style={"color": "var(--accent-color)"}),
805
+ ],
806
+ style={"marginBottom": "6px", "color": "#bdc3c7"},
807
+ ),
808
+ dmc.Slider(id="filter-feats", min=1, max=100, step=1, value=100),
809
+ ],
810
+ style={"marginBottom": "12px"},
811
+ ),
812
+ dmc.Select(
813
+ id="filter-complexity",
814
+ data=complexity_data,
815
+ value="all",
816
+ clearable=False,
817
+ style={"marginBottom": "12px"},
818
+ ),
819
+ dmc.CheckboxGroup(id="filter-algos", children=[], value=[], orientation="vertical"),
820
+ ]
821
+ ),
822
+ ],
823
+ ),
824
+ html.Main(
825
+ className="main-content",
826
+ children=[
827
+ html.Header(
828
+ [
829
+ html.H1("🏆 Leaderboard Dashboard", style={"color": "var(--secondary-color)", "margin": 0}),
830
+ html.Div("Comprehensive benchmark of feature selection algorithms across diverse datasets.", className="subtitle"),
831
+ ]
832
+ ),
833
+ html.Div(
834
+ className="card",
835
+ children=[
836
+ html.P([
837
+ "Feature selection is a critical step in machine learning and data analysis, aimed at ",
838
+ html.Strong("identifying the most relevant subset of features"),
839
+ " from a high-dimensional dataset. By eliminating irrelevant or redundant features, feature selection not only ",
840
+ html.Strong("improves model interpretability"),
841
+ " but also ",
842
+ html.Strong("enhances predictive performance"),
843
+ " and ",
844
+ html.Strong("reduces computational cost"),
845
+ ".",
846
+ ]),
847
+ html.P([
848
+ "This leaderboard presents a comprehensive comparison of various feature selection algorithms across multiple benchmark datasets. It includes several ",
849
+ html.Strong("information-theoretic and mutual information-based methods"),
850
+ ", which quantify the statistical dependency between features and the target variable to rank feature relevance. Mutual information approaches are particularly effective in ",
851
+ html.Strong("capturing both linear and non-linear relationships"),
852
+ ", making them suitable for complex datasets where classical correlation-based methods may fail.",
853
+ ]),
854
+ html.P([
855
+ "The leaderboard is structured to reflect algorithm performance across different datasets, allowing for an objective assessment of each method’s ability to select informative features. For each method and dataset combination, metrics such as ",
856
+ html.Strong("classification accuracy, F1-score, and area under the ROC curve (AUC)"),
857
+ " are reported, providing insights into how the selected features contribute to predictive modeling.",
858
+ ]),
859
+ html.P([
860
+ "By examining this feature selection leaderboard, researchers and practitioners can gain a better understanding of which methods perform consistently well across diverse domains, helping to guide the choice of feature selection strategies in real-world applications. This serves as a valuable resource for both benchmarking and method development in the field of feature selection.",
861
+ ]),
862
+ ],
863
+ style={"marginTop": "16px"},
864
+ ),
865
+ dmc.Grid(
866
+ id="overview",
867
+ gutter="md",
868
+ style={"marginTop": "16px"},
869
+ children=[
870
+ dmc.Col(
871
+ span=12,
872
+ md=6,
873
+ children=html.Div(
874
+ className="card",
875
+ children=[
876
+ html.H3("About This Dataset"),
877
+ html.P(["Analyzing performance on ", html.Strong(html.Span("Selected", id="desc-dataset-name")), "."]),
878
+ ],
879
+ ),
880
+ ),
881
+ dmc.Col(
882
+ span=12,
883
+ md=6,
884
+ children=html.Div(
885
+ className="card",
886
+ children=[
887
+ html.H3("Dataset Metadata"),
888
+ html.Div(["Name: ", html.Span("-", id="meta-name")]),
889
+ html.Div(["Samples: ", html.Span("-", id="meta-samples"), " | Features: ", html.Span("-", id="meta-features")]),
890
+ html.Div(["Last Updated: ", html.Span("-", id="meta-updated")]),
891
+ ],
892
+ ),
893
+ ),
894
+ ],
895
+ ),
896
+ html.Div(
897
+ id="main-table",
898
+ style={"marginTop": "24px"},
899
+ children=[
900
+ html.H3("📋 Detailed Rankings"),
901
+ html.Div(id="custom-table-container", className="custom-table-wrapper"),
902
+ dmc.Modal(
903
+ id="feature-modal",
904
+ opened=False,
905
+ title="Feature Details",
906
+ children=html.Div(id="feature-modal-content"),
907
+ size="lg",
908
+ zIndex=1200,
909
+ overlayOpacity=0.4,
910
+ overlayBlur=2,
911
+ ),
912
+ ],
913
+ ),
914
+ html.Div(
915
+ id="charts",
916
+ style={"marginTop": "24px"},
917
+ children=[
918
+ dmc.Grid(
919
+ gutter="md",
920
+ children=[
921
+ dmc.Col(
922
+ span=12,
923
+ md=6,
924
+ children=html.Div(
925
+ className="chart-card",
926
+ children=[
927
+ html.H3("📊 Performance Comparison"),
928
+ dcc.Graph(id="score-graph", config={"responsive": True}, style={"height": "100%"}),
929
+ ],
930
+ ),
931
+ ),
932
+ dmc.Col(
933
+ span=12,
934
+ md=6,
935
+ children=html.Div(
936
+ className="chart-card",
937
+ children=[
938
+ html.H3("📉 Pareto Frontier (Trade-off)"),
939
+ html.Div("X: Selected Features vs Y: F1 Score (Top-Left is better)", style={"fontSize": "0.9em", "color": "#666"}),
940
+ dcc.Graph(id="pareto-graph", config={"responsive": True}, style={"height": "100%"}),
941
+ ],
942
+ ),
943
+ ),
944
+ ],
945
+ )
946
+ ],
947
+ ),
948
+ html.Div(
949
+ id="details",
950
+ style={"marginTop": "50px", "color": "#999", "textAlign": "center", "borderTop": "1px solid #eee", "paddingTop": "20px"},
951
+ children="AutoFS Benchmark Platform © 2026",
952
+ ),
953
+ ],
954
+ ),
955
+ ],
956
+ )
957
+ )
958
+
959
+
960
+ @dash_app.callback(
961
+ Output("filter-feats", "max"),
962
+ Output("filter-feats", "value"),
963
+ Output("filter-f1", "min"),
964
+ Output("filter-f1", "max"),
965
+ Output("filter-f1", "value"),
966
+ Output("filter-algos", "children"),
967
+ Output("filter-algos", "value"),
968
+ Output("meta-name", "children"),
969
+ Output("meta-samples", "children"),
970
+ Output("meta-features", "children"),
971
+ Output("meta-updated", "children"),
972
+ Output("desc-dataset-name", "children"),
973
+ Output("stat-updated", "children"),
974
+ Output("stat-count", "children"),
975
+ Output("stat-best", "children"),
976
+ Output("score-graph", "figure"),
977
+ Output("pareto-graph", "figure"),
978
+ Output("custom-table-container", "children"),
979
+ Output("val-f1", "children"),
980
+ Output("val-feats", "children"),
981
+ Output("val-del-rate", "children"),
982
+ Input("dataset-select", "value"),
983
+ Input("view-mode", "value"),
984
+ Input("filter-f1", "value"),
985
+ Input("filter-feats", "value"),
986
+ Input("filter-del-rate", "value"),
987
+ Input("filter-complexity", "value"),
988
+ Input("filter-algos", "value"),
989
+ State("filter-f1", "min"),
990
+ State("filter-f1", "max"),
991
+ State("filter-feats", "max"),
992
+ State("filter-algos", "children"),
993
+ State("filter-algos", "value"),
994
+ )
995
+ def update_dashboard_all(
996
+ dataset,
997
+ view_mode,
998
+ min_f1_value,
999
+ max_features_value,
1000
+ del_range,
1001
+ complexity,
1002
+ selected_algos,
1003
+ f1_min_state,
1004
+ f1_max_state,
1005
+ feats_max_state,
1006
+ algo_children_state,
1007
+ algo_value_state,
1008
+ ):
1009
+ triggered_id = callback_context.triggered_id if callback_context.triggered else None
1010
+ dataset_changed = triggered_id == "dataset-select" or triggered_id is None
1011
+ selected = dataset or "Authorship"
1012
+ meta = DATASET_METADATA.get(selected, {"name": selected, "last_updated": "-", "num_samples": None, "total_features": None})
1013
+ results = get_results_for_dataset(selected)
1014
+ algo_list = sorted({r.get("algorithm") for r in results if r.get("algorithm")})
1015
+ if dataset_changed:
1016
+ f1_scores = [r.get("mean_f1") for r in results if r.get("mean_f1") is not None]
1017
+ if f1_scores:
1018
+ min_f1 = min(f1_scores)
1019
+ safe_min = max(0, math.floor((min_f1 - 0.1) * 10) / 10)
1020
+ else:
1021
+ safe_min = 0
1022
+ max_feats = meta.get("total_features") or 100
1023
+ f1_min = safe_min
1024
+ f1_max = 1
1025
+ f1_value = safe_min
1026
+ feats_max = max_feats
1027
+ feats_value = max_feats
1028
+ algo_children = [dmc.Checkbox(label=a, value=a) for a in algo_list]
1029
+ algo_value = algo_list
1030
+ else:
1031
+ f1_min = f1_min_state if f1_min_state is not None else 0
1032
+ f1_max = f1_max_state if f1_max_state is not None else 1
1033
+ f1_value = min_f1_value if min_f1_value is not None else f1_min
1034
+ feats_max = feats_max_state if feats_max_state is not None else (meta.get("total_features") or 100)
1035
+ feats_value = max_features_value if max_features_value is not None else feats_max
1036
+ if algo_children_state:
1037
+ algo_children = algo_children_state
1038
+ else:
1039
+ algo_children = [dmc.Checkbox(label=a, value=a) for a in algo_list]
1040
+ if selected_algos is not None:
1041
+ algo_value = selected_algos
1042
+ else:
1043
+ algo_value = algo_value_state if algo_value_state is not None else algo_list
1044
+ filtered = apply_filters(results, meta, f1_value or 0, feats_value, del_range, complexity, algo_value or [])
1045
+ count = len(filtered)
1046
+ if filtered:
1047
+ best = max(filtered, key=lambda r: r.get("mean_f1") or 0)
1048
+ best_text = f"{best.get('algorithm')} ({(best.get('mean_f1') or 0):.3f})"
1049
+ else:
1050
+ best_text = "-"
1051
+ score_fig = build_score_figure(filtered, view_mode or "overall")
1052
+ pareto_fig = build_pareto_figure(filtered)
1053
+ table_component = build_table(filtered, view_mode or "overall")
1054
+ val_f1 = f"{(f1_value or 0):.4f}"
1055
+ val_feats = str(int(feats_value)) if isinstance(feats_value, (int, float)) else "All"
1056
+ del_min = del_range[0] if del_range else 0
1057
+ del_max = del_range[1] if del_range else 100
1058
+ val_del = f"{del_min:.0f}% - {del_max:.0f}%"
1059
+ meta_samples = meta.get("num_samples") if meta.get("num_samples") is not None else "Unavailable"
1060
+ meta_features = meta.get("total_features") if meta.get("total_features") is not None else "Unavailable"
1061
+ return (
1062
+ feats_max,
1063
+ feats_value,
1064
+ f1_min,
1065
+ f1_max,
1066
+ f1_value,
1067
+ algo_children,
1068
+ algo_value,
1069
+ meta.get("name", "-"),
1070
+ meta_samples,
1071
+ meta_features,
1072
+ meta.get("last_updated", "-"),
1073
+ meta.get("name", "-"),
1074
+ meta.get("last_updated", "-"),
1075
+ count,
1076
+ best_text,
1077
+ score_fig,
1078
+ pareto_fig,
1079
+ table_component,
1080
+ val_f1,
1081
+ val_feats,
1082
+ val_del,
1083
+ )
1084
+
1085
+
1086
+ def sanitize_json(value):
1087
+ if value is None or isinstance(value, (str, int, float, bool)):
1088
+ return value
1089
+ if np and isinstance(value, np.generic):
1090
+ return value.item()
1091
+ if np and isinstance(value, np.ndarray):
1092
+ return value.tolist()
1093
+ if pd and isinstance(value, (pd.DataFrame, pd.Series)):
1094
+ if isinstance(value, pd.DataFrame):
1095
+ return value.to_dict(orient="records")
1096
+ return value.to_dict()
1097
+ if isinstance(value, (datetime.datetime, datetime.date)):
1098
+ return value.isoformat()
1099
+ if isinstance(value, dict):
1100
+ return {str(k): sanitize_json(v) for k, v in value.items()}
1101
+ if isinstance(value, (list, tuple, set)):
1102
+ return [sanitize_json(v) for v in value]
1103
+ if hasattr(value, "to_dict"):
1104
+ return sanitize_json(value.to_dict())
1105
+ return str(value)
1106
+
1107
+
1108
+ @dash_app.callback(
1109
+ Output("feature-modal", "opened"),
1110
+ Output("feature-modal", "title"),
1111
+ Output("feature-modal-content", "children"),
1112
+ Input({"type": "feature-link", "index": ALL}, "n_clicks"),
1113
+ State("dataset-select", "value"),
1114
+ State("view-mode", "value"),
1115
+ State("filter-f1", "value"),
1116
+ State("filter-feats", "value"),
1117
+ State("filter-del-rate", "value"),
1118
+ State("filter-complexity", "value"),
1119
+ State("filter-algos", "value"),
1120
+ prevent_initial_call=True,
1121
+ )
1122
+ def open_feature_modal(n_clicks_list, dataset, view_mode, f1_value, feats_value, del_range, complexity, selected_algos):
1123
+ try:
1124
+ if not n_clicks_list:
1125
+ return False, "", []
1126
+ # find which index triggered
1127
+ trig = None
1128
+ if callback_context and callback_context.triggered:
1129
+ prop_id = callback_context.triggered[0]["prop_id"]
1130
+ # prop_id example: {"type":"feature-link","index":3}.n_clicks
1131
+ if prop_id and prop_id != ".":
1132
+ left = prop_id.split(".")[0]
1133
+ trig = json.loads(left).get("index")
1134
+ if trig is None:
1135
+ # fallback: first clicked
1136
+ for i, v in enumerate(n_clicks_list):
1137
+ if v:
1138
+ trig = i
1139
+ break
1140
+ selected = dataset or "Authorship"
1141
+ meta = DATASET_METADATA.get(selected, {})
1142
+ results = get_results_for_dataset(selected)
1143
+ filtered = apply_filters(results, meta, f1_value or 0, feats_value, del_range, complexity, selected_algos or [])
1144
+ if trig is None or trig < 0 or trig >= len(filtered):
1145
+ return False, "", []
1146
+ row = filtered[trig]
1147
+ algo = row.get("algorithm") or "Unknown"
1148
+ feats = row.get("selected_features")
1149
+ # normalize features to a flat list
1150
+ feature_list = []
1151
+ if isinstance(feats, list):
1152
+ for item in feats:
1153
+ if isinstance(item, list):
1154
+ feature_list.extend(item)
1155
+ else:
1156
+ feature_list.append(item)
1157
+ title = f"{algo} - Top {len(feature_list) if feature_list else get_feature_count(row)} Features Details"
1158
+ # tags
1159
+ tags = []
1160
+ for ft in feature_list:
1161
+ tags.append(html.Span(str(ft), className="tag"))
1162
+ tags_wrap = html.Div(tags, style={"display": "flex", "flexWrap": "wrap", "gap": "6px"})
1163
+ # metrics table
1164
+ metrics = row.get("metrics") or {}
1165
+ def valfmt(x):
1166
+ try:
1167
+ return f"{float(x):.4f}"
1168
+ except Exception:
1169
+ return "N/A"
1170
+ metrics_rows = []
1171
+ for clf in ["nb", "svm", "rf"]:
1172
+ m = metrics.get(clf) or {}
1173
+ metrics_rows.append(
1174
+ html.Tr([
1175
+ html.Td(clf.upper()),
1176
+ html.Td(valfmt(m.get("f1"))),
1177
+ html.Td(valfmt(m.get("auc"))),
1178
+ ])
1179
+ )
1180
+ metrics_table = html.Table(
1181
+ [
1182
+ html.Thead(html.Tr([html.Th("Classifier"), html.Th("F1"), html.Th("AUC")])),
1183
+ html.Tbody(metrics_rows),
1184
+ ],
1185
+ style={"width": "100%", "borderCollapse": "collapse"},
1186
+ className="custom-table",
1187
+ )
1188
+ time_sec = row.get("time")
1189
+ meta_info = html.Div([
1190
+ html.Div(["Runtime: ", html.Strong(valfmt(time_sec))]),
1191
+ html.Div(["Num Features: ", html.Strong(str(get_feature_count(row)))]),
1192
+ ], style={"display": "flex", "gap": "16px", "marginTop": "8px"})
1193
+ content = [
1194
+ html.H4("Selected Features"),
1195
+ tags_wrap,
1196
+ html.H4("Classifier Metrics", style={"marginTop": "12px"}),
1197
+ metrics_table,
1198
+ meta_info,
1199
+ ]
1200
+ return True, title, content
1201
+ except Exception as e:
1202
+ print("modal error:", e)
1203
+ return False, "", [html.Div(f"Error: {e}")]
1204
+
1205
+ @server.route("/global")
1206
+ def global_view():
1207
+ return render_template("global.html")
1208
+
1209
+
1210
+ @server.route("/submit")
1211
+ def submit_view():
1212
+ return render_template("submit.html")
1213
+
1214
+
1215
+ @server.route("/api/results")
1216
+ def get_results_api():
1217
+ try:
1218
+ dataset = request.args.get("dataset") or "Authorship"
1219
+ leaderboard = get_results_for_dataset(dataset)
1220
+ return jsonify(sanitize_json(leaderboard))
1221
+ except Exception as e:
1222
+ print(e)
1223
+ return jsonify({"error": str(e)})
1224
+
1225
+
1226
+ @server.route("/api/datasets")
1227
+ def api_datasets():
1228
+ try:
1229
+ datasets = []
1230
+ for name, meta in DATASET_METADATA.items():
1231
+ datasets.append({
1232
+ "name": name,
1233
+ "last_updated": meta.get("last_updated"),
1234
+ "num_samples": meta.get("num_samples") if meta.get("num_samples") is not None else "Unavailable",
1235
+ "total_features": meta.get("total_features") if meta.get("total_features") is not None else "Unavailable",
1236
+ })
1237
+ return jsonify(sanitize_json(datasets))
1238
+ except Exception as e:
1239
+ print(e)
1240
+ return jsonify({"error": str(e)})
1241
+
1242
+
1243
+ @server.route("/api/global_stats")
1244
+ def api_global_stats():
1245
+ try:
1246
+ algo_totals = {}
1247
+ algo_counts = {}
1248
+ for dataset in DATASET_METADATA.keys():
1249
+ results = get_results_for_dataset(dataset) or []
1250
+ for row in results:
1251
+ algo = row.get("algorithm") or "Unknown"
1252
+ mean_f1 = row.get("mean_f1")
1253
+ mean_auc = row.get("mean_auc")
1254
+ if mean_f1 is None and mean_auc is None:
1255
+ continue
1256
+ totals = algo_totals.get(algo, {"f1": 0.0, "auc": 0.0})
1257
+ counts = algo_counts.get(algo, {"f1": 0, "auc": 0})
1258
+ if mean_f1 is not None:
1259
+ totals["f1"] += float(mean_f1)
1260
+ counts["f1"] += 1
1261
+ if mean_auc is not None:
1262
+ totals["auc"] += float(mean_auc)
1263
+ counts["auc"] += 1
1264
+ algo_totals[algo] = totals
1265
+ algo_counts[algo] = counts
1266
+ global_stats = []
1267
+ for algo, totals in algo_totals.items():
1268
+ counts = algo_counts.get(algo, {"f1": 0, "auc": 0})
1269
+ mean_f1_global = totals["f1"] / counts["f1"] if counts["f1"] else None
1270
+ mean_auc_global = totals["auc"] / counts["auc"] if counts["auc"] else None
1271
+ global_stats.append({
1272
+ "algorithm": algo,
1273
+ "mean_f1_global": mean_f1_global,
1274
+ "mean_auc_global": mean_auc_global,
1275
+ })
1276
+ return jsonify(sanitize_json(global_stats))
1277
+ except Exception as e:
1278
+ print(e)
1279
+ return jsonify({"error": str(e)})
1280
+
1281
+
1282
+ @server.route("/api/algos")
1283
+ def api_algorithms():
1284
+ return jsonify(DISPLAY_COMPLEXITY)
1285
+
1286
+
1287
+ @server.route("/pdfs/<path:filename>")
1288
+ def serve_pdf(filename):
1289
+ return send_from_directory(PDF_DIR, filename)
1290
+
1291
+
1292
+ if __name__ == "__main__":
1293
+ port = int(os.environ.get("PORT", 7865))
1294
+ print(f"Loaded {len(DATASET_METADATA)} datasets from {RESULT_DIR}")
1295
+ app.run(host="0.0.0.0", port=port, debug=False)