ayyuce commited on
Commit
d0bb937
·
verified ·
1 Parent(s): f42d4be

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import shutil
5
+ import uuid
6
+ import zipfile
7
+
8
+ def run_segmentation(uploaded_file, modality):
9
+ job_id = str(uuid.uuid4())
10
+ input_filename = f"input_{job_id}.nii.gz"
11
+ output_folder = f"segmentations_{job_id}"
12
+
13
+ with open(input_filename, "wb") as f:
14
+ f.write(uploaded_file.read())
15
+
16
+ command = ["TotalSegmentator", "-i", input_filename, "-o", output_folder]
17
+ if modality == "MR":
18
+ command.extend(["--task", "total_mr"])
19
+
20
+ try:
21
+ subprocess.run(command, check=True)
22
+ except subprocess.CalledProcessError as e:
23
+ return f"Error during segmentation: {e}"
24
+
25
+ zip_filename = f"segmentations_{job_id}.zip"
26
+ with zipfile.ZipFile(zip_filename, "w", zipfile.ZIP_DEFLATED) as zipf:
27
+ for root, dirs, files in os.walk(output_folder):
28
+ for file in files:
29
+ file_path = os.path.join(root, file)
30
+ arcname = os.path.relpath(file_path, output_folder)
31
+ zipf.write(file_path, arcname)
32
+
33
+ os.remove(input_filename)
34
+ shutil.rmtree(output_folder)
35
+
36
+ return zip_filename
37
+
38
+ with gr.Blocks() as demo:
39
+ gr.Markdown("# TotalSegmentator Gradio App")
40
+ gr.Markdown(
41
+ "Upload a CT or MR image (in NIfTI format) and run segmentation using TotalSegmentator. "
42
+ "For MR images, the task flag is set accordingly."
43
+ )
44
+
45
+ with gr.Row():
46
+ uploaded_file = gr.File(label="Upload NIfTI Image (.nii.gz)")
47
+ modality = gr.Radio(choices=["CT", "MR"], label="Select Image Modality", value="CT")
48
+
49
+ output_file = gr.File(label="Download Segmentation Output (zip)")
50
+
51
+ run_btn = gr.Button("Run Segmentation")
52
+ run_btn.click(fn=run_segmentation, inputs=[uploaded_file, modality], outputs=output_file)
53
+
54
+ demo.launch()