Spaces:
Sleeping
Sleeping
File size: 9,469 Bytes
883f80d 97e9ddc 883f80d fec5809 7c7ec80 963a894 6f9d64a 883f80d fec5809 59f797f 97e9ddc 883f80d 97e9ddc aa832f1 97e9ddc 883f80d 97e9ddc 883f80d f51c8e0 883f80d 1b4af4d 883f80d 1b4af4d 883f80d 97e9ddc 883f80d aa832f1 883f80d 97e9ddc f26565c 97e9ddc f26565c 4146752 97e9ddc 883f80d 9b3d576 883f80d 97e9ddc 883f80d 97e9ddc 9b3d576 883f80d 97e9ddc 4146752 8291c90 c6b094e 8291c90 c6b094e f26565c 4146752 883f80d 9b3d576 97e9ddc 9b3d576 8291c90 aa832f1 97e9ddc 8291c90 4146752 ee7e255 8291c90 f51c8e0 4146752 883f80d 97e9ddc aa832f1 883f80d aa832f1 883f80d 97e9ddc 6f9d64a 9b3d576 97e9ddc 9b3d576 6f9d64a 7c7ec80 6f9d64a 5ad5add 6f9d64a 7c7ec80 6f9d64a 9b3d576 59f797f 5ad5add 7c7ec80 4e6e6d6 c58ed05 4e6e6d6 7c7ec80 4e6e6d6 7c7ec80 4e6e6d6 6f9d64a 8291c90 6f9d64a 59f797f e12b67a 59f797f 5ad5add 59f797f aa832f1 883f80d 5ad5add 4e6e6d6 9b3d576 4146752 5ad5add 4146752 5ad5add 4146752 59f797f 883f80d 64a799b f26565c 64a799b 59f797f 5ad5add 59f797f 5ad5add 8291c90 59f797f 8291c90 59f797f 97e9ddc 883f80d |
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 |
import os
import gradio as gr
from .convert import nifti_to_obj
from .css_style import css
from .inference import run_model
from .logger import flush_logs
from .logger import read_logs
from .logger import setup_logger
from .utils import load_ct_to_numpy
from .utils import load_pred_volume_to_numpy
# setup logging
LOGGER = setup_logger()
class WebUI:
def __init__(
self,
model_name: str = None,
cwd: str = "/home/user/app/",
share: int = 1,
):
# global states
self.images = []
self.pred_images = []
# @TODO: This should be dynamically set based on chosen volume size
self.nb_slider_items = 820
self.model_name = model_name
self.cwd = cwd
self.share = share
self.filename = None
self.extension = None
self.class_name = "airways" # default
self.class_names = {
"airways": "CT_Airways",
"lungs": "CT_Lungs",
}
self.result_names = {
"airways": "Airways",
"lungs": "Lungs",
}
# define widgets not to be rendered immediantly, but later on
self.slider = gr.Slider(
minimum=1,
maximum=self.nb_slider_items,
value=1,
step=1,
label="Which 2D slice to show",
)
self.volume_renderer = gr.Model3D(
clear_color=[0.0, 0.0, 0.0, 0.0],
label="3D Model",
show_label=True,
visible=True,
elem_id="model-3d",
camera_position=[90, 180, 768],
height=512,
)
def set_class_name(self, value):
LOGGER.info(f"Changed task to: {value}")
self.class_name = value
def combine_ct_and_seg(self, img, pred):
return (img, [(pred, self.class_name)])
def upload_file(self, file):
out = file.name
LOGGER.info(f"File uploaded: {out}")
return out
def process(self, mesh_file_name):
path = mesh_file_name.name
curr = path.split("/")[-1]
self.extension = ".".join(curr.split(".")[1:])
self.filename = (
curr.split(".")[0] + "-" + self.class_names[self.class_name]
)
run_model(
path,
model_path=os.path.join(self.cwd, "resources/models/"),
task=self.class_names[self.class_name],
name=self.result_names[self.class_name],
output_filename=self.filename + "." + self.extension,
)
LOGGER.info("Converting prediction NIfTI to OBJ...")
nifti_to_obj(path=self.filename + "." + self.extension)
LOGGER.info("Loading CT to numpy...")
self.images = load_ct_to_numpy(path)
LOGGER.info("Loading prediction volume to numpy..")
self.pred_images = load_pred_volume_to_numpy(
self.filename + "." + self.extension
)
return "./prediction.obj"
def download_prediction(self):
if (self.filename is None) or (self.extension is None):
LOGGER.error(
"The prediction is not available or ready to download. Wait until the result is available in the 3D viewer."
)
raise ValueError("Run inference before downloading!")
return self.filename + "." + self.extension
def get_img_pred_pair(self, k):
k = int(k)
out = gr.AnnotatedImage(
self.combine_ct_and_seg(self.images[k], self.pred_images[k]),
visible=True,
elem_id="model-2d",
color_map={self.class_name: "#ffae00"},
height=512,
width=512,
)
return out
def toggle_sidebar(self, state):
state = not state
return gr.update(visible=state), state
def run(self):
with gr.Blocks(css=css) as demo:
with gr.Row():
with gr.Column(visible=True, scale=0.2) as sidebar_left:
logs = gr.Textbox(
placeholder="\n" * 16,
label="Logs",
info="Verbose from inference will be displayed below.",
lines=36,
max_lines=36,
autoscroll=True,
elem_id="logs",
show_copy_button=True,
container=True,
)
demo.load(read_logs, None, logs, every=1)
with gr.Column():
with gr.Row():
with gr.Column(scale=1, min_width=150):
sidebar_state = gr.State(True)
btn_toggle_sidebar = gr.Button(
"Toggle Sidebar",
elem_id="toggle-button",
)
btn_toggle_sidebar.click(
self.toggle_sidebar,
[sidebar_state],
[sidebar_left, sidebar_state],
)
btn_clear_logs = gr.Button(
"Clear logs", elem_id="logs-button"
)
btn_clear_logs.click(flush_logs, [], [])
file_output = gr.File(
file_count="single",
elem_id="upload",
scale=3,
)
file_output.upload(
self.upload_file, file_output, file_output
)
model_selector = gr.Dropdown(
list(self.class_names.keys()),
label="Task",
info="Which structure to segment.",
multiselect=False,
scale=1,
)
model_selector.input(
fn=lambda x: self.set_class_name(x),
inputs=model_selector,
outputs=None,
)
with gr.Column(scale=1, min_width=150):
run_btn = gr.Button(
"Run analysis",
variant="primary",
elem_id="run-button",
)
run_btn.click(
fn=lambda x: self.process(x),
inputs=file_output,
outputs=self.volume_renderer,
)
download_btn = gr.DownloadButton(
"Download prediction",
visible=True,
variant="secondary",
elem_id="download",
)
download_btn.click(
fn=self.download_prediction,
inputs=None,
outputs=download_btn,
)
with gr.Row():
gr.Examples(
examples=[
os.path.join(self.cwd, "test_thorax_CT.nii.gz"),
],
inputs=file_output,
outputs=file_output,
fn=self.upload_file,
cache_examples=True,
)
gr.Markdown(
"""
**NOTE:** Inference might take several minutes (Airways: ~8 minutes), see logs to the left. \\
The segmentation will be available in the 2D and 3D viewers below when finished.
"""
)
with gr.Row():
with gr.Group():
with gr.Column():
# create dummy image to be replaced by loaded images
t = gr.AnnotatedImage(
visible=True,
elem_id="model-2d",
color_map={self.class_name: "#ffae00"},
# height=512,
# width=512,
)
self.slider.input(
self.get_img_pred_pair,
self.slider,
t,
)
self.slider.render()
with gr.Group(): # gr.Box():
self.volume_renderer.render()
# sharing app publicly -> share=True:
# https://gradio.app/sharing-your-app/
# inference times > 60 seconds -> need queue():
# https://github.com/tloen/alpaca-lora/issues/60#issuecomment-1510006062
demo.queue().launch(
server_name="0.0.0.0", server_port=7860, share=self.share
)
|