Skip to content

Commit

Permalink
add subprocess/ fix captcha / annotate code
Browse files Browse the repository at this point in the history
  • Loading branch information
Arslan-Siraj committed Sep 21, 2023
1 parent 1d345cc commit 46d14b3
Show file tree
Hide file tree
Showing 8 changed files with 457 additions and 185 deletions.
52 changes: 6 additions & 46 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import streamlit as st
from captcha.image import ImageCaptcha
import random, string
from src.common import *
from streamlit.web import cli
from pathlib import Path
Expand All @@ -26,60 +25,21 @@ def main():
if "local" in sys.argv:
main()

else:

length_captcha = 5
width = 400
height = 180
##if docker or online mode
else:

# define the function for the captcha control
def captcha_control():
#control if the captcha is correct
if 'controllo' not in st.session_state or st.session_state['controllo'] == False:
st.title("Makesure you are not a robot🤖")

# define the session state for control if the captcha is correct
st.session_state['controllo'] = False
col1, col2 = st.columns(2)

# define the session state for the captcha text because it doesn't change during refreshes
if 'Captcha' not in st.session_state:
st.session_state['Captcha'] = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length_captcha))

#setup the captcha widget
image = ImageCaptcha(width=width, height=height)
data = image.generate(st.session_state['Captcha'])
col1.image(data)
capta2_text = col2.text_area('Enter captcha text', height=20)


if st.button("Verify the code"):
capta2_text = capta2_text.replace(" ", "")
# if the captcha is correct, the controllo session state is set to True
if st.session_state['Captcha'].lower() == capta2_text.lower().strip():
del st.session_state['Captcha']
col1.empty()
col2.empty()
st.session_state['controllo'] = True
st.experimental_rerun()
else:
# if the captcha is wrong, the controllo session state is set to False and the captcha is regenerated
st.error("🚨 Captch is wrong")
del st.session_state['Captcha']
del st.session_state['controllo']
st.experimental_rerun()
else:
#wait for the button click
st.stop()

# WORK LIKE MULTIPAGE APP
if 'controllo' not in st.session_state or st.session_state['controllo'] == False:
#delete pages
delete_page("app", "File_Upload")
delete_page("app", "View_Raw_Data")
delete_page("app", "Workflow")
#apply captcha
captcha_control()
else:
#run main
main()
#add all pages back
add_page("app", "File_Upload")
add_page("app", "View_Raw_Data")
add_page("app", "Workflow")
Expand Down
3 changes: 2 additions & 1 deletion assets/default-params.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"2D-map-intensity-cutoff": 5000,

"example-x-dimension": 10,
"example-y-dimension": 5
"example-y-dimension": 5,
"controllo": false
}
114 changes: 64 additions & 50 deletions pages/0_📁_File_Upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,67 +5,81 @@

from src.common import *
from src.fileupload import *
from src.captcha_ import *

params = page_setup()

# Make sure "selected-mzML-files" is in session state
if "selected-mzML-files" not in st.session_state:
st.session_state["selected-mzML-files"] = params["selected-mzML-files"]
#if local no need captcha
if st.session_state.location == "local":
params["controllo"] = True
st.session_state["controllo"] = True

st.title("File Upload")
#if controllo is false means not captcha applied
if 'controllo' not in st.session_state or params["controllo"] == False or st.session_state.location != "local":
#apply captcha
captcha_control()

else:
### main content of page

tabs = ["File Upload", "Example Data"]
if st.session_state.location == "local":
tabs.append("Files from local folder")
# Make sure "selected-mzML-files" is in session state
if "selected-mzML-files" not in st.session_state:
st.session_state["selected-mzML-files"] = params["selected-mzML-files"]

tabs = st.tabs(tabs)
st.title("File Upload")

with tabs[0]:
with st.form("mzML-upload", clear_on_submit=True):
files = st.file_uploader(
"mzML files", accept_multiple_files=(st.session_state.location == "local"))
cols = st.columns(3)
if cols[1].form_submit_button("Add files to workspace", type="primary"):
save_uploaded_mzML(files)
tabs = ["File Upload", "Example Data"]
if st.session_state.location == "local":
tabs.append("Files from local folder")

# Example mzML files
with tabs[1]:
st.markdown("Short information text about the example data.")
cols = st.columns(3)
if cols[1].button("Load Example Data", type="primary"):
load_example_mzML_files()
tabs = st.tabs(tabs)

