Code viewer for World: AI API Project (clone by A...

// Cloned by AbulHasan on 30 Nov 2024 from World "Websockets boxes" by Starter user 
// Please leave this clone trail here.
 

$('body').css({
  'margin': '10px',
  'padding': '10px',
  'font-family': 'Arial, sans-serif',
  'background-image': 'url(https://i.ibb.co/n0FwC7g/planet-earth-night-view-illumina.jpg)',
  'text-align': 'center',
});

$('#enterKey').css({
  'margin-bottom': '20px',
  'display': 'flex',
  'flex-direction': 'column',
  'align-items': 'center',
});

$('#apiKey').css({
  'width': '40vw',
  'padding': '8px',
  'border': '1px solid #ccc',
  'border-radius': '10px',
  'margin-bottom': '10px',
  'color': 'black',
  'background-color': '#fff',
});

$('.ab-normbutton').css({
  'padding': '10px',
  'font-size': '16px',
  'background-color': '#4CAF50',
  'color': 'white',
  'border': 'none',
  'border-radius': '10px',
  'cursor': 'pointer',
});

$('.ab-normbutton:hover').css({
  'background-color': '#45a049',
});

$('#prompt').css({
  'width': '70vw',
  'padding': '8px',
  'border': '1px solid #ccc',
  'border-radius': '10px',
  'margin-bottom': '20px',
  'margin': '0 auto',
  'color': 'black',
  'background-color': '#fff',
});

document.write(`
  <div id="container" style="background-color: white; padding: 20px 30px 70px; border-radius: 10px; width: 70%; max-width: 750px; margin: 250px auto; text-align: center;">
    <h1 style="color: black; margin-bottom: 20px;">Welcome to GeoAI !</h1>
    <p style="color: black; margin-bottom: 20px;">Please provide your unique API keys to authenticate</p>
   
    <div id="enterKey" style="margin-bottom: 2em; display: flex; flex-direction: column; align-items: center;">
      <input type="text" style="width: 70%; max-width: 300px; padding: 8px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 10px; color: black; text-align: center;" maxlength="2000" name="apiKey" id="apiKey" placeholder="Enter your rapidAPI key here">
      <button onclick="setAIKey();" class="ab-normbutton"
        style="padding: 10px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 10px; cursor: pointer;">
            Activate API Key
        </button>
    </div>
   
    <div id="guessOption" style="margin-bottom: 2em; display: flex; flex-direction: column; align-items: center;">
      <label for="guessType" style="margin-bottom: 10px; color: black;">Select what to guess:</label>
      <select id="guessType" style="width: 70%; max-width: 300px; padding: 8px; border: 1px solid #ccc; border-radius: 10px; text-align: center;">
        <option value="country">Country</option>
        <option value="city">City</option>
      </select>
    </div>
   
    <div id="enterImage" style="margin-bottom: 2em; display: flex; flex-direction: column; align-items: center;">
      <input type="text" id="imageUrlInput" placeholder="Enter the image URL here"
        style="width: 70%; max-width: 300px; padding: 8px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 10px; color: black; text-align: center;">
      <button onclick="runImageDescriptions(), coPilotDescribeImage() ;" class="ab-normbutton"
        style="padding: 10px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 10px; cursor: pointer;">
        Describe Image
      </button>
    </div>
   

    <div id="imageDescription" style="margin-top: 20px; color: black;"></div>
  </div>
`);
 


const imageGeneratorURL = "https://ai-image-generator3.p.rapidapi.com/generate";
const imageUrl = ""

var apiKeys = [];
var imageKey = "";

function setAIKey() {
  var enteredApiKey = $("#apiKey").val().trim();

  if (!enteredApiKey || enteredApiKey.length < 30 || enteredApiKey.length > 80) {
    $("#imageResult").html("<font color='##800000'><b>Please enter a valid API key (between 30 and 80 characters).</b></font>");
    return;
  }

  apiKeys.push(enteredApiKey);
  $("#enterKey").html("<b>API key has been set.</b>");
 
  console.log(apiKeys[0]);

} // Credit to Mark Humphrys for the setting of API key function.
// https://ancientbrain.com/world.php?world=2850716357


function coPilotDescribeImage(guessType) {
    const start = new Date();
    const imageUrl = $("#imageUrlInput").val().trim();
    const guessPrompt = `What ${guessType} is in this image?, give only the  ${guessType}`;
    console.log(guessPrompt);
   
    if (!apiKeys[0] || !imageUrl) {
        $("#imageDescription").html("<font color='#800000'><b>Please enter both API key and image URL.</b></font>");
        return;
    }
   
        const settings = {
    async: true,
    crossDomain: true,
    url: 'https://copilot5.p.rapidapi.com/copilot',
    method: 'POST',
    headers: {
    'x-rapidapi-key': apiKeys[0],
    'x-rapidapi-host': 'copilot5.p.rapidapi.com',
    'Content-Type': 'application/json'
    },
    processData: false,
        data: JSON.stringify({
            message: guessPrompt,
            conversation_id: null,
            tone: "BALANCED",
            markdown: false,
            photo_url: imageUrl
        })
    };
   
    $.ajax(settings).done(function (response) {
        const end = new Date();
        const duration = ((end - start) / 1000).toFixed(2);
        const description = response && response.data && response.data.message
          ? response.data.message
          : "No description found in the first API response.";
        displayImageDescription(1, description,duration);
    });
   
   
}


function gptVisionDescribeImage(guessType) {
    const start = new Date();
    const imageUrl = $("#imageUrlInput").val().trim();
    const guessPrompt = `What ${guessType} is in this image?, give only the  ${guessType}`;
    console.log(guessPrompt);
   
    if (!apiKeys[0] || !imageUrl) {
        $("#imageDescription").html("<font color='#800000'><b>Please enter both API key and image URL.</b></font>");
        return;
    }
   
        const settings = {
        async: true,
        crossDomain: true,
        url: 'https://chatgpt-42.p.rapidapi.com/matagvision',
        method: 'POST',
        headers: {
            'x-rapidapi-key': apiKeys[0],
            'x-rapidapi-host': 'chatgpt-42.p.rapidapi.com',
            'Content-Type': 'application/json'
        },
        processData: false,
        data: JSON.stringify({
            messages: [
                {
                    role: "user",
                    content: guessPrompt,
                    img_url: imageUrl
                }
            ]
        })
    };

    $.ajax(settings).done(function (response) {
        const end = new Date();
        const duration = ((end - start) / 1000).toFixed(2);
        const description = response && response.result
          ? response.result
          : "No description found in the second API response.";
        displayImageDescription(2, description,duration);
    });

}

function geminiDescribeImage(guessType) {
    const start = new Date();
    const imageUrl = $("#imageUrlInput").val().trim();
    const guessPrompt = `What ${guessType} is in this image?, give only the  ${guessType}`;
    console.log(guessPrompt);

    if (!apiKeys[0] || !imageUrl) {
        $("#imageDescription").html("<font color='#800000'><b>Please enter both API key and image URL.</b></font>");
        return;
    }

    const settings = {
        async: true,
        crossDomain: true,
        url: 'https://gemini-pro-ai.p.rapidapi.com/',
        method: 'POST',
        headers: {
            'x-rapidapi-key': apiKeys[0],
            'x-rapidapi-host': 'gemini-pro-ai.p.rapidapi.com',
            'Content-Type': 'application/json'
        },
        processData: false,
        data: JSON.stringify({
            contents: [
                {
                    role: "user",
                    parts: [
                        {
                            text: guessPrompt + imageUrl
                        }
                    ]
                }
            ]
        })
    };

    $.ajax(settings).done(function (response) {
        const end = new Date();
        const duration = ((end - start) / 1000).toFixed(2); // Calculate duration in seconds
        const description = response?.candidates?.[0]?.content?.parts?.[0]?.text || "No description found in Gemini API response.";
        displayImageDescription(3, description, duration);
    }).fail(function () {
        const end = new Date();
        const duration = ((end - start) / 1000).toFixed(2); // Calculate duration in seconds
        displayImageDescription(3, "Failed to fetch description from Gemini API.", duration);
    });
}

function displayImageDescription(api, description, duration) {
    let apiLabel;

   
    switch (api) {
        case 1:
            apiLabel = "First API (CoPilot)";
            break;
        case 2:
            apiLabel = "Second API (GPT Vision)";
            break;
        case 3:
            apiLabel = "Third API (Gemini)";
            break;
        default:
            apiLabel = "Unknown API";
    }


    $(`#${api === 1 ? "firstApiDescription" : api === 2 ? "secondApiDescription" : "thirdApiDescription"}`).html(`
        <p><b>${apiLabel} Description:</b> ${description}</p>
        <p><i>Response Time:</i> ${duration} seconds</p>
    `);
}

function runImageDescriptions() {
   
    const guessType = $("#guessType").val();

   
    $("#imageDescription").html(`
        <div id="firstApiDescription"><p><b>First API (CoPilot) Description:</b> Loading...</p></div>
        <div id="secondApiDescription"><p><b>Second API (GPT Vision) Description:</b> Loading...</p></div>
        <div id="thirdApiDescription"><p><b>Third API (Gemini) Description:</b> Loading...</p></div>
    `);

 
    coPilotDescribeImage(guessType);
    gptVisionDescribeImage(guessType);
    geminiDescribeImage(guessType);
}