-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
01version-deprecated.js
197 lines (159 loc) · 5.95 KB
/
01version-deprecated.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
//script.js
//script paso 2
async function generateAndDisplayArt() {
console.log("Button clicked");
const loadingMessage = document.getElementById('loadingMessage');
loadingMessage.style.display = 'block';
// Get user input
const userPrompt = document.getElementById('userPrompt').value || 'random complete';
// Generate art
const postOptions = {
method: 'POST',
headers: {
accept: 'application/json',
'content-type': 'application/json',
authorization: 'Bearer 45627a92-21bf-4099-8534-6335d475fc5f'
},
body: JSON.stringify({
height: 512,
modelId: '6bef9f1b-29cb-40c7-b9df-32b51c1f67d3',
prompt: userPrompt,
width: 512,
num_images: 1
})
};
let generationId;
try {
const response = await fetch('https://cloud.leonardo.ai/api/rest/v1/generations', postOptions);
const data = await response.json();
console.log("Generation Data:", data);
generationId = data.sdGenerationJob.generationId;
} catch (err) {
console.error("Error in generation:", err);
return;
}
// Poll for generated images
const getOptions = {
method: 'GET',
headers: {
accept: 'application/json',
authorization: 'Bearer 45627a92-21bf-4099-8534-6335d475fc5f'
}
};
let imageUrls = [];
const maxAttempts = 10;
let attempts = 0;
while (imageUrls.length === 0 && attempts < maxAttempts) {
try {
const response = await fetch(`https://cloud.leonardo.ai/api/rest/v1/generations/${generationId}`, getOptions);
const data = await response.json();
console.log("Image Data:", data);
imageUrls = data.generations_by_pk.generated_images.map(img => img.url);
if (imageUrls.length === 0) {
attempts++;
await new Promise(resolve => setTimeout(resolve, 2000)); // Wait for 2 seconds
} else {
displayImages(imageUrls);
}
} catch (err) {
console.error("Error in fetching images:", err);
}
}
}
// Function to display images on the webpage
// Function to display images on the webpage
function displayImages(imageUrls) {
const imageContainer = document.getElementById('imageContainer');
imageContainer.innerHTML = ''; // Clear previous images
imageUrls.forEach(url => {
const img = document.createElement('img');
img.src = url;
img.alt = 'Generated Art';
img.id = 'generatedImage'; // Asignar el ID aquí
img.style.width = '300px';
img.style.height = '300px';
imageContainer.appendChild(img);
});
}
// Attach event listener to button
document.getElementById('generateButton').addEventListener('click', generateAndDisplayArt);
// Función para actualizar el brillo y el contraste de la imagen
function updateImageFilter() {
const brightness = document.getElementById('brightness').value;
const contrast = document.getElementById('contrast').value;
// Obtener la imagen clonada por su nuevo ID
const filteredImage = document.getElementById('filteredImage');
if (filteredImage) {
filteredImage.style.filter = `brightness(${brightness}%) contrast(${contrast}%)`;
}
}
// Agregar event listeners a los controles deslizantes
const brightnessSlider = document.getElementById('brightness');
const contrastSlider = document.getElementById('contrast');
brightnessSlider.addEventListener('input', updateImageFilter);
contrastSlider.addEventListener('input', updateImageFilter);
//paso6
// Función para generar una nota aleatoria
function randomNote() {
const notes = [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88]; // Notas correspondientes a C4, D4, E4, F4, G4, A4, B4
return notes[Math.floor(Math.random() * notes.length)];
}
// Función para generar y tocar una melodía aleatoria
function generateMelody() {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
// Configurar el oscilador para tocar una nota aleatoria
oscillator.type = 'sine';
// Iniciar el oscilador
oscillator.start();
// Cambiar la nota cada 0.5 segundos
let time = audioContext.currentTime;
for (let i = 0; i < 4; i++) { // 4 notas en 2 segundos
oscillator.frequency.setValueAtTime(randomNote(), time);
time += 0.5;
}
// Detener el oscilador después de 2 segundos
oscillator.stop(audioContext.currentTime + 2);
}
// Añadir un event listener al botón para generar la melodía
const generateMelodyButton = document.getElementById('generateMelody');
generateMelodyButton.addEventListener('click', generateMelody);
//paso7chatgpt
// Paso 7: Obtener respuesta de ChatGPT
function askChatGPT() {
console.log("askChatGPT function called");
document.getElementById('hiddenText').style.display = 'block';
console.log("Hidden text should now be visible");
// Get the user's question from the input
const userQuestion = document.getElementById('userPrompt').value;
// Set up the options for the POST request
const postOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer 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' // Replace with your actual API key
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: userQuestion }],
temperature: 0.7
})
};
fetch('https://api.openai.com/v1/chat/completions', postOptions)
.then(response => response.json())
.then(data => {
// Display the answer on the webpage
const answer = data.choices[0].message.content.trim();
document.getElementById('gptAnswer').innerText = answer;
})
.catch(error => {
console.error('Error communicating with OpenAI API:', error);
});
}
// Add an event listener to the "Preguntar a ChatGPT" button
const askGptButton = document.getElementById('askGptButton');
askGptButton.addEventListener('click', askChatGPT);
// Hide the "Paso 8" text initially