// Cloned by Nik Shautsou on 1 Dec 2023 from World "Project (Hello World)" by Nik Shautsou
// Please leave this clone trail here.
// a large amount of this code was referenced from the "Chat with GPT model" world by
// "Starter User"
// https://ancientbrain.com/world.php?world=2850716357
// all code was taken and understood for the google cloud api was taken and or understood from
// the google cloud vision api documentation
// https://cloud.google.com/vision/docs/reference/rest/?apix=true
// set an empty API key so that a user can enter their own key
var visionapikey = "";
var openaiapikey = "";
// set an empty image value so that the user can enter their own unique image link
var image = "";
// taken from https://ancientbrain.com/world.php?world=2850716357
const openaiURL = "https://api.openai.com/v1/chat/completions"; // can POST to this 3rd party URL
const themodel = "gpt-3.5-turbo"; // the OpenAI model we are going to talk to
// default body is margin 0 and padding 0
// give it more whitespace:
$('body').css( "margin", "20px" );
$('body').css( "padding", "20px" );
// write a prompt for a user to set an api key (we also want to show the image the user
// has uploaded for readability)
document.write ( `
<h1> Funny text generator For a given image </h1>
<h3> Enter API keys </h3>
This World will never store your API keys.
You can view the <a href='https://ancientbrain.com/edit.world.php?world=1336086098'> source code</a> to see that is true!
<br>
<p>
<div id=enterkey>
Enter Cloud Vision API key:
<input style='width:25vw;' maxlength='2000' NAME="apikey" id="apikey" VALUE='' >
<button onclick='setkey();' class=ab-normbutton >Set API key</button>
</div>
<br>
<div id=enterkey2>
Enter OpenAI API key:
<input style='width:25vw;' maxlength='2000' NAME="apikey2" id="apikey2" VALUE='' >
<button onclick='setkey2();' class=ab-normbutton >Set API key</button>
</div>
<pre>
</pre>
<h3> Enter image </h3>
<div id="enterimage">
Enter an image to give the funny to:
<input style='width:50vw;' maxlength='2000' NAME="image" id="image" VALUE='' >
<button onclick='setImage();' class=ab-normbutton >Set image</button>
</div>
<div id="imageholder">
</div>
<div style="width:60vw; background-color:#ffffcc; border: 1px solid black; margin:20; padding: 20px;">
<h3> Vision recognises this as a <div id=response > </div> </h3>
<h3> with a confidence of <div id=confidence > </div> </h3>
</div>
<hr>
<h1> Generate some funny text based on the above entered image using OpenAI API </h1>
<div style="width:60vw; background-color:#ffffcc; border: 1px solid black; margin:20; padding: 20px;">
<h3> GPT replies </h3>
<div id=them > </div>
</div>
` );
// set key function which sets the cloud vision api key that a user inputs (referenced from
// https://ancientbrain.com/world.php?world=2850716357)
function setkey() {
visionapikey = jQuery("input#apikey").val();
visionapikey = visionapikey.trim();
$("#enterkey").html ( "<b> Cloud Vision API key has been set. </b>" );
// call the function below which creates a post request to the Vision api with our image
}
// set key function which sets the openai api key that a user inputs (referenced from
// https://ancientbrain.com/world.php?world=2850716357)
function setkey2()
{
openaiapikey = jQuery("input#apikey2").val();
openaiapikey = openaiapikey.trim();
$("#enterkey2").html ( "<b> OpenAI API key has been set. </b>" );
}
function setImage() {
image = jQuery("input#image").val();
image = image.trim();
$("#imageholder").html ( '<img src=' + image + ' width="500" height="500">' );
// the data we want to send to the vision api
var data = {
"requests": [
{
"image": {
"source": {
"imageUri": image
}
},
"features": [
{
"model": "vision",
"maxResults": 10,
// there are a couple different versions of this which can be used to detect text in an image,
// give you the main details of an image, find the location of an image and many more, all of
// which can be found in the cloud vision api documentation
// https://cloud.google.com/vision/docs/reference/rest/?apix=true
"type": "OBJECT_LOCALIZATION"
}
]
}
]
}
getResponse(visionapikey, data)
}
// this is a function used to send a post request of our image to the api so that we can receive
// a response to what the image is and what the confidence of that assessment is, this was altered
// to be an async function so as to allow an await for the fetch so that we can wait for the user to
// enter some api key which will then be deemed valid or invalid by the fetch request.
async function getResponse(apikey, data) {
const res = await fetch("https://vision.googleapis.com/v1/images:annotate?key=" + apikey, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
response = data
console.log(response);
$("#response").html ( response.responses[0].localizedObjectAnnotations[0].name );
$("#confidence").html ( response.responses[0].localizedObjectAnnotations[0].score );
sendchat(response.responses[0].localizedObjectAnnotations[0].name);
})
.catch((error) => {
console.error('Error:', error);
})
}
// all of the following code is referenced/taken from
// https://ancientbrain.com/world.php?world=2850716357
// --- Send my line of text ----------------------------------------------------------------
function sendchat(theprompt)
{
// 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."
var thedata = {
"model": themodel,
"temperature": 0.1,
"messages": [{
"role": "user",
// this is the only real change we are making to the code so as to generate a funny message
// in regards to some image above (as this is the hello world version of this project we will
// only be hardcoding in the prompt, set to giraffe above)
"content": "Generate me a unique line of funny text to do with a" + 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 " + openaiapikey
}
});
// 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;
function successfn ( data, rc )
{
a = data;
var answer = a["choices"][0].message.content;
$("#them").html ( answer );
}
function errorfn()
{
if ( openaiapikey == "" ) $("#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>" );
}