dbouget commited on
Commit
9ac677d
·
1 Parent(s): 83f69a3

Bump to newest gradio version

Browse files
.dockerfile → .dockerignore RENAMED
File without changes
.github/workflows/deploy.yml CHANGED
@@ -10,11 +10,11 @@ jobs:
10
  sync-to-hub:
11
  runs-on: ubuntu-latest
12
  steps:
13
- - uses: actions/checkout@v3
14
  with:
15
  fetch-depth: 0
16
  lfs: true
17
  - name: Push to hub
18
  env:
19
  HF_TOKEN: ${{ secrets.HF_TOKEN }}
20
- run: git push https://andreped:$HF_TOKEN@huggingface.co/spaces/andreped/LyNoS main
 
10
  sync-to-hub:
11
  runs-on: ubuntu-latest
12
  steps:
13
+ - uses: actions/checkout@v4
14
  with:
15
  fetch-depth: 0
16
  lfs: true
17
  - name: Push to hub
18
  env:
19
  HF_TOKEN: ${{ secrets.HF_TOKEN }}
20
+ run: git push https://dbouget:$HF_TOKEN@huggingface.co/spaces/dbouget/LyNoS main
.github/workflows/linting.yml CHANGED
@@ -11,16 +11,16 @@ on:
11
 
12
  jobs:
13
  build:
14
- runs-on: ubuntu-20.04
15
  steps:
16
- - uses: actions/checkout@v1
17
  - name: Set up Python 3.10
18
- uses: actions/setup-python@v2
19
  with:
20
  python-version: "3.10"
21
 
22
  - name: Install lint dependencies
23
- run: pip install wheel setuptools black==22.3.0 isort==5.10.1 flake8==4.0.1
24
 
25
  - name: Lint the code
26
  run: sh shell/lint.sh
 
11
 
12
  jobs:
13
  build:
14
+ runs-on: ubuntu-22.04
15
  steps:
16
+ - uses: actions/checkout@v4
17
  - name: Set up Python 3.10
18
+ uses: actions/setup-python@v5
19
  with:
20
  python-version: "3.10"
21
 
22
  - name: Install lint dependencies
23
+ run: pip install wheel setuptools black isort flake8
24
 
25
  - name: Lint the code
26
  run: sh shell/lint.sh
.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
Dockerfile CHANGED
@@ -1,6 +1,6 @@
1
  # read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
  # you will also find guides on how best to write your Dockerfile
3
- FROM python:3.8-slim
4
 
5
  # set language, format and stuff
6
  ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
@@ -56,10 +56,10 @@ WORKDIR $HOME/app
56
  COPY --chown=user . $HOME/app
57
 
58
  # Download pretrained models
59
- RUN wget "https://github.com/raidionics/Raidionics-models/releases/download/1.2.0/Raidionics-CT_LymphNodes-ONNX-v12.zip" && \
60
- unzip "Raidionics-CT_LymphNodes-ONNX-v12.zip" && mkdir -p resources/models/ && mv CT_LymphNodes/ resources/models/CT_LymphNodes/
61
- RUN wget "https://github.com/raidionics/Raidionics-models/releases/download/1.2.0/Raidionics-CT_Lungs-ONNX-v12.zip" && \
62
- unzip "Raidionics-CT_Lungs-ONNX-v12.zip" && mv CT_Lungs/ resources/models/CT_Lungs/
63
 
64
  RUN rm -r *.zip
65
 
 
1
  # read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
  # you will also find guides on how best to write your Dockerfile
3
+ FROM python:3.10-slim
4
 
5
  # set language, format and stuff
6
  ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
 
56
  COPY --chown=user . $HOME/app
57
 
58
  # Download pretrained models
59
+ RUN wget "https://github.com/raidionics/Raidionics-models/releases/download/v1.3.0-rc/Raidionics-CT_LymphNodes-v13.zip" && \
60
+ unzip "Raidionics-CT_LymphNodes-v13.zip" && mkdir -p resources/models/ && mv CT_LymphNodes/ resources/models/CT_LymphNodes/
61
+ RUN wget "https://github.com/raidionics/Raidionics-models/releases/download/v1.3.0-rc/Raidionics-CT_Lungs-v13.zip" && \
62
+ unzip "Raidionics-CT_Lungs-v13.zip" && mv CT_Lungs/ resources/models/CT_Lungs/
63
 
