Code viewer for World: Hoang-Bao Le - Practical 2...

// Cloned by Test account on 20 Dec 2024 from World "Hoang-Bao Le - Practical 2" by Hoang-Bao Le 
// Please leave this clone trail here.
 


// Cloned by Hoang-Bao Le on 23 Nov 2024 from World "Stability AI Image Generation" by Alfred Iyby 
// Please leave this clone trail here.
 


// Cloned by Alfred Iyby on 2 Dec 2023 from World "Image Generation using Generative AI 2" by Alfred Iyby 
// Please leave this clone trail here.



// Cloned by Alfred Iyby on 2 Dec 2023 from World "Chat with GPT model" by Starter user 
// Please leave this clone trail here.
  
var engine_id ="stable-diffusion-v1-6";
var 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" );

function copyText() {
    // Get the text field
    var copyText = document.getElementById("input");
    // Select the text field
    copyText.select();
    copyText.setSelectionRange(0, 99999); // For mobile devices
    // Copy the text inside the text field
    navigator.clipboard.writeText(copyText.value);
    // Alert the copied text
    alert("Copied the text: " + copyText.value);
}
 
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">
<head>
    <style>
    body {
    background-image: url("https://wallpapercave.com/wp/wp2885476.jpg");
    background-repeat: no-repeat;
    background-size: cover; /* Ensures the image covers the entire page */
    background-position: center; /* Centers the image */
    margin: 0; /* Removes default margin for the body */
    }
    </style>
</head>
<h1> GENERATIVE IMAGE by AI 2024 </h1>

<div id=enterkey class="input-group mb-3">
      <input type="text" class="form-control" placeholder="YOUR API KEY..." id="apikey">
      <button onclick='setkey();'  class="btn btn-primary" ><b>API key</b></button>
      <br>
      <input type="text" id="input" value="sk-SEs4GysofGjYDXLkRfrOhpJVcRshcQNQarPvZvoPzjkF1R7o"/>
      <button onclick="copyText()"><b>FREE API Copy</b></button>
</div>

<div style="width:60vw; background-color:lightblue; display:grid;  border: 1px solid black; padding: 20px;border-radius: 5px;" class="input-group mb-3">
    <label style="padding:5px;"> <b>ENTER PROMPT:</b> </label>
    <input type="text" style="width:50vw;" class="form-control" id=me value="Create a classroom with a male teacher wearing glasses and teaching Mathematics." >
    <br> 
    <button class="btn btn-warning" onclick="changePrompt()" style="width:250px";>Generate Random Prompt</button>
    &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp 
    <br>
    <div class="input-group mb-3">
        <div class="value left" style="padding:10px;"> Quality Scale &nbsp&nbsp </div>
        <input type="range" min="0" max="35" value="10" steps="1" id="cfg_value"/>
        <div class="value right" style="padding:10px;">&nbsp&nbspPrompt Matching</div> 
        <p></p>
        <label style="padding:10px;">Choose Image Style: </label>
        <select class="form-select" aria-label="Default select example" id="style_preset" style="width:25px">
          <option selected value="3d-model">3d-Model</option>
          <option value="analog-film">Analog</option>
          <option value="anime">Anime</option>
          <option value="cinematic">Cinematic</option>
          <option value="comic-book">Comic</option>
          <option value="digital-art">Digital</option>
          <option value="fantasy-art">Fantasy</option>
          <option value="origami">Origami</option>
          <option value="pixel-art">Pixel</option>
    </select>
    </div>
    <br>
    <button onclick="sendchat();" class="btn btn-success" style="width:5vw"> Send </button> 
    <br>
    <label for="cardType">Select Card Type:</label>
    <select id="cardType" style="width:250px">
        <option value="xmas">Christmas Card</option>
        <option value="newyear">New Year Card</option>
        <option value="">Generic Card</option>
    </select>
    <br>
    <div>The card prompt: </div>
    <input type="text" id="promptInput" placeholder="Create a special card having..." style="width:50vw;">
    <button class="btn btn-danger" onclick="createCard(document.getElementById('promptInput').value, document.getElementById('cardType').value)" style="background-color: red; color: white; border: none; padding: 10px 20px; width: 250px; font-size: 16px; cursor: pointer; box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.2); transition: transform 0.2s, box-shadow 0.2s;">Create a <i>special</i> card</button>
    <div id="wait"></div>
