<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      document.getElementById('json-error-message').textContent = '';
      // Function to fetch data and update the textarea
      function fetchDataAndUpdateTextarea() {
        const taskValue = document.getElementById('task').value;
        document.getElementById('params').value = 'Loading...';
        fetch(`/params/${taskValue}`)
          .then(response => response.json())
          .then(data => {
            document.getElementById('params').value = JSON.stringify(data, null, 2);
          })
          .catch(error => console.error('Error:', error));
      }
      function fetchDataAndUpdateModels() {
        const taskValue = document.getElementById('task').value;
        const baseModelSelect = document.getElementById('base_model');
        baseModelSelect.innerHTML = 'Fetching models...';
        fetch(`/model_choices/${taskValue}`)
          .then(response => response.json())
          .then(data => {
            const baseModelSelect = document.getElementById('base_model');
            baseModelSelect.innerHTML = ''; // Clear existing options
            data.forEach(model => {
              let option = document.createElement('option');
              option.value = model.id; // Assuming each model has an 'id'
              option.textContent = model.name; // Assuming each model has a 'name'
              baseModelSelect.appendChild(option);
            });
          })
          .catch(error => console.error('Error:', error));
      }

      // Function to validate JSON in the textarea
      function validateJSON() {
        try {
          JSON.parse(document.getElementById('params').value);
          document.getElementById('error-message').textContent = '';
        } catch (e) {
          document.getElementById('error-message').textContent = 'Invalid parameters: ' + e.message;
        }
      }
      function pollAccelerators() {
        // Send a request to the /accelerators endpoint
        fetch('/accelerators')
          .then(response => response.json()) // Assuming the response is in JSON format
          .then(data => {
            // Update the paragraph with the number of accelerators
            document.getElementById('num_accelerators').innerText = `Accelerators: ${data.accelerators}`;
          })
          .catch(error => {
            console.error('Error:', error);
            // Update the paragraph to show an error message
            document.getElementById('num_accelerators').innerText = 'Accelerators: Error fetching data';
          });
      }
      function pollModelTrainingStatus() {
        // Send a request to the /is_model_training endpoint
        fetch('/is_model_training')
          .then(response => response.json()) // Assuming the response is in JSON format
          .then(data => {
            // Construct the message to display
            let message = data.model_training ? 'Running jobs: ' + data.pids.join(', ') : 'No running jobs';

            // Update the paragraph with the status of model training
            let statusParagraph = document.getElementById('is_model_training');
            statusParagraph.innerText = message;

            // Change the text color based on the model training status
            if (data.model_training) {
              // Set text color to red if jobs are running
              statusParagraph.style.color = 'red';
            } else {
              // Set text color to green if no jobs are running
              statusParagraph.style.color = 'green';
            }
          })
          .catch(error => {
            console.error('Error:', error);
            // Update the paragraph to show an error message
            let statusParagraph = document.getElementById('is_model_training');
            statusParagraph.innerText = 'Error fetching training status';
            statusParagraph.style.color = 'red'; // Set error message color to red
          });
      }


      setInterval(pollAccelerators, 10000);
      setInterval(pollModelTrainingStatus, 5000);

      // Event listener for dropdown changes
      document.getElementById('task').addEventListener('change', fetchDataAndUpdateTextarea);
      document.getElementById('task').addEventListener('change', fetchDataAndUpdateModels);

      // Event listener for textarea changes
      document.getElementById('params').addEventListener('blur', validateJSON);

      // Initial call to populate the textarea when the page loads
      fetchDataAndUpdateTextarea();
      fetchDataAndUpdateModels();
      pollAccelerators();
      pollModelTrainingStatus();
    });
  </script>
</head>

