mqadir commited on
Commit
03d12e0
·
verified ·
1 Parent(s): b046c49

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -0
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import shutil
4
+ import joblib
5
+ import numpy as np
6
+ import nibabel as nib
7
+ import traceback
8
+ import tempfile
9
+ import torch
10
+ from nnunetv2.inference.predict_from_raw_data import nnUNetPredictor
11
+ from batchgenerators.utilities.file_and_folder_operations import join
12
+
13
+ # GLOBAL SETUP & MODEL INITIALIZATION
14
+ # Set dummy environment variables to prevent nnU-Net path errors in HF Spaces
15
+ os.environ['nnUNet_raw'] = './tmp/nnUNet_raw'
16
+ os.environ['nnUNet_results'] = './model_weights'
17
+ os.environ['nnUNet_preprocessed'] = './tmp/nnUNet_preprocessed'
18
+ os.makedirs('./tmp/nnUNet_raw', exist_ok=True)
19
+ os.makedirs('./tmp/nnUNet_preprocessed', exist_ok=True)
20
+
21
+ # Dynamically assign device (prevents crashes if deployed on a CPU space)
22
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
23
+ print(f"Initializing nnU-Net on device: {device}")
24
+
25
+ try:
26
+ predictor = nnUNetPredictor(
27
+ tile_step_size=0.5,
28
+ use_gaussian=True,
29
+ use_mirroring=True,
30
+ perform_everything_on_device=True,
31
+ device=device,
32
+ verbose=False,
33
+ verbose_preprocessing=False,
34
+ allow_tqdm=True
35
+ )
36
+
37
+ # UPDATE THIS PATH: Ensure this matches the folder structure in your HF Space repository
38
+ model_folder = './model_weights/Dataset998_PanTSTen/nnUNetTrainer__nnUNetPlans__3d_fullres'
39
+
40
+ predictor.initialize_from_trained_model_folder(
41
+ model_folder,
42
+ use_folds=('all',),
43
+ checkpoint_name='checkpoint_best.pth',
44
+ )
45
+ print("nnU-Net loaded successfully.")
46
+ except Exception as e:
47
+ predictor = None
48
+ print(f"Warning: nnU-Net failed to load. Ensure 'model_weights' folder exists. Error: {e}")
49
+
50
+ try:
51
+ risk_model = joblib.load("model.joblib")
52
+ except FileNotFoundError:
53
+ risk_model = None
54
+
55
+ # MAIN PROCESSING PIPELINE
56
+
57
+ def process_scan(nifti_file, no_chemo, pd_surgery):
58
+ if nifti_file is None:
59
+ return gr.update(value="**Error:** Please upload a NIfTI file.", visible=True), *[gr.update(value="")]*4, gr.update(value="")
60
+
61
+ try:
62
+ # Use Python's tempfile to handle temporary folders automatically
63
+ with tempfile.TemporaryDirectory() as temp_in_dir, tempfile.TemporaryDirectory() as temp_out_dir:
64
+
65
+ # File Validation & Renaming
66
+ original_path = nifti_file.name
67
+ base_name = os.path.basename(original_path)
68
+
69
+ # Enforce nnU-Net's _0000 naming convention
70
+ if not base_name.endswith("_0000.nii.gz") and base_name.endswith(".nii.gz"):
71
+ new_base = base_name.replace(".nii.gz", "_0000.nii.gz")
72
+ elif not base_name.endswith("_0000.nii") and base_name.endswith(".nii"):
73
+ new_base = base_name.replace(".nii", "_0000.nii")
74
+ else:
75
+ new_base = base_name
76
+
77
+ # Copy the single uploaded file into the temporary input directory
78
+ input_file_path = os.path.join(temp_in_dir, new_base)
79
+ shutil.copy(original_path, input_file_path)
80
+
81
+ # Segmentation (nnU-Net)
82
+ if predictor is None:
83
+ raise RuntimeError("nnU-Net predictor was not initialized properly at startup.")
84
+
85
+ # Predict from the temporary input folder to the temporary output folder
86
+ predictor.predict_from_files(
87
+ temp_in_dir,
88
+ temp_out_dir,
89
+ save_probabilities=False,
90
+ overwrite=False,
91
+ num_processes_preprocessing=2,
92
+ num_processes_segmentation_export=2,
93
+ folder_with_segs_from_prev_stage=None,
94
+ num_parts=1,
95
+ part_id=0
96
+ )
97
+
98
+ output_base = new_base.replace("_0000", "")
99
+ output_mask_path = os.path.join(temp_out_dir, output_base)
100
+
101
+ if not os.path.exists(output_mask_path):
102
+ raise FileNotFoundError("nnU-Net failed to generate the output mask.")
103
+
104
+ # --- Step 3: Feature Extraction ---
105
+ # TODO: Add your custom extraction logic here
106
+ # mask_img = nib.load(output_mask_path)
107
+ # mask_data = mask_img.get_fdata()
108
+ # mac, vev, aev, ttv = extract_features(mask_data, original_scan_data)
109
+
110
+ # Dummy values for UI demonstration
111
+ mac, vev, aev, ttv = 18.4, 62.0, 4.2, 1.8
112
+
113
+ # Risk Prediction
114
+ if risk_model is not None:
115
+ features = np.array([[mac, vev, aev, ttv, int(no_chemo), int(pd_surgery)]])
116
+ prob_r1 = risk_model.predict_proba(features)[0][1]
117
+ else:
118
+ prob_r1 = 0.72 # Dummy value
119
+
120
+ # Format Output
121
+ risk_percentage = prob_r1 * 100
122
+ risk_color = "red" if risk_percentage > 50 else "green"
123
+ risk_display = f"<h2 style='color: {risk_color}; margin-top: 0;'>Predicted probability of R1 resection: {risk_percentage:.1f}%</h2>"
124
+
125
+ return (
126
+ gr.update(value="", visible=False),
127
+ f"{mac:.1f}", f"{vev:.1f}", f"{aev:.1f}", f"{ttv:.1f}",
128
+ risk_display
129
+ )
130
+
131
+ except Exception as e:
132
+ error_msg = f"**Pipeline Error:** {str(e)}\n\n```\n{traceback.format_exc()}\n```"
133
+ return gr.update(value=error_msg, visible=True), *[gr.update(value="")]*4, gr.update(value="")
134
+
135
+ # GRADIO UI LAYOUT
136
+
137
+
138
+ with gr.Blocks(theme=gr.themes.Base()) as demo:
139
+ gr.Markdown("# Preoperative R1 Resection Risk Predictor")
140
+
141
+ with gr.Row():
142
+ with gr.Column(scale=1):
143
+ file_input = gr.File(label="Drop your NIfTI file here", file_types=[".nii.gz", ".nii"], file_count="single")
144
+
145
+ gr.Markdown("### Clinical Metadata")
146
+ no_chemo = gr.Checkbox(label="Absence of Neoadjuvant Chemo (1/0)")
147
+ pd_surgery = gr.Checkbox(label="Patient underwent PD (Pancreaticoduodenectomy) (1/0)")
148
+
149
+ analyze_btn = gr.Button("Run Analysis", variant="primary")
150
+
151
+ with gr.Column(scale=2):
152
+ error_box = gr.Markdown(visible=False)
153
+
154
+ gr.Markdown("### Segmentation Metrics")
155
+ with gr.Row():
156
+ mac_out = gr.Textbox(label="MAC", interactive=False)
157
+ vev_out = gr.Textbox(label="VEV", interactive=False)
158
+ aev_out = gr.Textbox(label="AEV", interactive=False)
159
+ ttv_out = gr.Textbox(label="TTV", interactive=False)
160
+
161
+ gr.Markdown("### Risk Assessment")
162
+ risk_out = gr.HTML(value="<i>Run analysis to see predicted risk...</i>")
163
+
164
+ analyze_btn.click(
165
+ fn=process_scan,
166
+ inputs=[file_input, no_chemo, pd_surgery],
167
+ outputs=[error_box, mac_out, vev_out, aev_out, ttv_out, risk_out]
168
+ )
169
+
170
+ if __name__ == "__main__":
171
+ demo.launch()