-
Notifications
You must be signed in to change notification settings - Fork 21
/
early.js
2281 lines (1848 loc) · 84.8 KB
/
early.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
const text_file_extensions = ['txt','js','ts','json','html','xhtml','css','yaml','ino','py','readme'];
const binary_image_extensions = ['png','jpg','jpeg','gif','webp','ico','bmp','tiff'];
const binary_video_extensions = ['mp4','h264','h265','mjpeg','webm','mov','ogv'];
const binary_audio_extensions = ['mp3','wav','flac','aac','m4a','ogg'];
const binary_media_extensions = binary_video_extensions.concat(binary_audio_extensions); //['mp4','mp3','wav','h264','h265','mjpeg','flac','aac','webm','m4a','ogg'];
const archive_extensions = ['zip','gzip'];
const binary_document_extensions = ['pdf','epub']; // epub is zipped html
function add_body_class(new_class=null){
if(typeof new_class == 'string' && new_class.length){
if(!document.body.classList.contains(new_class)){
document.body.classList.add(new_class);
}
}
}
window.add_body_class = add_body_class;
function remove_body_class(new_class=null){
if(typeof new_class == 'string' && new_class.length){
if(document.body.classList.contains(new_class)){
document.body.classList.remove(new_class);
}
}
}
window.remove_body_class = remove_body_class;
function add_element_class(target_element=null, class_name=null){
if(target_element != null && typeof class_name == 'string'){
if(!target_element.classList.contains(class_name)){
target_element.classList.add(class_name);
}
}
}
window.add_element_class = add_element_class;
function remove_element_class(target_element=null, class_name=null){
if(target_element != null && typeof class_name == 'string'){
if(target_element.classList.contains(class_name)){
target_element.classList.remove(class_name);
}
}
}
window.remove_element_class = remove_element_class;
function keyz(object){
if(typeof object != 'undefined' && object != null){
return Object.keys(object);
}
else{
console.error("KEYZ: invalid object provided");
return [];
}
}
window.keyz = keyz;
function delay(millisec) {
return new Promise(resolve => {
setTimeout(() => { resolve('') }, millisec);
})
}
window.delay = delay;
const n = navigator;
//console.log("does a service worker exist? n.serviceWorker:", n.serviceWorker);
const controlling = n.serviceWorker && n.serviceWorker.controller;
if(typeof navigator.serviceWorker != 'undefined'){
navigator.serviceWorker.addEventListener("message", (message) => {
console.error("index.html: received message from service worker: ", message);
});
}
//console.log("is a service worker controlling? ", controlling);
//console.log("window.crossOriginIsolated: ", window.crossOriginIsolated);
if(document.pictureInPictureEnabled){
document.body.classList.add('pip-available');
}
window.time_started = Date.now();
function delay(millisec) {
return new Promise(resolve => {
setTimeout(() => { resolve('') }, millisec);
})
}
function is_valid_URL(test_URL) {
let url;
try {
url = new URL(test_URL);
} catch (_) {
console.warn("is_valid_URL: URL is not valid: ", test_URL);
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
function clean_url_bar(){
console.warn("doing history.replaceState");
let new_location = window.location.origin + '/';
if(window.location.pathname.startsWith('/wasm4')){
new_location += 'wasm4/';
}
console.log("clean_url_bar: new_location: ", new_location);
history.replaceState(null, 'Papeg.ai', new_location);
}
let should_clean_url_bar = false;
let received_url_parameters = null;
window.url_parameters = new URLSearchParams(window.location.search);
//console.log("window.url_parameters: ", window.url_parameters);
window.url_parameter_functionality = window.url_parameters.get('do'); // ?do=
if(typeof window.url_parameter_functionality == 'string'){
if(window.url_parameter_functionality.startsWith('http') || window.url_parameter_functionality.indexOf('/') != -1){
console.error("unvalid functionality parameter in URL: " + window.url_parameter_functionality);
window.url_parameter_functionality = null;
}
else{
if(window.url_parameter_functionality.toLowerCase() == 'advanced'){
console.log("URL DO PARAMETER WAS ADVANCED");
window.settings.settings_complexity == 'advanced';
window.save_settings();
}
else if(window.url_parameter_functionality.toLowerCase() == 'developer'){
console.log("URL DO PARAMETER WAS DEVELOPER");
window.settings.settings_complexity == 'developer';
window.save_settings();
}
}
console.log("received functionality link. window.url_parameter_functionality: ", window.url_parameter_functionality);
should_clean_url_bar = true;
}
const ask_for_url_dialog_iframe_el = document.getElementById('ask-for-url-dialog-iframe');
ask_for_url_dialog_iframe_el.addEventListener('load', () => {
console.log("preview iframe has loaded in");
ask_for_url_dialog_iframe_el.classList.remove('hidden');
});
ask_for_url_dialog_iframe_el.addEventListener('error', () => {
console.error("Error loading preview image of URL to download");
});
let url_parameter_ai = window.url_parameters.get('ai');
if(typeof url_parameter_ai == 'string'){
url_parameter_ai = url_parameter_ai.replaceAll('?download=true','');
url_parameter_ai = url_parameter_ai.replace('http:/','http://');
url_parameter_ai = url_parameter_ai.replace('https:/','https://');
console.log("received AI in url: url_parameter_ai: ", url_parameter_ai);
if(url_parameter_ai.startsWith('http') && is_valid_URL(url_parameter_ai) === false){
url_parameter_ai = null;
}
should_clean_url_bar = true;
}
let url_parameter_file = window.url_parameters.get('file');
if(typeof url_parameter_file == 'string'){
console.log("received FILE in url: url_parameter_file: ", url_parameter_file);
if(!url_parameter_file.startsWith('http')){
console.warn("invalid file path provided (did not start with http)");
url_parameter_file = null;
}
if(!url_parameter_file.indexOf('.') == -1){
console.warn("invalid file path provided (did not contain dot)");
url_parameter_file = null;
}
url_parameter_file = url_parameter_file.replace('http:/','http://');
url_parameter_file = url_parameter_file.replace('https:/','https://');
console.log("url_parameter_file: ", url_parameter_file);
if(is_valid_URL(url_parameter_file) === false){
console.error("provided URL was invalid: ", url_parameter_file);
url_parameter_file = null;
}
else{
console.log("privided file URL seems valid: ", url_parameter_file);
}
should_clean_url_bar = true;
}
//console.log("url_parameter_ai: ", url_parameter_ai);
//const url_parameter_prompt = window.url_parameters.get('prompt');
//console.log("url_parameter_prompt: ", url_parameter_prompt);
//window.location.href = window.location.origin + window.location.pathname;
let received_a_document = false;
window.received_document = window.url_parameters.get('document');
window.received_document_extension = null;
window.received_document_filename = null;
if(typeof window.received_document == 'string'){
console.log("received a document via url: window.received_document: ", window.received_document);
received_a_document = true;
window.received_document_extension = window.url_parameters.get('extension');
if(typeof window.received_document_extension == 'string' && window.received_document_extension.length){
console.log("- also received a document extension: ", window.received_document_extension);
}
else{
window.received_document_extension = 'txt';
}
window.received_document_filename = window.url_parameters.get('filename');
if(typeof window.received_document_filename == 'string' && window.received_document_filename.length){
console.log("- also received a document filename: ", window.received_document_filename);
}
else{
window.received_document_filename = null;
}
}
else{
window.received_prompt = window.url_parameters.get('prompt');
if(typeof window.received_prompt == 'string'){
console.log("No received document, but did receive a prompt via the url: window.received_prompt: ", window.received_prompt);
}
}
if(typeof window.received_prompt == 'string'){
if(window.received_prompt.indexOf(' ') == -1){
window.received_prompt = window.received_prompt.replaceAll('_',' ');
}
should_clean_url_bar = true;
}
// Show received prompt
const received_prompt_textarea_el = document.getElementById('received-prompt-textarea');
function show_received_prompt(){
console.log("in show_received_prompt. window.received_prompt: ", window.received_prompt);
if(typeof window.received_prompt == 'string' && window.received_prompt.length > 2 && typeof url_parameter_ai == 'string' && url_parameter_ai.length > 1){
if(window.received_prompt.indexOf('_') != -1 && window.received_prompt.indexOf('%20') == -1 && window.received_prompt.indexOf(' ') == -1){
window.received_prompt = window.received_prompt.replaceAll('_',' ');
}
received_prompt_textarea_el.value = window.received_prompt;
if(typeof textAreaAdjust === 'function'){
textAreaAdjust(received_prompt_textarea_el);
}
if(typeof window.settings.assistants[window.settings.assistant] != 'undefined' && typeof window.settings.assistants[window.settings.assistant].emoji == 'string' && window.settings.assistants[window.settings.assistant].emoji.length){
let received_emoji_icon_el = document.getElementById('received-prompt-assistant-emoji');
received_emoji_icon_el.textContent = window.settings.assistants[window.settings.assistant].emoji;
if(typeof window.settings.assistants[window.settings.assistant].emoji_bg == 'string' && window.settings.assistants[window.settings.assistant].emoji_bg.length > 2){
if(!window.settings.assistants[window.settings.assistant].emoji_bg.startsWith('#')){
window.settings.assistants[window.settings.assistant].emoji_bg = '#' + window.settings.assistants[window.settings.assistant].emoji_bg;
save_settings();
}
received_emoji_icon_el.style.backgroundColor = window.settings.assistants[window.settings.assistant].emoji_bg;
}
}
else if(typeof window.settings.assistants[window.settings.assistant] != 'undefined' && typeof window.settings.assistants[window.settings.assistant].icon == 'string' && window.settings.assistants[window.settings.assistant].icon.length){
let received_prompt_icon_el = document.getElementById('received-prompt-assistant-name-icon');
received_prompt_icon_el.src = 'images/' + window.settings.assistants[window.settings.assistant].icon + '_thumb.png';
}
else{
let received_prompt_icon_el = document.getElementById('received-prompt-assistant-name-icon');
received_prompt_icon_el.src = 'images/developer_thumb.png';
}
document.getElementById('received-prompt-dialog').showModal();
}
window.received_prompt = null;
}
// Show received document
const received_document_dialog_el = document.getElementById('received-document-dialog');
const received_document_filename_el = document.getElementById('received-document-filename');
const received_document_textarea_el = document.getElementById('received-document-textarea');
const share_document_also_share_ai_el = document.getElementById('share-document-also-share-ai-checkbox');
const share_document_link_text_el = document.getElementById('share-document-link-text');
function show_received_document(text=null,suggested_filename=null,extension=null){
console.log("in show_received_document. text,extension: ", text, extension);
if(typeof text != 'string' && typeof window.received_document == 'string'){
text = window.received_document;
}
if(typeof text != 'string'){
console.error("show_received_document: invalid text or extension provided: ", text, extension);
return
}
if(text.indexOf('_') != -1 && text.indexOf('%20') == -1 && text.indexOf(' ') == -1){
text = text.replaceAll('_',' ');
}
received_document_textarea_el.value = text;
if(typeof suggested_filename != 'string' && typeof window.received_document_filename == 'string'){
//console.log("show_received_document: using window.received_document_filename: ", window.received_document_filename)
suggested_filename = window.received_document_filename;
}
if(typeof extension != 'string'){
if(typeof suggested_filename == 'string' && suggested_filename.indexOf('.') != -1){
extension = get_file_extension(suggested_filename);
}
else if(typeof window.received_document_extension == 'string' && window.received_document_extension.length){
extension = window.received_document_extension;
}
else{
extension = 'txt';
}
}
if(typeof extension != 'string' || extension == ''){
extension = 'txt';
}
console.log("received document extension: ", extension);
if(extension == "blueprint"){
received_document_dialog_el.classList.add('for-blueprint');
}
else{
received_document_dialog_el.classList.remove('for-blueprint');
}
// Suggest a filename
if(typeof suggested_filename != 'string' || (typeof suggested_filename == 'string' && suggested_filename == '')){
suggested_filename = '';
const d = new Date();
let date_string = d.toLocaleString([],{year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute:'2-digit'});
date_string = date_string.replaceAll('/','-');
date_string = date_string.replace(':','h');
if(extension == 'blueprint'){
suggested_filename = get_translation('Received_blueprint') + ' ' + date_string + '.blueprint';
}
else{
suggested_filename = get_translation('Received_document') + ' ' + date_string + '.' + extension;
}
}
received_document_filename_el.value = suggested_filename;
window.received_document = null;
window.received_document_filename = null;
window.received_document_extension = null;
document.getElementById('received-document-dialog').showModal();
}
if(
(typeof url_parameter_ai == 'string' && url_parameter_ai.length > 1)
|| (typeof url_parameter_file == 'string' && url_parameter_file.length > 5)
// && url_parameter_prompt != null
){
received_url_parameters = {};
//window.url_parameter_functionality = null; // don't do both a functionality and a new model at the same time // TODO: with the ability to download files this has become interesting
const keyCandidates = Array.from(window.url_parameters);
for(let kc = 0; kc < keyCandidates.length; kc++){
//console.log("keyCandidates: ", kc, keyCandidates[kc]);
if(Array.isArray(keyCandidates[kc]) && keyCandidates[kc].length == 2){
received_url_parameters[ keyCandidates[kc][0] ] = keyCandidates[kc][1];
if(typeof received_url_parameters[ keyCandidates[kc][0] ] == 'string' && received_url_parameters[ keyCandidates[kc][0] ].startsWith('http:/') && !received_url_parameters[ keyCandidates[kc][0] ].startsWith('http://')){
received_url_parameters[ keyCandidates[kc][0] ] = received_url_parameters[ keyCandidates[kc][0] ].replace('http:/','http://');
}
else if(typeof received_url_parameters[ keyCandidates[kc][0] ] == 'string' && received_url_parameters[ keyCandidates[kc][0] ].startsWith('https:/') && !received_url_parameters[ keyCandidates[kc][0] ].startsWith('https://')){
received_url_parameters[ keyCandidates[kc][0] ] = received_url_parameters[ keyCandidates[kc][0] ].replace('https:/','https://');
}
}
else{
console.error("unexpected shape of keyCandidates array: ", keyCandidates);
}
}
}
if( !(typeof url_parameter_ai == 'string' && url_parameter_ai.length > 1) ){
document.body.classList.add('no-received-ai');
}
/*
console.log("--> url_parameter_ai: ", url_parameter_ai);
console.log("--> window.received_prompt: ", window.received_prompt);
console.log("--> received_a_document: ", received_a_document);
console.log("--> window.received_document: ", window.received_document);
console.log("--> window.location.origin: ", window.location.origin);
console.log("--> window.location.pathname: ", window.location.pathname);
*/
if(
should_clean_url_bar
|| typeof url_parameter_ai == 'string'
|| typeof url_parameter_file == 'string'
|| typeof window.received_prompt == 'string'
|| typeof window.received_document == 'string'
|| received_a_document
){
clean_url_bar();
}
received_document_filename_el.addEventListener('input', () => {
update_share_document_url();
});
received_document_textarea_el.addEventListener('input', () => {
update_share_document_url();
});
share_document_also_share_ai_el.addEventListener('change', () => {
update_share_document_url();
});
function update_share_document_url(){
console.log("in update_share_document_url");
let share_link = '?document=' + encode_url_component(received_document_textarea_el.value.replaceAll(' ','_'));
if(received_document_filename_el.value.trim() != ''){
share_link = share_link + '&filename=' + encode_url_component(received_document_filename_el.value)
}
console.log("share_document_also_share_ai_el: ", share_document_also_share_ai_el);
console.log("share_document_also_share_ai_el.checked: ", share_document_also_share_ai_el.checked);
if(share_document_also_share_ai_el.checked === true){
console.log("also adding current AI");
share_link = create_share_prompt_link(false,null,'',share_link);
}
else{
let origin_part = window.location.origin + window.location.pathname.slice(0, window.location.pathname.lastIndexOf('/'));
if( (origin_part.length + share_link.length) > 2000){
share_link = get_translation('The_link_is_too_long_to_share') + ' (' + (origin_part.length + share_link.length) + '/2000)';
}
else{
share_link = origin_part + share_link;
}
}
share_document_link_text_el.textContent = share_link;
//let first_part = share_link.substr(0,share_link.indexOf('?'));
//share_link = share_link.replace(first_part,encode_url_component(first_part));
const fully_encoded_share_link = encode_url_component(share_link);
document.getElementById('twitter-share-document-link').href = 'https://x.com/intent/post?text=' + fully_encoded_share_link;
document.getElementById('facebook-share-document-link').href = 'http://www.facebook.com/sharer.php?u=' + fully_encoded_share_link;
document.getElementById('linkedin-share-document-link').href = 'https://www.linkedin.com/shareArticle?mini=true&url=' + fully_encoded_share_link;
document.getElementById('reddit-share-document-link').href = 'http://www.reddit.com/submit?url=' + fully_encoded_share_link + '&title=www.papeg.ai';
}
//window.cache_name = "llama-cpp-wasm-cache";
window.cache_name = "v1";
//window.cache_base_url = window.location.origin;
window.cache_base_url = location.protocol + '//' + location.host + location.pathname
//console.log("cache_base_url: ", cache_base_url);
window.scripts_to_add = { // a lookup table, not really used anymore
'musicgen': './musicgen_module.js',
'camera':'./camera_module.js',
'translation':'./translation_module.js',
'language_recognition':'./js/eld.M60.min.js'
}
window.web_gpu_supported = false; // only counts 16 bit as supported, which is the optimal variety when it comes to saving memory. TODO: does this put mac-users at a disadvantage?
window.web_gpu32_supported = false; // fallback if WebGPU is available, but 16bit is not
window.added_scripts = [];
window.chat_message_counter = 0;
//window.language = 'en';
window.microphone_enabled = false;
window.speaker_enabled = false;
window.current_audio_file_duration = null;
window.model_loaded = false;
window.last_loaded_model_url = null;
window.currently_loaded_assistant = null;
window.currently_loaded_llama_cpp_assistant = null;
window.currently_loaded_web_llm_assistant = null;
window.currently_loaded_ollama_assistant = null;
window.busy_loading_assistant = null
window.temperature = 0.7;
window.conversations = {};
window.developer_response_count = 0;
//window.tts_queue = []; // deprecated
window.audioCtx = null; // deprecated
window.transcribing = false;
window.used_memory = 0;
window.available_memory = 0;
window.docs = {};
window.coder = false; //whether a coding LLM is active
window.doc_text = '';
window.doc_length = 0;
window.doc_line_nr = null;
window.doc_current_line_nr = null; // TODO: duplicate
window.doc_selection = null;
window.doc_selected_text = null;
/*
let default_doc = {
'name':'unnamed',
'type':null,
'text':'',
'size':null,
'last_modified':0,
}
*/
window.speakers_manually_overridden = false;
window.should_add_demo_files = false; // becomes true on first ever run, when there are no settings in localstorage yet
// WEB LLM
window.should_restrict_models = false;
window.opencv_interval_delay = 500;
// These are probably not needed anymore
webLLMGlobal = {};
//window.prompts = ['what is the capital of Germany?'];
function check_if_mobile() {
var match = window.matchMedia || window.msMatchMedia;
if(match) {
var mq = match("(any-pointer:fine)");
//console.log("check_if_mobile: mq: ", mq);
if(!mq.matches && typeof localStorage != 'undefined' && typeof localStorage.mobile != 'undefined' && window.innerWidth < 1024){
return true
}
//return !mq.matches;
}
return false;
}
//window.is_mobile = localStorage.mobile; // || window.navigator.maxTouchPoints > 1;
//window.is_mobile = check_if_mobile();
window.is_mobile = false;
//if(typeof localStorage != 'undefined' && typeof localStorage.mobile != 'undefined' && window.innerWidth < 1024){
/*
if(window.innerWidth < 641){
window.is_mobile = true;
}
*/
if(localStorage.mobile || window.navigator.maxTouchPoints > 1){
//console.log("seems to be a mobile device. window.navigator.maxTouchPoints: ", window.navigator.maxTouchPoints);
window.is_mobile = true;
}
//console.log("check_if_mobile(): ", check_if_mobile());
//window.use_simple_vad = false;
// debug
window.use_simple_vad = true; // Switched to using it all the time, as it works better on mobile devices
//window.is_mobile = true;
console.log("is_mobile: ", window.is_mobile);
if(window.is_mobile == true){
document.body.classList.add('mobile');
window.use_simple_vad = true;
window.speakers_manually_overridden = true;
//window.settings.voice = 'basic';
window.opencv_interval_delay = 500;
if(typeof window.settings.assistants['danube'] == 'undefined'){
window.settings.assistants['danube'] = {};
}
window.settings.assistants['danube'].selected = true;
if(typeof window.settings.assistants['danube'] == 'undefined'){
window.settings.assistants['danube_3_500m'] = {};
}
window.settings.assistants['danube_3_500m'].selected = true;
}
/*
if(window.innerWidth < 641){
document.body.classList.add('mobile');
}
*/
window.is_firefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
if(window.is_firefox){
document.body.classList.add('is-firefox');
}
const iosDeviceMapping = new Map([
["320x480", "IPhone 4S, 4, 3GS, 3G, 1st gen"],
["320x568", "IPhone 5, SE 1st Gen,5C, 5S"],
["375x667", "IPhone SE 2nd Gen, 6, 6S, 7, 8"],
["375x812", "IPhone X, XS, 11 Pro, 12 Mini, 13 Mini"],
["390x844", "IPhone 13, 13 Pro, 12, 12 Pro"],
["414x736", "IPhone 8+"],
["414x896", "IPhone 11, XR, XS Max, 11 Pro Max"],
//["428x926", "IPhone 13 Pro Max, 12 Pro Max"],
["476x847", "IPhone 7+, 6+, 6S+"],
["744x1133", "IPad Mini 6th Gen"],
[
"768x1024",
"IPad Mini (5th Gen), IPad (1-6th Gen), iPad Pro (1st Gen 9.7), Ipad Mini (1-4), IPad Air(1-2) ",
],
["810x1080", "IPad 7-9th Gen"],
["820x1180", "iPad Air (4th gen)"],
["834x1194", "iPad Pro (3-5th Gen 11)"],
["834x1112", "iPad Air (3rd gen), iPad Pro (2nd gen 10.5)"],
//["1024x1366", "iPad Pro (1-5th Gen 12.9)"],
]);
const ios_screen_resolution = window.screen.width + 'x' + window.screen.height;
window.ios_device = null; // iosDeviceMapping.get(ios_screen_resolution);
window.old_ios_device = false;
window.is_ios = false;
if (/iP(hone|od|ad)/.test(navigator.platform)){
console.warn("Apple Device (iOS) detected");
window.is_ios = true;
document.body.classList.add('ios');
window.ios_device = iosDeviceMapping.get(ios_screen_resolution);
console.log("apple ios device model: ", ios_device);
if(window.ios_device){
window.old_ios_device = true;
document.body.classList.add('old-ios-device');
}
}
window.ios_device = iosDeviceMapping.get(ios_screen_resolution);
//console.error("window.ios_device failure is: ", window.ios_device );
// Maybe a little late? Could move this to early.js
async function check_gpu(){
//console.log("in check_gpu");
// CHECK WEB GPU SUPPORT
if (!navigator.gpu) {
console.error("WebGPU not supported.");
remove_body_class('web-gpu');
remove_body_class('web-gpu32');
}
else{
//console.log("navigator.gpu exists: ", navigator.gpu);
const adapter = await navigator.gpu.requestAdapter();
if (typeof adapter != 'undefined' && adapter != null && typeof adapter.features != 'undefined') {
if(adapter.features.has("shader-f16")){
//console.log(`Web GPU: 16 bit is available`);
window.web_gpu_supported = true;
add_body_class('web-gpu');
if (navigator.gpu.wgslLanguageFeatures && !navigator.gpu.wgslLanguageFeatures.has("packed_4x8_integer_dot_product")) {
//console.log(`webgpu DP4a built-in functions are not available`);
}
}
else{
console.warn("Web GPU: only 32-bit floating-point value support is available");
window.web_gpu32_supported = true;
remove_body_class('web-gpu');
add_body_class('web-gpu32');
add_web_gpu32_models();
}
}
else{
console.error("querying WebGPU failed, invalid adapter: ", adapter);
remove_body_class('web-gpu');
remove_body_class('web-gpu32');
}
}
}
check_gpu();
// Check if any cameras are available
window.camera_select_el = document.querySelector('select#video-sources-select');
window.has_camera = 0;
if(window.camera_select_el != null && typeof navigator.mediaDevices != 'undefined'){
navigator.mediaDevices.enumerateDevices()
.then(function (devices) {
//console.log("all media devices: ", devices);
for(var i = 0; i < devices.length; i ++){
var device = devices[i];
if (device.kind === 'videoinput') {
window.has_camera++;
document.body.classList.add('has-camera');
var option = document.createElement('option');
option.value = device.deviceId;
option.text = device.label || 'camera ' + (i + 1);
camera_select_el.appendChild(option);
}
}
if(window.has_camera < 2){
camera_select_el.style.display = 'none';
}
});
}
let scripts_busy_loading = [];
function add_script(path,module=false,load_async=null){
//console.log("in add_script. path,module,load_async: ", path,module,load_async);
return new Promise(function(resolve,reject) {
//console.log("add_script: inside promise");
if(typeof path == 'string' && path.length){
if(scripts_busy_loading.indexOf(path) != -1){
console.error("add_script: script was already handled: ",path);
resolve(false);
return false
}
if(typeof window.scripts_to_add[path] == 'string'){
//console.log("add_scripts: switching script name for script path: ", path, ' --> ',window.scripts_to_add[path]);
path = window.scripts_to_add[path];
}
if(window.added_scripts.indexOf(path) != -1){
//console.log("add_script: script was already in window.added_scripts: ", path);
resolve(true);
return true
}
else{
//console.log("add_script: script was not yet in window.added_scripts: ", path);
window.added_scripts.push(path);
}
var scripts = document.getElementsByTagName("script");
for (i=0; i<scripts.length; i++){
if(scripts[i].src == path){
//console.error("add_script: that script has already been added: ", path);
if(window.added_scripts.indexOf(path) == -1){
console.error("add_script: adding missing script path to list of scripts that have already been added: ", path);
window.added_scripts.push(path);
}
resolve(true);
return true
}
}
let new_script_el = document.createElement('script');
if(typeof load_async == 'boolean'){
new_script_el.async = load_async;
}
else{
new_script_el.async = false;
new_script_el.defer = false;
}
if(module){
new_script_el.type = 'module';
}
else{
new_script_el.type = 'text/javascript';
}
new_script_el.src = path;
new_script_el.addEventListener('load', function() {
//console.log("new script has loaded in: ", path);
/*
if(window.added_scripts.indexOf(path) == -1){
//console.log("new script has loaded in, adding path to window.added_scripts: ", path);
window.added_scripts.push(path);
}
else{
console.error("new script has loaded in, but it was already in window.added_scripts: ", path);
}
*/
//handle_script_loaded(path);
delay(1000)
.then(() => {
resolve(true);
})
//return true
});
document.body.appendChild(new_script_el);
}
else{
console.error("add_script: invalid path provided: ", path);
reject(false);
return false
}
});
}
window.add_script = add_script;
function is_script_added(script_name){
if(typeof script_name == 'string' && typeof window.scripts_to_add[script_name] != 'undefined'){
if(window.added_scripts.indexOf(window.scripts_to_add[script_name]) != -1){
//console.log("is_script_added: yes: ", script_name);
return true;
}
}
console.warn("is_script_added: no: ", script_name);
return false
}
function handle_script_loaded(path){
//console.log("in handle_script_loaded. path: ", path);
if(typeof path == 'string'){
if(window.added_scripts.indexOf(path) == -1){
window.added_scripts.push(path);
}
}
}
// Detect mobile phones
/*
const androidMaxStorageBufferBindingSize = 134217728; // 128MB
const mobileVendors = new Set([
"qualcomm",
"arm"
]);
let restrictModels = false;
let maxStorageBufferBindingSize;
let gpuVendor;
try {
[maxStorageBufferBindingSize, gpuVendor] = await Promise.all([
chat.getMaxStorageBufferBindingSize(),
chat.getGPUVendor()
]);
} catch (err) {
//chatUI.appendMessage("error", "Init error, " + err.toString());
console.log("Error detecting mobile phone GPU: ", err.stack);
return;
}
if (gpuVendor.length != 0 && mobileVendors.has(gpuVendor) || maxStorageBufferBindingSize <= androidMaxStorageBufferBindingSize) {
chatUI.appendMessage("init", "Your device seems to have limited resources, so we restrict the selectable models.");
restrictModels = true;
}
*/
function save_settings(){
//console.log("saving settings: ", JSON.stringify(window.settings,null,4));
//console.log("saving settings: ", window.settings);
localStorage.setItem("settings", JSON.stringify(window.settings));
if(window.generate_ui){
window.generate_ui();
}
let model_info_share_link_el = document.getElementById('model-info-share-clone-link-text');
if(model_info_share_link_el){
setTimeout(() => {
create_share_prompt_link(false,window.settings.assistant,''); // updates the share link if model info is open
},10);
}
}
window.save_settings = save_settings;
// load settings
let stored_settings = localStorage.getItem("settings");
if(stored_settings == null){
//console.log("no settings found in local storage");
window.should_add_demo_files = true; // TODO: no longer used
window.first_run = true;
if(typeof window.settings.assistants['image_to_text'] == 'undefined'){
window.settings.assistants['image_to_text'] = {}; // 'selected':true
}
/*
if(window.is_mobile){
window.settings.assistants['image_to_text']['huggingface_id'] = 'onnx-community/Florence-2-base-ft';
}
else{
window.settings.assistants['image_to_text']['huggingface_id'] = 'Xenova/moondream2';
}
*/
window.settings.assistants['image_to_text']['huggingface_id'] = 'Xenova/moondream2';
// Detect initial language
var browser_lang = navigator.language || navigator.userLanguage;
//console.log("browser_lang: ", browser_lang);
browser_lang = browser_lang.toLowerCase();
if(browser_lang.toLowerCase() == 'nl' || browser_lang.startsWith('nl-')){
//console.log("switching language to Dutch");
//window.language = 'nl';
window.settings.language = 'nl';
if(window.settings.input_language == 'en' && window.settings.output_language == null){
window.settings.output_language = 'nl';
}
window.settings.assistants['fietje3'] = {'selected':true};
save_settings();
}
else if(browser_lang.toLowerCase() == 'de' || browser_lang.startsWith('de-')){
//console.log("switching language to German");
//window.language = 'nl';
window.settings.language = 'de';
if(window.settings.input_language == 'en' && window.settings.output_language == null){
window.settings.output_language = 'de';
}
window.settings.assistants['german_gemma_2b'] = {'selected':true};
save_settings();
}
else if(browser_lang.toLowerCase() == 'fr' || browser_lang.startsWith('fr-')){
//console.log("switching language to French");
//window.language = 'nl';
window.settings.language = 'fr';
if(window.settings.input_language == 'en' && window.settings.output_language == null){
window.settings.output_language = 'fr';
}
window.settings.assistants['phi3_mini_french'] = {'selected':true};
save_settings();
}
else if(browser_lang.toLowerCase() == 'es' || browser_lang.startsWith('es-')){
//console.log("switching language to Spanish");
//window.language = 'nl';
window.settings.language = 'es';
if(window.settings.input_language == 'en' && window.settings.output_language == null){
window.settings.output_language = 'es';
}
window.settings.assistants['phi3_mini_spanish'] = {'selected':true};
save_settings();
}
else if(browser_lang.toLowerCase() == 'pt' || browser_lang.startsWith('pt-')){
//console.log("switching language to Portugese");
//window.language = 'nl';
window.settings.language = 'pt';
if(window.settings.input_language == 'en' && window.settings.output_language == null){
window.settings.output_language = 'pt';
}
window.settings.assistants['phi3_mini_portugese'] = {'selected':true};
save_settings();
}