<body>
  <header class="bg-white-800 text-white p-4">
    <div class="container mx-auto flex justify-between items-center">
      <img src="/static/logo.png" alt="AutoTrain" , class="w-32">
    </div>
  </header>
  <div class="form-container max-w-5xl mx-auto mt-3 p-6 shadow-2xl">
    <div class="block text-sm font-normal text-gray-700">AutoTrain Advanced is a no-code solution that
      allows you to train machine learning models in just a few clicks. Please note that you must upload data in correct
      format for project to be created.
      For help regarding proper data format and pricing, click <a href="https://hf.co/docs/autotrain" target="_blank"
        class="text-blue-700">here</a>.
    </div>
    <hr class="h-px my-4 bg-gray-200 border-b-2 dark:bg-gray-700">
    <form action="#" method="post" class="grid grid-cols-2 gap-2" enctype="multipart/form-data">
      <div>
        <div class="columns-2 mb-2">
          <div class="form-group">
            <label for="autotrain_user" class="text-sm font-medium text-gray-700">Hugging Face User
              <button type="button" id="autotrain_user_info" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-info-circle"></i>
              </button>
            </label>
            <select name="autotrain_user" , id="autotrain_user"
              class="mt-1 block w-full border border-gray-300 px-3 py-2 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
              {% for user in valid_users %}
              <option value="{{ user }}">{{ user }}</option>
              {% endfor %}
            </select>
            <label for="project_name" class="text-sm font-medium text-gray-700">Project name
              <button type="button" id="project_name_info" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-info-circle"></i>
              </button>
            </label>
            <input type="text" name="project_name" id="project_name"
              class="mt-1 block w-full border border-gray-300 px-3 py-1.5 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
              placeholder="eg: imdb-sentiment-analysis">
          </div>
        </div>
        <div class="columns-2 mb-2">
          <div class="form-group">
            <label for="hardware" class="text-sm font-medium text-gray-700">Hardware
              <button type="button" id="hardware_info" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-info-circle"></i>
              </button>
            </label>
            <select id="hardware" name="hardware"
              class="mt-1 block w-full border border-gray-300 px-3 py-2 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
              {% if enable_local == 1 %}
              <option value="Local">Local</option>
              {% else %}
              <optgroup label="Hugging Face Spaces">
                <option value="A10G Large">A10G Large</option>
                <option value="A100 Large">A100 Large</option>
                <option value="A10G Small">A10G Small</option>
                <option value="T4 Medium">T4 Medium</option>
                <option value="T4 Small">T4 Small</option>
                <option value="CPU Upgrade">CPU Upgrade</option>
                <option value="CPU (Free)">CPU (Free)</option>
              </optgroup>
              <optgroup label="Hugging Face Endpoints">
                <option value="EP US-East-1 1xA10g">1xA10G</option>
                <option value="EP US-East-1 1xA100">1xA100</option>
                <option value="EP US-East-1 2xA100">2xA100</option>
                <option value="EP US-East-1 4xA100">4xA100</option>
                <option value="EP US-East-1 8xA100">8xA100</option>
              </optgroup>
              {% if enable_ngc == 1 %}
              <optgroup label="NVIDIA DGX Cloud">
                <option value="DGX 1xA100">1xA100 DGX</option>
                <option value="DGX 2xA100">2xA100 DGX</option>
                <option value="DGX 4xA100">4xA100 DGX</option>
                <option value="DGX 8xA100">8xA100 DGX</option>
              </optgroup>
              {% endif %}
              {% if enable_nvcf == 1 %}
              <optgroup label="NVIDIA Cloud Functions">
                <option value="NVCF 1xA10G">1xA10G</option>
                <option value="NVCF 1xL40">1xL40</option>
                <option value="NVCF 1xL40G">1xL40G</option>
                <option value="NVCF 1xT10">1xT10</option>
              </optgroup>
              {% endif %}
              {% endif %}
            </select>
          </div>
          <div class="form-group">
            <label for="task" class="text-sm font-medium text-gray-700">Task
              <button type="button" id="task_info" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-info-circle"></i>
              </button>
            </label>
            <select id="task" name="task"
              class="mt-1 block w-full border border-gray-300 px-3 py-2 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
              <optgroup label="LLM Finetuning">
                <option value="llm:sft">LLM SFT</option>
                <option value="llm:generic">LLM Generic</option>
                <option value="llm:dpo">LLM DPO</option>
                <option value="llm:reward">LLM Reward</option>
              </optgroup>
              <optgroup label="Other Text Tasks">
                <option value="text-classification">Text Classification</option>
                <option value="seq2seq">Sequence To Sequence</option>
                <option value="token-classification">Token Classification</option>
              </optgroup>
              <optgroup label="Image Tasks">
                <option value="dreambooth">DreamBooth LoRA</option>
                <option value="image-classification">Image Classification</option>
              </optgroup>
              <optgroup label="Tabular Tasks">
                <option value="tabular:classification">Tabular Classification</option>
                <option value="tabular:regression">Tabular Regression</option>
              </optgroup>
            </select>
          </div>
        </div>
        <div class="form-group mb-2">
          <label for="base_model" class="text-sm font-medium text-gray-700">Base Model
            <button type="button" id="base_model_info" class="text-gray-500 hover:text-gray-700">
              <i class="fas fa-info-circle"></i>
            </button>
          </label>
          <select name="base_model" id="base_model"
            class="mt-1 block w-full border border-gray-300 px-3 py-2 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
          </select>
        </div>
        <div class="form-group mb-2">
          <div class="mb-4">
            <ul class="flex flex-wrap -mb-px text-sm font-medium text-center" id="default-tab"
              data-tabs-toggle="#default-tab-content" role="tablist">
              <li class="me-2" role="presentation">
                <button class="inline-block p-4 border-b-2 rounded-t-lg" id="training-data-tab"
                  data-tabs-target="#training-data" type="button" role="tab" aria-controls="training-data"
                  aria-selected="false">Training Data</button>
              </li>
              <li class="me-2" role="presentation">
                <button class="inline-block p-4 border-b-2 rounded-t-lg" id="valid-data-tab"
                  data-tabs-target="#valid-data" type="button" role="tab" aria-controls="valid-data"
                  aria-selected="false">Validation Data
                  (optional)</button>
              </li>
            </ul>
          </div>
          <div id="default-tab-content">
            <div class="hidden p-4 rounded-lg" id="training-data" role="tabpanel" aria-labelledby="training-data-tab">
              <div class="flex items-center justify-center w-full h-20">
                <label for="data_files_training"
                  class="flex flex-col items-center justify-center w-full h-40cursor-pointer">
                  <div class="flex flex-col items-center justify-center pt-5 pb-6">
                    <svg class="w-8 h-8 mb-4 text-gray-700" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"
                      fill="none" viewBox="0 0 20 16">
                      <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M13 13h3a3 3 0 0 0 0-6h-.025A5.56 5.56 0 0 0 16 6.5 5.5 5.5 0 0 0 5.207 5.021C5.137 5.017 5.071 5 5 5a4 4 0 0 0 0 8h2.167M10 15V6m0 0L8 8m2-2 2 2" />
                    </svg>
                    <p class="mb-2 text-sm text-gray-700"><span class="font-semibold">Upload Training File(s)
                        <p class="text-xs text-gray-700" id="file-container-training"></p>
                  </div>
                  <input id="data_files_training" name="data_files_training" type="file" multiple class="hidden" />
                </label>
              </div>
            </div>
            <div class="hidden p-4 rounded-lg" id="valid-data" role="tabpanel" aria-labelledby="valid-data-tab">
              <div class="flex items-center justify-center w-full h-20">
                <label for="data_files_valid"
                  class="flex flex-col items-center justify-center w-full h-40 cursor-pointer">
                  <div class="flex flex-col items-center justify-center pt-5 pb-6">
                    <svg class="w-8 h-8 mb-4 text-gray-700" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"
                      fill="none" viewBox="0 0 20 16">
                      <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M13 13h3a3 3 0 0 0 0-6h-.025A5.56 5.56 0 0 0 16 6.5 5.5 5.5 0 0 0 5.207 5.021C5.137 5.017 5.071 5 5 5a4 4 0 0 0 0 8h2.167M10 15V6m0 0L8 8m2-2 2 2" />
                    </svg>
                    <p class="mb-2 text-sm text-gray-700"><span class="font-semibold">Upload Validation File(s)
                        <p class="text-xs text-gray-700" id="file-container-valid"></p>
                  </div>
                  <input id="data_files_valid" name="data_files_valid" type="file" multiple class="hidden" />
                </label>
              </div>
            </div>
          </div>
        </div>
        <div class="columns-1" id="text_label">
          <label for="column_mapping" class="text-sm font-medium text-gray-700">Column mapping
            <button type="button" id="column_mapping_info" class="text-gray-500 hover:text-gray-700">
              <i class="fas fa-info-circle"></i>
            </button>
          </label>
          <input type="text" name="column_mapping" id="column_mapping"
            class="mt-1 block w-full border border-gray-300 px-3 py-2 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
        </div>
        <div class="form-actions mt-6">
          <button type="submit"
            class="w-full px-4 py-2 text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:bg-blue-700">Start
            Training</button>
        </div>
        <div class="mt-5">
          <p class="mb-2 text-sm text-gray-700" id="num_accelerators">Accelerators: Fetching...</p>
        </div>
      </div>
      <div>
        <div class="form-group">
          <label for="params" class="text-sm font-medium text-gray-700">Training Parameters (find params to
            copy-paste <a class="text-sm font-medium text-blue-700" href="#">here</a>)
            <button type="button" id="params_info" class="text-gray-500 hover:text-gray-700">
              <i class="fas fa-info-circle"></i>
            </button>
          </label>
          <textarea id="params" name="params" rows="25" class="p-2.5 w-full text-sm text-gray-900"
            placeholder="Loading..."></textarea>
        </div>
        <div class="mt-5">
          <p class="mb-2 text-sm text-gray-700 text-right font-bold" id="is_model_training">Fetching training status...
          </p>
        </div>
      </div>
    </form>
    <div id="json-error-message" style="color: red;"></div>
    <div id="error-message" style="color: red;"></div>
    <div id="success-message" style="color: green;"></div>
    <div id="loadingSpinner" role="status" class="hidden absolute -translate-x-1/2 -translate-y-1/2 top-2/4 left-1/2">
      <!-- <svg aria-hidden="true" class="w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/><path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/></svg> -->
      <div class="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
      <span class="sr-only">Loading...</span>
    </div>
    <div class="hidden justify-center items-center">
      <div class="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
    </div>
    <div id="confirmation-modal" tabindex="-1"
      class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
      <div class="relative p-4 w-full max-w-md max-h-full">
        <div class="relative bg-white rounded-lg shadow-2xl">
          <div class="p-4 md:p-5 text-center">
            <h3 class="mb-5 text-sm font-normal text-gray-800">AutoTrain is a paid offering and you will be charged for
              this action. You can ignore this message if you are running AutoTrain on a local hardware. Are you sure
              you want to continue?</h3>
            <button data-modal-hide="confirmation-modal" type="button"
              class="confirm text-white bg-green-600 hover:bg-green-800 focus:ring-4 focus:outline-none focus:ring-green-300font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center me-2">
              Yes, I'm sure
            </button>
            <button data-modal-hide="confirmation-modal" type="button"
              class="cancel text-white bg-red-600 hover:bg-red-100 focus:ring-4 focus:outline-none focus:ring-red-200 rounded-lg border border-red-200 text-sm font-medium px-5 py-2.5 hover:text-red-900 focus:z-10">No,
              cancel</button>
          </div>
        </div>
      </div>
    </div>
    <div id="final-modal" tabindex="-1"
      class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
      <div class="relative p-4 w-full max-w-md max-h-full">
        <div class="relative bg-white rounded-lg shadow-2xl">
          <button type="button"
            class="absolute top-3 end-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white"
            data-modal-hide="final-modal">
            <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
              <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
            </svg>
            <span class="sr-only">Close</span>
          </button>
          <div class="p-4 md:p-5 text-center">
            <h3 class="mb-5 text-sm font-normal text-gray-800"></h3>
          </div>
        </div>
      </div>
    </div>

    <div id="help-modal" tabindex="-1"
      class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
      <div class="relative p-4 w-full max-w-md max-h-full">
        <div class="relative bg-white rounded-lg shadow-2xl">
          <br>
          <button type="button"
            class="absolute top-3 end-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white"
            data-modal-hide="help-modal">
            <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
              <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
            </svg>
            <span class="sr-only">Close</span>
          </button>
          <div class="p-4 md:p-5 text-center">
            <h3 class="mb-5 text-sm font-normal text-gray-800"></h3>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
