CoolFace
Apppublic

StagChatbot/Multitasking-Chatbot

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
script.js471 linesDownload Raw Back to static
1let mapEnabled = false; // Flag to track if mapping is enabled2let spotifyEnabled = false; // Flag to track if spotify is enabled3startNewChat();4 5function sendMessage() {6    // Hide sample questions buttons7    hideAdditionalButtons();8 9    // Determine route based on Map and Spotify flags10    if (mapEnabled) {11        // If mapping is enabled, handle mapping functionality12        handleMapping()13    } else if (spotifyEnabled) {14        // If spotify is enabled, handle spotify functionality15        var userInput = document.getElementById("user-input").value.trim();16        if (userInput !== "") {17            // Pass user input to Python Flask for processing18            sendSpotifyRequest(userInput);19        } else {20            updateAndDisplayMessage("Please enter a song title or artist.", false);21        }22    } else {23        var userInput = document.getElementById("user-input").value.trim();24        sendRegularMessage(userInput)25    }26    // Clear input field27    document.getElementById("user-input").value = "";28}29 30 31// ============================== Spotify ==============================32function toggleSpotify(){33    hideAdditionalButtons();34    spotifyEnabled = !spotifyEnabled35    mapEnabled = false;36    // Update the appearance of the buttons37    updateButtons(spotifyEnabled,mapEnabled)38 39    if (spotifyEnabled) {40        updateAndDisplayMessage("Please enter a song title or artist.", false);41    } else {42        updateAndDisplayMessage("Spotify turned off.", false);43    }44 45}46function sendSpotifyRequest(musicRequest) {47    // Display user's message immediately48    displayMessage(musicRequest, true);49 50    // Send user's message and selected language to server51    fetch('/handle_spotify', {52        method: 'POST',53        headers: {54            'Content-Type': 'application/json;charset=UTF-8'55        },56        body: JSON.stringify({ song: musicRequest })57    })58    .then(response => {59        if (response.ok) {60            return response.json();61        } else {62            throw new Error('Network response was not ok.');63        }64    })65    .then(responseData => {66        // Display Spotify results67        displaySpotifyResults(responseData)68        console.log("Attempting to display Spotify results");69    })70    .catch(error => {71        console.error('Error:', error);72    });73}74function displaySpotifyResults(results) {75    updateAndDisplayMessage("Here are the top 5 results for this query:");76    var chatList = document.querySelector(".chat");77    results.forEach(track => {78        var messageElement = document.createElement("li");79        messageElement.className = "message-music";80 81        // Create and append image element82        var imageElement = document.createElement("img");83        imageElement.src = track.image;84        imageElement.className = "play-btn";85        imageElement.dataset.id = track.preview_url; // Use preview URL as track ID86        imageElement.addEventListener("click", play);87        messageElement.appendChild(imageElement);88 89        // Create and append text content (track name and artist)90        var textElement = document.createElement("span");91        textElement.textContent = track.name + ' - ' + track.artist;92        messageElement.appendChild(textElement);93 94        chatList.appendChild(messageElement);95    });96}97 98function play() {99    const trackId = this.getAttribute('data-id');100    fetch('/play', {101        method: 'POST',102        body: new URLSearchParams({track_id: trackId}),103        headers: {104            'Content-Type': 'application/x-www-form-urlencoded'105        }106    })107    .then(response => response.json())108    .then(data => {109        const player = document.getElementById('player');110        player.innerHTML = '';111        if (data && data.preview_url) {112            const audio = document.createElement('audio');113            audio.controls = true;114            audio.src = data.preview_url;115            player.appendChild(audio);116            audio.play()117            audio.addEventListener('ended', function() {118                audio.currentTime = 0; // Reset audio to the beginning119                audio.play(); // Restart playback120            });121        } else {122            player.innerHTML = 'No preview available';123        }124    });125}126 127 128// ============================== Mapping ==============================129function toggleMap() {130    hideAdditionalButtons();131    mapEnabled = !mapEnabled; // Toggle the flag132    spotifyEnabled = false;133    updateButtons(spotifyEnabled,mapEnabled)134    // Display message in the chat area based on the state135    if (mapEnabled) {136        addLocationDropDown("start_location", false, "Select Starting Location: ");137        addLocationDropDown("end_location", false, "Select Ending Location: ");138    } else {139        updateAndDisplayMessage("Mapping turned off.", false);140    }141}142function addLocationDropDown(idAndName, isUserMessage, location_string) {143    var chatList = document.querySelector(".chat");144 145    // Create message element146    var messageElement = document.createElement("li");147    messageElement.className = "message";148 149    // Create label for the drop down menu150    var dropdownLabel = document.createElement("label");151    dropdownLabel.setAttribute("for", idAndName);152    dropdownLabel.textContent = location_string;153 154    // Add elements to the html155    messageElement.appendChild(dropdownLabel);156    chatList.appendChild(messageElement);157 158    var dropdown = document.createElement("select");159    dropdown.setAttribute("id", idAndName);160    dropdown.setAttribute("name", idAndName);161    dropdown.className = "location-dropdown";162 163    var locations = {164        "42 Langguth Road":"42 Langguth Road, West Langguth Road, 06824 Fairfield, Connecticut, United States",165        "Kelley Center":"Aloysius P. Kelley Center, Loyola Drive, 06824 Fairfield, United States",166        "Alumni Hall Sports Arena":"Alumni Hall Sports Arena, Leeber Road, 06824 Fairfield, Connecticut, United States",167        "Alumni House":"Alumni House, Stonkas Road, 06824 Fairfield, United States",168        "Alumni Softball Field":"Alumni Softball Field, McCormick Road, 06824 Fairfield, United States",169        "Barlow Field":"Barlow Field, Barlow Road, 06824 Fairfield, United States",170        "Barone Campus Center":"Barone Campus Center, Loyola Drive, 06824 Fairfield, United States",171        "Bellarmine Hall":"Bellarmine Hall, Fitzgerald Way, 06824 Fairfield, United States",172        "Campion Hall":"Campion Hall, McCormick Road, 06824 Fairfield, United States",173        "Canisius Hall":"Canisius Hall, East Langguth Road, 06824 Fairfield, Connecticut, United States",174        "Center for Nursing and Health Studies":"Center for Nursing and Health Studies, McInnes Road, 06824 Fairfield, United States",175        "Charles F Dolan School of Business":"Charles F Dolan School of Business, Bellarmine Road, 06824 Fairfield, CT, United States",176        "Claver Hall":"Claver Hall, Mahan Road, 06824 Fairfield, United States",177        "Conference Center at Fairfield U":"Conference Center at Fairfield University, Walters Way, 06824 Fairfield, United States",178        "David J Dolan House":"David J Dolan House, Mooney Road, 06824 Fairfield, CT, United States",179        "DiMenna-Nyselius Library":"DiMenna-Nyselius Library, McInnes Road, 06824 Fairfield, United States",180        "Donnarumma Hall":"Donnarumma Hall, East Langguth Road, 06824 Fairfield, Connecticut, United States",181        "Egan Chapel of Saint Ignatius Lo":"Egan Chapel of Saint Ignatius Loyola, Bellarmine Road, 06824 Fairfield, United States",182        "Faber Hall":"Faber Hall, Bellarmine Road, 06824 Fairfield, United States",183        "Gonzaga Hall":"Gonzaga Hall, East Langguth Road, 06824 Fairfield, Connecticut, United States",184        "Jesuit Community Center":"Jesuit Community Center, Bellarmine Road, 06824 Fairfield, United States",185        "Jogues Hall":"Jogues Hall, McCormick Road, 06824 Fairfield, United States",186        "John C. Dolan Hall":"John C. Dolan Hall, Mooney Road, 06824 Fairfield, CT, United States",187        "Kelley Center Parking Garage":"Kelley Center Parking Garage, Leeber Road, 06824 Fairfield, Connecticut, United States",188        "Kostka Hall":"Kostka Hall, Mahan Road, 06824 Fairfield, United States",189        "Lessing Field":"Lessing Field, Leeber Road, 06824 Fairfield, Connecticut, United States",190        "Loyola Hall":"Loyola Hall, McCormick Road, 06824 Fairfield, United States",191        "Mahan Road":"Mahan Road, 06824 Fairfield, United States",192        "McAuliffe Hall":"McAuliffe Hall, Ross Road, 06824 Fairfield, United States",193        "McCormick Road":"McCormick Road, 06824 Fairfield, United States",194        "Meditz Hall":"Meditz Hall, McInnes Road, 06824 Fairfield, United States",195        "Rafferty Stadium":"Rafferty Stadium, Lynch Road, 06824 Fairfield, United States",196        "Regina A Quick Center for the Arts":"Regina A Quick Center for the Arts, McInnes Road, 06824 Fairfield, CT, United States",197        "Regis Hall":"Regis Hall, East Langguth Road, 06824 Fairfield, Connecticut, United States",198        "Rudolph F. Bannow Science Center":"Rudolph F. Bannow Science Center, McInnes Road, 06824 Fairfield, United States",199        "Student Townhouse Complex":"Student Townhouse Complex, Lynch Road, 06824 Fairfield, CT, United States",200        "The Levee":"The Levee, Lynch Road, 06824 Fairfield, CT, United States",201        "University Field":"University Field, Leeber Road, 06824 Fairfield, Connecticut, United States",202        "Walsh Athletic Center":"Walsh Athletic Center, Lynch Road, 06824 Fairfield, United States"203    };204 205    Object.keys(locations).forEach(function(key) {206        var option = document.createElement("option");207        option.setAttribute("value", locations[key]);208        option.textContent = key;209        dropdown.appendChild(option);210    });211    messageElement.appendChild(dropdown);212}213 214function handleMapping() {215    var start_location = document.getElementById("start_location").value216    var end_location = document.getElementById("end_location").value217    // Create an object with the data218    var data = {219        start_location: start_location,220        end_location: end_location221    };222    fetch('/handle_mapping', {223        method: 'POST',224        headers: {225            'Content-Type': 'application/json;charset=UTF-8'226        },227        body: JSON.stringify(data) // Pass the data object228    })229    .then(response => {230        if (response.ok) {231            return response.json();232        } else {233            throw new Error('Network response was not ok.');234        }235    })236    .then(responseData => {237        // Clear display, and display map rsults238        console.log("Attempting to display mapping results");239        toggleMap();240        clearChat();241        displayMessage(responseData.message, false);242        displayMap(responseData);243    })244    .catch(error => {245        console.error('Error:', error);246    });247}248function displayMap(responseData){249    // Select the chat area250    var chatList = document.querySelector(".chat");251 252    // Create new message element in the chat253    var messageElement = document.createElement("li");254    messageElement.className = "message";255    chatList.appendChild(messageElement);256 257    // Create new map element in the message element258    var mapContainer = document.createElement("iframe");259    mapContainer.srcdoc = responseData.map_html260    messageElement.appendChild(mapContainer);261}262 263 264// ============================== Chatbot ==============================265function sendRegularMessage(userInput) {266    var languageSelect = document.getElementById("language-select");267    var selectedLanguage = languageSelect.value;268 269    if (userInput.trim() !== "") {270        // Display user's message immediately271        displayMessage(userInput, true);272 273        // Display loading message for bot response274        displayMessage("...", false);275 276        // Send user's message and selected language to server using fetch277        fetch('/process_message', {278            method: 'POST',279            headers: {280                'Content-Type': 'application/json;charset=UTF-8'281            },282            body: JSON.stringify({ message: userInput, language: selectedLanguage })283        })284        .then(response => {285            if (response.ok) {286                return response.json();287            } else {288                throw new Error('Network response was not ok.');289            }290        })291        .then(responseData => {292            // Update bot's response293            updateBotResponse(responseData.response);294        })295        .catch(error => {296            console.error('Error:', error);297        });298 299        // Clear user input field300        document.getElementById("user-input").value = "";301    }302}303 304// Function to check if a message contains 'code block'305function hasCodeSnippet(message) {306    return /\```(?:[^```]+)\```/g.test(message);307}308 309// Function to convert message to HTML with code blocks310function convertMessageToHTML(message) {311    // Check if the message contains code snippets312    if (hasCodeSnippet(message)) {313        // Replace triple backticks with <pre><code> and </code></pre>314        message = message.replace(/```(.*?)```/gs, '<div class="code-wrapper"><pre><code>$1</code></pre></div>');315        return message316    } else {317        return message318    }319}320 321function updateBotResponse(botMessage) {322    // Find the loading message and replace it with the bot's response323    var loadingMessage = document.querySelector(".loading-message");324    if (loadingMessage) {325        loadingMessage.innerHTML = convertMessageToHTML(botMessage.trim());326        loadingMessage.classList.remove("loading-message");327    } else {328        // If loading message is not found, add the bot's response329        displayMessage(botMessage, false);330    }331}332 333function displayMessage(message, isUserMessage) {334    var chatList = document.querySelector(".chat");335 336    // Display user's message or bot's response337    var messageElement = document.createElement("li");338    if (hasCodeSnippet(message)){339        messageElement.innerHTML = convertMessageToHTML(message);340        messageElement.className = "message" + (isUserMessage ? " user-message" : " loading-message");341        chatList.appendChild(messageElement);342    } else {343        messageElement.innerHTML = message;344        messageElement.className = "message" + (isUserMessage ? " user-message" : " loading-message");345        chatList.appendChild(messageElement);346    }347}348 349// Helper function to display and update message350function updateAndDisplayMessage(message, isUserMessage){351    displayMessage(message, isUserMessage);352    updateBotResponse(message);353}354 355 356// ============================== New Chat ==============================357// Function to start new chat358function startNewChat() {359    mapEnabled = false; // Reset map flag to false360    spotifyEnabled = false; // Reset spotify flag to false361    updateButtons(spotifyEnabled,mapEnabled); // Update button highlighting362    showAdditionalButtons(); // Show the sample prompts363    clearChat();364    updateAndDisplayMessage("Hello, how can I assist you?", false);365 366    // Send a POST request to clear the conversation history on the server side367    fetch('/clear_history', {368        method: 'POST',369        headers: {370            'Content-Type': 'application/json;charset=UTF-8'371        }372    })373    .then(response => {374        if (response.ok) {375            console.log('Conversation history cleared.');376        } else {377            throw new Error('Failed to clear conversation history.');378        }379    })380    .catch(error => {381        console.error('Error:', error);382    });383    // Clear the audio player384    const player = document.getElementById('player');385    player.innerHTML = '';386}387 388// Helper function to clear chat container messages389function clearChat(){390    var chatList = document.querySelector(".chat");391    chatList.innerHTML = '';392}393 394// ============================== Speech Recognition ==============================395function startSpeechRecognition() {396    var recognition = new window.webkitSpeechRecognition(); // Create a new SpeechRecognition object397 398    recognition.lang = "en-US"; // Set language to English (United States)399 400    recognition.onresult = function(event) { // When speech recognition is successful401        var transcript = event.results[0][0].transcript; // Get the recognized transcript402        document.getElementById("user-input").value = transcript; // Set the transcript as user input403        sendMessage(); // Call sendMessage function to process the input404    };405 406    recognition.onerror = function(event) { // If there's an error in speech recognition407        console.error("Speech recognition error:", event.error);408        alert("Error occurred in speech recognition. Please try again."); // Show an error message409    };410 411    recognition.onstart = function() { // When speech recognition starts412        document.getElementById("record-button").classList.add("active"); // Add "active" class to record button413    };414 415    recognition.onend = function() { // When speech recognition ends416        document.getElementById("record-button").classList.remove("active"); // Remove "active" class from record button417    };418 419    recognition.start(); // Start speech recognition420}421 422// ============================== Instructions ==============================423const instructions = `Start Conversation: Type your message in the text box and press 'Send' to start a conversation with the chatbot.\n424Voice Input: Click 'Record Speech' to speak instead of typing. The chatbot will transcribe and respond to your voice message. \n425Language Selection: Use the dropdown menu to select your preferred language for communication with the chatbot. \n426New Chat: Click 'New Chat' to start a new conversation and clear the chat history. \n427Spotify: Click the spotify button to toggle functionality \n428Map: Click the map button to toggle mapping functionality\n`429// Function to display the instructions430function addInstructions() {431    startNewChat();432    updateAndDisplayMessage(instructions,false);433    hideAdditionalButtons();434}435 436 437// ============================== Buttons ==============================438// Function to update the spotify and map buttons439function updateButtons(spotifyEnabled,mapEnabled) {440    // Update spotify button441    const spotifyButton = document.getElementById("spotify-button");442    spotifyButton.classList.toggle("active", spotifyEnabled); // Add or remove "active" class443 444    // Update map button445    const mapButton = document.getElementById("map-button");446    mapButton.classList.toggle("active", mapEnabled); // Add or remove "active" class447}448// Function to hide additional buttons449function hideAdditionalButtons() {450    var additionalButtons = document.getElementById("additional-buttons");451    additionalButtons.style.display = "none";452}453// Function to show additional buttons454function showAdditionalButtons() {455    var additionalButtons = document.getElementById("additional-buttons");456    additionalButtons.style.display = "block";457}458// Function to handle sample buttons459function handleSample(button){460    const question = button.innerText.trim(); // Get the inner text of the button461    hideAdditionalButtons();462    sendRegularMessage(question);463}464// Function to allow user to press enter to submit465function handleKeyDown(event) {466    if (event.key === "Enter") {467        event.preventDefault(); // Prevents the default Enter key behavior (like adding a new line)468        sendMessage(); // Calls the sendMessage function when Enter is pressed469    }470}471