64
  RUN rm -r *.zip
65
 
demo/requirements.txt CHANGED
@@ -1,3 +1,2 @@
1
- raidionicsrads@git+https://github.com/dbouget/raidionics_rads_lib
2
- gradio@https://gradio-pypi-previews.s3.amazonaws.com/c5d763c3305fc143ace9ca6f8bdc32f12cef74d1/gradio-4.42.0-py3-none-any.whl
3
- gradio_shinymodel3d@https://github.com/raidionics/LyNoS/releases/download/ShinyModel3D/gradio_shinymodel3d-0.0.1-py3-none-any.whl
 
1
+ raidionicsrads
2
+ gradio
 
demo/src/gui.py CHANGED
@@ -1,7 +1,9 @@
1
  import os
2
 
3
  import gradio as gr
4
- from gradio_shinymodel3d import ShinyModel3D
 
 
5
 
6
  from .convert import nifti_to_obj
7
  from .css_style import css
@@ -23,36 +25,39 @@ class WebUI:
23
  cwd: str = "/home/user/app/",
24
  share: int = 1,
25
  ):
 
 
 
 
 
 
 
 
26
  # global states
27
  self.images = []
28
  self.pred_images = []
29
 
30
- # @TODO: This should be dynamically set based on chosen volume size
31
- self.nb_slider_items = 820
32
-
33
  self.model_name = model_name
34
  self.cwd = cwd
35
  self.share = share
36
 
37
- self.class_name = "Lymph Nodes" # default
38
  self.class_names = {
39
- "Lymph Nodes": "CT_LymphNodes",
40
  }
41
 
42
  self.result_names = {
43
- "Lymph Nodes": "LymphNodes",
44
  }
45
 
46
- # define widgets not to be rendered immediantly, but later on
47
- self.slider = gr.Slider(
48
- minimum=1,
49
- maximum=self.nb_slider_items,
50
- value=1,
51
- step=1,
52
- label="Which 2D slice to show",
53
  )
54
- # self.volume_renderer = gr.Model3D(
55
- self.volume_renderer = ShinyModel3D()
56
 
57
  def set_class_name(self, value):
58
  LOGGER.info(f"Changed task to: {value}")
@@ -83,25 +88,72 @@ class WebUI:
83
  LOGGER.info("Loading prediction volume to numpy..")
84
  self.pred_images = load_pred_volume_to_numpy("./prediction.nii.gz")
85
 
86
- return "./prediction.obj"
 
 
 
 
 
 
 
 
 
87
 
88
  def get_img_pred_pair(self, k):
89
- k = int(k)
90
- out = gr.AnnotatedImage(
91
- self.combine_ct_and_seg(self.images[k], self.pred_images[k]),
92
- visible=True,
93
- elem_id="model-2d",
94
- )
95
- return out
96
 
97
  def toggle_sidebar(self, state):
98
  state = not state
99
  return gr.update(visible=state), state
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  def run(self):
102
  with gr.Blocks(css=css) as demo:
103
  with gr.Row():
104
- with gr.Column(visible=True, scale=0.2) as sidebar_left:
105
  logs = gr.Textbox(
106
  placeholder="\n" * 16,
107
  label="Logs",
@@ -115,11 +167,13 @@ class WebUI:
115
  container=True,
116
  # line_breaks=True,
117
  )
118
- demo.load(read_logs, None, logs, every=1)
 
 
119
 
120
- with gr.Column():
121
  with gr.Row():
122
- with gr.Column(scale=0.2, min_width=150):
123
  sidebar_state = gr.State(True)
124
 