# Local file upload option: via directory path
if st.session_state.location == "local":
with tabs[2]:
# with st.form("local-file-upload"):
local_mzML_dir = st.text_input(
"path to folder with mzML files")
# raw string for file paths
local_mzML_dir = r"{}".format(local_mzML_dir)
with tabs[0]:
with st.form("mzML-upload", clear_on_submit=True):
files = st.file_uploader(
"mzML files", accept_multiple_files=(st.session_state.location == "local"))
cols = st.columns(3)
if cols[1].form_submit_button("Add files to workspace", type="primary"):
save_uploaded_mzML(files)

# Example mzML files
with tabs[1]:
st.markdown("Short information text about the example data.")
cols = st.columns(3)
if cols[1].button("Copy files to workspace", type="primary", disabled=(local_mzML_dir == "")):
copy_local_mzML_files_from_directory(local_mzML_dir)
if cols[1].button("Load Example Data", type="primary"):
load_example_mzML_files()

# Local file upload option: via directory path
if st.session_state.location == "local":
with tabs[2]:
# with st.form("local-file-upload"):
local_mzML_dir = st.text_input(
"path to folder with mzML files")
# raw string for file paths
local_mzML_dir = r"{}".format(local_mzML_dir)
cols = st.columns(3)
if cols[1].button("Copy files to workspace", type="primary", disabled=(local_mzML_dir == "")):
copy_local_mzML_files_from_directory(local_mzML_dir)

if any(Path(mzML_dir).iterdir()):
v_space(2)
# Display all mzML files currently in workspace
df = pd.DataFrame(
{"file name": [f.name for f in Path(mzML_dir).iterdir()]})
st.markdown("##### mzML files in current workspace:")
show_table(df)
v_space(1)
# Remove files
with st.expander("🗑️ Remove mzML files"):
to_remove = st.multiselect("select mzML files",
options=[f.stem for f in sorted(mzML_dir.iterdir())])
c1, c2 = st.columns(2)
if c2.button("Remove **selected**", type="primary", disabled=not any(to_remove)):
remove_selected_mzML_files(to_remove)
st.experimental_rerun()
if any(Path(mzML_dir).iterdir()):
v_space(2)
# Display all mzML files currently in workspace
df = pd.DataFrame(
{"file name": [f.name for f in Path(mzML_dir).iterdir()]})
st.markdown("##### mzML files in current workspace:")
show_table(df)
v_space(1)
# Remove files
with st.expander("🗑️ Remove mzML files"):
to_remove = st.multiselect("select mzML files",
options=[f.stem for f in sorted(mzML_dir.iterdir())])
c1, c2 = st.columns(2)
if c2.button("Remove **selected**", type="primary", disabled=not any(to_remove)):
remove_selected_mzML_files(to_remove)
st.experimental_rerun()

if c1.button("⚠️ Remove **all**", disabled=not any(mzML_dir.iterdir())):
remove_all_mzML_files()
st.experimental_rerun()
if c1.button("⚠️ Remove **all**", disabled=not any(mzML_dir.iterdir())):
remove_all_mzML_files()
st.experimental_rerun()

save_params(params)
155 changes: 85 additions & 70 deletions pages/1_👀_View_Raw_Data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,88 +3,103 @@

from src.common import *
from src.view import *
from src.captcha_ import *

params = page_setup()
st.title("View raw MS data")

selected_file = st.selectbox(
"choose file",
[f.name for f in Path(st.session_state.workspace,
"mzML-files").iterdir()],
)
if selected_file:
df = get_df(
Path(st.session_state.workspace, "mzML-files", selected_file))
df_MS1, df_MS2 = (
df[df["mslevel"] == 1],
df[df["mslevel"] == 2],
)
#if local no need captcha
if st.session_state.location == "local":
params["controllo"] = True
st.session_state["controllo"] = True

if not df_MS1.empty:
tabs = st.tabs(["📈 Base peak chromatogram and MS1 spectra",
"📈 Peak map and MS2 spectra"])
with tabs[0]:
# BPC and MS1 spec
st.markdown("💡 Click a point in the BPC to show the MS1 spectrum.")
bpc_fig = plot_bpc(df_MS1)
#if controllo is false means not captcha applied
if 'controllo' not in st.session_state or params["controllo"] == False or st.session_state.location != "local":
#apply captcha
captcha_control()

else:

