forked from no-saint-no-angel/BianqueNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamlit_app.py
450 lines (392 loc) · 16.9 KB
/
streamlit_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import os
import shutil
import subprocess
from datetime import datetime
from os import makedirs
from os.path import exists as pexists
from os.path import join as pjoin
from typing import Tuple
import pandas as pd
import streamlit as st
from huggingface_hub import hf_hub_download
from PIL import Image
from function.shiyan_jihe_signal_mean_std_plot_function import scatter_mean_std
def download_bianquenet(download_path):
REPO_ID = "alexbene/BianqueNet"
FILENAME = "deeplab_upernet_aspp_psp_ab_swin_skips_1288_0.0003.pth"
if os.path.exists(download_path):
return
hf_hub_download(
repo_id=REPO_ID,
filename=FILENAME,
local_dir=os.path.dirname(download_path),
)
DATETIME_FORMAT = "%Y%m%d"
# PATHS
INPUT_DIR = pjoin("./", "input", "data_input")
OUTPUT_DIR = pjoin("./", "output")
# Create input and output directories if they don't exist
makedirs(INPUT_DIR, exist_ok=True)
makedirs(OUTPUT_DIR, exist_ok=True)
# Input files name template
# D{date.strftime("%Y%m%d")}-A{age:03d}-S{"F" if sex == "Female" else "M"}{ext}
# Parse datetime object from string
def parse_date(dt) -> datetime:
return datetime.strptime(dt, DATETIME_FORMAT)
# Get updated filename from age, sex, date and old filename
def get_updated_filename(filename, age, sex, date) -> str:
_, ext = os.path.splitext(filename)
write_sex = "F" if sex == "Female" else "M"
return f"D{date.strftime(DATETIME_FORMAT)}-A{age:03d}-S{write_sex}{ext}"
# Get date, age, sex from filename
def get_metadata(filename: str) -> Tuple[datetime, int, str]:
filename_parts = filename.split(".")[0].split("-")
date, age, sex = datetime.now(), int(-1), str("Unknown")
if (
len(filename_parts) != 3
or len(filename_parts[0]) != 9
or len(filename_parts[1]) != 4
or len(filename_parts[2]) != 2
or filename_parts[0][0] != "D"
or filename_parts[1][0] != "A"
or filename_parts[2][0] != "S"
):
return date, age, sex
if len(filename_parts[0]) == 9:
date = parse_date(filename_parts[0][1:])
if len(filename_parts[1]) == 4:
age = int(filename_parts[1][1:])
if len(filename_parts[2]) == 2:
sex = "Female" if filename_parts[2][1:] == "F" else "Male"
return date, age, sex
def update_multiselect_state(name, updated=None, deleted=None):
if not updated and not deleted:
return
if deleted:
if deleted in st.session_state[name]:
st.session_state[name].remove(deleted)
st.session_state[f"{name}_state"] = sorted(st.session_state[name])
elif updated:
st.session_state[f"{name}_state"] = [
v if v != updated[0] else updated[1] for v in st.session_state[name]
]
# Define Streamlit app
def app():
st.title("Spline Analysis")
st.markdown(
"The system expect [spine sagittal T2-weighted MRI images](https://www.google.com/search?sca_esv=668e1abf6fdfcd6c&sca_upv=1&sxsrf=ADLYWIKmLutts_nNNe55bLngCChY73LyDA:1716834734152&q=spine+sagittal+T2-weighted+MRI+images&uds=ADvngMg3XiBUUido4UvvhKSfTjoFyMqEg7zenUa1FhiE3LIwud3pyBZq0PhDtIOIJUYEKWxP8yVIcw6QDVNzmA6ehh2PjMjY23Z3g9Gh2ld_QPsdsZ2T5_JXsNIkZAKJtUKFWLGcqeGeIUxr9esg6YYcCUgzmgqgmVtAxaxvR0uhierPy2oLXxGXVHpgdGn9nPWlzocXA3YNxG74Lb_9YrdnEPwc8knw3q8IhuJDXEsjdJinSBd9lWJgRNyRS6OBxT4oFphddNXEyClap4xZ_BeGU3ZGxTX-heWzUAe527AjkVe3XfhBpeNvT8tIppylAmM_dtCsLFrkBHeOuWtV4m5pb6z6v3cee1QL-ogr4Wy89PNxoCfoTBM2gbjxLKBCbly1mMUYQ4gK&udm=2&prmd=ivbnz&sa=X&ved=2ahUKEwjp993ju66GAxWY87sIHYIgAmsQtKgLegQIFRAB&biw=1712&bih=1329&dpr=2). "
"Images should be square and exported directly from the "
"corresponding software. For correct results, **rename the images "
" using the integrated `Edit` button to set the correct age and "
"gender**."
)
st.markdown(
"> **NOTE 📝**\n>\n"
"> This is just a frontend for the BianqueNet model introduced in "
'*"Deep learning-based high-accuracy quantitation for lumbar '
'intervertebral disc degeneration from MRI"* - '
"[\[paper\]](https://pubmed.ncbi.nlm.nih.gov/35149684/) "
"[\[original codebase\]](https://github.com/no-saint-no-angel/BianqueNet)"
)
# CSS hack to vertically align the columns' content
st.write(
"""<style>
[data-testid="stHorizontalBlock"] {
align-items: center;
}
a {
color: #5f54c1 !important;
text-decoration: none;
}
blockquote {
border-left: 2px solid #858585;
}
</style>
""",
unsafe_allow_html=True,
)
# ##################### SIDEBAR - Upload Images & Menu #####################
# Create sidebar for input file selection
st.sidebar.title("Upload Images")
with st.sidebar.form("file-uploader", clear_on_submit=True):
st.sidebar.write(
r"""<style>[data-testid="stForm"] {
border: 0px;
padding: 0px;
}</style>""",
unsafe_allow_html=True,
)
uploaded_files = st.file_uploader(
"Select images",
type=["png", "jpg", "jpeg", "bmp"],
accept_multiple_files=True,
label_visibility="collapsed",
)
submitted = st.form_submit_button(
"Save Files", use_container_width=True
)
if submitted and uploaded_files is not None:
for uploaded_file in uploaded_files:
with open(pjoin(INPUT_DIR, uploaded_file.name), "wb") as f:
f.write(uploaded_file.getbuffer())
st.sidebar.divider()
st.sidebar.title("Menu")
st.sidebar.markdown(
"### - [Overview and Rename](#images-overview-and-rename)\n"
"### - [Process](#process-images)\n"
"### - [Results](#results)"
)
st.sidebar.divider()
# ##################### Previw Images - Edit Metadata #####################
st.header("Images Overview and Rename")
filenames = sorted(os.listdir(INPUT_DIR))
if filenames:
if "previewer_state" not in st.session_state:
st.session_state.previewer_state = []
# Get form button state
container = st.container()
show_all = st.checkbox(
"Select all sorted", key="preview_show_all", value=True
)
filename_filt = container.multiselect(
"Which samples to show?",
filenames,
filenames if show_all else st.session_state.previewer_state,
key="previewer",
)
for filename in filename_filt:
# Load and display image
image = Image.open(pjoin(INPUT_DIR, filename))
# st.subheader(f"Image {filename}")
# COLUMN LEFT - Show image and metadata
left_col, right_col = st.columns([1, 1])
left_col.image(image, caption=filename, width=300)
# COLUMN RIGHT - Show metadata and edit button
# Get current metadata
date, age, sex = get_metadata(filename)
# Show current metadata and edit button
col1, col2 = right_col.columns([2, 1])
col1.write(f"**Age**: {age}")
col1.write(f"**Sex**: {sex}")
col1.write(f"**Date Taken**: {date.strftime('%Y-%m-%d')}")
edit_button = col2.button("**Edit**", key=f"edit_button_{filename}")
delete_button = col2.button(
"**Delete**", key=f"delete_button_{filename}"
)
# Delete image if delete button is pressed
if delete_button:
os.remove(pjoin(INPUT_DIR, filename))
# also remove the output folder if exists
if os.path.exists(pjoin(OUTPUT_DIR, filename.split(".")[0])):
shutil.rmtree(pjoin(OUTPUT_DIR, filename.split(".")[0]))
update_multiselect_state("previewer", deleted=filename)
update_multiselect_state(
"results", deleted=filename.split(".")[0]
)
st.rerun()
# Show form to edit metadata
# Create form button state if it doesn't exist
if f"formbtn_state_{filename}" not in st.session_state:
st.session_state.__setattr__(f"formbtn_state_{filename}", False)
# Get form button state
formbtn_state = st.session_state.__getattr__(
f"formbtn_state_{filename}"
)
# Show form if edit button is pressed or form button state is True
if edit_button and formbtn_state:
st.session_state.__setattr__(f"formbtn_state_{filename}", False)
elif edit_button or formbtn_state:
if formbtn_state:
st.session_state.__setattr__(
f"formbtn_state_{filename}", False
)
st.session_state.__setattr__(f"formbtn_state_{filename}", True)
# Show form to edit metadata
with st.form(filename):
form_col1, form_col2, form_col3 = st.columns([0.5, 1, 1])
edited_age = form_col1.number_input("Age", value=age)
edited_sex = form_col2.selectbox(
"Sex",
["Male", "Female"],
index=0 if sex == "Male" else 1,
)
edited_date = form_col3.date_input("Date", value=date)
submit_button = st.form_submit_button("Save")
# Save edited filename if submit button is pressed
if submit_button:
updated_filename = get_updated_filename(
filename, edited_age, edited_sex, edited_date
)
os.rename(
pjoin(INPUT_DIR, filename),
pjoin(INPUT_DIR, updated_filename),
)
if os.path.exists(
pjoin(OUTPUT_DIR, filename.split(".")[0])
):
os.rename(
pjoin(OUTPUT_DIR, filename.split(".")[0]),
pjoin(
OUTPUT_DIR, updated_filename.split(".")[0]
),
)
update_multiselect_state(
"previewer", updated=(filename, updated_filename)
)
update_multiselect_state(
"results", updated=(filename, updated_filename)
)
st.rerun()
# ############################ Process Images #############################
st.divider()
st.header("Process Images")
if "model_downloaded" not in st.session_state:
st.session_state["model_downloaded"] = False
process_button = st.empty()
if not st.session_state["model_downloaded"]:
process_button.warning("Downloading model...")
# ############################ Preview Results ############################
st.divider()
st.header("Results")
dirnames = sorted(os.listdir(OUTPUT_DIR))
metrics = ["DH", "DHI", "HDR", "SI"]
if dirnames:
if "results_state" not in st.session_state:
st.session_state.results_state = []
# Get form button state
results_container = st.container()
show_all = st.checkbox(
"Select all sorted", key="results_show_all", value=True
)
# st.write(show_all)
# st.write(dirnames)
def hh() -> None:
st.session_state.results_state = st.session_state.results
dirnames_filt = results_container.multiselect(
"Which samples to show?",
dirnames,
dirnames if show_all else None,
key="results",
on_change=hh,
)
for dirname in dirnames_filt:
st.subheader(f"Sample {dirname}")
results_dir = pjoin(OUTPUT_DIR, dirname)
date, age, sex = get_metadata(results_dir)
image_col, results_col = st.columns([1, 1])
# Load and display image
if pexists(pjoin(results_dir, "point_detect.BMP")):
image = Image.open(pjoin(results_dir, "point_detect.BMP"))
image_col.image(image, caption="point detections")
else:
image_col.error(
f"Image {pjoin(results_dir, 'point_detect.BMP')} \
can not be found"
)
# Read excel results from "quantitative_analysis_results.xlsx"
quant_analysis_results = pjoin(
results_dir, "quantitative_analysis_results.xlsx"
)
results = None
results_col.write("Quantitative Results")
if not pexists(quant_analysis_results):
df = None
results_col.error(
f"Spreadsheet {quant_analysis_results} can not be found"
)
else:
df = pd.read_excel(
quant_analysis_results,
index_col=0,
sheet_name=[
"jihe_parameter",
"SI_parameter",
"quantitative_results",
],
)
results_col.dataframe(
df["quantitative_results"], use_container_width=True
)
jihe_parameters_df = df["jihe_parameter"]
results = {
"DH": jihe_parameters_df[["DH"]],
"DHI": jihe_parameters_df[["DHI"]],
"HDR": jihe_parameters_df[["HDR/DWR"]],
"SI": df["SI_parameter"],
}
tabs = st.tabs(metrics)
for tab, metric in zip(tabs, metrics):
plot, table = tab.columns([1.5, 1])
if metric != "SI":
if pexists(pjoin(results_dir, f"{metric}.png")):
image = Image.open(pjoin(results_dir, f"{metric}.png"))
plot.image(image, use_column_width=True)
elif results is not None:
plot.pyplot(
scatter_mean_std(
0 if sex == "Female" else 1,
age,
results[metric].to_numpy(),
metric=metric,
)[0]
)
else:
plot.error(
f"Image {pjoin(results_dir, f'{metric}.png')} can \
not be found"
)
else:
if pexists(pjoin(results_dir, "SI_dj.png")) and pexists(
pjoin(results_dir, "SI_weizhi.png")
):
si1 = Image.open(pjoin(results_dir, "SI_dj.png"))
si2 = Image.open(pjoin(results_dir, "SI_weizhi.png"))
plot.image(si1)
plot.image(si2)
elif results is not None:
si1, si2 = scatter_mean_std(
0 if sex == "Female" else 1,
age,
results["SI"].to_numpy(),
metric="SI",
)
plot.pyplot(si1)
plot.pyplot(si2)
else:
plot.error(
f"Image {pjoin(results_dir, f'SI_dj.png')} can \
not be found"
)
plot.error(
f"Image {pjoin(results_dir, f'SI_weizhi.png')} \
can not be found"
)
if results is not None:
table.dataframe(results[metric], use_container_width=True)
else:
table.error(
f"Spreadsheet {quant_analysis_results} can not be found"
)
download_bianquenet(
os.path.join(
".",
"weights_big_apex",
"deeplab_upernet_aspp_psp_ab_swin_skips_1288",
"deeplab_upernet_aspp_psp_ab_swin_skips_1288_0.0003.pth",
)
)
st.session_state["model_downloaded"] = True
# Process images if process button is pressed
def on_process_button_click():
with process_button, st.spinner(
"Please wait as we process your images..."
):
subprocess.call(["python", "main.py"])
process_button.button(
"Process Images",
type="primary",
use_container_width=True,
on_click=on_process_button_click,
)
if __name__ == "__main__":
app()