File size: 14,747 Bytes
953a39e
 
 
 
 
 
81702ec
953a39e
 
 
 
81702ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953a39e
81702ec
 
 
953a39e
81702ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54729e7
 
81702ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54729e7
81702ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953a39e
 
 
 
 
 
 
 
 
fd164b2
 
 
 
 
 
 
 
 
 
 
953a39e
fd164b2
 
953a39e
 
 
 
 
 
fd164b2
 
953a39e
 
 
 
 
 
fd164b2
 
 
 
953a39e
 
 
 
54729e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81702ec
953a39e
 
 
7154898
 
 
 
fd164b2
 
 
81702ec
7154898
 
 
fd164b2
953a39e
 
 
81702ec
7154898
 
 
953a39e
 
 
 
81702ec
7154898
 
 
953a39e
 
 
 
81702ec
7154898
 
 
 
 
 
 
81702ec
7154898
 
 
953a39e
 
 
 
81702ec
7154898
 
 
953a39e
54729e7
 
 
 
 
 
 
 
953a39e
 
 
81702ec
7154898
 
 
953a39e
 
 
 
81702ec
7154898
 
 
953a39e
 
 
 
81702ec
7154898
 
 
953a39e
fd164b2
 
 
81702ec
7154898
 
 
fd164b2
953a39e
 
 
7154898
81702ec
953a39e
 
7154898
 
81702ec
953a39e
 
 
7154898
 
 
 
 
 
 
 
 
 
 
 
fd164b2
7154898
fd164b2
 
7154898
fd164b2
 
 
 
 
7154898
 
 
 
 
 
 
fd164b2
7154898
fd164b2
7154898
 
 
 
 
 
fd164b2
7154898
fd164b2
953a39e
 
 
 
81702ec
 
953a39e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81702ec
953a39e
 
 
81702ec
 
 
 
 
 
 
 
953a39e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import React, {
  createContext,
  useContext,
  useState,
  useCallback,
  useMemo,
  useEffect,
} from "react";

const LeaderboardContext = createContext();

// Helper pour mettre à jour l'URL
const updateURL = (params) => {
  const url = new URL(window.location);
  Object.entries(params).forEach(([key, value]) => {
    if (value) {
      url.searchParams.set(key, value);
    } else {
      url.searchParams.delete(key);
    }
  });
  window.history.pushState({}, "", url);
};

// Helper pour lire les paramètres de l'URL
const getURLParams = () => {
  const params = new URLSearchParams(window.location.search);
  return {
    category: params.get("category"),
    search: params.get("search"),
    arena: params.get("arena") === "true",
    language: params.get("language"),
  };
};

