Code viewer for World: Image Generation using Gen...

// Cloned by Alfred Iyby on 2 Dec 2023 from World "Chat with GPT model" by Starter user 
// Please leave this clone trail here.
  
const engine_id = "stable-diffusion-v1-6"; 
const stability_api_url = "https://api.stability.ai/v1/generation/"+ engine_id +"/text-to-image";
    

// default API key and prompt:

var apikey = "";
var theprompt = "";

 
// default body is margin 0 and padding 0 
// give it more whitespace:

  $('body').css( "margin", "20px" );
  $('body').css( "padding", "20px" );


 
document.write ( `
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<h1> GENERATIVE IMAGE AI </h1>


<div id=enterkey class="input-group mb-3">
      <input type="text" class="form-control" placeholder="INSERT API KEY" id="apikey">
      <button onclick='setkey();'  class="btn btn-primary" >Set API key</button>
</div>

<div style="width:70vw; background-color:white; display:grid;  border: 1px solid black; padding: 20px;border-radius: 5px;" class="input-group mb-3">
    <label style="padding:5px;"> ENTER PROMPT : </label>
    <input type="text" style="width:60vw;" class="form-control" id=me value="Create a striking digital artwork featuring a lone astronaut standing on a distant moon's surface, surrounded by vast, cratered landscapes. Illuminate the scene with the soft glow of Earth in the night sky, casting reflections on the astronaut's visor. The cosmic setting should evoke a sense of solitude, exploration, and the awe-inspiring beauty of outer space. Use your artistic skills to convey the quiet majesty of this lunar moment." >
    <br> 
    <div class="input-group mb-3">
        <div class="value left"> Better Quality &nbsp&nbsp </div>
        <input type="range" min="0" max="35" value="7" steps="1" id="cfg_value"/>
        <div class="value right">&nbsp&nbspMatch Prompt</div>
    </div>
    <br>
    <button onclick="sendchat();" class="btn btn-success" style="width:5vw"> Send </button> 
    
</div>


<div style="width:70vw; border: 1px solid black; padding: 20px;border-radius: 5px;" class="input-group mb-3">
<div id=them >
<h3> RESPONSE </h3>
</div>
</div>

<pre>

</pre>

` );




function setkey()          
{
	apikey =  jQuery("input#apikey").val();
	apikey = "sk-3O5EuLo8DfXLxt9ImcEXF4AgmNXcoKYx5K6bYNu2D0BxmFHr";
	$("#enterkey").html ( "<b> API KEY SET </b>" );
}



// Enter will also send chat:

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




// --- Send my line of text ----------------------------------------------------------------

function sendchat()
{
  theprompt = $("#me").val();
  cfgValue = Number(document.getElementById("cfg_value").value);
  console.log(cfgValue);
// construct request as JSON
var thedata = {
  "cfg_scale": cfgValue,
  "clip_guidance_preset": "FAST_BLUE",
  "height": 512,
  "width": 512,
  "sampler": "K_DPM_2_ANCESTRAL",
  "samples": 1,
  "steps": 30,
  "text_prompts": [
                    {
                      "text": theprompt,
                      "weight": 1
                    }
        ]
}
   
// 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",
        "Accept":"application/json",
        "Authorization": apikey  
  }
});


// POST to 3rd party URL: 

 $.ajax({
    type: "POST",
    url: stability_api_url,
    data: thedatastring,
    dataType: "json"
 }).done(function(dataString) {
    const pngBinaryText = dataString["artifacts"][0]["base64"];
    const img = new Image();
    img.src = `data:image/png;base64,${pngBinaryText}`;
    img.style.display = 'flex';
    $("#them").html ( `<h3>RESPONSE</h3>` );
    document.getElementById('them').appendChild(img);
  })
  .fail(function(error) {
      err = error.responseJSON;
      if(err["message"])  msg =err["message"];
      if ( apikey === "" )    $("#them").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
      else {
          $("#them").html ( `<font color=red><h3>RESPONSE</h3><b> ${msg} </b></font>` );
      }
  });
 
}