Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import h5py
|
4 |
+
import numpy as np
|
5 |
+
import gradio as gr
|
6 |
+
import plotly.graph_objects as go
|
7 |
+
from railnet_model import RailNetSystem
|
8 |
+
|
9 |
+
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
|
10 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
|
11 |
+
|
12 |
+
# model = RailNetSystem.from_pretrained(".").cuda()
|
13 |
+
|
14 |
+
model = RailNetSystem.from_pretrained("Tournesol-Saturday/railNet-tooth-segmentation-in-CBCT-image").cuda()
|
15 |
+
|
16 |
+
model.load_weights(from_hub=True, repo_id="Tournesol-Saturday/railNet-tooth-segmentation-in-CBCT-image")
|
17 |
+
|
18 |
+
def wait_for_stable_file(file_path, timeout=5, check_interval=0.2):
|
19 |
+
start_time = time.time()
|
20 |
+
last_size = -1
|
21 |
+
while time.time() - start_time < timeout:
|
22 |
+
current_size = os.path.getsize(file_path)
|
23 |
+
if current_size == last_size:
|
24 |
+
return True
|
25 |
+
last_size = current_size
|
26 |
+
time.sleep(check_interval)
|
27 |
+
return False
|
28 |
+
|
29 |
+
def process_cbct_file(h5_file, save_dir="./output"):
|
30 |
+
if not wait_for_stable_file(h5_file.name):
|
31 |
+
raise RuntimeError("File upload has not been completed or is unstable, please try again.")
|
32 |
+
|
33 |
+
try:
|
34 |
+
with h5py.File(h5_file.name, "r") as f:
|
35 |
+
if "image" not in f or "label" not in f:
|
36 |
+
raise KeyError("The file is missing ‘image’ or ‘label’ value")
|
37 |
+
image = f["image"][:]
|
38 |
+
label = f["label"][:]
|
39 |
+
except Exception as e:
|
40 |
+
raise RuntimeError(f"Failed to read the .h5 file: {str(e)}")
|
41 |
+
|
42 |
+
name = os.path.basename(h5_file.name).replace(".h5", "")
|
43 |
+
pred, dice, jc, hd, asd = model(image, label, save_dir, name)
|
44 |
+
return pred, f"Dice: {dice:.4f}, Jaccard: {jc:.4f}, 95HD: {hd:.2f}, ASD: {asd:.2f}"
|
45 |
+
|
46 |
+
def render_plotly_volume(pred, x_eye=1.25, y_eye=1.25, z_eye=1.25):
|
47 |
+
downsample_factor = 2
|
48 |
+
pred_ds = pred[::downsample_factor, ::downsample_factor, ::downsample_factor]
|
49 |
+
|
50 |
+
fig = go.Figure(data=go.Volume(
|
51 |
+
x=np.repeat(np.arange(pred_ds.shape[0]), pred_ds.shape[1] * pred_ds.shape[2]),
|
52 |
+
y=np.tile(np.repeat(np.arange(pred_ds.shape[1]), pred_ds.shape[2]), pred_ds.shape[0]),
|
53 |
+
z=np.tile(np.arange(pred_ds.shape[2]), pred_ds.shape[0] * pred_ds.shape[1]),
|
54 |
+
value=pred_ds.flatten(),
|
55 |
+
isomin=0.5,
|
56 |
+
isomax=1.0,
|
57 |
+
opacity=0.1,
|
58 |
+
surface_count=1,
|
59 |
+
colorscale=[[0, 'rgb(255, 0, 0)'], [1, 'rgb(255, 0, 0)']],
|
60 |
+
showscale=False
|
61 |
+
))
|
62 |
+
|
63 |
+
fig.update_layout(
|
64 |
+
scene=dict(
|
65 |
+
xaxis=dict(visible=False),
|
66 |
+
yaxis=dict(visible=False),
|
67 |
+
zaxis=dict(visible=False),
|
68 |
+
camera=dict(eye=dict(x=x_eye, y=y_eye, z=z_eye))
|
69 |
+
),
|
70 |
+
margin=dict(l=0, r=0, b=0, t=0)
|
71 |
+
)
|
72 |
+
return fig
|
73 |
+
|
74 |
+
def clear_all():
|
75 |
+
return None, "", None
|
76 |
+
|
77 |
+
with gr.Blocks() as demo:
|
78 |
+
gr.HTML("<div style='text-align: center; font-size: 22px; font-weight: bold;'>🦷 Demo of RailNet: A CBCT Tooth Segmentation System</div>")
|
79 |
+
gr.HTML("<div style='text-align: center; font-size: 15px'>✅ Steps: Upload a CBCT example file (.h5) → Automatic inference and metrics display → View 3D segmentation result (Mouse drag and scroll wheel zooming)</div>")
|
80 |
+
|
81 |
+
gr.HTML("<div style='font-size: 15px; font-weight: bold;'>📂 Step 1: Upload the .h5 example file containing both ‘image’ and ‘label’ values</div>")
|
82 |
+
file_input = gr.File()
|
83 |
+
with gr.Row():
|
84 |
+
clear_btn = gr.Button("清除", variant="secondary")
|
85 |
+
submit_btn = gr.Button("提交", variant="primary")
|
86 |
+
|
87 |
+
gr.HTML("<div style='font-size: 15px; font-weight: bold;'>📊 Step 2: Metrics (Dice, Jaccard, 95HD, ASD)</div>")
|
88 |
+
result_text = gr.Textbox()
|
89 |
+
hidden_pred = gr.State(value=None)
|
90 |
+
|
91 |
+
gr.HTML("<div style='font-size: 15px; font-weight: bold;'>👁️ Step 3: 3D Visualisation</div>")
|
92 |
+
plot_output = gr.Plot()
|
93 |
+
|
94 |
+
def handle_upload(h5_file):
|
95 |
+
pred, metrics = process_cbct_file(h5_file)
|
96 |
+
fig = render_plotly_volume(pred)
|
97 |
+
return metrics, pred, fig
|
98 |
+
|
99 |
+
submit_btn.click(
|
100 |
+
fn=handle_upload,
|
101 |
+
inputs=[file_input],
|
102 |
+
outputs=[result_text, hidden_pred, plot_output]
|
103 |
+
)
|
104 |
+
|
105 |
+
def update_view(pred, x_eye, y_eye, z_eye):
|
106 |
+
if pred is None:
|
107 |
+
return gr.update()
|
108 |
+
return render_plotly_volume(pred, x_eye, y_eye, z_eye)
|
109 |
+
|
110 |
+
clear_btn.click(
|
111 |
+
fn=clear_all,
|
112 |
+
inputs=[],
|
113 |
+
outputs=[file_input, result_text, plot_output]
|
114 |
+
)
|
115 |
+
|
116 |
+
demo.launch()
|
117 |
+
|