-
Notifications
You must be signed in to change notification settings - Fork 105
/
index.html
executable file
·5512 lines (4966 loc) · 250 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<title>Talking Head</title>
<meta charset="utf-8">
<meta content="width=device-width, height=device-height, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0, user-scalable=no, interactive-widget=resizes-content" name="viewport">
<link rel="icon" type="image/jpg" href="favicon.jpg">
<style>
html {
width:100%; height:100%; height: -webkit-fill-available; font-size: 14px;
}
/* Color themes */
:root, .theme-dark {
--colorBody: #88ccff;
--colorBackground: #202020;
--colorPanel: rgba(32,32,32,0.98);
--colorBorderPassive: rgba(136,204,255,0.6);
--colorBorderActive: #88ccff;
--colorUserText: #88ccff;
--colorSystemText: #cc77ff;
--colorToolbarPassive: rgba(136,204,255,0.6);
--colorToolbarPassive2: rgba(136,204,255,0.3);
--colorToolbarActive: #88ccff;
--widthLabel: 5rem;
--colorGlow: #88ccff;
}
.theme-light {
--colorBody: #505050;
--colorBackground: #f0f0f0;
--colorPanel: rgba(224,224,224,0.98);
--colorBorderPassive: #d0d0d0;
--colorBorderActive: #d0d0d0;
--colorUserText: #404444;
--colorSystemText: #678fb9;
--colorToolbarPassive: rgba(80,80,80,0.75);
--colorToolbarPassive2: rgba(80,80,80,0.5);
--colorToolbarActive: #606666;
--widthLabel: 5rem;
}
body {
width: 100%; height: 100%; min-height: 100vh;
min-height: -webkit-fill-available; margin: 0; padding: 0;
background-color: var(--colorBackground); color: var(--colorBody);
overflow: hidden; text-align: left; touch-action: manipulation;
font-family: "SansRegular", sans-serif; font-size: 1.4rem;
line-height: 1.4rem; scrollbar-color: var(--colorToolbarPassive) transparent;
scrollbar-width: 20px; scrollbar-height: 20px;
}
::-webkit-scrollbar { width: 20px; height: 20px; }
::-webkit-scrollbar-track {
background: linear-gradient(
to right, transparent,
transparent 9px,
var(--colorToolbarPassive) 9px,
var(--colorToolbarPassive) 11px,
transparent 11px
);
}
::-webkit-scrollbar-thumb {
background-color: var(--colorPanel); border-radius: 10px;
border: 2px solid var(--colorToolbarPassive);
}
input[type="range"] {
position: relative; width: 180px; height: 0.8rem; line-height: 2rem;
-webkit-appearance: none; appearance: none; margin-top: 0.6rem;
cursor: pointer; pointer-events: auto;
background: repeating-linear-gradient(
to right, var(--colorToolbarPassive),
var(--colorToolbarPassive) 2px,
transparent 2px,
transparent 44.5px
);
}
input[type="range"]::-webkit-slider-runnable-track {
background: var(--colorToolbarPassive); height: 2px;
}
input[type="range"]::-moz-range-track {
background: var(--colorToolbarPassive); height: 2px;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none; appearance: none;
background: var(--colorToolbarActive);
margin-top: -0.6rem; height: 1.4rem; width: 0.8rem; border-radius: 0.1rem;
}
input[type="range"]::-moz-range-thumb {
border: none; background-color: var(--colorToolbarActive); height: 1.2rem;
width: 0.8rem; border-radius: 0.1rem;
}
input[type="range"]:focus { outline: none; }
input[type="range"]:focus::-webkit-slider-thumb { outline: none; }
input[type="range"]:focus::-moz-range-thumb { outline: none; }
input[type="text"] {
flex: 1; background-color: transparent; color: var(--colorUserText);
border: 0; outline: none; line-height: 2rem; font-family: "SansRegular";
font-size: 1.4rem; cursor: pointer; pointer-events: auto; margin: 0;
padding: 0 6px;
}
input[type="text"]::placeholder {
color: var(--colorUserText); opacity: 0.3;
}
input[type="color"] { background: none; border: 0; }
/* Pages */
.pages {
position: absolute; top: 18px; left: 30px; right: 30px; bottom: 18px;
display: flex; flex-direction: column; row-gap: 6px;
}
.row { display: flex; row-gap: 0; column-gap: 8px; }
.column { flex: 1; display: flex; flex-direction: column; row-gap: 2px; }
.page {
flex-grow: 1; display: flex; flex-direction: column;
overflow-y: auto; overflow-x: hidden; min-height: 0; margin: 8px 0 8px 0;
padding-right: 16px;
}
.rowWrap {
display: flex; row-gap: 2px; column-gap: 8px; flex-wrap: wrap;
}
.vspace {
flex-shrink: 0; height: 1rem;
}
.vbar {
height: 1px; background-color: var(--colorToolbarPassive2);
flex-shrink: 0; margin: 1rem 0 1rem 0;
}
.fill, .filler {
flex-shrink: 0; flex-grow: 1; flex-basis: 0; min-width: 0;
}
.filler { visibility: hidden; pointer-events: none; }
.command, .text {
display: inline-flex; height: calc( 2rem + 2px); font-size: 1.4rem;
line-height: calc( 2rem + 2px); padding: 0 6px; gap: 12px;
vertical-align: middle; text-align: left; font-family: "SansRegularCondensed";
color: var(--colorToolbarPassive); white-space: nowrap; overflow: hidden;
}
.command, .text {
font-family: "SansRegularCondensed"; color: var(--colorToolbarPassive);
}
.command { cursor: pointer; pointer-events: auto; }
.command > svg, .text > svg {
height: 2rem; width: 2rem; padding: 1px 0;
min-height: 2rem; min-width: 2rem;
}
.label {
width: var(--widthLabel); flex-shrink: 0; color: var(--colorToolbarPassive2);
}
.border {
position: absolute; top: 0; left: 0; bottom: 0; right: 0;
background: transparent; border-width: 3px; border-style: solid;
border-color: var(--colorBorderActive); pointer-events: none;
border-radius: inherit;
}
.glow { box-shadow: 0 0 25px 5px var(--colorGlow); }
.theme-light .glow { box-shadow: none; }
/* Main */
#main {
position: absolute; top: 50%; left: 50%;
transform: translate(-50%,-50%); background-color: transparent;
}
/* Left panel */
#left {
position: absolute; margin: 4px; pointer-events: none;
background-color: var(--colorPanel);
}
#avatar, #view {
position: absolute; opacity: 0; top: 0; left: 0; right: 0;
bottom: 0; pointer-events: auto; overflow: hidden;
border-radius: inherit;
}
#view {
background-image: none; background-repeat:no-repeat;
background-position: center center; background-size: cover;
}
#video {
position: absolute; height: 100%; width: 100%;
object-position: center center; object-fit: cover;
}
/* Loading */
#loading {
display: block; position: absolute; top: 6px; left: 6px; width: 300px;
height: 30px; pointer-events: none; font-size: 1rem;
background-color: transparent;
}
#loading-back, #loading-top {
display: block; position: absolute; top: 10px; left: 20px; bottom: 10px;
width: 95px;
}
#loading-back {
background: repeating-linear-gradient(
to right, var(--colorToolbarPassive2),
var(--colorToolbarPassive) 5px,
transparent 5px,
transparent 10px
);
}
#loading-top {
clip-path: inset(0 100% 0 0);
background: repeating-linear-gradient(
to right, var(--colorBody),
var(--colorBody) 5px,
transparent 5px,
transparent 10px
);
}
#loading-value {
display: block; position: absolute; top: 0; left: 125px; bottom: 0;
right: 0; line-height: 30px; text-align: left; font-size: 1.4rem;
font-family: "SansRegularCondensed";
}
/* Right panel */
#right {
position: absolute; margin: 4px;
background-color: var(--colorPanel);
}
#right .border { border-color: var(--colorBorderPassive); }
.session { display: none; width: 100%; }
.session.selected { display: block; }
.message {
position: relative; display: block; width: 100%; min-height: 2rem;
}
.message * {
text-align:left; font-size: 1.4rem; line-height: 2rem;
}
.message > * {
display: block; padding: 0 calc(6rem + 8px) 0 calc(4rem + 4px);
color: var(--colorSystemText); z-index: 10;
}
.message ul, .message ol { margin: 0 0 0 2rem; }
.message.user > * { color: var(--colorUserText); }
.message > .toolbar-left {
position: absolute; left:0; bottom:0; padding: 0;
display: flex; row-gap: 0; column-gap: 4px;
}
.message > .toolbar-right {
position: absolute; right: 0; bottom:0; padding: 0;
display: flex; row-gap: 0; column-gap: 4px;
}
code { font-family: monospace; font-size: 1rem; }
#directory div:first-child div[data-entry-move="up"] { visibility: hidden; }
#directory div:last-child div[data-entry-move="down"] { visibility: hidden; }
#right textarea {
flex: 1; min-height: 2rem; margin: auto; background: transparent;
border: 0; font-family: "SansRegular"; font-size: 1.4rem; padding: 0 6px;
line-height: 2rem; resize: none; outline: none; color: var(--colorUserText);
pointer-events: auto;
}
#right textarea[data-item="ai-openai-ai1"], #right textarea[data-item="ai-openai-ai2"],
#right textarea[data-item="ai-gemini-ai1"], #right textarea[data-item="ai-gemini-ai2"] {
color: var(--colorSystemText);
}
#right textarea::placeholder { color: inherit; opacity: 0.3; }
.emoji { cursor: pointer; pointer-events: auto; }
#morphs .label { width: calc( 2.5 * var(--widthLabel) ); }
#right-sessions { scrollbar-gutter: stable; }
/* Bottom panel */
#bottom {
position: absolute; margin: 4px; padding: 25px 25px 60px 25px;
background-color: var(--colorPanel);
}
#bottom .border { border-color: var(--colorBorderPassive); }
#bottom textarea {
flex: 1; min-height: 2rem; margin: 0; background: transparent;
border: 0; font-family: "SansRegular"; font-size: 1.4rem;
line-height: 2rem; resize: none; outline: none; color: var(--colorUserText);
pointer-events: auto; box-sizing: border-box;
}
#bottom textarea::placeholder { color: var(--colorUserText); opacity: 0.3; }
#flag, #score, #scripttag, #scriptstatus { color: var(--colorToolbarPassive2); }
[data-image-type^='video/']:before {
content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' width='16' height='16' viewBox='-10 -10 58 58'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M43,42H5c-2.209,0-4-1.791-4-4V10c0-2.209,1.791-4,4-4h38c2.209,0,4,1.791,4,4v28 C47,40.209,45.209,42,43,42z M12,8H5c-1.104,0-2,0.896-2,2v2h9V8z M23,8h-9v4h9V8z M34,8h-9v4h9V8z M45,10c0-1.104-0.896-2-2-2h-7v4 h9l0,0V10z M45,14L45,14H3v20h42l0,0V14z M45,36L45,36h-9v4h-2v-4h-9v4h-2v-4h-9v4h-2v-4H3v2c0,1.104,0.896,2,2,2h38 c1.104,0,2-0.896,2-2V36z M21.621,29.765C21.449,29.904,21.238,30,21,30c-0.553,0-1-0.447-1-1V19c0-0.552,0.447-1,1-1 c0.213,0,0.4,0.082,0.563,0.196l7.771,4.872C29.72,23.205,30,23.566,30,24c0,0.325-0.165,0.601-0.405,0.783L21.621,29.765z' fill='gray'%3E%3C/path%3E%3C/svg%3E");
margin-right: 4px;
}
/* Misc */
.text.selected, .command.selected, .screen:active, .command:active,
.range:active , .emoji.selected, .emoji:active {
color: var(--colorToolbarActive); filter: drop-shadow(0 0 8px var(--colorGlow));
}
.theme-light .text.selected, .theme-light .command.selected,
.theme-light .screen:active, .theme-light .command:active,
.theme-light .range:active, .theme-light .emoji.selected,
.theme-light .emoji:active {
background-color: var(--colorToolbarActive); color: var(--colorPanel);
filter: none; border-radius: 6px;
}
.grayed { opacity: 0.3; }
.noselect {
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none; -ms-user-select: none;
user-select: none; -webkit-user-select: none;
}
.nodrag {
-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none;
-o-user-drag: none; -ms-user-drag: none; user-drag: none;
}
.disabled { opacity: 0.5; cursor: default; pointer-events: none; }
.hidden { display: none; }
.starttransparent { opacity: 0; }
/* blinking */
@-webkit-keyframes blinking { to { visibility: hidden } }
@keyframes blinking { to { visibility: hidden } }
.blink>:not(div):not(ol):not(ul):not(pre):last-child:after,
.blink>ol:last-child li:last-child:after,.blink>pre:last-child code:after,
.blink>ul:last-child li:last-child:after {
-webkit-animation: blinking 1s steps(5,start) infinite;
animation: blinking 1s steps(5,start) infinite; content: "▋";
position: absolute; margin: 0 0 0 .25rem; padding:0; vertical-align: baseline;
white-space: nowrap; width: 0; overflow: visible;
}
/* Fonts */
@font-face {
font-family:"SansRegular";
src: url("./fonts/FiraSansCondensed-Regular.ttf") format('truetype');
}
@font-face {
font-family:"SansItalic";
src: url("./fonts/FiraSansCondensed-Italic.ttf") format('truetype');
}
@font-face {
font-family:"SansBold";
src: url("./fonts/FiraSansCondensed-Bold.ttf") format('truetype');
}
@font-face {
font-family:"SansBoldItalic";
src: url("./fonts/FiraSansCondensed-BoldItalic.ttf") format('truetype');
}
@font-face {
font-family:"SansRegularCondensed";
src: url("./fonts/FiraSansExtraCondensed-Regular.ttf") format('truetype');
}
@font-face {
font-family:"SansBoldCondensed";
src: url("./fonts/FiraSansExtraCondensed-Bold.ttf") format('truetype');
}
/* Layouts */
#main.ratio-wide { width: min(96vw, 192vh, 1400px); height: min(48vw,96vh,700px); } /* 1:2 */
#main.ratio-normal { width: min(96vw, 128vh, 1040px); height: min(72vw,96vh,780px); } /* 3:4 */
#main.layout-full { width: 100%; height: 100%; }
#main.layout-land #left { top: 0; left: 0; bottom: 38%; right: 50%; }
#main.layout-port #left { top: 0; left: 0; bottom: 0; right: 60%; }
#main.layout-full #left { top: 0; left: 0; bottom: 0; right: 0; margin: 0; }
#main.layout-full #left .border { display: none; }
#main.layout-land #right { top: 0; left: 50%; bottom: 0; right: 0; }
#main.layout-port #right { top: 0; left: 40%; bottom: 30%; right: 0; }
#main.layout-full #right { top: 10%; left: 45%; bottom: 30%; right: 5%; max-width: 800px; }
#main.layout-land #bottom { top: 62%; left: 0; bottom: 0; right: 50%; }
#main.layout-port #bottom { top: 70%; left: 40%; bottom: 0; right: 0; }
#main.layout-full #bottom { top: 70%; left: 45%; bottom: 10%; right: 5%; max-width: 750px; }
#main.presence-vr #left { box-shadow: none; background-color: transparent; }
#main.presence-vr #view { display: none; }
#main.presence-vr #left .border { display: none; }
#main.presence-vr #avatar { bottom: -8px; left: -400px; right: -400px; }
#main.layout-full #avatar { top: 0; left: 0; bottom: 0; right: 45%; }
@media (max-width: 1000px) {
#main.ratio-wide, #main.ratio-normal { width: 96vw; height: 90vh; }
#main.layout-full { width: 100%; height: 100%; }
#main.layout-land #left { top: 0; left: 0; bottom: 62%; right: 0; }
#main.layout-port #left { top: 0; left: 0; bottom: 24%; right: 62%; }
#main.layout-land #right { top: 38%; left: 0; bottom: 24%; right: 0; }
#main.layout-port #right { top: 0; left: 38%; bottom: 24%; right: 0; }
#main.layout-full #right { top: 0; left: 38%; bottom: 24%; right: 0; max-width: none; }
#main.layout-land #bottom { top: 76%; left: 0; bottom: 0; right: 0; }
#main.layout-port #bottom { top: 76%; left: 0; bottom: 0; right: 0; }
#main.layout-full #bottom { top: 76%; left: 38%; bottom: 0; right: 0; max-width: none; }
}
</style>
<script nomodule>alert("You browser doesn't seem to support modules. Use a modern browser to run Enterprise.");</script>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script async src="https://cdn.jsdelivr.net/npm/es-module-shims@1.7.1/dist/es-module-shims.js"></script>
<script type="importmap">
{ "imports":
{
"three": "https://cdn.jsdelivr.net/npm/three@0.161.0/build/three.module.js/+esm",
"three/examples/": "https://cdn.jsdelivr.net/npm/three@0.161.0/examples/",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.161.0/examples/jsm/",
"dompurify": "https://cdn.jsdelivr.net/npm/dompurify@3.0.6/+esm",
"marked": "https://cdn.jsdelivr.net/npm/marked@11.2.0/+esm"
}
}
</script>
<script src="https://cdn.jsdelivr.net/npm/microsoft-cognitiveservices-speech-sdk@latest/distrib/browser/microsoft.cognitiveservices.speech.sdk.bundle-min.js"></script>
<script type="module">
import { site } from './siteconfig.js'
import { TalkingHead } from "./modules/talkinghead.mjs";
import dompurify from 'dompurify';
import { marked } from 'marked';
// API endpoints/proxys
const jwtEndpoint = "/app/jwt/get"; // Get JSON Web Token for Single Sign-On
const openaiChatCompletionsProxy = "/openai/v1/chat/completions";
const openaiModerationsProxy = "/openai/v1/moderations";
const openaiAudioTranscriptionsProxy = "/openai/v1/audio/transcriptions";
const geminiProxy = "/gemini/";
const googleTTSProxy = "/gtts/";
const elevenTTSProxy = [
"wss://" + window.location.host + "/elevenlabs/",
"/v1/text-to-speech/",
"/stream-input?model_id=eleven_multilingual_v2&output_format=pcm_22050"
];
const microsoftTTSProxy = [
"wss://" + window.location.host + "/mstts/",
"/cognitiveservices/websocket/v1"
];
// I18n internationalization
const i18n = {
'fi': {
'Avatar': 'Hahmo', 'Camera': 'Kamera', 'Audio': 'Ääni', 'Manuscript': 'Käsikirjoitus',
'Emotion': 'Tunne', 'Neutral': 'Perus', 'Happy': 'Ilo', 'Angry': 'Viha', 'Sad': 'Suru',
'Fear': 'Pelko', 'Disgust': 'Inho', 'Love': 'Rakkaus', 'Sleep': 'Uni', 'Pose': 'Asento',
'Action': 'Toiminta', 'Frame': 'Rajaus', 'Full': 'Kokovartalo', 'Upper': 'Yläosa',
'Head': 'Pää', 'Director': 'Ohjaus', 'Pause': 'Pysäytyskuva', 'Panning': 'Panorointi',
'Slow-motion': 'Hidastus', 'Ambience': 'Ambienssi', 'Silence': 'Hiljaisuus',
'Session': 'Sessio', 'Theme': 'Teema', 'Location': 'Paikka', 'Voice': 'Istuva',
'AI': 'Tekoäly', 'Emoji': 'Emojit', 'Title': 'Otsikko', 'System': 'Ohjeistus',
'ai-system': 'Järjestelmäviesti.', 'ai-user1': 'Käyttäjän syöte #1',
'ai-ai1': 'Tekoälyn vaste #1', 'ai-user2': 'Käyttäjän syöte #2',
'ai-ai2': 'Tekoälyn vaste #2', 'Example1': 'Esim #1', 'Example2': 'Esim #2',
'Dark': 'Tumma', 'Light': 'Vaalea', 'theme-wide': 'Laajakuva', 'theme-43': '4:3',
'theme-landscape': 'Vaaka', 'theme-portrait': 'Pysty', 'Empty': 'Tyhjä',
'Adjust': 'Säätö', 'Speech': 'Puhe', 'Silence': 'Hiljaisuus', 'Framing': 'Rajaus',
'Mixer': 'Mikseri', 'Space': 'Tila', 'Dry': 'Suora', 'voice-test': 'Äänitesti',
'Limits': 'Rajat', 'ai-stop': 'Stop', 'ai-stopword': 'Avainsana', 'ai-user': 'Käyttäjä',
'ai-username': 'Nimi', 'input': 'Kirjoita viesti.', 'Name': 'Nimi', 'Language': 'Kieli',
'en': 'English', 'fi': 'Finnish', 'words': 'sanaa', 'dialogs': 'sanomaa',
'Manuscript': 'Käsikirjoitus', 'Exclude': 'Ohita', 'Italics': 'Kursiivi',
'Code': 'Koodi', 'Light': 'Valo', 'LightAmbient': 'Ambientti',
'LightDirect': 'Suunnattu', 'LightSpot': 'Spotti', 'theme-full': "Täysi",
'lt': 'Liettua', 'test-sentence': "Kirjoita tähän testilause.", 'Mid': 'Keskiosa',
'Gesture': 'Ele', 'PoseMovement': 'Liike', 'Visible': 'Näytä',
'Helper': 'Apuri', 'Edit': 'Muokkaa', 'Script': 'Skripti'
},
'en': {
'ai-system': 'System message.', 'ai-user1': 'User example #1',
'ai-ai1': 'AI response #1', 'ai-user2': 'User example #2',
'ai-ai2': 'AI response #2', 'Example1': 'Example-1', 'Example2': 'Example-2',
'theme-wide': 'Widescreen', 'theme-43': '4:3', 'theme-landscape': 'Landscape',
'theme-portrait': 'Portrait', 'voice-test': 'Speak', 'ai-stop': 'Stop',
'ai-user': 'User', 'input': 'Message.', 'en': 'English', 'fi': 'Finnish',
'ai-stopword': 'Word', 'ai-username': 'Name', 'LightAmbient': 'Ambient',
'LightDirect': 'Direct', 'LightSpot': 'Spot', 'theme-full': "Fullscreen",
'lt': 'Lithuanian', 'test-sentence': "Write your test sentence.",
'PoseMovement': 'Movement'
}
}
// i18n
// Default UI language is English
function i18nWord(w,l) {
l = l || cfg('theme-lang') || 'en';
return (( i18n[l] && i18n[l][w] ) ? i18n[l][w] : w);
}
function i18nTranslate(l) {
l = l || cfg('theme-lang') || 'en';
// Text
d3.selectAll("[data-i18n-text]").nodes().forEach( n => {
const e = d3.select(n);
e.text( i18nWord(e.attr("data-i18n-text"),l ) );
});
// Title
d3.selectAll("[data-i18n-title]").nodes().forEach( n => {
const e = d3.select(n);
e.attr( 'title', i18nWord( e.attr("data-i18n-title"),l ) );
});
// Placeholder
d3.selectAll("[data-i18n-placeholder]").nodes().forEach( n => {
const e = d3.select(n);
e.attr( 'placeholder', i18nWord( e.attr("data-i18n-placeholder"),l) );
});
// Site
d3.selectAll("[data-i18n-site]").nodes().forEach( n => {
const e = d3.select(n);
const label = e.attr("data-i18n-site");
const [section, ...rest] = label.split('-');
const item = rest.join('-');
let text = item;
if ( site[section] && site[section][item] && site[section][item][l] ) {
text = site[section][item][l];
}
e.text( text );
});
}
// Markdown configuration
const markedOptions = { gfm: true, breaks: true };
// Open AI configuration
let aiController = null;
// ElevenLabs configuration
const elevenBOS = {
"text": " ",
"voice_settings": { "stability": 0.8, "similarity_boost": true },
"generation_config": {
"chunk_length_schedule": [500,500,500,500]
}
};
let elevenSocket = null;
let elevenInputMsgs = null;
let elevenOutputMsg = null;
let elevenOnProcessed = null;
// JSON Web Token (JWT)
let jwtExpires = 0;
let jwt = '';
// Get JSON Web Token
async function jwtGet() {
const limit = Math.round(Date.now() / 1000) + 60;
if ( jwtExpires < limit ) {
try {
const o = await (await fetch( jwtEndpoint, { cache: "no-store" } )).json();
if ( o && o.jwt ) {
const b64Url = o.jwt.split('.')[1];
const b64 = b64Url.replace(/-/g, '+').replace(/_/g, '/');
const s = decodeURIComponent( window.atob(b64).split('').map( (c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
const p = JSON.parse(s);
jwtExpires = (p && p.exp) ? p.exp : 0;
jwt = o.jwt;
} else {
jwt = '';
jwtExpires = 0;
}
} catch(e) {
console.error(e);
jwt = '';
jwtExpires = 0;
}
}
return jwt.slice();
}
// Speak using ElevenLabs
async function elevenSpeak(s,node=null) {
if ( !elevenSocket ) {
// Temporary reservation of WebSocket connection
elevenSocket = { readyState: 0 };
// Temporary stack of message until the connection is established
elevenInputMsgs = [
elevenBOS,
{
"text": s,
"try_trigger_generation": false,
"flush": true
}
];
// Build the URL
let url = elevenTTSProxy[0];
url += await jwtGet();
url += elevenTTSProxy[1];
url += cfg('voice-eleven-id');
url += elevenTTSProxy[2];
// Make the connection
elevenSocket = new WebSocket(url);
// Connection opened
elevenSocket.onopen = function (event) {
elevenOutputMsg = null;
while (elevenInputMsgs.length > 0) {
elevenSocket.send(JSON.stringify(elevenInputMsgs.shift()));
}
}
// New message received
elevenSocket.onmessage = function (event) {
const r = JSON.parse(event.data);
// Speak audio
if ( (r.isFinal || r.normalizedAlignment) && elevenOutputMsg ) {
head.speakAudio( elevenOutputMsg, { lipsyncLang: cfg('voice-lipsync-lang') }, node ? addText.bind(null,node) : null );
if ( elevenOnProcessed ) {
elevenOnProcessed();
}
elevenOutputMsg = null;
}
if ( !r.isFinal ) {
// New part
if ( r.alignment ) {
elevenOutputMsg = { audio: [], words: [], wtimes: [], wdurations: [] };
// Parse chars to words
let word = '';
let time = 0;
let duration = 0;
for( let i=0; i<r.alignment.chars.length; i++ ) {
if ( word.length === 0 ) time = r.alignment.charStartTimesMs[i];
if ( word.length && r.alignment.chars[i] === ' ' ) {
elevenOutputMsg.words.push( word );
elevenOutputMsg.wtimes.push(time);
elevenOutputMsg.wdurations.push(duration);
word = '';
duration = 0;
} else {
duration += r.alignment.charDurationsMs[i];
word += r.alignment.chars[i];
}
}
if ( word.length ) {
elevenOutputMsg.words.push(word);
elevenOutputMsg.wtimes.push(time);
elevenOutputMsg.wdurations.push(duration);
}
}
// Add audio content to message
if ( r.audio && elevenOutputMsg ) {
elevenOutputMsg.audio.push( head.b64ToArrayBuffer( r.audio ) );
}
}
};
// Error
elevenSocket.onerror = function (error) {
if ( elevenOnProcessed ) elevenOnProcessed();
console.error(`WebSocket Error: ${error}`);
};
// Connection closed
elevenSocket.onclose = function (event) {
if ( elevenOnProcessed ) elevenOnProcessed();
if ( event.wasClean) {
// console.info(`Connection closed cleanly, code=${event.code}, reason=${event.reason}`);
} else {
console.warn('Connection died');
}
elevenSocket = null;
};
} else {
let msg = {
"text": s
};
if ( s.length ) {
msg["try_trigger_generation"] = false;
msg["flush"] = true;
}
if (elevenSocket.readyState === 1) { // OPEN
elevenSocket.send(JSON.stringify(msg))
} else if ( elevenSocket.readyState === 0 ) { // CONNECTING
elevenInputMsgs.push(msg);
}
}
}
// Speak using Microsoft
let microsoftSynthesizer = null;
const microsoftQueue= [];
async function microsoftSpeak(s, node=null, onprocessed=null) {
if ( s === null ) {
microsoftQueue.push( null );
} else {
// Voice config
const id = cfg("voice-microsoft-id");
const e = d3.select("[data-voice-microsoft-id='" + id + "']");
const lang = e.attr("data-voice-microsoft-lang");
// SSML
const ssml = "<speak version='1.0' " +
"xmlns:mstts='http://www.w3.org/2001/mstts' " +
"xml:lang='" + lang + "'>" +
"<voice name='" + id + "'>" +
"<mstts:viseme type='redlips_front'/>" +
s.replaceAll('&','&').replaceAll('<','<').replaceAll('>','>') +
"</voice>" +
"</speak>";
microsoftQueue.push( {
ssml: ssml,
node: node,
onprocessed: onprocessed,
speak: {
audio: [], words: [], wtimes: [], wdurations: [],
visemes: [], vtimes: [], vdurations: [], markers: [], mtimes: []
}
} );
}
// If this was the first item, start the process
if ( microsoftQueue.length === 1 ) {
microsoftProcessQueue();
}
}
async function microsoftProcessQueue() {
if ( microsoftQueue.length ) {
const job = microsoftQueue[0];
if ( job === null ) {
microsoftQueue.shift();
if ( microsoftQueue.length === 0 && microsoftSynthesizer ) {
microsoftSynthesizer.close();
microsoftSynthesizer = null;
}
} else {
// If we do not a speech synthesizer, create a new
if ( !microsoftSynthesizer ) {
// Create a new speech synthesizer
const endpoint = microsoftTTSProxy[0] + await jwtGet() + microsoftTTSProxy[1];
const config = window.SpeechSDK.SpeechConfig.fromEndpoint(endpoint);
config.setProperty("SpeechServiceConnection_Endpoint",endpoint);
config.speechSynthesisOutputFormat = window.SpeechSDK.SpeechSynthesisOutputFormat.Raw22050Hz16BitMonoPcm;
config.setProperty(window.SpeechSDK.PropertyId.SpeechServiceResponse_RequestSentenceBoundary, "true");
microsoftSynthesizer = new window.SpeechSDK.SpeechSynthesizer(config,null);
// Viseme conversion from Microsoft to Oculus
// TODO: Check this conversion again!
const visemeMap = [
"sil", 'aa', 'aa', 'O', 'E', // 0 - 4
'E', 'I', 'U', 'O', 'aa', // 5 - 9
'O', 'I', 'kk', 'RR', 'nn', // 10 - 14
'SS', 'SS', 'TH', 'FF', 'DD', // 15 - 19
'kk', 'PP' // 20 - 21
];
// Process visemes
microsoftSynthesizer.visemeReceived = function(s, e) {
if ( microsoftQueue[0] && microsoftQueue[0].speak ) {
const o = microsoftQueue[0].speak;
const viseme = visemeMap[e.visemeId];
const time = e.audioOffset / 10000;
// Calculate the duration of the previous viseme
if ( o.vdurations.length ) {
if ( o.visemes[ o.visemes.length-1 ] === 0 ) {
o.visemes.pop();
o.vtimes.pop();
o.vdurations.pop();
} else {
// Remove silence
o.vdurations[ o.vdurations.length-1 ] = time - o.vtimes[ o.vdurations.length-1 ];
}
}
// Add this viseme
o.visemes.push( viseme );
o.vtimes.push( time );
o.vdurations.push( 75 ); // Duration will be fixed when the next viseme is received
}
};
// Process word boundaries and punctuations
microsoftSynthesizer.wordBoundary = function (s, e) {
if ( microsoftQueue[0] && microsoftQueue[0].speak ) {
const o = microsoftQueue[0].speak;
const word = e.text;
const time = e.audioOffset / 10000;
const duration = e.duration / 10000;
if ( e.boundaryType === "PunctuationBoundary" && o.words.length ) {
o.words[ o.words.length-1 ] += word;
} else if ( e.boundaryType === "WordBoundary" || e.boundaryType === "PunctuationBoundary" ) {
o.words.push( word );
o.wtimes.push( time );
o.wdurations.push( duration );
} else if ( e.boundaryType === "SentenceBoundary" ) {
if ( time > 500 ) {
o.markers.push( () => { head.lookAtCamera(500); });
o.mtimes.push( time - 500 );
}
}
}
};
}
// Speak the SSML
microsoftSynthesizer.speakSsmlAsync(job.ssml,
function (result) {
if ( microsoftQueue[0] && microsoftQueue[0].speak ) {
if (result.reason === window.SpeechSDK.ResultReason.SynthesizingAudioCompleted) {
const job = microsoftQueue[0];
job.speak.audio.push( result.audioData );
head.speakAudio(job.speak, {}, job.node ? addText.bind(null,job.node) : null );
if ( job.onprocessed ) job.onprocessed();
}
microsoftQueue.shift();
microsoftProcessQueue();
}
}, function (err) {
if ( job.onprocessed ) job.onprocessed();
console.log(err);
microsoftQueue.shift();
microsoftProcessQueue();
}
);
}
}
}
// Whisper MP3
let whisperAudio = null;
let whisperLipsyncLang = 'en';
async function whisperLoadMP3(file) {
try {
d3.select("#playmp3").classed("disabled", true);
const form = new FormData();
form.append("file", file);
form.append("model", "whisper-1");
form.append("response_format", "verbose_json" );
form.append("prompt","[The following is a full verbatim transcription without additional details, comments or emojis:]");
form.append("timestamp_granularities[]", "word" );
form.append("timestamp_granularities[]", "segment" );
const response = await fetch( openaiAudioTranscriptionsProxy , {
method: "POST",
body: form,
headers: {
"Authorization": "Bearer " + await jwtGet()
}
});
if ( response.ok ) {
const json = await response.json();
d3.select("#jsonmp3").property("value", JSON.stringify(json) );
// Fetch audio
if ( json.words && json.words.length ) {
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = async readerEvent => {
let arraybuffer = readerEvent.target.result;
let audiobuffer = await head.audioCtx.decodeAudioData(arraybuffer);
// Set lip-sync language
whisperLipsyncLang = json.language.substring(0,2);
// Add words to the audio object
whisperAudio = {
audio: audiobuffer,
words: [],
wtimes: [],
wdurations: [],
markers: [],
mtimes: []
};
json.words.forEach( x => {
// Word
whisperAudio.words.push( x.word );
// Starting time
let t = 1000 * x.start;
if ( t > 150 ) t -= 150;
whisperAudio.wtimes.push( t );
// Duration
let d = 1000 * (x.end - x.start);
if ( d > 20 ) d -= 20;
whisperAudio.wdurations.push( d );
});
// Add timed callback markers to the audio object
const startSegment = async () => {
// Look at the camera
head.lookAtCamera(500);
head.speakWithHands();
};
json.segments.forEach( x => {
if ( x.start > 2 && x.text.length > 10 ) {
whisperAudio.markers.push( startSegment );
whisperAudio.mtimes.push( 1000 * x.start - 1000 );
}
});
d3.select("#playmp3").classed("disabled", false);
}
}
} else {
d3.select("#jsonmp3").property("value", 'Error: ' + response.status + ' ' + response.statusText );
console.log(response);
}
} catch (error) {
console.log(error);
}
}
// RECORDING
let recordingMediaRecorder = null;
let recordingAnalyzer = null;
let recordingIgnoreData = false;
let recordingChunks = [];
const recordingMediaTypes = [
{ type: "audio/webm", ext: "webm" },
{ type: "video/mp4", ext: "mp4" }
];
let recordingMediaType = {};
for( let i=0; i<recordingMediaTypes.length; i++ ) {
if ( MediaRecorder.isTypeSupported(recordingMediaTypes[i].type) ) {
recordingMediaType = recordingMediaTypes[i];
break;
}
}
const recordingBeep = "data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+ Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ 0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7 FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb//////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=";
const recordingPlaySound = (function beep() {
const snd = new Audio(recordingBeep);
return function() { snd.play(); }
})();
async function recordingRecord() {
if ( !recordingMediaRecorder ) {
try {
if ( !navigator.mediaDevices ) throw new Error("No navigator.mediaDevices available for recording.");
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
recordingMediaRecorder = new MediaRecorder(stream, { mimeType: recordingMediaType.type });
recordingMediaRecorder.ondataavailable = async (event) => {
// If marked ignore, do not transcribe
if ( recordingIgnoreData ) {
recordingIgnoreData = false;
return;
} else {
console.log('Recorded data:',event);
recordingIgnoreData = false;
}
if ( event.data.size > 0 ) {
// Make a transcription
const file = new File([event.data], 'file.'+recordingMediaType.ext, { type: recordingMediaType.type });
const form = new FormData();
form.append("file", file);
form.append("model", "whisper-1");
const lang = cfg('theme-lang') || 'en';
form.append("language", lang);
const response = await fetch( openaiAudioTranscriptionsProxy , {
method: "POST",
body: form,
headers: {
"Authorization": "Bearer " + await jwtGet()
}
});
// Append text to input
if ( response.ok ) {
let json;
try {
json = await response.json();
} catch(error) {
console.error("Invalid response from OpenAI");
}
if ( json && json.text ) {
const e = d3.select("#input");
let text = e.property("value");
if ( text ) {
e.property("value", text + ' ' + json.text );
} else {
e.property("value", json.text );
}
}