export const LeaderboardProvider = ({ children }) => {
  // Lire les paramètres initiaux depuis l'URL
  const initialParams = getURLParams();

  const [leaderboards, setLeaderboards] = useState([]);
  const [searchQuery, setSearchQuery] = useState(initialParams.search || "");
  const [arenaOnly, setArenaOnly] = useState(initialParams.arena);
  const [selectedCategory, setSelectedCategory] = useState(
    initialParams.category
  );
  const [selectedLanguage, setSelectedLanguage] = useState(
    initialParams.language
  );
  const [expandedSections, setExpandedSections] = useState(new Set());

  // Mettre à jour l'URL quand les filtres changent
  useEffect(() => {
    updateURL({
      category: selectedCategory,
      search: searchQuery,
      arena: arenaOnly ? "true" : null,
      language: selectedLanguage,
    });
  }, [selectedCategory, searchQuery, arenaOnly, selectedLanguage]);

  // Écouter les changements d'URL (navigation back/forward)
  useEffect(() => {
    const handleURLChange = () => {
      const params = getURLParams();
      setSearchQuery(params.search || "");
      setArenaOnly(params.arena);
      setSelectedCategory(params.category);
      setSelectedLanguage(params.language);
    };

    window.addEventListener("popstate", handleURLChange);
    return () => window.removeEventListener("popstate", handleURLChange);
  }, []);

  // Wrapper pour setSelectedCategory qui gère aussi l'expansion des sections
  const handleCategorySelection = useCallback((categoryId) => {
    // On réinitialise toujours la langue sélectionnée
    setSelectedLanguage(null);

    setSelectedCategory((prev) => {
      if (prev === categoryId) {
        // Si on désélectionne, on replie toutes les sections
        setExpandedSections(new Set());
        return null;
      }
      // Si on sélectionne une nouvelle catégorie, on la déploie
      setExpandedSections(new Set([categoryId]));
      return categoryId;
    });
  }, []);

  // Wrapper pour la sélection de langue
  const handleLanguageSelection = useCallback((language) => {
    setSelectedLanguage((prev) => (prev === language ? null : language));
  }, []);

  // Filter leaderboards based on search query and arena toggle, ignoring category selection
  const filterLeaderboardsForCount = useCallback(
    (boards) => {
      if (!boards) return [];

      let filtered = [...boards];

      // Filter by search query (text only)
      if (searchQuery) {
        const query = searchQuery.toLowerCase();
        filtered = filtered.filter((board) =>
          board.card_data?.title?.toLowerCase().includes(query)
        );
      }

      // Filter arena only
      if (arenaOnly) {
        filtered = filtered.filter((board) =>
          board.tags?.includes("judge:humans")
        );
      }

      return filtered;
    },
    [searchQuery, arenaOnly]
  );

  // Filter leaderboards based on all criteria including category and language selection
  const filterLeaderboards = useCallback(
    (boards) => {
      if (!boards) return [];

      let filtered = filterLeaderboardsForCount(boards);

      // Filter by selected language if any
      if (selectedLanguage) {
        filtered = filtered.filter((board) =>
          board.tags?.some(
            (tag) =>
              tag.toLowerCase() === `language:${selectedLanguage.toLowerCase()}`
          )
        );
      }

      // Filter by selected category if any
      if (selectedCategory) {
        filtered = filtered.filter((board) => {
          const { tags = [] } = board;
          switch (selectedCategory) {
            case "agentic":
              return tags.includes("modality:agent");
            case "code":
              return tags.includes("eval:code");
            case "math":
              return tags.includes("eval:math");
            case "language":
              return tags.some((tag) => tag.startsWith("language:"));
            case "vision":
              return tags.some(
                (tag) => tag === "modality:video" || tag === "modality:image"
              );
            case "threeD":
              return tags.includes("modality:3d");
            case "audio":
              return tags.includes("modality:audio");
            case "financial":
              return tags.includes("domain:financial");
            case "medical":
              return tags.includes("domain:medical");
            case "legal":
              return tags.includes("domain:legal");
            case "safety":
              return tags.includes("eval:safety");
            case "uncategorized":
              return !tags.some(
                (tag) =>
                  [
                    "modality:agent",
                    "eval:code",
                    "eval:math",
                    "modality:video",
                    "modality:image",
                    "modality:3d",
                    "modality:audio",
                    "domain:financial",
                    "domain:medical",
                    "domain:legal",
                    "eval:safety",
                  ].includes(tag) || tag.startsWith("language:")
              );
            default:
              return true;
          }
        });
      }

      return filtered;
    },
    [filterLeaderboardsForCount, selectedCategory, selectedLanguage]
  );

  // Fonction pour obtenir les leaderboards bruts d'une section
  const getSectionLeaderboards = useCallback((boards) => {
    if (!boards) return [];
    return [...boards];
  }, []);

  // Fonction pour compter les leaderboards par langue
  const getLanguageStats = useCallback((boards) => {
    const stats = new Map();

    boards.forEach((board) => {
      board.tags?.forEach((tag) => {
        if (tag.startsWith("language:")) {
          const language = tag.split(":")[1];
          const capitalizedLang =
            language.charAt(0).toUpperCase() + language.slice(1);
          const count = stats.get(capitalizedLang) || 0;
          stats.set(capitalizedLang, count + 1);
        }
      });
    });

    return stats;
  }, []);

  // Calculate total number of unique leaderboards (excluding duplicates)
  const totalLeaderboards = useMemo(() => {
    const uniqueIds = new Set(leaderboards.map((board) => board.id));
    return uniqueIds.size;
  }, [leaderboards]);

  // Filter functions for categories
  const filterByTag = useCallback((tag, boards) => {
    const searchTag = tag.toLowerCase();
    console.log("Filtering by tag:", {
      searchTag,
      boards: boards?.map((board) => ({
        id: board.id,
        tags: board.tags,
        matches: {
          tags: board.tags?.some((t) => t.toLowerCase() === searchTag),
        },
      })),
    });
    return (
      boards?.filter((board) =>
        board.tags?.some((t) => t.toLowerCase() === searchTag)
      ) || []
    );
  }, []);

  const filterByLanguage = useCallback((boards) => {
    return (
      boards?.filter((board) =>
        board.tags?.some((tag) => tag.startsWith("language:"))
      ) || []
    );
  }, []);

  const filterByVision = useCallback((boards) => {
    return (
      boards?.filter((board) =>
        board.tags?.some(
          (tag) => tag === "modality:video" || tag === "modality:image"
        )
      ) || []
    );
  }, []);

  // Helper function to get the category group of a section
  const getSectionGroup = (id) => {
    const groups = {
      agentic: ["agentic"],
      capabilities: ["code", "math"],
      languages: ["language"],
      modalities: ["vision", "audio"],
      threeD: ["threeD"],
      domains: ["financial", "medical", "legal"],
      evaluation: ["safety"],
      misc: ["uncategorized"],
    };

    for (const [group, ids] of Object.entries(groups)) {
      if (ids.includes(id)) {
        return group;
      }
    }
    return "misc";
  };

  // Define sections with raw data
  const allSections = useMemo(() => {
    if (!leaderboards) return [];

    // Garder une trace des leaderboards déjà catégorisés
    const categorizedIds = new Set();

    const sections = [
      {
        id: "agentic",
        title: "Agentic",
        data: filterByTag("modality:agent", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "code",
        title: "Code",
        data: filterByTag("eval:code", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "math",
        title: "Math",
        data: filterByTag("eval:math", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "language",
        title: "Language Specific",
        data: filterByLanguage(leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "vision",
        title: "Vision",
        data: filterByVision(leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "audio",
        title: "Audio",
        data: filterByTag("modality:audio", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "threeD",
        title: "3D",
        data: filterByTag("modality:3d", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "financial",
        title: "Financial",
        data: filterByTag("domain:financial", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "medical",
        title: "Medical",
        data: filterByTag("domain:medical", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "legal",
        title: "Legal",
        data: filterByTag("domain:legal", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "safety",
        title: "Safety",
        data: filterByTag("eval:safety", leaderboards).map((board) => {
          categorizedIds.add(board.id);
          return board;
        }),
      },
      {
        id: "uncategorized",
        title: "Uncategorized",
        // Mettre dans uncategorized uniquement les leaderboards qui n'apparaissent nulle part ailleurs
        data: leaderboards.filter((board) => !categorizedIds.has(board.id)),
      },
    ];

    return sections;
  }, [leaderboards, filterByTag, filterByLanguage, filterByVision]);

  // Get sections with data
  const sections = useMemo(() => {
    console.log("Starting sections filtering...");
    console.log(
      "All sections before filtering:",
      allSections.map((s) => ({
        title: s.title,
        count: s.data.length,
        ids: s.data.map((b) => b.id),
      }))
    );

    // On garde une trace des titres déjà vus
    const seenTitles = new Set();
    const filteredSections = allSections.filter((section) => {
      console.log(`\nAnalyzing section ${section.title}:`, {
        data: section.data,
        count: section.data.length,
        uniqueIds: new Set(section.data.map((b) => b.id)).size,
        boards: section.data.map((board) => ({
          id: board.id,
          tags: board.tags,
        })),
      });

      // On garde la section si elle a des données et qu'on ne l'a pas déjà vue
      if (section.data.length > 0 && !seenTitles.has(section.title)) {
        seenTitles.add(section.title);
        return true;
      }
      return false;
    });

    console.log(
      "\nFinal sections after filtering:",
      filteredSections.map((s) => ({
        title: s.title,
        count: s.data.length,
        uniqueIds: new Set(s.data.map((b) => b.id)).size,
      }))
    );

    return filteredSections;
  }, [allSections]);

  // Get filtered count
  const filteredCount = useMemo(() => {
    return filterLeaderboardsForCount(leaderboards).length;
  }, [filterLeaderboardsForCount, leaderboards]);

  // Function to get highlighted parts of text
  const getHighlightedText = useCallback((text, searchTerm) => {
    if (!searchTerm || !text) return { text, shouldHighlight: false };

    const query = searchTerm.toLowerCase();
    const searchableTagPrefixes = [
      "domain:",
      "language:",
      "judge:",
      "test:",
      "modality:",
      "submission:",
    ];

    // Si c'est une recherche par tag, on ne highlight rien
    if (searchableTagPrefixes.some((prefix) => query.startsWith(prefix))) {
      return { text, shouldHighlight: false };
    }

    // Sinon on highlight les parties qui matchent
    const index = text.toLowerCase().indexOf(query);
    if (index === -1) return { text, shouldHighlight: false };

    return {
      text,
      shouldHighlight: true,
      highlightStart: index,
      highlightEnd: index + query.length,
    };
  }, []);

  const value = {
    leaderboards,
    setLeaderboards,
    searchQuery,
    setSearchQuery,
    arenaOnly,
    setArenaOnly,
    totalLeaderboards,
    filteredCount,
    filterLeaderboards,
    filterLeaderboardsForCount,
    sections,
    allSections,
    getHighlightedText,
    selectedCategory,
    setSelectedCategory: handleCategorySelection,
    selectedLanguage,
    setSelectedLanguage: handleLanguageSelection,
    expandedSections,
    setExpandedSections,
    getLanguageStats,
    getSectionLeaderboards,
  };

  return (
    <LeaderboardContext.Provider value={value}>
      {children}
    </LeaderboardContext.Provider>
  );
};

export const useLeaderboard = () => {
  const context = useContext(LeaderboardContext);
  if (!context) {
    throw new Error("useLeaderboard must be used within a LeaderboardProvider");
  }
  return context;
};