import { create_dataframe, create_selection, create_uploaded_file_radio, showSuccessMessage, showLoader, clearPreviousContent, resetContainers } from './methods.js'; $(document).ready(function () { // Add visibility to fade-in elements on scroll const fadeElements = document.querySelectorAll('.fade-in'); const elementInView = (el, percentageScroll = 100) => { const elementTop = el.getBoundingClientRect().top; return elementTop <= (window.innerHeight || document.documentElement.clientHeight) * (percentageScroll / 100); }; const displayFadeElement = (element) => { element.classList.add('visible'); }; const handleFadeAnimation = () => { fadeElements.forEach((el) => { if (elementInView(el)) { displayFadeElement(el); } }); }; window.addEventListener('scroll', () => { handleFadeAnimation(); }); // Initial check for elements already in view handleFadeAnimation(); function fetchDatasetData(df_name) { const csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); showLoader(true); $.ajax({ method: 'POST', url: '', headers: { 'X-CSRFToken': csrftoken }, data: { 'action': "dataset", 'df_name': df_name }, success: function (values) { showLoader(false); handleSuccessResponse(values); $("#new_or_load").show(); }, error: function (ret) { console.error("Failed to fetch dataset:", ret); } }); } function handleSuccessResponse(values) { if (!values) return; clearPreviousContent(); const ret = JSON.parse(values); const datasetType = ret["dataset_type"]; if (datasetType === "tabular") { setupTabularDataset(ret); } else if (datasetType === "timeseries") { setupTimeseriesDataset(ret); } } function setupTabularDataset(ret) { const { data_to_display: df, fig, features, feature1, feature2, labels, curlabel } = ret; const selection1 = create_selection(features, "feature1", null, feature1); const selection2 = create_selection(features, "feature2", null, feature2); const selection3 = create_selection(labels, "label", null, curlabel); const tb = create_dataframe(df, "df_container"); $("#model_container, #df, #df_stats").fadeIn(200); $("#df_div").append(tb); $("#selection").append(selection1, selection2, selection3); const figDiv = $("
", { id: 'stats_container', class: "plotly_fig" }).html(fig); $("#stats_div").append(figDiv); } function setupTimeseriesDataset(ret) { const { fig, fig1 } = ret; const figDiv = $("
", { id: 'ts_confidence_container', class: "plotly_fig" }).html(fig); const figDiv1 = $("
", { id: 'ts_stats_container', class: "plotly_fig" }).html(fig1); $("#ts_stats, #ts_confidence").fadeIn(200); $("#ts_stats_div").append(figDiv); $("#ts_confidence_div").append(figDiv1); } $('.btn-dataset').click(function (e) { const df_name = $(this).is('#upload') ? "upload" : $(this).attr('id'); $("#new_or_load_cached").hide(); resetContainers(); $("#upload_col").toggle(df_name === "upload"); $("#timeseries-datasets").toggle(df_name === "timeseries"); $(this).toggleClass("active").siblings().removeClass("active"); $(this).addClass("active"); const timeseries_dataset = df_name === "timeseries" ? $("input:radio[name=timeseries_dataset]:checked").val() : ""; if (timeseries_dataset || (df_name !== "timeseries")) { fetchDatasetData(timeseries_dataset || df_name); } }); }); document.getElementById("viewModelsButton").addEventListener("click", function () { // Prompt or redirect the user to the pre-trained models section window.location.href = "/charts.html"; // Replace with the actual URL }); $(document).ready(function () { $('#timeseries-datasets').change(function () { if ($("input[name=timeseries_dataset]:checked").length > 0) { var timeseries_dataset = $("input:radio[name=timeseries_dataset]:checked").val(); $("#df_container").hide(); $("#stats_container").hide(); $("#figs").hide(); $("#ts_confidence_cached").hide() $("#ts_stats_cached").hide() $("#ts_confidence").hide() $("#ts_stats").hide() var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $("#loader_ds").show(); $("#loader_stats").show(); $("#new_or_load").hide(); $("#new_or_load_cached").hide(); $.ajax({ method: 'POST', url: '', headers: { 'X-CSRFToken': csrftoken, }, data: { 'action': "timeseries-dataset", 'timeseries_dataset': timeseries_dataset }, success: function (values) { $("#loader_ds").hide(); $("#loader_stats").hide(); // fetch data // remove data if already displayed if (document.getElementById("df_container")) { $("#pretrained_radio").remove(); $("#df_container").remove(); $("#stats_container").remove(); $("#feature1").remove(); $("#feature2").remove(); $("#label").remove(); } $("#new_or_load").show(); if (document.getElementById("ts_confidence_container")) { $("#ts_confidence_container").remove(); $("#ts_stats_container").remove(); } var ret = JSON.parse(values) var dataset_type = ret["dataset_type"] if (values) { // timeseries // var feature = ret["feature"] var fig = ret["fig"] var fig1 = ret["fig1"] var iDiv = document.createElement('div'); iDiv.id = 'ts_confidence_container'; iDiv.innerHTML = fig; iDiv.setAttribute("class", "plotly_fig") var iDiv1 = document.createElement('div'); iDiv1.id = 'ts_stats_container'; iDiv1.innerHTML = fig1; iDiv1.setAttribute("class", "plotly_fig") $("#ts_stats").show(); $("#ts_confidence").show(); $("#ts_stats_div").append(iDiv); $("#ts_confidence_div").append(iDiv1); } }, error: function (ret) { console.log("All bad") } }); } }) }); // $(document).ready(function () { // $('#radio_buttons').change(function () { // if ($("input[name=uploaded_file]:checked").length > 0) { // var uploaded_dataset = $("input:radio[name=uploaded_file]:checked").val(); // if (document.getElementById("df_container")) { // $("#df").hide(); // $("#df_stats").hide(); // } // if (document.getElementById("df_cached")) { // $("#df_cached").hide() // $("#df_stats_cached").hide() // } // if (document.getElementById("ts_confidence")) { // $("#ts_confidence").hide() // $("#ts_stats").hide() // } // if (document.getElementById("ts_confidence_cached")) { // $("#ts_confidence_cached").hide() // $("#ts_stats_cached").hide() // } // $("#new_or_load").hide() // var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); // $("#loader_ds").show(); // $("#loader_stats").show(); // $.ajax({ // method: 'POST', // url: '', // headers: { 'X-CSRFToken': csrftoken, }, // data: { 'action': "uploaded_datasets", 'df_name': uploaded_dataset }, // success: function (values) { // $("#loader_ds").hide(); // $("#loader_stats").hide(); // $("#new_or_load").show() // // fetch data // // remove data if already displayed // if (document.getElementById("df_container")) { // $("#pretrained_radio").remove(); // $("#df_container").remove(); // $("#stats_container").remove(); // $("#feature1").remove(); // $("#feature2").remove(); // $("#label").remove(); // } // if (document.getElementById("df_cached")) { // $("#df_cached").remove() // $("#df_stats_cached").remove() // $("#ts_confidence_cached").remove() // $("#ts_stats_cached").remove() // } // if (document.getElementById("ts_confidence_container")) { // $("#ts_confidence_container").remove(); // $("#ts_stats_container").remove(); // } // var ret = JSON.parse(values) // var dataset_type = ret["dataset_type"] // if (values) { // if (dataset_type == "tabular") { // var df = ret["data_to_display"] // var fig = ret["fig"] // var features = ret["features"] // var feature1 = ret["feature1"] // var feature2 = ret["feature2"] // // cur labels // var labels = ret["labels"] // var curlabel = ret["curlabel"] // var selection1 = create_selection(features, "feature1", null, feature1) // var selection2 = create_selection(features, "feature2", null, feature2) // var selection3 = create_selection(labels, "label", null, curlabel) // // create table // var tb = create_dataframe(df, "df_container") // $("#model_container").show() // $("#df").show(); // $("#df_stats").show(); // // append new data // $("#df_div").append(tb); // $("#selection").append(selection1); // $("#selection").append(selection2); // $("#selection").append(selection3); // // append fig // var iDiv = document.createElement('div'); // iDiv.id = 'stats_container'; // iDiv.innerHTML = fig; // iDiv.setAttribute("class", "plotly_fig") // $("#stats_div").append(iDiv); // } else if (dataset_type == "timeseries") { // // timeseries // // var feature = ret["feature"] // var fig = ret["fig"] // var fig1 = ret["fig1"] // var iDiv = document.createElement('div'); // iDiv.id = 'ts_confidence_container'; // iDiv.innerHTML = fig; // iDiv.setAttribute("class", "plotly_fig") // var iDiv1 = document.createElement('div'); // iDiv1.id = 'ts_stats_container'; // iDiv1.innerHTML = fig1; // iDiv1.setAttribute("class", "plotly_fig") // $("#ts_stats").show(); // $("#ts_confidence").show(); // $("#ts_stats_div").append(iDiv); // $("#ts_confidence_div").append(iDiv1); // } // } // }, // error: function (ret) { // } // }); // } // }) // }); // $('#upload_btn').click(function (event) { // event.preventDefault(); // Prevent default form submission // var datasetType = $('input[name="dataset_type"]:checked').val(); // var fileInput = $('#doc')[0].files[0]; // var csrfToken = $('input[name="csrfmiddlewaretoken"]').val(); // if (!datasetType || !fileInput) { // alert('Please select a dataset type and choose a file to upload.'); // return; // } // // Use FormData to handle file upload // var formData = new FormData(); // formData.append('action', 'upload_dataset'); // formData.append('dataset_type', datasetType); // formData.append('excel_file', fileInput); // formData.append('csrfmiddlewaretoken', csrfToken); // $("#cfbtn_loader").show(); // $.ajax({ // url: '', // Replace with your Django view URL for uploading // type: 'POST', // data: formData, // processData: false, // Prevent jQuery from processing data // contentType: false, // Prevent jQuery from setting content type // success: function (response) { // try { // var ret = JSON.parse(response); // var df_name = ret["df_name"]; // var uploaded_files = ret["uploaded_files"]; // var counter = uploaded_files.length - 1; // // Add uploaded file to the list // alert("here") // $("#radio_buttons").append(create_uploaded_file_radio(df_name, counter)); // // Check if target_labels exist in the response // if (ret["target_labels"]) { // populateLabelModal(ret["target_labels"]); // Populate the modal for label selection // } // showSuccessMessage(); // } catch (error) { // console.error("Error processing response:", error); // alert("An error occurred while processing the upload response."); // } finally { // $("#cfbtn_loader").hide(); // } // }, // error: function (xhr, status, error) { // console.error("Error uploading:", status, error); // alert("An error occurred during upload. Please try again."); // $("#cfbtn_loader").hide(); // } // }); // }); // function populateLabelModal(targetLabels) { // const positiveDropdown = $("#positive-label"); // const negativeDropdown = $("#negative-label"); // const errorContainer = $("#selection-error"); // // Populate dropdowns // updateDropdownOptions(positiveDropdown, targetLabels, null); // updateDropdownOptions(negativeDropdown, targetLabels, null); // // Reset error message // errorContainer.addClass("d-none").text(""); // // Open the modal // $("#labelSelectionModal").modal({ // backdrop: 'static', // Prevent closing when clicking outside // keyboard: false // Prevent closing with "Escape" // }); // let selectedPositive = null; // let selectedNegative = null; // // Handle changes in positive dropdown // positiveDropdown.off("change").on("change", function () { // selectedPositive = $(this).val(); // updateDropdownOptions(negativeDropdown, targetLabels, selectedPositive, selectedNegative); // validateSelection(selectedPositive, selectedNegative); // }); // // Handle changes in negative dropdown // negativeDropdown.off("change").on("change", function () { // selectedNegative = $(this).val(); // updateDropdownOptions(positiveDropdown, targetLabels, selectedNegative, selectedPositive); // validateSelection(selectedPositive, selectedNegative); // }); // $("#save-label-choices").click(function (event) { // if (validateSelection(selectedPositive, selectedNegative, true)) { // var csrfToken = $('input[name="csrfmiddlewaretoken"]').val(); // var formData = new FormData(); // formData.append('action', 'select_class_labels_for_uploaded_timeseries'); // formData.append('positive_label', selectedPositive); // formData.append('negative_label', selectedNegative); // formData.append('csrfToken', csrfToken); // // Show loader // $("#loader_ds").removeClass("d-none"); // // Disable the Save button to prevent duplicate submissions // $("#save-label-choices").prop("disabled", true); // $.ajax({ // url: '', // Replace with your Django view URL for uploading // type: 'POST', // headers: { 'X-CSRFToken': csrfToken, }, // data: formData, // processData: false, // Prevent jQuery from processing data // contentType: false, // Prevent jQuery from setting content type // success: function (response) { // console.log('Labels saved successfully:', response); // // Hide loader // $("#loader_ds").addClass("d-none"); // // Enable the Save button // $("#save-label-choices").prop("disabled", false); // // Close the modal // $("#labelSelectionModal").modal("hide"); // // Optionally update the UI with the response // }, // error: function (xhr) { // const errorContainer = $("#selection-error"); // const errorMessage = xhr.responseJSON?.message || 'An error occurred while saving labels.'; // errorContainer.html(` ${errorMessage}`) // .removeClass("d-none"); // // Hide loader // $("#loader_ds").addClass("d-none"); // // Enable the Save button // $("#save-label-choices").prop("disabled", false); // } // }); // } // }); // /** // * Helper function to retrieve CSRF token. // * Assumes the CSRF token is stored in a cookie named 'csrftoken'. // * @returns {string} - CSRF token value. // */ // function getCSRFToken() { // const name = 'csrftoken'; // const cookies = document.cookie.split(';'); // for (let cookie of cookies) { // cookie = cookie.trim(); // if (cookie.startsWith(name + '=')) { // return cookie.substring(name.length + 1); // } // } // return ''; // } // } // /** // * Update dropdown options dynamically, excluding the currently selected value in the other dropdown. // * @param {jQuery} dropdown - The dropdown to update. // * @param {Array} options - The list of options to populate. // * @param {string|null} exclude - The value to exclude from the dropdown options. // * @param {string|null} currentValue - The current value of the dropdown being updated. // */ // function updateDropdownOptions(dropdown, options, exclude, currentValue = null) { // dropdown.empty(); // Clear existing options // // Add default placeholder // dropdown.append(''); // // Repopulate options, excluding the selected value from the other dropdown // options.forEach(option => { // if (option !== exclude) { // dropdown.append( // `` // ); // } // }); // // Reset dropdown if the current value is no longer valid // if (exclude === currentValue) { // dropdown.val(""); // } // } // /** // * Validate the selected positive and negative labels. // * @param {string|null} positive - The selected positive label. // * @param {string|null} negative - The selected negative label. // * @param {boolean} showError - Whether to show an error message on failure. // * @returns {boolean} - Returns true if the selection is valid, otherwise false. // */ // function validateSelection(positive, negative, showError = false) { // const errorContainer = $("#selection-error"); // if (!positive || !negative) { // if (showError) { // errorContainer.text("You must select both a positive and a negative label!").removeClass("d-none"); // } // return false; // } // if (positive === negative) { // if (showError) { // errorContainer.text("Positive and Negative labels must be different!").removeClass("d-none"); // } // return false; // } // // Clear error if valid // errorContainer.addClass("d-none").text(""); // return true; // } document.getElementById("selection").addEventListener("change", function (e) { var feature1 = document.getElementById("feature1").value var feature2 = document.getElementById("feature2").value var label = document.getElementById("label").value var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $("#stats_container").remove() $('#loader_stats').show() $.ajax({ method: 'POST', url: '', headers: { 'X-CSRFToken': csrftoken, }, data: { 'action': "stat", 'feature1': feature1, 'feature2': feature2, 'label': label }, success: function (ret) { $('#loader_stats').hide() var ret = JSON.parse(ret) var fig = ret["fig"] var iDiv = document.createElement('div'); iDiv.id = 'stats_container'; iDiv.insertAdjacentHTML('beforeend', fig); $("#stats_div").append(iDiv); }, error: function (ret) { } }); }); if (document.getElementById("selection_cached")) { document.getElementById("selection_cached").addEventListener("change", function (e) { var feature1 = document.getElementById("feature1_cached").value var feature2 = document.getElementById("feature2_cached").value var label = document.getElementById("label_cached").value var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $("#stats_container_cached").html("") $('#loader_stats_cached').show() $.ajax({ method: 'POST', url: '', headers: { 'X-CSRFToken': csrftoken, }, data: { 'action': "stat", 'feature1': feature1, 'feature2': feature2, 'label': label }, success: function (ret) { $('#loader_stats_cached').hide() var ret = JSON.parse(ret) var fig = ret["fig"] var iDiv = document.createElement('div'); iDiv.id = 'stats_container_cached'; iDiv.insertAdjacentHTML('beforeend', fig); $("#stats_container_cached").html(fig) // $("#stats_container_cached").append(iDiv); }, error: function (ret) { } }); }); }