-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1265 lines (1065 loc) · 50.1 KB
/
script.js
File metadata and controls
1265 lines (1065 loc) · 50.1 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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let instructions = [];
let selectedImageSrc = 'CircleStart.png'; // Track the current image source
let rejectedImageSrc = 'CircleStart.png'; // Track the current image source
let generationCount = 0; // Track iteration number
let storedApiKey = null; // Store API key to avoid asking every time
let variantChosen = false; // Track if user has chosen a variant
let variant1Data = null; // Store variant 1 data
let variant2Data = null; // Store variant 2 data
let generationsHistory = []; // Store all generations history
// Vote counting system (3 clicks required)
let variant1Votes = 0; // Count votes for variant 1
let variant2Votes = 0; // Count votes for variant 2
const VOTES_REQUIRED = 3; // Number of clicks needed to proceed
// Raspberry Pi configuration
const RASPBERRY_PI_IP = '10.112.20.53';
const RASPBERRY_PI_PORT = '8765';
const RASPBERRY_PI_BASE_URL = `ws://${RASPBERRY_PI_IP}:${RASPBERRY_PI_PORT}`;
// Retry configuration constants
const MAX_RETRY_ATTEMPTS = 3;
const RETRY_DELAY_MS = 5000; // 5 seconds
// ========================
// LOADING CONTROL FUNCTIONS
// ========================
function showLoadingIndicators(message = 'Generating new images') {
const loading1 = document.getElementById('generationLoading1');
const loading2 = document.getElementById('generationLoading2');
// Hide all variant content (images, texts, buttons)
hideVariantContent();
if (loading1) {
loading1.textContent = message;
loading1.style.display = 'block';
}
if (loading2) {
loading2.textContent = message;
loading2.style.display = 'block';
}
}
function hideLoadingIndicators() {
const loading1 = document.getElementById('generationLoading1');
const loading2 = document.getElementById('generationLoading2');
if (loading1) loading1.style.display = 'none';
if (loading2) loading2.style.display = 'none';
// Show all variant content (images, texts, buttons)
showVariantContent();
}
function updateLoadingMessage(message) {
const loading1 = document.getElementById('generationLoading1');
const loading2 = document.getElementById('generationLoading2');
if (loading1) {
loading1.textContent = message;
}
if (loading2) {
loading2.textContent = message;
}
}
function hideVariantContent() {
// Hide images
const img1 = document.getElementById('generatedImage1');
const img2 = document.getElementById('generatedImage2');
if (img1) img1.style.display = 'none';
if (img2) img2.style.display = 'none';
// Hide instruction texts
const instruction1 = document.getElementById('usedInstruction1');
const instruction2 = document.getElementById('usedInstruction2');
if (instruction1) instruction1.style.display = 'none';
if (instruction2) instruction2.style.display = 'none';
// Hide choose buttons
const chooseButton1 = document.getElementById('chooseVariant1');
const chooseButton2 = document.getElementById('chooseVariant2');
if (chooseButton1) chooseButton1.style.display = 'none';
if (chooseButton2) chooseButton2.style.display = 'none';
}
function showVariantContent() {
// Show images
const img1 = document.getElementById('generatedImage1');
const img2 = document.getElementById('generatedImage2');
if (img1) img1.style.display = 'block';
if (img2) img2.style.display = 'block';
// Show instruction texts
const instruction1 = document.getElementById('usedInstruction1');
const instruction2 = document.getElementById('usedInstruction2');
if (instruction1) instruction1.style.display = 'block';
if (instruction2) instruction2.style.display = 'block';
// Show choose buttons
const chooseButton1 = document.getElementById('chooseVariant1');
const chooseButton2 = document.getElementById('chooseVariant2');
if (chooseButton1) chooseButton1.style.display = 'block';
if (chooseButton2) chooseButton2.style.display = 'block';
// Initialize vote display when variants are shown
updateVoteDisplay();
}
// ========================
// LOCALSTORAGE SYNC FUNCTIONS
// ========================
function saveToLocalStorage(key, value) {
try {
localStorage.setItem(key, value);
console.log(`Saved to localStorage: ${key} (${value.length} chars)`);
// Verify the save worked
const retrieved = localStorage.getItem(key);
if (retrieved !== value) {
console.error(`localStorage verification failed for ${key}`);
}
} catch (error) {
console.error(`Error saving to localStorage: ${key}`, error);
if (error.name === 'QuotaExceededError') {
console.error('localStorage quota exceeded - clearing old data');
// Clear some old data and retry
localStorage.removeItem('variant1_img');
localStorage.removeItem('variant2_img');
try {
localStorage.setItem(key, value);
console.log(`Retry successful for ${key}`);
} catch (retryError) {
console.error(`Retry failed for ${key}`, retryError);
}
}
}
}
function getFromLocalStorage(key, defaultValue = null) {
try {
const value = localStorage.getItem(key);
return value !== null ? value : defaultValue;
} catch (error) {
console.error(`Error reading from localStorage: ${key}`, error);
return defaultValue;
}
}
// Save generation state for variant pages
function updateVariantPages() {
saveToLocalStorage('generationCount', generationCount.toString());
saveToLocalStorage('isGenerating', 'false');
}
// Convert instruction verbs to past tense
function convertToPastTense(instruction) {
if (!instruction) return instruction;
// Common verb conversions for image generation instructions
const verbConversions = {
'give': 'gave',
'make': 'made',
'duplicate': 'duplicated',
'place': 'placed',
'blow': 'blew',
'turn': 'turned',
'discipline': 'disciplined',
'simplify': 'simplified',
'change': 'changed',
'adapt': 'adapted',
'look': 'looked',
'introduce': 'introduced',
'remove': 'removed',
'add': 'added',
'reduce': 'reduced',
'wrap': 'wrapped',
'let': 'let',
'emphasize': 'emphasized',
'blur': 'blurred',
'have': 'had',
'amplify': 'amplified',
'convert': 'converted',
'clean': 'cleaned',
'abstract': 'abstracted',
'erase': 'erased',
'delete': 'deleted',
'zoom': 'zoomed',
'rebuild': 'rebuilt',
'tone': 'toned',
'offer': 'offered',
'use': 'used',
'cut': 'cut',
'smudge': 'smudged',
'create': 'created',
'draw': 'drew',
'paint': 'painted',
'transform': 'transformed',
'modify': 'modified',
'apply': 'applied',
'enhance': 'enhanced',
'increase': 'increased',
'sharpen': 'sharpened',
'brighten': 'brightened',
'darken': 'darkened',
'rotate': 'rotated',
'flip': 'flipped',
'crop': 'cropped',
'resize': 'resized',
'scale': 'scaled',
'shift': 'shifted',
'move': 'moved',
'adjust': 'adjusted',
'distort': 'distorted',
'stretch': 'stretched',
'compress': 'compressed',
'expand': 'expanded',
'invert': 'inverted',
'reverse': 'reversed',
'mirror': 'mirrored',
'skew': 'skewed',
'tilt': 'tilted',
'bend': 'bent',
'twist': 'twisted',
'warp': 'warped'
};
// Split instruction into words
const words = instruction.split(' ');
// Convert first word (verb) if it exists in our conversion map
if (words.length > 0 && verbConversions[words[0].toLowerCase()]) {
words[0] = verbConversions[words[0].toLowerCase()];
// Capitalize first letter
words[0] = words[0].charAt(0).toUpperCase() + words[0].slice(1);
}
return words.join(' ');
}
// Load instructions from JSON file
async function loadInstructions() {
try {
const response = await fetch('instructions.json');
const data = await response.json();
instructions = data.random_instructions;
updateInstructionsCounter();
console.log(`Loaded ${instructions.length} instructions`);
} catch (error) {
console.error('Error loading instructions:', error);
alert('Error loading instructions file');
}
}
// Get random instruction
function getRandomInstruction() {
if (instructions.length === 0) {
return "Transform this image"; // Fallback if all instructions are used
}
return instructions[Math.floor(Math.random() * instructions.length)];
}
// Remove instruction from the list
function removeInstruction(instructionElement) {
// Get the original instruction from dataset if it exists, otherwise use the text content
const originalInstruction = instructionElement.dataset?.originalInstruction || instructionElement.textContent;
const index = instructions.indexOf(originalInstruction);
if (index > -1) {
instructions.splice(index, 1);
console.log(`Removed instruction: "${originalInstruction}". Remaining: ${instructions.length}`);
updateInstructionsCounter();
}
}
// Update the instructions counter display
function updateInstructionsCounter() {
const counter = document.getElementById('instructionsCount');
const container = document.getElementById('instructionsCounter');
if (counter && container) {
counter.textContent = instructions.length;
// Show counter after first generation
if (instructions.length < 70) { // Assuming original count was around 70
container.style.display = 'block';
}
// Change color when running low
if (instructions.length < 10) {
container.style.background = '#ffeeee';
container.style.borderColor = '#ff0000';
} else if (instructions.length < 25) {
container.style.background = '#fff8ee';
container.style.borderColor = '#ff8800';
}
}
}
// Convert image to base64 (handles both URLs and data URLs)
async function imageToBase64(imageSource) {
// If it's already a data URL, extract the base64 part
if (imageSource.startsWith('data:')) {
return imageSource.split(',')[1];
}
// If it's a regular URL, fetch and convert
const response = await fetch(imageSource);
const blob = await response.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.readAsDataURL(blob);
});
}
// Generate two image variants using Gemini 2.5 Flash Image
async function generateImage() {
const generateButton = document.getElementById('generateButton');
const currentGenerationContainer = document.getElementById('currentGenerationContainer');
try {
// If this is not the first generation and no variant was chosen,
// ask user to choose first
if (generationCount > 0 && !variantChosen && (variant1Data || variant2Data)) {
alert('Please choose a variant from the current generation first!');
return;
}
generateButton.disabled = true;
// Show current generation container with loading dots
currentGenerationContainer.style.display = 'block';
document.getElementById('variantsContent').style.display = 'block';
showLoadingIndicators();
// Reset variant chosen state and vote counts for new generation
variantChosen = false;
resetVoteCounts();
generationCount++;
// Save generation state to localStorage
saveToLocalStorage('isGenerating', 'true');
saveToLocalStorage('generationCount', generationCount.toString());
// Convert current image to base64 (iterative: use last generated or original)
console.log('Converting image to base64, source:', selectedImageSrc, rejectedImageSrc);
const selectedImageBase64 = await imageToBase64(selectedImageSrc);
const rejectedImageBase64 = await imageToBase64(rejectedImageSrc);
// Validate base64 data
if (!selectedImageBase64 || selectedImageBase64.length < 100) {
throw new Error('Invalid image data - base64 conversion failed');
}
console.log('Base64 conversion successful, size:', selectedImageBase64.length, 'chars');
// Get API key (ask only once, then store it)
if (!storedApiKey) {
storedApiKey = prompt('Please enter your Google AI API key:');
if (!storedApiKey) {
throw new Error('API key is required');
}
}
// Validate API key format (basic check)
if (!storedApiKey.startsWith('AIza') || storedApiKey.length < 30) {
console.warn('API key format might be incorrect');
}
// Generate two variants with different instructions
const instruction1 = getRandomInstruction();
let instruction2 = getRandomInstruction();
// Ensure the instructions are different
let attempts = 0;
while (instruction1 === instruction2 && attempts < 10) {
instruction2 = getRandomInstruction();
attempts++;
}
document.getElementById('usedInstruction1').textContent = convertToPastTense(instruction1);
document.getElementById('usedInstruction2').textContent = convertToPastTense(instruction2);
// Store original instructions for removal
document.getElementById('usedInstruction1').dataset.originalInstruction = instruction1;
document.getElementById('usedInstruction2').dataset.originalInstruction = instruction2;
// Generate first variant with retry mechanism
const variant1Promise = generateSingleVariantWithRetry(selectedImageBase64, instruction1, storedApiKey, rejectedImageBase64);
// Generate second variant with retry mechanism
const variant2Promise = generateSingleVariantWithRetry(selectedImageBase64, instruction2, storedApiKey, rejectedImageBase64);
// Wait for both variants to complete
const [variant1Result, variant2Result] = await Promise.all([variant1Promise, variant2Promise]);
// Display both variants
if (variant1Result && variant2Result) {
document.getElementById('generatedImage1').src = variant1Result;
document.getElementById('generatedImage2').src = variant2Result;
variant1Data = variant1Result;
variant2Data = variant2Result;
// Save variants to localStorage
saveToLocalStorage('variant1_img', variant1Result);
saveToLocalStorage('variant1_instruction', instruction1);
saveToLocalStorage('variant2_img', variant2Result);
saveToLocalStorage('variant2_instruction', instruction2);
saveToLocalStorage('isGenerating', 'false');
console.log(`Generation ${generationCount} saved - Variant2 image size:`, variant2Result.length, 'chars');
// Hide loading dots and show variants
hideLoadingIndicators();
document.getElementById('variantsContent').style.display = 'block';
// Re-initialize zoom for new variant images
setTimeout(() => {
const generatedImage1 = document.getElementById('generatedImage1');
const generatedImage2 = document.getElementById('generatedImage2');
// Re-add zoom functionality to new images (these are variant images that use voting)
makeImageZoomable(generatedImage1, `Generated Variant 1 - Generation ${generationCount}`, true);
makeImageZoomable(generatedImage2, `Generated Variant 2 - Generation ${generationCount}`, true);
}, 100);
// Initialize vote display and status message
const statusElement = document.getElementById('selectionStatus');
if (statusElement) {
statusElement.textContent = `Click 3 times on a variant to select it! | Variant 1: 0/3 votes | Variant 2: 0/3 votes`;
}
// Update button text - keep it enabled for manual use if needed
generateButton.textContent = `Or click here to generate iteration #${generationCount + 1}`;
generateButton.disabled = false;
// Update selection status if element exists
const selectionStatus = document.getElementById('selectionStatus');
if (selectionStatus) {
selectionStatus.textContent = 'Choose a variant to generate the next iteration';
}
const selectionStatusContainer = document.querySelector('.selection-status');
if (selectionStatusContainer) {
selectionStatusContainer.classList.remove('selected');
}
} else {
throw new Error('Failed to generate both variants');
}
} catch (error) {
console.error('Error generating image:', error);
const errorMessage = error.message || error.toString() || 'Unknown error occurred';
console.error('Error details:', {
message: error.message,
stack: error.stack,
name: error.name,
error: error
});
// Only show alert for critical errors that couldn't be retried
// (retryable errors like "No image found" and "RECITATION" are handled automatically by the retry mechanism)
const isRetryableError = errorMessage.includes('No image found in API response') ||
errorMessage.includes('RECITATION') ||
errorMessage.includes('Content blocked by AI safety filters');
if (!isRetryableError) {
alert(`Error generating image: ${errorMessage}\n\nYou can try choosing a variant again or generate a new image.`);
} else {
console.log('All retry attempts failed. The system tried 3 times with 5-second delays for AI safety filters or missing images.');
}
generateButton.disabled = false;
// Hide loading dots in case of error
hideLoadingIndicators();
// Reset variant chosen state so user can choose again
variantChosen = false;
// Remove selection styling from previous generation if it exists
document.getElementById('variant1Container').classList.remove('selected');
document.getElementById('variant2Container').classList.remove('selected');
const selectionStatusContainer = document.querySelector('.selection-status');
if (selectionStatusContainer) {
selectionStatusContainer.classList.remove('selected');
}
// Show previous variants if they exist (allow user to choose again)
if (variant1Data || variant2Data) {
document.getElementById('variantsContent').style.display = 'block';
const selectionStatus = document.getElementById('selectionStatus');
if (selectionStatus) {
const isRetryableError = errorMessage.includes('No image found in API response') ||
errorMessage.includes('RECITATION') ||
errorMessage.includes('Content blocked by AI safety filters');
if (isRetryableError) {
selectionStatus.textContent = 'Generation failed after 3 retry attempts (AI safety filters or technical issues). Choose a variant to try again or generate a new image.';
} else {
selectionStatus.textContent = 'Error occurred. Choose a variant to retry or generate a new image.';
}
}
// Re-enable choice buttons
const chooseButton1 = document.getElementById('chooseVariant1');
const chooseButton2 = document.getElementById('chooseVariant2');
if (chooseButton1) chooseButton1.disabled = false;
if (chooseButton2) chooseButton2.disabled = false;
}
// Clear localStorage error state
saveToLocalStorage('isGenerating', 'false');
}
}
// Generate a single variant
async function generateSingleVariant(imageBase64, instruction, apiKey, rejectedImageBase64) {
try {
console.log('Generating variant with instruction:', instruction);
console.log('Image data size:', imageBase64.length, 'chars');
const fullPrompt = `Modify the first image according to the following instruction: ${instruction}. The generated image should NEVER look the same as either of the provided images.`;
const requestBody = {
contents: [{
parts: [
{
inline_data: {
mime_type: "image/png",
data: imageBase64
}
},
{
inline_data: {
mime_type: "image/png",
data: rejectedImageBase64
}
},
{
text: fullPrompt
}
]
}],
generationConfig: {
temperature: 0.8,
candidateCount: 1,
maxOutputTokens: 2048,
}
};
console.log('Making API request to Gemini...');
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=${apiKey}`, {
method: 'POST',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorText = await response.text();
console.error('API Error Response:', errorText);
throw new Error(`API request failed: ${response.status} - ${errorText}`);
}
const result = await response.json();
console.log('API Response received:', result);
// Check if the response contains an image
if (result.candidates && result.candidates[0] && result.candidates[0].content && result.candidates[0].content.parts) {
const parts = result.candidates[0].content.parts;
console.log('Response parts:', parts);
for (const part of parts) {
console.log('Checking part:', part);
if (part.inlineData && part.inlineData.mimeType && part.inlineData.mimeType.startsWith('image/')) {
console.log('Found image part with mimeType:', part.inlineData.mimeType);
return `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`;
}
if (part.text) {
console.log('Found text part:', part.text);
}
}
} else {
console.log('Response structure unexpected:');
console.log('- result.candidates exists:', !!result.candidates);
if (result.candidates) {
console.log('- result.candidates[0] exists:', !!result.candidates[0]);
if (result.candidates[0]) {
console.log('- result.candidates[0].content exists:', !!result.candidates[0].content);
if (result.candidates[0].content) {
console.log('- result.candidates[0].content.parts exists:', !!result.candidates[0].content.parts);
}
}
}
}
// Check if there's an error message in the response
if (result.error) {
throw new Error(`API Error: ${result.error.message || JSON.stringify(result.error)}`);
}
// Check if the content was blocked or filtered
if (result.candidates && result.candidates[0] && result.candidates[0].finishReason) {
const finishReason = result.candidates[0].finishReason;
if (finishReason === 'SAFETY' || finishReason === 'RECITATION') {
throw new Error(`Content blocked by AI safety filters. Reason: ${finishReason}. Try a different instruction.`);
}
}
throw new Error('No image found in API response - the AI may have returned only text or encountered an issue generating the image');
} catch (error) {
console.error('Error in generateSingleVariant:', error);
// Don't wrap the error message again if it's already a custom error
if (error.message.startsWith('API Error:') || error.message.startsWith('Content blocked:') || error.message.startsWith('No image found:')) {
throw error;
}
throw new Error(`Network error: ${error.message || 'Failed to connect to API'}`);
}
}
// ========================
// RETRY WRAPPER FUNCTION
// ========================
async function generateSingleVariantWithRetry(imageBase64, instruction, apiKey, rejectedImageBase64, attemptNumber = 1) {
try {
console.log(`Generation attempt ${attemptNumber}/${MAX_RETRY_ATTEMPTS} for instruction: "${instruction.substring(0, 50)}..."`);
return await generateSingleVariant(imageBase64, instruction, apiKey, rejectedImageBase64);
} catch (error) {
console.error(`Attempt ${attemptNumber} failed:`, error.message);
// Check if this is an error we want to retry for
const isRetryableError = error.message.includes('No image found in API response') ||
error.message.includes('RECITATION') ||
error.message.includes('Content blocked by AI safety filters');
if (isRetryableError && attemptNumber < MAX_RETRY_ATTEMPTS) {
const errorType = error.message.includes('RECITATION') ? 'AI safety filter (RECITATION)' :
error.message.includes('Content blocked') ? 'AI safety filter' :
'Missing image in response';
console.log(`Retrying in ${RETRY_DELAY_MS / 1000} seconds... (Error: ${errorType})`);
// Wait for the specified delay
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
// Recursive retry
return await generateSingleVariantWithRetry(imageBase64, instruction, apiKey, rejectedImageBase64, attemptNumber + 1);
} else {
// If it's not a retryable error or we've exceeded max attempts, throw the error
throw error;
}
}
}
// ========================
// VARIANT SELECTION FUNCTIONS
// ========================
// Vote for variant 1 (3 votes required to proceed)
async function chooseVariant1() {
try {
// Show physical button feedback if triggered by physical button
if (window.physicalButtonsAvailable) {
showPhysicalButtonFeedback('variant1');
}
// Increment vote count
variant1Votes++;
console.log(`🗳️ Vote for Variant 1! Current votes: ${variant1Votes}/${VOTES_REQUIRED}`);
// Update vote display
updateVoteDisplay();
// Check if enough votes to proceed
if (variant1Votes >= VOTES_REQUIRED) {
console.log('✅ Variant 1 has enough votes! Proceeding...');
selectedImageSrc = variant1Data;
variantChosen = true;
// Remove the instruction from variant 2 (not chosen) from future use
const variant2InstructionElement = document.getElementById('usedInstruction2');
removeInstruction(variant2InstructionElement);
// Update UI to show final selection
document.getElementById('variant1Container').classList.add('selected');
document.getElementById('variant2Container').classList.remove('selected');
// Update selection status if element exists
const selectionStatus = document.getElementById('selectionStatus');
if (selectionStatus) {
selectionStatus.textContent = 'Variant 1 wins! Generating next iteration...';
if (selectionStatus.parentElement) {
selectionStatus.parentElement.classList.add('selected');
}
}
// Reset vote counts for next round
resetVoteCounts();
// Add current generation to history
addGenerationToHistory(1);
// Automatically start next generation
await generateImage();
} else {
// Not enough votes yet, just show feedback
const selectionStatus = document.getElementById('selectionStatus');
if (selectionStatus) {
selectionStatus.textContent = `Variant 1: ${variant1Votes}/${VOTES_REQUIRED} votes | Variant 2: ${variant2Votes}/${VOTES_REQUIRED} votes`;
}
}
} catch (error) {
console.error('Error in chooseVariant1:', error);
// Reset the selection state if generation fails
variantChosen = false;
document.getElementById('variant1Container').classList.remove('selected');
// Update selection status if element exists
const selectionStatus = document.getElementById('selectionStatus');
if (selectionStatus) {
selectionStatus.textContent = 'Error occurred. Please choose a variant again.';
if (selectionStatus.parentElement) {
selectionStatus.parentElement.classList.remove('selected');
}
}
}
}
// Vote for variant 2 (3 votes required to proceed)
async function chooseVariant2() {
try {
// Show physical button feedback if triggered by physical button
// Increment vote count
variant2Votes++;
console.log(`🗳️ Vote for Variant 2! Current votes: ${variant2Votes}/${VOTES_REQUIRED}`);
// Update vote display
updateVoteDisplay();
// Check if enough votes to proceed
if (variant2Votes >= VOTES_REQUIRED) {
console.log('✅ Variant 2 has enough votes! Proceeding...');
selectedImageSrc = variant2Data;
variantChosen = true;
// Remove the instruction from variant 1 (not chosen) from future use
const variant1InstructionElement = document.getElementById('usedInstruction1');
removeInstruction(variant1InstructionElement);
// Update UI to show final selection
document.getElementById('variant2Container').classList.add('selected');
document.getElementById('variant1Container').classList.remove('selected');
// Update selection status if element exists
const selectionStatus = document.getElementById('selectionStatus');
if (selectionStatus) {
selectionStatus.textContent = 'Variant 2 wins! Generating next iteration...';
if (selectionStatus.parentElement) {
selectionStatus.parentElement.classList.add('selected');
}
}
// Reset vote counts for next round
resetVoteCounts();
// Add current generation to history
addGenerationToHistory(2);
// Automatically start next generation
await generateImage();
} else {
// Not enough votes yet, just show feedback
const selectionStatus = document.getElementById('selectionStatus');
if (selectionStatus) {
selectionStatus.textContent = `Variant 1: ${variant1Votes}/${VOTES_REQUIRED} votes | Variant 2: ${variant2Votes}/${VOTES_REQUIRED} votes`;
}
}
} catch (error) {
console.error('Error in chooseVariant2:', error);
// Reset the selection state if generation fails
variantChosen = false;
document.getElementById('variant2Container').classList.remove('selected');
// Update selection status if element exists
const selectionStatus = document.getElementById('selectionStatus');
if (selectionStatus) {
selectionStatus.textContent = 'Error occurred. Please choose a variant again.';
if (selectionStatus.parentElement) {
selectionStatus.parentElement.classList.remove('selected');
}
}
}
}
// ========================
// VOTE MANAGEMENT FUNCTIONS
// ========================
// Reset vote counts for new generation
function resetVoteCounts() {
variant1Votes = 0;
variant2Votes = 0;
console.log('🔄 Vote counts reset for new generation');
updateVoteDisplay();
}
// Update vote display in UI
function updateVoteDisplay() {
// Update variant containers with vote indicators
const variant1Container = document.getElementById('variant1Container');
const variant2Container = document.getElementById('variant2Container');
if (variant1Container) {
// Add or update vote counter
let voteCounter = variant1Container.querySelector('.vote-counter');
if (!voteCounter) {
voteCounter = document.createElement('div');
voteCounter.className = 'vote-counter';
variant1Container.appendChild(voteCounter);
}
voteCounter.textContent = `Votes: ${variant1Votes}/${VOTES_REQUIRED}`;
// Add visual indication of vote progress
variant1Container.style.opacity = variant1Votes > 0 ? '1' : '0.8';
}
if (variant2Container) {
// Add or update vote counter
let voteCounter = variant2Container.querySelector('.vote-counter');
if (!voteCounter) {
voteCounter = document.createElement('div');
voteCounter.className = 'vote-counter';
variant2Container.appendChild(voteCounter);
}
voteCounter.textContent = `Votes: ${variant2Votes}/${VOTES_REQUIRED}`;
// Add visual indication of vote progress
variant2Container.style.opacity = variant2Votes > 0 ? '1' : '0.8';
}
}
// Add current generation to history
function addGenerationToHistory(selectedVariant) {
const generation = {
number: generationCount,
variant1: {
image: variant1Data,
instruction: document.getElementById('usedInstruction1').textContent
},
variant2: {
image: variant2Data,
instruction: document.getElementById('usedInstruction2').textContent
},
selectedVariant: selectedVariant
};
generationsHistory.push(generation);
renderHistory();
// Show history title if this is the first generation
if (generationsHistory.length === 1) {
document.getElementById('historyTitle').style.display = 'block';
}
// Scroll to the new generation smoothly
setTimeout(() => {
const currentContainer = document.getElementById('currentGenerationContainer');
currentContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 100);
}
// Render the generations history
function renderHistory() {
const historyContainer = document.getElementById('generationsHistory');
historyContainer.innerHTML = '';
generationsHistory.forEach((generation, index) => {
const generationDiv = document.createElement('div');
generationDiv.className = 'generation-item';
if (index === generationsHistory.length - 1) {
generationDiv.classList.add('selected-generation');
}
generationDiv.innerHTML = `
<div class="generation-header">
<div class="generation-number">Generation ${generation.number}</div>
</div>
<div class="history-variants-grid">
<div class="history-variant ${generation.selectedVariant === 1 ? 'was-selected' : ''}">
<h4>Variant 1</h4>
<img src="${generation.variant1.image}" alt="Generation ${generation.number} Variant 1">
<p>${generation.variant1.instruction}</p>
</div>
<div class="history-variant ${generation.selectedVariant === 2 ? 'was-selected' : ''}">
<h4>Variant 2</h4>
<img src="${generation.variant2.image}" alt="Generation ${generation.number} Variant 2">
<p>${generation.variant2.instruction}</p>
</div>
</div>
`;
historyContainer.appendChild(generationDiv);
});
// Make all history images zoomable after they're added to DOM
setTimeout(() => {
makeHistoryImagesZoomable();
}, 100);
}
// Reset context (clear localStorage and reset everything)
function resetContext() {
if (confirm('This will reset everything including the voting system and clear all stored data. Are you sure?')) {
// Clear all localStorage data
try {
localStorage.clear();
console.log('localStorage cleared');
} catch (error) {
console.error('Error clearing localStorage:', error);
}
// Reset all variables to initial state
selectedImageSrc = 'CircleStart.png';
generationCount = 0;
variantChosen = false;
variant1Data = null;
variant2Data = null;
generationsHistory = [];
storedApiKey = null; // This will ask for API key again
// Hide all containers
const variantsContent = document.getElementById('variantsContent');
hideLoadingIndicators();
if (variantsContent) variantsContent.style.display = 'none';
document.getElementById('historyTitle').style.display = 'none';
document.getElementById('instructionsCounter').style.display = 'none';
// Clear history
document.getElementById('generationsHistory').innerHTML = '';
// Reset button and instruction text
document.getElementById('generateButton').textContent = 'Generate New Image';
document.getElementById('generateButton').disabled = false;
document.getElementById('usedInstruction1').textContent = '';
document.getElementById('usedInstruction2').textContent = '';
// Clear selection states
document.getElementById('variant1Container').classList.remove('selected');
document.getElementById('variant2Container').classList.remove('selected');
document.querySelector('.selection-status').classList.remove('selected');
// Reload instructions from JSON
loadInstructions();
// Scroll to top
window.scrollTo({ top: 0, behavior: 'smooth' });
alert('Context reset successfully! All data cleared.');
}
}
// ========================
// PHYSICAL BUTTON SUPPORT
// ========================
async function checkPhysicalButton() {
try {
// Fast request with short timeout for quick response
const response = await fetch(`${RASPBERRY_PI_BASE_URL}/check-button-press`, {
signal: AbortSignal.timeout(500) // 500ms timeout for faster failure
});
const data = await response.json();
if (data.button_pressed) {
const buttonType = data.button_type;
console.log(`🔘 Physical button pressed: ${buttonType} at ${new Date().toLocaleTimeString()}`);
if (buttonType === 'variant1') {
// Only allow variant selection if variants are available and no variant chosen yet
if (variant1Data && !variantChosen) {
console.log('✅ Physical button triggered: Choosing Variant 1');