Anirudh Balaraman commited on
Commit
30f1102
·
1 Parent(s): 1084b5c
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apt-get update && apt-get install -y \
6
+ build-essential \
7
+ curl \
8
+ git \
9
+ libgl1 \
10
+ libglib2.0-0 \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ COPY requirements.txt ./
14
+ COPY . .
15
+
16
+ RUN pip3 install -r requirements.txt
17
+
18
+ EXPOSE 8501
19
+
20
+ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
21
+
22
+ ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false", "--server.enableCORS=false"]
23
+
24
+
README.md CHANGED
@@ -1,10 +1,11 @@
1
  ---
2
- title: My Streamlit App
3
  emoji: 🚀
4
  colorFrom: blue
5
  colorTo: red
6
  sdk: docker
7
  pinned: false
 
8
  app_port: 8501
9
  ---
10
  <p align="center">
 
1
  ---
2
+ title: Prostate Inference
3
  emoji: 🚀
4
  colorFrom: blue
5
  colorTo: red
6
  sdk: docker
7
  pinned: false
8
+ short_description: Predicts csPCa risk and PI-RADS score from bpMRI sequences
9
  app_port: 8501
10
  ---
11
  <p align="center">
app.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import subprocess
3
+ import os
4
+ import shutil
5
+ from huggingface_hub import hf_hub_download
6
+ import nrrd
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import matplotlib.patches as patches
10
+ import json
11
+ import plotly.graph_objects as go
12
+ import base64
13
+
14
+ def render_clickable_image(image_path, link_url, width=100):
15
+ """
16
+ Generates a clickable image using HTML and Base64 encoding.
17
+ """
18
+ # 1. Read the image file and encode it to base64
19
+ with open(image_path, "rb") as f:
20
+ data = base64.b64encode(f.read()).decode("utf-8")
21
+
22
+ # 2. Create the HTML string
23
+ # target="_blank" opens the link in a new tab
24
+ html_code = f"""
25
+ <a href="{link_url}" target="_blank">
26
+ <img src="data:image/png;base64,{data}" width="{width}" style="border-radius: 5px;">
27
+ </a>
28
+ """
29
+
30
+ # 3. Render it
31
+ st.markdown(html_code, unsafe_allow_html=True)
32
+
33
+
34
+ st.set_page_config(
35
+ page_title="Prostate Scoring",
36
+ page_icon="🩺",
37
+ layout="wide",
38
+ initial_sidebar_state="expanded"
39
+ )
40
+
41
+
42
+ @st.cache_data
43
+ def load_nrrd(file_path):
44
+ """Load NRRD file and return data + header."""
45
+ data, header = nrrd.read(file_path)
46
+ return data, header
47
+
48
+ def display_slicer(scan_paths, mask_path=None, bboxes=None, title="Scan Viewer", key_suffix=""):
49
+ """
50
+ Displays slicer with Multi-Background Support, Mask Overlay, and Bounding Box Multiselect.
51
+
52
+ Args:
53
+ scan_paths: Dict of {Label: FilePath}. Example: {"T2W": "path/to/t2.nrrd", "ADC": "..."}
54
+ """
55
+ # 1. Layout: Image/Slider (Left) | Controls (Right)
56
+ c_viewer, c_controls = st.columns([3, 1.5])
57
+
58
+ # --- CONTROLS SECTION (Right Column) ---
59
+ with c_controls:
60
+ st.write(f"**{title} Controls**")
61
+
62
+ # A. Background Selection
63
+ # We assume the first key in the dict is the default
64
+ available_scans = list(scan_paths.keys())
65
+ selected_scan_name = st.radio("Background Image", available_scans, index=0, key=f"bg_{key_suffix}")
66
+ current_file_path = scan_paths[selected_scan_name]
67
+
68
+ # B. Lesion Selection (Multiselect)
69
+ box_labels = []
70
+ selected_labels = []
71
+ if bboxes:
72
+ box_labels = [f"Lesion {i+1}" for i in range(len(bboxes))]
73
+ st.write("---") # Divider
74
+ selected_labels = st.multiselect(
75
+ "Select Lesions",
76
+ options=box_labels,
77
+ default=box_labels,
78
+ key=f"multi_{key_suffix}"
79
+ )
80
+
81
+ # C. Toggles
82
+ st.write("---")
83
+ show_mask = False
84
+ if mask_path and os.path.exists(mask_path):
85
+ show_mask = st.checkbox("Show Mask Overlay", value=False, key=f"mk_{key_suffix}")
86
+
87
+ # --- VIEWER SECTION (Left Column) ---
88
+ with c_viewer:
89
+ if not os.path.exists(current_file_path):
90
+ st.error(f"File not found: {current_file_path}")
91
+ return
92
+
93
+ # Load the selected background image
94
+ data, _ = load_nrrd(current_file_path)
95
+
96
+ if len(data.shape) != 3:
97
+ st.warning("Data is not 3D.")
98
+ return
99
+
100
+ total_slices = data.shape[2]
101
+
102
+ # D. Slider Logic
103
+ start_slice = total_slices // 2
104
+ # Auto-jump logic: If exactly one lesion is selected, jump to it
105
+ if len(selected_labels) == 1 and bboxes:
106
+ idx = int(selected_labels[0].split(" ")[1]) - 1
107
+ if 0 <= idx < len(bboxes):
108
+ b = bboxes[idx]
109
+ start_slice = int(b[2] + (b[5] // 2))
110
+ start_slice = max(0, min(start_slice, total_slices - 1))
111
+
112
+ slice_idx = st.slider("Select Slice (Z-Axis)", 0, total_slices - 1, start_slice, key=f"sl_{key_suffix}")
113
+
114
+ # E. Plotting
115
+ img_slice = data[:, :, slice_idx]
116
+
117
+ # Normalize Image (0-1)
118
+ img_slice = img_slice.astype(float)
119
+
120
+ fig, ax = plt.subplots(figsize=(5, 5))
121
+ ax.imshow(img_slice, cmap="gray", origin="upper")
122
+
123
+ # 1. Overlay Mask
124
+ if show_mask:
125
+ # Load mask on the fly (or cache it if slow)
126
+
127
+ m_data, _ = load_nrrd(mask_path)
128
+ # Check shape compatibility
129
+ if m_data.shape == data.shape:
130
+ mslice = m_data[:, :, slice_idx]
131
+ overlay = np.ma.masked_where(mslice == 0, mslice)
132
+ ax.imshow(overlay, cmap="Reds", alpha=0.5, origin="upper")
133
+ else:
134
+ # Fallback warning if mask dims don't match selected background
135
+ # (Common if ADC resolution != T2 resolution)
136
+ ax.text(5, 5, "Mask shape mismatch", color='red', fontsize=8)
137
+
138
+
139
+ # 2. Overlay Bounding Boxes
140
+ if bboxes:
141
+ for i, box in enumerate(bboxes):
142
+ label = f"Lesion {i+1}"
143
+ if label not in selected_labels:
144
+ continue
145
+
146
+ bx, by, bz, bw, bh, bd = box
147
+
148
+ # Visibility check
149
+ if bz <= slice_idx < (bz + bd):
150
+ rect = patches.Rectangle(
151
+ (bx, by), bw, bh,
152
+ linewidth=2, edgecolor='yellow', facecolor='none'
153
+ )
154
+ ax.add_patch(rect)
155
+ ax.text(bx, by-5, f"L{i+1}", color='yellow', fontsize=9, fontweight='bold')
156
+
157
+ ax.axis("off")
158
+ st.pyplot(fig, use_container_width=False)
159
+
160
+ @st.cache_resource
161
+ def download_all_models():
162
+ # 1. Ensure the 'models' directory exists
163
+ models_dir = os.path.join(os.getcwd(), 'models')
164
+ os.makedirs(models_dir, exist_ok=True)
165
+
166
+ for filename in FILENAMES:
167
+ try:
168
+ # 2. Download from Hugging Face (to cache)
169
+ cached_path = hf_hub_download(repo_id=REPO_ID, filename=filename)
170
+
171
+ # 3. Define where we want it to live locally
172
+ destination_path = os.path.join(models_dir, filename)
173
+
174
+ # 4. Copy only if it's not already there
175
+ if not os.path.exists(destination_path):
176
+ shutil.copy(cached_path, destination_path)
177
+
178
+ except Exception as e:
179
+ st.error(f"Failed to download {filename}: {e}")
180
+ st.stop()
181
+
182
+ with st.container():
183
+ col1, col2, col3, col4 = st.columns(4)
184
+
185
+ with col1:
186
+ render_clickable_image("deployment_images/logo1.png", "https://www.comfort-ai.eu/", width=220)
187
+ with col2:
188
+ render_clickable_image("deployment_images/logo2.png", "https://www.charite.de/", width=220)
189
+ with col3:
190
+ render_clickable_image("deployment_images/logo3.png", "https://mri.tum.de/de", width=220)
191
+ with col4:
192
+ render_clickable_image("deployment_images/logo4.png", "https://ai-assisted-healthcare.com/", width=220)
193
+
194
+ st.write("")
195
+ st.write("")
196
+ st.title("PI-RADS and csPCa Risk Prediction from bpMRI")
197
+ # --- TRIGGER THE DOWNLOAD STARTUP ---
198
+ st.markdown("💡 This application utilizes a weakly supervised, attention-based multiple-instance learning (MIL) model to predict scan-level PI-RADS scores and clinically significant prostate cancer (csPCa) risk from axial biparametric MRI (bpMRI) sequences (T2W, ADC, and DWI). Users may upload their own bpMRI scans as NRRD or select a provided sample case to evaluate the tool. Following inference, outcomes are detailed in the Results & Downloads section. The Visualization module allows users to inspect the prostate mask and the top five salient patches overlaid on the bpMRI sequences. The salient patches are displayed only when the predicted PI-RADS score is 3 or more. For execution details, refer to the log file; for methodology, please visit our [Project Page](https://anirudhbalaraman.github.io/WSAttention-Prostate/) or read the [Paper]. For more implementation details, check our [Github](https://github.com/anirudhbalaraman/WSAttention-Prostate/tree/main)")
199
+ st.markdown("***NOTE*** Required NRRD dimension format: Height x Width x Depth. ")
200
+
201
+ #--- CONSTANTS ---
202
+ REPO_ID = "anirudh0410/WSAttention-Prostate"
203
+ FILENAMES = ["pirads.pt", "prostate_segmentation_model.pt", "cspca_model.pth"]
204
+ with st.spinner("Initializing..."):
205
+ download_all_models()
206
+ st.success("Models ready!")
207
+
208
+ # --- CONFIGURATION ---
209
+ # Base paths
210
+ BASE_DIR = os.getcwd()
211
+ INPUT_BASE = os.path.join(BASE_DIR, "temp_data" )
212
+ OUTPUT_DIR = os.path.join(BASE_DIR, "temp_data", "processed")
213
+ SAMPLES_BASE_DIR = os.path.join(BASE_DIR, "dataset","samples")
214
+ SAMPLE_CASES = {
215
+ "Sample 1": {
216
+ "path": os.path.join(SAMPLES_BASE_DIR, "sample1"),
217
+ "files": {"t2": "t2.nrrd", "adc": "adc.nrrd", "dwi": "dwi.nrrd"}
218
+ },
219
+ "Sample 2": {
220
+ "path": os.path.join(SAMPLES_BASE_DIR, "sample2"),
221
+ "files": {"t2": "t2.nrrd", "adc": "adc.nrrd", "dwi": "dwi.nrrd"}
222
+ },
223
+ "Sample 3": {
224
+ "path": os.path.join(SAMPLES_BASE_DIR, "sample3"),
225
+ "files": {"t2": "t2.nrrd", "adc": "adc.nrrd", "dwi": "dwi.nrrd"}
226
+ }
227
+ }
228
+
229
+ # Create specific sub-directories for each input type
230
+ # This ensures we pass a clean directory path to your script
231
+ T2_DIR = os.path.join(INPUT_BASE, "t2")
232
+ ADC_DIR = os.path.join(INPUT_BASE, "adc")
233
+ DWI_DIR = os.path.join(INPUT_BASE, "dwi")
234
+
235
+ # Ensure all folders exist
236
+ for path in [T2_DIR, ADC_DIR, DWI_DIR, OUTPUT_DIR]:
237
+ os.makedirs(path, exist_ok=True)
238
+
239
+
240
+ # --- 1. DATA SOURCE SELECTION ---
241
+ with st.sidebar:
242
+ st.header("Data Selection")
243
+ # Dropdown to choose mode
244
+ data_source = st.radio(
245
+ "Choose Data Source:",
246
+ ["Upload My Own Files", "Sample 1", "Sample 2", "Sample 3"],
247
+ index=0
248
+ )
249
+
250
+ # --- 2. INPUT HANDLING ---
251
+ t2_file = None
252
+ adc_file = None
253
+ dwi_file = None
254
+ is_demo_mode = data_source != "Upload My Own Files"
255
+ if is_demo_mode:
256
+ # --- DEMO MODE LOGIC ---
257
+ selected_sample = SAMPLE_CASES[data_source]
258
+ st.info(f"👉 **Demo Mode Active:** Using {data_source}")
259
+
260
+ # Verify files exist
261
+ base_path = selected_sample["path"]
262
+ f_names = selected_sample["files"]
263
+
264
+ missing = []
265
+ for key, fname in f_names.items():
266
+ if not os.path.exists(os.path.join(base_path, fname)):
267
+ missing.append(os.path.join(base_path, fname))
268
+
269
+ if missing:
270
+ st.error(f"Error: The following sample files are missing in the repo:\n{missing}")
271
+
272
+ else:
273
+ # Visual feedback
274
+ c1, c2, c3 = st.columns(3)
275
+ c1.success(f"T2: {f_names['t2']}")
276
+ c2.success(f"ADC: {f_names['adc']}")
277
+ c3.success(f"DWI: {f_names['dwi']}")
278
+
279
+ else:
280
+ # --- UPLOAD MODE LOGIC ---
281
+
282
+ st.markdown("### Upload your T2W, ADC, and DWI scans")
283
+
284
+ # --- 1. UI: THREE UPLOADERS ---
285
+ col1, col2, col3 = st.columns(3)
286
+
287
+ with col1:
288
+ t2_file = st.file_uploader("Upload T2W (NRRD)", type=["nrrd"])
289
+ with col2:
290
+ adc_file = st.file_uploader("Upload ADC (NRRD)", type=["nrrd"])
291
+ with col3:
292
+ dwi_file = st.file_uploader("Upload DWI (NRRD)", type=["nrrd"])
293
+
294
+ # --- 2. EXECUTION LOGIC ---
295
+ if "inference_done" not in st.session_state:
296
+ st.session_state.inference_done = False
297
+ if "logs" not in st.session_state:
298
+ st.session_state.logs = ""
299
+ ready_to_run = (not is_demo_mode and t2_file and adc_file and dwi_file) or is_demo_mode
300
+ if ready_to_run:
301
+ if st.button("Run Inference", type="primary"):
302
+
303
+ st.session_state.inference_done = False
304
+ st.session_state.logs = ""
305
+ # --- A. CLEANUP & SAVE ---
306
+ # Clear old files to prevent mixing previous runs
307
+ # (Optional but recommended for a clean state)
308
+ for folder in [T2_DIR, ADC_DIR, DWI_DIR, OUTPUT_DIR]:
309
+ for f in os.listdir(folder):
310
+ if os.path.isfile(os.path.join(folder,f)):
311
+ os.remove(os.path.join(folder, f))
312
+ elif os.path.isdir(os.path.join(folder,f)):
313
+ shutil.rmtree(os.path.join(folder,f))
314
+
315
+
316
+
317
+ if is_demo_mode:
318
+
319
+
320
+
321
+ # Copy from the specific sample folder
322
+ src = SAMPLE_CASES[data_source]
323
+ shutil.copy(os.path.join(src["path"], src["files"]["t2"]), os.path.join(T2_DIR, "sample.nrrd"))
324
+ shutil.copy(os.path.join(src["path"], src["files"]["adc"]), os.path.join(ADC_DIR, "sample.nrrd"))
325
+ shutil.copy(os.path.join(src["path"], src["files"]["dwi"]), os.path.join(DWI_DIR, "sample.nrrd"))
326
+ st.write(f"Loaded data from {data_source}...")
327
+
328
+ else:
329
+
330
+ # Save T2
331
+ # We save it inside the T2_DIR folder
332
+ with open(os.path.join(T2_DIR, t2_file.name), "wb") as f:
333
+ shutil.copyfileobj(t2_file, f)
334
+
335
+ # Save ADC
336
+ with open(os.path.join(ADC_DIR, t2_file.name), "wb") as f:
337
+ shutil.copyfileobj(adc_file, f)
338
+
339
+ # Save DWI
340
+ with open(os.path.join(DWI_DIR, t2_file.name), "wb") as f:
341
+ shutil.copyfileobj(dwi_file, f)
342
+ st.write("Uploaded files saved...")
343
+
344
+ st.write("Starting Inference Pipeline...")
345
+
346
+ # --- B. CONSTRUCT COMMAND ---
347
+ # We pass the FOLDER paths, not file paths, matching your argument names
348
+ command = [
349
+ "python", "run_inference.py",
350
+ "--t2_dir", T2_DIR,
351
+ "--dwi_dir", DWI_DIR,
352
+ "--adc_dir", ADC_DIR,
353
+ "--output_dir", OUTPUT_DIR,
354
+ "--project_dir", BASE_DIR
355
+ ]
356
+
357
+ # DEBUG: Show the exact command being run (helpful for troubleshooting)
358
+ st.code(" ".join(command), language="bash")
359
+
360
+ # --- C. RUN SCRIPT ---
361
+ with st.spinner("Running Inference... (This may take a moment)"):
362
+ try:
363
+ # Run the script and capture output
364
+ result = subprocess.run(
365
+ command,
366
+ capture_output=True,
367
+ text=True,
368
+ check=True
369
+ )
370
+
371
+
372
+ st.session_state.inference_done = True
373
+ st.session_state.logs = result.stdout
374
+
375
+ except subprocess.CalledProcessError as e:
376
+ st.error("Script Execution Failed.")
377
+ st.error("Error Output:")
378
+ st.code(e.stderr)
379
+
380
+ # --- D. SHOW OUTPUT FILES ---
381
+ if st.session_state.inference_done:
382
+ st.success("Pipeline Execution Successful!")
383
+
384
+
385
+
386
+ st.divider()
387
+ with st.expander("📊 Results & Downloads", expanded=True):
388
+ if st.session_state.get("logs"): # Show Logs
389
+ with st.expander("View Execution Logs"):
390
+ st.code(st.session_state.logs)
391
+ # List everything in the output directory
392
+
393
+ output_files = os.listdir(OUTPUT_DIR)
394
+ if output_files:
395
+ for file_name in output_files:
396
+ file_path = os.path.join(OUTPUT_DIR, file_name)
397
+ if not os.path.isfile(file_path):
398
+ continue
399
+
400
+
401
+ with open(file_path, "rb") as f:
402
+ st.download_button(
403
+ label=f"⬇️ Download {file_name}",
404
+ data=f.read(),
405
+ file_name=file_name
406
+ )
407
+ if file_name == "results.json":
408
+ with open(file_path, "r") as f:
409
+ temp_data = json.load(f)
410
+ first_case = next(iter(temp_data.values()))
411
+ st.session_state.pirads = first_case.get("Predicted PIRAD Score")
412
+ st.session_state.risk = first_case.get("csPCa risk")
413
+ st.session_state.coords = first_case.get("Top left coordinate of top 5 patches(x,y,z)")
414
+
415
+
416
+ else:
417
+ st.warning("Script finished but no files were found in output_dir.")
418
+
419
+ with st.expander("🩺 Results", expanded=True):
420
+ if "risk" in st.session_state and "pirads" in st.session_state:
421
+ #st.metric("csPCa Risk Score", f"{st.session_state.risk:.2f}")
422
+ risk = st.session_state.get("risk")
423
+ z = np.linspace(0, 1, 100).reshape(1, -1) # 1 row, 100 columns
424
+ col_chart, col_spacer = st.columns([1, 1])
425
+ with col_chart:
426
+ fig = go.Figure()
427
+ fig.add_trace(go.Heatmap(
428
+ z=z, # one row, two columns
429
+ x=np.linspace(0, 1, 100), # 0 to 1 scale
430
+ y=[0, 1],
431
+ showscale=False,
432
+ colorscale="RdYlGn_r",
433
+ hoverinfo='none'
434
+ ))
435
+ fig.add_trace(go.Scatter(
436
+ x=[risk],
437
+ y=[0.1],
438
+ mode="markers+text",
439
+ marker=dict(symbol="triangle-down", size=16, color="black"),
440
+ text=[f"csPCa Risk: {risk:.2f}"],
441
+ textposition="top center",
442
+ textfont=dict(color="black", size=16),
443
+ showlegend=False,
444
+ cliponaxis=False
445
+ ))
446
+
447
+ # Layout adjustments
448
+ fig.update_layout(
449
+ height=80,
450
+ margin=dict(l=20, r=20, t=20, b=25),
451
+ xaxis=dict(
452
+ range=[0, 1],
453
+ tickmode="array",
454
+ tickvals=[0, 1],
455
+ ticktext=["0", "1"],
456
+ showgrid=False,
457
+ ticks="outside",
458
+ ticklen=4,
459
+ tickfont=dict(
460
+ size=16,
461
+ color="black"
462
+ ),
463
+ ticklabelposition="inside bottom",
464
+ showline=False,
465
+ zeroline=False,
466
+ mirror=False,
467
+ side="bottom"
468
+ ),
469
+ yaxis=dict(
470
+ range=[0, 1],
471
+ showticklabels=False,
472
+ showgrid=False,
473
+ showline=False
474
+ ),
475
+ plot_bgcolor="white"
476
+ )
477
+
478
+ st.plotly_chart(fig, use_container_width=False)
479
+
480
+ pirads = st.session_state.get("pirads")
481
+ score_config = {
482
+ 2: {"bg": "#28a745", "text": "white"}, # Green
483
+ 3: {"bg": "#ffc107", "text": "black"}, # Yellow
484
+ 4: {"bg": "#fd7e14", "text": "white"}, # Orange
485
+ 5: {"bg": "#dc3545", "text": "white"}, # Red
486
+ }
487
+
488
+ html_circles = ""
489
+
490
+ for s in range(2, 6):
491
+ config = score_config[s]
492
+
493
+ # Define styles cleanly without newlines/indentation to prevent HTML errors
494
+ if s == int(pirads):
495
+ # Selected: Thick border, full opacity
496
+ border = "4px solid black"
497
+ opacity = "1.0"
498
+ transform = "scale(1.1)"
499
+ box_shadow = "0 4px 6px rgba(0,0,0,0.3)"
500
+ else:
501
+ # Unselected: Transparent border, low opacity
502
+ border = "4px solid transparent"
503
+ opacity = "0.3"
504
+ transform = "scale(1.0)"
505
+ box_shadow = "none"
506
+
507
+ # Build the div string
508
+ # distinct styling properties are joined by semicolons
509
+ html_circles += f"""
510
+ <div style="
511
+ width: 60px;
512
+ height: 60px;
513
+ background-color: {config['bg']};
514
+ color: {config['text']};
515
+ border-radius: 50%;
516
+ display: flex;
517
+ align-items: center;
518
+ justify-content: center;
519
+ font-size: 24px;
520
+ font-weight: bold;
521
+ font-family: Arial, sans-serif;
522
+ margin-right: 15px;
523
+ border: {border};
524
+ opacity: {opacity};
525
+ transform: {transform};
526
+ box-shadow: {box_shadow};">
527
+ {s}
528
+ </div>
529
+ """
530
+
531
+ # Display Container
532
+ st.markdown(f"### PI-RADS Score: {pirads}")
533
+ st.markdown(
534
+ f"""
535
+ <div style="display: flex; flex-direction: row; align-items: center; padding: 10px 0;">
536
+ {html_circles}
537
+ </div>
538
+ """,
539
+ unsafe_allow_html=True
540
+ )
541
+ else:
542
+ st.info("Results not available.")
543
+
544
+ with st.expander("Visualisation", expanded=True):
545
+ t2_vis_path = None
546
+ dwi_vis_path = None
547
+ adc_vis_path = None
548
+ mask_vis_path = None
549
+
550
+ t2_vis_dir = os.path.join(OUTPUT_DIR, "t2_registered")
551
+ if os.path.exists(t2_vis_dir) and len(os.listdir(t2_vis_dir)) > 0:
552
+ files_in_dir = os.listdir(t2_vis_dir)[0]
553
+ t2_vis_path = os.path.join(t2_vis_dir, files_in_dir)
554
+
555
+ adc_vis_dir = os.path.join(OUTPUT_DIR, "ADC_registered")
556
+ if os.path.exists(adc_vis_dir) and len(os.listdir(adc_vis_dir)) > 0:
557
+ files_in_dir = os.listdir(adc_vis_dir)[0]
558
+ adc_vis_path = os.path.join(adc_vis_dir, files_in_dir)
559
+
560
+ dwi_vis_dir = os.path.join(OUTPUT_DIR, "DWI_registered")
561
+ if os.path.exists(dwi_vis_dir) and len(os.listdir(dwi_vis_dir)) > 0:
562
+ files_in_dir = os.listdir(dwi_vis_dir)[0]
563
+ dwi_vis_path = os.path.join(dwi_vis_dir, files_in_dir)
564
+
565
+ mask_vis_dir = os.path.join(OUTPUT_DIR, "prostate_mask")
566
+ if os.path.exists(mask_vis_dir) and len(os.listdir(mask_vis_dir)) > 0:
567
+ files_in_maskdir = os.listdir(mask_vis_dir)[0]
568
+ mask_vis_path = os.path.join(mask_vis_dir, files_in_maskdir)
569
+ print('mask_vis_path')
570
+ else:
571
+ print('No mask dir')
572
+
573
+ roi_bbox = None
574
+ if "coords" in st.session_state:
575
+ detected_boxes = []
576
+ for i in st.session_state.coords:
577
+ indi_box = [i[1],i[0],i[2],64,64,3]
578
+ detected_boxes.append(indi_box)
579
+
580
+ scan_dict = {}
581
+ if t2_vis_path and os.path.exists(t2_vis_path):
582
+ scan_dict["T2W"] = t2_vis_path
583
+ if adc_vis_path and os.path.exists(adc_vis_path):
584
+ scan_dict["ADC"] = adc_vis_path
585
+ if dwi_vis_path and os.path.exists(dwi_vis_path):
586
+ scan_dict["DWI"] = dwi_vis_path
587
+
588
+ if scan_dict and st.session_state.pirads > 2:
589
+ display_slicer(
590
+ scan_paths=scan_dict, # <--- Pass the Dict here
591
+ mask_path=mask_vis_path,
592
+ bboxes=detected_boxes,
593
+ title="Salient Patch Viewer",
594
+ key_suffix="main_viz"
595
+ )
596
+ elif scan_dict:
597
+ display_slicer(
598
+ scan_paths=scan_dict, # <--- Pass the Dict here
599
+ mask_path=mask_vis_path,
600
+ bboxes=None,
601
+ title="Salient Patch Viewer",
602
+ key_suffix="main_viz"
603
+ )
604
+
605
+
606
+
607
+
608
+
609
+
610
+
deployment_images/logo1.png ADDED
deployment_images/logo2.png ADDED
deployment_images/logo4.png ADDED
requirements.txt CHANGED
@@ -20,7 +20,7 @@ pynrrd==1.1.1
20
  nibabel==5.3.2
21
  scikit-image==0.24.0
22
  scikit-learn==1.5.2
23
- opencv-python==4.10.0.84
24
  picai_prep==2.1.13
25
 
26
  # ---- Transformers / Hugging Face ----
@@ -29,6 +29,7 @@ huggingface_hub==1.3.3
29
  # ---- Visualization ----
30
  matplotlib==3.9.3
31
  seaborn==0.13.2
 
32
 
33
  # ---- Experiment tracking ----
34
  wandb==0.16.6
@@ -36,6 +37,7 @@ tensorboard==2.18.0
36
 
37
  # ---- Utilities ----
38
  tqdm==4.67.1
 
39
  requests
40
  filelock
41
  packaging
 
20
  nibabel==5.3.2
21
  scikit-image==0.24.0
22
  scikit-learn==1.5.2
23
+ opencv-python-headless==4.10.0.84
24
  picai_prep==2.1.13
25
 
26
  # ---- Transformers / Hugging Face ----
 
29
  # ---- Visualization ----
30
  matplotlib==3.9.3
31
  seaborn==0.13.2
32
+ plotly
33
 
34
  # ---- Experiment tracking ----
35
  wandb==0.16.6
 
37
 
38
  # ---- Utilities ----
39
  tqdm==4.67.1
40
+ gdown==5.2.0
41
  requests
42
  filelock
43
  packaging