mgbam commited on
Commit
d58d5be
·
verified ·
1 Parent(s): 48ac3b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -89
app.py CHANGED
@@ -1,109 +1,186 @@
 
1
  import torch
2
  from PIL import Image
3
- import gradio as gr
4
- import spaces
5
- from transformers import AutoProcessor, AutoModel, CLIPVisionModel
6
- import torch.nn.functional as F
7
 
8
  #---------------------------------
9
  #++++++++ Model ++++++++++
10
  #---------------------------------
11
 
12
  def load_biomedclip_model():
13
- """Loads the BiomedCLIP model and tokenizer."""
14
- biomedclip_model_name = 'microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224'
15
- processor = AutoProcessor.from_pretrained(biomedclip_model_name)
16
- config = AutoModel.from_pretrained(biomedclip_model_name).config
17
- vision_model = CLIPVisionModel.from_pretrained(config.vision_config._name_or_path, torch_dtype=torch.float16).cuda().eval()
18
- text_model = AutoModel.from_pretrained(config.text_config._name_or_path).cuda().eval()
19
- return vision_model, text_model, processor
20
-
21
- def compute_similarity(image, text, vision_model, text_model, biomedclip_processor):
22
- """Computes similarity scores using BiomedCLIP."""
23
- with torch.no_grad():
24
- inputs = biomedclip_processor(text=text, images=image, return_tensors="pt", padding=True).to(text_model.device)
25
- text_embeds = text_model(**inputs).last_hidden_state[:,0,:] # Extract the [CLS] token
26
- image_inputs = biomedclip_processor(images=image, return_tensors="pt").to(vision_model.device)
27
- image_embeds = vision_model(**image_inputs).last_hidden_state[:,0,:] # Extract the image embedding
28
- image_embeds = F.normalize(image_embeds, dim=-1)
29
- text_embeds = F.normalize(text_embeds, dim=-1)
30
- similarity = (text_embeds @ image_embeds.transpose(-1, -2)).squeeze()
31
- return similarity
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  #---------------------------------
34
  #++++++++ Gradio ++++++++++
35
  #---------------------------------
36
 
37
- def gradio_reset(chat_state, img_list, similarity_output):
38
- """Resets the chat state and image list."""
39
- if chat_state is not None:
40
- chat_state.messages = []
41
- if img_list is not None:
42
- img_list = []
43
- return None, gr.update(value=None, interactive=True), gr.update(placeholder='Please upload your medical image first', interactive=False), gr.update(value="Upload & Start Analysis", interactive=True), chat_state, img_list, gr.update(value="", visible=False)
44
-
45
- def upload_img(gr_img, text_input, chat_state, similarity_output):
46
- """Handles image upload."""
47
- if gr_img is None:
48
- return None, None, gr.update(interactive=True), chat_state, None, gr.update(visible=False)
49
- img_list = [gr_img]
50
- return gr.update(interactive=False), gr.update(interactive=True, placeholder='Type and press Enter'), gr.update(value="Start Analysis", interactive=False), chat_state, img_list, gr.update(visible=True)
51
-
52
- def gradio_ask(user_message, chatbot, chat_state):
53
- """Handles user input."""
54
- if not user_message:
55
- return gr.update(interactive=True, placeholder='Input should not be empty!'), chatbot, chat_state
56
- chatbot = chatbot + [[user_message, None]]
57
- return '', chatbot, chat_state
58
-
59
- @spaces.GPU
60
- def gradio_answer(chatbot, chat_state, img_list, vision_model, text_model, biomedclip_processor, similarity_output):
61
- """Computes and displays similarity scores."""
62
- if not img_list:
63
- return chatbot, chat_state, img_list, similarity_output
64
-
65
- similarity_score = compute_similarity(img_list[0], chatbot[-1][0], vision_model, text_model, biomedclip_processor)
66
- print(f'Similarity Score is: {similarity_score}')
67
-
68
- similarity_text = f"Similarity Score: {similarity_score:.3f}"
69
- chatbot[-1][1] = similarity_text
70
- return chatbot, chat_state, img_list, gr.update(value=similarity_text, visible=True)
71
-
72
-
73
- title = """<h1 align="center">Medical Image Analysis Tool</h1>"""
74
- description = """<h3>Upload medical images, ask questions, and receive a similarity score.</h3>"""
75
- examples_list=[
76
- ["./case1.png", "Analyze the X-ray for any abnormalities."],
77
- ["./case2.jpg", "What type of disease may be present?"],
78
- ["./case1.png","What is the anatomical structure shown here?"]
79
- ]
80
-
81
- # Load models and related resources outside of the Gradio block for loading on startup
82
- vision_model, text_model, biomedclip_processor = load_biomedclip_model()
83
 
84
- with gr.Blocks() as demo:
85
- gr.Markdown(title)
86
- gr.Markdown(description)
87
 