</body>

<script>
  async function openHelpModal(contentId) {
    const modal = document.getElementById('help-modal');
    var helpModalContent = document.querySelector('#help-modal .text-center');

    try {
      const response = await fetch(`/help/${contentId}`);
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      const data = await response.json();

      helpModalContent.innerHTML = data.message;

      modal.classList.remove('hidden');
    } catch (error) {
      console.error('There has been a problem with your fetch operation:', error);
    }
  }

  document.getElementById('autotrain_user_info').addEventListener('click', function () {
    openHelpModal('autotrain_user_info');
  });

  document.getElementById('project_name_info').addEventListener('click', function () {
    openHelpModal('project_name_info');
  });

  document.getElementById('hardware_info').addEventListener('click', function () {
    openHelpModal('hardware_info');
  });

  document.getElementById('task_info').addEventListener('click', function () {
    openHelpModal('task_info');
  });

  document.getElementById('base_model_info').addEventListener('click', function () {
    openHelpModal('base_model_info');
  });

  document.getElementById('column_mapping_info').addEventListener('click', function () {
    openHelpModal('column_mapping_info');
  });

  document.getElementById('params_info').addEventListener('click', function () {
    openHelpModal('params_info');
  });

  // Close modal functionality
  document.querySelector('[data-modal-hide="help-modal"]').addEventListener('click', function () {
    document.getElementById('help-modal').classList.add('hidden');
  });

