+#!/usr/bin/env perl
+use strict;
+use warnings;
+use CGI qw(:standard);
+use DBI;
+use POSIX qw(strftime);
+
+sub format_time {
+ my $seconds = shift;
+
+ if ($seconds < 1e-3) { # Less than 1 millisecond
+ return sprintf("%.2f μs", $seconds * 1e6);
+ }
+ else { # 1 millisecond or more
+ return sprintf("%.2f ms", $seconds * 1e3);
+ }
+}
+
+print header(-type => 'text/html', -charset => 'utf-8');
+print start_html(-title => "CUDA Kernel Competition Leaderboard",
+ -style => {-src => 'index.css'});
+
+my $db_file = "/www/kernelbot/leaderboard.db";
+my $dbh = DBI->connect("dbi:SQLite:dbname=$db_file", "", "", {
+ PrintError => 0,
+ RaiseError => 0,
+ AutoCommit => 1
+});
+
+if (!$dbh) {
+ print h1("CUDA Kernel Competition Leaderboard");
+ print p("Database not available or empty. Please check back later.");
+ print p("Error: $DBI::errstr");
+ print end_html;
+ exit;
+}
+
+# Get export timestamp
+my $timestamp_query = "SELECT value FROM metadata WHERE key = 'export_time'";
+my $timestamp = $dbh->selectrow_array($timestamp_query) || "Unknown";
+
+# Get challenges
+my $challenges_query = "SELECT id, name, desc FROM challenges ORDER BY name";
+my $challenges_sth = $dbh->prepare($challenges_query);
+$challenges_sth->execute();
+
+print h1("CUDA Kernel Competition Leaderboard");
+
+while (my ($challenge_id, $challenge_name, $challenge_desc) = $challenges_sth->fetchrow_array()) {
+ print h2("Challenge: $challenge_name");
+ print p($challenge_desc) if $challenge_desc;
+
+ my $submissions_query = qq{
+ SELECT
+ user_id, username, kernel_name, kernel_type, timing
+ FROM best_submissions
+ WHERE challenge_id = ?
+ ORDER BY timing ASC
+ };
+
+ my $submissions_sth = $dbh->prepare($submissions_query);
+ $submissions_sth->execute($challenge_id);
+
+ print "<table border='1' cellspacing='0' cellpadding='5'>";
+ print "<tr><th>Rank</th><th>User</th><th>Kernel</th><th>Type</th><th>Time</th></tr>";
+
+ my $rank = 1;
+ while (my ($user_id, $username, $kernel, $type, $time) = $submissions_sth->fetchrow_array()) {
+ my $medal = "";
+ if ($rank == 1) {
+ $medal = "🥇 ";
+ } elsif ($rank == 2) {
+ $medal = "🥈 ";
+ } elsif ($rank == 3) {
+ $medal = "🥉 ";
+ }
+
+ $username ||= "User-$user_id"; # Default if username is NULL
+
+ my $style = "";
+ if ($rank <= 3) {
+ $style = "style='font-weight: bold;'";
+ }
+
+ print "<tr $style>";
+ print "<td>$medal$rank</td>";
+ print "<td>$username</td>";
+ print "<td>$kernel</td>";
+ print "<td>$type</td>";
+ print "<td>", format_time($time), "</td>";
+ print "</tr>";
+
+ $rank++;
+ }
+
+ if ($rank == 1) {
+ print "<tr><td colspan='5'>No submissions yet</td></tr>";
+ }
+
+ print "</table>";
+ print "<br>";
+
+ $submissions_sth->finish();
+}
+
+print "<hr>";
+print "<p>Last updated: $timestamp</p>";
+
+print end_html;
+$challenges_sth->finish();
+$dbh->disconnect();