shakesbeardz commited on
Commit
42a56da
1 Parent(s): 309c17a

added app.py

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. app.py +337 -0
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Bioclip Demo
3
  emoji: 🐘
4
  colorFrom: indigo
5
  colorTo: purple
 
1
  ---
2
+ title: ReefNet Demo
3
  emoji: 🐘
4
  colorFrom: indigo
5
  colorTo: purple
app.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import heapq
3
+ import json
4
+ import os
5
+ import logging
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ import polars as pl
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from open_clip import create_model, get_tokenizer
13
+ from torchvision import transforms
14
+
15
+ from templates import openai_imagenet_template
16
+ from components.query import get_sample
17
+
18
+ log_format = "[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s"
19
+ logging.basicConfig(level=logging.INFO, format=log_format)
20
+ logger = logging.getLogger()
21
+
22
+ hf_token = os.getenv("HF_TOKEN")
23
+
24
+ # For sample images
25
+ METADATA_PATH = "components/metadata.csv"
26
+ # Read page ID as int and filter out smaller ablation duplicated training split
27
+ metadata_df = pl.read_csv(METADATA_PATH, low_memory = False)
28
+ metadata_df = metadata_df.with_columns(pl.col("eol_page_id").cast(pl.Int64))
29
+
30
+ model_str = "hf-hub:imageomics/bioclip"
31
+ tokenizer_str = "ViT-B-16"
32
+
33
+ txt_emb_npy = "txt_emb_species.npy"
34
+ txt_names_json = "txt_emb_species.json"
35
+
36
+ min_prob = 1e-9
37
+ k = 5
38
+
39
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
40
+
41
+ preprocess_img = transforms.Compose(
42
+ [
43
+ transforms.ToTensor(),
44
+ transforms.Resize((224, 224), antialias=True),
45
+ transforms.Normalize(
46
+ mean=(0.48145466, 0.4578275, 0.40821073),
47
+ std=(0.26862954, 0.26130258, 0.27577711),
48
+ ),
49
+ ]
50
+ )
51
+
52
+ ranks = ("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species")
53
+
54
+ open_domain_examples = [
55
+ ["examples/Ursus-arctos.jpeg", "Species"],
56
+ ["examples/Phoca-vitulina.png", "Species"],
57
+ ["examples/Felis-catus.jpeg", "Genus"],
58
+ ["examples/Sarcoscypha-coccinea.jpeg", "Order"],
59
+ ]
60
+ zero_shot_examples = [
61
+ [
62
+ "examples/Ursus-arctos.jpeg",
63
+ "brown bear\nblack bear\npolar bear\nkoala bear\ngrizzly bear",
64
+ ],
65
+ ["examples/milk-snake.png", "coral snake\nmilk snake"],
66
+ ["examples/coral-snake.jpeg", "coral snake\nmilk snake"],
67
+ [
68
+ "examples/Carnegiea-gigantea.png",
69
+ "Carnegiea gigantea\nSchlumbergera opuntioides\nMammillaria albicoma",
70
+ ],
71
+ [
72
+ "examples/Amanita-muscaria.jpeg",
73
+ "Amanita fulva\nAmanita vaginata (grisette)\nAmanita calyptrata (coccoli)\nAmanita crocea\nAmanita rubescens (blusher)\nAmanita caesarea (Caesar's mushroom)\nAmanita jacksonii (American Caesar's mushroom)\nAmanita muscaria (fly agaric)\nAmanita pantherina (panther cap)",
74
+ ],
75
+ [
76
+ "examples/Actinostola-abyssorum.png",
77
+ "Animalia Cnidaria Hexacorallia Actiniaria Actinostolidae Actinostola abyssorum\nAnimalia Cnidaria Hexacorallia Actiniaria Actinostolidae Actinostola bulbosa\nAnimalia Cnidaria Hexacorallia Actiniaria Actinostolidae Actinostola callosa\nAnimalia Cnidaria Hexacorallia Actiniaria Actinostolidae Actinostola capensis\nAnimalia Cnidaria Hexacorallia Actiniaria Actinostolidae Actinostola carlgreni",
78
+ ],
79
+ [
80
+ "examples/Sarcoscypha-coccinea.jpeg",
81
+ "scarlet elf cup (coccinea)\nscharlachroter kelchbecherling (austriaca)\ncrimson cup (dudleyi)\nstalked scarlet cup (occidentalis)",
82
+ ],
83
+ [
84
+ "examples/Onoclea-hintonii.jpg",
85
+ "Onoclea attenuata\nOnoclea boryana\nOnoclea hintonii\nOnoclea intermedia\nOnoclea sensibilis",
86
+ ],
87
+ [
88
+ "examples/Onoclea-sensibilis.jpg",
89
+ "Onoclea attenuata\nOnoclea boryana\nOnoclea hintonii\nOnoclea intermedia\nOnoclea sensibilis",
90
+ ],
91
+ ]
92
+
93
+
94
+ def indexed(lst, indices):
95
+ return [lst[i] for i in indices]
96
+
97
+
98
+ @torch.no_grad()
99
+ def get_txt_features(classnames, templates):
100
+ all_features = []
101
+ for classname in classnames:
102
+ txts = [template(classname) for template in templates]
103
+ txts = tokenizer(txts).to(device)
104
+ txt_features = model.encode_text(txts)
105
+ txt_features = F.normalize(txt_features, dim=-1).mean(dim=0)
106
+ txt_features /= txt_features.norm()
107
+ all_features.append(txt_features)
108
+ all_features = torch.stack(all_features, dim=1)
109
+ return all_features
110
+
111
+
112
+ @torch.no_grad()
113
+ def zero_shot_classification(img, cls_str: str) -> dict[str, float]:
114
+ classes = [cls.strip() for cls in cls_str.split("\n") if cls.strip()]
115
+ txt_features = get_txt_features(classes, openai_imagenet_template)
116
+
117
+ img = preprocess_img(img).to(device)
118
+ img_features = model.encode_image(img.unsqueeze(0))
119
+ img_features = F.normalize(img_features, dim=-1)
120
+
121
+ logits = (model.logit_scale.exp() * img_features @ txt_features).squeeze()
122
+ probs = F.softmax(logits, dim=0).to("cpu").tolist()
123
+ return {cls: prob for cls, prob in zip(classes, probs)}
124
+
125
+
126
+ def format_name(taxon, common):
127
+ taxon = " ".join(taxon)
128
+ if not common:
129
+ return taxon
130
+ return f"{taxon} ({common})"
131
+
132
+
133
+ @torch.no_grad()
134
+ def open_domain_classification(img, rank: int, return_all=False):
135
+ """
136
+ Predicts from the entire tree of life.
137
+ If targeting a higher rank than species, then this function predicts among all
138
+ species, then sums up species-level probabilities for the given rank.
139
+ """
140
+
141
+ logger.info(f"Starting open domain classification for rank: {rank}")
142
+ img = preprocess_img(img).to(device)
143
+ img_features = model.encode_image(img.unsqueeze(0))
144
+ img_features = F.normalize(img_features, dim=-1)
145
+
146
+ logits = (model.logit_scale.exp() * img_features @ txt_emb).squeeze()
147
+ probs = F.softmax(logits, dim=0)
148
+
149
+ if rank + 1 == len(ranks):
150
+ topk = probs.topk(k)
151
+ prediction_dict = {
152
+ format_name(*txt_names[i]): prob for i, prob in zip(topk.indices, topk.values)
153
+ }
154
+ logger.info(f"Top K predictions: {prediction_dict}")
155
+ top_prediction_name = format_name(*txt_names[topk.indices[0]]).split("(")[0]
156
+ logger.info(f"Top prediction name: {top_prediction_name}")
157
+ sample_img, taxon_url = get_sample(metadata_df, top_prediction_name, rank)
158
+ if return_all:
159
+ return prediction_dict, sample_img, taxon_url
160
+ return prediction_dict
161
+
162
+ output = collections.defaultdict(float)
163
+ for i in torch.nonzero(probs > min_prob).squeeze():
164
+ output[" ".join(txt_names[i][0][: rank + 1])] += probs[i]
165
+
166
+ topk_names = heapq.nlargest(k, output, key=output.get)
167
+ prediction_dict = {name: output[name] for name in topk_names}
168
+ logger.info(f"Top K names for output: {topk_names}")
169
+ logger.info(f"Prediction dictionary: {prediction_dict}")
170
+
171
+ top_prediction_name = topk_names[0]
172
+ logger.info(f"Top prediction name: {top_prediction_name}")
173
+ sample_img, taxon_url = get_sample(metadata_df, top_prediction_name, rank)
174
+ logger.info(f"Sample image and taxon URL: {sample_img}, {taxon_url}")
175
+
176
+ if return_all:
177
+ return prediction_dict, sample_img, taxon_url
178
+ return prediction_dict
179
+
180
+
181
+ def change_output(choice):
182
+ return gr.Label(num_top_classes=k, label=ranks[choice], show_label=True, value=None)
183
+
184
+
185
+ if __name__ == "__main__":
186
+ logger.info("Starting.")
187
+ model = create_model(model_str, output_dict=True, require_pretrained=True)
188
+ model = model.to(device)
189
+ logger.info("Created model.")
190
+
191
+ model = torch.compile(model)
192
+ logger.info("Compiled model.")
193
+
194
+ tokenizer = get_tokenizer(tokenizer_str)
195
+
196
+ txt_emb = torch.from_numpy(np.load(txt_emb_npy, mmap_mode="r")).to(device)
197
+ with open(txt_names_json) as fd:
198
+ txt_names = json.load(fd)
199
+
200
+ done = txt_emb.any(axis=0).sum().item()
201
+ total = txt_emb.shape[1]
202
+ status_msg = ""
203
+ if done != total:
204
+ status_msg = f"{done}/{total} ({done / total * 100:.1f}%) indexed"
205
+
206
+ with gr.Blocks() as app:
207
+
208
+ with gr.Tab("Open-Ended"):
209
+ with gr.Row(variant = "panel", elem_id = "images_panel"):
210
+ with gr.Column():
211
+ img_input = gr.Image(height = 400, sources=["upload"])
212
+
213
+ with gr.Column():
214
+ # display sample image of top predicted taxon
215
+ sample_img = gr.Image(label = "Sample Image of Predicted Taxon",
216
+ height = 400,
217
+ show_download_button = False)
218
+
219
+ taxon_url = gr.HTML(label = "More Information",
220
+ elem_id = "url"
221
+ )
222
+
223
+ with gr.Row():
224
+ with gr.Column():
225
+ rank_dropdown = gr.Dropdown(
226
+ label="Taxonomic Rank",
227
+ info="Which taxonomic rank to predict. Fine-grained ranks (genus, species) are more challenging.",
228
+ choices=ranks,
229
+ value="Species",
230
+ type="index",
231
+ )
232
+ open_domain_btn = gr.Button("Submit", variant="primary")
233
+ with gr.Column():
234
+ open_domain_output = gr.Label(
235
+ num_top_classes=k,
236
+ label="Prediction",
237
+ show_label=True,
238
+ value=None,
239
+ )
240
+ # open_domain_flag_btn = gr.Button("Flag Mistake", variant="primary")
241
+
242
+ with gr.Row():
243
+ gr.Examples(
244
+ examples=open_domain_examples,
245
+ inputs=[img_input, rank_dropdown],
246
+ cache_examples=True,
247
+ fn=lambda img, rank: open_domain_classification(img, rank, return_all=False),
248
+ outputs=[open_domain_output],
249
+ )
250
+ '''
251
+ # Flagging Code
252
+ open_domain_callback = gr.HuggingFaceDatasetSaver(
253
+ hf_token, "bioclip-demo-open-domain-mistakes", private=True
254
+ )
255
+ open_domain_callback.setup(
256
+ [img_input, rank_dropdown, open_domain_output],
257
+ flagging_dir="bioclip-demo-open-domain-mistakes/logs/flagged",
258
+ )
259
+ open_domain_flag_btn.click(
260
+ lambda *args: open_domain_callback.flag(args),
261
+ [img_input, rank_dropdown, open_domain_output],
262
+ None,
263
+ preprocess=False,
264
+ )
265
+ '''
266
+ with gr.Tab("Zero-Shot"):
267
+ with gr.Row():
268
+ img_input_zs = gr.Image(height = 400, sources=["upload"])
269
+
270
+ with gr.Row():
271
+ with gr.Column():
272
+ classes_txt = gr.Textbox(
273
+ placeholder="Canis familiaris (dog)\nFelis catus (cat)\n...",
274
+ lines=3,
275
+ label="Classes",
276
+ show_label=True,
277
+ info="Use taxonomic names where possible; include common names if possible.",
278
+ )
279
+ zero_shot_btn = gr.Button("Submit", variant="primary")
280
+
281
+ with gr.Column():
282
+ zero_shot_output = gr.Label(
283
+ num_top_classes=k, label="Prediction", show_label=True
284
+ )
285
+ # zero_shot_flag_btn = gr.Button("Flag Mistake", variant="primary")
286
+
287
+ with gr.Row():
288
+ gr.Examples(
289
+ examples=zero_shot_examples,
290
+ inputs=[img_input_zs, classes_txt],
291
+ cache_examples=True,
292
+ fn=zero_shot_classification,
293
+ outputs=[zero_shot_output],
294
+ )
295
+ '''
296
+ # Flagging Code
297
+ zero_shot_callback = gr.HuggingFaceDatasetSaver(
298
+ hf_token, "bioclip-demo-zero-shot-mistakes", private=True
299
+ )
300
+ zero_shot_callback.setup(
301
+ [img_input, zero_shot_output], flagging_dir="bioclip-demo-zero-shot-mistakes/logs/flagged"
302
+ )
303
+ zero_shot_flag_btn.click(
304
+ lambda *args: zero_shot_callback.flag(args),
305
+ [img_input, zero_shot_output],
306
+ None,
307
+ preprocess=False,
308
+ )
309
+ '''
310
+ rank_dropdown.change(
311
+ fn=change_output, inputs=rank_dropdown, outputs=[open_domain_output]
312
+ )
313
+
314
+ open_domain_btn.click(
315
+ fn=lambda img, rank: open_domain_classification(img, rank, return_all=True),
316
+ inputs=[img_input, rank_dropdown],
317
+ outputs=[open_domain_output, sample_img, taxon_url],
318
+ )
319
+
320
+ zero_shot_btn.click(
321
+ fn=zero_shot_classification,
322
+ inputs=[img_input_zs, classes_txt],
323
+ outputs=zero_shot_output,
324
+ )
325
+
326
+ # Footer to point out to model and data from app page.
327
+ gr.Markdown(
328
+ """
329
+ For more information on the [BioCLIP Model](https://huggingface.co/imageomics/bioclip) creation, see our [BioCLIP Project GitHub](https://github.com/Imageomics/bioclip), and
330
+ for easier integration of BioCLIP, checkout [pybioclip](https://github.com/Imageomics/pybioclip).
331
+
332
+ To learn more about the data, check out our [TreeOfLife-10M Dataset](https://huggingface.co/datasets/imageomics/TreeOfLife-10M).
333
+ """
334
+ )
335
+
336
+ app.queue(max_size=20)
337
+ app.launch(share=True)