-
Notifications
You must be signed in to change notification settings - Fork 276
/
chatbot.html
471 lines (430 loc) · 15.6 KB
/
chatbot.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bobble Ai-Chat Bot</title>
<link
href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css"
rel="stylesheet"
/>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<link href="Style.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/a11y-dark.min.css"
/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.1/marked.min.js"></script>
</head>
<body class="bg-gradient-to-r from-blue-400 to-indigo-300 flex items-center justify-center min-h-screen">
<div id="Loader"></div>
<div
class="flex flex-col items-center justify-center w-full max-w-xl space-y-4"
>
<div class="w-full flex justify-center">
<img
src="boy.png"
alt="Chat Bot"
class="h-42 w-42 object-cover rounded-lg shadow-lg"
/>
</div>
<div class="chat-container w-full bg-white p-6 rounded-lg shadow-xl">
<div id="output-field" class="text-center text-lg font-semibold text-gray-700 mb-3">
How can I help you today?
</div>
<div
id="output-container"
class="mb-3 overflow-auto"
style="max-height: 300px"
></div>
<div class="input-group mb-3 flex items-center space-x-2">
<div id="image-preview-container" class="flex items-center">
<span
id="image-preview"
class="flex items-center space-x-2 hidden"
style="display: none"
>
<img src="" alt="Image preview" class="h-10 mr-2 object-cover rounded-lg" />
<button
type="button"
id="clear-image"
class="text-red-600 text-2xl leading-none"
aria-label="Close"
>
×
</button>
</span>
</div>
<input
type="text"
id="prompt-input"
class="form-control flex-1 p-2 border border-gray-300 rounded-lg"
placeholder="Type your prompt here..."
aria-label="Message input"
/>
<div id="microphone-animation" class="hidden">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<button
class="p-2 bg-gray-100 rounded-lg hover:bg-gray-200 transition"
id="inputGroupFileAddon"
onclick="document.getElementById('image-input').click();"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="25"
height="25"
fill="currentColor"
class="bi bi-image"
viewBox="0 0 16 16"
>
<path d="M6.002 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0" />
<path
d="M2.002 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2zm12 1a1 1 0 0 1 1 1v6.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71-2.66-1.772a.5.5 0 0 0-.63.062L1.002 12V3a1 1 0 0 1 1-1z"
/>
</svg>
</button>
<input type="file" id="image-input" accept="image/*" class="hidden" />
<button id="voiceBtn" class="p-2 bg-gray-100 rounded-lg hover:bg-gray-200 transition"><i class="fa fa-microphone" style="font-size:24px"></i></button>
<button id="generate-btn" class="btn btn-primary">Send</button>
</div>
</div>
</div>
<style>
.chat-container {
width: 100%;
max-width: 500px;
padding: 20px;
background-color: white;
border-radius: 12px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
body,
html {
margin: 0;
padding: 0;
}
.user-message {
text-align: right;
background-color: #f0f0f0;
border-radius: 15px 15px 0px 15px;
padding: 10px 10px 5px 10px;
margin: 10px;
max-width: 60%;
float: right;
clear: both;
}
.ai-message {
text-align: left;
background-color: #e0f7fa;
border-radius: 15px 15px 15px 0px;
padding: 10px 10px 5px 10px;
margin: 10px;
max-width: 60%;
float: left;
clear: both;
}
#microphone-animation {
display: none; /* Hide initially */
align-items: center;
justify-content: center;
margin-left: 10px; /* Adjust as needed */
}
.dot {
height: 5px; /* Size of the dots */
width: 5px;
margin: 0 3px; /* Space between dots */
background-color: #007bff; /* Color of the dots */
border-radius: 50%; /* Make it circular */
animation: bounce 0.6s infinite alternate; /* Animation */
}
.dot:nth-child(1) {
animation-delay: 0s;
}
.dot:nth-child(2) {
animation-delay: 0.2s;
}
.dot:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes bounce {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-10px); /* Distance to bounce */
}
}
</style>
<script type="importmap">
{
"imports": {
"@google/generative-ai": "https://esm.run/@google/generative-ai"
}
}
</script>
<script type="module">
import {
GoogleGenerativeAI,
HarmBlockThreshold,
HarmCategory,
} from "@google/generative-ai";
const API_KEY = "AIzaSyBF265bY6o63VuPypal-5w0-b7sr0N_O3A"; // Replace with your gemini-api actual API key
const genAI = new GoogleGenerativeAI(API_KEY);
let chat;
const safetySettings = [
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH,
},
];
async function fileToGenerativePart(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64Data = reader.result.split(",")[1];
resolve({ inlineData: { data: base64Data, mimeType: file.type } });
};
reader.readAsDataURL(file);
});
}
async function sendMessage(prompt, imageParts = []) {
let model;
let result;
clearGreeting(); // Clear the greeting after sending the message
if (imageParts.length > 0) {
model = genAI.getGenerativeModel({
model: "gemini-pro-vision",
safetySettings,
});
} else {
if (!chat) {
chat = await genAI
.getGenerativeModel({ model: "gemini-pro", safetySettings })
.startChat({
history: [],
generationConfig: {
maxOutputTokens: 4000, // maxOutputTokens Limit around 4096
},
});
}
model = chat;
}
try {
if (imageParts.length > 0) {
result = await model.generateContent([prompt, ...imageParts]);
} else {
result = await model.sendMessage(prompt);
}
const response = await result.response;
if (response) {
const text = await response.text();
displayMessage(text, "ai");
} else {
// This block handles a null response, suggesting blocked content
displayMessage(
"This content is not safe for display based on current settings.",
"ai"
);
}
} catch (error) {
console.error("Error during message generation:", error);
displayMessage(
"This content is not safe for display based on current settings. or an internal error.",
"ai"
);
}
clearInputs();
}
function displayMessage(message, sender) {
const outputContainer = document.getElementById("output-container");
const msgDiv = document.createElement("div");
msgDiv.classList.add(
"chat-message",
sender === "user" ? "user-message" : "ai-message"
);
if (sender === "ai") {
// Show loading animation for AI messages
msgDiv.innerHTML =
'<div class="loading">' +
'<div class="loading-dot"></div>' +
'<div class="loading-dot"></div>' +
'<div class="loading-dot"></div>' +
"</div>";
outputContainer.appendChild(msgDiv);
// Simulate processing delay
setTimeout(() => {
// Clear loading animation
msgDiv.innerHTML = "";
if (message.startsWith("```") && message.endsWith("```")) {
// Code block handling
const codeContent = message.substring(3, message.length - 3);
const escapedCode = codeContent
.replace(/</g, "<")
.replace(/>/g, ">");
msgDiv.innerHTML = `<pre><code class="hljs">${escapedCode}</code></pre>`;
window.hljs.highlightBlock(msgDiv.querySelector("code"));
// Add Copy button
const copyButton = document.createElement("button");
copyButton.innerText = "Copy code";
copyButton.onclick = function () {
navigator.clipboard.writeText(codeContent).then(
() => {
// Change text to show confirmation instead of using alert
copyButton.innerText = "Copied!";
// Optional: revert the button text back to "Copy code" after 2 seconds
setTimeout(() => {
copyButton.innerText = "Copy code";
}, 2000);
},
(err) => {
console.error("Failed to copy text: ", err);
}
);
};
msgDiv.appendChild(copyButton);
} else {
// For regular messages
msgDiv.innerHTML = marked.parse(message);
}
// Scroll the output container to the bottom to ensure the latest message is visible
outputContainer.scrollTop = outputContainer.scrollHeight;
}, 1500); // Adjust the delay as needed
} else {
// User messages are displayed immediately without the loading animation
msgDiv.innerHTML =
message.startsWith("```") && message.endsWith("```")
? `<pre><code class="hljs">${message.substring(
3,
message.length - 3
)}</code></pre>`
: marked.parse(message);
// If it's a code block, enable syntax highlighting and add a copy button
if (message.startsWith("```") && message.endsWith("```")) {
const codeBlock = msgDiv.querySelector("pre code");
window.hljs.highlightBlock(codeBlock);
const copyButton = document.createElement("button");
copyButton.innerText = "Copy code";
copyButton.onclick = function () {
navigator.clipboard.writeText(codeBlock.textContent).then(
() => {
alert("Code copied to clipboard!");
},
(err) => {
alert("Failed to copy text: ", err);
}
);
};
msgDiv.appendChild(copyButton);
}
outputContainer.appendChild(msgDiv);
}
// Ensure the latest message is visible
outputContainer.scrollTop = outputContainer.scrollHeight;
}
function clearInputs() {
document.getElementById("prompt-input").value = "";
document.getElementById("image-input").value = "";
clearImagePreview();
}
document
.getElementById("generate-btn")
.addEventListener("click", async () => {
const prompt = document.getElementById("prompt-input").value;
const files = document.getElementById("image-input").files;
const imageParts = await Promise.all(
[...files].map(fileToGenerativePart)
);
if (prompt.trim() !== "") {
displayMessage(prompt, "user");
await sendMessage(prompt, imageParts);
}
});
function clearGreeting() {
const outputField = document.getElementById("output-field");
if (outputField) {
outputField.style.display = "none"; // Hide the field completely
}
}
document
.getElementById("image-input")
.addEventListener("change", function (event) {
const [file] = event.target.files;
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
const previewContainer = document.getElementById("image-preview");
const previewImage =
previewContainer.getElementsByTagName("img")[0];
previewImage.src = e.target.result;
previewContainer.style.display = "flex";
};
reader.readAsDataURL(file);
}
});
document
.getElementById("clear-image")
.addEventListener("click", function () {
// Clear the preview
const previewContainer = document.getElementById("image-preview");
const previewImage = previewContainer.getElementsByTagName("img")[0];
previewImage.src = "";
previewContainer.style.display = "none";
// Clear the file input
document.getElementById("image-input").value = "";
});
function clearImagePreview() {
const previewContainer = document.getElementById("image-preview");
if (previewContainer) {
const previewImage = previewContainer.getElementsByTagName("img")[0];
previewImage.src = "";
previewContainer.style.display = "none";
}
}
</script>
<script>
var loader = document.getElementById("Loader");
window.addEventListener("load", function () {
loader.style.display = "none";
});
</script>
<script>
const voiceBtn = document.getElementById('voiceBtn');
const promptInput = document.getElementById('prompt-input');
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.lang = 'en-US'; // Change this to your preferred language if needed
recognition.interimResults = false;
// When speech recognition gives a result
recognition.addEventListener('result', (event) => {
const transcript = event.results[0][0].transcript; // Get the transcript of what was said
promptInput.value += transcript; // Append the transcript to the input field
});
// Show microphone animation when recognition starts
voiceBtn.addEventListener('click', () => {
document.getElementById('microphone-animation').style.display = 'flex'; // Show dots
recognition.start(); // Start voice recognition
});
// Hide microphone animation when recognition ends
recognition.addEventListener('end', () => {
document.getElementById('microphone-animation').style.display = 'none'; // Hide dots
});
recognition.addEventListener('error', (event) => {
console.error('Speech recognition error:', event.error); // Log any errors
});
document.getElementById("prompt-input").addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault(); // Prevents the default action of the Enter key
document.getElementById("generate-btn").click(); // Programmatically clicks the send button
}
});
</script>
</body>
</html>