File size: 40,931 Bytes
3566452
 
b9eaea7
4728dd2
f1a11e6
94ae045
b1a6869
 
71e2a20
d91102e
 
 
4408bec
d91102e
dadd12e
4734edd
dfff50a
b1a6869
 
 
 
8119410
d91102e
dfff50a
b1a3cc1
f994ab3
2cb93fb
8119410
 
3e5ef51
8119410
 
 
2cb93fb
8119410
3e5ef51
8119410
356e41c
8119410
3566452
d91102e
2cb93fb
3566452
d91102e
2cb93fb
 
a85a0a3
3e5ef51
8119410
dadd12e
fe4e8b5
 
 
dfff50a
 
fe4e8b5
 
b9eaea7
83b7c6a
857bb0f
 
884c10b
857bb0f
83b7c6a
2cb93fb
83b7c6a
 
857bb0f
8b18526
83b7c6a
3566452
3e5ef51
83b7c6a
 
7a54f74
8b18526
857bb0f
83b7c6a
7a54f74
8b18526
 
 
 
3566452
8b18526
7a54f74
a22369d
83b7c6a
3e5ef51
8b18526
83b7c6a
4463626
 
83b7c6a
8b18526
2cb93fb
3e5ef51
83b7c6a
 
884c10b
857bb0f
4463626
 
a22369d
a2a070a
8b18526
857bb0f
884c10b
 
 
 
 
 
 
 
a22369d
a2a070a
8b18526
 
 
 
a2a070a
8b18526
a2a070a
 
 
 
 
 
 
 
884c10b
 
 
a2a070a
 
884c10b
a2a070a
884c10b
 
a2a070a
 
a22369d
 
 
7d67389
857bb0f
 
884c10b
857bb0f
a22369d
83b7c6a
 
 
857bb0f
8b18526
83b7c6a
 
3e5ef51
8b18526
83b7c6a
4463626
 
83b7c6a
8b18526
83b7c6a
3e5ef51
83b7c6a
3566452
3e5ef51
83b7c6a
 
4734edd
857bb0f
4463626
 
7a54f74
a2a070a
8b18526
a2a070a
884c10b
 
 
 
 
 
 
 
a22369d
a2a070a
8b18526
 
 
 
a2a070a
8b18526
a2a070a
 
 
 
 
 
 
 
857bb0f
884c10b
 
a2a070a
 
884c10b
a2a070a
884c10b
 
a2a070a
 
7a54f74
 
 
fe4e8b5
 
857bb0f
884c10b
fe4e8b5
7681112
fe4e8b5
a22369d
fe4e8b5
d91102e
 
 
b1a3cc1
d91102e
 
f994ab3
b1a3cc1
 
 
d91102e
b1a3cc1
 
 
 
 
 
 
 
 
 
 
 
 
3166abf
2cb93fb
b1a3cc1
a85a0a3
b1a3cc1
 
 
 
 
 
 
 
a22369d
fe4e8b5
d91102e
 
 
b1a3cc1
d91102e
b1a3cc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe4e8b5
 
6598d76
 
a22369d
fe4e8b5
 
 
 
 
a22369d
fe4e8b5
857bb0f
 
3566452
857bb0f
b1a3cc1
857bb0f
d91102e
fe4e8b5
3566452
fe4e8b5
3566452
 
4734edd
3566452
 
a22369d
857bb0f
8b18526
857bb0f
3566452
857bb0f
3566452
 
857bb0f
 
 
 
3566452
857bb0f
 
 
3566452
 
 
 
 
 
 
 
857bb0f
 
3566452
 
d91102e
857bb0f
 
f994ab3
 
857bb0f
884c10b
857bb0f
884c10b
3566452
857bb0f
 
3566452
8119410
 
8b18526
a2a070a
 
3566452
 
 
a2a070a
3566452
d91102e
3566452
d91102e
251d442
ef20573
995c1d0
f994ab3
a22369d
a2a070a
857bb0f
3566452
857bb0f
3566452
857bb0f
3566452
 
 
 
 
 
 
d91102e
2cb93fb
3566452
b1a3cc1
3566452
d91102e
3566452
 
 
 
 
 
 
2e24354
3566452
 
857bb0f
b1a3cc1
3566452
857bb0f
3566452
857bb0f
b1a3cc1
3566452
 
857bb0f
3566452
857bb0f
3566452
857bb0f
 
3566452
8119410
 
857bb0f
a22369d
3566452
 
 
 
857bb0f
3566452
 
 
2cb93fb
 
 
 
3566452
 
 
 
 
 
 
 
 
2cb93fb
3566452
 
 
 
d91102e
3566452
ef20573
3566452
 
 
 
 
 
 
 
2cb93fb
3566452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f994ab3
3566452
 
 
 
 
 
 
 
 
 
a22369d
3566452
857bb0f
884c10b
3566452
857bb0f
 
 
 
 
2e24354
3566452
 
4463626
 
3566452
857bb0f
3566452
857bb0f
3566452
 
857bb0f
3566452
 
 
 
2cb93fb
857bb0f
2cb93fb
 
 
 
3566452
 
 
 
 
857bb0f
3566452
 
ef20573
2cb93fb
8b18526
3566452
d91102e
a2a070a
ef20573
 
3566452
ef20573
857bb0f
8119410
f994ab3
857bb0f
3566452
857bb0f
3566452
ef20573
857bb0f
8b18526
857bb0f
ef20573
a2a070a
ef20573
 
3566452
 
83b7c6a
3566452
 
2cb93fb
 
 
 
3566452
 
 
 
 
 
 
 
 
2cb93fb
3566452
 
 
d91102e
3566452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e24354
 
3566452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
857bb0f
3566452
2e24354
857bb0f
 
 
 
2e24354
3566452
 
 
2cb93fb
 
 
 
3566452
 
 
 
 
857bb0f
3566452
 
 
2cb93fb
a22369d
 
3566452
d91102e
a22369d
fe4e8b5
f1a11e6
ef20573
3566452
 
d91102e
ef20573
 
83b7c6a
857bb0f
ef20573
 
a22369d
857bb0f
 
