-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
522 lines (485 loc) · 19.9 KB
/
index.html
File metadata and controls
522 lines (485 loc) · 19.9 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Image Compressor</title>
<style>
/* Basic Reset & Body Styling */
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-color: #111827; /* bg-gray-900 */
color: #ffffff; /* text-white */
}
/* Main App Container */
.app-container {
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
padding: 1rem;
}
@media (min-width: 768px) {
.app-container {
padding: 2rem;
}
}
.content-wrapper {
width: 100%;
max-width: 80rem; /* max-w-7xl */
margin: 0 auto;
}
/* Header */
.app-header {
text-align: center;
margin-bottom: 2rem;
}
.app-title {
font-size: 2.25rem; /* text-4xl */
font-weight: 700;
background-image: linear-gradient(to right, #a78bfa, #ec4899);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
@media (min-width: 768px) {
.app-title {
font-size: 3rem; /* md:text-5xl */
}
}
.app-subtitle {
color: #9ca3af; /* text-gray-400 */
margin-top: 0.5rem;
}
/* Main Content Area */
.main-content {
background-color: rgba(31, 41, 55, 0.5); /* bg-gray-800/50 */
border-radius: 1rem; /* rounded-2xl */
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); /* shadow-2xl */
padding: 1.5rem;
border: 1px solid #374151; /* border-gray-700 */
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
}
@media (min-width: 768px) {
.main-content {
padding: 2rem;
}
}
/* Upload Box */
.upload-box {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 20rem; /* h-80 */
border: 2px dashed #4b5563; /* border-dashed border-gray-600 */
border-radius: 0.75rem; /* rounded-xl */
text-align: center;
}
.upload-icon {
width: 4rem; /* w-16 */
height: 4rem; /* h-16 */
color: #6b7280; /* text-gray-500 */
margin-bottom: 1rem;
}
.upload-box h3 {
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 0.5rem;
}
.upload-box p {
color: #9ca3af; /* text-gray-400 */
margin-bottom: 1rem;
}
/* Buttons */
.btn {
padding: 0.75rem 1.5rem;
border-radius: 0.5rem; /* rounded-lg */
font-weight: 600;
border: none;
cursor: pointer;
transition: transform 0.2s, background-color 0.2s;
display: inline-flex;
align-items: center;
justify-content: center;
}
.btn:hover {
transform: scale(1.05);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-primary {
background-color: #9333ea; /* bg-purple-600 */
color: white;
}
.btn-primary:hover:not(:disabled) {
background-color: #7e22ce; /* hover:bg-purple-700 */
}
.btn-gradient {
background-image: linear-gradient(to right, #a855f7, #ec4899); /* from-purple-500 to-pink-500 */
color: white;
font-size: 1.125rem; /* text-lg */
}
.btn-gradient:hover:not(:disabled) {
background-image: linear-gradient(to right, #9333ea, #db2777); /* hover:from-purple-600 hover:to-pink-600 */
}
.btn-secondary {
background-color: #4b5563; /* bg-gray-600 */
color: white;
}
.btn-secondary:hover:not(:disabled) {
background-color: #374151; /* hover:bg-gray-700 */
}
/* Image Grid */
.image-grid {
display: grid;
grid-template-columns: 1fr;
gap: 1.5rem;
}
@media (min-width: 768px) {
.image-grid {
grid-template-columns: repeat(3, 1fr);
}
}
/* Image Card */
.image-card {
background-color: #1f2937; /* bg-gray-800 */
padding: 1rem;
border-radius: 0.5rem; /* rounded-lg */
display: flex;
flex-direction: column;
justify-content: space-between;
text-align: center;
}
.image-card h3 {
font-weight: 700;
font-size: 1.125rem; /* text-lg */
margin-bottom: 0.5rem;
}
.image-placeholder {
aspect-ratio: 1 / 1;
background-color: #111827; /* bg-gray-900 */
border-radius: 0.25rem; /* rounded-md */
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
color: #6b7280; /* text-gray-500 */
}
.image-card img {
width: 100%;
height: 100%;
object-fit: contain;
}
.image-info {
margin-top: 1rem;
height: 1.5rem; /* h-6 */
}
.image-size-badge {
font-family: monospace;
background-color: rgba(55, 65, 81, 0.5); /* bg-gray-700/50 */
border-radius: 9999px; /* rounded-full */
padding: 0.25rem 0.75rem;
display: inline-block;
font-size: 0.875rem; /* text-sm */
}
/* Controls Section */
.controls-section {
margin-top: 2rem;
padding-top: 1.5rem;
border-top: 1px solid #374151; /* border-gray-700 */
}
.controls-layout {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
gap: 1.5rem;
}
@media (min-width: 768px) {
.controls-layout {
flex-direction: row;
gap: 1rem;
}
}
.slider-container {
width: 100%;
}
@media (min-width: 768px) {
.slider-container {
width: 50%;
}
}
.slider-container label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: #d1d5db; /* text-gray-300 */
}
.slider {
width: 100%;
}
.button-group {
display: flex;
gap: 1rem;
}
.error-message {
color: #f87171; /* text-red-400 */
text-align: center;
margin-top: 1rem;
}
.hidden-input {
display: none;
}
/* Spinner Animation */
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spinner {
animation: spin 1s linear infinite;
width: 1.25rem;
height: 1.25rem;
margin-right: 0.75rem;
}
.spinner-wrapper{
display: flex;
flex-direction: column;
align-items: center;
}
</style>
</head>
<body>
<div id="root">
<!-- App will be rendered here by JavaScript -->
</div>
<script>
// --- STATE MANAGEMENT ---
let state = {
originalImage: null,
originalImageURL: '',
compressedImageURL: '',
superResolvedImageURL: '',
compressionLevel: 95,
isLoading: false,
originalSize: 0,
compressedSize: 0,
error: '',
};
// --- UTILITY FUNCTIONS ---
const formatBytes = (bytes) => {
if (!bytes || bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
// --- API CALL ---
async function callSuperResolutionAPI(base64ImageData) {
const apiKey = ""; // Canvas will provide key if needed
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image-preview:generateContent?key=${apiKey}`;
const payload = {
contents: [{
parts: [
{ text: "Act as an expert image restoration AI. You will be given a tiny, heavily compressed, low-quality image. Your task is to perform super-resolution to restore it to a high-quality, detailed photograph. Reconstruct missing details, sharpen features, and fix compression artifacts to make it look like a real, high-resolution photo. Do not add any new elements not present in the original, just enhance what is there." },
{ inlineData: { mimeType: "image/jpeg", data: base64ImageData } }
]
}],
generationConfig: {
responseModalities: ['IMAGE']
},
};
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorBody = await response.text();
console.error("API Error Response:", errorBody);
throw new Error(`API request failed with status ${response.status}`);
}
const result = await response.json();
const base64Data = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data;
if (base64Data) {
state.superResolvedImageURL = `data:image/png;base64,${base64Data}`;
} else {
console.error("No image data found in API response body:", result);
throw new Error("No image data found in API response.");
}
} catch (error) {
console.error("Error in API call:", error);
state.error = "Failed to get response from the AI model. Please try again.";
} finally {
state.isLoading = false;
renderApp(); // Re-render the app to show the final result or error
}
}
// --- EVENT HANDLERS ---
function handleImageUpload(event) {
const file = event.target.files[0];
if (file) {
if (!file.type.startsWith('image/')) {
state.error = 'Please upload a valid image file.';
renderApp();
return;
}
state.error = '';
state.originalImage = file;
state.originalImageURL = URL.createObjectURL(file);
state.originalSize = file.size;
state.compressedImageURL = '';
state.superResolvedImageURL = '';
state.compressedSize = 0;
renderApp();
}
}
async function handleProcessImage() {
if (!state.originalImage) {
state.error = 'Please upload an image first.';
renderApp();
return;
}
state.isLoading = true;
state.error = '';
state.compressedImageURL = '';
state.superResolvedImageURL = '';
state.compressedSize = 0;
renderApp(); // Show loading state
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = state.originalImageURL;
img.onload = async () => {
const reductionFactor = (100 - state.compressionLevel) / 100;
const newWidth = Math.max(1, img.width * reductionFactor);
const newHeight = Math.max(1, img.height * reductionFactor);
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
const compressedDataURL = canvas.toDataURL('image/jpeg', 0.1);
state.compressedImageURL = compressedDataURL;
const compressedBlob = await (await fetch(compressedDataURL)).blob();
state.compressedSize = compressedBlob.size;
renderApp(); // Show compressed image while AI is working
const base64ImageData = compressedDataURL.split(',')[1];
await callSuperResolutionAPI(base64ImageData);
};
img.onerror = () => {
state.error = 'Could not load the image for processing.';
state.isLoading = false;
renderApp();
}
}
function handleSliderChange(event) {
state.compressionLevel = Number(event.target.value);
document.getElementById('compressionLevelLabel').textContent = `Compression Level (Size Reduction: ${state.compressionLevel}%)`;
}
// --- RENDERING LOGIC ---
function getSpinnerHTML(isLarge = false) {
const svg = `
<svg class="spinner" style="${isLarge ? 'width: 2rem; height: 2rem;' : ''}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle style="opacity: 0.25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path style="opacity: 0.75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>`;
return isLarge ? `<div class="spinner-wrapper">${svg}</div>` : svg;
}
function getImageCardHTML(title, imageUrl, size, isLoading, isSuperResolved = false) {
let content;
if (isLoading) {
content = `
<div class="spinner-wrapper">
${getSpinnerHTML(true)}
<span style="margin-top: 0.5rem; font-size: 0.875rem; color: #9ca3af;">
${isSuperResolved ? "AI is enhancing..." : "Compressing..."}
</span>
</div>`;
} else if (imageUrl) {
content = `<img src="${imageUrl}" alt="${title}" />`;
} else {
content = `<div>Output will appear here</div>`;
}
return `
<div class="image-card">
<div>
<h3>${title}</h3>
<div class="image-placeholder">${content}</div>
</div>
<div class="image-info">
${size > 0 ? `<p class="image-size-badge">${formatBytes(size)}</p>` : ''}
</div>
</div>`;
}
function renderApp() {
const root = document.getElementById('root');
const uploadViewHTML = `
<div class="upload-box">
<svg class="upload-icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<h3>Upload an Image</h3>
<p>Drag & drop or click to select a file</p>
<button id="selectImageBtn" class="btn btn-primary">Select Image</button>
</div>`;
const resultsViewHTML = `
<div>
<div class="image-grid">
${getImageCardHTML('Original', state.originalImageURL, state.originalSize)}
${getImageCardHTML('Compressed', state.compressedImageURL, state.compressedSize, state.isLoading && !state.compressedImageURL)}
${getImageCardHTML('AI Super-Resolved', state.superResolvedImageURL, 0, state.isLoading && state.compressedImageURL && !state.superResolvedImageURL, true)}
</div>
<div class="controls-section">
<div class="controls-layout">
<div class="slider-container">
<label id="compressionLevelLabel" for="compressionLevel">Compression Level (Size Reduction: ${state.compressionLevel}%)</label>
<input id="compressionLevel" type="range" min="0" max="100" value="${state.compressionLevel}" class="slider" ${state.isLoading ? 'disabled' : ''}>
</div>
<div class="button-group">
<button id="changeImageBtn" class="btn btn-secondary" ${state.isLoading ? 'disabled' : ''}>Change Image</button>
<button id="processImageBtn" class="btn btn-gradient" ${state.isLoading ? 'disabled' : ''}>
${state.isLoading ? `${getSpinnerHTML()} Processing...` : 'Compress & Enhance'}
</button>
</div>
</div>
${state.error ? `<p class="error-message">${state.error}</p>` : ''}
</div>
</div>`;
const appHTML = `
<div class="app-container">
<div class="content-wrapper">
<header class="app-header">
<h1 class="app-title">AI Super Resolution Compressor</h1>
<p class="app-subtitle">Drastically compress your images, then use ML to restore them.</p>
</header>
<main class="main-content">
${!state.originalImage ? uploadViewHTML : resultsViewHTML}
<input type="file" id="fileInput" class="hidden-input" accept="image/*">
</main>
</div>
</div>`;
root.innerHTML = appHTML;
// --- ADD EVENT LISTENERS ---
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', handleImageUpload);
if (!state.originalImage) {
document.getElementById('selectImageBtn').addEventListener('click', () => fileInput.click());
} else {
document.getElementById('changeImageBtn').addEventListener('click', () => fileInput.click());
document.getElementById('processImageBtn').addEventListener('click', handleProcessImage);
document.getElementById('compressionLevel').addEventListener('input', handleSliderChange);
}
}
// --- INITIAL RENDER ---
document.addEventListener('DOMContentLoaded', renderApp);
</script>
</body>
</html>