-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
311 lines (269 loc) · 13 KB
/
index.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voice Assistant</title>
</head>
<body>
<center> <img id="carlGif" src="Carl2.gif" alt="Carl1.gif" /></center>
<h1>CARL</h1>
<h3><center>Communicating Advanced Responding Language model</h3>
<p>This page will listen to your voice commands and perform actions when the wake word "Carl" is detected.</p>
<p id="output"></p>
<div id="searchResults"></div> <!-- Added div to display search results -->
<script>
const output = document.getElementById('output');
const searchResultsContainer = document.getElementById('searchResults'); // Container for displaying search results
let listening = false;
let timerId;
let lastSpeechTimestamp = 0;
const speechTimeout = 1500; // 1.5 seconds
const gifElement = document.getElementById('carlGif');
const gifs = ["Carl2.gif", "Carl1.gif"];
let currentGifIndex = 1; // Start with "Carl1.gif"
function changeGif() {
gifElement.src = gifs[currentGifIndex];
currentGifIndex = (currentGifIndex + 1) % gifs.length; // Toggle between 0 and 1
}
// Show confirmation dialog when the user tries to leave the page
window.addEventListener('beforeunload', (event) => {
if (listening) {
event.preventDefault();
event.returnValue = ''; // Display a confirmation message
}
});
// Check if the browser supports speech recognition
if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = 'en-US'; // Set the language to English
recognition.continuous = true; // Enable continuous recognition
recognition.onstart = () => {
output.textContent = 'Listening...';
changeGif();
};
recognition.onend = () => {
if (listening) {
const currentTime = new Date().getTime();
const timeSinceLastSpeech = currentTime - lastSpeechTimestamp;
if (timeSinceLastSpeech >= speechTimeout) {
// If no speech for 1.5 seconds, reset and wait for the wake word
resetRecognition();
} else {
recognition.start();
}
}
};
recognition.onresult = async (event) => {
const result = event.results[event.results.length - 1][0].transcript;
if (listening) {
output.textContent = `You said: ${result}`;
lastSpeechTimestamp = new Date().getTime();
// Check if the recognized text is a question
const isQuestion = /(who|what|where|when|why|how)\b/i.test(result);
if (isQuestion) {
if (/whatis/i.test(result)) {
// Do nothing because "what is" is mentioned
} else {
// Open a new tab and perform a Google search
window.open(`https://www.google.com/search?q=${encodeURIComponent(result)}`, '_blank');
}
// Handle "Do nothing" command
handlePhrase(/what is/i, () => {
// Do nothing here, i.e., no action will be taken
});
}
// Check if the recognized text contains "Open"
if (/open/i.test(result)) {
const words = result.split(' ');
const openIndex = words.findIndex(word => word.toLowerCase() === 'open');
if (openIndex !== -1 && openIndex < words.length - 1) {
const domain = words.slice(openIndex + 1).join(''); // Combine all words after "open"
// Remove spaces to format the URL
const formattedDomain = domain.replace(/\s/g, '');
// Check if the formatted URL is valid
if (isValidDomain(formattedDomain)) {
// Open the valid domain in a new tab
window.open(`http://${formattedDomain}`, '_blank');
}
}
}
// Check if the recognized text contains "Set timer for"
if (/set timer for (\d+) minutes?/i.test(result)) {
const minutesMatch = result.match(/set timer for (\d+) minutes?/i);
if (minutesMatch) {
const minutes = parseInt(minutesMatch[1]);
setTimer(minutes);
}
}
// Check if the recognized text contains "directions to" or "where is"
if (/directions to (.+)/i.test(result) || /where is (.+)/i.test(result)) {
const locationMatch = result.match(/directions to (.+)/i) || result.match(/where is (.+)/i);
if (locationMatch) {
const location = locationMatch[1];
openGoogleMaps(location);
}
}
// Check if the recognized text contains "Read from website"
if (/read from website/i.test(result)) {
const searchQuery = result.replace(/read from website/i, '').trim();
const url = `https://www.google.com/search?q=${encodeURIComponent(searchQuery)}`;
try {
const searchResults = await fetchSearchResults(url);
if (searchResults && searchResults.length > 0) {
displaySearchResults(searchResults);
} else {
output.textContent = 'No search results found.';
}
} catch (error) {
output.textContent = 'An error occurred while fetching search results.';
}
}
// Check if the recognized text contains "translate"
if (/translate/i.test(result)) {
const textToTranslate = result.replace(/translate/i, '').trim();
const url = `https://www.spanishdict.com/translate/${encodeURIComponent(textToTranslate)}`;
// Open a new tab and perform a translation search
window.open(url, '_blank');
}
} else {
// Check if the wake word "Carl" is detected
if (/carl/i.test(result)) {
output.textContent = 'Carl: Listening...';
listening = true;
changeGif();
recognition.start();
currentGifIndex = (currentGifIndex + 1) % gifs.length;
gifElement.src = gifs[currentGifIndex];
}
}
};
recognition.onerror = (event) => {
output.textContent = 'Error occurred. Please try again.';
console.error(event.error);
changeGif();
currentGifIndex = (currentGifIndex + 1) % gifs.length;
gifElement.src = gifs[currentGifIndex];
};
// Start continuous recognition when the page loads
window.addEventListener('load', () => {
output.textContent = 'Waiting for wake word "Carl"...';
listening = false;
recognition.start();
});
// Function to check if a string is a valid domain
function isValidDomain(domain) {
const pattern = /^(www\.)?([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,})+$/;
return pattern.test(domain);
}
// Function to set a timer and play an alarm
function setTimer(minutes) {
clearTimeout(timerId);
output.textContent = `Timer set for ${minutes} minutes.`;
timerId = setTimeout(() => {
output.textContent = 'Timer expired. Alarm!';
playAlarm();
}, minutes * 60000); // Convert minutes to milliseconds
}
// Function to play an alarm sound (you can replace this with your desired sound)
function playAlarm() {
// Add code here to play an alarm sound (e.g., using the Web Audio API or an audio element)
// For example, you can use an HTML5 audio element like this:
const audio = new Audio('path-to-your-alarm-sound.mp3');
audio.play();
}
// Function to reset recognition and wait for the wake word
function resetRecognition() {
listening = false;
output.textContent = 'Waiting for wake word "Carl"...';
changeGif();
}
// Function to open Google Maps with directions to a location
function openGoogleMaps(location) {
const googleMapsURL = `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(location)}`;
window.open(googleMapsURL, '_blank');
}
// Function to fetch search results from Google
async function fetchSearchResults(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const searchResults = [];
const resultElements = doc.querySelectorAll('.tF2Cxc');
resultElements.forEach((resultElement) => {
const title = resultElement.querySelector('h3')?.textContent;
if (title) {
searchResults.push({ title });
}
});
return searchResults;
} catch (error) {
console.error(error);
return [];
}
}
// Function to display search results in HTML
function displaySearchResults(results) {
searchResultsContainer.innerHTML = ''; // Clear previous results
results.forEach((result, index) => {
const resultElement = document.createElement('div');
resultElement.innerHTML = `<p>Result ${index + 1}: ${result.title}</p>`;
searchResultsContainer.appendChild(resultElement);
});
}
} else {
output.textContent = 'Speech recognition is not supported in this browser.';
}
</script>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
text-align: center;
}
h1 {
font-size: 24px;
color: #333;
}
h3 {
font-size: 16px;
color: #666;
}
p {
font-size: 16px;
color: #666;
max-width: 400px;
margin: 20px;
}
#output {
font-size: 18px;
font-weight: bold;
background-color: #fff;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
max-width: 80%;
margin: 20px;
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
}
/* Added style for displaying search results */
#searchResults {
font-size: 16px;
max-width: 80%;
text-align: left;
}
</style>
</body>
</html>