Spaces:
Running
Running
File size: 16,097 Bytes
833aed9 859c45e 833aed9 859c45e 833aed9 859c45e 833aed9 859c45e 833aed9 859c45e 833aed9 859c45e 833aed9 859c45e 833aed9 |
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 |
// LionGuard 2 Frontend JavaScript
// State management
const state = {
selectedModel: 'lionguard-2.1',
selectedModelGC: 'lionguard-2.1',
currentTextId: '',
chatHistories: {
no_moderation: [],
openai_moderation: [],
lionguard: []
}
};
// Utility functions
function showLoading(button) {
button.disabled = true;
button.classList.add('loading');
const originalText = button.textContent;
button.textContent = 'Loading...';
return originalText;
}
function hideLoading(button, originalText) {
button.disabled = false;
button.classList.remove('loading');
button.textContent = originalText;
}
function getScoreLevel(score) {
if (score < 0.4) {
return { className: 'good', icon: '<i class="bx bx-check-circle"></i>', title: 'Low risk' };
}
if (score < 0.7) {
return { className: 'warn', icon: '<i class="bx bx-error"></i>', title: 'Needs review' };
}
return { className: 'bad', icon: '<i class="bx bx-error-circle"></i>', title: 'High risk' };
}
function formatScore(score) {
const percentage = Math.round(score * 100);
const { className, icon, title } = getScoreLevel(score);
return `<span class="score-chip ${className}" title="${title}">${icon} ${percentage}%</span>`;
}
function renderCategoryMeter(score) {
const filledSegments = Math.min(10, Math.round(score * 10));
const { className } = getScoreLevel(score);
const segments = Array.from({ length: 10 }, (_, index) => {
const isFilled = index < filledSegments;
const filledClass = isFilled ? `filled ${className}` : '';
return `<span class="category-meter-segment ${filledClass}"></span>`;
}).join('');
return `<div class="category-meter" aria-label="${Math.round(score * 100)}%">${segments}</div>`;
}
// Tab switching
function initTabs() {
const tabs = document.querySelectorAll('.tab[data-tab]');
const tabContents = document.querySelectorAll('.tab-content');
const dropdownToggle = document.querySelector('.dropdown-toggle');
const demoTabs = ['detector', 'chat'];
const updateDropdownState = (targetTab) => {
if (!dropdownToggle) return;
if (demoTabs.includes(targetTab)) {
dropdownToggle.classList.add('active');
} else {
dropdownToggle.classList.remove('active');
}
};
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const targetTab = tab.dataset.tab;
// Update tabs
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
// Update content
tabContents.forEach(content => {
content.classList.remove('active');
if (content.id === `${targetTab}-content`) {
content.classList.add('active');
}
});
updateDropdownState(targetTab);
// Smooth scroll to top when switching tabs
window.scrollTo({ top: 0, behavior: 'smooth' });
});
});
const initialActiveTab = document.querySelector('.tab[data-tab].active');
if (initialActiveTab) {
updateDropdownState(initialActiveTab.dataset.tab);
}
}
function initNavDropdown() {
const dropdown = document.querySelector('.nav-dropdown');
if (!dropdown) return;
const toggle = dropdown.querySelector('.dropdown-toggle');
const dropdownTabs = dropdown.querySelectorAll('.dropdown-item[data-tab]');
const closeDropdown = () => {
dropdown.classList.remove('open');
toggle.setAttribute('aria-expanded', 'false');
};
const toggleDropdown = (event) => {
event.stopPropagation();
const isOpen = dropdown.classList.toggle('open');
toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
};
toggle.addEventListener('click', toggleDropdown);
dropdownTabs.forEach(tab => {
tab.addEventListener('click', () => {
closeDropdown();
});
});
document.addEventListener('click', (event) => {
if (!dropdown.contains(event.target)) {
closeDropdown();
}
});
}
// Model selection for Classifier
function initModelSelector() {
const select = document.getElementById('model-select');
if (!select) return;
select.value = state.selectedModel;
select.addEventListener('change', () => {
state.selectedModel = select.value;
});
}
// Model selection for Guardrail Comparison
function initModelSelectorGC() {
const select = document.getElementById('model-select-gc');
if (!select) return;
select.value = state.selectedModelGC;
select.addEventListener('change', () => {
state.selectedModelGC = select.value;
});
}
// Classifier: Analyze text
async function analyzeText() {
const textInput = document.getElementById('text-input');
const analyzeBtn = document.getElementById('analyze-btn');
const binaryResult = document.getElementById('binary-result');
const categoryResults = document.getElementById('category-results');
const feedbackSection = document.getElementById('feedback-section');
const feedbackMessage = document.getElementById('feedback-message');
const text = textInput.value.trim();
if (!text) {
alert('Please enter some text to analyze');
return;
}
const originalText = showLoading(analyzeBtn);
feedbackMessage.textContent = '';
feedbackMessage.className = 'feedback-message';
try {
const response = await fetch('/moderate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: text,
model: state.selectedModel
})
});
if (!response.ok) {
throw new Error('Failed to analyze text');
}
const data = await response.json();
// Display binary result
const verdictClass = data.binary_verdict;
const verdictText = verdictClass.charAt(0).toUpperCase() + verdictClass.slice(1);
const verdictIcons = {
'pass': '<i class="bx bx-check-shield"></i>',
'warn': '<i class="bx bx-shield-minus"></i>',
'fail': '<i class="bx bx-shield-x"></i>'
};
binaryResult.innerHTML = `
<div class="binary-card ${verdictClass}">
<div class="binary-icon">${verdictIcons[verdictClass]}</div>
<div class="binary-body">
<div class="binary-label">Overall</div>
<div class="binary-score-line">
<h2>${verdictText}</h2>
<span class="binary-percentage">${data.binary_percentage}/100</span>
</div>
</div>
</div>
`;
// Display category results
const categoryHTML = data.categories.map(cat => `
<div class="category-card">
<div class="category-label">${cat.emoji} ${cat.name}</div>
${renderCategoryMeter(cat.max_score)}
<div class="category-score">${formatScore(cat.max_score)}</div>
</div>
`).join('');
categoryResults.innerHTML = `
<div class="category-grid">
${categoryHTML}
</div>
`;
// Show feedback section
state.currentTextId = data.text_id;
feedbackSection.style.display = 'block';
} catch (error) {
console.error('Error:', error);
binaryResult.innerHTML = `
<div style="color: #E63946; padding: 20px; text-align: center;">
❌ Error analyzing text: ${error.message}
</div>
`;
} finally {
hideLoading(analyzeBtn, originalText);
}
}
// Classifier: Submit feedback
async function submitFeedback(agree) {
const feedbackMessage = document.getElementById('feedback-message');
if (!state.currentTextId) {
feedbackMessage.textContent = 'No analysis to provide feedback on';
feedbackMessage.className = 'feedback-message info';
return;
}
try {
const response = await fetch('/send_feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text_id: state.currentTextId,
agree: agree
})
});
if (!response.ok) {
throw new Error('Failed to submit feedback');
}
const data = await response.json();
feedbackMessage.textContent = data.message;
feedbackMessage.className = 'feedback-message success';
} catch (error) {
console.error('Error:', error);
feedbackMessage.textContent = 'Error submitting feedback';
feedbackMessage.className = 'feedback-message info';
}
}
// Guardrail Comparison: Render chat messages
function renderChatMessages(containerId, messages) {
const container = document.getElementById(containerId);
container.innerHTML = messages.map(msg => `
<div class="chat-message ${msg.role}">
${msg.content}
</div>
`).join('');
// Scroll to bottom
container.scrollTop = container.scrollHeight;
}
// Guardrail Comparison: Send message
async function sendMessage() {
const messageInput = document.getElementById('message-input');
const sendBtn = document.getElementById('send-btn');
const message = messageInput.value.trim();
if (!message) {
alert('Please enter a message');
return;
}
const originalText = showLoading(sendBtn);
try {
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: message,
model: state.selectedModelGC,
histories: state.chatHistories
})
});
if (!response.ok) {
throw new Error('Failed to send message');
}
const data = await response.json();
// Update state
state.chatHistories = data.histories;
// Render all chat panels
renderChatMessages('chat-no-mod', data.histories.no_moderation);
renderChatMessages('chat-openai', data.histories.openai_moderation);
renderChatMessages('chat-lionguard', data.histories.lionguard);
// Clear input
messageInput.value = '';
} catch (error) {
console.error('Error:', error);
alert('Error sending message: ' + error.message);
} finally {
hideLoading(sendBtn, originalText);
}
}
// Guardrail Comparison: Clear all chats
function clearAllChats() {
state.chatHistories = {
no_moderation: [],
openai_moderation: [],
lionguard: []
};
document.getElementById('chat-no-mod').innerHTML = '';
document.getElementById('chat-openai').innerHTML = '';
document.getElementById('chat-lionguard').innerHTML = '';
}
// Initialize event listeners
function initEventListeners() {
// Classifier tab
const analyzeBtn = document.getElementById('analyze-btn');
const textInput = document.getElementById('text-input');
const thumbsUpBtn = document.getElementById('thumbs-up');
const thumbsDownBtn = document.getElementById('thumbs-down');
analyzeBtn.addEventListener('click', analyzeText);
textInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && e.ctrlKey) {
analyzeText();
}
});
thumbsUpBtn.addEventListener('click', () => submitFeedback(true));
thumbsDownBtn.addEventListener('click', () => submitFeedback(false));
// Guardrail Comparison tab
const sendBtn = document.getElementById('send-btn');
const messageInput = document.getElementById('message-input');
const clearBtn = document.getElementById('clear-btn');
sendBtn.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
sendMessage();
}
});
clearBtn.addEventListener('click', clearAllChats);
}
// Dark mode toggle
function initThemeToggle() {
const themeToggle = document.getElementById('theme-toggle');
if (!themeToggle) return;
const themeIcon = themeToggle.querySelector('.theme-icon');
const updateIcon = (isDark) => {
themeToggle.setAttribute('aria-pressed', isDark ? 'true' : 'false');
if (themeIcon) {
// Toggle class for boxicons
themeIcon.className = isDark ? 'bx bx-moon theme-icon' : 'bx bx-sun theme-icon';
themeIcon.textContent = ''; // clear text content
}
};
const savedTheme = localStorage.getItem('theme') || 'light';
const shouldStartDark = savedTheme === 'dark';
if (shouldStartDark) {
document.body.classList.add('dark-mode');
}
updateIcon(shouldStartDark);
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
const isDark = document.body.classList.contains('dark-mode');
updateIcon(isDark);
localStorage.setItem('theme', isDark ? 'dark' : 'light');
});
}
// Code snippet tabs for Get Started
function initCodeTabs() {
const tabs = document.querySelectorAll('.code-tab');
const blocks = document.querySelectorAll('.code-block');
if (!tabs.length) return;
tabs.forEach(tab => {
tab.addEventListener('click', () => {
// Remove active class from all tabs
tabs.forEach(t => t.classList.remove('active'));
// Add active class to clicked tab
tab.classList.add('active');
// Hide all blocks
blocks.forEach(b => b.classList.remove('active'));
// Show target block
const targetId = `code-${tab.dataset.code}`;
const targetBlock = document.getElementById(targetId);
if (targetBlock) {
targetBlock.classList.add('active');
}
});
});
}
// Copy Code Functionality
function initCopyButton() {
const copyBtn = document.getElementById('copy-code-btn');
if (!copyBtn) return;
copyBtn.addEventListener('click', async () => {
// Find active code block
const activeBlock = document.querySelector('.code-block.active code');
if (!activeBlock) return;
const textToCopy = activeBlock.textContent;
try {
await navigator.clipboard.writeText(textToCopy);
// Provide feedback
const originalHtml = copyBtn.innerHTML;
copyBtn.innerHTML = `<i class='bx bx-check'></i> Copied!`;
copyBtn.classList.add('success');
setTimeout(() => {
copyBtn.innerHTML = originalHtml;
copyBtn.classList.remove('success');
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
copyBtn.innerHTML = `<i class='bx bx-x'></i> Failed`;
setTimeout(() => {
copyBtn.innerHTML = `<i class='bx bx-copy'></i> Copy`;
}, 2000);
}
});
}
// Initialize app
document.addEventListener('DOMContentLoaded', () => {
initTabs();
initNavDropdown();
initModelSelector();
initModelSelectorGC();
initEventListeners();
initThemeToggle();
initCodeTabs();
initCopyButton();
console.log('LionGuard 2 app initialized');
});
|