Code viewer for World: Azure Image Description Ge...
// Credits:
// Several sections of the code are adapted from the following Ancient Brain world://ancientbrain.com/world.php?world=2850716357


// endpoint code reference and several other code section from official Microsoft site - https://learn.microsoft.com/en-us/rest/api/computervision/analyze-image/analyze-image?view=rest-computervision-v3.1&tabs=HTTP

// MH edit
// enter your own Azure endpoint:
//  const endpoint = 'https://SOMEDOMAIN.cognitiveservices.azure.com/vision/v3.0/analyze?visualFeatures=Description&details=Landmarks&language=en'; 
    const endpoint =   'https://suraksha.cognitiveservices.azure.com/vision/v3.0/analyze?visualFeatures=Description&details=Landmarks&language=en'; 

let apiKey = '';



//Code section reference from W3Schools - from https://www.w3schools.com/css/default.asp
document.write(`
<style>
  body {
    font-family: Georgia, serif;
    background-color: #ffffff;
    color: #444;
    text-align: center;
    padding: 20px;
  }

  h1 {
    font-size: 36px;
    color: #333;
  }

  h3 {
    font-size: 24px;
    color: #333;
  }

  a {
    color: #007bff;
    text-decoration: none;
  }

  input[type="text"],
  button {
    padding: 10px;
    font-size: 16px;
    border-radius: 5px;
    border: 1px solid #ccc;
    margin-bottom: 10px;
  }

  .ab-normbutton {
    background-color: #007bff;
    color: #fff;
    cursor: pointer;
  }

  #enterkey,
  #results {
    margin: 20px auto;
    width: 80%;
    background-color: #ffffff;
    border: 1px solid #ccc;
    padding: 20px;
  }
  

  #results img {
    max-width: 100%;
    height: auto;
    margin-bottom: 20px;
  }

  #errordiv {
  color: #d9534f; /* Subtle red color */
  font-size: 18px;
  margin-top: 10px;
}
</style>

<h1>URL-based Image Description Generator</h1>

<h3></h3>

<p>
  Unlock the power of Microsoft Azure's Cognitive Service - Computer Vision effortlessly! <br> <a href='https://azure.microsoft.com/en-us/products/api-management/?ef_id=_k_Cj0KCQiAyKurBhD5ARIsALamXaEDDX6Vq2YnDRvDP_p7ag0ggR74NzcdUjGcZTfd55dblb-8O3AKXS0aAti8EALw_wcB_k_&OCID=AIDcmmsmruuku2_SEM__k_Cj0KCQiAyKurBhD5ARIsALamXaEDDX6Vq2YnDRvDP_p7ag0ggR74NzcdUjGcZTfd55dblb-8O3AKXS0aAti8EALw_wcB_k_&gad_source=1&gclid=Cj0KCQiAyKurBhD5ARIsALamXaEDDX6Vq2YnDRvDP_p7ag0ggR74NzcdUjGcZTfd55dblb-8O3AKXS0aAti8EALw_wcB'>Sign up</a>
   for free today and instantly receive your exclusive API key. Start revolutionizing your projects with cutting-edge technology—seamless integration awaits!
  <br>
  
</p>

<div id="enterkey">
  Enter your unique API key:
  <input style='width:25vw;' maxlength='2000' name="apikey" id="apikey" value=''>
  <button onclick='setkey();' class='ab-normbutton' style='background-color: #4CAF50; color: white; padding: 12px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px;'>
  Unlock the Power
</button>

</div>

<h2>Ready for analysis?</h2>
<div id="results">
Enter URL of image:
<input style='width:25vw;' maxlength='2000' id=url name=url value=''>
<button onclick='recognise();' class='ab-normbutton' style='background-color: #4CAF50; color: white; padding: 12px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px;'>
  Analyze Now!
</button>
<p style='font-family: Georgia, serif; color: #1E90FF; font-size: 14px;'>**Venture into Ancient Brain's realm for image uploads! (Psst... It's the secret passage for your images!)</p>

<div id=errordiv name=errordiv></div>

</div>
`);


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

// Code section is adapted from the following Ancient Brain world://ancientbrain.com/world.php?world=2850716357
// Function to recognize an image
function recognise() {
  let url = jQuery("input#url").val().trim();

  if (!url.startsWith("https://ancientbrain.com/uploads/")) {
    $("#errordiv").html("<font color=red><b>Oops! It seems like the image needs to take a detour through Ancient Brain's gallery before heading here.</b></font>");
    return;
  }
   AB.removeSplash();	
   url =  url.replace ( "https://ancientbrain.com/uploads/", "/uploads/" );
   
   fetchAndAnalyzeImage(url);
    
  }


// Function to update UI with API response data
function updateUI(data, url) {
  $("#results").html('<h2>Image</h2>');
  $("#results").append(`<img src="${url}" alt="User Image" style="max-width: 100%; height: auto;">`);

  // Applying font style and color adjustments
  $("#results").css({
    'font-family': 'Georgia, serif',
    'color': '#333',
    'background-color': 'white'
  });
  
  

  // Display categories
  if (data.categories && data.categories.length > 0) {
    $("#results").append('<h4>Category:</h4>');
    data.categories.forEach(category => {
      $("#results").append(`<p>${category.name}, (Confidence: ${category.score})</p>`);
    });
  } else {
    $("#results").append('<p>No categories found</p>');
  }

  // Display description
  if (data.description && data.description.captions && data.description.captions.length > 0) {
    $("#results").append('<h4>Description:</h4>');
    data.description.captions.forEach(caption => {
      $("#results").append(`<p>${caption.text}, (Confidence: ${caption.confidence})</p>`);
    });

    // Display tags with commas
    if (data.description.tags && data.description.tags.length > 0) {
      $("#results").append('<h4>Tags associated with image:</h4>');
      const tagsString = data.description.tags.join(', ');
      $("#results").append(`<p>${tagsString}</p>`);
    } else {
      $("#results").append('<p>No tags available</p>');
    }
  } else {
    $("#results").append('<p>No description available</p>');
  }

  // Display metadata
  $("#results").append('<h4>Image Dimensions:</h4>');
  $("#results").append(`<p>Image Height: ${data.metadata.height}, Image Width: ${data.metadata.width}, Format: ${data.metadata.format}</p>`);
}

function fetchAndAnalyzeImage(url) {
  
//Credits: code section from official Microsoft site - https://learn.microsoft.com/en-us/rest/api/computervision/analyze-image/analyze-image?view=rest-computervision-v3.1&tabs=HTTP
fetch(url)
    .then(response => response.blob())  // Converting the image into a readable binary format, credits: https://youtu.be/0svE9rgmmiU?si=RzHIA0HJyo0Jf3Qm
    .then(imageBlob => {
      const formData = new FormData();
      formData.append('file', imageBlob); 

      fetch(endpoint, {
        method: 'POST',
        headers: {
          'Ocp-Apim-Subscription-Key': apiKey
        },
        body: formData
      })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        // Update the UI with the API response data
        updateUI(data,url);
        console.log(data);
      })
      .catch(error => {
        console.error('Error:', error);
      });
    })
    .catch(error => {
      console.error('Image fetch error:', error);
    });
}