document.write(`
<!DOCTYPE html>
<html>
<head>
<title>Design you space using AI!</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://threejs.org/build/three.js"></script>
<style>
body {
margin: 0;
}
canvas {
display: block;
}
#input_fields {
position: absolute;
top: 10px;
left: 10px;
z-index: 1000;
}
input, select, button {
margin-top: 5px;
}
.description-input {
width: 300px;
/* Add more styling for the description input if needed */
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
/* Add other styles as needed */
}
</style>
</head>
<body>
<div id="input_fields">
<!-- UI container -->
<h1>Simple AI design Illustrator</h1>
<p>This AI allows some to describe a room design and builds for them skecthes based on the inputs</p>
<div>
<label for="apiKey">Api Key:</label>
<input type="password" type="text" id="apiKey">
</div>
<div class="chat-log" id="dynamic_area">
<!-- Chat log will be displayed here -->
</div>
<div class="dynamic-input" id="dynamic-input">
<!-- Drop down will be generated here -->
<div class="chat-log" id="start_input">
<label for="space">Select your space :</label>
<select id="space">
<option value="Home">Home</option>
<option value="Office">Office</option>
<option value="Hotel">Hotel</option>
<option value="School">School</option>
</select>
</div>
</div>
</div>
<div id="sceneContainer"></div>
<script>
// Three.js scene variables
let scene, camera, renderer, cube;
var selectedOptions = {};
var spaceSelect = document.getElementById("space");
// Add an onchange event listener
spaceSelect.addEventListener("change", function() {
// Get the selected value
var selectedSpace = spaceSelect.value;
selectedOptions['roomType'] = selectedSpace;
deleteAllDivs();
generateRequest('wallColor', 'Please select your prefered wall Color', selectedSpace);
// Do something with the selected value
// console.log("Selected space: " + selectedSpace);
});
// Function to create a sentence from selected options
function createSentence(options, nextOption) {
var sentence = "Given a";
// Loop through key-value pairs in the options object
for (var key in options) {
if (options.hasOwnProperty(key)) {
var value = options[key];
// Add key and value to the sentence if the value is not null
if (value !== null) {
sentence += " " + key + " " + value + ", ";
}
}
}
// Add the final part of the sentence
sentence += ", generate a list of possible " + nextOption + ". Make it a comma separated list without bullets, hyphens or numbers";
return sentence;
}
function generateRequest(label_name, label_text, selectedOption) {
var apiKey = document.getElementById('apiKey').value;
var authorizationHeader = 'Bearer ' + apiKey;
// Show error if API key is not entered
var logContainer = document.getElementById('dynamic_area');
var errorDiv = logContainer.querySelector('.error-message');
console.log("Selected option: " + selectedOption);
if (errorDiv) {
// Remove the error log div
logContainer.removeChild(errorDiv);
}
if (!apiKey) {
dynamic_area.innerHTML += '<div class="error-message">ERROR: Please provide an API key</div>';
console.log('API key is missing.');
return;
}
var statement = createSentence(selectedOptions, label_name);
console.log('statement :', statement);
var url = 'https://api.openai.com/v1/engines/text-davinci-003/completions';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': authorizationHeader
},
body: JSON.stringify({
prompt: statement,
'max_tokens': 250,
'temperature': 1
}),
})
.then(response => response.json())
.then(data => {
var textReturned = data.choices[0].text;
console.log('Response :', textReturned);
//var roomArray = textReturned.split('\\n').filter(Boolean);
var roomArray = textReturned.split(',').filter(Boolean);
createDropdown(label_name, label_text, roomArray);
})
.catch(error => {
console.error('Error:', error);
});
}
// Function to create and return a new dropdown
function createDropdown(label_name, label_text, roomArray) {
// Generate dynamic IDs
var divId = "dropdown-" + label_name;
var selectId = "select-" + label_name;
// Create a new div with a dynamic ID
var newDiv = document.createElement("div");
newDiv.className = "another-div";
newDiv.id = divId;
// Create a new label for the dropdown
var label = document.createElement("label");
label.for = selectId;
label.innerText = label_text;
// Create a new select element with a dynamic ID
var newSelect = document.createElement("select");
newSelect.id = selectId;
// Add options to the select element
roomArray.forEach(function(room, index) {
var option = document.createElement("option");
option.value = room;
option.text = room;
newSelect.add(option);
});
// Append label and select to the new div
newDiv.appendChild(label);
newDiv.appendChild(newSelect);
// Append the new div to the existing div
document.getElementById("dynamic-input").appendChild(newDiv);
// Add event listener for the new select element
newSelect.addEventListener("change", function() {
var selectedSpace = newSelect.value;
console.log("Selected space: " + selectedSpace);
selectedOptions[label_name] = selectedSpace;
deleteDivs(divId);
if (label_name === "wallColor") {
generateRequest('floorType', 'Please select prefered floorType : ', selectedSpace);
}
else if (label_name === "floorType") {
generateRequest('lighting', 'Please select prefered lighting : ', selectedSpace);
}
else if (label_name === "lighting") {
generateRequest('theme', 'Please select prefered theme : ', selectedSpace);
}
else if (label_name === "theme") {
generateRequest('furniture', 'Please select prefered furniture : ', selectedSpace);
}
else if (label_name === "furniture") {
generateRequest('decor', 'Please select prefered decor :', selectedSpace);
}
else if (label_name === "decor") {
generateRequest('texture', 'Please select prefered texture', selectedSpace);
}
else if (label_name === "texture") {
generateResponse();
}
});
}
function deleteAllDivs() {
// Get the reference to the dynamic-input div
var dynamicInputDiv = document.getElementById("dynamic-input");
// Get all divs within dynamic-input div
var allDivs = dynamicInputDiv.querySelectorAll("div");
// Find the index of the div to delete
var deleteIndex = 0;
// Remove divs after the specified one
for (var i = allDivs.length - 1; i > deleteIndex; i--) {
dynamicInputDiv.removeChild(allDivs[i]);
}
}
function deleteDivs(divId) {
// Get the reference to the dynamic-input div
var dynamicInputDiv = document.getElementById("dynamic-input");
// Get all divs within dynamic-input div
var allDivs = dynamicInputDiv.querySelectorAll("div");
// Find the index of the div to delete
var deleteIndex = Array.from(allDivs).findIndex(div => div.id === divId);
// Remove divs after the specified one
for (var i = allDivs.length - 1; i > deleteIndex; i--) {
dynamicInputDiv.removeChild(allDivs[i]);
}
}
// Generate the image
function generateResponse() {
var apiKey = document.getElementById('apiKey').value;
var authorizationHeader = 'Bearer ' + apiKey;
// Show error if API key is not entered
var logContainer = document.getElementById('dynamic_area');
var errorDiv = logContainer.querySelector('.error-message');
if (errorDiv) {
// Remove the error log div
logContainer.removeChild(errorDiv);
}
if (!apiKey) {
dynamic_area.innerHTML += '<div class="error-message">ERROR: Please provide an API key</div>';
console.log('API key is missing.');
return;
}
// var description = document.getElementById('userInput').value;
// document.getElementById('userInput').innerHTML = ''; // Clear user input message
var description = 'Create a 3D rendered image of a room design from an interior perspective. This need to match the following parametes ' + selectedOptions;
var url = 'https://api.openai.com/v1/images/generations';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': authorizationHeader
},
body: JSON.stringify({
prompt: description,
size: '1024x1024',
quality: 'standard',
n: 1,
}),
})
.then(response => response.json())
.then(outputdata => {
var imageUrl = outputdata.data[0].url;
applyImageToAllFaces(imageUrl)
console.log('Response :', imageUrl);
})
.catch(error => {
console.error('Error:', error);
});
}
function setupScene() {
// Create a new scene
scene = new THREE.Scene();
// Set the background color to sky blue
scene.background = new THREE.Color('#FFFFFF');
// Create a perspective camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// Create a WebGL renderer
renderer = new THREE.WebGLRenderer();
// Set the size of the renderer to match the window size
renderer.setSize(window.innerWidth, window.innerHeight);
// Append the renderer's DOM element to the 'sceneContainer' element in your HTML
document.getElementById('sceneContainer').appendChild(renderer.domElement);
// Set up a cube with a box geometry
const geometry = new THREE.BoxGeometry(5, 5, 5);
// Use a Lambert material for better lighting effects
const material = new THREE.MeshLambertMaterial({ color: 0xffffff });
// Create a mesh with the geometry and material
cube = new THREE.Mesh(geometry, material);
// Add the cube to the scene
scene.add(cube);
// Set the camera position
camera.position.z = 10;
// Add ambient light to the scene for better visibility
const ambientLight = new THREE.AmbientLight(0x0fffff, 0.5);
scene.add(ambientLight);
// Add a directional light to cast shadows
const directionalLight = new THREE.DirectionalLight(0xffff0f, 0.5);
directionalLight.position.set(5, 5, 5);
scene.add(directionalLight);
display();
}
function display() {
requestAnimationFrame(display);
renderer.render(scene, camera);
}
function applyImageToAllFaces(imageUrl) {
//To solve CORS https issue
const proxyUrl = 'https://corsproxy.io/?' + encodeURIComponent(imageUrl);
new THREE.TextureLoader().load(proxyUrl, function(tex) {
const materials = [];
for (let i = 0; i < 6; i++) {
materials.push(new THREE.MeshBasicMaterial({ map: tex }));
}
cube.material = materials;
});
}
// Initializes the scene
setupScene();
</script>
</body>
</html>
`);