Spaces:
Sleeping
Sleeping
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 | |
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 | |
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() | |