3566452
857bb0f
3566452
 
b1a3cc1
3566452
d91102e
b1a3cc1
3566452
 
 
 
 
 
 
 
 
 
4734edd
8119410
 
 
4734edd
8119410
 
 
 
4734edd
8119410
 
 
 
 
 
 
 
 
 
857bb0f
 
3566452
857bb0f
 
 
 
 
2e24354
3566452
 
4463626
 
3566452
857bb0f
3566452
857bb0f
ef20573
857bb0f
3566452
2e24354
857bb0f
 
ef20573
857bb0f
 
8119410
857bb0f
ef20573
857bb0f
8b18526
ef20573
3566452
ef20573
857bb0f
ef20573
857bb0f
8b18526
ef20573
 
 
857bb0f
 
f1a11e6
ef20573
7d67389
857bb0f
ef20573
 
 
a2a070a
857bb0f
3566452
 
857bb0f
 
3566452
2e24354
857bb0f
 
 
 
2e24354
3566452
 
857bb0f
3566452
857bb0f
ef20573
857bb0f
2e24354
 
857bb0f
3566452
4463626
ef20573
857bb0f
 
 
 
ef20573
 
3566452
ef20573
857bb0f
ef20573
 
a2a070a
3566452
 
 
d91102e
a2a070a
 
 
857bb0f
a2a070a
 
 
ef20573
 
857bb0f
 
884c10b
ef20573
7d67389
857bb0f
884c10b
f1a11e6
a22369d
995c1d0
23fe20b
3566452
857bb0f
b1a3cc1
857bb0f
 
4463626
3566452
 
857bb0f
3566452
 
857bb0f
 
d91102e
857bb0f
f1a11e6
3566452
 
 
d91102e
3566452
b1a3cc1
 
995c1d0
3566452
857bb0f
 
995c1d0
857bb0f
995c1d0
3566452
857bb0f
 
995c1d0
3566452
b1a3cc1
d91102e
3566452
857bb0f
2e24354
857bb0f
 
 
 
 
 
 
 
69ee4d8
857bb0f
 
 
 
995c1d0
857bb0f
 
 
a22369d
3566452
 
 
23fe20b
857bb0f
 
3566452
857bb0f
 
 
 
 
3566452
857bb0f
69ee4d8
857bb0f
 
23fe20b
857bb0f
 
 
 
 
 
 
 
995c1d0
 
ef20573
b1a3cc1
3566452
fe4e8b5
995c1d0
 
3566452
857bb0f
995c1d0
a22369d
b9eaea7
d725d3b
857bb0f
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
import utils
import app_utils
import gradio as gr
import os
import random

intro = """

This tool is designed to assist you with two main tasks:
1. **Channel Mapping**: Align your EEG channels with our template channels to ensure compatibility with our models.
2. **EEG Data Denoising**: Use our pre-trained models—**ART**, **IC-U-Net**, **IC-U-Net++**, and **IC-U-Net-Attn**—to denoise your EEG data.

## File Requirements and Preparation
- **Channel locations**: If you don't have the channel location file, we recommend you to download the standard montage <a href="">here</a>. If the channels in those files don't match yours, you can use **EEGLAB** to adjust them to your required montage.
- **Raw data**: Your data format must be a two-dimensional array (channels, timepoints).
- **Channel requirements**: Your data must include some channels that correspond to our template channels, which include: ``Fp1, Fp2, F7, F3, Fz, F4, F8, FT7, FC3, FCz, FC4, FT8, T7, C3, Cz, C4, T8, TP7, CP3, CPz, CP4, TP8, P7, P3, Pz, P4, P8, O1, Oz, O2``. At least some of them need to be present for successful mapping. Additionally, please remove any reference, ECG, EOG, EMG... channels before uploading your files.

"""

readme = """

## 1. Channel Mapping
The following steps will guide you through the process of mapping your EEG channels to our template channels.

### Step1: Initial Matching and Scaling
After clicking on ``Map`` button, we will first match your channels to our template channels by their names. Using the matched channels as reference points, we will apply Thin Plate Spline (TPS) transformation to scale your montage to align with our template's dimensions. The template montage and your scaled montage will be displayed side by side for comparison. Channels that do not have a match in our template will be **highlighted in red**.
- If your data includes all the 30 template channels, you will be directed to **Mapping Results**.
- If your data doesn't include all the 30 template channels and you have some channels that do not match the template, you will be directed to **Step2**.
- If all your channels are included in our template but you have fewer than 30 channels, you will be directed to **Step3**.

### Step2: Forwarding Unmatched Channels
In this step, you will handle the channels that didn't have a direct match with our template, by manually assigning them to the template channels that are still empty, ensuring the most efficient use of your data.  
Your unmatched channels, previously highlighted in red, will be shown on your montage with a radio button displayed above each. You can choose to forward the data from these unmatched channels to the empty template channels. The interface will display each empty template channel in sequence, allowing you to select which of your unmatched channels to forward.
- If all empty template channels are filled by your selections, you will be directed to **Mapping Results**.
- If there are still empty template channels remaining, you will be directed to **Step3**.

### Step3: Filling Remaining Template Channels
To run the models successfully, we need to ensure that all 30 template channels are filled. In this step, you are required to select one of the methods provided below to fill the remaining empty template channels:
- **Mean** method: Each empty template channel is filled with the average value of data from the nearest input channels. By default, the 4 closest input channels (determined after aligning your montage to the template's scale using TPS) are selected for this averaging process. On the interface, you will see checkboxes displayed above each of your channel. The 4 nearest channels are pre-selected by default for each empty template channels, but you can modify these selections as needed. If you uncheck all the checkboxes for a particular template channel, it will be filled with zeros.
- **Zero** method: All empty template channels are filled with zeros.  
Choose the method that best suits your needs, considering that the model's performance may vary depending on the method used.  
Once all template channels are filled, you will be directed to **Mapping Results**.

### Mapping Results
After completing the previous steps, your channels will be aligned with the template channels required by our models.
- In case there are still some channels that haven't been mapped, we will automatically batch and optimally assign them to the template. This ensures that even channels not initially mapped will still be included in the final results.
- Once the channel mapping process is completed, a **JSON file** containing the mapping results will be generated. This file is necessary only if you plan to run the models using the <a href="">source code</a>; otherwise, you can ignore it.

## 2. Decode data
After clicking on ``Run`` button, we will process your EEG data based on the mapping results. If necessary, your data will be devided into batches and run the models on each batch sequentially, ensuring that all channels are properly processed.
"""

