var rawHTML = `
<style>
#apiKey {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 100; /* Ensures it's above other elements */
background: #a2a2a2a2;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
#apiInput {
width: 300px;
height: 30px;
font-size: 20px;
padding: 5px;
border-radius: 5px;
border: 1px solid #000;
}
#setApi {
width: 100px;
height: 40px;
font-size: 20px;
border-radius: 5px;
padding: 5px;
border: 1px solid #000;
cursor: pointer;
}
</style>
<div id="apiKey">
<input type="text" id="apiInput" placeholder="Enter Api Key" />
<button id="setApi">Set Key</button>
</div>`;
document.body.innerHTML += rawHTML;
// Prompt input setup
const apiKeyInput = document.getElementById("apiKey");
const apiInput = document.getElementById("apiInput");
const setApiButton = document.getElementById("setApi");
var apikey = "";
// Event listener for the set API key button
setApiButton.addEventListener("click", function () {
if (apiInput.value == "") return; // no empty API keys
apikey = apiInput.value;
apiKeyInput.style.display = "none"; // Hide the prompt input
getImage();
});
async function getImage() {
const proxiedUrl =
"https://corsproxy.io/?" +
encodeURIComponent("https://api.replicate.com/v1/predictions");
const token = apikey;
const model =
"39ed52f2a78e934b3ba6e2a89f5b1c712de7dfea535525255b1aa35c5565e08b";
const prompt = 'A photo of a cat';
try {
const response = await fetch(proxiedUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Token " + token,
},
body: JSON.stringify({
version: model,
input: { prompt: prompt },
}),
});
const data = await response.json();
console.log(data);
if (data.urls && data.urls.get) {
const pollingUrl =
"https://corsproxy.io/?" + encodeURIComponent(data.urls.get);
await pollForOutput(pollingUrl, token);
}
} catch (error) {
console.error("Error:", error);
}
}
async function pollForOutput(url, token) {
let hasOutput = false;
const maxPollAttempts = 10;
let pollAttempts = 0;
while (!hasOutput && pollAttempts < maxPollAttempts) {
try {
const pollResponse = await fetch(url, {
headers: {
"Content-Type": "application/json",
Authorization: "Token " + token,
},
});
const pollData = await pollResponse.json();
console.log(pollData);
if (pollData.output) {
hasOutput = true;
console.log("Output:", pollData.output);
//display the image on screen
const img = document.createElement("img");
img.src = pollData.output[0];
document.body.appendChild(img);
} else {
// Wait for 5 seconds before the next poll
await new Promise((resolve) => setTimeout(resolve, 5000));
}
} catch (error) {
console.error("Error while polling:", error);
break;
}
}
}