</div>


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

<pre>

</pre>

` );



    const imagePrompts = [
      "Create a collection of images showcasing breathtaking landscapes, such as lush forests, serene beaches, towering mountains, and vibrant sunsets.",
      "Explore the world through images of traditional clothing, festivals, local cuisines, and architecture from different countries.",
      "Design a series of images imagining futuristic cities, advanced robotics, flying cars, and cutting-edge gadgets.",
      "Capture images of rare and exotic animals in their natural habitats, from the depths of the oceans to the heart of the jungle.",
      "Illustrate moments that changed history, such as the moon landing, ancient civilizations, famous battles, or iconic leaders.",
      "Bring to life mythical creatures, enchanted forests, magical castles, and epic adventures in an imaginary realm.",
      "Create a visual representation of emotions like joy, sadness, love, fear, and anger using diverse facial expressions and scenarios.", 
      "Showcase the bustling life in cities with skyscrapers, crowded markets, street art, and nightlife scenes.",
      "Depict the unique charm of the four seasons—spring blossoms, summer beaches, autumn leaves, and snowy winters.",
      "Illustrate galaxies, planets, astronauts, and spacecraft exploring the vast expanse of the universe."
    ];

    function changePrompt() {
      const inputElement = document.getElementById("me");
      const randomIndex = Math.floor(Math.random() * imagePrompts.length);
      inputElement.value = imagePrompts[randomIndex];
    }

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

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

function sendchat()
{
  $("#wait").html ( `<p>Image is generating</p>` );
  theprompt = $("#me").val();
  cfgValue = Number(document.getElementById("cfg_value").value);
  style_value = document.getElementById("style_preset").value;

    jsonData = {
      "cfg_scale": cfgValue,
      "clip_guidance_preset": "FAST_BLUE",
      "height": 512,
      "width": 512,
      "sampler": "K_DPM_2_ANCESTRAL",
      "samples": 1,
      "steps": 40,
      "style_preset":style_value,
      "text_prompts": [
                        {
                          "text": theprompt,
                          "weight": 1
                        }
            ]
    }
    jsonData = JSON.stringify(jsonData);
    
$.ajaxSetup({
  headers:
  {
        "Content-Type": "application/json",
        "Accept":"application/json",
        "Authorization": apikey  
  }
});


// POST to 3rd party URL: 


 $.ajax({
    type: "POST",
    url: stability_api_url,
    data: jsonData,
    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);
    $("#wait").empty();
  })
  .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>` );
      }
      $("#wait").empty();
  });

  
}




function createCard(prompt, type) {
    $("#wait").html(`<p>Card Image is generating...</p>`);

    // Define default prompts based on type
    let promptText;
    if (type === "xmas") {
        promptText = "Create a Christmas Card with 'Merry X-Mas' on the header having " + prompt;
    } else if (type === "newyear") {
        promptText = "Create a New Year Card with 'Happy New Year' on the header having " + prompt;
    } else {
        promptText = "Create a beautiful greeting card having " + prompt;
    }

    // Prepare JSON data for the API request
    let jsonData = {
        "cfg_scale": 8,
        "clip_guidance_preset": "FAST_GREEN",
        "height": 512,
        "width": 512,
        "sampler": "K_DPM_2_ANCESTRAL",
        "samples": 1,
        "steps": 49,
        "style_preset": "photographic",
        "text_prompts": [
            {
                "text": promptText,
                "weight": 1
            }
        ]
    };
    jsonData = JSON.stringify(jsonData);

    // Configure AJAX setup
    $.ajaxSetup({
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": apikey
        }
    });

    // Make the AJAX POST request
    $.ajax({
        type: "POST",
        url: stability_api_url,
        data: jsonData,
        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);
        $("#wait").empty();
    }).fail(function(error) {
        const err = error.responseJSON;
        let msg = err && err["message"] ? err["message"] : "An unknown error occurred.";
        if (apikey === "") {
            $("#them").html("<font color=red><b> Enter API KEY to start generation</b></font>");
        } else {
            $("#them").html(`<font color=red><h3>RESPONSE</h3><b> ${msg} </b></font>`);
        }
        $("#wait").empty();
    });
}