-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
5254 lines (4595 loc) · 238 KB
/
content.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
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
// content.js
// Author:
// Author URI: https://
// Author Github URI: https://www.github.com/
// Project Repository URI: https://github.com/
// Description: Handles all the webpage level activities (e.g. manipulating page data, etc.)
// License: MIT
let ttsEnabled = false;
let cartesiaConnected = false;
let audioContext;
let audioWorklet;
let audioCache = new Map();
let currentAudioBuffer = [];
let isAudioReady = false;
let currentText = '';
let currentlyPlaying = null;
let manuallyStopped = false;
let wordTimestamps = []; // [ { word: 'hello', start: 0.1, end: 0.4 }, ... ]
let cachedVoices = [];
let characterVoices = {};
let useNpcVoices = false;
let maxRevisions = 3;
let improvedLocationDetection = false;
let aiEnhancedTranscriptions = false;
let instructionsText = '';
const shortAudioThreshold = 2 * 44100; // 2 seconds at 44100 Hz
//const delayBetweenReading = 2000;
// SETTINGS
let autoPlayNew = true;
let autoPlayOwn = false;
let autoSendAfterSpeaking = false;
//let leaveMicOn = false;
//let deepgramApiKey = '';
let cartesiaConnection = null;
let apiKey = '';
let voiceId = '';
let speed = 'normal';
let locationBackground = 'off';
let openaiApiKey = '';
let openaiModel = 'gpt-4o-mini';
let autoSelectMusic = false;
let musicAiNotes = '';
let musicLocked = false;
let enableStoryEditor = false;
let disallowedElements = '';
let disallowedRelaxed = '';
let lastRevised = null;
let revisions = 0;
let notebookEnabled = true;
let OBS;
let UI;
let TTS;
let STT;
let MUSIC;
let AI;
let CAMPAIGN;
let CAPTION;
let EDITOR;
let VOICE;
let UTILITY;
let NOTEBOOK;
// UI
class UIManager {
constructor() {
this.lastLocation = null;
this.focused = null;
this.lastFocused = null;
}
initialize() {
// Create a MutationObserver to detect when the mic toggle is removed
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList' && !document.getElementById('micToggle')) {
STT.stopRecording();
this.addMicToggle();
}
});
});
observer.observe(document.body, { childList: true, subtree: true });
// Hook the send button and textarea to turn off microphone when sending a message
const sendButton = document.getElementById('send');
const textarea = document.querySelector('textarea[name="message"]');
if (sendButton) {
sendButton.addEventListener('click', () => {
STT.stopRecording();
UI.toggleMic(false);
});
}
if (textarea) {
textarea.addEventListener('keydown', (event) => {
if (event.key === 'Enter' && !event.shiftKey) {
STT.stopRecording();
UI.toggleMic(false);
}
});
}
// Add keyboard shortcut to open AI Editor
document.addEventListener('keydown', (event) => {
if (event.key === 'F4') {
event.preventDefault(); // Prevent default F4 behavior
//AI.notebookHandler();
} else if (event.ctrlKey && event.key === 'm') {
event.preventDefault(); // Prevent default Ctrl+M behavior
//AI.notebookHandler();
}
if (event.key === 'F6') {
event.preventDefault(); // Prevent default F4 behavior
//NOTEBOOK.eraseNotebook(true);
}
if (event.key === 'F3') {
event.preventDefault(); // Prevent default F4 behavior
//CAMPAIGN.updateNotebook();
}
});
}
// TTS Toggle Button
addTTSToggleButton() {
const targetDiv = document.querySelector('.flex.flex-row.items-center.overflow-hidden');
if (!targetDiv) {
console.error('Target div not found');
return;
}
if (document.getElementById('ttsToggleButton')) {
return;
}
const chatInput = document.querySelector('#chat-input');
chatInput.value = '';
chatInput.dispatchEvent(new Event('input', { bubbles: true }));
const buttonContainer = document.createElement('div');
buttonContainer.style.cssText = 'width: auto; opacity: 1; margin-left: 4px; margin-right: 4px;';
const button = document.createElement('button');
button.id = 'ttsToggleButton';
button.className = 'inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group hover:bg-transparent h-10 w-10 bg-input rounded-full p-2';
button.type = 'button';
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '24');
svg.setAttribute('height', '24');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('fill', 'none');
svg.setAttribute('stroke', 'currentColor');
svg.setAttribute('stroke-width', '2');
svg.setAttribute('stroke-linecap', 'round');
svg.setAttribute('stroke-linejoin', 'round');
svg.classList.add('h-5', 'w-5');
button.appendChild(svg);
buttonContainer.appendChild(button);
targetDiv.appendChild(buttonContainer);
this.updateTTSToggleButton();
button.addEventListener('click', () => TTS.toggleCartesiaConnection());
// Add the new CSS rule
const style = document.createElement('style');
style.textContent = `
@media (min-width: 768px) {
.md\\:pl-14 {
padding-left: 3.5rem;
padding-right: 2.5rem !important;
}
}
`;
document.head.appendChild(style);
}
updateTTSToggleButton() {
const button = document.getElementById('ttsToggleButton');
if (button) {
const svg = button.querySelector('svg');
const volumeSVG = `
<path d="M11 5L6 9H2v6h4l5 4V5z"></path>
<path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path>
<path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path>
`;
const volumeXmarkSVG = `
<path d="M11 5L6 9H2v6h4l5 4V5z"></path>
<line x1="23" y1="9" x2="17" y2="15"></line>
<line x1="17" y1="9" x2="23" y2="15"></line>
`;
svg.innerHTML = cartesiaConnected ? volumeXmarkSVG : volumeSVG;
}
}
// Play Pause Buttons
addPlayButtons(div) {
let franzMessage = true;
const messageDivs = div ? [div] : document.querySelectorAll('div.grid.grid-cols-\\[25px_1fr_10px\\].md\\:grid-cols-\\[40px_1fr_30px\\].pb-4.relative');
messageDivs.forEach((div, index) => {
if (isMobileDevice()) {
console.log('isMobileDevice true', div);
const buttonContainer = div.querySelector('div.flex.flex-row.items-center.gap-1');
if (buttonContainer && !buttonContainer.querySelector('.tts-play-button')) {
const button = this.createPlayButton();
console.log('button', button);
buttonContainer.appendChild(button);
}
} else {
if (!div.querySelector('.tts-play-button')) {
let buttonBar = div.querySelector('div.ml-2.justify-center.items-center.flex.flex-col.z-\\[50\\]');
if (!buttonBar && index > messageDivs.length - 5 && div.querySelector('p.text-base')) {
console.log('creating button bar', index, div);
buttonBar = document.createElement('div');
buttonBar.className = 'ml-2 justify-center items-center flex flex-col z-[50]';
div.querySelector('.hidden.md\\:block').appendChild(buttonBar);
franzMessage = false;
}
if (buttonBar) {
const button = this.createPlayButton();
console.log('button', button);
buttonBar.appendChild(button);
}
}
}
});
return franzMessage;
}
createPlayButton() {
const existingButtons = document.querySelectorAll('[id^="tts-play-button-"]');
const highestIndex = Math.max(...Array.from(existingButtons).map(button => parseInt(button.id.split('-').pop())), 0);
const newIndex = highestIndex + 1;
const button = document.createElement('button');
button.id = 'tts-play-button-' + newIndex;
console.log('createPlayButton', button.id);
if (isMobileDevice()) {
button.className = 'tts-play-button inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group hover:bg-transparent px-1 h-fit group';
} else {
button.className = 'tts-play-button inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group hover:bg-transparent px-4 py-2 h-fit group';
}
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '14');
svg.setAttribute('height', '14');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('fill', 'none');
svg.setAttribute('stroke', 'currentColor');
svg.setAttribute('stroke-width', '2');
svg.setAttribute('stroke-linecap', 'round');
svg.setAttribute('stroke-linejoin', 'round');
svg.classList.add('text-gray-400', 'group-hover:text-primary');
svg.innerHTML = `
<circle cx="12" cy="12" r="10"></circle>
<polygon points="10 8 16 12 10 16 10 8"></polygon>
`;
button.appendChild(svg);
button.addEventListener('click', () => UI.togglePlayPause(button.id));
return button;
}
updatePlayButtonIcon(buttonId, isPlaying) {
//console.log('updatePlayButtonIcon', buttonId, isPlaying);
const button = document.getElementById(buttonId);
if (!button) { return; }
//console.log('updatePlayButtonIcon button', button, buttonId);
const svg = button.querySelector('svg');
if (!svg) { return; }
if (isPlaying) {
//console.log('updatePlayButtonIcon isPlaying', isPlaying);
svg.innerHTML = `
<circle cx="12" cy="12" r="10"></circle>
<line x1="10" y1="15" x2="10" y2="9"></line>
<line x1="14" y1="15" x2="14" y2="9"></line>
`;
} else {
svg.innerHTML = `
<circle cx="12" cy="12" r="10"></circle>
<polygon points="10 8 16 12 10 16 10 8"></polygon>
`;
}
}
togglePlayPause(buttonId) {
const button = document.getElementById(buttonId);
const messageDiv = button.closest('div.grid.grid-cols-\\[25px_1fr_10px\\].md\\:grid-cols-\\[40px_1fr_30px\\].pb-4.relative');
const isPlaying = buttonId === currentlyPlaying;
if (currentlyPlaying) {
this.updatePlayButtonIcon(currentlyPlaying, false);
}
manuallyStopped = true;
if (!isPlaying) {
currentlyPlaying = buttonId;
this.updatePlayButtonIcon(buttonId, true);
TTS.stopPlayback();
TTS.playMessage(messageDiv);
} else {
currentlyPlaying = null;
TTS.stopPlayback();
}
}
removePlayButtons() {
const playButtons = document.querySelectorAll('.tts-play-button');
playButtons.forEach(button => button.remove());
}
// STT
toggleMic(isToggled=null) {
const micToggle = document.getElementById('micToggle');
if (!micToggle) { return; }
if (isToggled === null) { isToggled = micToggle.classList.contains('active'); }
if (isToggled) {
micToggle.classList.add('active');
} else {
micToggle.classList.remove('active');
}
}
addMicToggle() {
const mainElement = document.querySelector('body');
if (mainElement) {
let micToggle = document.getElementById('micToggle');
if (!micToggle) {
micToggle = document.createElement('button');
micToggle.id = 'micToggle';
micToggle.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"></path><path d="M19 10v2a7 7 0 0 1-14 0v-2"></path><line x1="12" y1="19" x2="12" y2="23"></line><line x1="8" y1="23" x2="16" y2="23"></line></svg>';
micToggle.classList.add('mic-toggle-bubble');
const styles = `
.mic-toggle-bubble {
position: fixed;
right: 20px;
bottom: 20px;
width: 60px;
height: 60px;
border-radius: 50%;
background-color: #3a3a3a;
border: none;
cursor: pointer;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
z-index: 2147483647;
pointer-events: auto;
overflow: visible;
opacity: 0;
pointer-events: none;
}
.mic-toggle-bubble:hover {
background-color: #4a4a4a;
}
.mic-toggle-bubble.active {
background-color: #ffd700;
}
.mic-toggle-bubble svg {
color: #fff;
transition: color 0.3s ease;
}
.mic-toggle-bubble.active svg {
color: #3a3a3a;
}
`;
const styleElement = document.createElement('style');
styleElement.textContent = styles;
document.head.appendChild(styleElement);
micToggle.addEventListener('click', this.handleMicToggleClick);
mainElement.appendChild(micToggle);
document.addEventListener('focusin', this.handleFocusIn);
document.addEventListener('focusout', this.handleFocusOut);
}
}
}
handleMicToggleClick = (event) => {
console.log('micToggle clicked');
event.preventDefault();
event.stopPropagation();
console.log('micToggle clicked focused', this.focused);
setTimeout(() => {
if (UI.lastFocused) {
UI.lastFocused.focus();
if (UI.lastFocused.tagName === 'INPUT' || UI.lastFocused.tagName === 'TEXTAREA') {
UI.focused = UI.lastFocused;
}
}
}, 50);
if (!event.currentTarget.classList.contains('active')) {
event.currentTarget.classList.add('active');
UI.toggleMic(true);
STT.startRecording();
} else {
event.currentTarget.classList.remove('active');
UI.toggleMic(false);
STT.stopRecording();
}
}
handleFocusIn = (event) => {
if (event.target.matches('input:not([type]), input[type="text"], textarea')) {
this.moveMicToggleToActiveElement(event.target);
this.showMicToggle();
this.focused = event.target;
this.lastFocused = event.target;
console.log('focused', this.focused);
}
}
handleFocusOut = (event) => {
if (event.target.matches('input:not([type]), input[type="text"], textarea')) {
UI.focused = null
setTimeout(function() {
if (!UI.focused) {
UI.hideMicToggle();
}
}, 150);
console.log('focused reset', this.focused);
}
}
moveMicToggleToActiveElement(activeElement) {
const micToggle = document.getElementById('micToggle');
if (!micToggle) { console.log('micToggle not found'); return; }
console.log('moveMicToggleToActiveElement', activeElement);
const rect = activeElement.getBoundingClientRect();
if (rect.width <= 100) {
console.log('Active element width is 100px or less, not moving mic toggle');
return;
}
activeElement.parentNode.insertBefore(micToggle, activeElement.nextSibling);
micToggle.style.position = 'absolute';
micToggle.style.left = '50%';
micToggle.style.transform = 'translateX(-50%)';
const parentRect = activeElement.parentNode.getBoundingClientRect();
const micToggleHeight = micToggle.offsetHeight;
if (activeElement.name === 'message') {
micToggle.style.top = `${rect.top - parentRect.top - micToggleHeight - 10}px`;
} else {
micToggle.style.top = `${rect.bottom - parentRect.top + 20}px`;
}
micToggle.style.bottom = 'auto';
micToggle.style.right = 'auto';
}
hideMicToggle() {
const micToggle = document.getElementById('micToggle');
if (micToggle && !micToggle.classList.contains('active')) {
micToggle.style.opacity = '0';
micToggle.style.pointerEvents = 'none';
}
}
showMicToggle() {
const micToggle = document.getElementById('micToggle');
if (micToggle) {
micToggle.style.opacity = '1';
micToggle.style.pointerEvents = 'auto';
}
}
// BACKGROUND IMAGE
updateBackgroundImage() {
const existingBackgroundImage = document.querySelector('img[alt="location"][width="300"]');
if (existingBackgroundImage) {
if (locationBackground === 'off' && this.lastLocation) {
const mainElement = document.querySelector('main');
mainElement.style.backgroundImage = 'none';
this.lastLocation = null;
return;
}
if (locationBackground !== 'off' && this.lastLocation !== existingBackgroundImage.src) {
this.lastLocation = existingBackgroundImage.src;
UI.setBackgroundImage(existingBackgroundImage.src);
}
}
}
setBackgroundImage(imageUrl) {
if (locationBackground === 'off') {
return;
}
imageUrl = imageUrl.replace('?width=384','?width=2048');
const mainElement = document.querySelector('main');
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
// Draw the image to the canvas
ctx.drawImage(img, 0, 0);
// Apply blur effect
ctx.filter = 'blur(5px)';
if (locationBackground == 'dark') {
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(canvas, 0, 0);
// Reset the filter
ctx.filter = 'none';
// Get the blurred image as a data URL
const blurredImageUrl = canvas.toDataURL();
canvas.remove();
// Apply the blurred image as background to mainElement
mainElement.style.backgroundImage = `url(${blurredImageUrl})`;
mainElement.style.backgroundSize = 'cover';
mainElement.style.backgroundPosition = 'center';
};
img.src = imageUrl;
}
// OVERLAY
addOverlay(element) {
const overlay = document.createElement('div');
overlay.classList.add('overlay');
overlay.classList.add('rounded-md');
overlay.textContent = "Enhancing narrative...";
element.insertBefore(overlay, element.firstChild);
overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
overlay.style.backdropFilter = 'blur(5px)';
overlay.style.webkitBackdropFilter = 'blur(5px)';
}
updateOverlay(message) {
const overlay = document.querySelector('.overlay');
if (overlay) {
overlay.textContent = message;
}
}
removeOverlay(element=null) {
const overlay = (element ? element : document).querySelector('.overlay');
if (!overlay) { return; }
overlay.style.backgroundColor = 'rgba(0, 0, 0, 0)';
overlay.style.backdropFilter = 'blur(0px)';
overlay.style.webkitBackdropFilter = 'blur(0px)';
setTimeout(() => {
if (overlay) {
overlay.remove();
}
}, 1000);
}
// LOCATION SUGGESTION
addLocationSuggestion() {
if (document.getElementById('location-suggestion-button')) {
return;
}
const locationButton = document.createElement('button');
locationButton.id = 'location-suggestion-button';
locationButton.className = 'inline-flex items-center justify-center whitespace-nowrap font-medium ring-offset-background transition-all duration-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group bg-gray-400 bg-clip-padding backdrop-filter backdrop-blur-md bg-opacity-20 border border-gray-500 hover:border-primary text-gray-300 h-9 rounded-md px-3';
locationButton.style.fontSize = '14px';
locationButton.style.display = 'flex';
locationButton.style.alignItems = 'center';
locationButton.style.marginBottom = '10px';
locationButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-map-pin mr-2 h-4 w-4" style="margin-bottom: 2px;">
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
<circle cx="12" cy="10" r="3"/>
</svg>
<span style="line-height: 1; margin-top: 1px;">Location</span>
`;
const inviteButton = Array.from(document.querySelectorAll('button')).find(button => button.textContent.includes('Invite') || button.textContent.includes('Party Full'));
if (inviteButton && inviteButton.parentNode) {
inviteButton.parentNode.insertBefore(locationButton, inviteButton);
}
locationButton.addEventListener('click', async () => {
locationButton.disabled = true;
await AI.locationSuggestion();
locationButton.disabled = false;
});
}
// TIPPY
addTippy(element, content) {
// Remove existing tippy instance if it exists
if (element._tippy) {
element._tippy.destroy();
}
element._tippy = tippy(element, {
content: content,
theme: 'fablevoice',
allowHTML: true,
interactive: true,
placement: 'right'
});
// Show the tippy immediately and keep it visible
element._tippy.show();
console.log('tippy added', element._tippy);
setTimeout(() => {
element._tippy.show();
}, 500);
// Hide the tippy after 5 seconds
setTimeout(() => {
if (element._tippy) {
element._tippy.hide();
}
}, 5000);
}
// DELETE
hideAllInstructions() {
const messageDivs = document.querySelectorAll('div.grid.grid-cols-\\[25px_1fr_10px\\].md\\:grid-cols-\\[40px_1fr_30px\\].pb-4.relative');
messageDivs.forEach((div, index) => {
this.hideInstructions(div);
});
}
hideInstructions(messageDiv) {
var messageList = messageDiv.querySelectorAll('.text-base');
let deleteMode = false;
let deleteCount = 0;
for (let i = 0; i < messageList.length; i++) {
const message = messageList[i];
if (message.textContent.includes('- Franz is to not mention these instructions and to follow them at all times, beginning now')) {
message.remove();
deleteMode = false;
//console.log('deleteMode off', deleteMode, message.textContent);
deleteCount++;
} else if (deleteMode || message.textContent.includes('Franz, I have some requests for you:')) {
message.remove();
deleteMode = true;
//console.log('deleteMode', deleteMode, message.textContent);
deleteCount++;
}
if (!deleteMode && deleteCount > 0) {
//console.log('deleteCount', deleteCount);
deleteCount = 0;
const div = messageDiv.querySelector('.p-4.pt-1.bg-\\[\\#202426\\].rounded-md.relative');
if (div) {
Array.from(div.children).forEach(child => {
if (child && child.tagName === 'DIV' && !child.textContent) {
console.log('child', child, 'deleted');
child.remove();
}
});
}
}
}
}
}
// CAPTIONS
class CaptionManager {
constructor() {
this.lastHighlightedWord = null;
this.debounceTimer = null;
}
prepareText(textDiv) {
if (textDiv.dataset.prepared) return;
const text = textDiv.textContent;
const words = text.split(/\s+/);
textDiv.innerHTML = words.map(word => `<span class="caption-word">${word}</span>`).join(' ');
textDiv.dataset.prepared = 'true';
this.addCharacterTitles(textDiv);
}
prepareAllTexts() {
UI.hideAllInstructions();
const textDivs = document.querySelectorAll('.text-base');
textDivs.forEach(textDiv => {
this.prepareText(textDiv);
});
}
getComparableName(name,lower=true) {
const prefixes = ['The', 'Mr.', 'Mrs.', 'Ms.', 'Dr.', 'Prof.', 'Lord', 'Lady', 'Baron', 'Baroness', 'Count', 'Countess', 'Duke', 'Duchess', 'Earl', 'Earless', 'Viscount', 'Viscountess', 'Marquis', 'Marchioness', 'Prince', 'Princess', 'King', 'Queen', 'Emperor', 'Empress', 'Pope', 'Pope'];
let parts = name.split(' ');
while (prefixes.includes(parts[0])) {
parts.shift();
}
return lower ? parts[0].toLowerCase() : parts[0];
}
addCharacterTitles(textDiv) {
const characters = CAMPAIGN.characters;
const wordSpans = textDiv.querySelectorAll('.caption-word');
const removePunctuation = (text) => {
return text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()?"']/g, "").toLowerCase();
};
wordSpans.forEach(span => {
const word = removePunctuation(span.textContent);
const character = characters.find(char => {
const charName = this.getComparableName(char.name);
return word === charName || (word.startsWith(charName) && !characters.some(c => word === this.getComparableName(c.name)));
});
if (character) {
span.style.cursor = 'pointer';
tippy(span, {
content: `
<div class="character-tooltip">
<div class="aspect-square relative overflow-hidden rounded-lg">
<img src="${character.avatar}" alt="${character.name}" class="object-cover w-full h-full" />
<div class="absolute inset-x-0 bottom-0 bg-gradient-to-t from-background to-transparent h-1/2"></div>
<div class="absolute inset-0 bg-gradient-to-b from-background from-3% via-transparent via-5% to-transparent to-100%"></div>
<div class="absolute inset-0 bg-gradient-to-r from-background from-3% via-transparent via-20% to-transparent to-100%"></div>
<div class="absolute inset-0 bg-gradient-to-l from-background from-3% via-transparent via-20% to-transparent to-100%"></div>
<div class="absolute inset-0 -top-5 bg-[radial-gradient(circle,transparent_0%,transparent_50%,rgba(1,10,13,0.9)_100%)]"></div>
<div class="absolute inset-x-0 bottom-0 text-gray-300">
<div class="text-2xl font-header text-center">${character.name}</div>
<div class="text-sm font-header text-center">${character.type}</div>
<div class="text-xs text-center italic font-header mt-1">${character.brief_description || ''}</div>
</div>
</div>
</div>
`,
theme: 'fablevoice',
allowHTML: true,
interactive: true
});
//console.log('character name added', character);
}
});
}
activeWord(data) {
//console.log('activeWord', data.word);
const playButton = document.getElementById(currentlyPlaying);
if (!playButton) return;
const messageDiv = playButton.closest('div.grid.grid-cols-\\[25px_1fr_10px\\].md\\:grid-cols-\\[40px_1fr_30px\\].pb-4.relative');
const textDivs = messageDiv.querySelectorAll('.text-base');
this.prepareAllTexts();
const allWordSpans = [];
textDivs.forEach(textDiv => {
allWordSpans.push(...textDiv.querySelectorAll('.caption-word'));
});
if (this.lastHighlightedWord) {
//this.lastHighlightedWord.classList.remove('highlighted');
}
const wordSpan = allWordSpans[data.index];
if (wordSpan) {
wordSpan.classList.add('highlighted');
//console.log('highlighted', wordSpan.textContent, wordSpan.classList, wordSpan);
this.lastHighlightedWord = wordSpan;
setTimeout(() => {
if (wordSpan) {
wordSpan.classList.remove('highlighted');
}
}, 1000);
}
}
}
// TEXT-TO-SPEECH
class CartesiaConnection {
constructor() {
this.connection = null;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.reconnectInterval = 5000; // 5 seconds
this.intentionalClose = false;
this.loadSettings();
this.currentContextId = null;
this.pendingRequests = [];
this.isProcessing = false;
this.currentSessionBuffer = [];
this.currentSessionTimestamps = [];
this.cumulativeDuration = 0;
this.pendingDuration = 0;
this.silenceDuration = 0.5; // Default silence duration in seconds
this.cumulativeSilence = 0; // Track total silence added
}
loadSettings() {
chrome.storage.local.get(['apiKey', 'voiceId', 'speed', 'silenceDuration'], function(data) {
console.log('loadSettings', data);
apiKey = data.apiKey || '';
voiceId = data.voiceId || '';
speed = data.speed || 'normal';
this.silenceDuration = data.silenceDuration || 0.5;
});
}
initialize() {
const apiVersion = '2024-06-10';
const url = `wss://api.cartesia.ai/tts/websocket?api_key=${apiKey}&cartesia_version=${apiVersion}`;
this.connection = new WebSocket(url);
this.connection.onopen = () => {
console.log('Cartesia connection established.');
this.reconnectAttempts = 0;
this.intentionalClose = false;
this.processNextRequest();
};
this.connection.onmessage = (event) => {
this.handleMessage(JSON.parse(event.data));
};
this.connection.onclose = (event) => {
console.log('Cartesia connection closed.');
if (!this.intentionalClose) {
this.attemptReconnect();
}
};
this.connection.onerror = (error) => {
butterup.toast({
title: 'Cartesia Error',
message: 'Could not connect. Check your API key and available credits.',
location: 'bottom-left',
icon: false,
dismissable: true,
type: 'error',
});
console.error('Cartesia connection error:', error);
};
}
attemptReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
setTimeout(() => this.initialize(), this.reconnectInterval);
} else {
console.error('Max reconnection attempts reached. Please check your connection and try again later.');
}
}
handleMessage(response) {
if (response.type === 'chunk') {
this.handleChunk(response);
} else if (response.type === 'done') {
this.handleDone(response);
} else if (response.type === 'timestamps') {
this.handleTimestamps(response);
} else if (response.type === 'error') {
butterup.toast({
title: 'Cartesia Error',
message: 'Could not handle message.',
location: 'bottom-left',
icon: false,
dismissable: true,
type: 'error',
});
console.error('Cartesia error:', response);
}
}
handleChunk(response) {
if (audioWorklet && response.data && response.data.length > 0) {
const audioData = decodeAudioData(response.data);
this.currentSessionBuffer.push(audioData);
audioWorklet.port.postMessage({ type: 'append', buffer: audioData });
const totalSamples = this.currentSessionBuffer.reduce((sum, chunk) => sum + chunk.length, 0);
if (totalSamples >= shortAudioThreshold && this.currentSessionTimestamps.length > 0 && !isAudioReady) {
isAudioReady = true;
console.log('checkAndPlayAudio called from handleChunk', this.currentSessionTimestamps, 'isAudioReady', isAudioReady);
TTS.checkAndPlayAudio();
}
}
}
handleDone(response) {
console.log('Received done:', response);
if (response.context_id === this.currentContextId) {
this.cumulativeDuration += this.pendingDuration;
this.pendingDuration = 0;
this.currentContextId = null;
this.isProcessing = false;
// Add silence buffer
const silenceSamples = Math.floor(this.silenceDuration * 44100); // Assuming 44100 sample rate
const silenceBuffer = new Float32Array(silenceSamples).fill(0);
this.currentSessionBuffer.push(silenceBuffer);
audioWorklet.port.postMessage({ type: 'append', buffer: silenceBuffer });
// Update cumulative silence
this.cumulativeSilence += this.silenceDuration;
if (this.pendingRequests.length === 0) {
this.finalizeSession();
} else {
this.processNextRequest();
}
}
}
finalizeSession() {
console.log(`Caching audio, total chunks: ${this.currentSessionBuffer.length}`);
audioCache.set(currentText, {
audio: this.currentSessionBuffer,
timestamps: this.currentSessionTimestamps
});
console.log('finalizeSession', this.currentSessionTimestamps);
audioWorklet.port.postMessage({ type: 'done' });
if (!isAudioReady) {
isAudioReady = true;
TTS.checkAndPlayAudio();
}
// Reset buffers for the next session
this.currentSessionBuffer = [];
this.currentSessionTimestamps = [];
this.cumulativeDuration = 0;
this.pendingDuration = 0;
this.cumulativeSilence = 0;
}
handleTimestamps(response) {
if (response.word_timestamps) {
const { words, start, end } = response.word_timestamps;
// Add new timestamps to the array, adjusting for cumulative duration and silence
const newTimestamps = words.map((word, index) => ({
word,
start: start[index] + this.cumulativeDuration + this.cumulativeSilence,
end: end[index] + this.cumulativeDuration + this.cumulativeSilence
}));
this.currentSessionTimestamps = this.currentSessionTimestamps.concat(newTimestamps);
// Update pending duration
if (end.length > 0) {
this.pendingDuration = Math.max(this.pendingDuration, end[end.length - 1]);
}
// Send timestamp data to audio worklet
if (audioWorklet) {
audioWorklet.port.postMessage({
type: 'timestamps',
data: {
words: this.currentSessionTimestamps.map(ts => ts.word),
start: this.currentSessionTimestamps.map(ts => ts.start),
end: this.currentSessionTimestamps.map(ts => ts.end)
}
});
}
}
}
validateEmotions(emotions) {
if (!emotions) { return false; }
const validEmotions = ['anger', 'positivity', 'surprise', 'sadness', 'curiosity'];
const validLevels = ['lowest', 'low', '', 'high', 'highest'];
return emotions.every(emotion => {
const [emotionName, level] = emotion.split(':');
return validEmotions.includes(emotionName) &&
(level === undefined || validLevels.includes(level));
});
}