-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
711 lines (624 loc) · 37 KB
/
Copy pathscript.js
File metadata and controls
711 lines (624 loc) · 37 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
// Knowledge base data
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
primary: '#6d28d9',
secondary: '#8b5cf6',
accent: '#a78bfa',
dark: {
primary: '#8b5cf6',
secondary: '#a78bfa',
bg: '#121212',
card: '#1e1e1e',
text: '#f0f0f0',
},
light: {
primary: '#6d28d9',
secondary: '#8b5cf6',
bg: '#f5f3ff',
card: '#ffffff',
text: '#333333',
}
},
animation: {
'text-gradient': 'text-gradient 3s ease infinite',
'float': 'float 6s ease-in-out infinite',
'pulse-slow': 'pulse 5s cubic-bezier(0.4, 0, 0.6, 1) infinite',
'slide-in': 'slideIn 0.5s ease-out forwards',
'fade-in': 'fadeIn 1s ease-in forwards',
'wave': 'wave 12s linear infinite',
'ripple': 'ripple 1.5s ease-out infinite',
'spin-slow': 'spin 6s linear infinite'
},
keyframes: {
'text-gradient': {
'0%, 100%': { 'background-position': '0% 50%' },
'50%': { 'background-position': '100% 50%' },
},
'float': {
'0%, 100%': { transform: 'translateY(0)' },
'50%': { transform: 'translateY(-20px)' },
},
'slideIn': {
'0%': { transform: 'translateY(50px)', opacity: 0 },
'100%': { transform: 'translateY(0)', opacity: 1 }
},
'fadeIn': {
'0%': { opacity: 0 },
'100%': { opacity: 1 }
},
'wave': {
'0%': { transform: 'translateX(0)' },
'100%': { transform: 'translateX(-50%)' }
},
'ripple': {
'0%': { transform: 'scale(0.8)', opacity: 0.5 },
'70%': { transform: 'scale(1.3)', opacity: 0 },
'100%': { transform: 'scale(1.4)', opacity: 0 }
}
}
}
}
}
const knowledgeBase = {
"about": {
title: "About NovaAI",
content: "NovaAI is an advanced conversational assistant designed to help with a wide range of tasks. It combines natural language processing with machine learning to provide intelligent responses to your questions."
},
"programming": {
title: "Programming Help",
content: "I can assist with various programming languages including Python, JavaScript, Java, C++, and more. I can help debug code, explain concepts, and provide examples."
},
"creative": {
title: "Creative Writing",
content: "Need help with creative writing? I can generate poems, stories, marketing copy, and other creative content based on your prompts."
},
"learning": {
title: "Learning Resources",
content: "I can recommend learning resources for various subjects including mathematics, science, programming, and humanities. Just let me know what you're interested in learning!"
}
};
// Training data for the NLP system
const trainingData = [
{
patterns: ["hello", "hi", "hey", "greetings"],
responses: ["Hello! How can I help you today?", "Hi there! What can I do for you?", "Greetings! What would you like to know?"]
},
{
patterns: ["how are you", "how's it going", "how do you feel"],
responses: ["I'm just a program, so I don't have feelings, but I'm functioning perfectly! How can I assist you today?", "I'm always ready to help! What do you need assistance with?", "I'm operating at 100% capacity. How can I be of service?"]
},
{
patterns: ["what can you do", "what are your capabilities", "help"],
responses: ["I can help with a wide range of topics including answering questions, explaining concepts, generating creative content, assisting with programming, and much more. What specifically do you need help with?", "My capabilities include answering questions, providing explanations, generating text, and assisting with various tasks. Try asking me anything!"]
},
{
patterns: ["thank you", "thanks", "appreciate it"],
responses: ["You're welcome! Is there anything else I can help with?", "Happy to help! Let me know if you have other questions.", "My pleasure! Feel free to ask if you need anything else."]
},
{
patterns: ["bye", "goodbye", "see you later"],
responses: ["Goodbye! Come back if you have more questions.", "See you later! Don't hesitate to return if you need help.", "Bye for now! I'll be here when you need me."]
},
{
patterns: ["your name", "who are you"],
responses: ["I'm NovaAI, your intelligent assistant. You can call me Nova if you'd like!", "I'm NovaAI, an AI assistant designed to help you with various tasks. What can I do for you today?"]
},
{
patterns: ["weather", "temperature", "forecast"],
responses: ["I don't have real-time weather data, but you can check services like Weather.com or your local weather app for accurate forecasts.", "For weather information, I recommend checking a dedicated weather service as I don't have live weather data access."]
},
{
patterns: ["time", "what time is it", "current time"],
responses: [`The current time is ${new Date().toLocaleTimeString()}.`, `Right now it's ${new Date().toLocaleTimeString()}.`]
},
{
patterns: ["date", "what day is it", "today's date"],
responses: [`Today is ${new Date().toLocaleDateString()}.`, `The date today is ${new Date().toLocaleDateString()}.`]
},
{
patterns: ["joke", "tell me a joke", "make me laugh"],
responses: [
"Why don't scientists trust atoms? Because they make up everything!",
"Why did the scarecrow win an award? Because he was outstanding in his field!",
"What do you call a fake noodle? An impasta!",
"How do you organize a space party? You planet!"
]
},
{
patterns: ["programming help", "coding assistance", "debug code"],
responses: ["I'd be happy to help with programming! Please share the code you're working on and describe the issue you're facing.", "For programming assistance, please provide the code snippet and explain what problem you're encountering."]
},
{
patterns: ["explain quantum computing", "what is quantum computing"],
responses: ["Quantum computing uses quantum bits or qubits which can exist in multiple states at once (superposition). This allows quantum computers to process complex calculations much faster than classical computers for certain problems. They're particularly useful for cryptography, optimization, and molecular modeling."]
},
{
patterns: ["write a poem", "poem about", "creative writing"],
responses: ["I'd be happy to write a poem! What would you like it to be about?", "Sure! What theme or subject should the poem focus on?"]
},
{
patterns: ["healthy recipes", "dinner ideas", "meal suggestions"],
responses: ["Here are some healthy meal ideas: 1) Grilled salmon with quinoa and roasted vegetables, 2) Chicken stir-fry with brown rice, 3) Lentil soup with whole grain bread. Would you like more specific recipes?", "For healthy eating, consider meals like vegetable curry with chickpeas, stuffed bell peppers with lean ground turkey, or a colorful salad with mixed greens, berries, and nuts. Need more details?"]
},
{
patterns: ["ai research", "latest in ai", "new ai developments"],
responses: ["Recent advances in AI include large language models like GPT-4, multimodal AI systems that can process text, images and audio simultaneously, and progress in reinforcement learning. Would you like information on a specific area of AI research?"]
},
{
patterns: ["learn machine learning", "how to study ml", "ml resources"],
responses: ["To learn machine learning: 1) Start with Python programming, 2) Learn linear algebra and statistics basics, 3) Study ML fundamentals with courses like Andrew Ng's on Coursera, 4) Practice with projects using TensorFlow or PyTorch. Would you like specific resource recommendations?"]
}
];
// Show notification
function showNotification(title, message) {
const notification = document.getElementById('notification');
const notificationTitle = document.getElementById('notification-title');
const notificationMessage = document.getElementById('notification-message');
notificationTitle.textContent = title;
notificationMessage.textContent = message;
notification.classList.add('show');
setTimeout(() => {
notification.classList.remove('show');
}, 3000);
}
// Update greeting based on time of day
function updateGreeting() {
const greetingElement = document.getElementById('greeting');
const dateElement = document.getElementById('date-display');
const now = new Date();
const hour = now.getHours();
let greeting = "Good ";
if (hour < 12) {
greeting += "Morning";
} else if (hour < 18) {
greeting += "Afternoon";
} else {
greeting += "Evening";
}
const userName = localStorage.getItem('nova-username') || '';
if (userName) {
greeting += `, ${userName}`;
} else {
greeting += `!`;
}
greetingElement.textContent = greeting;
// Update date
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
dateElement.textContent = now.toLocaleDateString('en-US', options);
}
// Ripple effect
function createRipple(event, element) {
const rect = element.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const ripple = document.createElement('span');
ripple.className = 'ripple';
ripple.style.left = `${x}px`;
ripple.style.top = `${y}px`;
element.appendChild(ripple);
setTimeout(() => {
if (ripple && ripple.parentNode) {
ripple.parentNode.removeChild(ripple);
}
}, 1500);
}
// Name collection function
function collectUserName() {
const nameOverlay = document.getElementById('name-overlay');
nameOverlay.classList.add('active');
const submitNameButton = document.getElementById('submit-name');
const userNameInput = document.getElementById('user-name-input');
submitNameButton.addEventListener('click', function() {
const userName = userNameInput.value.trim();
if (userName) {
localStorage.setItem('nova-username', userName);
proceedToApp(userName);
} else {
userNameInput.focus();
userNameInput.setAttribute('placeholder', 'Please enter your name...');
}
});
userNameInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
submitNameButton.click();
}
});
}
function proceedToApp(userName) {
const nameOverlay = document.getElementById('name-overlay');
const intro = document.getElementById('intro');
const app = document.getElementById('app');
nameOverlay.classList.remove('active');
setTimeout(() => {
intro.style.opacity = '0';
setTimeout(() => {
intro.style.display = 'none';
app.style.display = 'flex';
setUserNameInHeader(userName);
// Update greeting with name
updateGreeting();
// Show personalized notification
showNotification(`Welcome, ${userName}!`, "Your NovaAI assistant is ready to help you.");
}, 1000);
}, 500);
}
function setUserNameInHeader(userName) {
const userNameContainer = document.getElementById('user-name-display');
const usernameSpan = document.getElementById('username-span');
if (userName && userNameContainer) {
userNameContainer.classList.remove('hidden');
usernameSpan.textContent = userName;
}
}
// Intro animation
document.addEventListener('DOMContentLoaded', function() {
const intro = document.getElementById('intro');
const app = document.getElementById('app');
const progressBar = document.querySelector('.intro-progress-bar');
// Check if we already have a user name
const storedName = localStorage.getItem('nova-username');
// Start progress bar animation
setTimeout(() => {
progressBar.style.width = '100%';
}, 1500);
// After animation completes, show name collection popup
setTimeout(() => {
if (storedName) {
// We already have a name, proceed to app
proceedToApp(storedName);
} else {
// Show the name collection overlay
collectUserName();
}
}, 4000);
// Initialize greeting
updateGreeting();
// Update greeting every hour
setInterval(updateGreeting, 60 * 60 * 1000);
// Create ripple effect for all buttons
document.querySelectorAll('button, .suggestion-chip, .knowledge-item, .sidebar-item').forEach(item => {
item.addEventListener('click', function() {
createRipple(event, this);
});
});
// Mobile menu toggle
const mobileMenuButton = document.getElementById('mobile-menu-button');
const sidebar = document.getElementById('sidebar');
mobileMenuButton.addEventListener('click', function() {
sidebar.classList.toggle('open');
createRipple(event, this);
});
// Auto-resize textarea
const messageInput = document.getElementById('message-input');
messageInput.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
// Knowledge base toggle
const knowledgeBaseToggle = document.getElementById('knowledge-base-toggle');
const knowledgeBase = document.getElementById('knowledge-base');
knowledgeBaseToggle.addEventListener('click', function() {
knowledgeBase.classList.toggle('open');
const chevron = this.querySelector('.fa-chevron-down');
chevron.classList.toggle('rotate-180');
createRipple(event, this);
});
// Knowledge base items
const knowledgeItems = document.querySelectorAll('.knowledge-item');
knowledgeItems.forEach(item => {
item.addEventListener('click', function() {
const text = this.querySelector('span').textContent.toLowerCase();
let topic = '';
if (text.includes('about')) topic = 'about';
else if (text.includes('programming')) topic = 'programming';
else if (text.includes('creative')) topic = 'creative';
else if (text.includes('learning')) topic = 'learning';
if (topic && knowledgeBase[topic]) {
addAIMessage(knowledgeBase[topic].title, knowledgeBase[topic].content);
createRipple(event, this);
}
});
});
// Suggestion chips
const suggestionChips = document.querySelectorAll('.suggestion-chip');
suggestionChips.forEach(chip => {
chip.addEventListener('click', function() {
const prompt = this.getAttribute('data-prompt');
messageInput.value = prompt;
messageInput.focus();
createRipple(event, this);
});
});
// Theme toggle
const themeToggle = document.getElementById('theme-toggle');
themeToggle.addEventListener('click', function() {
document.documentElement.classList.toggle('dark');
const icon = this.querySelector('i');
if (document.documentElement.classList.contains('dark')) {
icon.classList.remove('fa-moon');
icon.classList.add('fa-sun');
} else {
icon.classList.remove('fa-sun');
icon.classList.add('fa-moon');
}
createRipple(event, this);
// Show notification for theme change
if (document.documentElement.classList.contains('dark')) {
showNotification("Night Mode", "Dark theme enabled for comfortable viewing");
} else {
showNotification("Day Mode", "Light theme enabled");
}
});
// Set dark mode if system preference
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark');
const icon = themeToggle.querySelector('i');
icon.classList.remove('fa-moon');
icon.classList.add('fa-sun');
}
// Settings button
const settingsButton = document.getElementById('settings-button');
settingsButton.addEventListener('click', function() {
showNotification("Settings", "Here you can configure your NovaAI experience. Settings options coming soon!");
createRipple(event, this);
});
// New chat button
const newChatButton = document.getElementById('new-chat-button');
newChatButton.addEventListener('click', function() {
const chatArea = document.getElementById('chat-area');
chatArea.innerHTML = `
<div class="max-w-3xl mx-auto">
<div class="chat-bubble bg-white dark:bg-dark-card p-6">
<div class="flex items-start space-x-4">
<div class="w-10 h-10 rounded-full bg-gradient-to-br from-primary dark:from-dark-primary to-secondary dark:to-dark-secondary flex items-center justify-center text-white">
<i class="fas fa-robot"></i>
</div>
<div>
<h3 class="font-bold text-dark dark:text-light-text mb-2">NovaAI Assistant</h3>
<div class="text-gray-700 dark:text-gray-300">
<p class="mb-4">Hello! I'm NovaAI, your intelligent assistant. I can help you with a wide range of tasks including answering questions, generating creative content, coding assistance, and much more.</p>
<p class="mb-4">Here are some things you can ask me:</p>
<div class="flex flex-wrap mb-4">
<div class="suggestion-chip" data-prompt="Explain quantum computing in simple terms">Explain quantum computing</div>
<div class="suggestion-chip" data-prompt="Write a poem about artificial intelligence">Write a poem</div>
<div class="suggestion-chip" data-prompt="Help me debug this Python code">Debug Python code</div>
<div class="suggestion-chip" data-prompt="Suggest some healthy dinner recipes">Healthy recipes</div>
<div class="suggestion-chip" data-prompt="What's the latest in AI research?">AI research</div>
<div class="suggestion-chip" data-prompt="How do I learn machine learning?">Learn ML</div>
</div>
<p>Or just ask me anything!</p>
</div>
</div>
</div>
</div>
</div>
`;
createRipple(event, this);
// Reattach event listeners to suggestion chips
document.querySelectorAll('.suggestion-chip').forEach(chip => {
chip.addEventListener('click', function() {
const prompt = this.getAttribute('data-prompt');
messageInput.value = prompt;
messageInput.focus();
});
});
});
// Model selector
const modelSelectors = document.querySelectorAll('.model-selector');
modelSelectors.forEach(selector => {
selector.addEventListener('click', function() {
modelSelectors.forEach(s => s.classList.remove('active'));
this.classList.add('active');
createRipple(event, this);
const model = this.getAttribute('data-model');
let modelName = "Nova Pro";
if (model === "lite") modelName = "Nova Lite";
else if (model === "creative") modelName = "Nova Creative";
showNotification("Model Changed", `You've switched to ${modelName}. This model is optimized for ${model === 'lite' ? 'speed and efficiency' : model === 'creative' ? 'creative tasks' : 'general intelligence'}.`);
});
});
// Sidebar items
const sidebarItems = document.querySelectorAll('.sidebar-item');
sidebarItems.forEach(item => {
item.addEventListener('click', function() {
if (!this.id) { // Skip items with IDs (like knowledge base toggle)
sidebarItems.forEach(i => i.classList.remove('active'));
this.classList.add('active');
createRipple(event, this);
const conversationType = this.querySelector('span').textContent;
showNotification("Conversation Type", `You've selected "${conversationType}".`);
}
});
});
// Voice recognition functionality
let recognition;
let isListening = false;
const voiceButton = document.getElementById('voice-button');
const voiceIcon = voiceButton.querySelector('i');
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.onstart = function() {
isListening = true;
voiceButton.classList.add('voice-active');
showNotification("Voice Input", "Listening... Speak now");
};
recognition.onresult = function(event) {
const transcript = event.results[0][0].transcript;
messageInput.value = transcript;
isListening = false;
voiceButton.classList.remove('voice-active');
showNotification("Voice Input", "Voice captured successfully");
};
recognition.onerror = function(event) {
console.error('Speech recognition error', event.error);
isListening = false;
voiceButton.classList.remove('voice-active');
showNotification("Voice Error", "Error occurred in voice recognition: " + event.error);
};
recognition.onend = function() {
if (isListening) {
recognition.stop();
isListening = false;
voiceButton.classList.remove('voice-active');
}
};
voiceButton.addEventListener('click', function() {
if (isListening) {
recognition.stop();
isListening = false;
voiceButton.classList.remove('voice-active');
showNotification("Voice Input", "Stopped listening");
} else {
recognition.start();
createRipple(event, this);
}
});
} else {
voiceButton.style.display = 'none';
showNotification("Voice Unavailable", "Your browser doesn't support speech recognition");
}
// Send message functionality
const sendButton = document.getElementById('send-button');
function sendMessage() {
const message = messageInput.value.trim();
if (message) {
// Add user message to chat
addUserMessage(message);
// Clear input
messageInput.value = '';
messageInput.style.height = 'auto';
// Process message and generate response
processMessage(message);
createRipple(event, sendButton);
}
}
function addUserMessage(message) {
const chatArea = document.getElementById('chat-area');
const userMessage = document.createElement('div');
userMessage.className = 'max-w-3xl mx-auto';
userMessage.innerHTML = `
<div class="flex justify-end mb-4">
<div class="chat-bubble bg-gradient-to-br from-primary dark:from-dark-primary to-secondary dark:to-dark-secondary text-white p-4 max-w-xs md:max-w-md">
<p>${message}</p>
</div>
</div>
`;
chatArea.appendChild(userMessage);
// Scroll to bottom
chatArea.scrollTop = chatArea.scrollHeight;
}
function addAIMessage(title, content) {
const chatArea = document.getElementById('chat-area');
// Add typing indicator
const typingIndicator = document.createElement('div');
typingIndicator.className = 'max-w-3xl mx-auto';
typingIndicator.innerHTML = `
<div class="flex justify-start mb-4">
<div class="chat-bubble bg-white dark:bg-dark-card p-4 max-w-xs md:max-md">
<div class="typing-indicator">
<div class="typing-dot"></div>
<div class="typing-dot"></极>
<div class="typing-dot"></div>
</div>
</div>
</div>
`;
chatArea.appendChild(typingIndicator);
// Scroll to bottom
chatArea.scrollTop = chatArea.scrollHeight;
// Simulate response after delay
setTimeout(() => {
// Remove typing indicator
chatArea.removeChild(typingIndicator);
// Add AI response
const aiResponse = document.createElement('div');
aiResponse.className = 'max-w-3xl mx-auto';
aiResponse.innerHTML = `
<div class="flex justify-start mb-4">
<div class="chat-bubble bg-white dark:bg-dark-card p-4 max-w-xs md:max-w-md">
${title ? `<h4 class="font-bold text-primary dark:text-dark-primary mb-2">${title}</h4>` : ''}
<p>${content}</p>
</div>
</div>
`;
chatArea.appendChild(aiResponse);
// Scroll to bottom
chatArea.scrollTop = chatArea.scrollHeight;
}, 1000 + Math.random() * 1000); // Random delay between 1-2 seconds
}
function processMessage(message) {
// Convert to lowercase for case-insensitive matching
const lowerMessage = message.toLowerCase();
// Check for exact matches in training data
let response = null;
for (const item of trainingData) {
for (const pattern of item.patterns) {
if (lowerMessage.includes(pattern)) {
// Randomly select one of the possible responses
response = item.responses[Math.floor(Math.random() * item.responses.length)];
break;
}
}
if (response) break;
}
// If no exact match, use NLP to analyze the message
if (!response) {
const nlp = window.nlp;
if (nlp) {
const doc = nlp(message);
// Check for question words
const questions = doc.questions();
if (questions.length > 0) {
// It's a question - try to find the main topic
const nouns = doc.nouns().out('array');
const verbs = doc.verbs().out('array');
const adjectives = doc.adjectives().out('array');
if (nouns.includes('quantum') && nouns.includes('computing')) {
response = "Quantum computing uses quantum bits or qubits which can exist in multiple states at once (superposition). This allows quantum computers to process complex calculations much faster than classical computers for certain problems.";
} else if (nouns.includes('poem') || verbs.includes('write') || verbs.includes('compose')) {
response = "I'd be happy to write a poem! What would you like it to be about?";
} else if (nouns.includes('code') || nouns.includes('programming') || nouns.includes('debug')) {
response = "I can help with programming! Please share the code you're working on and describe the issue you're facing.";
} else if (nouns.includes('recipe') || nouns.includes('food') || nouns.includes('meal')) {
response = "Here are some healthy meal ideas: 1) Grilled salmon with quinoa and roasted vegetables, 2) Chicken stir-fry with brown rice, 3) Lentil soup with whole grain bread. Would you like more specific recipes?";
} else {
// Generic response for questions
response = "That's an interesting question. While I don't have a specific answer prepared, I can try to help. Could you provide more details about what you're looking for?";
}
} else {
// Not a question - generate a generic response
if (verbs.includes('help') || verbs.includes('assist')) {
response = "I'd be happy to help! What specifically do you need assistance with?";
} else if (adjectives.includes('happy') || adjectives.includes('excited')) {
response = "That's great to hear! What's making you feel this way?";
} else if (adjectives.includes('sad') || adjectives.includes('upset')) {
response = "I'm sorry to hear that. Would you like to talk about what's bothering you?";
} else {
// Default response
response = "Thanks for sharing that. Is there anything specific you'd like me to help with?";
}
}
} else {
// Fallback if NLP library fails to load
response = "I'm not sure how to respond to that. Could you rephrase or ask something else?";
}
}
// Add the AI response
addAIMessage(null, response);
}
sendButton.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
});