Spaces:
Sleeping
Sleeping
File size: 39,008 Bytes
3566452 b9eaea7 4728dd2 44cad58 94ae045 b1a6869 71e2a20 d91102e b89e03e d91102e 4408bec d91102e dadd12e 4734edd b1a6869 8119410 d91102e dfff50a b1a3cc1 f994ab3 2cb93fb 8119410 3e5ef51 8119410 2cb93fb 8119410 3e5ef51 8119410 356e41c 8119410 3566452 d91102e 2cb93fb 3566452 d91102e 2cb93fb b9816ab 3e5ef51 8119410 b9816ab fe4e8b5 1fb1b4e dfff50a fe4e8b5 b9eaea7 83b7c6a 0f679e8 884c10b 83b7c6a e59c290 83b7c6a 857bb0f 8b18526 83b7c6a 3566452 3e5ef51 83b7c6a 7a54f74 857bb0f 83b7c6a 7a54f74 8b18526 6ce7643 8b18526 7a54f74 a22369d 83b7c6a 3e5ef51 8b18526 83b7c6a 4463626 83b7c6a 8b18526 e59c290 3e5ef51 83b7c6a 884c10b 857bb0f 4463626 a2a070a 8b18526 857bb0f 884c10b a22369d a2a070a 8b18526 a2a070a 8b18526 a2a070a 884c10b a2a070a 884c10b a2a070a 884c10b a2a070a a22369d 7d67389 0f679e8 884c10b a22369d 83b7c6a 32b85fc 83b7c6a 857bb0f 8b18526 efd7fc6 83b7c6a 3e5ef51 8b18526 83b7c6a 4463626 83b7c6a 8b18526 83b7c6a 3e5ef51 83b7c6a 3566452 3e5ef51 efd7fc6 83b7c6a 4734edd 32b85fc 4463626 a2a070a 8b18526 a2a070a 884c10b a22369d a2a070a 8b18526 a2a070a 8b18526 a2a070a 857bb0f 884c10b a2a070a 884c10b a2a070a 884c10b a2a070a 7a54f74 fe4e8b5 64d9ce3 fe4e8b5 7681112 fe4e8b5 a22369d b9816ab 5e68958 b9816ab 5e68958 db94983 5e68958 b9816ab 5e68958 b9816ab 9fb4a28 5e68958 db94983 5e68958 9fb4a28 5e68958 9fb4a28 5e68958 b9816ab 5e68958 b9816ab 5e68958 b9816ab 5e68958 d91102e 5e68958 b9816ab 5e68958 b9816ab fe4e8b5 6598d76 a22369d fe4e8b5 a22369d fe4e8b5 857bb0f 3566452 b221fea 0f679e8 8d3606f d941b9c 0f679e8 44cad58 d91102e 44cad58 861c9e0 44cad58 0f679e8 9361bcd a22369d 0f679e8 9361bcd 0f679e8 6ce7643 857bb0f 0f679e8 32b85fc efd7fc6 32b85fc efd7fc6 32b85fc 0f679e8 efd7fc6 2f42d70 0f679e8 9fb4a28 0f679e8 857bb0f 0f679e8 884c10b 0f679e8 64d9ce3 3566452 857bb0f 0f679e8 3566452 8119410 8b18526 a2a070a 3566452 9361bcd a2a070a 3566452 d91102e 251d442 ef20573 b9816ab 0f679e8 f994ab3 a22369d a2a070a 857bb0f 73dadfd 857bb0f 0f679e8 3566452 d91102e 2cb93fb 8206bc7 b1a3cc1 3566452 d91102e 6ce7643 3566452 2e24354 3566452 857bb0f b1a3cc1 3566452 857bb0f 3566452 857bb0f b1a3cc1 3566452 857bb0f 3566452 64d9ce3 857bb0f 3566452 8119410 857bb0f a22369d 3566452 857bb0f 3566452 2cb93fb b9816ab 2cb93fb 3566452 6ce7643 0f679e8 3566452 64d9ce3 2cb93fb 3566452 ba1c502 fcafb9d 9fb4a28 3566452 2cb93fb be921ab efd7fc6 32b85fc 3566452 be921ab 3566452 be921ab 64d9ce3 3566452 64d9ce3 3566452 fcafb9d 3566452 b9816ab 3566452 64d9ce3 3566452 a22369d 3566452 857bb0f be921ab b9816ab 857bb0f be921ab 857bb0f 2e24354 2f42d70 4463626 1101e3a 3566452 857bb0f 2296fd1 9fb4a28 3566452 9fb4a28 3566452 857bb0f 2cb93fb b9816ab 2cb93fb 6ce7643 0f679e8 3566452 64d9ce3 2cb93fb 8b18526 3566452 a2a070a ba1c502 3566452 ef20573 857bb0f 8119410 b9816ab 857bb0f 3566452 64d9ce3 857bb0f 8b18526 857bb0f ef20573 a2a070a ef20573 3566452 2cb93fb b9816ab 2cb93fb 6ce7643 0f679e8 3566452 64d9ce3 2cb93fb 3566452 ba1c502 3566452 2f42d70 3566452 2f42d70 3566452 be921ab efd7fc6 32b85fc 3566452 be921ab 2e24354 3566452 2f42d70 3566452 be921ab 64d9ce3 3566452 64d9ce3 3566452 be921ab b9816ab 2f42d70 b9816ab 3566452 2cb93fb b9816ab 2cb93fb 6ce7643 0f679e8 3566452 64d9ce3 2cb93fb a22369d ba1c502 fe4e8b5 f1a11e6 ef20573 64d9ce3 ba1c502 ef20573 83b7c6a 64d9ce3 ef20573 a22369d 857bb0f 3566452 857bb0f 3566452 64d9ce3 d91102e b9816ab 3566452 64d9ce3 3566452 64d9ce3 0f679e8 4734edd 8119410 9fb4a28 4734edd 64d9ce3 0f679e8 32b85fc efd7fc6 8119410 0f679e8 32b85fc be921ab b9816ab 857bb0f efd7fc6 857bb0f 2e24354 2f42d70 4463626 3566452 857bb0f be921ab efd7fc6 ef20573 9fb4a28 3566452 2e24354 efd7fc6 ef20573 32b85fc 857bb0f efd7fc6 64d9ce3 857bb0f 8b18526 ef20573 3566452 ef20573 64d9ce3 857bb0f 8b18526 ef20573 64d9ce3 f1a11e6 ef20573 7d67389 64d9ce3 ef20573 a2a070a 857bb0f 3566452 0f679e8 32b85fc be921ab efd7fc6 b9816ab 2f42d70 b9816ab 857bb0f be921ab efd7fc6 ef20573 efd7fc6 2e24354 857bb0f 2f42d70 4463626 ef20573 32b85fc 857bb0f efd7fc6 64d9ce3 ef20573 3566452 ef20573 64d9ce3 ef20573 a2a070a 3566452 64d9ce3 ba1c502 a2a070a 64d9ce3 a2a070a ef20573 64d9ce3 884c10b ef20573 7d67389 64d9ce3 884c10b f1a11e6 a22369d 995c1d0 23fe20b 3566452 857bb0f ba1c502 64d9ce3 0f679e8 ba1c502 8d3606f 64d9ce3 be921ab 0f679e8 8d3606f 0f679e8 44cad58 e7a030a 41cfe38 44cad58 861c9e0 44cad58 0f679e8 9361bcd 41cfe38 d91102e 41cfe38 f1a11e6 0f679e8 9361bcd 3566452 6ce7643 b1a3cc1 44cad58 b1a3cc1 0f679e8 64d9ce3 b9816ab 41cfe38 995c1d0 0f679e8 efd7fc6 2f42d70 b1a3cc1 0f679e8 6ce7643 857bb0f 8d3606f 0f679e8 9fb4a28 e9151ee 2f42d70 94b6e02 857bb0f 9fb4a28 857bb0f 9361bcd 857bb0f 9361bcd 857bb0f 9361bcd 857bb0f 9361bcd 857bb0f 9fb4a28 857bb0f 9fb4a28 857bb0f b9816ab 857bb0f 0f679e8 64d9ce3 44cad58 b9816ab 857bb0f 995c1d0 e7a030a 0f679e8 64d9ce3 995c1d0 64d9ce3 995c1d0 a22369d b9eaea7 94b6e02 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 |
import utils
import app_utils
import gradio as gr
import os
import uuid
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 Artifact Removal**: Use our 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 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 divided 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 = """
(stage1_info, channel_info) => {
stage1_info = JSON.parse(JSON.stringify(stage1_info));
channel_info = JSON.parse(JSON.stringify(channel_info));
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.inputMontage}");
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 = """
(stage1_info, channel_info) => {
stage1_info = JSON.parse(JSON.stringify(stage1_info));
channel_info = JSON.parse(JSON.stringify(channel_info));
let selector;
let cnt, channel, left, bottom;
if(stage1_info.state == "step2-selecting"){
selector = "#radio-group > div:nth-of-type(2)";
cnt = stage1_info.step2.count
// 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)";
cnt = stage1_info.step3.count
}else return;
// update the indication
channel = stage1_info.missingTemplates[cnt-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:
stage1_json = gr.JSON(visible=False)
stage2_json = gr.JSON(visible=False)
channel_json = gr.JSON(visible=False)
gr.Markdown(intro)
with gr.Row():
with gr.Column(variant="panel"):
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")
# ---------------------output--------------------
desc_md = gr.Markdown(visible=False)
out_json_file = gr.File(visible=False)
# --------------------mapping--------------------
# step1
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
radio_group = gr.Radio(elem_id="radio-group", visible=False)
# step3
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)
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(variant="panel"):
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")],
value="EEGART",
label="Model")
run_btn = gr.Button("Run", interactive=False)
cancel_btn = gr.Button("Cancel", visible=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(stage1_info, stage2_info, in_loc):
# stop Stage2
if stage2_info!=None and stage2_info["state"]=="running":
utils.dataDelete(stage2_info["filePath"])
rootpath = os.path.dirname(str(in_loc))
# delete the previous folder(s) of Stage1
folders = [ f.path for f in os.scandir(rootpath) if f.is_dir()]
for folder in folders:
utils.dataDelete(folder)
# establish a new folder
stage1_id = uuid.uuid4().hex
os.mkdir(rootpath+'/'+stage1_id+'/')
stage1_info = {
"filePath" : rootpath+'/'+stage1_id+'/',
"fileNames" : {
"inputLocation" : in_loc,
"inputMontage" : rootpath+'/'+stage1_id+'/input_montage.png',
"mappedMontage" : rootpath+'/'+stage1_id+'/mapped_montage.png',
"outputResult" : rootpath+'/'+stage1_id+'/mapping_result.json'
},
"state" : "step1-initializing",
"step2" : {
"count" : None,
"totalNum" : None
},
"step3" : {
"count" : None,
"totalNum" : None
},
"unassignedInputs" : None,
"missingTemplates" : None,
"batchNum" : None,
"mappingResults" : [
{
"newOrder" : None,
"fillFlags" : None
#"channelUsageNum" : None
}
]
}
stage2_info = None
channel_info = None
return {stage1_json : stage1_info,
stage2_json : stage2_info,
channel_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),
# --------------------Stage2-------------------------
in_data_file : gr.File(value=None),
in_samplerate : gr.Textbox(value=None),
run_btn : gr.Button(interactive=False),
cancel_btn : gr.Button(interactive=False),
batch_md : gr.Markdown("", visible=False),
out_data_file : gr.File(value=None, visible=False)}
# +========================================================================================+
# | step transition |
# +========================================================================================+
def init_next_step(stage1_info, channel_info, fillmode, selected_radio, selected_chkbox):
# ========================================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)
# scale the coordinates
channel_info = app_utils.align_coords(channel_info, tpl_montage, in_montage)
# generate and save figures of the montages
filename1 = stage1_info["fileNames"]["inputMontage"]
filename2 = stage1_info["fileNames"]["mappedMontage"]
channel_info = app_utils.save_figures(channel_info, tpl_montage, filename1, 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"
yield {stage1_json : stage1_info,
channel_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
if matched_num == 30:
md = """
### Mapping Results
The mapping process has been finished.
Download the file below if you plan to run the models using the <a href="">source code</a>.
"""
# finalize and save the mapping results
filename = stage1_info["fileNames"]["outputResult"]
stage1_info, channel_info = app_utils.mapping_result(stage1_info, channel_info, filename)
stage1_info["state"] = "finished"
yield {stage1_json : stage1_info,
channel_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)}
# step1 to step2
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["step2"] = {
"count" : 1,
"totalNum" : len(stage1_info["missingTemplates"])
}
name = stage1_info["missingTemplates"][0]
label = '{} (1/{})'.format(name, stage1_info["step2"]["totalNum"])
stage1_info["state"] = "step2-selecting"
# determine which button to display
if stage1_info["step2"]["totalNum"] == 1:
yield {stage1_json : stage1_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 {stage1_json : stage1_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
elif in_num == matched_num:
md = """
### Step3: Filling Remaining Template Channels
Select one of the methods provided below to fill the remaining template channels.
"""
stage1_info["state"] = "step3-select-method"
yield {stage1_json : stage1_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---------------------------------
# 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["step2"]["count"]-1]
prev_target_idx = channel_info["templateDict"][prev_target_name]["index"]
selected_idx = channel_info["inputDict"][selected_radio]["index"]
stage1_info["mappingResults"][0]["newOrder"][prev_target_idx] = [selected_idx]
stage1_info["mappingResults"][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--------------------------------
# exclude the selected in_channel of the previous round
stage1_info["unassignedInputs"] = app_utils.get_unassigned_inputs(channel_info["inputOrder"],
channel_info["inputDict"])
# exclude the tpl_channels filled in step2
stage1_info["missingTemplates"] = app_utils.get_empty_templates(channel_info["templateOrder"],
channel_info["templateDict"])
# -----------------------------determine the next step------------------------------
# step2 to step4
if len(stage1_info["missingTemplates"]) == 0:
md = """
### Mapping Results
The mapping process has been finished.
Download the file below if you plan to run the models using the <a href="">source code</a>.
"""
filename = stage1_info["fileNames"]["outputResult"]
stage1_info, channel_info = app_utils.mapping_result(stage1_info, channel_info, filename)
stage1_info["state"] = "finished"
yield {stage1_json : stage1_info,
channel_json : channel_info,
desc_md : gr.Markdown(md),
radio_group : gr.Radio(visible=False),
out_json_file : gr.File(filename, visible=True),
clear_btn : gr.Button(visible=False),
next_btn : gr.Button(visible=False)}
# step2 to step3-1
else:
md = """
### Step3: Filling Remaining Template Channels
Select one of the methods provided below to fill the remaining template channels.
"""
stage1_info["state"] = "step3-select-method"
yield {stage1_json : stage1_info,
channel_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.
Download the file below if you plan to run the models using the <a href="">source code</a>.
"""
filename = stage1_info["fileNames"]["outputResult"]
stage1_info, channel_info = app_utils.mapping_result(stage1_info, channel_info, filename)
stage1_info["state"] = "finished"
yield {stage1_json : stage1_info,
channel_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)}
# 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["mappingResults"][0]["newOrder"] = app_utils.find_neighbors(
channel_info,
stage1_info["missingTemplates"],
stage1_info["mappingResults"][0]["newOrder"])
# initialize the progress indication label
stage1_info["step3"] = {
"count" : 1,
"totalNum" : len(stage1_info["missingTemplates"])
}
target_name = stage1_info["missingTemplates"][0]
chkbox_label = '{} (1/{})'.format(target_name, stage1_info["step3"]["totalNum"])
target_idx = channel_info["templateDict"][target_name]["index"]
chkbox_value = stage1_info["mappingResults"][0]["newOrder"][target_idx]
chkbox_value = [channel_info["inputOrder"][i] for i in chkbox_value]
stage1_info["state"] = "step3-2-selecting"
# determine which button to display
if stage1_info["step3"]["totalNum"] == 1:
yield {stage1_json : stage1_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 {stage1_json : stage1_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---------------------------------
prev_target_name = stage1_info["missingTemplates"][stage1_info["step3"]["count"]-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["mappingResults"][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.
Download the file below if you plan to run the models using the <a href="">source code</a>.
"""
filename = stage1_info["fileNames"]["outputResult"]
stage1_info, channel_info = app_utils.mapping_result(stage1_info, channel_info, filename)
stage1_info["state"] = "finished"
yield {stage1_json : stage1_info,
channel_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)}
next_btn.click(
fn = init_next_step,
inputs = [stage1_json, channel_json, in_fillmode, radio_group, chkbox_group],
outputs = [stage1_json, channel_json, desc_md, tpl_img, mapped_img, radio_group, clear_btn, step2_btn,
in_fillmode, fillmode_btn, chkbox_group, step3_btn, out_json_file, next_btn]
).success(
fn = None,
js = init_js,
inputs = [stage1_json, channel_json],
outputs = []
)
# +========================================================================================+
# | Stage1-step0 |
# +========================================================================================+
map_btn.click(
fn = reset_all,
inputs = [stage1_json, stage2_json, in_loc_file],
outputs = [stage1_json, stage2_json, channel_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, in_data_file, in_samplerate, run_btn, cancel_btn, batch_md, out_data_file]
).success(
fn = init_next_step,
inputs = [stage1_json, channel_json, in_fillmode, radio_group, chkbox_group],
outputs = [stage1_json, channel_json, map_btn, desc_md, tpl_img, mapped_img, next_btn]
)
# +========================================================================================+
# | Stage1-step2 |
# +========================================================================================+
@radio_group.select(inputs = stage1_json, outputs = [step2_btn, next_btn])
def determine_button(stage1_info):
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()}
# clear the selected value and reset the buttons
@clear_btn.click(inputs = stage1_json, outputs = [radio_group, step2_btn, next_btn])
def clear_value(stage1_info):
step2 = stage1_info["step2"]
if len(stage1_info["unassignedInputs"])==1 and step2["count"]<step2["totalNum"]:
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(stage1_info, channel_info, selected):
step2 = stage1_info["step2"]
# ----------------------------------store information-----------------------------------
# if the user has selected an in_channel to forward to the previous target tpl_channel
if selected != []:
prev_target_name = stage1_info["missingTemplates"][step2["count"]-1]
prev_target_idx = channel_info["templateDict"][prev_target_name]["index"]
selected_idx = channel_info["inputDict"][selected]["index"]
stage1_info["mappingResults"][0]["newOrder"][prev_target_idx] = [selected_idx]
stage1_info["mappingResults"][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 the new round---------------------------------
step2["count"] += 1
# 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"][step2["count"]-1]
radio_label = '{} ({}/{})'.format(target_name, step2["count"], step2["totalNum"])
stage1_info["step2"] = step2
# determine which button to display
if step2["count"] == step2["totalNum"]:
return {stage1_json : stage1_info,
channel_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 {stage1_json : stage1_info,
channel_json : channel_info,
radio_group : gr.Radio(choices=stage1_info["unassignedInputs"],
value=[], label=radio_label)}
step2_btn.click(
fn = update_radio,
inputs = [stage1_json, channel_json, radio_group],
outputs = [stage1_json, channel_json, radio_group, step2_btn, next_btn]
).success(
fn = None,
js = update_js,
inputs = [stage1_json, channel_json],
outputs = []
)
# +========================================================================================+
# | Stage1-step3 |
# +========================================================================================+
def update_chkbox(stage1_info, channel_info, selected):
step3 = stage1_info["step3"]
# ----------------------------------store information-----------------------------------
prev_target_name = stage1_info["missingTemplates"][step3["count"]-1]
prev_target_idx = channel_info["templateDict"][prev_target_name]["index"]
selected_indices = [channel_info["inputDict"][channel]["index"] for channel in selected]
stage1_info["mappingResults"][0]["newOrder"][prev_target_idx] = selected_indices
#print(f'{prev_target_name}({prev_target_idx}): {selected_indices}')
# ---------------------------------update the new round---------------------------------
step3["count"] += 1
target_name = stage1_info["missingTemplates"][step3["count"]-1]
chkbox_label = '{} ({}/{})'.format(target_name, step3["count"], step3["totalNum"])
target_idx = channel_info["templateDict"][target_name]["index"]
chkbox_value = stage1_info["mappingResults"][0]["newOrder"][target_idx]
chkbox_value = [channel_info["inputOrder"][i] for i in chkbox_value]
stage1_info["step3"] = step3
# determine which button to display
if step3["count"] == step3["totalNum"]:
return {stage1_json : stage1_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 {stage1_json : stage1_info,
chkbox_group : gr.CheckboxGroup(value=chkbox_value, label=chkbox_label)}
fillmode_btn.click(
fn = init_next_step,
inputs = [stage1_json, channel_json, in_fillmode, radio_group, chkbox_group],
outputs = [stage1_json, channel_json, desc_md, in_fillmode, fillmode_btn, chkbox_group, step3_btn,
out_json_file, next_btn]
).success(
fn = None,
js = init_js,
inputs = [stage1_json, channel_json],
outputs = []
)
step3_btn.click(
fn = update_chkbox,
inputs = [stage1_json, channel_json, chkbox_group],
outputs = [stage1_json, chkbox_group, step3_btn, next_btn]
).success(
fn = None,
js = update_js,
inputs = [stage1_json, channel_json],
outputs = []
)
# +========================================================================================+
# | Stage2: decode data |
# +========================================================================================+
@gr.on(triggers = [in_data_file.upload, in_data_file.clear, in_samplerate.change, out_json_file.change],
inputs = [stage1_json, in_data_file, in_samplerate], outputs = run_btn)
def check_input(stage1_info, in_data, samplerate):
if stage1_info["state"]=="finished" and in_data!=None and samplerate!="":
return gr.Button(interactive=True)
else:
return gr.Button(interactive=False)
@cancel_btn.click(inputs = stage2_json, outputs = [stage2_json, cancel_btn, batch_md])
def stop_stage2(stage2_info):
utils.dataDelete(stage2_info["filePath"])
stage2_info["state"] = "stopped"
return stage2_info, gr.Button(interactive=False), gr.Markdown(visible=False)
def reset_stage2(in_data, samplerate, modelname):
rootpath = os.path.dirname(str(in_data))
# delete the previous folder(s) of Stage2
folders = [ f.path for f in os.scandir(rootpath) if f.is_dir()]
for folder in folders:
utils.dataDelete(folder)
# establish a new folder
stage2_id = uuid.uuid4().hex
os.mkdir(rootpath+'/'+stage2_id+'/')
filename = os.path.basename(str(in_data))
new_filename = modelname+'_'+os.path.splitext(filename)[0]+'.csv'
stage2_info = {
"filePath" : rootpath+'/'+stage2_id+'/',
"fileNames" : {
"inputData" : in_data,
"outputData" : rootpath+'/'+stage2_id+'/'+new_filename
},
"state" : "running",
"sampleRate" : int(samplerate)
}
return {stage2_json : stage2_info,
run_btn : gr.Button(visible=False),
cancel_btn : gr.Button(visible=True, interactive=True),
batch_md : gr.Markdown("", visible=True),
out_data_file : gr.File(value=None, visible=False)}
def run_model(stage1_info, stage2_info, modelname):
batch_num = stage1_info["batchNum"]
mapping_results = stage1_info["mappingResults"]
samplerate = stage2_info["sampleRate"]
filepath = stage2_info["filePath"]
filename = stage2_info["fileNames"]["inputData"]
new_filename = stage2_info["fileNames"]["outputData"]
break_flag = False
for i in range(batch_num):
yield {batch_md : gr.Markdown('Running model({}/{})...'.format(i+1, batch_num))}
new_idx = mapping_results[i]["newOrder"]
fill_flags = mapping_results[i]["fillFlags"]
m_filename = 'mapped_{:02d}.csv'.format(i+1)
d_filename = 'denoised_{:02d}.csv'.format(i+1)
try:
# establish a temp folder
os.mkdir(filepath+'temp_data/')
# step1: Reorder input data
data_shape = app_utils.reorder_data(new_idx, fill_flags, filename, filepath+'temp_data/'+m_filename)
# step2: Data preprocessing
total_file_num = utils.preprocessing(filepath+'temp_data/', m_filename, samplerate)
# step3: Signal reconstruction
utils.reconstruct(modelname, total_file_num, filepath+'temp_data/', d_filename, samplerate)
# step4: Restore original order
app_utils.restore_order(i, data_shape, new_idx, fill_flags, filepath+'temp_data/'+d_filename, new_filename)
except FileNotFoundError:
print('break!!')
break_flag = True
break
else:
utils.dataDelete(filepath+'temp_data/')
if break_flag == True:
yield {run_btn : gr.Button(visible=True),
cancel_btn : gr.Button(visible=False)}
else:
stage2_info["state"] = "finished"
yield {stage2_json : stage2_info,
run_btn : gr.Button(visible=True),
cancel_btn : gr.Button(visible=False),
batch_md : gr.Markdown(visible=False),
out_data_file : gr.File(new_filename, visible=True)}
run_btn.click(
fn = reset_stage2,
inputs = [in_data_file, in_samplerate, in_modelname],
outputs = [stage2_json, run_btn, cancel_btn, batch_md, out_data_file]
).success(
fn = run_model,
inputs = [stage1_json, stage2_json, in_modelname],
outputs = [stage2_json, run_btn, cancel_btn, batch_md, out_data_file]
)
if __name__ == "__main__":
demo.launch()
|