-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
287 lines (236 loc) · 8.48 KB
/
script.js
File metadata and controls
287 lines (236 loc) · 8.48 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
// Get references to HTML elements
const startListeningButton = document.getElementById("start-listening");
const stopAssistantButton = document.getElementById("stop-assistant");
const themeToggleButton = document.getElementById("theme-toggle");
const clearOutputButton = document.getElementById("clear-output");
const submitCommandButton = document.getElementById("submit-command");
const manualCommandInput = document.getElementById("manual-command");
const response = document.getElementById("response");
const spokenTextSection = document.getElementById("spoken-text");
const commandHistory = document.getElementById("command-history");
const commandsList = document.getElementById("commands-list");
// Initialize speech recognition only if supported
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = SpeechRecognition ? new SpeechRecognition() : null;
// Initialize state variables
let isListening = false;
let shouldStopSpeaking = false;
let isSpeaking = false;
const MAX_HISTORY_ITEMS = 8;
const DEFAULT_COMMANDS = [
'Say "Hello" to greet the assistant.',
'Say "Teach me about [topic]" to get information on a specific topic.',
'Say "Tell me about yourself" to learn more about the assistant.',
'Say "Stop" or "Exit" to stop the assistant from listening.',
'Say "Repeat" to hear the latest assistant response again.',
'Type any command in the text box and click "Submit Command".',
];
renderAvailableCommands();
if (recognition) {
recognition.continuous = true;
recognition.onstart = function () {
startListeningButton.textContent = "Listening...";
isListening = true;
};
recognition.onresult = function (event) {
const transcript =
event.results[event.results.length - 1][0].transcript.toLowerCase();
processCommand(transcript, "voice");
};
recognition.onend = function () {
if (isListening) {
recognition.start();
}
};
} else {
startListeningButton.disabled = true;
speak(
"Voice recognition is not supported in this browser. You can still use typed commands."
);
}
startListeningButton.addEventListener("click", function () {
if (!recognition) {
return;
}
if (isListening) {
recognition.stop();
isListening = false;
startListeningButton.textContent = "Start Listening";
} else {
recognition.start();
}
});
stopAssistantButton.addEventListener("click", function () {
stopAssistant();
});
themeToggleButton.addEventListener("click", function () {
document.body.classList.toggle("dark-mode");
});
clearOutputButton.addEventListener("click", function () {
response.innerText = "";
spokenTextSection.innerText = "";
commandHistory.innerHTML = "";
});
submitCommandButton.addEventListener("click", function () {
submitTypedCommand();
});
manualCommandInput.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
submitTypedCommand();
}
});
function submitTypedCommand() {
const typedCommand = manualCommandInput.value.trim().toLowerCase();
if (!typedCommand) {
return;
}
processCommand(typedCommand, "typed");
manualCommandInput.value = "";
}
function processCommand(transcript, source) {
response.innerText = `You ${source === "voice" ? "said" : "typed"}: "${transcript}"`;
addHistoryItem(transcript, source);
if (transcript.includes("hello")) {
speak("Hello! How can I assist you?");
} else if (transcript.includes("teach me about")) {
const query = transcript.replace("teach me about", "").trim();
if (!query) {
speak("Please provide a topic after saying teach me about.");
return;
}
searchWikipedia(query);
} else if (transcript.includes("stop") || transcript.includes("exit")) {
stopAssistant();
speak("Assistant stopped. Click the button to start listening again.");
} else if (transcript.includes("tell me about yourself")) {
speak(
"I am EDUCATIONAL ASSISTANT, your virtual teacher, here to assist and answer your questions. I was created by Atharv Shinde. Let's learn something new together!"
);
} else if (transcript.includes("repeat")) {
const currentSpokenText = spokenTextSection.innerText.replace(
'Assistant says: "',
""
);
speak(currentSpokenText.replace(/"$/, "") || "There is nothing to repeat yet.");
} else {
speak(
"I did not recognize that command yet. Try hello, teach me about, repeat, or tell me about yourself."
);
}
}
function addHistoryItem(command, source) {
const historyItem = document.createElement("li");
historyItem.className = "command-item";
historyItem.innerText = `${new Date().toLocaleTimeString()} • ${source}: ${command}`;
commandHistory.prepend(historyItem);
while (commandHistory.children.length > MAX_HISTORY_ITEMS) {
commandHistory.removeChild(commandHistory.lastChild);
}
}
function renderAvailableCommands() {
commandsList.innerHTML = "";
DEFAULT_COMMANDS.forEach((command) => {
const item = document.createElement("li");
item.className = "command-item";
item.innerText = command;
commandsList.appendChild(item);
});
}
function stopAssistant() {
if (recognition) {
recognition.stop();
}
isListening = false;
startListeningButton.textContent = "Start Listening";
shouldStopSpeaking = true;
if (isSpeaking) {
window.speechSynthesis.cancel();
isSpeaking = false;
}
}
function speak(text) {
const synth = window.speechSynthesis;
const utterance = new SpeechSynthesisUtterance(text);
utterance.onstart = function () {
isSpeaking = true;
};
utterance.onend = function () {
isSpeaking = false;
if (shouldStopSpeaking) {
window.speechSynthesis.cancel();
shouldStopSpeaking = false;
}
};
spokenTextSection.innerText = `Assistant says: "${text}"`;
synth.speak(utterance);
}
async function searchWikipedia(query) {
try {
const pageId = await searchUsingLocalPhp(query);
await getSummaryUsingLocalPhp(pageId);
} catch (localError) {
console.warn("Local PHP endpoints unavailable. Falling back to public Wikipedia API.", localError);
try {
const summary = await getSummaryFromPublicWikipedia(query);
speak(summary);
} catch (publicError) {
console.error("Wikipedia lookup failed:", publicError);
speak(
"Sorry, I could not load information right now. Please make sure your server is running or try again in a moment."
);
}
}
}
async function searchUsingLocalPhp(query) {
const apiUrl = `search-wikipedia.php?query=${encodeURIComponent(query)}`;
const apiResponse = await fetch(apiUrl);
if (!apiResponse.ok) {
throw new Error("Local search endpoint request failed");
}
const data = await apiResponse.json();
if (!data.query || !data.query.search || data.query.search.length === 0) {
throw new Error("No results from local search endpoint");
}
return data.query.search[0].pageid;
}
async function getSummaryUsingLocalPhp(pageId) {
const apiUrl = `get-summary.php?pageid=${pageId}`;
const apiResponse = await fetch(apiUrl);
if (!apiResponse.ok) {
throw new Error("Local summary endpoint request failed");
}
const data = await apiResponse.json();
if (!data.query || !data.query.pages || !data.query.pages[pageId]) {
throw new Error("No summary from local endpoint");
}
const extract = data.query.pages[pageId].extract;
const summary = extract.split(".").slice(0, 5).join(".").trim();
speak(summary || "Sorry, I couldn't find a summary for that topic.");
}
async function getSummaryFromPublicWikipedia(query) {
const searchUrl = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(
query
)}&format=json&origin=*`;
const searchResponse = await fetch(searchUrl);
if (!searchResponse.ok) {
throw new Error("Public search request failed");
}
const searchData = await searchResponse.json();
if (!searchData.query || !searchData.query.search || searchData.query.search.length === 0) {
throw new Error("No results from public Wikipedia search");
}
const title = searchData.query.search[0].title;
const summaryUrl = `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(
title
)}`;
const summaryResponse = await fetch(summaryUrl);
if (!summaryResponse.ok) {
throw new Error("Public summary request failed");
}
const summaryData = await summaryResponse.json();
const extract = (summaryData.extract || "").trim();
if (!extract) {
throw new Error("No public summary returned");
}
return extract.split(".").slice(0, 5).join(".").trim();
}