88
- with gr.Row():
89
- with gr.Column(scale=0.5):
90
- image = gr.Image(type="pil", label="Medical Image")
91
- upload_button = gr.Button(value="Upload & Start Analysis", interactive=True, variant="primary")
92
- clear = gr.Button("Restart")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- with gr.Column():
95
- chat_state = gr.State()
96
- img_list = gr.State()
97
- chatbot = gr.Chatbot(label='Medical Analysis')
98
- text_input = gr.Textbox(label='Analysis Query', placeholder='Please upload your medical image first', interactive=False)
99
- similarity_output = gr.Textbox(label="Similarity Score", visible=False, interactive=False)
100
- gr.Examples(examples=examples_list, inputs=[image, text_input])
101
 
102
- upload_button.click(upload_img, [image, text_input, chat_state, similarity_output], [image, text_input, upload_button, chat_state, img_list, similarity_output])
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
- text_input.submit(gradio_ask, [text_input, chatbot, chat_state], [text_input, chatbot, chat_state]).then(
105
- gradio_answer, [chatbot, chat_state, img_list, vision_model, text_model, biomedclip_processor, similarity_output], [chatbot, chat_state, img_list, similarity_output]
 
 
 
 
106
  )
107
- clear.click(gradio_reset, [chat_state, img_list, similarity_output], [chatbot, image, text_input, upload_button, chat_state, img_list, similarity_output], queue=False)
108
 
109
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
  import torch
3
  from PIL import Image
4
+ import open_clip
5
+ import numpy as np
6
+ from LeGrad.legrad import LeWrapper, LePreprocess
7
+ import cv2
8
 
9
  #---------------------------------
10
  #++++++++ Model ++++++++++
11
  #---------------------------------
12
 
13
  def load_biomedclip_model():
14
+ """Loads the BiomedCLIP model and prepares it with LeGrad."""
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+ model_name = "hf-hub:microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224"
17
+ model, preprocess = open_clip.create_model_from_pretrained(
18
+ model_name=model_name, device=device
19
+ )
20
+ tokenizer = open_clip.get_tokenizer(model_name=model_name)
21
+ model = LeWrapper(model) # Equip the model with LeGrad
22
+ preprocess = LePreprocess(
23
+ preprocess=preprocess, image_size=448
24
+ ) # Optional higher-res preprocessing
25
+ return model, preprocess, tokenizer, device
26
+
27
+ def classify_image_with_biomedclip(editor_value, prompts, model, preprocess, tokenizer, device):
28
+ """Classifies the image with the given text prompts using BiomedCLIP."""
29
+ if editor_value is None:
30
+ return None, None
31
+
32
+ image = editor_value["composite"]
33
+
34
+ if not isinstance(image, Image.Image):
35
+ image = Image.fromarray(image)
36
+
37
+ image_input = preprocess(image).unsqueeze(0).to(device)
38
+ text_inputs = tokenizer(prompts).to(device)
39
+
40
+ text_embeddings = model.encode_text(text_inputs, normalize=True)
41
+ image_embeddings = model.encode_image(image_input, normalize=True)
42
+
43
+ similarity = (
44
+ model.logit_scale.exp() * image_embeddings @ text_embeddings.T
45
+ ).softmax(dim=-1)
46
+ probabilities = similarity[0].detach().cpu().numpy()
47
+ explanation_maps = model.compute_legrad_clip(
48
+ image=image_input, text_embedding=text_embeddings[probabilities.argmax()]
49
+ )
50
+
51
+ explanation_maps = explanation_maps.squeeze(0).detach().cpu().numpy()
52
+ explanation_map = (explanation_maps * 255).astype(np.uint8)
53
+
54
+ return probabilities, explanation_map
55
+
56
+ def prepare_output_image(image, explanation_map):
57
+ """Prepares the output image by blending the original image with the explanation map."""
58
+ if not isinstance(image, Image.Image):
59
+ image = Image.fromarray(image)
60
+
61
+ explanation_image = explanation_map[0]
62
+ if isinstance(explanation_image, torch.Tensor):
63
+ explanation_image = explanation_image.cpu().numpy()
64
+
65
+ explanation_image_resized = cv2.resize(
66
+ explanation_image, (image.width, image.height)
67
+ )
68
+
69
+ explanation_image_resized = cv2.normalize(
70
+ explanation_image_resized, None, 0, 255, cv2.NORM_MINMAX
71
+ )
72
+
73
+ explanation_colormap = cv2.applyColorMap(
74
+ explanation_image_resized.astype(np.uint8), cv2.COLORMAP_JET
75
+ )
76
+
77
+ image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
78
+
79
+ alpha = 0.5
80
+ blended_image = cv2.addWeighted(image_cv, 1 - alpha, explanation_colormap, alpha, 0)
81
+
82
+ blended_image_rgb = cv2.cvtColor(blended_image, cv2.COLOR_BGR2RGB)
83
+ output_image = Image.fromarray(blended_image_rgb)
84
+ return output_image
85
 
