Code viewer for World: CA 686 Assignment 2 P5 Ani...
const openaiURL = "https://api.openai.com/v1/chat/completions";           
const themodel = "gpt-3.5-turbo";       
var apikey = "";
var theprompt = "hello";


 //Makarand : adding a new font 

  $('body').css( "margin", "20px" );
  $('body').css("color","#181818")
  $('body').css( "padding", "20px" );
  $('body').css("font-family","Poppins")
  $("head").append(`<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">`);


 
//Makarand: Added some additional CSS and Temperature control slider
//credits for temprature slider : https://www.w3schools.com/howto/howto_js_rangeslider.asp

document.write(`


<div style='margin-top: 50px; padding: 20px; text-align: center;'>


  <h1> 2D Animation Generator with Chat GPT</h1>

  <div id="enterkey" style="margin-bottom: 20px;">
    <h4>Enter API key</h4>
    <input style="width: 25vw; padding: 8px;border : 1px solid darkgrey" maxlength="2000" name="apikey" id="apikey" value="">
    <button onclick="setkey();"  style="display: inline;padding: 10px 10px;border-width: 0;outline: none;border-radius: 2px;background-color: #1D1D1D;color: #ecf0f1;">Set API key</button>
  </div>

  <div style="width: 60vw; background-color: #f9f9f9; border: 1px solid #f0f0f0; border-radius : 15px ;margin: 20px auto; padding: 20px; text-align: center; box-shadow: 1px 3px 10px #b3b3b3">
    <h3>Adjust Temperature (Try Different temperature levels)</h3>
    <input type="range" min="0" max="1" step="0.1" value="0" id="temperatureSlider" oninput="updateTemperature()">
    <span id="temperatureValue" style="font-weight: bold; margin-left: 10px;">0</span>

    <h3 style="margin-top: 20px;">Enter a one or two words prompt for 2D animation</h3>
    <input style="width: 50vw; padding: 8px;border : 1px solid darkgrey" id="me" value="Walking Man">
    <button onclick="sendchat();" style="display: inline;padding: 10px 10px;border-width: 0;outline: none;border-radius: 2px;background-color: #1D1D1D;color: #ecf0f1;">Send</button>
  </div>

  <div id="response" style="display: none;width: 60vw; background-color: #f9f9f9; border: 1px solid  #f0f0f0; border-radius : 15px; margin: 20px auto; padding: 20px; text-align: center;box-shadow: 1px 3px 10px #b3b3b3">
    <h3>GPT Response</h3>
    <a id="link" href="#"></a>
    <div id="them">
    
    </div>
    
  </div>
  

</div>

`);


function setkey()          
{
	apikey =  jQuery("input#apikey").val();
	apikey = apikey.trim();
	$("#enterkey").html ( "<b> API key has been set. </b>" );
}



// Enter will also send chat:

document.getElementById('me').onkeydown   = function(event) 	{ if (event.keyCode == 13)  sendchat(); };




function sendchat()
{
  //Makarand : updating the Promt so that chat GPT gives code for the topic
  $('#response').css( "display", "block" );
   $('#link').css( "display", "none" );
  $("#them").html("<pre> Loading... </pre>");
 theprompt = "Give me code for " + $("#me").val() + " in p5 js without any comments";
  console.log(theprompt);

//Makarand : To get the value of temprature

var temperature = document.getElementById("temperatureSlider").value;
// construct request as JSON
// "Lowering temperature means it will take fewer risks, and completions will be more accurate and deterministic. Increasing temperature will result in more diverse completions."

// Makarand : Passing the value of temprature as a float
var thedata = {
     "model": themodel,
     "temperature": parseFloat(temperature),
     "messages": [{
         "role": "user", 
         "content": theprompt
        }] 
   };
   
// then as string representing that JSON:
var thedatastring = JSON.stringify ( thedata );   
   
// HTTP headers must be set up with API key: 

$.ajaxSetup({
   headers:
   {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + apikey  
   }
});


// POST to 3rd party URL: 

 $.ajax({
    type: "POST",
    url: openaiURL,
    data: thedatastring,
    dataType: "json",
    success: function ( d, rc ) { successfn ( d, rc ); },
      error: function()         { errorfn (); }
 });
 
}


 
 // global variable to examine return data in console 
 var a;
 
 //Makarand : Created a Function to Convert the P5 code (String format from response) as a script element 


//Makarand : Created a function to extract just the code part from Response and to remove the comments
//Credits : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions
function extractCode(inputCode) {
  const codePattern = /```javascript([\s\S]*?)```/g; //to fetch the code block
  const commentPattern = /\/\/.*|\/\*[\s\S]*?\*\//g; //to remove inline commments

  let codeMatches = inputCode.match(codePattern);

  if (codeMatches) {
    // Extract code between delimiters
    let extractedCode = codeMatches.map(match => match.replace(codePattern, '$1')).join('\n');

    // Remove comments
    extractedCode = extractedCode.replace(commentPattern, '');

    return extractedCode.trim();
  }

  return null; // Return null if no code is found
}

// Makarand :Function to update the temprature when the slider is moved
function updateTemperature() {
  var sliderValue = document.getElementById("temperatureSlider").value;
  document.getElementById("temperatureValue").innerHTML = sliderValue;
}


//Makarand : Calling the runP5Code function in the success function and also printing the code in in the HTML
//Makarand : calling the extractCode function to exctract just the code part 
 function successfn ( data, rc )
 {
     a = data;
     var answer = a["choices"][0].message.content;
     console.log(answer)
     newAnswer = extractCode(answer)
     //console.log(newAnswer)
     $("#them").html("<pre>" + newAnswer + "</pre>");
     $('#link').css( "display", "block" );
     document.getElementById("link").innerHTML = "Click here to watch the Animation";
      
     document.getElementById("link").href = "https://run.ancientbrain.com/run.php?world=9178317088&ignore=3&ignoretoo=3&code="+newAnswer;
     
     // mh edit
     // removed:
     // &userid=makarand&dataticket=21285035590341136413099615656069
     
 }
 
 function errorfn()
 {
     if ( apikey == "" )    $("#them").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
     else                   $("#them").html ( "<font color=red><b> Unknown error. </b></font>" ); 
 }