multimodalart HF Staff commited on
Commit
bf63b9e
Β·
verified Β·
1 Parent(s): 61044b6

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,13 +1,38 @@
1
  ---
2
- title: Jolia
3
- emoji: πŸ“š
4
- colorFrom: pink
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 6.22.0
8
- python_version: '3.12'
9
  app_file: app.py
 
 
 
10
  pinned: false
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Jolia 3D CT Zero-Shot
3
+ emoji: 🫁
4
+ colorFrom: red
5
+ colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.22.0
 
8
  app_file: app.py
9
+ short_description: Zero-shot 3D CT classification with Jolia
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 1h
12
  pinned: false
13
  ---
14
 
15
+ # 🫁 Jolia β€” 3D CT Foundation Model (Zero-Shot)
16
+
17
+ Interactive demo of [`raidium/Jolia`](https://huggingface.co/raidium/Jolia), a 3D CT foundation
18
+ model that encodes a whole CT volume into a global embedding plus 102 per-organ query embeddings,
19
+ all aligned with radiology-report text via CLIP.
20
+
21
+ Upload a chest/abdominal CT volume (NIfTI `.nii` / `.nii.gz`) and score it against arbitrary text
22
+ prompts β€” no fine-tuning:
23
+
24
+ - **Global zero-shot** β€” the whole-volume embedding vs each text prompt (calibrated CLIP logits β†’ match probability).
25
+ - **Per-organ zero-shot** β€” routes short findings phrases to a specific organ's query embedding via the ParallelOrganCLIP head.
26
+
27
+ Paired text encoder: [`Qwen/Qwen3-Embedding-8B`](https://huggingface.co/Qwen/Qwen3-Embedding-8B) (bf16).
28
+
29
+ ## Example data
30
+
31
+ The bundled example CT volumes come from the **TotalSegmentator** dataset
32
+ ([MedOtter/totalsegmentator-organs](https://huggingface.co/datasets/MedOtter/totalsegmentator-organs),
33
+ CC-BY-4.0; Wasserthal et al., *Radiology: Artificial Intelligence* 2023).
34
+
35
+ ## Disclaimer
36
+
37
+ ⚠️ Research preview. **Not a medical device and not for clinical use.** Jolia is a feature extractor
38
+ for research on adult chest/abdominal CT and does not produce diagnoses.
app.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
3
+
4
+ import sys
5
+ import time
6
+ import numpy as np
7
+ import spaces
8
+ import torch
9
+ import gradio as gr
10
+ import nibabel as nib
11
+ from huggingface_hub import snapshot_download
12
+ from transformers import AutoModel
13
+
14
+ # ----------------------------------------------------------------------------
15
+ # Model loading (module scope, eager .to("cuda") for ZeroGPU)
16
+ # ----------------------------------------------------------------------------
17
+ JOLIA_ID = "raidium/Jolia"
18
+ TEXT_ID = "Qwen/Qwen3-Embedding-8B"
19
+
20
+ # Jolia ships its preprocessing + text-encoder helpers as plain modules in the
21
+ # repo. Grab them via snapshot_download and put them on sys.path.
22
+ _repo = snapshot_download(JOLIA_ID)
23
+ sys.path.append(_repo)
24
+ from preprocessing_jolia import JoliaPreprocessor # noqa: E402
25
+ from text_encoder_jolia import JoliaTextEncoder # noqa: E402
26
+
27
+ print("Loading Jolia vision backbone ...")
28
+ jolia = AutoModel.from_pretrained(JOLIA_ID, trust_remote_code=True).eval().to("cuda")
29
+
30
+ print("Loading paired text encoder (Qwen3-Embedding-8B, bf16) ...")
31
+ text_encoder = (
32
+ JoliaTextEncoder.from_pretrained(
33
+ TEXT_ID,
34
+ dtype=torch.bfloat16,
35
+ context_length=jolia.config.text_context_length,
36
+ )
37
+ .eval()
38
+ .to("cuda")
39
+ )
40
+
41
+ preprocessor = JoliaPreprocessor()
42
+ ORGAN_NAMES = jolia.organ_slot_names # 102 named organ slots
43
+ print(f"Ready. {len(ORGAN_NAMES)} organ slots available.")
44
+
45
+ DEFAULT_PROMPTS = (
46
+ "a chest CT showing pneumonia\n"
47
+ "a CT with a lung nodule\n"
48
+ "a CT showing pleural effusion\n"
49
+ "a normal chest CT\n"
50
+ "a CT showing cardiomegaly"
51
+ )
52
+ DEFAULT_ORGANS = ["lungs", "heart", "liver", "spleen", "kidneys", "pancreas"]
53
+ DEFAULT_ORGAN_PROMPTS = "a lesion\nan enlarged organ\nlooks normal"
54
+
55
+
56
+ # ----------------------------------------------------------------------------
57
+ # NIfTI reading + light preview (CPU, cheap)
58
+ # ----------------------------------------------------------------------------
59
+ def _read_nifti(path):
60
+ """Load a NIfTI CT volume -> (volume float32 (H,W,D), spacing (r,c,s) mm)."""
61
+ img = nib.load(path)
62
+ vol = np.asarray(img.get_fdata(), dtype=np.float32)
63
+ if vol.ndim != 3:
64
+ raise gr.Error(
65
+ f"Expected a 3D CT volume, got shape {vol.shape}. "
66
+ "Upload a single-series CT scan in NIfTI (.nii / .nii.gz) format."
67
+ )
68
+ zooms = img.header.get_zooms()[:3]
69
+ spacing = tuple(float(z) if z and z > 0 else 1.0 for z in zooms)
70
+ return vol, spacing
71
+
72
+
73
+ def _window(slice_hu, center=40.0, width=400.0):
74
+ """Apply a CT window (default soft-tissue) and map to 0-255 uint8."""
75
+ lo, hi = center - width / 2.0, center + width / 2.0
76
+ s = np.clip((slice_hu - lo) / (hi - lo), 0.0, 1.0)
77
+ return (s * 255.0).astype(np.uint8)
78
+
79
+
80
+ def preview_nifti(path):
81
+ """Render 3 mid-slices (axial / coronal / sagittal) of the uploaded CT."""
82
+ if not path:
83
+ return None
84
+ vol, spacing = _read_nifti(path)
85
+ # vol is (H, W, D). Build a simple montage of mid slices.
86
+ h, w, d = vol.shape
87
+ ax = np.rot90(_window(vol[:, :, d // 2])) # axial
88
+ cor = np.rot90(_window(vol[:, w // 2, :])) # coronal
89
+ sag = np.rot90(_window(vol[h // 2, :, :])) # sagittal
90
+ # Pad to same height and concat side by side.
91
+ hh = max(ax.shape[0], cor.shape[0], sag.shape[0])
92
+
93
+ def _pad(a):
94
+ pad = hh - a.shape[0]
95
+ if pad > 0:
96
+ a = np.pad(a, ((0, pad), (0, 0)), constant_values=0)
97
+ return a
98
+
99
+ montage = np.concatenate([_pad(ax), _pad(cor), _pad(sag)], axis=1)
100
+ return montage
101
+
102
+
103
+ def _parse_prompts(text):
104
+ return [ln.strip() for ln in (text or "").replace(",", "\n").splitlines() if ln.strip()]
105
+
106
+
107
+ def _estimate_duration(nifti_path, prompts_text, organs, organ_prompts_text, *args, **kwargs):
108
+ n_prompts = max(1, len(_parse_prompts(prompts_text)) + len(_parse_prompts(organ_prompts_text)))
109
+ n_organs = max(1, len(organs or []))
110
+ return min(180, 45 + n_prompts * 3 + n_organs * 2)
111
+
112
+
113
+ # ----------------------------------------------------------------------------
114
+ # Inference (GPU)
115
+ # ----------------------------------------------------------------------------
116
+ @spaces.GPU(duration=_estimate_duration)
117
+ def classify(nifti_path, prompts_text, organs, organ_prompts_text,
118
+ progress=gr.Progress(track_tqdm=True)):
119
+ """Zero-shot classification of a 3D CT volume with the Jolia foundation model.
120
+
121
+ Args:
122
+ nifti_path: path to a CT volume in NIfTI (.nii/.nii.gz) format.
123
+ prompts_text: newline/comma separated text prompts scored against the
124
+ whole-volume (global) embedding.
125
+ organs: list of organ names to run per-organ (query-routed) zero-shot on.
126
+ organ_prompts_text: short findings phrases scored per organ.
127
+
128
+ Returns:
129
+ A global-classification table and a per-organ score table.
130
+ """
131
+ if not nifti_path:
132
+ raise gr.Error("Please upload a CT volume (.nii or .nii.gz) first.")
133
+
134
+ prompts = _parse_prompts(prompts_text)
135
+ if not prompts:
136
+ raise gr.Error("Please enter at least one text prompt for global classification.")
137
+ organ_prompts = _parse_prompts(organ_prompts_text)
138
+
139
+ t0 = time.perf_counter()
140
+ vol, spacing = _read_nifti(nifti_path)
141
+ image = preprocessor(vol, resolution=spacing).unsqueeze(0).to("cuda")
142
+
143
+ with torch.no_grad():
144
+ # --- Global zero-shot ---
145
+ text_features = text_encoder(prompts).to("cuda")
146
+ logits = jolia.zero_shot(image, text_features) # (1, N) calibrated
147
+ probs = torch.sigmoid(logits)[0].float().cpu().numpy()
148
+ cosine = jolia.zero_shot(image, text_features, calibrated=False)[0].float().cpu().numpy()
149
+
150
+ order = np.argsort(-probs)
151
+ global_rows = [
152
+ [prompts[i], round(float(probs[i]), 4), round(float(cosine[i]), 4)]
153
+ for i in order
154
+ ]
155
+
156
+ # --- Per-organ zero-shot ---
157
+ organ_rows = []
158
+ if organs and organ_prompts:
159
+ with torch.no_grad():
160
+ organ_text = text_encoder(organ_prompts).to("cuda")
161
+ per_organ = jolia.zero_shot_organs(image, organ_text, organs=list(organs))
162
+ for organ in organs:
163
+ lg = per_organ[organ][0].float().cpu().numpy()
164
+ pr = 1.0 / (1.0 + np.exp(-lg))
165
+ row = [organ] + [round(float(x), 4) for x in pr]
166
+ organ_rows.append(row)
167
+
168
+ elapsed = time.perf_counter() - t0
169
+ organ_headers = ["organ"] + (organ_prompts if organ_prompts else ["(no prompts)"])
170
+ info = (
171
+ f"Volume {vol.shape} @ {tuple(round(s, 2) for s in spacing)} mm β€’ "
172
+ f"{len(prompts)} global prompt(s), {len(organs or [])} organ(s) β€’ "
173
+ f"{elapsed:.1f}s"
174
+ )
175
+ return (
176
+ gr.update(value=global_rows),
177
+ gr.update(value=organ_rows, headers=organ_headers),
178
+ info,
179
+ )
180
+
181
+
182
+ # ----------------------------------------------------------------------------
183
+ # UI
184
+ # ----------------------------------------------------------------------------
185
+ CSS = """
186
+ #col-container { max-width: 1150px; margin: 0 auto; }
187
+ .dark .gradio-container { color: var(--body-text-color); }
188
+ """
189
+
190
+ with gr.Blocks(theme=gr.themes.Citrus(), css=CSS, title="Jolia β€” 3D CT Zero-Shot") as demo:
191
+ with gr.Column(elem_id="col-container"):
192
+ gr.Markdown(
193
+ """
194
+ # 🫁 Jolia β€” 3D CT Foundation Model (Zero-Shot)
195
+
196
+ [`raidium/Jolia`](https://huggingface.co/raidium/Jolia) is a 3D CT foundation model that
197
+ encodes a whole CT volume into a global embedding + 102 per-organ query embeddings, aligned
198
+ with radiology-report text via CLIP. Upload a chest/abdominal CT volume and score it against
199
+ **arbitrary text prompts** β€” no fine-tuning β€” both globally and per organ.
200
+
201
+ Paired text encoder: `Qwen/Qwen3-Embedding-8B`.
202
+ ⚠️ **Research preview β€” not a medical device, not for clinical use.**
203
+ """
204
+ )
205
+
206
+ with gr.Row():
207
+ with gr.Column(scale=1):
208
+ nifti = gr.File(
209
+ label="CT volume (NIfTI: .nii / .nii.gz)",
210
+ file_types=[".nii", ".gz"],
211
+ type="filepath",
212
+ )
213
+ preview = gr.Image(
214
+ label="Preview (axial Β· coronal Β· sagittal, soft-tissue window)",
215
+ height=240,
216
+ )
217
+ run = gr.Button("Run zero-shot classification", variant="primary")
218
+ with gr.Column(scale=1):
219
+ prompts_box = gr.Textbox(
220
+ label="Global prompts (one per line)",
221
+ value=DEFAULT_PROMPTS,
222
+ lines=6,
223
+ )
224
+ with gr.Accordion("Per-organ zero-shot (query-routed)", open=True):
225
+ organs_box = gr.Dropdown(
226
+ label="Organs to score",
227
+ choices=ORGAN_NAMES,
228
+ value=DEFAULT_ORGANS,
229
+ multiselect=True,
230
+ )
231
+ organ_prompts_box = gr.Textbox(
232
+ label="Per-organ findings phrases (one per line)",
233
+ value=DEFAULT_ORGAN_PROMPTS,
234
+ lines=3,
235
+ )
236
+
237
+ info_out = gr.Markdown()
238
+ global_out = gr.Dataframe(
239
+ headers=["prompt", "match probability", "cosine"],
240
+ label="Global zero-shot β€” whole-volume embedding vs text (sorted by probability)",
241
+ wrap=True,
242
+ )
243
+ organ_out = gr.Dataframe(
244
+ label="Per-organ zero-shot β€” organ-query embedding vs findings text (match probability)",
245
+ wrap=True,
246
+ )
247
+
248
+ gr.Examples(
249
+ examples=[
250
+ ["examples/s0000_ct.nii.gz", DEFAULT_PROMPTS, DEFAULT_ORGANS, DEFAULT_ORGAN_PROMPTS],
251
+ ["examples/s0004_ct.nii.gz", DEFAULT_PROMPTS, DEFAULT_ORGANS, DEFAULT_ORGAN_PROMPTS],
252
+ ["examples/s0010_ct.nii.gz", DEFAULT_PROMPTS, DEFAULT_ORGANS, DEFAULT_ORGAN_PROMPTS],
253
+ ],
254
+ inputs=[nifti, prompts_box, organs_box, organ_prompts_box],
255
+ outputs=[global_out, organ_out, info_out],
256
+ fn=classify,
257
+ cache_examples=True,
258
+ cache_mode="lazy",
259
+ )
260
+
261
+ gr.Markdown(
262
+ """
263
+ ---
264
+ Example CT volumes from the **TotalSegmentator** dataset
265
+ ([MedOtter/totalsegmentator-organs](https://huggingface.co/datasets/MedOtter/totalsegmentator-organs),
266
+ CC-BY-4.0; Wasserthal et al.). Model: [raidium/Jolia](https://huggingface.co/raidium/Jolia).
267
+ """
268
+ )
269
+
270
+ nifti.change(fn=preview_nifti, inputs=nifti, outputs=preview)
271
+ run.click(
272
+ fn=classify,
273
+ inputs=[nifti, prompts_box, organs_box, organ_prompts_box],
274
+ outputs=[global_out, organ_out, info_out],
275
+ api_name="classify",
276
+ )
277
+
278
+ if __name__ == "__main__":
279
+ demo.launch(mcp_server=True)
examples/s0000_ct.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddaf56bf37da43616e20e8cadc154536127cc42923c5b92c7085ad6b7663c267
3
+ size 14678484
examples/s0004_ct.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3b79850e0a7d425bce31b51608c934c07bb81db51894dbf1308890a116b258b
3
+ size 29168502
examples/s0010_ct.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ceb0d9b62dce2c18a155b0e9fdd57b161f6c72973933c9ff29fe6a2dcac41291
3
+ size 29412677
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ transformers
2
+ timm
3
+ einops
4
+ numpy
5
+ safetensors
6
+ nibabel
7
+ accelerate