125
  btn_toggle_sidebar = gr.Button(
@@ -135,36 +189,25 @@ class WebUI:
135
  btn_clear_logs = gr.Button("Clear logs", elem_id="logs-button")
136
  btn_clear_logs.click(flush_logs, [], [])
137
 
138
- file_output = gr.File(file_count="single", elem_id="upload")
139
- file_output.upload(self.upload_file, file_output, file_output)
140
 
141
- model_selector = gr.Dropdown(
142
  list(self.class_names.keys()),
143
  label="Task",
144
  info="Which structure to segment.",
145
  multiselect=False,
146
  )
147
- model_selector.input(
148
- fn=lambda x: self.set_class_name(x),
149
- inputs=model_selector,
150
- outputs=None,
151
- )
152
 
153
- with gr.Column(scale=0.2, min_width=150):
154
- run_btn = gr.Button("Run analysis", variant="primary", elem_id="run-button")
155
- run_btn.click(
156
- fn=lambda x: self.process(x),
157
- inputs=file_output,
158
- outputs=self.volume_renderer,
159
- )
160
 
161
  with gr.Row():
162
  gr.Examples(
163
  examples=[
164
  os.path.join(self.cwd, "test_thorax_CT.nii.gz"),
165
  ],
166
- inputs=file_output,
167
- outputs=file_output,
168
  fn=self.upload_file,
169
  cache_examples=False,
170
  )
@@ -176,21 +219,17 @@ class WebUI:
176
  """
177
  )
178
 
179
- with gr.Row():
180
- with gr.Column():
181
- # create dummy image to be replaced by loaded images
182
- t = gr.AnnotatedImage(visible=True, elem_id="model-2d")
183
-
184
- self.slider.input(
185
- self.get_img_pred_pair,
186
- self.slider,
187
- t,
188
- )
189
-
190
- self.slider.render()
191
-
192
- self.volume_renderer.render()
193
-
194
  # sharing app publicly -> share=True:
195
  # https://gradio.app/sharing-your-app/
196
  # inference times > 60 seconds -> need queue():
 
1
  import os
2
 
3
  import gradio as gr
4
+ # from gradio_shinymodel3d import ShinyModel3D
5
+ from zipfile import ZipFile
6
+ from PIL import Image
7
 
8
  from .convert import nifti_to_obj
9
  from .css_style import css
 
25
  cwd: str = "/home/user/app/",
26
  share: int = 1,
27
  ):
28
+ self.file_output = None
29
+ self.model_selector = None
30
+ self.stripped_cb = None
31
+ self.registered_cb = None
32
+ self.run_btn = None
33
+ self.slider = None
34
+ self.download_file = None
35
+
36
  # global states
37
  self.images = []
38
  self.pred_images = []
39
 
 
 
 
40
  self.model_name = model_name
41
  self.cwd = cwd
42
  self.share = share
43
 
44
+ self.class_name = "LymphNodes" # default
45
  self.class_names = {
46
+ "LymphNodes": "CT_LymphNodes",
47
  }
48
 
49
  self.result_names = {
50
+ "LymphNodes": "LymphNodes",
51
  }
52
 
53
+ self.volume_renderer = gr.Model3D(
54
+ clear_color=[0.0, 0.0, 0.0, 0.0],
55
+ label="3D Model",
56
+ visible=True,
57
+ elem_id="model-3d",
58
+ height=512,
 
59
  )
60
+ # self.volume_renderer = ShinyModel3D()
 
61
 
62
  def set_class_name(self, value):
63
  LOGGER.info(f"Changed task to: {value}")
 
88
  LOGGER.info("Loading prediction volume to numpy..")
89
  self.pred_images = load_pred_volume_to_numpy("./prediction.nii.gz")
90
 
91
+ slider = gr.Slider(
92
+ minimum=0,
93
+ maximum=len(self.images) - 1,
94
+ value=int(len(self.images) / 2),
95
+ step=1,
96
+ label="Which 2D slice to show",
97
+ interactive=True,
98
+ )
99
+
100
+ return "./prediction.obj", slider
101
 
102
  def get_img_pred_pair(self, k):
103
+ img = self.images[k]
104
+ img_pil = Image.fromarray(img)
105
+ seg_list = []
106
+ seg_list.append((self.pred_images[k], self.class_name))
107
+ return img_pil, seg_list
 
 
108
 
109
  def toggle_sidebar(self, state):
110
  state = not state
111
  return gr.update(visible=state), state
112
 
113
+ def package_results(self):
114
+ """Generates text files and zips them."""
115
+ output_dir = "temp_output"
116
+ os.makedirs(output_dir, exist_ok=True)
117
+
118
+ zip_filename = os.path.join(output_dir, "generated_files.zip")
119
+ with ZipFile(zip_filename, 'w') as zf:
120
+ zf.write("./prediction.nii.gz")
121
+
122
+ return zip_filename
123
+
124
+ def setup_interface_outputs(self):
125
+ with gr.Row():
126
+ with gr.Group():
127
+ with gr.Column(scale=2):
128
+ t = gr.AnnotatedImage(
129
+ visible=True,
130
+ elem_id="model-2d",
131
+ color_map={self.class_name: "#ffae00"},
132
+ height=512,
133
+ width=512,
134
+ )
135
+
136
+ self.slider = gr.Slider(
137
+ minimum=0,
138
+ maximum=1,
139
+ value=0,
140
+ step=1,
141
+ label="Which 2D slice to show",
142
+ interactive=True,
143
+ )
144
+
145
+ self.slider.change(fn=self.get_img_pred_pair, inputs=self.slider, outputs=t)
146
+
147
+ with gr.Group():
148
+ self.volume_renderer.render()
149
+ self.download_btn = gr.DownloadButton(label="Download results", visible=False)
150
+ self.download_file = gr.File(label="Download Zip", interactive=True, visible=False)
151
+
152
+
153
  def run(self):
154
  with gr.Blocks(css=css) as demo:
155
  with gr.Row():
156
+ with gr.Column(scale=1, visible=True) as sidebar_left:
157
  logs = gr.Textbox(
158
  placeholder="\n" * 16,
159
  label="Logs",
 
167
  container=True,
168
  # line_breaks=True,
169
  )
170
+ timer = gr.Timer(value=1, active=True)
171
+ timer.tick(fn=read_logs, inputs=None, outputs=logs)
172
+ # demo.load(read_logs, None, logs, every=0.5)
173
 
174
+ with gr.Column(scale=2):
175
  with gr.Row():
176
+ with gr.Column(min_width=150):
177
  sidebar_state = gr.State(True)
178
 
179
  btn_toggle_sidebar = gr.Button(
 
189
  btn_clear_logs = gr.Button("Clear logs", elem_id="logs-button")
190
  btn_clear_logs.click(flush_logs, [], [])
191
 
192
+ self.file_output = gr.File(file_count="single", elem_id="upload")
 
193
 
194
+ self.model_selector = gr.Dropdown(
195
  list(self.class_names.keys()),
196
  label="Task",
197
  info="Which structure to segment.",
198
  multiselect=False,
199
  )
 
 
 
 
 
200
 
201
+ with gr.Column(min_width=150):
202
+ self.run_btn = gr.Button("Run segmentation", variant="primary", elem_id="run-button")
 
 
 
 
 
203
 
204
  with gr.Row():
205
  gr.Examples(
206
  examples=[
207
  os.path.join(self.cwd, "test_thorax_CT.nii.gz"),
208
  ],
209
+ inputs=self.file_output,
210
+ outputs=self.file_output,
211
  fn=self.upload_file,
212
  cache_examples=False,
213
  )
 
219
  """
220
  )
