Spaces:
Sleeping
Sleeping
File size: 11,793 Bytes
0f7e074 | 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 | // ============================================
// AI Voice Assistant - Frontend Logic
// ============================================
let isListening = false;
let currentVoice = 'girl';
let recognition = null;
// Initialize Speech Recognition (Web Speech API)
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = 'en-IN';
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
stopListening();
addMessage(transcript, 'user');
processMessage(transcript);
};
recognition.onerror = (event) => {
console.error('Speech error:', event.error);
stopListening();
updateMicStatus("Couldn't hear you. Try again.");
setTimeout(() => updateMicStatus('Tap to speak'), 2000);
};
recognition.onend = () => {
if (isListening) stopListening();
};
}
// Toggle Microphone
function toggleMic() {
if (isListening) {
recognition.stop();
stopListening();
} else {
startListening();
}
}
function startListening() {
if (!recognition) {
alert('Speech recognition is not supported in this browser. Please use Chrome.');
return;
}
isListening = true;
const micBtn = document.getElementById('micBtn');
micBtn.classList.add('listening');
document.getElementById('micIcon').textContent = 'mic_off';
updateMicStatus('Listening...');
recognition.start();
}
function stopListening() {
isListening = false;
const micBtn = document.getElementById('micBtn');
micBtn.classList.remove('listening');
document.getElementById('micIcon').textContent = 'mic';
updateMicStatus('Tap to speak');
}
function updateMicStatus(text) {
document.getElementById('micStatus').textContent = text;
}
// Send text message
function sendText() {
const input = document.getElementById('textInput');
const message = input.value.trim();
if (!message) return;
input.value = '';
addMessage(message, 'user');
processMessage(message);
}
// Quick action buttons
function sendQuick(message) {
addMessage(message, 'user');
processMessage(message);
}
// Process message with backend
async function processMessage(message) {
// Hide welcome msg
const welcomeMsg = document.getElementById('welcomeMsg');
if (welcomeMsg) welcomeMsg.style.display = 'none';
// Check voice toggle command
if (message.toLowerCase().includes('change') && message.toLowerCase().includes('voice')) {
await toggleVoiceAPI();
return;
}
// Show typing indicator
showTyping();
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message })
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Server Error (${response.status}): ${errorText}`);
}
const data = await response.json();
removeTyping();
if (data.response) {
addMessage(data.response, 'ai');
await speakResponse(data.response);
} else if (data.error) {
addMessage(data.error, 'ai');
} else {
addMessage('Something went wrong. Please try again.', 'ai');
}
} catch (error) {
removeTyping();
console.error('Chat error:', error);
addMessage(`System Error: ${error.message}`, 'ai');
}
}
// Add message bubble to chat
function addMessage(text, sender, manualTime = null) {
const chatArea = document.getElementById('chatArea');
const time = manualTime
? new Date(manualTime).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })
: new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
const msgDiv = document.createElement('div');
msgDiv.classList.add('message', sender);
const icon = sender === 'user' ? 'person' : 'smart_toy';
msgDiv.innerHTML = `
<div class="message-avatar">
<span class="material-icons-round">${icon}</span>
</div>
<div>
<div class="message-content">${text}</div>
<div class="message-time">${time}</div>
</div>
`;
chatArea.appendChild(msgDiv);
chatArea.scrollTop = chatArea.scrollHeight;
}
// Typing indicator
function showTyping() {
const chatArea = document.getElementById('chatArea');
const typingDiv = document.createElement('div');
typingDiv.classList.add('message', 'ai');
typingDiv.id = 'typingIndicator';
typingDiv.innerHTML = `
<div class="message-avatar">
<span class="material-icons-round">smart_toy</span>
</div>
<div class="message-content">
<div class="typing-indicator">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</div>
`;
chatArea.appendChild(typingDiv);
chatArea.scrollTop = chatArea.scrollHeight;
}
function removeTyping() {
const typing = document.getElementById('typingIndicator');
if (typing) typing.remove();
}
// Speak response using backend Edge TTS
async function speakResponse(text) {
try {
updateMicStatus('🔊 Speaking...');
const response = await fetch('/api/speak', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, voice: currentVoice })
});
if (!response.ok) {
let detail = `HTTP ${response.status}`;
try {
const err = await response.json();
if (err.error) detail = err.error;
} catch (_) { /* ignore */ }
console.error('Speak API failed:', detail);
updateMicStatus('Tap to speak');
return;
}
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.onended = () => {
updateMicStatus('Tap to speak');
URL.revokeObjectURL(audioUrl);
};
await audio.play();
} catch (error) {
console.error('Speech error:', error);
updateMicStatus('Tap to speak');
}
}
// Voice toggle
document.getElementById('voiceSwitch').addEventListener('change', async (e) => {
currentVoice = e.target.checked ? 'boy' : 'girl';
const label = currentVoice === 'boy' ? '👦 Boy' : '👩 Girl';
// Visual feedback
document.getElementById('voiceLabel').style.opacity = currentVoice === 'girl' ? '1' : '0.4';
document.getElementById('voiceLabelBoy').style.opacity = currentVoice === 'boy' ? '1' : '0.4';
// Speak confirmation
const confirmText = `Voice changed to ${currentVoice === 'boy' ? "boy's" : "girl's"} voice.`;
addMessage(confirmText, 'ai');
await speakResponse(confirmText);
});
async function toggleVoiceAPI() {
const voiceSwitch = document.getElementById('voiceSwitch');
voiceSwitch.checked = !voiceSwitch.checked;
voiceSwitch.dispatchEvent(new Event('change'));
}
// ============================================
// Sidebar Functions
// ============================================
function goHome() {
// Clear chat and show welcome message
const chatArea = document.getElementById('chatArea');
chatArea.innerHTML = '';
const welcomeHtml = `
<div class="welcome-message" id="welcomeMsg">
<div class="welcome-icon">
<span class="material-icons-round">waving_hand</span>
</div>
<h2>Hello! I'm your AI Assistant</h2>
<p>Press the mic button and start talking, or type your message below.</p>
<div class="quick-actions">
<button class="quick-btn" onclick="sendQuick('What is the time?')">
<span class="material-icons-round">schedule</span> Time
</button>
<button class="quick-btn" onclick="sendQuick('What is the date?')">
<span class="material-icons-round">calendar_today</span> Date
</button>
<button class="quick-btn" onclick="sendQuick('Tell me a joke')">
<span class="material-icons-round">sentiment_very_satisfied</span> Joke
</button>
<button class="quick-btn" onclick="sendQuick('Tell me a fun fact')">
<span class="material-icons-round">lightbulb</span> Fun Fact
</button>
</div>
</div>
`;
chatArea.innerHTML = welcomeHtml;
// Update active sidebar button
document.querySelectorAll('.sidebar-btn').forEach(btn => btn.classList.remove('active'));
document.getElementById('homeBtn').classList.add('active');
}
function newChat() {
// Clear chat and show welcome
goHome();
addMessage("Started a new conversation!", 'ai');
const welcomeMsg = document.getElementById('welcomeMsg');
if (welcomeMsg) welcomeMsg.style.display = 'none';
}
async function toggleHistory() {
const welcomeMsg = document.getElementById('welcomeMsg');
if (welcomeMsg) welcomeMsg.style.display = 'none';
// Update active sidebar button
document.querySelectorAll('.sidebar-btn').forEach(btn => btn.classList.remove('active'));
const historyBtn = document.getElementById('historyBtn');
if (historyBtn) historyBtn.classList.add('active');
const chatArea = document.getElementById('chatArea');
chatArea.innerHTML = '';
showTyping(); // Use typing indicator as loading state
try {
const response = await fetch('/api/history');
const data = await response.json();
chatArea.innerHTML = ''; // Clear loading state
if (data.history && data.history.length > 0) {
const header = document.createElement('div');
header.style.textAlign = 'center';
header.style.color = 'rgba(255, 255, 255, 0.7)';
header.style.padding = '15px 0 25px 0';
header.style.fontSize = '0.95rem';
header.innerHTML = '<span class="material-icons-round" style="vertical-align: middle; font-size: 1.2rem; margin-right: 5px;">history</span> Past Conversations';
chatArea.appendChild(header);
data.history.forEach(msg => {
if (msg.user_message) {
addMessage(msg.user_message, 'user', msg.timestamp);
}
if (msg.ai_response) {
addMessage(msg.ai_response, 'ai', msg.timestamp);
}
});
} else {
addMessage("No chat history found. Start a new conversation!", 'ai');
}
} catch (error) {
chatArea.innerHTML = '';
addMessage("Failed to load chat history. Please try again.", 'ai');
console.error('History error:', error);
}
}
function toggleSettings() {
// Show current settings info
const voiceInfo = currentVoice === 'boy' ? "Boy (PrabhatNeural)" : "Girl (NeerjaNeural)";
addMessage(`⚙️ Current Settings:\n• Voice: ${voiceInfo}\n• Language: English (India)\n• AI Model: Gemini 2.5 Flash`, 'ai');
const welcomeMsg = document.getElementById('welcomeMsg');
if (welcomeMsg) welcomeMsg.style.display = 'none';
}
|