AIEEG / app.py
audrey06100's picture
update
93b494a
raw
history blame
39 kB
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()