</script>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    var taskSelect = document.getElementById('task');
    var columnMappingInput = document.getElementById('column_mapping');

    // Function to update the placeholder based on the selected task
    function updateColumnMapping() {
      var selectedTask = taskSelect.value;
      var placeholderText = '';
      var isDisabled = false;

      switch (selectedTask) {
        case 'llm:sft':
          placeholderText = '{"text": "text"}';
          break;
        case 'llm:generic':
          placeholderText = '{"text": "text"}';
          break;
        case 'llm:dpo':
          placeholderText = '{"prompt": "prompt", "text": "text", "rejected_text": "rejected_text"}';
          break;
        case 'llm:reward':
          placeholderText = '{"text": "text", "rejected_text": "rejected_text"}';
          break;
        case 'text-classification':
          placeholderText = '{"text": "text", "label": "target"}';
          break;
        case 'token-classification':
          placeholderText = '{"text": "tokens", "label": "tags"}';
          break;
        case 'seq2seq':
          placeholderText = '{"text": "text", "label": "target"}';
          break;
        case 'dreambooth':
          placeholderText = '{"image": "image"}';
          isDisabled = true;
          break;
        case 'image-classification':
          placeholderText = '{"image": "image", "label": "label"}';
          isDisabled = true;
          break;
        case 'tabular:classification':
          placeholderText = '{"id": "id", "label": ["target"]}';
          break;
        case 'tabular:regression':
          placeholderText = '{"id": "id", "label": ["target"]}';
          break;
        default:
          placeholderText = 'Enter column mapping...';
      }

      columnMappingInput.value = placeholderText;
      columnMappingInput.disabled = isDisabled;
    }

    taskSelect.addEventListener('change', function () {
      updateColumnMapping();
    });
    updateColumnMapping();
  });