# Determine RT positions from clicks in BPC to show MS1 at this position
bpc_points = plotly_events(bpc_fig)
if bpc_points:
ms1_rt = bpc_points[0]["x"]
else:
ms1_rt = df_MS1.loc[0, "RT"]
### main content of page

spec = df_MS1.loc[df_MS1["RT"] == ms1_rt].squeeze()
st.title("View raw MS data")
selected_file = st.selectbox(
"choose file",
[f.name for f in Path(st.session_state.workspace,
"mzML-files").iterdir()],
)
if selected_file:
df = get_df(
Path(st.session_state.workspace, "mzML-files", selected_file))
df_MS1, df_MS2 = (
df[df["mslevel"] == 1],
df[df["mslevel"] == 2],
)

title = f"MS1 spectrum @RT {spec['RT']}"
fig = plot_ms_spectrum(
spec,
title,
"#EF553B",
)
show_fig(fig, title.replace(" ", "_"))
if not df_MS1.empty:
tabs = st.tabs(["📈 Base peak chromatogram and MS1 spectra",
"📈 Peak map and MS2 spectra"])
with tabs[0]:
# BPC and MS1 spec
st.markdown("💡 Click a point in the BPC to show the MS1 spectrum.")
bpc_fig = plot_bpc(df_MS1)

with tabs[1]:
c1, c2 = st.columns(2)
c1.number_input(
"2D map intensity cutoff",
1000,
1000000000,
params["2D-map-intensity-cutoff"],
1000,
key="2D-map-intensity-cutoff"
)
v_space(1, c2)
c2.markdown("💡 Click anywhere to show the closest MS2 spectrum.")
map2D = plot_2D_map(
df_MS1,
df_MS2,
st.session_state["2D-map-intensity-cutoff"],
)
map_points = plotly_events(map2D)
# Determine RT and mz positions from clicks in the map to get closest MS2 spectrum
if not df_MS2.empty:
if map_points:
rt = map_points[0]["x"]
prec_mz = map_points[0]["y"]
# Determine RT positions from clicks in BPC to show MS1 at this position
bpc_points = plotly_events(bpc_fig)
if bpc_points:
ms1_rt = bpc_points[0]["x"]
else:
rt = df_MS2.iloc[0, 2]
prec_mz = df_MS2.iloc[0, 0]
spec = df_MS2.loc[
(
abs(df_MS2["RT"] - rt) +
abs(df_MS2["precursormz"] - prec_mz)
).idxmin(),
:,
]
title = f"MS2 spectrum @precursor m/z {round(spec['precursormz'], 4)} @RT {round(spec['RT'], 2)}"
ms1_rt = df_MS1.loc[0, "RT"]

ms2_fig = plot_ms_spectrum(
spec = df_MS1.loc[df_MS1["RT"] == ms1_rt].squeeze()

title = f"MS1 spectrum @RT {spec['RT']}"
fig = plot_ms_spectrum(
spec,
title,
"#00CC96"
"#EF553B",
)
show_fig(ms2_fig, title.replace(" ", "_"))
show_fig(fig, title.replace(" ", "_"))

with tabs[1]:
c1, c2 = st.columns(2)
c1.number_input(
"2D map intensity cutoff",
1000,
1000000000,
params["2D-map-intensity-cutoff"],
1000,
key="2D-map-intensity-cutoff"
)
v_space(1, c2)
c2.markdown("💡 Click anywhere to show the closest MS2 spectrum.")
map2D = plot_2D_map(
df_MS1,
df_MS2,
st.session_state["2D-map-intensity-cutoff"],
)
map_points = plotly_events(map2D)
# Determine RT and mz positions from clicks in the map to get closest MS2 spectrum
if not df_MS2.empty:
if map_points:
rt = map_points[0]["x"]
prec_mz = map_points[0]["y"]
else:
rt = df_MS2.iloc[0, 2]
prec_mz = df_MS2.iloc[0, 0]
spec = df_MS2.loc[
(
abs(df_MS2["RT"] - rt) +
abs(df_MS2["precursormz"] - prec_mz)
).idxmin(),
:,
]
title = f"MS2 spectrum @precursor m/z {round(spec['precursormz'], 4)} @RT {round(spec['RT'], 2)}"

ms2_fig = plot_ms_spectrum(
spec,
title,
"#00CC96"
)
show_fig(ms2_fig, title.replace(" ", "_"))

save_params(params)
Loading

0 comments on commit 46d14b3

Please sign in to comment.