-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
242 lines (210 loc) · 10.4 KB
/
index.html
File metadata and controls
242 lines (210 loc) · 10.4 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Image & Caption Generator</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Inter', sans-serif;
}
.loader {
border-top-color: #3498db;
-webkit-animation: spin 1s linear infinite;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 flex items-center justify-center min-h-screen p-4">
<div class="w-full max-w-2xl bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 md:p-8 space-y-6">
<div class="text-center">
<h1 class="text-3xl font-bold text-gray-800 dark:text-white">AI Image & Caption Generator</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">Create stunning visuals with a descriptive prompt.</p>
</div>
<!-- Input Form -->
<div class="space-y-4">
<div>
<label for="prompt" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Image Prompt</label>
<textarea id="prompt" rows="3" class="w-full p-3 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition" placeholder="e.g., A photo of a cute corgi wearing a chef's hat in a kitchen"></textarea>
</div>
<button id="generate-btn" class="w-full bg-blue-600 text-white font-semibold py-3 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition duration-300 ease-in-out transform hover:scale-105">
Generate Image
</button>
</div>
<!-- Status and Result Area -->
<div id="status-container" class="hidden text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg space-y-3">
<div class="flex items-center justify-center space-x-3">
<div id="loader" class="loader ease-linear rounded-full border-4 border-t-4 border-gray-200 h-8 w-8"></div>
<p id="status" class="text-lg font-medium text-gray-700 dark:text-gray-300">Initializing...</p>
</div>
<p id="error" class="text-red-500 text-sm hidden"></p>
</div>
<div id="result-container" class="hidden text-center">
<h2 class="text-xl font-semibold mb-4">Generated Image</h2>
<div class="relative group">
<canvas id="canvas" class="w-full h-auto rounded-lg shadow-md"></canvas>
</div>
<a id="download-link" href="#" class="mt-4 inline-block bg-green-600 text-white font-semibold py-2 px-6 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition duration-300">Download Image</a>
</div>
</div>
<script>
const generateBtn = document.getElementById('generate-btn');
const promptInput = document.getElementById('prompt');
const statusContainer = document.getElementById('status-container');
const statusEl = document.getElementById('status');
const errorEl = document.getElementById('error');
const resultContainer = document.getElementById('result-container');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const downloadLink = document.getElementById('download-link');
const loader = document.getElementById('loader');
// This is the URL of our local server, which we will use instead of calling Replicate directly.
const SERVER_URL = 'http://localhost:3001';
generateBtn.addEventListener('click', async () => {
const prompt = promptInput.value.trim();
if (!prompt) {
showError("Please enter a prompt.");
return;
}
// Reset UI
hideError();
resultContainer.classList.add('hidden');
statusContainer.classList.remove('hidden');
generateBtn.disabled = true;
generateBtn.classList.add('opacity-50', 'cursor-not-allowed');
try {
// --- Step 1: Generate the image ---
updateStatus('1/3: Generating image...');
const imageUrl = await generateImage(prompt);
// --- Step 2: Generate the caption ---
updateStatus('2/3: Generating clever caption...');
const caption = await generateCaption(imageUrl);
// --- Step 3: Draw image and caption on canvas ---
updateStatus('3/3: Finalizing image...');
await drawImageWithCaption(imageUrl, caption);
// --- Final Step: Show the result ---
statusContainer.classList.add('hidden');
resultContainer.classList.remove('hidden');
} catch (err) {
console.error('An error occurred:', err);
showError(err.message || 'An unknown error occurred. Check the console.');
updateStatus('Failed!', true);
} finally {
generateBtn.disabled = false;
generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
}
});
// Makes a request to our local server to generate the image
async function generateImage(prompt) {
const response = await fetch(`${SERVER_URL}/api/generate-image`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Image generation failed: ${errorData.error}`);
}
const data = await response.json();
return data.imageUrl;
}
// Makes a request to our local server to generate the caption
async function generateCaption(imageUrl) {
const response = await fetch(`${SERVER_URL}/api/generate-caption`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ imageUrl }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Caption generation failed: ${errorData.error}`);
}
const data = await response.json();
return data.caption;
}
async function drawImageWithCaption(imageUrl, caption) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "Anonymous"; // Required for loading images from other domains
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
// --- Caption styling ---
const fontSize = Math.max(24, Math.floor(img.width / 25));
ctx.font = `bold ${fontSize}px 'Inter', sans-serif`;
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
// --- Text shadow for better visibility ---
ctx.shadowColor = 'black';
ctx.shadowBlur = 7;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
const x = canvas.width / 2;
const y = canvas.height - (fontSize * 0.8); // Padding from bottom
// Wrap text if necessary
wrapText(ctx, caption.trim(), x, y, canvas.width * 0.9, fontSize * 1.2);
// --- Set download link ---
downloadLink.href = canvas.toDataURL('image/png');
downloadLink.download = `${promptInput.value.substring(0, 20).replace(/\s/g, '_') || 'generated_image'}.png`;
resolve();
};
img.onerror = (err) => {
console.error("Image load error", err);
reject(new Error("Could not load the generated image to draw on it."));
};
// Use our server as a proxy to fetch the image to avoid canvas CORS issues
img.src = `${SERVER_URL}/api/image-proxy?url=${encodeURIComponent(imageUrl)}`;
});
}
function wrapText(context, text, x, y, maxWidth, lineHeight) {
const words = text.split(' ');
let line = '';
let testLine;
let metrics;
let testWidth;
const lines = [];
for (let n = 0; n < words.length; n++) {
testLine = line + words[n] + ' ';
metrics = context.measureText(testLine);
testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
lines.push(line);
line = words[n] + ' ';
} else {
line = testLine;
}
}
lines.push(line);
// Adjust y to start drawing from the top of the wrapped text block
let currentY = y - (lines.length - 1) * lineHeight;
for (let i = 0; i < lines.length; i++) {
context.fillText(lines[i].trim(), x, currentY);
currentY += lineHeight;
}
}
function updateStatus(message, isError = false) {
statusEl.textContent = message;
if (isError) {
loader.classList.add('hidden');
} else {
loader.classList.remove('hidden');
}
}
function showError(message) {
errorEl.textContent = message;
errorEl.classList.remove('hidden');
}
function hideError() {
errorEl.classList.add('hidden');
}
</script>
</body>
</html>