import utils import app_utils import os import uuid import tempfile import gradio as gr gradio_temp_dir = os.path.join(tempfile.gettempdir(), 'gradio') os.makedirs(gradio_temp_dir, exist_ok=True) os.environ['GRADIO_TEMP_DIR'] = gradio_temp_dir title = """
Artifact Removal Transformer 🤗 Gradio Demo

ART: Artifact Removal Transformer for Reconstructing Noise-Free Multichannel Electroencephalographic Signals
Chun-Hsiang Chuang, Kong-Yi Chang, Chih-Sheng Huang, Anne-Mei Bessas


""" guide = """ This 🤗 Gradio Demo 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 here. 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).
❗️❗️❗️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.
❗️❗️❗️Please remove any reference, ECG, EOG, EMG, or other non-EEG channels before uploading your files. ## Step1. Channel Mapping The following steps will guide you through the process of mapping your EEG channels to our template channels. ### Step1-1: 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 Result**. - 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**. ### Step1-2: 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 Result**. - If there are still empty template channels remaining, you will be directed to **Step3**. ### Step1-3: 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 channel, 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 Result**. ### Mapping Result 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 result. - Once the mapping process is completed, a JSON file containing the mapping result will be generated. This file is necessary only if you plan to run the models using the source code; otherwise, you can ignore it. ## Step2. Data Denoising After uploading your EEG data and clicking on `Run` button, we will process your data based on the mapping result.
- 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. """ js = """ () => { const styleSheet = document.styleSheets[0]; styleSheet.insertRule(` .channel-box { position: absolute; z-index: 2; width: 2.5%; height: 2.5%; transform: translate(-50%, 50%); } `, styleSheet.cssRules.length); styleSheet.insertRule(` .channel-input { display: block !important; width: 100% !important; height: 100% !important; } `, styleSheet.cssRules.length); } """ 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; 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; const div = document.querySelector(selector); // add figure of the input montage div.style.cssText = ` position: relative; width: 100%; aspect-ratio: 1; background-image: url("file=${stage1_info.fileNames.originalMontage}"); background-position: left bottom; background-size: 100%; `; // move the radios/checkboxes let name, left, bottom; const elements = div.querySelectorAll(":scope > label"); Array.from(elements).forEach( el => { name = el.querySelector(":scope > input").getAttribute(attribute); left = channel_info.inputDict[name].css_position[0]; bottom = channel_info.inputDict[name].css_position[1]; el.className = "channel-box"; el.style.cssText = `left: ${left}%; bottom: ${bottom}%;`; el.querySelector(":scope > input").classList.add("channel-input"); el.querySelector(":scope > span").innerText = ""; }); // add indication for the first empty tpl_channel name = stage1_info.emptyTemplate[0]; left = channel_info.templateDict[name].css_position[0]; bottom = channel_info.templateDict[name].css_position[1]; const dotRule = ` ${selector}::before { content: ""; position: absolute; left: ${left}%; bottom: ${bottom}%; width: 2%; height: 2%; border-radius: 50%; background-color: red; } `; const textRule = ` ${selector}::after { content: "${name}"; position: absolute; z-index: 1; left: ${left+2.7}%; bottom: ${bottom}%; font-size: 1em; font-weight: 900; color: red; } `; // check if indicator already exist const styleSheet = document.styleSheets[0]; for(let i=0; i { stage1_info = JSON.parse(JSON.stringify(stage1_info)); channel_info = JSON.parse(JSON.stringify(channel_info)); let selector; let cnt, name, left, bottom; if(stage1_info.state == "step2-selecting"){ selector = "#radio-group > div:nth-of-type(2)"; cnt = stage1_info.step2.count; // update the radios const elements = document.querySelectorAll(selector+" > label"); Array.from(elements).forEach( el => { name = el.querySelector(":scope > input").value; left = channel_info.inputDict[name].css_position[0]; bottom = channel_info.inputDict[name].css_position[1]; el.style.cssText = `left: ${left}%; bottom: ${bottom}%;`; }); }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 name = stage1_info.emptyTemplate[cnt-1]; left = channel_info.templateDict[name].css_position[0]; bottom = channel_info.templateDict[name].css_position[1]; const dotRule = ` ${selector}::before { content: ""; position: absolute; left: ${left}%; bottom: ${bottom}%; width: 2%; height: 2%; border-radius: 50%; background-color: red; } `; const textRule = ` ${selector}::after { content: "${name}"; position: absolute; z-index: 1; left: ${left+2.7}%; bottom: ${bottom}%; font-size: 1em; font-weight: 900; color: red; } `; // update the rules const styleSheet = document.styleSheets[0]; for(let i=0; i - channels highlighted in red are those that do not match any template channels. """ stage1_info["state"] = "step1-finished" return {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-1======================================== elif stage1_info["state"] == "step1-finished": in_num = len(channel_info["inputNames"]) matched_num = 30 - len(stage1_info["emptyTemplate"]) # step1-1 to step1-4 if matched_num == 30: md = """ ### Mapping Result The mapping process has been finished.
Download the file below if you plan to run the models using the source code. """ # finalize and save the mapping result outputname = stage1_info["fileNames"]["outputData"] stage1_info, channel_info = app_utils.mapping_result(stage1_info, channel_info, outputname) stage1_info["state"] = "finished" return {stage1_json : stage1_info, channel_json : channel_info, desc_md : gr.Markdown(md), out_result_file : gr.File(outputname, visible=True), tpl_img : gr.Image(visible=False), mapped_img : gr.Image(visible=False), next_btn : gr.Button(visible=False), run_btn : gr.Button(interactive=True)} # step1-1 to step1-2 elif in_num > matched_num: md = """ ### Step1-2: 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["emptyTemplate"]) } tpl_name = stage1_info["emptyTemplate"][0] label = '{} (1/{})'.format(tpl_name, stage1_info["step2"]["totalNum"]) stage1_info["state"] = "step2-selecting" # determine which button to display if stage1_info["step2"]["totalNum"] == 1: return {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["unassignedInput"], value=[], label=label, visible=True), clear_btn : gr.Button(visible=True)} else: return {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["unassignedInput"], value=[], label=label, visible=True), clear_btn : gr.Button(visible=True), step2_btn : gr.Button(visible=True), next_btn : gr.Button(visible=False)} # step1-1 to step1-3-1 elif in_num == matched_num: md = """ ### Step1-3: Filling Remaining Template Channels Select one of the methods provided below to fill the remaining template channels. """ stage1_info["state"] = "step3-select-method" return {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)} # =======================================step1-2======================================== elif stage1_info["state"] == "step2-selecting": if sel_radio != []: stage1_info["unassignedInput"].remove(sel_radio) prev_tpl_name = stage1_info["emptyTemplate"][stage1_info["step2"]["count"]-1] prev_tpl_idx = channel_info["templateDict"][prev_tpl_name]["index"] sel_idx = channel_info["inputDict"][sel_radio]["index"] stage1_info["mappingResult"][0]["index"][prev_tpl_idx] = [sel_idx] stage1_info["mappingResult"][0]["isOriginalData"][prev_tpl_idx] = True channel_info["templateDict"][prev_tpl_name]["matched"] = True channel_info["inputDict"][sel_radio]["assigned"] = True # exclude the tpl_channels filled in step1-2 stage1_info["emptyTemplate"] = app_utils.get_empty_template(channel_info["templateNames"], channel_info["templateDict"]) # step1-2 to step1-4 if len(stage1_info["emptyTemplate"]) == 0: md = """ ### Mapping Result The mapping process has been finished.
Download the file below if you plan to run the models using the source code. """ outputname = stage1_info["fileNames"]["outputData"] stage1_info, channel_info = app_utils.mapping_result(stage1_info, channel_info, outputname) stage1_info["state"] = "finished" return {stage1_json : stage1_info, channel_json : channel_info, desc_md : gr.Markdown(md), out_result_file : gr.File(outputname, visible=True), radio_group : gr.Radio(visible=False), clear_btn : gr.Button(visible=False), next_btn : gr.Button(visible=False), run_btn : gr.Button(interactive=True)} # step1-2 to step1-3-1 else: md = """ ### Step1-3: Filling Remaining Template Channels Select one of the methods provided below to fill the remaining template channels. """ stage1_info["state"] = "step3-select-method" return {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)} # ======================================step1-3-1======================================= elif stage1_info["state"] == "step3-select-method": # step1-3-1 to step1-4 if fillmode == "zero": md = """ ### Mapping Result The mapping process has been finished.
Download the file below if you plan to run the models using the source code. """ outputname = stage1_info["fileNames"]["outputData"] stage1_info, channel_info = app_utils.mapping_result(stage1_info, channel_info, outputname) stage1_info["state"] = "finished" return {stage1_json : stage1_info, channel_json : channel_info, desc_md : gr.Markdown(md), out_result_file : gr.File(outputname, visible=True), in_fillmode : gr.Dropdown(visible=False), fillmode_btn : gr.Button(visible=False), run_btn : gr.Button(interactive=True)} # step1-3-1 to step1-3-2 elif fillmode == "mean": md = """ ### Step1-3: 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_channel stage1_info["mappingResult"][0]["index"] = app_utils.find_neighbors( channel_info, stage1_info["emptyTemplate"], stage1_info["mappingResult"][0]["index"]) # initialize the progress indication label stage1_info["step3"] = { "count" : 1, "totalNum" : len(stage1_info["emptyTemplate"]) } tpl_name = stage1_info["emptyTemplate"][0] label = '{} (1/{})'.format(tpl_name, stage1_info["step3"]["totalNum"]) tpl_idx = channel_info["templateDict"][tpl_name]["index"] value = stage1_info["mappingResult"][0]["index"][tpl_idx] value = [channel_info["inputNames"][i] for i in value] stage1_info["state"] = "step3-2-selecting" # determine which button to display if stage1_info["step3"]["totalNum"] == 1: return {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["inputNames"], value=value, label=label, visible=True), next_btn : gr.Button(visible=True)} else: return {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["inputNames"], value=value, label=label, visible=True), step3_btn : gr.Button(visible=True)} # ======================================step1-3-2======================================= # step1-3-2 to step1-4 elif stage1_info["state"] == "step3-2-selecting": prev_tpl_name = stage1_info["emptyTemplate"][stage1_info["step3"]["count"]-1] prev_tpl_idx = channel_info["templateDict"][prev_tpl_name]["index"] sel_idx = [channel_info["inputDict"][name]["index"] for name in sel_chkbox] stage1_info["mappingResult"][0]["index"][prev_tpl_idx] = sel_idx if sel_idx!=[] else [None] md = """ ### Mapping Result The mapping process has been finished.
Download the file below if you plan to run the models using the source code. """ outputname = stage1_info["fileNames"]["outputData"] stage1_info, channel_info = app_utils.mapping_result(stage1_info, channel_info, outputname) stage1_info["state"] = "finished" return {stage1_json : stage1_info, channel_json : channel_info, desc_md : gr.Markdown(md), out_result_file : gr.File(outputname, visible=True), chkbox_group : gr.CheckboxGroup(visible=False), next_btn : gr.Button(visible=False), run_btn : gr.Button(interactive=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, out_result_file, tpl_img, mapped_img, radio_group, in_fillmode, fillmode_btn, chkbox_group, clear_btn, step2_btn, step3_btn, next_btn, run_btn] ).success( fn = None, js = init_js, inputs = [stage1_json, channel_json], outputs = [] ) # +========================================================================================+ # | Stage1-step0 | # +========================================================================================+ map_btn.click( fn = reset_all, inputs = [session_dir, stage1_json, stage2_json, in_loc_file], outputs = [stage1_json, stage2_json, channel_json, map_btn, desc_md, out_result_file, tpl_img, mapped_img, radio_group, in_fillmode, fillmode_btn, chkbox_group, clear_btn, step2_btn, step3_btn, next_btn, 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["unassignedInput"]) == 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): if len(stage1_info["unassignedInput"])==1 and stage1_info["step2"]["count"]