86
  #---------------------------------
87
  #++++++++ Gradio ++++++++++
88
  #---------------------------------
89
 
90
+ def update_output(editor_value, prompts_input, model, preprocess, tokenizer, device):
91
+ """Main function to update the output based on image and prompts."""
92
+ prompts_list = [p.strip() for p in prompts_input.split(",") if p.strip()]
93
+ if not prompts_list:
94
+ return None, "Please enter at least one prompt."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
+ probabilities, explanation_map = classify_image_with_biomedclip(
97
+ editor_value, prompts_list, model, preprocess, tokenizer, device
98
+ )
99
 
100
+ if probabilities is None:
101
+ return None, "Please upload and annotate an image."
102
+
103
+ prob_text = "\n".join(
104
+ [
105
+ f"{prompt}: {prob*100:.2f}%"
106
+ for prompt, prob in zip(prompts_list, probabilities)
107
+ ]
108
+ )
109
+
110
+ image = editor_value["composite"]
111
+ output_image = prepare_output_image(image, explanation_map)
112
+
113
+ return output_image, prob_text
114
+
115
+ def clear_inputs():
116
+ return None, ""
117
+
118
+ # Load model outside the Gradio blocks
119
+ model, preprocess, tokenizer, device = load_biomedclip_model()
120
 
 
 
 
 
 
 
 
121
 
122
+ with gr.Blocks() as demo:
123
+ gr.Markdown(
124
+ "# ✨ Visual Prompt Engineering for Medical Vision Language Models in Radiology ✨",
125
+ elem_id="main-header",
126
+ )
127
+
128
+ gr.Markdown(
129
+ "This tool applies **visual prompt engineering to improve the classification of medical images using the BiomedCLIP**[3], the current state of the art in zero-shot biomedical image classification. By uploading biomedical images (e.g., chest X-rays), you can manually annotate areas of interest directly on the image. These annotations serve as visual prompts, which guide the model's attention on the region of interest. This technique improves the model's ability to focus on subtle yet important details.\n\n"
130
+ "After annotating and inputting text prompts (e.g., 'A chest X-ray with a benign/malignant lung nodule indicated by a red circle'), the tool returns classification results. These results are accompanied by **explainability maps** generated by **LeGrad** [3], which show where the model focused its attention, conditioned on the highest scoring text prompt. This helps to better interpret the model's decision-making process.\n\n"
131
+ "In our paper **[Visual Prompt Engineering for Medical Vision Language Models in Radiology](https://arxiv.org/pdf/2408.15802)**, we show, that visual prompts such as arrows, circles, and contours improve the zero-shot classification of biomedical vision language models in radiology."
132
+ )
133
+
134
+ gr.Markdown("---")
135
 
136
+ gr.Markdown(
137
+ "## 📝 **How It Works**:\n"
138
+ "1. **Upload** a biomedical image.\n"
139
+ "2. **Annotate** the image using the built-in editor to highlight regions of interest.\n"
140
+ "3. **Enter text prompts** separated by comma (e.g., 'A chest X-ray with a (benign/malignant) lung nodule indicated by a red circle').\n"
141
+ "4. **Submit** to get class probabilities and an explainability map conditioned on the highest scoring text prompt."
142
  )
 
143
 
144
+ gr.Markdown("---")
145
+
146
+ with gr.Row():
147
+ with gr.Column():
148
+ image_editor = gr.ImageEditor(
149
+ label="Upload and Annotate Image",
150
+ type="pil",
151
+ interactive=True,
152
+ mirror_webcam=False,
153
+ layers=False,
154
+ scale=2,
155
+ )
156
+ prompts_input = gr.Textbox(
157
+ placeholder="Enter prompts, comma-separated", label="Text Prompts"
158
+ )
159
+ submit_button = gr.Button("Submit", variant="primary")
160
+ with gr.Column():
161
+ output_image = gr.Image(
162
+ type="pil",
163
+ label="Output Image with Explanation Map",
164
+ )
165
+ prob_text = gr.Textbox(
166
+ label="Class Probabilities", interactive=False, lines=10
167
+ )
168
+
169
+ inputs = [image_editor, prompts_input]
170
+ outputs = [output_image, prob_text]
171
+ submit_button.click(fn=update_output, inputs=inputs, outputs=outputs,
172
+ _js=None,
173
+ api_name=None,
174
+ scroll_to_output=True,
175
+ show_progress=True,
176
+ queue=True,
177
+ batch=False,
178
+ preprocess=True,
179
+ postprocess=True,
180
+ cancels=None,
181
+ show_loading_status=True,
182
+ scroll_to_output_id=None,
183
+ model=model, preprocess=preprocess, tokenizer=tokenizer, device=device
184
+ )
185
+ if __name__ == "__main__":
186
+ demo.launch(share=True)