icunet = """
# IC-U-Net
### Abstract
Electroencephalography (EEG) signals are often contaminated with artifacts. It is imperative to develop a practical and reliable artifact removal method to prevent the misinterpretation of neural signals and the underperformance of brain–computer interfaces. Based on the U-Net architecture, we developed a new artifact removal model, IC-U-Net, for removing pervasive EEG artifacts and reconstructing brain signals. IC-U-Net was trained using mixtures of brain and non-brain components decomposed by independent component analysis. It uses an ensemble of loss functions to model complex signal fluctuations in EEG recordings. The effectiveness of the proposed method in recovering brain activities and removing various artifacts (e.g., eye blinks/movements, muscle activities, and line/channel noise) was demonstrated in a simulation study and four real-world EEG experiments. IC-U-Net can reconstruct a multi-channel EEG signal and is applicable to most artifact types, offering a promising end-to-end solution for automatically removing artifacts from EEG recordings. It also meets the increasing need to image natural brain dynamics in a mobile setting.
"""

init_js = """
(app_info, channel_info) => {
	app_info = JSON.parse(JSON.stringify(app_info));
	channel_info = JSON.parse(JSON.stringify(channel_info));
	stage1_info = app_info.stage1
	
	let selector, attribute;
	let channel, left, bottom;
	
	if(stage1_info.state == "step2-selecting"){
	    selector = "#radio-group > div:nth-of-type(2)";
	    attribute = "value";
	}else if(stage1_info.state == "step3-2-selecting"){
	    selector = "#chkbox-group > div:nth-of-type(2)";
	    attribute = "name";
	}else return;
	
	
	// add figure of the input montage
	document.querySelector(selector).style.cssText = `
		position: relative;
		width: 100%;
		aspect-ratio: 1;
		//width: 560px;
		//height: 560px;
		background: url("file=${stage1_info.fileNames.input_montage}");
		background-size: contain;
	`;
	
	// move the radios/checkboxes
	let all_elem = document.querySelectorAll(selector+" > label");
	Array.from(all_elem).forEach(item => {
		channel = item.querySelector("input").getAttribute(attribute);
		left = channel_info.inputDict[channel].css_position[0];
		bottom = channel_info.inputDict[channel].css_position[1];
		
		item.style.cssText = `position: absolute; left: ${left}; bottom: ${bottom};`;
		item.className = "";
		item.querySelector(":scope > span").innerText = "";
	});
	
	// add indication for the missing channels
	channel = stage1_info.missingTemplates[0];
	left = channel_info.templateDict[channel].css_position[0];
	bottom = channel_info.templateDict[channel].css_position[1];
	
	let dot_rule = `
		${selector}::before {
			content: "";
			position: absolute;
			background-color: red;
			width: 10px;
			height: 10px;
			border-radius: 50%;
			left: ${left};
			bottom: ${bottom};
		}
	`;
	
	left = parseFloat(left.slice(0, -1))+2.5;
	left = left.toString()+"%";
	bottom = parseFloat(bottom.slice(0, -1))-1;
	bottom = bottom.toString()+"%";
	let txt_rule = `
		${selector}::after {
			content: "${channel}";
			position: absolute;
			color: red;
			left: ${left};
			bottom: ${bottom};
		}
	`;
	
	// check if indicator already exist
	const styleSheet = document.styleSheets[0];
	for(let i=0; i<styleSheet.cssRules.length; i++){
		let tmp = styleSheet.cssRules[i].selectorText;
		if(tmp==selector+"::before" || tmp==selector+"::after"){
			styleSheet.deleteRule(i);
			i--;
		}
	}
	styleSheet.insertRule(dot_rule, styleSheet.cssRules.length);
	styleSheet.insertRule(txt_rule, styleSheet.cssRules.length);
}
"""

update_js = """
(app_info, channel_info) => {
	app_info = JSON.parse(JSON.stringify(app_info));
	channel_info = JSON.parse(JSON.stringify(channel_info));
	stage1_info = app_info.stage1
	
	let selector;
	let channel, left, bottom;
	
	if(stage1_info.state == "step2-selecting"){
	    selector = "#radio-group > div:nth-of-type(2)";
	    
	    // update the radios
		let all_elem = document.querySelectorAll(selector+" > label");
		Array.from(all_elem).forEach(item => {
			channel = item.querySelector("input").value;
			left = channel_info.inputDict[channel].css_position[0];
			bottom = channel_info.inputDict[channel].css_position[1];
			
			item.style.cssText = `position: absolute; left: ${left}; bottom: ${bottom};`;
			item.className = "";
			item.querySelector(":scope > span").innerText = "";
		});
	}else if(stage1_info.state == "step3-2-selecting"){
	    selector = "#chkbox-group > div:nth-of-type(2)";
	}else return;
	
	// update the indication
	channel = stage1_info.missingTemplates[stage1_info["fillingCount"]-1];
	left = channel_info.templateDict[channel].css_position[0];
	bottom = channel_info.templateDict[channel].css_position[1];
	
	let dot_rule = `
		${selector}::before {
			content: "";
			position: absolute;
			background-color: red;
			width: 10px;
			height: 10px;
			border-radius: 50%;
			left: ${left};
			bottom: ${bottom};
		}
	`;
	
	left = parseFloat(left.slice(0, -1))+2.5;
	left = left.toString()+"%";
	bottom = parseFloat(bottom.slice(0, -1))-1;
	bottom = bottom.toString()+"%";
	let txt_rule = `
		${selector}::after {
			content: "${channel}";
			position: absolute;
			color: red;
			left: ${left};
			bottom: ${bottom};
		}
	`;
	
	// update the rules
	const styleSheet = document.styleSheets[0];
	for(let i=0; i<styleSheet.cssRules.length; i++){
		let tmp = styleSheet.cssRules[i].selectorText;
		if(tmp==selector+"::before" || tmp==selector+"::after"){
			styleSheet.deleteRule(i);
			i--;
		}
	}
	styleSheet.insertRule(dot_rule, styleSheet.cssRules.length);
	styleSheet.insertRule(txt_rule, styleSheet.cssRules.length);
}
"""

