File size: 9,785 Bytes
c54c2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bbf9a
c54c2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dead14d
c54c2bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dead14d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""BioLoom: zero-shot biomedical image classification.

Loads the BioLoom (DFN-2B) checkpoint from ChartFoundation/BioLoom-models via the
authors' open_clip fork (vendored here, MIT licence) and scores an uploaded image
against a user-editable list of candidate classes, following the exact protocol
from the BioLoom evaluation suite: each class is described by its two prompt
views, the two normalized view embeddings are averaged and re-normalized into a
class prototype, and the (normalized) image embedding is compared by cosine
similarity.
"""

from pathlib import Path

import spaces  # must precede torch
import torch
import torch.nn.functional as F
from PIL import Image

import gradio as gr

from huggingface_hub import snapshot_download

from open_clip import create_model_from_pretrained, get_tokenizer
from presets import PRESETS

MODELS_REPO = "ChartFoundation/BioLoom-models"
CHECKPOINT_DIR = "Main/DFN-2B"
ARCH = "BioClinicalModernBERT-large-ViT-L-14-pretrained"
MAX_CLASSES = 50

# ------------------------------------------------------------- module load
_snapshot = snapshot_download(
    MODELS_REPO,
    allow_patterns=[
        f"{CHECKPOINT_DIR}/open_clip_pytorch_model.bin",
        f"{CHECKPOINT_DIR}/open_clip_config.json",
    ],
)
_directory = Path(_snapshot) / CHECKPOINT_DIR

model, preprocess = create_model_from_pretrained(f"local-dir:{_directory}", device="cpu")
model = model.eval().to("cuda")  # eager: ZeroGPU packs weights, streams them in per call
tokenizer = get_tokenizer(ARCH)  # built-in arch config resolves the HF tokenizer


def _parse_classes(text):
    """Split the label textbox into (display, viewA, viewB) triples.

    Accepts either plain labels (one per line, optionally comma separated) which
    get default prompt views, or 'label | viewA | viewB' lines for full control.
    """
    lines = [ln.strip() for ln in text.split("\n") if ln.strip()]
    if len(lines) == 1 and "|" not in lines[0] and "," in lines[0]:
        lines = [s.strip() for s in lines[0].split(",") if s.strip()]

    out = []
    for line in lines:
        parts = [p.strip() for p in line.split("|")]
        label = parts[0]
        view_a = parts[1] if len(parts) > 1 else f"a biomedical image of {label}"
        view_b = parts[2] if len(parts) > 2 else f"a photo of {label}"
        out.append((label, view_a, view_b))
    return out[:MAX_CLASSES]


def _class_prototypes(classes):
    """Encode two prompt views per class and collapse to normalized prototypes.

    Matches the authors' evaluation/common.py: normalize each view, average the
    two views per class, re-normalize.
    """
    flat = [v for (_, a, b) in classes for v in (a, b)]
    tokens = tokenizer(flat).to("cuda")
    with torch.inference_mode(), torch.autocast("cuda", enabled=True):
        feats = model.encode_text(tokens)
    feats = F.normalize(feats.float(), dim=-1)
    means = feats.reshape(len(classes), 2, -1).mean(1)
    return F.normalize(means, dim=-1)


@spaces.GPU(duration=10)
def classify(image, labels_text: str, top_k: int = 5):
    """Zero-shot classify a biomedical image against candidate classes.

    Args:
        image: the image file to classify.
        labels_text: candidate classes, one per line. A line may be a bare label
            or 'label | first prompt view | second prompt view'; bare labels get
            default biomedical prompt views.
        top_k: number of top classes to show in the bar chart.

    Returns:
        Markdown header with the top prediction, the full ranking as
        (class, cosine similarity) rows, and the top-k bar chart data.
    """
    classes = _parse_classes(labels_text)
    if image is None:
        raise gr.Error("Please upload an image first.")
    if len(classes) < 2:
        raise gr.Error("Please provide at least two candidate classes.")
    top_k = max(1, int(top_k))

    x = preprocess(Image.open(image).convert("RGB")).unsqueeze(0).to("cuda")
    prototypes = _class_prototypes(classes)
    with torch.inference_mode(), torch.autocast("cuda", enabled=True):
        img_feat = model.encode_image(x)
    img_feat = F.normalize(img_feat.float(), dim=-1)
    scores = (img_feat @ prototypes.T).squeeze(0)
    order = torch.argsort(scores, descending=True).tolist()

    ranked = [[classes[i][0], round(float(scores[i]), 4)] for i in order]
    header = f"### Predicted class: **{ranked[0][0]}**  \nCosine similarity: {ranked[0][1]:.4f}"
    chart = {
        "Class": [r[0] for r in ranked[:top_k]],
        "Similarity": [r[1] for r in ranked[:top_k]],
    }
    return header, ranked, chart


def _preset_to_text(preset):
    """Render a preset as 'label | viewA | viewB' lines for the editable textbox."""
    return "\n".join(f"{c[0]} | {c[1]} | {c[2]}" for c in preset["classes"])


def apply_preset(preset_key: str):
    """Load a benchmark preset's classes and prompts into the textbox.

    Args:
        preset_key: key into PRESETS, or '__custom__' to clear the textbox.

    Returns:
        A gr.update for the classes textbox.
    """
    if preset_key == "__custom__":
        return gr.update(value="")
    return gr.update(value=_preset_to_text(PRESETS[preset_key]))


def preset_info(preset_key: str) -> str:
    """Return a one-line description of the selected preset."""
    if preset_key == "__custom__":
        return "*Custom classes — one per line, optionally 'label | view A | view B'.*"
    p = PRESETS[preset_key]
    return (
        f"*{p['title']} · {p['domain']} · {len(p['classes'])} classes — prompt views "
        "verbatim from the [BioLoom evaluation suite]"
        "(https://huggingface.co/datasets/ChartFoundation/BioLoom-EvalSuite).*"
    )


# ------------------------------------------------------------------- UI
CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""

PRESET_CHOICES = [("Custom", "__custom__")] + [
    (v["title"], k) for k, v in PRESETS.items()
]

with gr.Blocks() as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            """
            # 🔬 BioLoom — zero-shot biomedical image classification
            Upload a biomedical image and score it against candidate classes with
            [BioLoom (DFN-2B)](https://huggingface.co/ChartFoundation/BioLoom-models), a
            ~454M-parameter biomedical CLIP-style dual encoder (ViT-L/14 vision tower +
            BioClinical ModernBERT text tower) trained on 52.4M figure-caption pairs from
            scientific articles. Class prompts default to the exact two-view prompts from the
            [BioLoom evaluation suite](https://huggingface.co/datasets/ChartFoundation/BioLoom-EvalSuite);
            scoring follows the published prototype protocol (per-class mean of the two
            normalized view embeddings, re-normalized, cosine similarity to the image).
            """
        )

        with gr.Row():
            with gr.Column(scale=1):
                image_in = gr.Image(
                    type="filepath", label="Image", sources=["upload", "clipboard"], height=320
                )
            with gr.Column(scale=1):
                preset_dd = gr.Dropdown(
                    choices=PRESET_CHOICES,
                    value="hyperkvasir",
                    label="Benchmark preset (loads classes below)",
                    filterable=True,
                )
                preset_md = gr.Markdown(preset_info("hyperkvasir"))
                labels_tb = gr.Textbox(
                    label="Candidate classes (editable, one per line)",
                    placeholder="impacted stool\npolyp\nnormal z-line\n…",
                    lines=8,
                    max_lines=14,
                    value=_preset_to_text(PRESETS["hyperkvasir"]),
                )
                top_k_slider = gr.Slider(1, 15, value=5, step=1, label="Classes to chart")
                run_btn = gr.Button("Classify", variant="primary")

        header_md = gr.Markdown("")
        ranked_df = gr.Dataframe(
            headers=["Class", "Cosine similarity"],
            datatype=["str", "number"],
            label="Ranking — all candidate classes",
            interactive=False,
            wrap=True,
        )
        chart = gr.BarPlot(
            label="Top classes by cosine similarity",
            x="Class",
            y="Similarity",
            tooltip=["Class", "Similarity"],
            height=300,
        )

        preset_dd.input(apply_preset, inputs=[preset_dd], outputs=[labels_tb])
        preset_dd.input(preset_info, inputs=[preset_dd], outputs=[preset_md])
        run_btn.click(
            classify,
            inputs=[image_in, labels_tb, top_k_slider],
            outputs=[header_md, ranked_df, chart],
            api_name="classify",
        )

        _TEXT = {k: _preset_to_text(PRESETS[k]) for k in ("hyperkvasir", "gastrovision", "derm12345")}
        gr.Examples(
            examples=[
                ["examples/hyperkvasir_0.jpg", _TEXT["hyperkvasir"]],
                ["examples/hyperkvasir_1.jpg", _TEXT["hyperkvasir"]],
                ["examples/gastrovision_0.jpg", _TEXT["gastrovision"]],
                ["examples/gastrovision_1.jpg", _TEXT["gastrovision"]],
                ["examples/derm12345_0.jpg", _TEXT["derm12345"]],
                ["examples/derm12345_1.jpg", _TEXT["derm12345"]],
            ],
            inputs=[image_in, labels_tb],
            fn=classify,
            outputs=[header_md, ranked_df, chart],
            cache_examples=True,
            cache_mode="lazy",
            examples_per_page=6,
            label="Examples — benchmark test images (click loads image + its class list)",
        )

demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)