Spaces:
Sleeping
Sleeping
File size: 15,517 Bytes
fe02ff1 |
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 |
// ---- VRAM categories ----
const CATEGORIES = [
{ key: "6gb", label: "6GB VRAM" },
{ key: "12gb", label: "12GB VRAM" },
{ key: "16gb", label: "16GB VRAM" },
{ key: "24gb", label: "24GB VRAM" },
{ key: "48gb", label: "48GB VRAM" },
{ key: "72gb", label: "72GB VRAM" },
{ key: "96gb", label: "96GB VRAM" }
];
// ---- State management ----
const state = {
activeCategory: CATEGORIES[0].key,
sortOption: 'votes', // 'votes', 'newest', 'oldest'
data: {},
lastVotedIds: {},
refreshInterval: null,
pollInterval: 10000, // 10 seconds
};
// ---- helpers ----
async function api(url, data) {
const opts = data ? {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
} : {};
const res = await fetch(url, opts);
const json = await res.json();
if (!res.ok) throw new Error(json.error || 'Server error');
return json;
}
function calculatePercentage(votes, totalVotes) {
if (totalVotes === 0) return 0;
return Math.round((votes / totalVotes) * 100);
}
function getTotalVotes(entries) {
return entries.reduce((sum, entry) => sum + entry.votes, 0);
}
function formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
} else if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num.toString();
}
function sortEntries(entries, sortOption) {
const entriesCopy = [...entries];
if (sortOption === 'votes') {
return entriesCopy.sort((a, b) => {
// First sort by votes (descending)
const votesDiff = b.votes - a.votes;
if (votesDiff !== 0) return votesDiff;
// If votes are equal, sort by id (newest first)
return parseInt(b.id) - parseInt(a.id);
});
} else if (sortOption === 'newest') {
return entriesCopy.sort((a, b) => parseInt(b.id) - parseInt(a.id));
} else if (sortOption === 'oldest') {
return entriesCopy.sort((a, b) => parseInt(a.id) - parseInt(b.id));
}
// Default to votes sorting
return entriesCopy.sort((a, b) => b.votes - a.votes);
}
// ---- rendering ----
function createCategoryTabs() {
const tabsContainer = document.getElementById('category-tabs');
tabsContainer.innerHTML = '';
CATEGORIES.forEach(category => {
const tab = document.createElement('div');
tab.className = `tab ${category.key === state.activeCategory ? 'active' : ''}`;
tab.setAttribute('data-category', category.key);
tab.textContent = category.label;
tabsContainer.appendChild(tab);
});
}
function createLeaderboardSection(category) {
const section = document.createElement('section');
section.className = `leaderboard-section ${category.key === state.activeCategory ? 'active' : ''}`;
section.id = `section-${category.key}`;
section.innerHTML = `
<div class="section-header">
<h2 class="section-title">${category.label} Leaderboard</h2>
<div class="sort-options">
<button class="sort-option ${state.sortOption === 'votes' ? 'active' : ''}" data-sort="votes">Most Votes</button>
<button class="sort-option ${state.sortOption === 'newest' ? 'active' : ''}" data-sort="newest">Newest</button>
<button class="sort-option ${state.sortOption === 'oldest' ? 'active' : ''}" data-sort="oldest">Oldest</button>
</div>
</div>
<div class="poll-items" id="poll-items-${category.key}">
<!-- Poll items will be rendered here -->
</div>
<div class="add-form-container">
<form class="add-form" data-category="${category.key}">
<div class="input-container">
<input class="add-input" type="text" placeholder="Add a new entry..." required autocomplete="off" />
<div class="validation-indicator"></div>
<div class="dropdown-container">
<div class="dropdown-loading hidden">
<div class="spinner"></div>
<span>Loading results...</span>
</div>
<ul class="dropdown-results hidden"></ul>
</div>
</div>
<button type="submit" class="add-btn" disabled>Add & Vote</button>
<span class="error add-error"></span>
</form>
</div>
`;
return section;
}
function renderPollItems(category) {
const container = document.getElementById(`poll-items-${category}`);
if (!container) return;
container.innerHTML = '';
const entries = state.data[category] || [];
if (entries.length === 0) {
container.innerHTML = '<p class="no-entries">No entries yet. Be the first to add one!</p>';
return;
}
const sortedEntries = sortEntries(entries, state.sortOption);
const totalVotes = getTotalVotes(sortedEntries);
sortedEntries.forEach((entry, index) => {
const percentage = calculatePercentage(entry.votes, totalVotes);
const isVoted = state.lastVotedIds[category] === entry.id;
const rankClass = index < 3 ? `rank-${index + 1}` : '';
const pollItem = document.createElement('div');
pollItem.className = `poll-item ${isVoted ? 'voted' : ''}`;
pollItem.setAttribute('data-id', entry.id);
if (state.lastVotedIds[category] === entry.id) {
pollItem.classList.add('highlight');
// Remove highlight class after animation completes
setTimeout(() => {
pollItem.classList.remove('highlight');
}, 1000);
}
pollItem.innerHTML = `
<div class="poll-item-header">
<div class="poll-item-name">
${rankClass ? `<span class="rank ${rankClass}">${index + 1}</span>` : `<span class="rank">${index + 1}</span>`}
${entry.name}
</div>
<div class="poll-item-votes">${formatNumber(entry.votes)} votes</div>
</div>
<div class="progress-container">
<div class="progress-bar" style="width: ${percentage}%"></div>
</div>
<div class="poll-item-footer">
<span class="vote-percentage">${percentage}%</span>
<button class="vote-btn ${isVoted ? 'voted' : ''}"
data-id="${entry.id}"
data-category="${category}"
${isVoted ? 'disabled' : ''}>
${isVoted ? 'Voted' : 'Vote'}
</button>
</div>
`;
container.appendChild(pollItem);
});
}
async function refreshData(category, highlightChanges = false) {
try {
const entries = await api(`/api/entries?category=${category}`);
// Store previous data for comparison if highlighting changes
const prevEntries = state.data[category] || [];
// Update state
state.data[category] = entries;
// Render the updated data
renderPollItems(category);
// Highlight changes if needed
if (highlightChanges && prevEntries.length > 0) {
entries.forEach(entry => {
const prevEntry = prevEntries.find(e => e.id === entry.id);
if (prevEntry && prevEntry.votes !== entry.votes) {
const pollItem = document.querySelector(`.poll-item[data-id="${entry.id}"]`);
if (pollItem) {
pollItem.classList.add('highlight');
setTimeout(() => {
pollItem.classList.remove('highlight');
}, 1000);
}
}
});
}
} catch (err) {
console.error(`Error refreshing ${category}:`, err);
}
}
function setupPolling() {
// Clear any existing interval
if (state.refreshInterval) {
clearInterval(state.refreshInterval);
}
// Set up new polling interval
state.refreshInterval = setInterval(() => {
refreshData(state.activeCategory, true);
}, state.pollInterval);
}
// ---- event handlers ----
function handleCategoryChange(category) {
// Update active category
state.activeCategory = category;
// Update UI
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.toggle('active', tab.getAttribute('data-category') === category);
});
document.querySelectorAll('.leaderboard-section').forEach(section => {
section.classList.toggle('active', section.id === `section-${category}`);
});
// Refresh data for the new category
refreshData(category);
}
function handleSortChange(sortOption) {
// Update sort option
state.sortOption = sortOption;
// Update UI
document.querySelectorAll('.sort-option').forEach(btn => {
btn.classList.remove('active');
if (btn.getAttribute('data-sort') === sortOption) {
btn.classList.add('active');
}
});
// Re-render with new sort
refreshData(state.activeCategory, false).then(() => {
renderPollItems(state.activeCategory);
});
}
// Hugging Face API validation
let debounceTimer;
let selectedModel = null;
async function validateWithHuggingFace(query) {
if (!query || query.length < 2) return [];
try {
// Use our server-side proxy endpoint to avoid CORS issues
const response = await fetch(`/api/huggingface/models?query=${encodeURIComponent(query)}`);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to fetch from Hugging Face API');
}
return await response.json();
} catch (error) {
console.error('Hugging Face API error:', error);
return [];
}
}
function setupModelValidation(form) {
const input = form.querySelector('.add-input');
const dropdownContainer = form.querySelector('.dropdown-container');
const dropdownResults = form.querySelector('.dropdown-results');
const dropdownLoading = form.querySelector('.dropdown-loading');
const submitBtn = form.querySelector('.add-btn');
const validationIndicator = form.querySelector('.validation-indicator');
input.addEventListener('input', function() {
const query = this.value.trim();
selectedModel = null;
// Reset validation state
validationIndicator.className = 'validation-indicator';
submitBtn.disabled = true;
// Clear previous results
dropdownResults.innerHTML = '';
dropdownResults.classList.add('hidden');
if (query.length < 2) return;
// Show loading indicator
dropdownLoading.classList.remove('hidden');
// Debounce API calls
clearTimeout(debounceTimer);
debounceTimer = setTimeout(async () => {
try {
const results = await validateWithHuggingFace(query);
// Hide loading indicator
dropdownLoading.classList.add('hidden');
if (results.length === 0) {
dropdownResults.innerHTML = '<li class="no-results">No matching models found</li>';
dropdownResults.classList.remove('hidden');
return;
}
// Populate dropdown with results
results.forEach(model => {
const li = document.createElement('li');
li.className = 'dropdown-item';
// Create a more informative display with model name and author
const displayName = model.modelId || model.id || model.name;
const authorInfo = model.author && model.author !== 'Unknown' ? ` by ${model.author}` : '';
li.innerHTML = `
<div class="dropdown-item-name">${displayName}</div>
${authorInfo ? `<div class="dropdown-item-author">${authorInfo}</div>` : ''}
`;
li.addEventListener('click', () => {
input.value = displayName;
selectedModel = model;
dropdownResults.classList.add('hidden');
// Show validation success
validationIndicator.className = 'validation-indicator valid';
submitBtn.disabled = false;
});
dropdownResults.appendChild(li);
});
dropdownResults.classList.remove('hidden');
} catch (error) {
console.error('Validation error:', error);
dropdownLoading.classList.add('hidden');
// Show validation error
validationIndicator.className = 'validation-indicator invalid';
}
}, 300);
});
// Hide dropdown when clicking outside
document.addEventListener('click', (e) => {
if (!dropdownContainer.contains(e.target)) {
dropdownResults.classList.add('hidden');
}
});
// Prevent form submission when pressing Enter in the input field
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !selectedModel) {
e.preventDefault();
}
});
}
async function handleAddEntry(form) {
const category = form.getAttribute('data-category');
const input = form.querySelector('.add-input');
const errorSpan = form.querySelector('.error');
const name = input.value.trim();
errorSpan.textContent = '';
if (!name) {
errorSpan.textContent = 'Please enter a name';
return;
}
if (!selectedModel) {
errorSpan.textContent = 'Please select a validated model from the dropdown';
return;
}
try {
const entry = await api('/api/add', { name, category });
input.value = '';
selectedModel = null;
// Reset validation state
form.querySelector('.validation-indicator').className = 'validation-indicator';
form.querySelector('.add-btn').disabled = true;
// Update state
state.lastVotedIds[category] = entry.id;
// Refresh data
await refreshData(category);
} catch (err) {
errorSpan.textContent = err.message;
}
}
async function handleVote(btn) {
const id = btn.getAttribute('data-id');
const category = btn.getAttribute('data-category');
try {
await api('/api/vote', { id, category });
// Update state
state.lastVotedIds[category] = id;
// Refresh data
await refreshData(category);
} catch (err) {
alert(err.message);
}
}
// ---- main ----
window.addEventListener('DOMContentLoaded', () => {
const leaderboardsDiv = document.getElementById('leaderboards');
leaderboardsDiv.innerHTML = '';
// Create category tabs
createCategoryTabs();
// Render all leaderboard sections
CATEGORIES.forEach(cat => {
const section = createLeaderboardSection(cat);
leaderboardsDiv.appendChild(section);
});
// Set up model validation for all forms
document.querySelectorAll('.add-form').forEach(form => {
setupModelValidation(form);
});
// Initial data load
CATEGORIES.forEach(cat => {
refreshData(cat.key);
});
// Set up polling for real-time updates
setupPolling();
// Tab click handler
document.getElementById('category-tabs').addEventListener('click', e => {
if (e.target.classList.contains('tab')) {
const category = e.target.getAttribute('data-category');
handleCategoryChange(category);
}
});
// Sort option click handler
leaderboardsDiv.addEventListener('click', e => {
if (e.target.classList.contains('sort-option')) {
const sortOption = e.target.getAttribute('data-sort');
if (sortOption && sortOption !== state.sortOption) {
handleSortChange(sortOption);
}
}
});
// Add entry form handler
leaderboardsDiv.addEventListener('submit', async e => {
if (e.target.classList.contains('add-form')) {
e.preventDefault();
await handleAddEntry(e.target);
}
});
// Vote button handler
leaderboardsDiv.addEventListener('click', async e => {
if (e.target.classList.contains('vote-btn') && !e.target.disabled) {
await handleVote(e.target);
}
});
});
// Clean up polling on page unload
window.addEventListener('beforeunload', () => {
if (state.refreshInterval) {
clearInterval(state.refreshInterval);
}
}); |