forked from met4citizen/TalkingHead
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
executable file
·4165 lines (3754 loc) · 189 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: 2rem;
}
.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) ); }
/* 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 { 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: "▋";
margin-left: .25rem; vertical-align: baseline; white-space: nowrap;
}
/* 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/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{ "imports":
{
"three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js/+esm",
"three/examples/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/",
"three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/",
"dompurify": "https://cdn.jsdelivr.net/npm/[email protected]/+esm",
"marked": "https://cdn.jsdelivr.net/npm/[email protected]/+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 vertexaiChatCompletionsProxy = "/vertexai/";
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'
},
'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."
}
}
// 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;
// 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 );
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) {
console.error(`WebSocket Error: ${error}`);
};
// Connection closed
elevenSocket.onclose = function (event) {
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) {
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,
speak: { audio: [], words: [], wtimes: [], wdurations: [], visemes: [], vtimes: [], vdurations: [] }
} );
}
// 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;
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 );
}
}
};
}
// 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 );
}
microsoftQueue.shift();
microsoftProcessQueue();
}
}, function (err) {
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("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);
}
}
// Number of words on a string.
function nWords(str) {
return str ? str.trim().split(/\s+/).length : 0;
}
// Default settings
let CFG = {
session: 0,
sessions : [
{
name: "Nimetön",
theme: { lang: 'en', brightness:"dark", ratio:"wide", layout:"port" },
view: { image: 'NONE' },
avatar: {},
camera: { frame: 'full' },
ai: {},
voice: { background: "NONE", type: "google", google:{ id: "en-GB-Standard-A"}, lipsync:{ lang: 'en' } }
},
{
name: "Nimetön 2",
theme: { lang: 'en', brightness: "dark", ratio: "wide", layout: "land" },
view: { image: 'NONE' },
avatar: {},
camera: { frame: 'upper' },
ai: {},
voice: { background: "NONE", type: "google", google:{ id: "en-GB-Standard-A"}, lipsync:{ lang: 'en' } }
},
]
};
// Dynamically created icons
const svgSelect = '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M10.5858 13.4142L7.75735 10.5858L6.34314 12L10.5858 16.2427L17.6568 9.1716L16.2426 7.75739L10.5858 13.4142Z" fill="currentColor" /></svg>';
const svgSpeak = '<svg viewBox="-2 -2 28 28" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M12 18.939C14.2091 18.939 16 17.1482 16 14.939C16 12.7299 14.2091 10.939 12 10.939C9.79086 10.939 8 12.7299 8 14.939C8 17.1482 9.79086 18.939 12 18.939ZM12 16.939C13.1046 16.939 14 16.0436 14 14.939C14 13.8345 13.1046 12.939 12 12.939C10.8954 12.939 10 13.8345 10 14.939C10 16.0436 10.8954 16.939 12 16.939Z" fill="currentColor" /><path d="M12 9.04401C13.1046 9.04401 14 8.14858 14 7.04401C14 5.93944 13.1046 5.04401 12 5.04401C10.8954 5.04401 10 5.93944 10 7.04401C10 8.14858 10.8954 9.04401 12 9.04401Z" fill="currentColor" /><path fill-rule="evenodd" clip-rule="evenodd" d="M7 1C5.34315 1 4 2.34315 4 4V20C4 21.6569 5.34315 23 7 23H17C18.6569 23 20 21.6569 20 20V4C20 2.34315 18.6569 1 17 1H7ZM17 3H7C6.44772 3 6 3.44772 6 4V20C6 20.5523 6.44772 21 7 21H17C17.5523 21 18 20.5523 18 20V4C18 3.44772 17.5523 3 17 3Z" fill="currentColor" /></svg>'
const svgStop = '<svg viewBox="-2 -2 28 28" xmlns="http://www.w3.org/2000/svg"><path d="M6.2253 4.81108C5.83477 4.42056 5.20161 4.42056 4.81108 4.81108C4.42056 5.20161 4.42056 5.83477 4.81108 6.2253L10.5858 12L4.81114 17.7747C4.42062 18.1652 4.42062 18.7984 4.81114 19.1889C5.20167 19.5794 5.83483 19.5794 6.22535 19.1889L12 13.4142L17.7747 19.1889C18.1652 19.5794 18.7984 19.5794 19.1889 19.1889C19.5794 18.7984 19.5794 18.1652 19.1889 17.7747L13.4142 12L19.189 6.2253C19.5795 5.83477 19.5795 5.20161 19.189 4.81108C18.7985 4.42056 18.1653 4.42056 17.7748 4.81108L12 10.5858L6.2253 4.81108Z" fill="currentColor" /></svg>';
const svgRepost = '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M13.1459 11.0499L12.9716 9.05752L15.3462 8.84977C14.4471 7.98322 13.2242 7.4503 11.8769 7.4503C9.11547 7.4503 6.87689 9.68888 6.87689 12.4503C6.87689 15.2117 9.11547 17.4503 11.8769 17.4503C13.6977 17.4503 15.2911 16.4771 16.1654 15.0224L18.1682 15.5231C17.0301 17.8487 14.6405 19.4503 11.8769 19.4503C8.0109 19.4503 4.87689 16.3163 4.87689 12.4503C4.87689 8.58431 8.0109 5.4503 11.8769 5.4503C13.8233 5.4503 15.5842 6.24474 16.853 7.52706L16.6078 4.72412L18.6002 4.5498L19.1231 10.527L13.1459 11.0499Z" fill="currentColor" /></svg>';
// Get/set config value for the current session
function cfg(key,value) {
if ( key === undefined ) return CFG.sessions[CFG.session];
let parts = key.split('-').map( x => isNaN(x) ? x : parseInt(x) );
if ( value === undefined ) {
return parts.reduce( (o,p) => o ? o[p] : undefined, CFG.sessions[CFG.session] );
} else {
parts.reduce( (o,p,i) => {
const def = (typeof parts[i+1] === 'number') ? [] : {};
return (o[p] = (parts.length-1) === i ? value : (o[p] || def));
}, CFG.sessions[CFG.session] );
}
}
// Load settings
try {
let json = localStorage.getItem('talkinghead');
CFG = (json ? JSON.parse(json) : CFG);
} catch(error) {
alert("Invalid JSON settings");
console.error(error);
}
window.cfg = cfg;
// Save config to localStorage and show active session config
let loadingConfig = false;
function saveConfig() {
if ( !loadingConfig ) {
let json = JSON.stringify(CFG);
localStorage.setItem("talkinghead", json);
json = JSON.stringify( cfg() );
d3.select("#json").property("value", json );
}
}
// Load config for the given session
function loadConfig(session = null) {
try {
loadingConfig = true;
let json = localStorage.getItem('talkinghead');
const config = (json ? JSON.parse(json) : CFG);
if ( config && config.hasOwnProperty("session") && config.hasOwnProperty("sessions") && config.sessions.length ) {
CFG = config;
if ( session !== null && session >= 0 && session < CFG.sessions.length ) {
CFG.session = session;
json = JSON.stringify(CFG);
localStorage.setItem("talkinghead", json);
}
// Populate sessions
d3.selectAll(".session").nodes().forEach( n => {
const e = d3.select(n);
const id = parseInt( e.property("id").split("-")[1] );
if ( id >= 0 && id < CFG.sessions.length ) {
e.classed("selected", (id === CFG.session) );
} else {
e.remove();
}
});
for( let i=0; i<CFG.sessions.length; i++ ) {
const e = d3.select("#session-"+i);