Gayatrii commited on
Commit
e095cbb
·
verified ·
1 Parent(s): f8fc18e

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +146 -0
  2. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import torch
4
+ import gradio as gr
5
+ from PIL import Image
6
+
7
+ from diffusers import StableDiffusion3ControlNetPipeline
8
+ from transformers import T5Tokenizer
9
+
10
+
11
+ # --- Semantic palette from the model card ---
12
+ CLASS_DICT_ATLAS = {
13
+ 0: (0, 0, 0),
14
+ 1: (255, 60, 0),
15
+ 2: (255, 60, 232),
16
+ 3: (134, 79, 117),
17
+ 4: (125, 0, 190),
18
+ 5: (117, 200, 191),
19
+ 6: (230, 91, 101),
20
+ 7: (255, 0, 155),
21
+ 8: (75, 205, 155),
22
+ 9: (100, 37, 200),
23
+ }
24
+
25
+ NAME_CLASS_DICT = {
26
+ 0: "background",
27
+ 1: "aorta",
28
+ 2: "kidney_left",
29
+ 3: "liver",
30
+ 4: "postcava",
31
+ 5: "stomach",
32
+ 6: "gall_bladder",
33
+ 7: "kidney_right",
34
+ 8: "pancreas",
35
+ 9: "spleen",
36
+ }
37
+
38
+
39
+ def mask_to_labels(mask_rgb: Image.Image) -> np.ndarray:
40
+ """Convert RGB mask -> label map using exact color matches."""
41
+ arr = np.asarray(mask_rgb.convert("RGB"), dtype=np.uint8)
42
+ h, w, _ = arr.shape
43
+ labels = np.zeros((h, w), dtype=np.int16)
44
+
45
+ for cls_id, rgb in CLASS_DICT_ATLAS.items():
46
+ m = np.all(arr == np.array(rgb, dtype=np.uint8), axis=-1)
47
+ labels[m] = cls_id
48
+ return labels
49
+
50
+
51
+ # --- Load pipeline once (cached) ---
52
+ MODEL_ID = "onkarsus13/Semantic-Control-Stable-diffusion-3-M-Mask2CT-Atlas"
53
+ PIPE = None
54
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
55
+
56
+
57
+ def load_pipe():
58
+ global PIPE
59
+ if PIPE is not None:
60
+ return PIPE
61
+
62
+ dtype = torch.float16 if DEVICE == "cuda" else torch.float32
63
+
64
+ pipe = StableDiffusion3ControlNetPipeline.from_pretrained(
65
+ MODEL_ID,
66
+ torch_dtype=dtype,
67
+ safety_checker=None,
68
+ feature_extractor=None,
69
+ )
70
+
71
+ # Model card explicitly loads tokenizer_3 from this repo
72
+ pipe.tokenizer_3 = T5Tokenizer.from_pretrained(MODEL_ID, subfolder="tokenizer_3")
73
+
74
+ if DEVICE == "cuda":
75
+ pipe.to("cuda")
76
+ # Helps reduce VRAM spikes on smaller GPUs (slower but safer)
77
+ pipe.enable_model_cpu_offload()
78
+ else:
79
+ pipe.to("cpu")
80
+
81
+ PIPE = pipe
82
+ return PIPE
83
+
84
+
85
+ def generate(mask_img, steps, cond_scale, seed):
86
+ if mask_img is None:
87
+ return None, "Please upload a semantic mask image."
88
+
89
+ pipe = load_pipe()
90
+
91
+ mask_pil = mask_img.convert("RGB")
92
+ orig_size = mask_pil.size
93
+
94
+ labels = mask_to_labels(mask_pil)
95
+ unique_ids = np.unique(labels).tolist()
96
+ organ_ids = [i for i in unique_ids if i != 0]
97
+
98
+ if organ_ids:
99
+ organ_names = [NAME_CLASS_DICT[i] for i in organ_ids]
100
+ prompt = "CT image containing " + " ".join(organ_names)
101
+ else:
102
+ organ_names = []
103
+ prompt = "CT image containing abdominal organs"
104
+
105
+ gen = torch.Generator(device=DEVICE).manual_seed(int(seed))
106
+
107
+ out = pipe(
108
+ prompt=prompt,
109
+ control_image=mask_pil,
110
+ height=128,
111
+ width=128,
112
+ num_inference_steps=int(steps),
113
+ generator=gen,
114
+ controlnet_conditioning_scale=float(cond_scale),
115
+ ).images[0]
116
+
117
+ out = out.resize(orig_size)
118
+ msg = f"Detected classes: {', '.join(['background'] + organ_names)}\nPrompt: {prompt}"
119
+ return out, msg
120
+
121
+
122
+ with gr.Blocks(title="Mask2CT Atlas Demo (SD3 ControlNet)") as demo:
123
+ gr.Markdown(
124
+ """
125
+ # Mask → CT (Atlas) demo
126
+ Upload an **RGB semantic mask** (segmentation map) using the palette from the model card.
127
+ The app auto-detects organs in the mask and generates a synthetic CT slice.
128
+ """
129
+ )
130
+
131
+ with gr.Row():
132
+ mask_in = gr.Image(label="Semantic mask (RGB)", type="pil")
133
+ ct_out = gr.Image(label="Generated CT", type="pil")
134
+
135
+ with gr.Row():
136
+ steps = gr.Slider(10, 80, value=50, step=1, label="Inference steps")
137
+ cond = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="ControlNet conditioning scale")
138
+ seed = gr.Number(value=1, precision=0, label="Seed")
139
+
140
+ btn = gr.Button("Generate")
141
+ info = gr.Textbox(label="Info", lines=3)
142
+
143
+ btn.click(fn=generate, inputs=[mask_in, steps, cond, seed], outputs=[ct_out, info])
144
+
145
+ if __name__ == "__main__":
146
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ diffusers>=0.36.0
3
+ transformers
4
+ accelerate
5
+ safetensors
6
+ sentencepiece
7
+ numpy
8
+ pillow
9
+ gradio