Code viewer for World: POOJA_SALGAR_HELLO_WORLD
//Sample hello world to demostrate API CALL
// ===================================================================================================================
// ==== Assignment 2 | Part 2  ========================================================================================
/*
        STUDENT NAME:       POOJA NAMDEV SALGAR
        STUDENT NUMBER:     23267148
        STUDENT EMAIL:      pooja.salgar2@dcu.mail.ie
        MODULE NAME:        Foundations of AI (online)
        MODULE CODE:        CA686I
    

*/
// ===================================================================================================================
// ======================


//===================================body====================================================================================
//Sets CSS styles for the <body> element of the webpage
$('body').css({
    "background-image": "url('https://ancientbrain.com/uploads/pooja20/bright-yellow-brick.jpg')", //https://www.shopify.com/stock-photos/photos/bright-yellow-brick?c=color-backgrounds
    "background-size": "cover",
    "background-repeat": "no-repeat",
    "background-attachment": "fixed",
    "background-position": "center",
    "margin": "0",
    "padding": "70px",
    "text-align": "center"
});

//=================================================================================================================================================================
//Dynamically write HTML content into the document

document.write(`
    <h1>HELLO WORLD</h1>
    <div style="margin-bottom: 20px;">
        <h3>Enter API key</h3>
        <input style='width:25vw;' id="apikey" placeholder="Enter API Key" />
        <button onclick='setkey();'>Set API key</button>
    </div>

    <div style="display: flex; justify-content: center; align-items: center;">
        <div style="width:40vw; background-color:#FFFFFF; padding: 20px; border: 1px solid black;">
            <h3>Wait for reply!!</h3>
            <div id="output"></div>
        </div>
    </div>
`);

//==========================================================================================================================
//URLs for OpenAI Text and Image Generation APIs

// MH edit 
// "https://api.openai.com/v1/chat/completions"; 

const openaiURL =   "https://api.openai.com/v1/engines/text-davinci-003/completions";
const imageGenerationApiURL = "https://api.openai.com/v1/images/generations";

//Reference to the output div
output1=document.getElementById("output");

//==============================================================================================================================
//Function to set the API key and trigger API requests

function setkey() {
    let apiKey = document.getElementById("apikey").value;
    if (!apiKey) {
        displayError("Please enter an API key to continue.");
        return;
    }

    // Pass the apiKey to sendRequestToOpenAI
    sendRequestToOpenAI(apiKey);
}

//=============================================================================================================================================
//Function to send a request to OpenAI's GPT-3 API
function sendRequestToOpenAI(apiKey) {
    const data = {
        prompt: "prompt1",
        max_tokens: 1024,
        temperature: 0.7
    };

// AJAX POST request to the GPT-3 API
    $.ajax({
        type: "POST",
        url: openaiURL,
        data: JSON.stringify(data),
        headers: {
            "Authorization": `Bearer ${apiKey}`,
            "Content-Type": "application/json"
        },
        success: function (response) {
            // Handle the response from GPT-3
            const recipeText = response.choices[0].text.trim();
            createImageEdit(apiKey);
            console.log("Connection successful to ChatGPT");
              output1.textContent="connection successful to CHATGPT";
        },
        error: function (xhr) {
            
            // Handle errors from the GPT-3 API request
            displayError("Failed to generate recipe. Please try again.");
        }
    });
}

//====================================================================================================================================

// Function to send a request to OpenAI's Image Generation API

async function createImageEdit(api) {
    
   
    const imageGenerationApiURL = "https://api.openai.com/v1/images/generations";
  //  const apiKey = "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";
  
  try {
    const imageres = await fetch(imageGenerationApiURL,
     // Replace with the actual API endpoint
      {
          method:'post',
          headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${api}`,

                    },
        body:JSON.stringify({
            model:'dall-e-2',
            prompt:"testing",
            n:1,
            size: '1024x1024',
        
            
        })
        
       
      }
      
      
    );
    const getdata=await imageres.json();
    const getimage = getdata.data[0].url;
    //display_image.src=getimage;
    console.log("connection successful to DALL_E");
   output1.textContent = "Connection successful to chatgpt and \n Connection successful to DALL_E";

    //console.log('Edited Image URL:', imageUrl);
  } catch (error) {
      
      // Handle errors from the Image Generation API request
    console.error('Error:', error.message);
  }
}

//=====================================================================================================================================================s
// Function to display error messages

function displayError(message) {
    $("#response-container").html(`<span class="error">${message}</span>`);
}