221
 
222
+ self.setup_interface_outputs()
223
+
224
+ # Define the signals/slots
225
+ self.file_output.upload(self.upload_file, self.file_output, self.file_output)
226
+ self.model_selector.input(fn=lambda x: self.set_class_name(x), inputs=self.model_selector, outputs=None)
227
+ self.run_btn.click(fn=self.process, inputs=[self.file_output],
228
+ outputs=[self.volume_renderer, self.slider]).then(fn=lambda:
229
+ gr.DownloadButton(visible=True), inputs=None, outputs=self.download_btn)
230
+ self.download_btn.click(fn=self.package_results, inputs=[], outputs=self.download_file).then(fn=lambda
231
+ file_path: gr.File(label="Download Zip", visible=True, value=file_path), inputs=self.download_file,
232
+ outputs=self.download_file)
 
 
 
 
233
  # sharing app publicly -> share=True:
234
  # https://gradio.app/sharing-your-app/
235
  # inference times > 60 seconds -> need queue():
demo/src/inference.py CHANGED
@@ -3,6 +3,8 @@ import logging
3
  import os
4
  import shutil
5
  import traceback
 
 
6
 
7
 
8
  def run_model(
@@ -10,7 +12,7 @@ def run_model(
10
  model_path: str,
11
  verbose: str = "info",
12
  task: str = "CT_LymphNodes",
13
- name: str = "Lymph nodes",
14
  ):
15
  if verbose == "debug":
16
  logging.getLogger().setLevel(logging.DEBUG)
@@ -55,11 +57,8 @@ def run_model(
55
  rads_config.set("System", "input_folder", patient_directory)
56
  rads_config.set("System", "output_folder", output_path)
57
  rads_config.set("System", "model_folder", model_path)
58
- rads_config.set(
59
- "System",
60
- "pipeline_filename",
61
- os.path.join(model_path, task, "pipeline.json"),
62
- )
63
  rads_config.add_section("Runtime")
64
  rads_config.set("Runtime", "reconstruction_method", "thresholding") # thresholding, probabilities
65
  rads_config.set("Runtime", "reconstruction_order", "resample_first")
@@ -68,16 +67,41 @@ def run_model(
68
  with open("rads_config.ini", "w") as f:
69
  rads_config.write(f)
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  # finally, run inference
72
  from raidionicsrads.compute import run_rads
73
-
74
  run_rads(config_filename="rads_config.ini")
75
 
76
- # rename and move final result
77
- os.rename(
78
- "./result/prediction-" + splits[0] + "/T0/" + splits[0] + "-t1gd_annotation-" + name + ".nii.gz",
79
- "./prediction.nii.gz",
80
- )
 
 
 
 
81
  # Clean-up
82
  if os.path.exists(patient_directory):
83
  shutil.rmtree(patient_directory)
 
3
  import os
4
  import shutil
5
  import traceback
6
+ import json
7
+ import fnmatch
8
 
9
 
10
  def run_model(
 
12
  model_path: str,
13
  verbose: str = "info",
14
  task: str = "CT_LymphNodes",
15
+ name: str = "LymphNodes",
16
  ):
17
  if verbose == "debug":
18
  logging.getLogger().setLevel(logging.DEBUG)
 
57
  rads_config.set("System", "input_folder", patient_directory)
58
  rads_config.set("System", "output_folder", output_path)
59
  rads_config.set("System", "model_folder", model_path)
60
+ rads_config.set('System', 'pipeline_filename', os.path.join(output_path,
61
+ 'test_pipeline.json'))
 
 
 
62
  rads_config.add_section("Runtime")
63
  rads_config.set("Runtime", "reconstruction_method", "thresholding") # thresholding, probabilities
64
  rads_config.set("Runtime", "reconstruction_order", "resample_first")
 
67
  with open("rads_config.ini", "w") as f:
68
  rads_config.write(f)
69
 
70
+ pip = {}
71
+ step_index = 1
72
+ pip_num = str(step_index)
73
+ pip[pip_num] = {}
74
+ pip[pip_num]["task"] = "Classification"
75
+ pip[pip_num]["inputs"] = {} # Empty input means running it on all existing data for the patient
76
+ pip[pip_num]["target"] = ["MRSequence"]
77
+ pip[pip_num]["model"] = "MRI_SequenceClassifier"
78
+ pip[pip_num]["description"] = "Classification of the MRI sequence type for all input scans."
79
+
80
+ step_index = step_index + 1
81
+ pip_num = str(step_index)
82
+ pip[pip_num] = {}
83
+ pip[pip_num]["task"] = 'Model selection'
84
+ pip[pip_num]["model"] = task
85
+ pip[pip_num]["timestamp"] = 0
86
+ pip[pip_num]["format"] = "thresholding"
87
+ pip[pip_num]["description"] = f"Identifying the best {task} segmentation model for existing inputs"
88
+
89
+ with open(os.path.join(output_path, 'test_pipeline.json'), 'w', newline='\n') as outfile:
90
+ json.dump(pip, outfile, indent=4, sort_keys=True)
91
+
92
  # finally, run inference
93
  from raidionicsrads.compute import run_rads
 
94
  run_rads(config_filename="rads_config.ini")
95
 
96
+ logging.info(f"Looking for the following pattern: {task}")
97
+ patterns = [f"*-{name}.*"]
98
+ existing_files = os.listdir(os.path.join(output_path, "T0"))
99
+ logging.info(f"Existing files: {existing_files}")
100
+ fileName = str(os.path.join(output_path, "T0",
101
+ [x for x in existing_files if
102
+ any(fnmatch.fnmatch(x, pattern) for pattern in patterns)][0]))
103
+ os.rename(src=fileName, dst="./prediction.nii.gz")
104
+
105
  # Clean-up
106
  if os.path.exists(patient_directory):
107
  shutil.rmtree(patient_directory)