Spaces:
Runtime error
Runtime error
File size: 2,416 Bytes
3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc 6b9dce9 3514bdc |
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 |
document.addEventListener("DOMContentLoaded", () => {
const chatBox = document.getElementById("chatBox");
const input = document.getElementById("userInput");
const micBtn = document.getElementById("micBtn");
// Append a message to the chat box
function appendMessage(text, sender = "bot") {
const msg = document.createElement("div");
msg.className = sender === "bot" ? "bot-message" : "user-message";
msg.innerText = text;
chatBox.appendChild(msg);
chatBox.scrollTop = chatBox.scrollHeight;
}
// Send message to backend
async function sendMessage() {
const message = input.value.trim();
if (!message) return;
appendMessage(message, "user");
input.value = "";
const loadingMsg = document.createElement("div");
loadingMsg.className = "bot-message";
loadingMsg.innerText = "Loading...";
chatBox.appendChild(loadingMsg);
chatBox.scrollTop = chatBox.scrollHeight;
try {
const res = await fetch("/api", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question: message })
});
const data = await res.json();
loadingMsg.remove();
appendMessage(data.answer || "β No response from AI.", "bot");
} catch (err) {
loadingMsg.remove();
appendMessage("β Failed to get response: " + err.message, "bot");
}
}
// Make sendMessage available globally for <form onsubmit>
window.sendMessage = sendMessage;
// Submit on Enter key (in case form fallback fails)
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
sendMessage();
}
});
// Voice input (mic) support
if ("webkitSpeechRecognition" in window || "SpeechRecognition" in window) {
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = "en-IN";
recognition.onstart = () => appendMessage("ποΈ Listening...", "bot");
recognition.onresult = (e) => {
const transcript = e.results[0][0].transcript;
input.value = transcript;
sendMessage();
};
recognition.onerror = (e) => {
appendMessage("β οΈ Mic error: " + e.error, "bot");
};
micBtn.onclick = () => recognition.start();
} else {
micBtn.disabled = true;
micBtn.title = "π€ Voice input not supported in this browser.";
}
});
|