with gr.Blocks() as demo:

	app_info_json = gr.JSON(visible=False)
	channel_info_json = gr.JSON(visible=False)

	gr.Markdown(intro)
	with gr.Row():

		with gr.Column():
			with gr.Row(variant='panel'):
				with gr.Column():
					gr.Markdown("# 1.Channel Mapping")
					# --------------------input----------------------
					in_loc_file = gr.File(label="Channel locations (.loc, .locs, .xyz, .sfp, .txt)",
									file_types=[".loc", "locs", ".xyz", ".sfp", ".txt"])
					map_btn = gr.Button("Map")
					# -------------------mapping---------------------
					desc_md = gr.Markdown(visible=False)
					# step1 : initial matching and scaling
					with gr.Row():
						tpl_img = gr.Image("./template_montage.png", label="Template montage", visible=False)
						mapped_img = gr.Image(label="Matching results", visible=False)
					# step2 : forward unmatched input channels to empty template channels
					radio_group = gr.Radio(elem_id="radio-group", visible=False)
					# step3 : fill the remaining template channels
					with gr.Row():
						in_fillmode = gr.Dropdown(choices=["mean", "zero"],
													value="mean",
													label="Filling method",
													visible=False,
													scale=2)
						fillmode_btn = gr.Button("OK", visible=False, scale=1)
					chkbox_group = gr.CheckboxGroup(elem_id="chkbox-group", visible=False)
					# step4 : mapping results
					out_json_file = gr.File(visible=False)
					res_md = gr.Markdown("""
					(Download this file if you plan to run the models using the <a href="">source code</a>.)
					""", visible=False)
					
					with gr.Row():
						clear_btn = gr.Button("Clear", visible=False)
						step2_btn = gr.Button("Next", visible=False)
						step3_btn = gr.Button("Next", visible=False)
						next_btn = gr.Button("Next step", visible=False)
					# -----------------------------------------------

		with gr.Column():
			with gr.Row(variant='panel'):
				with gr.Column():
					gr.Markdown("# 2.Decode Data")
					# --------------------input----------------------
					with gr.Row():
						in_data_file = gr.File(label="Raw data (.csv)", file_types=[".csv"])
						with gr.Column():
							in_samplerate = gr.Textbox(label="Sampling rate (Hz)")
							in_modelname = gr.Dropdown(choices=[
												("ART", "EEGART"),
												("IC-U-Net", "ICUNet"),
												("IC-U-Net++", "UNetpp"),
												("IC-U-Net-Attn", "AttUnet")],
												#"(mapped data)"],
												value="EEGART",
												label="Model")
							run_btn = gr.Button(interactive=False)
					# --------------------output---------------------
					batch_md = gr.Markdown(visible=False)
					out_data_file = gr.File(label="Denoised data", visible=False)
					# -----------------------------------------------
				
	with gr.Row():
		with gr.Tab("README"):
			gr.Markdown(readme)
		with gr.Tab("ART"):
			gr.Markdown()
		with gr.Tab("IC-U-Net"):
			gr.Markdown(icunet)
		with gr.Tab("IC-U-Net++"):
			gr.Markdown()
		with gr.Tab("IC-U-Net-Attn"):
			gr.Markdown()
	
	# +========================================================================================+
	# |                                Stage1: channel mapping                                 |
	# +========================================================================================+
	def reset_all(in_loc):
		# establish a new folder for the current session
		rootpath = os.path.dirname(str(in_loc))
		try:
			os.mkdir(rootpath+"/session_data/")
		except OSError as e:
			utils.dataDelete(rootpath+"/session_data/")
			os.mkdir(rootpath+"/session_data/")
			#print(e)
		os.mkdir(rootpath+"/session_data/stage1/")
		os.mkdir(rootpath+"/session_data/stage2/")
		
		# initialize channel_info, app_info
		channel_info = {}
		app_info = {
			"rootPath" : rootpath+"/session_data/",
			"stage1" : {
				"filePath" : rootpath+"/session_data/stage1/",
				"fileNames" : {
					"input_loc" : in_loc,
					"input_montage" : "",
		    		"mapped_montage" : ""
				},
				"state" : "step1-initializing",
				"fillingCount" : None,
				"totalFillingNum" : None,
	    		"unassignedInputs" : None,
	    		"missingTemplates" : None,
	    		"mappingData" : [
	    		{
					"newOrder" : None,
					"fillFlags" : None,
					#"channelUsageNum" : None
				}
	    		]
			},
			"stage2" : {
				"filePath" : rootpath+"/session_data/stage2/",
				"fileNames" : {
					"input_data" : "",
					"output_data" : ""
				},
				"sampleRate" : None,
				"totalBatchNum" : None
			}
		}
		return {app_info_json : app_info,
				channel_info_json : channel_info,
				# --------------------Stage1-------------------------
				map_btn : gr.Button(interactive=False),
				desc_md : gr.Markdown(visible=False),
				next_btn : gr.Button(visible=False),
				tpl_img : gr.Image(visible=False),
				mapped_img : gr.Image(value=None, visible=False),
				radio_group : gr.Radio(choices=[], value=[], label="", visible=False),
				clear_btn : gr.Button(visible=False),
				step2_btn : gr.Button(visible=False),
				in_fillmode : gr.Dropdown(value="mean", visible=False),
				fillmode_btn : gr.Button(visible=False),
				chkbox_group : gr.CheckboxGroup(choices=[], value=[], label="", visible=False),
				step3_btn : gr.Button(visible=False),
				out_json_file : gr.File(value=None, visible=False),
				res_md : gr.Markdown(visible=False),
				# --------------------Stage2-------------------------
				in_data_file : gr.File(value=None),
				in_samplerate : gr.Textbox(value=None),
				run_btn : gr.Button(interactive=False),
				batch_md : gr.Markdown(visible=False),
				out_data_file : gr.File(value=None, visible=False)}
	
	
	# +========================================================================================+
	# |                                 manage step transition                                 |
	# +========================================================================================+
	def init_next_step(app_info, channel_info, fillmode, selected_radio, selected_chkbox):
		stage1_info = app_info["stage1"]
		stage2_info = app_info["stage2"]
		filepath = stage1_info["filePath"]
		
		# ========================================step0=========================================
		# step0 to step1
		if stage1_info["state"] == "step1-initializing":
			yield {desc_md : gr.Markdown("Mapping...", visible=True)}
		    
			# match the names
			stage1_info, channel_info, tpl_montage, in_montage = app_utils.match_names(stage1_info, channel_info)
			# scale the coordinates
			channel_info = app_utils.align_coords(channel_info, tpl_montage, in_montage)
			# generate and save figures of the montages
			filename1 = filepath+"input_montage_"+str(random.randint(1,10000))+".png"
			filename2 = filepath+"mapped_montage_"+str(random.randint(1,10000))+".png"
			channel_info = app_utils.save_figures(channel_info, tpl_montage, filename1, filename2)
			stage1_info["fileNames"].update({
				"input_montage" : filename1,
				"mapped_montage" : filename2
			})
			
			unassigned_num = len(stage1_info["unassignedInputs"])
			if unassigned_num == 0:
				md = """
				### Step1: Initial Matching and Scaling
				Below is the result of mapping your channels to our template channels based on their names.
				"""
			else:
				md = """
				### Step1: Initial Matching and Scaling
				Below is the result of mapping your channels to our template channels based on their names.  
				- channels highlighted in red are those that do not match any template channels.
				"""
			stage1_info["state"] = "step1-finished"
			app_info["stage1"] = stage1_info
			yield {app_info_json : app_info,
					channel_info_json : channel_info,
					map_btn : gr.Button(interactive=True),
					desc_md : gr.Markdown(md),
					tpl_img : gr.Image(visible=True),
					mapped_img : gr.Image(value=filename2, visible=True),
					next_btn : gr.Button(visible=True)}
		
		# ========================================step1=========================================
		elif stage1_info["state"] == "step1-finished":
			in_num = len(channel_info["inputOrder"])
			matched_num = 30 - len(stage1_info["missingTemplates"])
			
			# step1 to step4
			# the in_channels has all the 30 tpl_channels (in_num>=30)
			if matched_num == 30:
				md = """
				### Mapping Results
				The mapping process has been finished.
				"""
				# finalize and save the mapping results
				filename = filepath+"mapping_result.json"
				stage1_info, stage2_info, channel_info = app_utils.mapping_result(
																		stage1_info, stage2_info, channel_info, filename)
				stage1_info["state"] = "finished"
				app_info["stage1"] = stage1_info
				app_info["stage2"] = stage2_info
				yield {app_info_json : app_info,
						channel_info_json : channel_info,
						desc_md : gr.Markdown(md),
						tpl_img : gr.Image(visible=False),
						mapped_img : gr.Image(visible=False),
						next_btn : gr.Button(visible=False),
						out_json_file : gr.File(filename, visible=True),
						res_md : gr.Markdown(visible=True),
						run_btn : gr.Button(interactive=True)}
			
			# step1 to step2
			# matched_num < 30, and there're still some unmatched in_channels
			elif in_num > matched_num:
				md = """
				### Step2: Forwarding Unmatched Channels
				Select one of your unmatched channels to forward its data to the empty template channel 
				currently indicated in red.
				"""
				# initialize the progress indication label
				stage1_info.update({
					"fillingCount" : 1,
					"totalFillingNum" : len(stage1_info["missingTemplates"])
				})
				name = stage1_info["missingTemplates"][0]
				label = "{} (1/{})".format(name, stage1_info["totalFillingNum"])
				
				stage1_info["state"] = "step2-selecting"
				app_info["stage1"] = stage1_info
				# determine which button to display
				if stage1_info["totalFillingNum"] == 1:
					yield {app_info_json : app_info,
							desc_md : gr.Markdown(md),
							tpl_img : gr.Image(visible=False),
							mapped_img : gr.Image(visible=False),
							radio_group : gr.Radio(choices=stage1_info["unassignedInputs"], value=[], label=label, visible=True),
							clear_btn : gr.Button(visible=True)}
				else:
					yield {app_info_json : app_info,
							desc_md : gr.Markdown(md),
							tpl_img : gr.Image(visible=False),
							mapped_img : gr.Image(visible=False),
							radio_group : gr.Radio(choices=stage1_info["unassignedInputs"], value=[], label=label, visible=True),
							clear_btn : gr.Button(visible=True),
							step2_btn : gr.Button(visible=True),
							next_btn : gr.Button(visible=False)}
			
			# step1 to step3-1
			# in_num < 30, but all of them can match to some tpl_channels
			elif in_num == matched_num:
				md = """
				### Step3: Filling Remaining Template Channels
				Select one of the methods provided below to fill the remaining empty template channels.
				"""
				stage1_info["state"] = "step3-select-method"
				app_info["stage1"] = stage1_info
				yield {app_info_json : app_info,
						desc_md : gr.Markdown(md),
						tpl_img : gr.Image(visible=False),
						mapped_img : gr.Image(visible=False),
						in_fillmode : gr.Dropdown(visible=True),
						fillmode_btn : gr.Button(visible=True),
						next_btn : gr.Button(visible=False)}
		
		# ========================================step2=========================================
		elif stage1_info["state"] == "step2-selecting":
		
			# --------------------store information before the button click---------------------
			# check if the user has selected an in_channel to forward to the previous target tpl_channel
			if selected_radio != []:
				prev_target_name = stage1_info["missingTemplates"][stage1_info["fillingCount"]-1]
				prev_target_idx = channel_info["templateDict"][prev_target_name]["index"]
				selected_idx = channel_info["inputDict"][selected_radio]["index"]
				
				stage1_info["mappingData"][0]["newOrder"][prev_target_idx] = [selected_idx]
				stage1_info["mappingData"][0]["fillFlags"][prev_target_idx] = False
				channel_info["templateDict"][prev_target_name]["matched"] = True
				channel_info["inputDict"][selected_radio]["assigned"] = True				
				#print(prev_target_name, '<-', selected_radio)
			
			# -----------------------update information for the next step-----------------------
			# update the list of unassignedInputs to exclude the selected in_channel of the previous round
			stage1_info["unassignedInputs"] = app_utils.get_unassigned_inputs(channel_info["inputOrder"],
																			  channel_info["inputDict"])
			# update the list of missingTemplates to exclude those filled in step2
			stage1_info["missingTemplates"] = app_utils.get_empty_templates(channel_info["templateOrder"],
																			channel_info["templateDict"])
			# -----------------------------determine the next step------------------------------
			# step2 to step4
			# all the unmatched tpl_channels were filled
			if len(stage1_info["missingTemplates"]) == 0:
				md = """
				### Mapping Results
				The mapping process has been finished.
				"""
				# finalize and save the mapping results
				filename = filepath+"mapping_result.json"
				stage1_info, stage2_info, channel_info = app_utils.mapping_result(
																		stage1_info, stage2_info, channel_info, filename)
				stage1_info["state"] = "finished"
				app_info["stage1"] = stage1_info
				app_info["stage2"] = stage2_info
				yield {app_info_json : app_info,
						channel_info_json : channel_info,
						desc_md : gr.Markdown(md),
						radio_group : gr.Radio(visible=False),
						out_json_file : gr.File(filename, visible=True),
						res_md : gr.Markdown(visible=True),
						clear_btn : gr.Button(visible=False),
						next_btn : gr.Button(visible=False),
						run_btn : gr.Button(interactive=True)}
			# step2 to step3-1
			else:
				md = """
				### Step3: Filling Remaining Template Channels
				Select one of the methods provided below to fill the remaining empty template channels.
				"""
				stage1_info["state"] = "step3-select-method"
				app_info["stage1"] = stage1_info
				yield {app_info_json : app_info,
						channel_info_json : channel_info,
						desc_md : gr.Markdown(md),
						radio_group : gr.Radio(visible=False),
						in_fillmode : gr.Dropdown(visible=True),
						fillmode_btn : gr.Button(visible=True),
						clear_btn : gr.Button(visible=False),
						next_btn : gr.Button(visible=False)}
		
		# =======================================step3-1========================================
		elif stage1_info["state"] == "step3-select-method":
			
			# step3-1 to step4
			if fillmode == "zero":
				md = """
				### Mapping Results
				The mapping process has been finished.
				"""
				# finalize and save the mapping results
				filename = filepath+"mapping_result.json"
				stage1_info, stage2_info, channel_info = app_utils.mapping_result(
																		stage1_info, stage2_info, channel_info, filename)
				stage1_info["state"] = "finished"
				app_info["stage1"] = stage1_info
				app_info["stage2"] = stage2_info
				yield {app_info_json : app_info,
						channel_info_json : channel_info,
						desc_md : gr.Markdown(md),
						in_fillmode : gr.Dropdown(visible=False),
						fillmode_btn : gr.Button(visible=False),
						out_json_file : gr.File(filename, visible=True),
						res_md : gr.Markdown(visible=True),
						run_btn : gr.Button(interactive=True)}
			# step3-1 to step3-2
			elif fillmode == "mean":
				md = """
				### Step3: Fill the remaining template channels
				The current empty template channel, indicated in red, will be filled with the average 
				value of the data from the selected channels. (By default, the 4 nearest channels are pre-selected.)
				"""
				# find the 4 nearest in_channels for each unmatched tpl_channels
				stage1_info["mappingData"][0]["newOrder"] = app_utils.find_neighbors(
																		channel_info,
																		stage1_info["missingTemplates"],
																		stage1_info["mappingData"][0]["newOrder"])
				# initialize the progress indication label
				stage1_info.update({
					"fillingCount" : 1,
					"totalFillingNum" : len(stage1_info["missingTemplates"])
				})
				target_name = stage1_info["missingTemplates"][0]
				chkbox_label = "{} (1/{})".format(target_name, stage1_info["totalFillingNum"])
				
				target_idx = channel_info["templateDict"][target_name]["index"]
				chkbox_value = stage1_info["mappingData"][0]["newOrder"][target_idx]
				chkbox_value = [channel_info["inputOrder"][i] for i in chkbox_value]
				
				stage1_info["state"] = "step3-2-selecting"
				app_info["stage1"] = stage1_info
				# determine which button to display
				if stage1_info["totalFillingNum"] == 1:
					yield {app_info_json : app_info,
					        desc_md : gr.Markdown(md),
							in_fillmode : gr.Dropdown(visible=False),
				    		fillmode_btn : gr.Button(visible=False),
				    		chkbox_group : gr.CheckboxGroup(choices=channel_info["inputOrder"],
															value=chkbox_value, label=chkbox_label, visible=True),
				            next_btn : gr.Button(visible=True)}
				else:
					yield {app_info_json : app_info,
					        desc_md : gr.Markdown(md),
							in_fillmode : gr.Dropdown(visible=False),
				    		fillmode_btn : gr.Button(visible=False),
				    		chkbox_group : gr.CheckboxGroup(choices=channel_info["inputOrder"],
															value=chkbox_value, label=chkbox_label, visible=True),
				            step3_btn : gr.Button(visible=True)}
		
		# =======================================step3-2========================================
		# step3-2 to step4
		elif stage1_info["state"] == "step3-2-selecting":
			
			# --------------------store information before the button click---------------------
			# check if the user didn't uncheck all in_channel checkboxes
			if selected_chkbox != []:
				prev_target_name = stage1_info["missingTemplates"][stage1_info["fillingCount"]-1]
				prev_target_idx = channel_info["templateDict"][prev_target_name]["index"]
				selected_indices = [channel_info["inputDict"][channel]["index"] for channel in selected_chkbox]
				
				stage1_info["mappingData"][0]["newOrder"][prev_target_idx] = selected_indices
				#print(f'{prev_target_name}({prev_target_idx}): {selected_indices}')
			# ----------------------------------------------------------------------------------
			md = """
			### Mapping Results
			The mapping process has been finished.
			"""
			# finalize and save the mapping results
			filename = filepath+"mapping_result.json"
			stage1_info, stage2_info, channel_info = app_utils.mapping_result(
																	stage1_info, stage2_info, channel_info, filename)
			stage1_info["state"] = "finished"
			app_info["stage1"] = stage1_info
			app_info["stage2"] = stage2_info
			yield {app_info_json : app_info,
					channel_info_json : channel_info,
					desc_md : gr.Markdown(md),
					chkbox_group : gr.CheckboxGroup(visible=False),
					next_btn : gr.Button(visible=False),
					out_json_file : gr.File(filename, visible=True),
					res_md : gr.Markdown(visible=True),
					run_btn : gr.Button(interactive=True)}
	
	next_btn.click(
		fn = init_next_step,
		inputs = [app_info_json, channel_info_json, in_fillmode, radio_group, chkbox_group],
		outputs = [app_info_json, channel_info_json, desc_md, tpl_img, mapped_img, radio_group, clear_btn, step2_btn,
		            in_fillmode, fillmode_btn, chkbox_group, step3_btn, out_json_file, res_md, next_btn, run_btn]
	).success(
	    fn = None,
	    js = init_js,
	    inputs = [app_info_json, channel_info_json],
		outputs = []
	)
	
	
	# +========================================================================================+
	# |                                      Stage1-step0                                      |
	# +========================================================================================+
	map_btn.click(
	    fn = reset_all,
	    inputs = in_loc_file,
	    outputs = [app_info_json, channel_info_json, map_btn, desc_md, next_btn, tpl_img, mapped_img,
	    			radio_group, clear_btn, step2_btn, in_fillmode, fillmode_btn, chkbox_group, step3_btn,
	    			out_json_file, res_md, in_data_file, in_samplerate, run_btn, batch_md, out_data_file]
	).success(
	    fn = init_next_step,
	    inputs = [app_info_json, channel_info_json, in_fillmode, radio_group, chkbox_group], 
		outputs = [app_info_json, channel_info_json, map_btn, desc_md, tpl_img, mapped_img, next_btn]
	)
	
	
	# +========================================================================================+
	# |                                      Stage1-step2                                      |
	# +========================================================================================+
	# determine which button to display based on the current state
	@radio_group.select(inputs = app_info_json, outputs = [step2_btn, next_btn])
	def determine_button(app_info):
		stage1_info = app_info["stage1"]
		if len(stage1_info["unassignedInputs"]) == 1:
			return {step2_btn : gr.Button(visible=False),
					next_btn : gr.Button(visible=True)}
		else:
			return {step2_btn : gr.Button()} # change nothing
	# clear the selected value and reset the buttons
	@clear_btn.click(inputs = app_info_json, outputs = [radio_group, step2_btn, next_btn])
	def clear_value(app_info):
		stage1_info = app_info["stage1"]
		if len(stage1_info["unassignedInputs"])==1 and stage1_info["fillingCount"]<stage1_info["totalFillingNum"]:
			return {radio_group : gr.Radio(value=[]),
					step2_btn : gr.Button(visible=True),
					next_btn : gr.Button(visible=False)}
		else:
			return {radio_group : gr.Radio(value=[])}
	
	def update_radio(app_info, channel_info, selected):
		stage1_info = app_info["stage1"]
		# ----------------------store information before the button click-----------------------
		# check if the user has selected an in_channel to forward to the previous target tpl_channel
		if selected != []:
			prev_target_name = stage1_info["missingTemplates"][stage1_info["fillingCount"]-1]
			prev_target_idx = channel_info["templateDict"][prev_target_name]["index"]
			selected_idx = channel_info["inputDict"][selected]["index"]
			
			stage1_info["mappingData"][0]["newOrder"][prev_target_idx] = [selected_idx]
			stage1_info["mappingData"][0]["fillFlags"][prev_target_idx] = False
			channel_info["templateDict"][prev_target_name]["matched"] = True
			channel_info["inputDict"][selected]["assigned"] = True
			#print(prev_target_name, '<-', selected)
		
		# ------------------------update information for the new round--------------------------
		stage1_info["fillingCount"] += 1
		
		# update the list of unassignedInputs to exclude the selected in_channel of the previous round
		stage1_info["unassignedInputs"] = app_utils.get_unassigned_inputs(channel_info["inputOrder"], channel_info["inputDict"])
		
		target_name = stage1_info["missingTemplates"][stage1_info["fillingCount"]-1]
		radio_label = "{} ({}/{})".format(target_name, stage1_info["fillingCount"], stage1_info["totalFillingNum"])
		
		app_info["stage1"] = stage1_info
		# determine which button to display
		if stage1_info["fillingCount"] == stage1_info["totalFillingNum"]:
			return {app_info_json : app_info,
					channel_info_json : channel_info,
					radio_group : gr.Radio(choices=stage1_info["unassignedInputs"],
					                        value=[], label=radio_label),
					step2_btn : gr.Button(visible=False),
					next_btn : gr.Button(visible=True)}
		else:
			return {app_info_json : app_info,
					channel_info_json : channel_info,
					radio_group : gr.Radio(choices=stage1_info["unassignedInputs"],
					                        value=[], label=radio_label)}
	
	step2_btn.click(
	    fn = update_radio,
	    inputs = [app_info_json, channel_info_json, radio_group],
	    outputs = [app_info_json, channel_info_json, radio_group, step2_btn, next_btn]
	).success(
	    fn = None,
	    js = update_js,
	    inputs = [app_info_json, channel_info_json],
		outputs = []
	)
	
	
	# +========================================================================================+
	# |                                      Stage1-step3                                      |
	# +========================================================================================+	
	def update_chkbox(app_info, channel_info, selected):
		stage1_info = app_info["stage1"]
		# ----------------------store information before the button click-----------------------
		# check if the user didn't uncheck all in_channel checkboxes
		if selected != []:
			prev_target_name = stage1_info["missingTemplates"][stage1_info["fillingCount"]-1]
			prev_target_idx = channel_info["templateDict"][prev_target_name]["index"]
			selected_indices = [channel_info["inputDict"][channel]["index"] for channel in selected]
			
			stage1_info["mappingData"][0]["newOrder"][prev_target_idx] = selected_indices
			#print(f'{prev_target_name}({prev_target_idx}): {selected_indices}')
		
		# ------------------------update information for the new round--------------------------
		stage1_info["fillingCount"] += 1
		
		target_name = stage1_info["missingTemplates"][stage1_info["fillingCount"]-1]
		chkbox_label = "{} ({}/{})".format(target_name, stage1_info["fillingCount"], stage1_info["totalFillingNum"])
		
		target_idx = channel_info["templateDict"][target_name]["index"]
		chkbox_value = stage1_info["mappingData"][0]["newOrder"][target_idx]
		chkbox_value = [channel_info["inputOrder"][i] for i in chkbox_value]
		
		app_info["stage1"] = stage1_info
		# determine which button to display
		if stage1_info["fillingCount"] == stage1_info["totalFillingNum"]:
			return {app_info_json : app_info,
					chkbox_group : gr.CheckboxGroup(value=chkbox_value, label=chkbox_label),
					step3_btn : gr.Button(visible=False),
					next_btn : gr.Button(visible=True)}
		else:
			return {app_info_json : app_info,
					chkbox_group : gr.CheckboxGroup(value=chkbox_value, label=chkbox_label)}
	
	fillmode_btn.click(
	    fn = init_next_step,
		inputs = [app_info_json, channel_info_json, in_fillmode, radio_group, chkbox_group],
		outputs = [app_info_json, channel_info_json, desc_md, in_fillmode, fillmode_btn, chkbox_group, step3_btn,
					out_json_file, res_md, next_btn, run_btn]
	).success(
	    fn = None,
	    js = init_js,
	    inputs = [app_info_json, channel_info_json],
		outputs = []
	)
	
	step3_btn.click(
	    fn = update_chkbox,
	    inputs = [app_info_json, channel_info_json, chkbox_group],
	    outputs = [app_info_json, chkbox_group, step3_btn, next_btn]
	).success(
	    fn = None,
	    js = update_js,
	    inputs = [app_info_json, channel_info_json],
		outputs = []
	)
	
	
	# +========================================================================================+
	# |                                  Stage2: decode data                                   |
	# +========================================================================================+
	def reset_run(app_info, in_data, samplerate, modelname):
		stage1_info = app_info["stage1"]
		stage2_info = app_info["stage2"]
	    
	    # delete the previous folder of Stage2
		filepath = stage2_info["filePath"]
		utils.dataDelete(filepath)
		# establish a new folder for Stage2
		new_filepath = app_info["rootPath"]+"stage2_"+str(random.randint(1,10000))+"/"
		os.mkdir(new_filepath)
		# generate the output filename
		filename = os.path.basename(str(in_data))
		new_filename = os.path.splitext(filename)[0]+'_'+modelname+'.csv'
		
		stage2_info.update({
			"filePath" : new_filepath,
			"fileNames" : {
				"input_data" : in_data,
				"output_data" : new_filepath + new_filename
			},
			"sampleRate" : int(samplerate)
		})
		app_info["stage2"] = stage2_info
		return {app_info_json : app_info,
				#run_btn : gr.Button(interactive=False),
				batch_md : gr.Markdown(visible=False),
				out_data_file : gr.File(visible=False)}
	
	def run_model(app_info, modelname):
		stage1_info = app_info["stage1"]
		stage2_info = app_info["stage2"]
		
		filepath = stage2_info["filePath"]
		samplerate = stage2_info["sampleRate"]
		filename = stage2_info["fileNames"]["input_data"]
		new_filename = stage2_info["fileNames"]["output_data"]
		
		break_flag = False # indicate if the process has been interrupted by the user
		for i in range(stage2_info["totalBatchNum"]):
			# establish a temp folder
			try:
				os.mkdir(filepath+"temp_data/")
			#except FileExistsError:
				#utils.dataDelete(filepath+"temp_data/")
				#os.mkdir(filepath+"temp_data/")
			except FileNotFoundError:
				print('break1')
				break_flag = True
				break
			except OSError as e:
				print(e)
			
			# update the running status
			md = "Running model({}/{})...".format(i+1, stage2_info["totalBatchNum"])
			yield {batch_md : gr.Markdown(md, visible=True)}
			
			# get the mapped index order and the filled status for each tpl_channels
			new_idx = stage1_info["mappingData"][i]["newOrder"]
			fill_flags = stage1_info["mappingData"][i]["fillFlags"]
			# ----------------------------------------------------------------------------------
			try:
				# step1: Reorder input data
				data_shape = app_utils.reorder_data(new_idx, fill_flags, filename, filepath+"temp_data/mapped.csv")
				# step2: Data preprocessing
				total_file_num = utils.preprocessing(filepath+"temp_data/", "mapped.csv", samplerate)
				# step3: Signal reconstruction
				utils.reconstruct(modelname, total_file_num, filepath+"temp_data/", "denoised.csv", samplerate)
				# step4: Restore original order
				app_utils.restore_order(i, data_shape, new_idx, fill_flags, filepath+"temp_data/denoised.csv", new_filename)
			except FileNotFoundError:
				print('break2')
				break_flag = True
				break
			# ----------------------------------------------------------------------------------
			utils.dataDelete(filepath+"temp_data/")
		
		if break_flag == True:
			yield {batch_md : gr.Markdown(visible=False)}
		else:
			yield {#run_btn : gr.Button(interactive=True),
					batch_md : gr.Markdown(visible=False),
					out_data_file : gr.File(new_filename, visible=True)}
	
	run_btn.click(
		fn = reset_run,
		inputs = [app_info_json, in_data_file, in_samplerate, in_modelname],
		outputs = [app_info_json, run_btn, batch_md, out_data_file]
		
	).success(
		fn = run_model,
		inputs = [app_info_json, in_modelname],
		outputs = [run_btn, batch_md, out_data_file]
	)
	
if __name__ == "__main__":
    demo.launch()