-
Notifications
You must be signed in to change notification settings - Fork 1
/
gui.js
9095 lines (7215 loc) · 245 KB
/
gui.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
"use strict";
function set_loss_and_metric (loss, metric) {
if(!metric) {
metric = loss;
if(metric == "binaryCrossentropy") {
metric = "categoricalCrossentropy";
}
}
set_loss(loss);
set_metric(metric);
}
async function set_labels (arr, force_allow_empty=0) {
if(!arr) {
err(language[lang]["arr_is_undefined_or_false"]);
return;
}
if(!Array.isArray(arr)) {
err(language[lang]["arr_is_not_an_array"]);
return;
}
if(arr.length == 0 && !force_allow_empty) {
err(language[lang]["arr_is_an_array_but_empty"]);
return;
}
if(get_shape_from_array(arr).length != 1 && !force_allow_empty) {
err(language[lang]["arr_is_an_array_but_multidimensional_it_needs_to_be_one_dimensional"]);
return;
}
if(!model) {
if(finished_loading) {
wrn(language[lang]["model_is_not_defined"]);
} else {
dbg(language[lang]["model_is_not_defined"]);
}
return;
}
if(!Object.keys(model).includes("layers") || !model.layers.length) {
err(language[lang]["model_layers_is_not_defined_or_empty"]);
return;
}
for (var i = 0; i < arr.length; i++) {
if(typeof(arr[i]) != "string") {
err(`typeof(arr[${i}]) is not a string but ${typeof(arr[i])}. Cannot continue. All values must be strings.`);
return;
}
}
var old_array_string = JSON.stringify(labels);
var new_array_string = JSON.stringify(arr);
if(old_array_string != new_array_string) {
labels = arr;
dbg(`${language[lang]["set_labels"]} = [${arr.join(", ")}]`);
} else {
dbg(language[lang]["not_changing_labels_they_stayed_the_same"]);
return;
}
var last_layer_nr = model.layers.length - 1;
var last_layer = model.layers[last_layer_nr];
var last_layer_type = last_layer.getClassName();
var mos = last_layer.getOutputAt(0).shape;
var last_layer_activation = last_layer.getConfig()["activation"];
if(mos[0] === null && mos.length == 2 && last_layer_activation == "softmax" && last_layer_type == "Dense") {
var model_number_output_categories = mos[1];
var new_number_output_neurons = arr.length;
if(new_number_output_neurons && model_number_output_categories != new_number_output_neurons && !is_setting_config) {
void(0); dbg(`set_item_value(${last_layer_nr}, "units", ${new_number_output_neurons})`);
set_item_value(last_layer_nr, "units", new_number_output_neurons);
await repredict();
} else {
var msg = "";
if(!new_number_output_neurons) {
msg += language[lang]["new_number_of_output_neurons_is_zero_or_undefined"] + ". ";
}
if(is_setting_config) {
msg += language[lang]["do_not_change_neurons_while_is_setting_config_is_true"] + ". ";
}
if(model_number_output_categories == new_number_output_neurons) {
msg += language[lang]["new_number_of_output_neurons_matches_the_number_already_in_the_model"] + ". ";
}
dbg(msg);
//console.trace();
}
} else {
var msg = "";
if(mos[0] !== null) {
msg += language[lang]["batch_dimension_in_output_shape_must_be_null"] + ". ";
}
if(mos.length != 2) {
msg += language[lang]["output_shape_length_must_be_two"] + ". ";
}
if(last_layer_activation != "softmax") {
msg += language[lang]["last_layer_must_have_softmax_to_autoset_layers"] + ". ";
}
if (last_layer_type != "Dense") {
msg += language[lang]["last_layer_must_be_of_type_dense"] + ". ";
}
dbg(language[lang]["cannot_autoset_layer_errors"] + " " + msg);
return;
}
}
async function load_labels_from_json_string (json) {
var struct;
try {
struct = JSON.parse(json);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
if(("" + e).includes("SyntaxError")) {
err(language[lang]["the_uploaded_labels_json_isnt_valid"]);
return;
} else {
throw new Error(e);
}
}
await set_labels(struct);
}
function download_labels_json () {
download("labels.json", JSON.stringify(labels));
}
async function reset_labels () {
await set_labels([], 1);
}
function enable_train () {
$(".train_neural_network_button").prop("disabled", false);
}
function disable_train () {
$(".train_neural_network_button").prop("disabled", true);
}
function get_key_from_path(_array, keypath) {
if (keypath.length == 0) {
return _array;
}
var this_key = undefined;
var tmp = _array;
for (var i = 0; i < keypath.length; i++) {
this_key = keypath[i];
tmp = tmp[this_key];
if(!tmp) {
return null;
}
}
return tmp;
}
function get_full_shape_without_batch(file) {
typeassert(file, string, "file");
if (file === null) {
return null;
}
var input_shape_line = file.split("\n")[0];
var shape_match = /^#\s*shape\s*:?\s*\((.*)\)$/.exec(input_shape_line);
assert(shape_match !== null, "shape_match is null");
//shape_match[0] = null;
var res = eval("[" + shape_match[1] + "]");
res[0] = null;
return res;
}
function get_shape_from_file(file) {
typeassert(file, string, "file");
if (file === null) {
return null;
}
var input_shape_line = file.split("\n")[0];
var shape_match = /^#\s*shape\s*:?\s*\(\d+,?\s*(.*)\)$/.exec(input_shape_line);
assert(shape_match !== null, "shape_match is null");
if (1 in shape_match) {
return shape_match[1];
}
return null;
}
function get_dimensionality_from_layer_name(layer_type) {
typeassert(layer_type, string, "layer_type");
var match = layer_type.match(/(\d+)[dD]/);
assert(match !== null, "match is null");
if (match) {
return parse_int(match[1]);
}
return null;
}
async function md5 (content) {
try {
var res = await hashwasm.md5(content);
return res;
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
err("[md5] " + e);
}
}
async function get_current_layer_container_status_hash() {
var html = $("#layers_container").html();
html = html.replaceAll(" disabled=\"\"", "");
var res = await md5(html);
return res;
}
async function get_current_status_hash(use_weights=1) {
var html_code = "";
var allitems = [];
allitems = Array.prototype.concat.apply(allitems, document.getElementsByTagName("input"));
allitems = Array.prototype.concat.apply(allitems, document.getElementsByTagName("checkbox"));
allitems = Array.prototype.concat.apply(allitems, document.getElementsByTagName("select"));
allitems = Array.prototype.concat.apply(allitems, document.getElementsByTagName("textarea"));
allitems.forEach(function (x) {
var item = $(x);
html_code += ";;;;;;;" + x.id + ";;;;" + x.className + "=" + x.value + ";;;;" + x.checked;
});
if(use_weights) {
html_code += get_weights_as_string();
}
var new_status_hash = await md5(html_code);
last_status_hash = new_status_hash;
return new_status_hash;
}
/* This function returns the value of an item in a given layer, specified by classname. If the item is a checkbox, it returns whether or not the box is checked. Otherwise, it returns the value of the item. */
function get_item_value(layer, classname) {
assert(typeof(layer) == "number", "Layer is not an integer, but " + typeof(layer));
assert(typeof(classname) == "string", "classname '" + classname + "' is not a string, but " + typeof(classname));
var layer_settings = $(".layer_setting");
var $layer = $(layer_settings[layer]);
if (typeof(classname) == "string") {
var found = $($layer.find("." + classname)[0]);
if (found.attr("type") == "checkbox") {
return found.is(":checked");
} else {
var data = found.val();
return data;
}
} else {
for (var this_classname in classname) {
var found = $($layer.find("." + this_classname)[0]);
if (found.attr("type") == "checkbox") {
return found.is(":checked");
} else {
var data = found.val();
if (data) {
return data;
}
}
}
return null;
}
}
function set_item_value(layer, classname, value) {
if (classname == "name") {
return;
}
assert(typeof(layer) == "number", "Layer is not an integer, but " + typeof(layer));
assert(typeof(classname) == "string", "classname '" + classname + "' is not a string, but " + typeof(classname));
assert(["string", "number", "boolean"].includes(typeof(value)), "value '" + value + "' for " + classname + " is not a string or number, but " + typeof(value));
var layer_settings = $(".layer_setting");
if(layer >= layer_settings.length) {
wrn(`[set_item_value] Layer ${layer} was too high. Max number is ${layer_settings.length - 1}`);
return;
}
var layer_setting = layer_settings[layer];
var found_setting = $($(layer_setting).find("." + classname)[0]);
if (found_setting.length) {
if (found_setting.attr("type") == "checkbox") {
found_setting.prop("checked", value == 1 ? true : false).trigger("change");
} else {
found_setting.val(value).trigger("change");
}
} else {
if(classname == "rate") {
set_item_value(layer, "dropout_rate", value);
} else if(classname != "trainable") {
err("Unknown classname '" + classname + "' in layer " + layer);
}
}
}
function get_tr_str_for_description(desc) {
assert(typeof(desc) == "string", desc + " is not string but " + typeof(desc));
return "<tr><td><span class='TRANSLATEME_description'></span>:</td><td><span class='typeset_me'>" + desc + "</span></td></tr>";
}
function is_numeric(str) {
if (typeof str != "string") return false;
if (str == "") return false;
return !isNaN(str) && !isNaN(parse_float(str));
}
function quote_python(item, nobrackets=0) {
if (item === undefined) {
return "";
}
if (typeof(item) == "object") {
return JSON.stringify(item);
} else {
if (is_numeric(item)) {
return item;
} else if (!nobrackets && /^\d+(,\d+)*$/.test(item)) {
return "[" + item + "]";
} else if (item == "True" || item == "False") {
return item;
} else if (!nobrackets && item.includes("get_shape")) {
return item;
} else if (!nobrackets && item.startsWith("[")) {
return item;
} else {
return "\"" + item + "\"";
}
}
return item;
}
function get_js_name(_name) {
if(typeof(_name) == "boolean") {
if(_name) {
return "true";
}
return "false";
}
if(Array.isArray(_name)) {
return _name;
}
if (_name in python_names_to_js_names) {
return python_names_to_js_names[_name];
}
return _name;
}
function get_python_name(_name) {
if(typeof(_name) == "boolean") {
if(_name) {
return "True";
}
return "False";
}
if(Array.isArray(_name)) {
return _name;
}
if (_name in js_names_to_python_names) {
return js_names_to_python_names[_name];
}
return _name;
}
function get_tr_str_for_layer_table(desc, classname, type, data, nr, tr_class, hidden, expert_mode_only = 0) {
assert(typeof(classname) == "string", "classname is not a string");
assert(typeof(data) == "object", "data is not an object");
assert(typeof(nr) == "number", "nr is not a number");
assert(typeof(tr_class) == "string" ||tr_class === undefined || tr_class === null, "tr_class is not a string");
assert(expert_mode_only === 0 || expert_mode_only === 1, "expert_mode_only for get_tr_str_for_layer_table must be either 0 or 1, but is " + expert_mode_only);
var new_uuid = uuidv4();
var str = "<tr";
if(expert_mode_only) {
if(tr_class) {
tr_class = tr_class + " expert_mode_only";
} else {
tr_class = "expert_mode_only";
}
}
if (tr_class) {
str += " class='" + tr_class + "'";
}
if (hidden) {
str += " style='display: none' ";
}
str += ">";
var help = "";
str += "<td>" + desc + help + ":</td>";
str += "<td>";
if (type == "select") {
var onchange_text = "updated_page(null, null, this);";
var types_init_or_reg = ["initializer", "regularizer"];
for (var tk = 0; tk < valid_initializer_types.length; tk++) {
for (var tir = 0; tir < types_init_or_reg.length; tir++) {
var new_name = valid_initializer_types[tk] + "_" + types_init_or_reg[tir];
if (classname == new_name) {
var _get_layer_str = "find_layer_number_by_element($(this))";
var _init_type = `"${valid_initializer_types[tk]}"`;
var _updated_page_str = "updated_page(null, null, this)";
var _func_name = `insert_${types_init_or_reg[tir]}_options`;
onchange_text = `${_func_name}(${_get_layer_str}, ${_init_type});${_updated_page_str}`;
}
}
}
if (classname == "activation") {
//onchange_text = "insert_activation_options(find_layer_number_by_element($(this)));updated_page(null, null, this)";
}
str += `<select id="select_${new_uuid}" class='input_field input_data ${classname}' _onchange='${onchange_text}'>`;
for (var [key, value] of Object.entries(data)) {
str += "<option value=\"" + key + "\">" + value + "</option>";
}
str += "</select>";
} else if (type == "text") {
var placeholder = "";
if ("placeholder" in data) {
placeholder = " placeholder='" + data["placeholder"] + "' ";
}
var pre_text = "";
if ("text" in data) {
var text = data["text"];
if (typeof(data["text"]) == "function") {
text = data["text"](nr);
}
pre_text = " value='" + text + "' ";
}
str += `<input id="text_field_${uuidv4()}" class="input_field input_data ${classname}" ${pre_text} ${placeholder} type="text" _onchange="updated_page()" onkeyup="updated_page(null, null, this)" />`;
} else if (type == "number") {
str += "<input class='input_field input_data " + classname + "' type='number' ";
if ("min" in data) {
str += " min=" + data["min"] + " ";
}
if ("max" in data) {
str += " max=" + data["max"] + " ";
}
if ("step" in data) {
str += " step=" + data["step"] + " ";
}
if ("value" in data) {
str += " value=" + data["value"] + " ";
}
if(classname.includes("_initializer_") && (classname.includes("kernel") || classname.includes("bias"))) {
//updated_page(no_graph_restart, disable_auto_enable_valid_layer_types, item, no_prediction, no_update_initializers) {
str += `id='get_tr_str_for_layer_table_${new_uuid}' onchange='updated_page(null, null, null, null, 1)' onkeyup="var original_no_update_math=no_update_math; no_update_math = is_hidden_or_has_hidden_parent('#math_tab_code') ? 1 : 0; is_hidden_or_has_hidden_parent('#math_tab_code'); updated_page(null, null, this, null, 1); no_update_math=original_no_update_math;" />`;
} else {
str += `id='get_tr_str_for_layer_table_${new_uuid}' _onchange='updated_page()' onkeyup="var original_no_update_math=no_update_math; no_update_math = is_hidden_or_has_hidden_parent('#math_tab_code') ? 1 : 0; is_hidden_or_has_hidden_parent('#math_tab_code'); updated_page(null, null, this); no_update_math=original_no_update_math;" />`;
}
var original_no_update_math = no_update_math;
} else if (type == "checkbox") {
var on_change_string = "updated_page(null, null, this);";
str += `<input id='checkbox_${new_uuid}' type='checkbox' class='input_data ${classname}' `;
if ("status" in data && data["status"] == "checked") {
str += " checked='CHECKED' ";
}
if(classname == "use_bias") {
on_change_string += "change_bias_selection(this);";
}
str += `_onchange='${on_change_string}' />`;
} else {
alert("Invalid table type: " + type);
}
str += "</td>";
return str;
}
function change_bias_selection (elem) {
if(!$(elem).is(":checked")) {
$(elem).parent().parent().parent().find(".bias_initializer_tr").remove();
}
}
function add_cell_option() {
return "";
}
function add_number_lstm_cells_option(type, nr) {
var res = get_tr_str_for_layer_table("LSTM Cells", "number_lstm_cells", "number", { "min": 0, "step": 1, "value": 1 }, nr);
return res;
}
function add_seed_option (type, nr) {
var style = "";
var current_input_shape = get_input_shape();
if (current_input_shape.length != 3) {
style = " style=\"display: none\" ";
}
var res = "<tr class='seed_value' " + style + "><td>Seed</td><td><input onchange='updated_page()' type='number' name='seed' class='seed dropout_seed' value='1' /></td></tr>";
return res;
}
function add_visualize_option(type, nr) {
assert(typeof(type) == "string", "type is not a number");
assert(typeof(nr) == "number", "nr is not a number");
var style = "";
var res = "<tr class='visualize_button' " + style + "><td><span class='TRANSLATEME_visualize_this_layer'></span>?</td><td><button class='visualize_layer_button' onclick='draw_maximally_activated_layer(find_layer_number_by_element(this), \"" + type + "\")'><span class='TRANSLATEME_visualize_layer'></span></button></td></tr>";
return res;
}
function add_pool_size_option(type, nr) {
assert(typeof(type) == "string", "type is not a number");
assert(typeof(nr) == "number", "nr is not a number");
var str = "";
var dimensionality = get_dimensionality_from_layer_name(type);
assert(typeof(dimensionality) == "number", `get_dimensionality_from_layer_name does not return a number for type '${type}'`);
var letter_code = "x".charCodeAt();
for (var i = 0; i < dimensionality; i++) {
var letter = String.fromCharCode(letter_code);
str += get_tr_str_for_layer_table("Pool-Size " + letter, "pool_size_" + letter, "number", { "min": 1, "max": 4096, "step": 1, "value": get_default_option(type, "pool_size")[i] }, nr);
letter_code++;
}
return str;
}
function add_kernel_size_option(type, nr) {
var str = "";
var dimensionality = get_dimensionality_from_layer_name(type);
assert(typeof(dimensionality) == "number", `get_dimensionality_from_layer_name does not return a number for type '${type}'`);
var letter_code = "x".charCodeAt();
for (var i = 0; i < dimensionality; i++) {
var letter = String.fromCharCode(letter_code);
str += get_tr_str_for_layer_table(
"<span class='TRANSLATEME_kernel_size'></span> " + letter,
"kernel_size_" + letter, "number",
{ "min": 1, "max": 4096, "step": 1, "value": get_default_option(type, "kernel_size")[i] },
nr
);
letter_code++;
}
return str;
}
function add_strides_option(type, nr) {
var str = "";
var dimensionality = get_dimensionality_from_layer_name(type);
assert(typeof(dimensionality) == "number", `get_dimensionality_from_layer_name does not return a number for type '${type}'`);
var letter_code = "x".charCodeAt();
for (var i = 0; i < dimensionality; i++) {
var letter = String.fromCharCode(letter_code);
str += get_tr_str_for_layer_table("Strides " + letter, "strides_" + letter, "number", { "min": 1, "max": 4096, "step": 1, "value": get_default_option(type, "strides")[i] }, nr);
letter_code++;
}
return str;
}
/* activation gui functions end */
function insert_activation_option_trs(layer_nr, option_type) {
assert(["alpha", "max_value", "axis", "theta", "alpha_initializer", "alpha_regularizer", "alpha_constraint", "shared_axes"].includes(option_type), "invalid option type " + option_type);
assert(typeof(layer_nr) == "number", "Layer number's type must be number, is: " + typeof(layer_nr));
if (option_type != "none") {
var eval_string = `$(add_activation_${option_type}_option($($(".layer_type")[${layer_nr}]).val(), ${layer_nr})).insertAfter($($(".activation")[${layer_nr}]).parent().parent());`;
eval(eval_string);
} else {
log("[insert_activation_option] option_type is '" + option_type + "'");
}
}
function insert_regularizer_option_trs(layer_nr, regularizer_type, option_type) {
assert(valid_initializer_types.includes(regularizer_type), "insert_regularizer_option_trs(layer_nr, " + regularizer_type + ") is not a valid regularizer_type (2nd option)");
assert(["l1", "l1l2", "l2", "none"].includes(option_type), "invalid option type " + option_type);
assert(typeof(layer_nr) == "number", "Layer number's type must be number, is: " + typeof(layer_nr));
if (option_type != "none") {
var eval_string = `$(add_${regularizer_type}_regularizer_${option_type}_option($($(".layer_type")[${layer_nr}]).val(), ${layer_nr})).insertAfter($($(".layer_setting")[${layer_nr}]).find(".${regularizer_type}_regularizer").parent().parent())`;
eval(eval_string);
} else {
log("[insert_regularizer_option_trs] option_type is '" + option_type + "'");
}
}
function insert_initializer_option_trs(layer_nr, initializer_type, option_type) {
assert(valid_initializer_types.includes(initializer_type), "insert_initializer_option_trs(layer_nr, " + initializer_type + ") is not a valid initializer_type (2nd option)");
assert(["seed", "mean", "stddev", "value", "mode", "distribution", "minval", "maxval", "scale", ...valid_initializer_types].includes(option_type), "invalid option type " + option_type);
assert(typeof(layer_nr) == "number", "Layer number's type must be number, is: " + typeof(layer_nr));
var function_name = `add_${initializer_type}_initializer_${option_type}_option`;
var eval_string = `$(${function_name}($($(".layer_type")[${layer_nr}]).val(), ${layer_nr})).
insertAfter($($(".layer_setting")[${layer_nr}]).
find(".${initializer_type}_initializer").
parent().
parent()
)
`;
//console.log(eval_string);
eval(eval_string);
}
async function insert_activation_options(layer_nr) {
// TODO NOT YET USED
assert(typeof(layer_nr) == "number", "layer_nr must be of the type of number but is: " + typeof(layer_nr));
assert(layer_nr >= 0 && layer_nr <= get_number_of_layers(), "Invalid layer number");
$($(".layer_options_internal")[layer_nr]).find(".activation_tr").remove();
var activation_item = $($(".layer_options_internal")[layer_nr]).find(".activation");
if (activation_item && activation_item.length) {
var activation_name = activation_item.val();
if (activation_name == "linear") {
return;
}
if (Object.keys(activation_options).includes(activation_name)) {
var options = activation_options[activation_name]["options"];
for (var i = 0; i < options.length; i++) {
insert_activation_option_trs(layer_nr, options[i]);
}
}
} else {
if(get_layer_type_array()[layer_nr] != "flatten") {
log("[insert_activation_options] Layer " + layer_nr + " does not seem to have a activation setting");
}
}
await updated_page();
}
function set_last_layer_activation_function (activation_function) {
assert(Object.keys(activations).includes(activation_function), "activation function " + activation_function + " is invalid. Must be one of these: " + Object.keys(activations).join(", "));
var last_layer_nr = $(".layer_type").length - 1;
var activation_item = $($(".layer_options_internal")[last_layer_nr]).find(".activation");
if(activation_item.val() != activation_function) {
activation_item.val(activation_function).trigger("change");
}
}
async function insert_regularizer_options(layer_nr, regularizer_type) {
assert(valid_initializer_types.includes(regularizer_type), "insert_regularizer_trs(layer_nr, " + regularizer_type + ") is not a valid regularizer_type (2nd option)");
assert(typeof(layer_nr) == "number", "layer_nr must be of the type of number but is: " + typeof(layer_nr));
var max_layer = get_number_of_layers();
if(!(layer_nr >= 0 && layer_nr <= max_layer)) {
dbg(sprintf(language[lang]["invalid_layer_nr_max_layer_n_layer_nr_m"], max_layer, layer_nr));
return;
}
$($(".layer_options_internal")[layer_nr]).find("." + regularizer_type + "_regularizer_tr").remove();
var regularizer = $($(".layer_options_internal")[layer_nr]).find("." + regularizer_type + "_regularizer");
if (regularizer.length) {
var regularizer_name = regularizer.val();
var options = regularizer_options[regularizer_name]["options"];
for (var i = 0; i < options.length; i++) {
insert_regularizer_option_trs(layer_nr, regularizer_type, options[i]);
}
} else {
if(get_layer_type_array()[layer_nr] != "flatten") {
log("[insert_regularizer_options] Layer " + layer_nr + " does not seem to have a " + regularizer_type + " regularizer setting");
}
}
await updated_page();
}
function findInitializerElement(arr) {
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === "string" && arr[i].includes("_initializer_")) {
return arr[i];
}
}
return null; // Return null if no matching element is found
}
async function insert_initializer_options (layer_nr, initializer_type) {
assert(valid_initializer_types.includes(initializer_type), "insert_initializer_trs(layer_nr, " + initializer_type + ") is not a valid initializer_type (2nd option)");
assert(typeof(layer_nr) == "number", "layer_nr must be of the type of number but is: " + typeof(layer_nr));
var max_layer = get_number_of_layers();
if(!(layer_nr >= 0 && layer_nr <= max_layer)) {
dbg(sprintf(language[lang]["invalid_layer_nr_max_layer_n_layer_nr_m"], max_layer, layer_nr));
return;
}
var existing_init_elements = $($(".layer_options_internal")[layer_nr]).find("." + initializer_type + "_initializer_tr");
var initializer = $($(".layer_options_internal")[layer_nr]).find("." + initializer_type + "_initializer");
var initializer_name = initializer.val();
if(existing_init_elements.length) {
var number_of_removed_items = 0;
var options = initializer_options[initializer_name]["options"];
var prev_classes = [];
for (var i = 0; i < existing_init_elements.length; i++) {
var remove = true;
var found_element = $(existing_init_elements[i]);
if(found_element.length) {
var found_input_element = $(found_element[0]).find("input");
if(found_input_element.length) {
var class_list = found_input_element[0].classList;
var this_initializer_class_type = findInitializerElement(class_list);
var this_initializer_type = this_initializer_class_type.replace(/.*_initializer_/, "");
if(options.includes(this_initializer_type) && prev_classes.includes(this_initializer_type)) {
remove = false;
} else {
prev_classes.push(this_initializer_type);
}
}
}
if(remove) {
$(existing_init_elements[i]).remove();
number_of_removed_items++;
}
}
if(number_of_removed_items == 0) {
return;
}
}
if(initializer_name) {
var options = initializer_options[initializer_name]["options"];
for (var i = 0; i < options.length; i++) {
insert_initializer_option_trs(layer_nr, initializer_type, options[i]);
}
}
}
async function get_json(url) {
try {
var data = await $.getJSON(url);
return data;
} catch (e) {
assert(false, `${url}: ${e.statusText}`);
}
}
async function get_cached_json(url) {
if (Object.keys(_cached_json).includes(url)) {
return _cached_json[url];
}
try {
var worked = 1;
var data = await $.getJSON(url).fail(function() {
worked = 0;
log_once("Could not get " + url);
});
if(worked) {
_cached_json[url] = data;
}
return data;
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
if(Object.keys(e).includes("statusText")) {
e = e.statusText;
}
log_once("Probably harmless error getting url: " + url + ": " + e);
}
}
/* This function gets the configuration for the index passed in. If no index is passed in, it gets the configuration for the currently selected dataset. */
async function _get_configuration(index) {
assert(["string", "undefined"].includes(typeof(index)), "Index must be either string or undefined, but is " + typeof(index) + " (" + index + ")");
var data = undefined;
if (index) {
if (Object.keys(status_saves).includes(index)) {
data = {};
data["model_structure"] = status_saves[index]["model_structure"];
data["weights"] = status_saves[index]["weights"];
} else {
log("[_get_configuration] Index " + index + " could not be found");
}
}
if (typeof(data) == "undefined") {
try {
while ($("#dataset").val() === null) {
await delay(50);
}
var data_url, keras_url;
var filename = traindata_struct[$("#dataset option:selected").text()]["filename"];
if(filename.startsWith("get_")) {
data_url = traindata_struct[$("#dataset option:selected").text()]["data"];
keras_url = filename;
} else {
data_url = "traindata/" + $("#dataset").val() + ".json";
keras_url = "traindata/" + $("#dataset").val() + "_keras.json";
}
data = await get_cached_json(data_url);
if (uploaded_model == "") {
var new_data = await get_cached_json(keras_url);
if(new_data) {
data["keras"] = new_data;
}
} else {
data["keras"] = JSON.parse(uploaded_model);
uploaded_model = "";
}
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
err(e);
return null;
}
}
return data;
}
function copy_to_clipboard(text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
function copy_id_to_clipboard(idname) {
var serialized = $("#" + idname).text();
copy_to_clipboard(serialized);
}
function enable_disable_grad_cam() {
if ($("#show_grad_cam").is(":checked")) {
$("#grad_cam_heatmap").show();
} else {
$("#grad_cam_heatmap").hide();
}
if($("#show_layer_data").is(":checked")) {
wrn("[enable_disable_grad_cam] You can either use grad CAM or the internal layer states, but not both. Disabling internal layer states.");
$("#show_layer_data").prop("checked", false).trigger("change");
}
hide_empty_tabs("visualization_ribbon");
}
function enable_disable_kernel_images() {
if ($("#show_layer_data").is(":checked")) {
$("#show_kernel_images").prop("disabled", false);
$("#data_plotter").show();
$("#layer_visualizations_tab").show();
} else {
$("#show_kernel_images").prop("disabled", true);
$("#data_plotter").hide();
$("#layer_visualizations_tab").hide();
}
if($("#show_grad_cam").is(":checked")) {
wrn("[enable_disable_kernel_images] You can either use grad CAM or the internal layer states, but not both. GradCAM.");
$("#show_grad_cam").prop("checked", false).trigger("change");
}
$("#grad_cam_heatmap").hide();
hide_empty_tabs("visualization_ribbon");
}
function change_kernel_pixel_size() {
kernel_pixel_size = parse_int($("#kernel_pixel_size").val());
}
function change_pixel_size() {
pixel_size = parse_int($("#pixel_size").val());
}
async function change_height() {
await change_width_or_height("height", 0);
}