Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
635 lines (557 loc) · 23.1 KB
/
Copy pathindex.html
File metadata and controls
635 lines (557 loc) · 23.1 KB
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Interview Preparation</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
window.MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']],
processEscapes: true
},
svg: { fontCache: 'global' }
};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js" async></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400&family=Outfit:wght@500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="web_utils/style.css">
</head>
<body>
<!-- Top Bar -->
<div class="top-bar">
<nav class="breadcrumb" id="breadcrumb">
<span class="breadcrumb-item active">Home</span>
</nav>
<button class="settings-btn" id="settings-btn" title="Settings">⚙</button>
</div>
<!-- Settings Modal -->
<div id="settings-modal" class="modal-overlay" style="display:none;">
<div class="modal-content">
<div class="modal-header">
<h2>Settings</h2>
<button class="modal-close" id="modal-close">×</button>
</div>
<div class="modal-body">
<div class="settings-section">
<label for="model-input">LLM Model</label>
<input type="text" id="model-input" placeholder="nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free">
<p class="settings-hint">OpenRouter model ID for answer verification. Browse models at <a href="https://openrouter.ai/models" target="_blank">openrouter.ai/models</a>.</p>
</div>
<div class="settings-section">
<label for="api-key-input">OpenRouter API Key</label>
<input type="password" id="api-key-input" placeholder="sk-or-v1-...">
<p class="settings-hint">Stored locally in your browser. Get a free key at <a href="https://openrouter.ai/keys" target="_blank">openrouter.ai/keys</a>.</p>
</div>
<div class="settings-actions">
<button id="save-settings-btn">Save</button>
<button id="clear-settings-btn">Clear</button>
</div>
<p id="settings-status" class="key-status"></p>
</div>
</div>
</div>
<!-- HOME VIEW -->
<div id="home-view">
<h1>Interview Preparation</h1>
<p class="home-subtitle">Select a topic to start practicing</p>
<div class="cards-grid">
<div class="topic-card" data-subject="Transformers">
<div class="card-bg" style="background-image: url('images/transformers.jpg')"></div>
<div class="card-overlay"></div>
<div class="card-content">
<h2>Transformers</h2>
<p>Attention mechanisms, architectures, deployment & case studies</p>
<span class="card-count" id="count-Transformers"></span>
</div>
</div>
<div class="topic-card" data-subject="Diffusion">
<div class="card-bg" style="background-image: url('images/diffusion.jpg')"></div>
<div class="card-overlay"></div>
<div class="card-content">
<h2>Diffusion</h2>
<p>DDPM, DDIM, score matching & generative modeling</p>
<span class="card-count" id="count-Diffusion"></span>
</div>
</div>
<div class="topic-card" data-subject="ReinforcementLearning">
<div class="card-bg" style="background-image: url('images/reinforcement-learning.jpg')"></div>
<div class="card-overlay"></div>
<div class="card-content">
<h2>Reinforcement Learning</h2>
<p>Bellman equations, policy gradients, Q-learning & beyond</p>
<span class="card-count" id="count-ReinforcementLearning"></span>
</div>
</div>
</div>
</div>
<!-- TOPIC VIEW -->
<div id="topic-view" style="display: none;">
<h1 id="topic-title"></h1>
<div class="mode-switch">
<button id="all-btn" class="active">Study Mode</button>
<button id="practice-btn">Practice Mode</button>
</div>
<br>
<div class="topic-tabs" id="topic-tabs"></div>
<div class="tag-filters" id="tag-filters"></div>
<br>
<div id="qa-container"></div>
</div>
<script>
let qaData = [];
let mode = "all";
let currentTopic = "All";
let currentTag = "All";
let currentIndex = -1;
let order = [];
let visited = [];
let currentSubject = "";
const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions";
const OPENROUTER_MODEL = "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free";
const PROXY_URL = "%%PROXY_URL%%";
function renderMarkdown(text) {
if (!text || typeof marked === 'undefined') return text;
text = text.replace(/``([^`]*?)''/g, '“$1”');
const mathMap = {};
let idx = 0;
let processed = text.replace(/\$\$([\s\S]*?)\$\$/g, (m) => {
const key = `%%DISPLAY_MATH_${idx++}%%`;
mathMap[key] = m;
return `\n\n${key}\n\n`;
});
processed = processed.replace(/\\\[([\s\S]*?)\\\]/g, (m) => {
const key = `%%DISPLAY_MATH_${idx++}%%`;
mathMap[key] = m;
return `\n\n${key}\n\n`;
});
processed = processed.replace(/\$([^$\n]+?)\$/g, (m) => {
const key = `%%INLINE_MATH_${idx++}%%`;
mathMap[key] = m;
return key;
});
processed = processed.replace(/\\\([\s\S]*?\\\)/g, (m) => {
const key = `%%INLINE_MATH_${idx++}%%`;
mathMap[key] = m;
return key;
});
let html = marked.parse(processed, { breaks: true });
Object.keys(mathMap).forEach(key => {
if (key.includes('DISPLAY_MATH')) {
html = html.replace(key, `</p><div class="math-display">${mathMap[key]}</div><p>`);
} else {
html = html.replace(key, mathMap[key]);
}
});
html = html.replace(/<p>\s*<\/p>/g, '');
return html;
}
const subjects = {
Transformers: "Transformers",
Diffusion: "Diffusion",
ReinforcementLearning: "Reinforcement Learning"
};
// --- Routing ---
function navigate(hash) {
window.location.hash = hash;
}
function handleRoute() {
const hash = window.location.hash || "#home";
if (hash === "#home" || hash === "") {
showHome();
} else if (hash.startsWith("#topic/")) {
const subject = hash.replace("#topic/", "");
if (subjects[subject]) {
showTopic(subject);
} else {
navigate("#home");
}
} else {
navigate("#home");
}
}
function updateBreadcrumb(subject) {
const bc = $("#breadcrumb");
bc.empty();
if (subject) {
bc.append(`<a class="breadcrumb-item" href="#home">Home</a>`);
bc.append(`<span class="breadcrumb-sep">/</span>`);
bc.append(`<span class="breadcrumb-item active">${subjects[subject]}</span>`);
} else {
bc.append(`<span class="breadcrumb-item active">Home</span>`);
}
}
function showHome() {
updateBreadcrumb(null);
$("#home-view").show();
$("#topic-view").hide();
currentSubject = "";
loadQuestionCounts();
}
function showTopic(subject) {
updateBreadcrumb(subject);
$("#home-view").hide();
$("#topic-view").attr("data-theme", subject).show();
$("#topic-title").text(subjects[subject]);
loadSubject(subject);
}
function loadQuestionCounts() {
Object.keys(subjects).forEach(subject => {
$.getJSON(`topics/${subject}/QA.json`, function (data) {
$(`#count-${subject}`).text(`${data.length} questions`);
}).fail(() => {
$(`#count-${subject}`).text("Coming soon");
});
});
}
// --- LLM Verification ---
async function verifyAnswerWithLLM(userAnswer, correctAnswer, question) {
const prompt = `You are an expert evaluator. Compare the user's answer with the correct answer for the following question.
Question: ${question}
Correct Answer:
${correctAnswer}
User's Answer:
${userAnswer}
Please provide your evaluation as a JSON object with the following structure:
{
"score": <number from 0-100>,
"analysis": "<brief analysis text>",
"keyPoints": "<key points text>",
"feedback": "<overall feedback text>"
}
IMPORTANT: Return ONLY valid JSON, no additional text before or after.`;
const requestBody = {
model: localStorage.getItem('openrouter_model') || OPENROUTER_MODEL,
messages: [{ role: "user", content: prompt }],
temperature: 0.3
};
const useProxy = PROXY_URL && !PROXY_URL.startsWith("%%");
const apiKey = localStorage.getItem('openrouter_api_key');
if (!useProxy && !apiKey) {
return { success: false, error: "No API key configured. Click the gear icon to add your OpenRouter key." };
}
try {
let response;
if (useProxy) {
try {
response = await fetch(PROXY_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errBody = await response.text().catch(() => '');
try {
const errJson = JSON.parse(errBody);
return { success: false, error: errJson.error?.message || errBody };
} catch {
return { success: false, error: `Error (${response.status}): ${errBody || 'Unknown error'}` };
}
}
} catch (e) {
response = null;
}
}
if (!response) {
if (!apiKey) {
return { success: false, error: "No API key configured. Click the gear icon to add your OpenRouter key." };
}
response = await fetch(OPENROUTER_API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
"HTTP-Referer": window.location.origin,
"X-Title": "Interview Preparation"
},
body: JSON.stringify(requestBody)
});
}
if (!response.ok) throw new Error(`API error: ${response.status}`);
const data = await response.json();
let llmResponse = data.choices[0].message.content.trim();
try {
let jsonStr = llmResponse;
if (llmResponse.startsWith('{')) {
let braceCount = 0, endIndex = -1;
for (let i = 0; i < llmResponse.length; i++) {
if (llmResponse[i] === '{') braceCount++;
if (llmResponse[i] === '}') { braceCount--; if (braceCount === 0) { endIndex = i + 1; break; } }
}
if (endIndex > 0) jsonStr = llmResponse.substring(0, endIndex);
} else {
const jsonMatch = llmResponse.match(/\{[\s\S]*\}/);
if (jsonMatch) jsonStr = jsonMatch[0];
}
const parsed = JSON.parse(jsonStr);
const str = v => Array.isArray(v) ? v.join('\n') : (typeof v === 'object' && v ? JSON.stringify(v) : String(v || ''));
return {
success: true,
score: typeof parsed.score === 'number' ? parsed.score : null,
analysis: str(parsed.analysis),
keyPoints: str(parsed.keyPoints || parsed.key_points),
feedback: str(parsed.feedback)
};
} catch (parseError) {
return { success: true, score: null, analysis: llmResponse, keyPoints: "", feedback: llmResponse };
}
} catch (error) {
return { success: false, error: error.message || "Failed to verify answer" };
}
}
// --- Topic Tabs ---
const TYPE_ORDER = ["Theory", "Models", "Learning", "Deployment", "Case Studies"];
function typeRank(t) { const i = TYPE_ORDER.indexOf(t); return i === -1 ? TYPE_ORDER.length : i; }
function populateTopicTabs() {
const topics = [...new Set(qaData.map(q => q.type).filter(Boolean))]
.sort((a, b) => typeRank(a) - typeRank(b));
const tabContainer = $("#topic-tabs");
tabContainer.empty();
tabContainer.append(`<div class="topic-tab active" data-topic="All">All</div>`);
topics.forEach(topic => {
tabContainer.append(`<div class="topic-tab" data-topic="${topic}">${topic}</div>`);
});
$(".topic-tab").on("click", function () {
$(".topic-tab").removeClass("active");
$(this).addClass("active");
currentTopic = $(this).data("topic");
currentTag = "All";
populateTagFilters();
setMode(mode);
});
}
function populateTagFilters() {
const pool = currentTopic === "All" ? qaData : qaData.filter(q => q.type === currentTopic);
const tags = [...new Set(pool.flatMap(q => q.tags || []).filter(Boolean))];
const container = $("#tag-filters");
container.empty();
if (tags.length === 0) return;
const TAG_ORDER = ["Basic", "Deep", "Hands-on"];
tags.sort((a, b) => {
const ia = TAG_ORDER.indexOf(a), ib = TAG_ORDER.indexOf(b);
return (ia === -1 ? TAG_ORDER.length : ia) - (ib === -1 ? TAG_ORDER.length : ib);
});
container.append(`<span class="tag-filter active" data-tag="All">All</span>`);
tags.forEach(tag => {
container.append(`<span class="tag-filter" data-tag="${tag}">${tag}</span>`);
});
$(".tag-filter").on("click", function () {
$(".tag-filter").removeClass("active");
$(this).addClass("active");
currentTag = $(this).data("tag");
setMode(mode);
});
}
function getFilteredData() {
let data = currentTopic === "All" ? qaData : qaData.filter(q => q.type === currentTopic);
if (currentTag !== "All") data = data.filter(q => q.tags && q.tags.includes(currentTag));
return data;
}
// --- All Mode ---
function renderAllMode() {
const container = $("#qa-container");
container.empty();
const filtered = getFilteredData();
filtered.forEach((q) => {
const tagsHtml = q.tags && q.tags.length > 0
? `<div class="tags-container">${q.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}</div>`
: '';
const card = $(`
<div class="qa-card">
<div class="type-tags-row">
<div class="type-label">${q.type}</div>
${tagsHtml}
</div>
<div class="question">${q.id}. ${q.question}<span class="toggle-icon">+</span></div>
<div class="answer">${renderMarkdown(q.answer)}</div>
</div>
`);
container.append(card);
});
$(".answer").hide();
$(".toggle-icon").text("+");
$(".question").on("click", function () {
const ans = $(this).siblings(".answer");
const icon = $(this).find(".toggle-icon");
const isVisible = ans.is(":visible");
ans.slideToggle(200);
icon.text(isVisible ? "+" : "−");
});
if (window.MathJax) MathJax.typesetPromise();
}
// --- Practice Mode ---
function renderPracticeMode(index = null) {
const container = $("#qa-container");
container.empty();
const filteredData = getFilteredData();
if (filteredData.length === 0) {
container.html(`<p class="empty-msg">No questions in this topic.</p>`);
return;
}
if (order.length === 0) {
order = [...Array(filteredData.length).keys()];
for (let i = order.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[order[i], order[j]] = [order[j], order[i]];
}
visited = [];
}
if (index !== null) currentIndex = index;
else currentIndex = visited.length;
if (currentIndex >= order.length) {
container.html(`<p class="empty-msg">You've completed all questions in this topic!</p>`);
return;
}
const qIndex = order[currentIndex];
visited.push(qIndex);
const q = filteredData[qIndex];
const tagsHtml = q.tags && q.tags.length > 0
? `<div class="tags-container">${q.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}</div>`
: '';
const card = $(`
<div class="practice-card">
<div class="counter">Question ${currentIndex + 1} / ${filteredData.length}</div>
<div class="type-tags-row">
<div class="type-label">${q.type}</div>
${tagsHtml}
</div>
<div class="question">${q.id}. ${q.question}</div>
<textarea class="user-input" id="user-answer" placeholder="Type your answer here..."></textarea>
<div class="practice-actions">
<button id="verify-btn">Verify with LLM</button>
<button id="check-btn">Check Answer</button>
<button id="prev-btn">Previous</button>
<button id="next-btn">Next</button>
</div>
<div id="verification-result" class="verification-box" style="display: none;"></div>
<div id="correct-answer" class="answer-box">${renderMarkdown(q.answer)}</div>
</div>
`);
container.append(card);
$("#verify-btn").on("click", async () => {
const userAnswer = $("#user-answer").val().trim();
if (!userAnswer) { alert("Please enter an answer before verifying."); return; }
$("#verify-btn").prop("disabled", true).text("Verifying...");
const resultDiv = $("#verification-result");
resultDiv.html("<p>Verifying your answer with LLM...</p>").slideDown(300);
try {
const verification = await verifyAnswerWithLLM(userAnswer, q.answer, q.question);
if (!verification.success) {
resultDiv.html(`<div class="verification-error"><p><strong>Error:</strong> ${verification.error}</p></div>`);
} else {
const score = (verification.score !== null && verification.score !== undefined) ? verification.score : "N/A";
let scoreColor = "#64748b";
if (typeof score === 'number') {
if (score >= 80) scoreColor = "#4CAF50";
else if (score >= 60) scoreColor = "#FF9800";
else scoreColor = "#F44336";
}
let htmlContent = `<div class="verification-content">
<div class="score-display" style="background: ${scoreColor}; color: white; padding: 10px; border-radius: 5px; margin-bottom: 15px; text-align: center;">
<h3>Score: ${score}${typeof score === 'number' ? '/100' : ''}</h3>
</div><div class="verification-details">`;
const s = v => String(v || '');
if (s(verification.analysis).trim()) {
const escaped = $('<div>').text(s(verification.analysis)).html();
htmlContent += `<div class="verification-section"><p class="section-title">Analysis:</p><p class="section-content">${escaped.replace(/\n/g, '<br>')}</p></div>`;
}
if (s(verification.keyPoints).trim()) {
const escaped = $('<div>').text(s(verification.keyPoints)).html();
htmlContent += `<div class="verification-section"><p class="section-title">Key Points:</p><p class="section-content">${escaped.replace(/\n/g, '<br>')}</p></div>`;
}
if (s(verification.feedback).trim() && s(verification.feedback) !== s(verification.analysis)) {
const escaped = $('<div>').text(s(verification.feedback)).html();
htmlContent += `<div class="verification-section"><p class="section-title">Feedback:</p><p class="section-content">${escaped.replace(/\n/g, '<br>')}</p></div>`;
}
htmlContent += `</div></div>`;
resultDiv.html(htmlContent);
}
} catch (err) {
resultDiv.html(`<div class="verification-error"><p><strong>Error:</strong> ${err.message}</p></div>`);
} finally {
$("#verify-btn").prop("disabled", false).text("Verify with LLM");
if (window.MathJax) MathJax.typesetPromise();
}
});
$("#check-btn").on("click", () => $("#correct-answer").slideDown(300));
$("#next-btn").on("click", () => {
if (currentIndex < order.length - 1) renderPracticeMode(currentIndex + 1);
else container.html(`<p class="empty-msg">You've completed all questions!</p>`);
});
$("#prev-btn").on("click", () => {
if (currentIndex > 0) renderPracticeMode(currentIndex - 1);
});
if (window.MathJax) MathJax.typesetPromise();
}
// --- Mode & Subject ---
function setMode(newMode) {
mode = newMode;
$("#all-btn").toggleClass("active", mode === "all");
$("#practice-btn").toggleClass("active", mode === "practice");
order = [];
visited = [];
if (mode === "all") renderAllMode();
else renderPracticeMode();
}
function loadSubject(subject) {
currentSubject = subject;
currentTopic = "All";
currentTag = "All";
order = [];
visited = [];
mode = "all";
$.getJSON(`topics/${subject}/QA.json`, function (data) {
qaData = data.sort((a, b) => typeRank(a.type) - typeRank(b.type));
populateTopicTabs();
populateTagFilters();
setMode(mode);
}).fail(() => {
qaData = [];
$("#topic-tabs").empty();
$("#qa-container").html(`<p class="empty-msg">No questions available for ${subjects[subject] || subject} yet.</p>`);
});
}
// --- Init ---
$(document).ready(function () {
$(".topic-card").on("click", function () {
const subject = $(this).data("subject");
navigate(`#topic/${subject}`);
});
$("#all-btn").on("click", () => setMode("all"));
$("#practice-btn").on("click", () => setMode("practice"));
// Settings modal
$("#settings-btn").on("click", () => {
$("#model-input").val(localStorage.getItem('openrouter_model') || OPENROUTER_MODEL);
$("#api-key-input").val(localStorage.getItem('openrouter_api_key') || '');
$("#settings-status").text('');
$("#settings-modal").fadeIn(200);
});
$("#modal-close").on("click", () => $("#settings-modal").fadeOut(200));
$("#settings-modal").on("click", function (e) {
if (e.target === this) $(this).fadeOut(200);
});
$("#save-settings-btn").on("click", () => {
const key = $("#api-key-input").val().trim();
const model = $("#model-input").val().trim();
if (key) localStorage.setItem('openrouter_api_key', key);
if (model) localStorage.setItem('openrouter_model', model);
$("#settings-status").text("Settings saved").css("color", "#4CAF50");
});
$("#clear-settings-btn").on("click", () => {
localStorage.removeItem('openrouter_api_key');
localStorage.removeItem('openrouter_model');
$("#api-key-input").val('');
$("#model-input").val(OPENROUTER_MODEL);
$("#settings-status").text("Settings cleared").css("color", "#94a3b8");
});
window.addEventListener("hashchange", handleRoute);
handleRoute();
});
</script>
</body>
</html>