</script>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const taskSelect = document.getElementById('task');
    const validDataTab = document.getElementById('valid-data-tab');

    function toggleValidationTab() {
      const task = taskSelect.value;
      // Check if the selected task is DreamBooth or any LLM task
      if (task === 'dreambooth' || task.includes('llm:')) {
        validDataTab.style.display = 'none'; // Hide the tab
      } else {
        validDataTab.style.display = 'block'; // Show the tab
      }
    }

    // Initialize the state of the validation tab
    toggleValidationTab();

    // Add event listener for changes in the task dropdown
    taskSelect.addEventListener('change', toggleValidationTab);
  });

</script>

<script>
  // Function to hide all tab contents
  function hideAllTabContents() {
    document.querySelectorAll('#default-tab-content > div').forEach(function (tabContent) {
      tabContent.classList.add('hidden');
    });
  }

  // Function to deactivate all tabs
  function deactivateAllTabs() {
    document.querySelectorAll('#default-tab > li > button').forEach(function (tabButton) {
      tabButton.classList.remove('border-b-2', 'rounded-t-lg');
      tabButton.setAttribute('aria-selected', 'false');
    });
  }

  // Function to activate a tab
  function activateTab(tabButton, tabContent) {
    // Hide all tab contents and deactivate all tabs
    hideAllTabContents();
    deactivateAllTabs();

    // Show the selected tab content and activate the tab
    tabContent.classList.remove('hidden');
    tabButton.classList.add('border-b-2', 'rounded-t-lg');
    tabButton.setAttribute('aria-selected', 'true');
  }

  // Event listeners for tab buttons
  document.querySelector('#training-data-tab').addEventListener('click', function () {
    activateTab(this, document.querySelector('#training-data'));
  });

  document.querySelector('#valid-data-tab').addEventListener('click', function () {
    activateTab(this, document.querySelector('#valid-data'));
  });

  // Initialize by showing the first tab
  activateTab(document.querySelector('#training-data-tab'), document.querySelector('#training-data'));

