-
Notifications
You must be signed in to change notification settings - Fork 287
/
model.js
1585 lines (1406 loc) · 50.8 KB
/
model.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 PDR = OpenSeadragon.pixelDensityRatio;
const IDB_URL = 'indexeddb://';
var csvContent;
var mem;
var flag = -1;
var choices1;
var jsondata;
var fileName = '';
// INITIALIZE DB
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// id(autoinc), name, location(name+id), classes
var request; var db;
var modelName;
// tensorflowjs creates its own IndexedDB on saving a model.
(async function(callback) {
const model = tf.sequential();
await model.save('indexeddb://dummy');
await tf.io.removeModel('indexeddb://dummy');
console.log('DB initialised');
callback();
})(dbInit);
// Opening the db created by tensorflowjs
function dbInit() {
request = window.indexedDB.open('tensorflowjs', 1);
request.onupgradeneeded = function(e) {
console.log('nasty!');
};
request.onerror = function(e) {
console.log('ERROR', e);
};
request.onsuccess = function(e) {
db = request.result;
console.log('tfjs db opened and ready');
};
}
let $CAMIC = null;
const $UI = {};
const $D = {
pages: {
home: '../table.html',
table: '../table.html',
},
params: null,
};
// const objAreaMin = 400;
// const objAreaMax = 4500;
// const lineWidth = 2;
// const timeOutMs = 10;
/**
* Sanitize the input
*
* @param string
*/
function sanitize(string) {
string = string || '';
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
'\'': ''',
'/': '/',
};
const reg = /[&<>"'/]/ig;
return string.toString().replace(reg, (match)=>(map[match]));
}
function initialize() {
var checkPackageIsReady = setInterval(function() {
if (IsPackageLoading) {
clearInterval(checkPackageIsReady);
initUIcomponents();
initCore();
}
}, 100);
}
async function initUIcomponents() {
/* create UI components */
// Create uploadModal for model uploads.
$UI.uploadModal = new ModalBox({
id: 'upload_panel',
hasHeader: true,
headerText: 'Upload Model',
hasFooter: false,
provideContent: true,
content: `
<form action="#" class='form-style'>
<ul>
<li>
<label align="left"> Name: </label>
<input name="name" id="name" type="text" required />
<span> Name of the model </span>
</li>
<li>
<label align="left"> Classes: </label>
<input name="classes" id="classes" type="text" required />
<span> Enter the classes model classifies into separated by comma. </span>
</li>
<li>
<label align="left"> Input patch size: </label>
<input name="imageSize" id="imageSize" type="number" required />
<span> The image size on which the model is trained </span>
</li>
<label>Input image format:</label> <br>
<input type="radio" id="gray" name="channels" value=1 checked>
<label for="gray">Gray</label> <br>
<input type="radio" id="rgb" name="channels" value=3>
<label for="rgb" padding="10px">RGB</label>
<li id="mg">
<label for="magnification">Magnification:</label>
<select id="magnification">
<option value=10>10x</option>
<option value=20>20x</option>
<option value=40>40x</option>
</select>
<span> Magnification of input images </span>
</li>
<hr>
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider"></div></label> <br> <br>
<div class="checkfalse"><div>Select model.json first followed by the weight binaries.</div> <br>
<input name="filesupload" id="modelupload" type="file" required/>
<input name="filesupload" id="weightsupload" type="file" multiple="" required/> <br> <br> </div>
<div class="checktrue" > URL to the ModelAndWeightsConfig JSON describing the model. <br> <br>
<label align-"left"> Enter the URL: </label> <input type="url" name="url" id="url" required> <br><br></div>
<button id="submit">Upload</button> <span id="status"></span> <br>
</form>
<button id="refresh" class='material-icons'>cached</button>
`,
});
// Create infoModal to show information about models uploaded.
$UI.infoModal = new ModalBox({
id: 'model_info',
hasHeader: true,
headerText: 'Available Models',
hasFooter: false,
provideContent: true,
content: `
<table id='mtable'>
<thead>
<tr>
<th>Name</th>
<th>Classes</th>
<th>Input Size</th>
<th>Size (MB)</th>
<th>Date Saved</th>
<th>Remove Model</th>
<th>Edit Class List</th>
</tr>
<tbody id="mdata">
</tbody>
</thead>
</table>
`,
});
// Create infoModal to show information about models uploaded.
$UI.helpModal = new ModalBox({
id: 'help',
hasHeader: true,
headerText: 'Help',
hasFooter: false,
});
// Create Modal to take input from user of new class list
$UI.chngClassLst = new ModalBox({
id: 'chngClass',
hasHeader: true,
headerText: 'Help',
hasFooter: false,
});
// Create roiExtract for taking details of ROI extraction
$UI.roiModal = new ModalBox({
id: 'roi_panel',
hasHeader: true,
headerText: 'ROI Extraction',
hasFooter: false,
provideContent: true,
content: `
<div class = "message" >
<h3> Please select a model</h3></div><br>
<table id = 'roitable'>
<thead>
<tr>
<th>Name</th>
<th>Classes</th>
<th>Input Size</th>
<th>Size (MB)</th>
<th>Date Saved</th>
<th>Select Model</th>
</tr>
<tbody id = "roidata">
</tbody>
</thead>
</table>
`,
});
$UI.choiceModal = new ModalBox({
id: 'choice_panel',
hasHeader: true,
headerText: 'Select Parameters',
hasFooter: false,
provideContent: true,
content: `
<div class = "message" >
<h3> Select the parameters for the patches that you want to download</h3></div><br>
<table id = 'choicetable'>
<thead>
<tbody id = "choicedata">
</tbody>
</thead>
</table>
`,
});
$UI.detailsModal = new ModalBox({
id: 'details_panel',
hasHeader: true,
headerText: 'Details',
hasFooter: false,
provideContent: true,
content: `
<div class= "message" >
<h3> The details of the extracted patches are : </h3></div><br>
<table id='detailstable'>
<thead>
<tbody id="detailsdata">
</tbody>
</thead>
</table>
`,
});
// create the message queue
$UI.message = new MessageQueue();
const dropDownList = [];
modelName = [];
Object.keys(await tf.io.listModels()).forEach(function(element) {
const dict = {};
const value = element.split('/').pop();
if (value.slice(0, 4) == 'pred') {
const title = element.split('/').pop().split('_').splice(2).join('_').slice(0, -3);
dict.icon = 'flip_to_back';
dict.title = title;
dict.value = value;
dict.checked = false;
// Saving to previously defined model names
modelName.push(dict['title']);
dropDownList.push(dict);
}
});
const filterList = [
{
icon: 'filter_1',
title: 'Normalization',
value: 'norm',
checked: true,
}, {
icon: 'filter_2',
title: 'Centering',
value: 'center',
checked: false,
}, {
icon: 'filter_3',
title: 'Standardization',
value: 'std',
checked: false,
},
];
// create toolbar
$UI.toolbar = new CaToolbar({
id: 'ca_tools',
zIndex: 601,
hasMainTools: false,
subTools: [
{
icon: 'aspect_ratio',
type: 'check',
value: 'rect',
title: 'Predict',
callback: drawRectangle,
}, {
icon: 'keyboard_arrow_down',
type: 'dropdown',
value: 'rect',
dropdownList: dropDownList,
title: 'Select Model',
callback: setValue,
}, {
icon: 'photo_filter',
type: 'dropdown',
dropdownList: filterList,
title: 'Pixel Scaling',
callback: setFilter,
}, {
icon: 'insert_photo',
type: 'btn',
value: 'viewer',
title: 'Viewer',
callback: function() {
if (window.location.search.length > 0) {
window.location.href = '../viewer/viewer.html' + window.location.search;
} else {
window.location.href = '../viewer/viewer.html';
}
},
}, {
icon: 'add',
type: 'btn',
value: 'Upload model',
title: 'Add model',
callback: uploadModel,
}, {
icon: 'info',
type: 'btn',
value: 'Model info',
title: 'Model info',
callback: showInfo,
}, {
icon: 'help',
type: 'btn',
value: 'Help',
title: 'Help',
callback: openHelp,
}, {
icon: 'archive',
type: 'btn',
value: 'ROI',
title: 'ROI',
callback: selectModel,
}, {
icon: 'bug_report',
title: 'Bug Report',
value: 'bugs',
type: 'btn',
callback: () => {
window.open('https://goo.gl/forms/mgyhx4ADH0UuEQJ53', '_blank').focus();
},
},
{
icon: 'subject',
title: 'Model Summary',
value: 'summary',
type: 'btn',
callback: () => {
tfvis.visor().toggle();
}},
],
});
}
// setting core functionality
function initCore() {
// start initial
const opt = {
hasZoomControl: true,
hasDrawLayer: true,
hasLayerManager: true,
hasScalebar: true,
hasMeasurementTool: true,
};
// set states if exist
if ($D.params.states) {
opt.states = $D.params.states;
}
try {
const slideQuery = {};
slideQuery.id = $D.params.slideId;
slideQuery.name = $D.params.slide;
slideQuery.location = $D.params.location;
$CAMIC = new CaMic('main_viewer', slideQuery, opt);
} catch (error) {
Loading.close();
$UI.message.addError('Core Initialization Failed');
console.error(error);
return;
}
$CAMIC.loadImg(function(e) {
// image loaded
if (e.hasError) {
$UI.message.addError(e.message);
} else {
$D.params.data = e;
}
});
$CAMIC.store.getSlide($D.params.slideId).then((response) => {
if (response[0]) {
if (response[0]['filepath']) {
return response[0]['filepath'];
}
return location.substring(
location.lastIndexOf('/') + 1,
location.length,
);
} else {
throw new Error('Slide not found');
}
}).then((fileName) => {
console.log(fileName);
});
$CAMIC.viewer.addOnceHandler('open', function(e) {
const viewer = $CAMIC.viewer;
// add stop draw function
viewer.canvasDrawInstance.addHandler('stop-drawing', camicStopDraw);
// UI to select the part of image
$UI.modelPanel = new ModelPanel(viewer);
$UI.modelPanel.__btn_save.addEventListener('click', function(e) {
const fname = $D.params.slideId + '_roi.png';
download($UI.modelPanel.__fullsrc, fname);
});
// TO-DO -Save class probabilities
$UI.modelPanel.__btn_savecsv.addEventListener('click', function(e) {
const fname = $D.params.slideId + '_roi.csv';
downloadCSV(fname);
});
});
}
function setValue(args) {
$UI.args = args;
}
function setFilter(filter) {
$UI.filter = filter;
}
/**
* Toolbar button callback
* @param e
*/
function drawRectangle(e) {
console.log(e);
const canvas = $CAMIC.viewer.drawer.canvas; // Original Canvas
canvas.style.cursor = e.checked ? 'crosshair' : 'default';
var args;
const canvasDraw = $CAMIC.viewer.canvasDrawInstance;
if (e.state == 'roi') {
args = {status: ''};
args.status = e.model;
console.log(args);
} else {
args = $UI.args;
}
// console.log(args);
canvasDraw.drawMode = 'stepSquare';
// Save size in an arg list
if (args) canvasDraw.size = args.status.split('_')[1].split('-')[0];
else canvasDraw.size = 1;
canvasDraw.style.color = '#FFFF00';
canvasDraw.style.isFill = false;
if (e.checked ) {
// Warn about zoom level
const currentZoom = Math.round($CAMIC.viewer.imagingHelper._zoomFactor * 40);
requiredZoom = $UI.args? parseInt($UI.args.status.split('_')[1].split('-')[1]):currentZoom;
if (currentZoom != requiredZoom && flag != 0) {
alert(`You are testing the model for a different zoom level (recommended: ${requiredZoom}). Performance might be affected.`);
}
document.querySelector('.drop_down').classList.add('disabled');
canvasDraw.drawOn();
} else {
canvasDraw.drawOff();
document.querySelector('.drop_down').classList.remove('disabled');
}
}
/**
* This is basically onmouseup after drawing rectangle.
* @param e
*/
function camicStopDraw(e) {
console.log(e);
const viewer = $CAMIC.viewer;
const canvasDraw = viewer.canvasDrawInstance;
const imgColl = canvasDraw.getImageFeatureCollection();
if (imgColl.features.length > 0 && imgColl.features[0].bound.coordinates[0].length >= 5) {
// Check size first
const box = checkSize(imgColl, viewer.imagingHelper);
if (Object.keys(box).length === 0 && box.constructor === Object) {
console.error('SOMETHING WICKED THIS WAY COMES.');
} else {
const args = $UI.args;
console.log(flag);
if (flag != -1 ) {
extractRoi(choices1, flag);
} else {
if (args) {
runPredict(args.status);
}
}
$UI.modelPanel.setPosition(box.rect.x, box.rect.y, box.rect.width, box.rect.height);
if ($UI.modelPanel.__spImgWidth != 0) {
$UI.modelPanel.open(args);
}
canvasDraw.clear();
csvContent = '';
}
} else {
console.error('Could not get feature collection.');
}
}
function checkSize(imgColl, imagingHelper) {
// 5x2 array
const bound = imgColl.features[0].bound;
// slide images svsslide images svs
// get position on viewer
const topLeft = imgColl.features[0].bound.coordinates[0][0];
const bottomRight = imgColl.features[0].bound.coordinates[0][2];
const min = imagingHelper._viewer.viewport.imageToViewportCoordinates(topLeft[0], topLeft[1]);
const max = imagingHelper._viewer.viewport.imageToViewportCoordinates(bottomRight[0], bottomRight[1]);
const rect = new OpenSeadragon.Rect(min.x, min.y, max.x-min.x, max.y-min.y);
const self = $UI.modelPanel;
self.__top_left = topLeft;
self.__spImgX = topLeft[0];
self.__spImgY = topLeft[1];
self.__spImgWidth = bottomRight[0]-topLeft[0];
self.__spImgHeight = bottomRight[1]-topLeft[1];
// Convert to screen coordinates
const foo = convertCoordinates(imagingHelper, bound);
// retina screen
const newArray = foo.map(function(a) {
const x = a.slice();
x[0] *= PDR;
x[1] *= PDR;
return x;
});
const xCoord = Math.round(newArray[0][0]);
const yCoord = Math.round(newArray[0][1]);
const width = Math.round(newArray[2][0] - xCoord);
const height = Math.round(newArray[2][1] - yCoord);
self.__x = xCoord;
self.__y = yCoord;
self.__width = xCoord;
self.__height = yCoord;
// check that image size is ok
if (width * height > 8000000) {
alert('Selected ROI too large, current version is limited to 4 megapixels');
// Clear the rectangle canvas-draw-overlay.clear()
$CAMIC.viewer.canvasDrawInstance.clear();
return {}; // throw('image too large')
} else {
return {'rect': rect, 'xCoord': xCoord, 'yCoord': yCoord, 'width': width, 'height': height};
}
}
/**
* Run model
* @param key
*/
function runPredict(key) {
// But first, some setup...
const self = $UI.modelPanel;
const X = self.__spImgX;
const Y = self.__spImgY;
const totalSize = self.__spImgWidth;
const step = parseInt(key.split('_')[1].split('-')[0]);
self.showResults(' --Result-- ');
if (totalSize > 0) {
const prefixUrl = ImgloaderMode == 'iip'?`../../img/IIP/raw/?IIIF=${$D.params.data.location}`:$CAMIC.slideId;
self.showProgress('Predicting...');
const fullResCvs = self.__fullsrc;
// Starting the transaction and opening the model store
const tx = db.transaction('models_store', 'readonly');
const store = tx.objectStore('models_store');
store.get(key).onsuccess = async function(e) {
// Keras sorts the labels by alphabetical order.
const classes = e.target.result.classes.sort();
const inputShape = e.target.result.input_shape;
// let inputChannels = parseInt(inputShape[3]);
const inputChannels = 3;
const imageSize = inputShape[1];
model = await tf.loadLayersModel(IDB_URL + key);
self.showProgress('Model loaded...');
tfvis.show.modelSummary({name: 'Model Summary', tab: 'Model Inspection'}, model);
// Warmup the model before using real data.
tf.tidy(()=>{
model.predict(tf.zeros([1, imageSize, imageSize, inputChannels]));
console.log('Model ready');
});
const memory = tf.memory();
console.log('Model Memory Usage');
console.log('GPU : ' + memory.numBytesInGPU + ' bytes');
console.log('Total : ' + memory.numBytes + ' bytes');
const temp = document.querySelector('#dummy');
temp.height = step;
temp.width = step;
function addImageProcess(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
}
const results = [];
csvContent = 'data:text/csv;charset=utf-8,';
classes.forEach((e) => {
csvContent += e + ',';
});
csvContent += 'x,y\n\r';
self.showProgress('Predicting...');
for (let y = Y, dy = 0; y < (Y + totalSize); y+=(step)) {
let dx = 0;
for (let x = X; x < (X + totalSize); x+=(step)) {
const src = prefixUrl+'\/'+x+','+y+','+step+','+step+'\/'+step+',/0/default.jpg';
const lImg = await addImageProcess(src);
fullResCvs.height = lImg.height;
fullResCvs.width = lImg.width;
fullResCvs.getContext('2d').drawImage(lImg, 0, 0);
const imgData = fullResCvs.getContext('2d').getImageData(0, 0, fullResCvs.width, fullResCvs.height);
tf.tidy(()=>{
const img = tf.browser.fromPixels(imgData).toFloat();
let img2;
if (inputChannels == 1) {
img2 = tf.image.resizeBilinear(img, [imageSize, imageSize]).mean(2);
} else {
img2 = tf.image.resizeBilinear(img, [imageSize, imageSize]);
}
const scaleMethod = $UI.filter? $UI.filter.status: 'norm';
console.log(scaleMethod);
let normalized;
if (scaleMethod == 'norm') {
// Pixel Normalization: scale pixel values to the range 0-1.
const scale = tf.scalar(255);
normalized = img2.div(scale);
} else if (scaleMethod == 'center') {
// Pixel Centering: scale pixel values to have a zero mean.
const mean = img2.mean();
normalized = img2.sub(mean);
// normalized.mean().print(true); // Uncomment to check mean value.
// let min = img2.min();
// let max = img2.max();
// let normalized = img2.sub(min).div(max.sub(min));
} else {
// Pixel Standardization: scale pixel values to have a zero mean and unit variance.
const mean = img2.mean();
const std = (img2.squaredDifference(mean).sum()).div(img2.flatten().shape).sqrt();
normalized = img2.sub(mean).div(std);
}
const batched = normalized.reshape([1, imageSize, imageSize, inputChannels]);
const values =model.predict(batched).dataSync();
values.forEach((e) => {
csvContent += e.toString() + ',';
});
csvContent += '' + dx + ',' + dy + '\n\r';
results.push(values);
// Retrieving the top class
dx += step;
});
}
dy += step;
}
const len = results.length;
const final = new Array(results[0].length).fill(0);
for (let i = 0; i < results.length; i++) {
for (let j = 0; j < results[0].length; j++) {
final[j] += results[i][j];
}
}
for (let i = 0; i < final.length; i++) {
final[i] /= len;
}
iMax = Object.keys(final).reduce((a, b) => final[a] > final[b] ? a : b);
const i = parseInt(iMax) + 1;
self.showResults('' + i + ': ' + classes[iMax] + ' - ' + final[iMax].toFixed(3));
self.hideProgress();
model.dispose();
};
} else {
alert('Selected section too small. Please select a larger section.');
}
}
// TO-DO: Allow uploading and using tensorflow graph models. Can't save graph models. Need to use right away.
function uploadModel() {
var _name = document.querySelector('#name');
var _classes = document.querySelector('#classes');
var mag = document.querySelector('#magnification');
var _imageSize = document.querySelector('#imageSize');
var topology = document.querySelector('#modelupload');
var weights = document.querySelector('#weightsupload');
var status = document.querySelector('#status');
var toggle = document.querySelector('#togBtn');
var url = document.querySelector('#url');
var refresh = document.querySelector('#refresh');
var submit = document.querySelector('#submit');
// Reset previous input
_name.value = _classes.value = topology.value = weights.value = status.innerText = _imageSize.value = url.value = '';
$UI.uploadModal.open();
toggle.addEventListener('change', function(e) {
if (this.checked) {
document.querySelector('.checktrue').style.display = 'block';
document.querySelector('.checkfalse').style.display = 'none';
} else {
document.querySelector('.checktrue').style.display = 'none';
document.querySelector('.checkfalse').style.display = 'block';
}
});
refresh.addEventListener('click', () => {
initUIcomponents();
});
submit.addEventListener('click', async function(e) {
e.preventDefault();
if ( _name.value && _classes.value && _imageSize.value &&
((!toggle.checked && topology.files[0].name.split('.').pop() == 'json') || (toggle.checked && url))) {
status.innerText = 'Uploading';
status.classList.remove('error');
status.classList.add('blink');
const _channels = parseInt(document.querySelector('input[name="channels"]:checked').value);
// Adding some extra digits in the end to maintain uniqueness
const name = 'pred_' + _imageSize.value.toString() + '-' + mag.value.toString() +
'_' + _name.value + (new Date().getTime().toString()).slice(-4, -1);
// Create an array from comma separated values of classes
const classes = _classes.value.split(/\s*,\s*/);
if (toggle.checked) {
var modelInput = url.value;
} else {
var modelInput = tf.io.browserFiles([topology.files[0], ...weights.files]);
}
// Check if model with same name is previously defined
try {
if (modelName.indexOf(_name.value)!=-1) {
throw new Error('Model name repeated');
}
} catch (e) {
status.innerText = 'Model with the same name already exists. Please choose a new name';
status.classList.remove('blink');
console.log(e);
document.getElementById('name').style = 'border:2px; border-style: solid; border-color: red;';
return;
}
try {
// This also ensures that valid model is uploaded.
const model = await tf.loadLayersModel(modelInput);
try {
const result = model.predict(
tf.ones([1, parseInt(_imageSize.value), parseInt(_imageSize.value), parseInt(_channels)]));
result.dispose();
} catch (e) {
status.innerText = 'Model failed on the given values of patch size.' +
'Please input values on which the model was trained.';
console.log(e);
status.classList.remove('blink');
document.getElementById('imageSize').style = 'border:2px; border-style: solid; border-color: red;';
return;
}
await model.save(IDB_URL + name);
// Update the model store db entry to have the classes array
tx = db.transaction('models_store', 'readwrite');
store = tx.objectStore('models_store');
store.get(name).onsuccess = function(e) {
const data = e.target.result;
data['classes'] = classes;
data['input_shape'] = [1, parseInt(_imageSize.value), parseInt(_imageSize.value), parseInt(_channels)];
const req = store.put(data);
req.onsuccess = function(e) {
console.log('SUCCESS, ID:', e.target.result);
modelName.push(_name.value);
let popups = document.getElementById('popup-container');
if (popups.childElementCount < 2) {
let popupBox = document.createElement('div');
popupBox.classList.add('popup-msg', 'slide-in');
popupBox.innerHTML = `<i class="small material-icons">info</i>` + _name.value + ` model uploaded sucessfully`;
popups.insertBefore(popupBox, popups.childNodes[0]);
setTimeout(function() {
popups.removeChild(popups.lastChild);
}, 3000);
}
$UI.uploadModal.close();
initUIcomponents();
};
req.onerror = function(e) {
status.innerText = 'Some error this way!';
console.log(e);
status.classList.remove('blink');
};
};
} catch (e) {
status.classList.add('error');
status.classList.remove('blink');
if (toggle.checked) status.innerText = 'Please enter a valid URL.';
else {
status.innerText = 'Please enter a valid model.' +
'Input model.json in first input and all weight binaries in second one without renaming.';
}
console.error(e);
}
} else {
status.innerText = 'Please fill out all the fields with valid values.';
status.classList.add('error');
console.error(e);
}
});
}
/**
* Delete a model from the store
*
* @param name : Model name
*/
async function deleteModel(name) {
deletedmodelName = name.split('/').pop().split('_').splice(2).join('_').slice(0, -3);
if (confirm('Are you sure you want to delete ' + deletedmodelName + ' model?')) {
const res = await tf.io.removeModel(IDB_URL + name);
console.log(res);
const tx = db.transaction('models_store', 'readwrite');
const store = tx.objectStore('models_store');
let status = false;
try {
store.delete(name);
status = true;
} catch (err) {
alert(err);
} finally {
if (status) {
let popups = document.getElementById('popup-container');
if (popups.childElementCount < 2) {
let popupBox = document.createElement('div');
popupBox.classList.add('popup-msg', 'slide-in');
popupBox.innerHTML = `<i class="small material-icons">info</i>` + deletedmodelName + ` model deleted successfully`;
popups.insertBefore(popupBox, popups.childNodes[0]);
setTimeout(function() {
popups.removeChild(popups.lastChild);
}, 3000);
}
$UI.infoModal.close();
initUIcomponents();
}
}
} else {
return;
}
}
// Shows the uploaded models' details
async function showInfo() {
var data = await tf.io.listModels();
var table = document.querySelector('#mdata');
var tx = db.transaction('models_store', 'readonly');
var store = tx.objectStore('models_store');
var modelCount = 0;
empty(table);
// Update table data
(function(callback) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
const name = key.split('/').pop();
const date = data[key].dateSaved.toString().slice(0, 15);
const size = (data[key].modelTopologyBytes +
data[key].weightDataBytes +
data[key].weightSpecsBytes) / (1024*1024);
const row = table.insertRow();
let classes; let inputShape; let td;
if (name.slice(0, 4) == 'pred') {
store.get(name).onsuccess = function(e) {
classes = (e.target.result.classes.join(', '));
inputShape = e.target.result.input_shape.slice(1, 3).join('x');
td = row.insertCell();
td.innerText = name.split('/').pop().split('_').splice(2).join('_').slice(0, -3);
td = row.insertCell();
td.innerText = classes;
td = row.insertCell();
td.innerText = inputShape;
td = row.insertCell();
td.innerText = +size.toFixed(2);
td = row.insertCell();
td.innerText = date;
td = row.insertCell();
td.innerHTML = '<button class="btn-del" ' +
'id=removeModel' + modelCount +' type="button"><i class="material-icons"'+
'style="font-size:16px;">delete_forever</i>Remove Model</button>';
td = row.insertCell();
td.innerHTML = '<button class="btn-change" '+
'id=chngClassListBtn'+ modelCount +' type="button"><i class="material-icons"' +
'style="font-size:16px;">edit</i> Edit Classes</button>';
document.getElementById('removeModel'+ modelCount).addEventListener('click', () => {
deleteModel(name);
});
document.getElementById('chngClassListBtn' + modelCount).addEventListener('click', () => {
showNewClassInput(name, classes);
});
modelCount += 1;
};
}
}
}
callback;
})($UI.infoModal.open());
}
function showNewClassInput(name, classes) {
const self = $UI.chngClassLst;
self.body.innerHTML = `
<input id ="new_classList" type="text"/>
<button class="btn btn-primary btn-xs my-xs-btn btn-final-change" id='chngbtn' type="button">Change Class List</button>
`;
document.getElementById('new_classList').defaultValue = classes;
$UI.chngClassLst.open(); // Open the box to take input from user
document.getElementById('chngbtn').addEventListener('click', () => {
// $UI.chngClassLst.close();
var newList = document.querySelector('#new_classList').value; // Get the list inputed by user
$UI.infoModal.close();
$UI.chngClassLst.close();
changeClassList(newList, name); // Call to a function to change class list
});
}
async function changeClassList(newList, name) {
var data = await tf.io.listModels();
var tx = db.transaction('models_store', 'readwrite');
var store = tx.objectStore('models_store');
for (const key in data) {
if (name === key.split('/').pop()) {
store.get(name).onsuccess = function(e) {
const d = e.target.result;
const classList = newList.split(/\s*,\s*/);
d['classes'] = classList;
const req = store.put(d);