</script>

<script type="module">
  import { uploadFiles, createRepo } from 'https://cdn.jsdelivr.net/npm/@huggingface/hub@0.12.1/+esm'
  document.addEventListener("DOMContentLoaded", function () {
    document.getElementById('success-message').textContent = '';
    document.getElementById('error-message').textContent = '';
    // Select the form element
    const form = document.querySelector('form');
    // Select the loading spinner
    const loadingSpinner = document.getElementById('loadingSpinner');

    // Function to show the modal
    function showFinalModal() {
      const modal = document.getElementById('final-modal');
      modal.classList.add('flex');
      modal.classList.remove('hidden');
    }

    // Function to hide the modal
    function hideFinalModal() {
      const modal = document.getElementById('final-modal');
      modal.classList.remove('flex');
      modal.classList.add('hidden');
    }

    // Function to show the modal
    function showModal() {
      const modal = document.getElementById('confirmation-modal');
      modal.classList.add('flex');
      modal.classList.remove('hidden');
    }

    // Function to hide the modal
    function hideModal() {
      const modal = document.getElementById('confirmation-modal');
      modal.classList.remove('flex');
      modal.classList.add('hidden');
    }

    // Add an event listener for the form submission
    form.addEventListener('submit', async function (event) {
      // Prevent the default form submission
      event.preventDefault();
      showModal();
    });

    document.querySelector('#confirmation-modal .confirm').addEventListener('click', async function () {
      hideModal();
      loadingSpinner.classList.remove('hidden');

      // Confirmation dialog
      // const userConfirmed = window.confirm("AutoTrain is a paid service and you will be charged. Confirm to continue!");
      // if (!userConfirmed) {
      //     return; // Stop the function if the user did not confirm
      // }

      // Show the loading spinner
      loadingSpinner.classList.remove('hidden');

      // Get form data
      const formData = new FormData(form);

      // Extract necessary data for Hugging Face
      const token = formData.get('token');
      const username = formData.get('username');
      const project_name = formData.get('project_name');
      const train_files = formData.getAll('data_files_training');
      const valid_files = formData.getAll('data_files_valid');

      // Prepare credentials and repo information for Hugging Face
      const credentials = { accessToken: token };
      const repo = { type: 'model', name: `${username}/autotrain-data-${project_name}` };

      // Upload files to Hugging Face Hub
      // MODIFY for training and valid files both
      // try {
      //     await createRepo({
      //       repo: repo,
      //       credentials: credentials,
      //       private: true,
      //     });
      //     for (let file of files) {
      //         await uploadFiles({
      //             repo,
      //             credentials,
      //             files: [{
      //                 path: file.name,
      //                 content: file
      //             }],
      //         });
      //     }
      //     console.log('Files uploaded to Hugging Face Hub successfully');
      //     document.getElementById('success-message').textContent = 'Uploaded files to Hugging Face Hub successfully';
      // } catch (error) {
      //     console.error('Error uploading files to Hugging Face Hub:', error);
      //     // Hide the loading spinner and return to stop further processing
      //     document.getElementById('error-message').textContent = 'Error uploading files to Hugging Face Hub: ' + error.message;
      //     loadingSpinner.classList.add('hidden');
      //     return;
      // }

      // Send request to internal API
      const xhr = new XMLHttpRequest();
      xhr.open('POST', '/create_project', true); // Replace '/create_project' with your FastAPI endpoint URL

      // Handle the response
      xhr.onload = function () {
        // Hide the loading spinner
        loadingSpinner.classList.add('hidden');
        var finalModalContent = document.querySelector('#final-modal .text-center');

        if (xhr.status === 200) {
          console.log('Response:', xhr.responseText);
          var responseObj = JSON.parse(xhr.responseText);
          var monitorURL = responseObj.monitor_url;
          finalModalContent.innerHTML = '<p>Success!</p>' +
            '<p>You can check the progress of your training here: <a href="' + monitorURL + '" target="_blank">' + monitorURL + '</a></p>';

          showFinalModal();
        } else {
          // Error logic here
          finalModalContent.innerHTML = '<p>Error: ' + xhr.status + ' ' + xhr.statusText + '</p>' + '<p> Please check the logs for more information.</p>';
          console.error('Error:', xhr.status, xhr.statusText);
          showFinalModal();
        }
      };

      // Send the request with the FormData object
      xhr.send(formData);
    });
    document.querySelector('#confirmation-modal .cancel').addEventListener('click', function () {
      hideModal();
    });
    document.querySelector('#final-modal button').addEventListener('click', function () {
      hideFinalModal();
    });
  });
</script>

<script>
  document.getElementById('data_files_training').addEventListener('change', function () {
    var fileContainer = document.getElementById('file-container-training');
    var files = this.files;
    var fileText = '';

    for (var i = 0; i < files.length; i++) {
      fileText += files[i].name + ' ';
    }

    fileContainer.innerHTML = fileText;
  });
  document.getElementById('data_files_valid').addEventListener('change', function () {
    var fileContainer = document.getElementById('file-container-valid');
    var files = this.files;
    var fileText = '';

    for (var i = 0; i < files.length; i++) {
      fileText += files[i].name + ' ';
    }

    fileContainer.innerHTML = fileText;
  });
</script>
<script>
  // Function to generate a random alphanumeric string
  function generateRandomString(length) {
    let result = '';
    const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
  }

  // Function to set a random project name
  function setRandomProjectName() {
    // Generate parts of the string
    const part1 = generateRandomString(5);
    const part2 = generateRandomString(5);

    // Combine parts with hyphens
    const randomName = `autotrain-${part1}-${part2}`;

    // Set the value of the project_name input field
    document.getElementById('project_name').value = randomName;
  }

  // Call the function on page load
  window.onload = setRandomProjectName;
</script>

</html>