egrace479 commited on
Commit
b524bf4
·
verified ·
1 Parent(s): 7c50947

Updates original demo code to use BioCLIP 2 and fetch TreeOfLife-200M samples

Browse files

Also uses pybioclip for zero-shot, 'read more' URLs are for both GBIF and EOL (where available)

Modified from BioCLIP demo: https://huggingface.co/spaces/imageomics/bioclip-demo/tree/e5926783d64614adbc4498765ea2ad3136be9495

app.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 components.query import get_sample
16
+ from bioclip import CustomLabelsClassifier
17
+ from huggingface_hub import hf_hub_download
18
+
19
+ log_format = "[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s"
20
+ logging.basicConfig(level=logging.INFO, format=log_format)
21
+ logger = logging.getLogger()
22
+
23
+ hf_token = os.getenv("HF_TOKEN")
24
+
25
+ # For sample images
26
+ hf_hub_download(repo_id="imageomics/bioclip-demo-data",
27
+ filename="metadata.parquet",
28
+ repo_type="dataset",
29
+ local_dir = "components",
30
+ token = hf_token)
31
+ METADATA_PATH = "components/metadata.parquet"
32
+ # Read page IDs as int
33
+ metadata_df = pl.read_parquet(METADATA_PATH, low_memory = False)
34
+ metadata_df = metadata_df.with_columns(pl.col(["eol_page_id", "taxonID"]).cast(pl.Int64))
35
+
36
+ MODEL_STR = "hf-hub:imageomics/bioclip-2"
37
+ TOKENIZER_STR = "ViT-L-14"
38
+
39
+ txt_emb_npy = "https://huggingface.co/datasets/imageomics/TreeOfLife-200M/resolve/main/embeddings/txt_emb_species.npy"
40
+ txt_names_json = "embeddings/txt_emb_species.json"
41
+
42
+ min_prob = 1e-9
43
+ k = 5
44
+
45
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
46
+
47
+ preprocess_img = transforms.Compose(
48
+ [
49
+ transforms.ToTensor(),
50
+ transforms.Resize((224, 224), antialias=True),
51
+ transforms.Normalize(
52
+ mean=(0.48145466, 0.4578275, 0.40821073),
53
+ std=(0.26862954, 0.26130258, 0.27577711),
54
+ ),
55
+ ]
56
+ )
57
+
58
+ ranks = ("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species")
59
+
60
+ open_domain_examples = [
61
+ ["examples/Ursus-arctos.jpeg", "Species"],
62
+ ["examples/Phoca-vitulina.png", "Species"],
63
+ ["examples/Felis-catus.jpeg", "Genus"],
64
+ ["examples/Sarcoscypha-coccinea.jpeg", "Order"],
65
+ ]
66
+ zero_shot_examples = [
67
+ [
68
+ "examples/Ursus-arctos.jpeg",
69
+ "brown bear\nblack bear\npolar bear\nkoala bear\ngrizzly bear",
70
+ ],
71
+ ["examples/milk-snake.png", "coral snake\nmilk snake"],
72
+ ["examples/coral-snake.jpeg", "coral snake\nmilk snake"],
73
+ [
74
+ "examples/Carnegiea-gigantea.png",
75
+ "Carnegiea gigantea\nSchlumbergera opuntioides\nMammillaria albicoma",
76
+ ],
77
+ [
78
+ "examples/Amanita-muscaria.jpeg",
79
+ "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)",
80
+ ],
81
+ [
82
+ "examples/Actinostola-abyssorum.png",
83
+ "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",
84
+ ],
85
+ [
86
+ "examples/Sarcoscypha-coccinea.jpeg",
87
+ "scarlet elf cup (coccinea)\nscharlachroter kelchbecherling (austriaca)\ncrimson cup (dudleyi)\nstalked scarlet cup (occidentalis)",
88
+ ],
89
+ [
90
+ "examples/Onoclea-hintonii.jpg",
91
+ "Onoclea attenuata\nOnoclea boryana\nOnoclea hintonii\nOnoclea intermedia\nOnoclea sensibilis",
92
+ ],
93
+ [
94
+ "examples/Onoclea-sensibilis.jpg",
95
+ "Onoclea attenuata\nOnoclea boryana\nOnoclea hintonii\nOnoclea intermedia\nOnoclea sensibilis",
96
+ ],
97
+ ]
98
+
99
+
100
+ def indexed(lst, indices):
101
+ return [lst[i] for i in indices]
102
+
103
+
104
+ def zero_shot_classification(img, cls_str: str) -> dict[str, float]:
105
+ classes = [cls.strip() for cls in cls_str.split("\n") if cls.strip()]
106
+ classifier = CustomLabelsClassifier(
107
+ cls_ary = classes,
108
+ model_str = MODEL_STR, # remove this line once pybioclip uses BioCLIP 2
109
+ )
110
+ return classifier.predict(img)
111
+
112
+
113
+ def format_name(taxon, common):
114
+ taxon = " ".join(taxon)
115
+ if not common:
116
+ return taxon
117
+ return f"{taxon} ({common})"
118
+
119
+
120
+ @torch.no_grad()
121
+ def open_domain_classification(img, rank: int, return_all=False):
122
+ """
123
+ Predicts from the entire tree of life.
124
+ If targeting a higher rank than species, then this function predicts among all
125
+ species, then sums up species-level probabilities for the given rank.
126
+ """
127
+
128
+ logger.info(f"Starting open domain classification for rank: {rank}")
129
+ img = preprocess_img(img).to(device)
130
+ img_features = model.encode_image(img.unsqueeze(0))
131
+ img_features = F.normalize(img_features, dim=-1)
132
+
133
+ logits = (model.logit_scale.exp() * img_features @ txt_emb).squeeze()
134
+ probs = F.softmax(logits, dim=0)
135
+
136
+ if rank + 1 == len(ranks):
137
+ topk = probs.topk(k)
138
+ prediction_dict = {
139
+ format_name(*txt_names[i]): prob for i, prob in zip(topk.indices, topk.values)
140
+ }
141
+ logger.info(f"Top K predictions: {prediction_dict}")
142
+ top_prediction_name = format_name(*txt_names[topk.indices[0]]).split("(")[0]
143
+ logger.info(f"Top prediction name: {top_prediction_name}")
144
+ sample_img, taxon_url = get_sample(metadata_df, top_prediction_name, rank)
145
+ if return_all:
146
+ return prediction_dict, sample_img, taxon_url
147
+ return prediction_dict
148
+
149
+ output = collections.defaultdict(float)
150
+ for i in torch.nonzero(probs > min_prob).squeeze():
151
+ output[" ".join(txt_names[i][0][: rank + 1])] += probs[i]
152
+
153
+ topk_names = heapq.nlargest(k, output, key=output.get)
154
+ prediction_dict = {name: output[name] for name in topk_names}
155
+ logger.info(f"Top K names for output: {topk_names}")
156
+ logger.info(f"Prediction dictionary: {prediction_dict}")
157
+
158
+ top_prediction_name = topk_names[0]
159
+ logger.info(f"Top prediction name: {top_prediction_name}")
160
+ sample_img, taxon_url = get_sample(metadata_df, top_prediction_name, rank)
161
+ logger.info(f"Sample image and taxon URL: {sample_img}, {taxon_url}")
162
+
163
+ if return_all:
164
+ return prediction_dict, sample_img, taxon_url
165
+ return prediction_dict
166
+
167
+
168
+ def change_output(choice):
169
+ return gr.Label(num_top_classes=k, label=ranks[choice], show_label=True, value=None)
170
+
171
+
172
+ if __name__ == "__main__":
173
+ logger.info("Starting.")
174
+ model = create_model(MODEL_STR, output_dict=True, require_pretrained=True)
175
+ model = model.to(device)
176
+ logger.info("Created model.")
177
+
178
+ model = torch.compile(model)
179
+ logger.info("Compiled model.")
180
+
181
+ tokenizer = get_tokenizer(TOKENIZER_STR)
182
+
183
+ txt_emb = torch.from_numpy(np.load(txt_emb_npy, mmap_mode="r")).to(device)
184
+ with open(txt_names_json) as fd:
185
+ txt_names = json.load(fd)
186
+
187
+ done = txt_emb.any(axis=0).sum().item()
188
+ total = txt_emb.shape[1]
189
+ status_msg = ""
190
+ if done != total:
191
+ status_msg = f"{done}/{total} ({done / total * 100:.1f}%) indexed"
192
+
193
+ with gr.Blocks() as app:
194
+
195
+ with gr.Tab("Open-Ended"):
196
+ with gr.Row(variant = "panel", elem_id = "images_panel"):
197
+ with gr.Column():
198
+ img_input = gr.Image(height = 400, sources=["upload"])
199
+
200
+ with gr.Column():
201
+ # display sample image of top predicted taxon
202
+ sample_img = gr.Image(label = "Sample Image of Predicted Taxon",
203
+ height = 400,
204
+ show_download_button = False)
205
+
206
+ taxon_url = gr.HTML(label = "More Information",
207
+ elem_id = "url"
208
+ )
209
+
210
+ with gr.Row():
211
+ with gr.Column():
212
+ rank_dropdown = gr.Dropdown(
213
+ label="Taxonomic Rank",
214
+ info="Which taxonomic rank to predict. Fine-grained ranks (genus, species) are more challenging.",
215
+ choices=ranks,
216
+ value="Species",
217
+ type="index",
218
+ )
219
+ open_domain_btn = gr.Button("Submit", variant="primary")
220
+ with gr.Column():
221
+ open_domain_output = gr.Label(
222
+ num_top_classes=k,
223
+ label="Prediction",
224
+ show_label=True,
225
+ value=None,
226
+ )
227
+
228
+ with gr.Row():
229
+ gr.Examples(
230
+ examples=open_domain_examples,
231
+ inputs=[img_input, rank_dropdown],
232
+ cache_examples=True,
233
+ fn=lambda img, rank: open_domain_classification(img, rank, return_all=False),
234
+ outputs=[open_domain_output],
235
+ )
236
+
237
+ with gr.Tab("Zero-Shot"):
238
+ with gr.Row():
239
+ img_input_zs = gr.Image(height = 400, sources=["upload"])
240
+
241
+ with gr.Row():
242
+ with gr.Column():
243
+ classes_txt = gr.Textbox(
244
+ placeholder="Canis familiaris (dog)\nFelis catus (cat)\n...",
245
+ lines=3,
246
+ label="Classes",
247
+ show_label=True,
248
+ info="Use taxonomic names where possible; include common names if possible.",
249
+ )
250
+ zero_shot_btn = gr.Button("Submit", variant="primary")
251
+
252
+ with gr.Column():
253
+ zero_shot_output = gr.Label(
254
+ num_top_classes=k, label="Prediction", show_label=True
255
+ )
256
+
257
+ with gr.Row():
258
+ gr.Examples(
259
+ examples=zero_shot_examples,
260
+ inputs=[img_input_zs, classes_txt],
261
+ cache_examples=True,
262
+ fn=zero_shot_classification,
263
+ outputs=[zero_shot_output],
264
+ )
265
+
266
+ rank_dropdown.change(
267
+ fn=change_output, inputs=rank_dropdown, outputs=[open_domain_output]
268
+ )
269
+
270
+ open_domain_btn.click(
271
+ fn=lambda img, rank: open_domain_classification(img, rank, return_all=True),
272
+ inputs=[img_input, rank_dropdown],
273
+ outputs=[open_domain_output, sample_img, taxon_url],
274
+ )
275
+
276
+ zero_shot_btn.click(
277
+ fn=zero_shot_classification,
278
+ inputs=[img_input_zs, classes_txt],
279
+ outputs=zero_shot_output,
280
+ )
281
+
282
+ # Footer to point out to model and data from app page.
283
+ gr.Markdown(
284
+ """
285
+ For more information on the [BioCLIP 2 Model](https://huggingface.co/imageomics/bioclip-2) creation, see our [BioCLIP 2 Project website](https://imageomics.github.io/bioclip-2/),
286
+ and for easier integration of BioCLIP 2, checkout [pybioclip](https://github.com/Imageomics/pybioclip).
287
+
288
+ To learn more about the data, check out our [TreeOfLife-200M Dataset](https://huggingface.co/datasets/imageomics/TreeOfLife-200M).
289
+ """
290
+ )
291
+
292
+ app.queue(max_size=20)
293
+ app.launch(share=True)
components/query.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import boto3
3
+ import requests
4
+ import numpy as np
5
+ import polars as pl
6
+ from PIL import Image
7
+ from botocore.config import Config
8
+ import logging
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # S3 for sample images
13
+ my_config = Config(
14
+ region_name='us-east-1'
15
+ )
16
+ s3_client = boto3.client('s3', config=my_config)
17
+
18
+ # Set basepath for EOL pages for info
19
+ EOL_URL = "https://eol.org/pages/"
20
+ GBIF_URL = "https://gbif.org/species/"
21
+ RANKS = ["kingdom", "phylum", "class", "order", "family", "genus", "species"]
22
+
23
+ def get_sample(df, pred_taxon, rank):
24
+ '''
25
+ Function to retrieve a sample image of the predicted taxon and GBIF or EOL page link for more info.
26
+
27
+ Parameters:
28
+ -----------
29
+ df : DataFrame
30
+ DataFrame with all sample images listed and their filepaths (in "file_path" column).
31
+ pred_taxon : str
32
+ Predicted taxon of the uploaded image.
33
+ rank : int
34
+ Index of rank in RANKS chosen for prediction.
35
+
36
+ Returns:
37
+ --------
38
+ img : PIL.Image
39
+ Sample image of predicted taxon for display.
40
+ ref_page : str
41
+ URL to GBIF or EOL page for the taxon (may be a lower rank, e.g., species sample).
42
+ '''
43
+ logger.info(f"Getting sample for taxon: {pred_taxon} at rank: {rank}")
44
+ try:
45
+ filepath, taxonID, eol_page_id, full_name, is_exact = get_sample_data(df, pred_taxon, rank)
46
+ except Exception as e:
47
+ logger.error(f"Error retrieving sample data: {e}")
48
+ return None, f"We encountered the following error trying to retrieve a sample image: {e}."
49
+ if filepath is None:
50
+ logger.warning(f"No sample image found for taxon: {pred_taxon}")
51
+ return None, f"Sorry, our GBIF and EOL images do not include {pred_taxon}."
52
+
53
+ # Get sample image of selected individual
54
+ try:
55
+ img_src = s3_client.generate_presigned_url('get_object',
56
+ Params={'Bucket': 'treeoflife-200m-sample-images',
57
+ 'Key': filepath}
58
+ )
59
+ img_resp = requests.get(img_src)
60
+ img = Image.open(io.BytesIO(img_resp.content))
61
+ if taxonID:
62
+ gbif_url = GBIF_URL + taxonID
63
+ if eol_page_id:
64
+ eol_url = EOL_URL + eol_page_id
65
+ if is_exact:
66
+ ref_page = f"<p>Check out the <a href={eol_url} target='_blank'>EOL</a> or <a href={gbif_url} target='_blank'>GBIF</a> entry for {pred_taxon} to learn more.</p>"
67
+ else:
68
+ ref_page = f"<p>Check out an example entry within {pred_taxon} to learn more: {full_name} at <a href={eol_url} target='_blank'>EOL</a> or <a href={gbif_url} target='_blank'>GBIF</a>.</p>"
69
+ else:
70
+ if is_exact:
71
+ ref_page = f"<p>Check out the <a href={gbif_url} target='_blank'>GBIF</a> entry for {pred_taxon} to learn more.</p>"
72
+ else:
73
+ ref_page = f"<p>Check out an example GBIF entry within {pred_taxon} to learn more: <a href={gbif_url} target='_blank'>{full_name}</a>.</p>"
74
+ else:
75
+ eol_url = EOL_URL + eol_page_id
76
+ if is_exact:
77
+ ref_page = f"<p>Check out the <a href={eol_url} target='_blank'>EOL</a> entry for {pred_taxon} to learn more.</p>"
78
+ else:
79
+ ref_page = f"<p>Check out an example EOL entry within {pred_taxon} to learn more: <a href={eol_url} target='_blank'>{full_name}</a>.</p>"
80
+ logger.info(f"Successfully retrieved sample image and page for {pred_taxon}")
81
+ return img, ref_page
82
+ except Exception as e:
83
+ logger.error(f"Error retrieving sample image: {e}")
84
+ return None, f"We encountered the following error trying to retrieve a sample image: {e}."
85
+
86
+ def get_sample_data(df, pred_taxon, rank):
87
+ '''
88
+ Function to randomly select a sample individual of the given taxon and provide associated native location.
89
+
90
+ Parameters:
91
+ -----------
92
+ df : DataFrame
93
+ DataFrame with all sample images listed and their filepaths (in "file_path" column).
94
+ pred_taxon : str
95
+ Predicted taxon of the uploaded image.
96
+ rank : int
97
+ Index of rank in RANKS chosen for prediction.
98
+
99
+ Returns:
100
+ --------
101
+ filepath : str
102
+ Filepath of selected sample image for predicted taxon.
103
+ taxonID: str
104
+ GBIF page ID associated with predicted taxon for more information.
105
+ eol_page_id : str
106
+ EOL page ID associated with predicted taxon for more information.
107
+ full_name : str
108
+ Full taxonomic name of the selected sample.
109
+ is_exact : bool
110
+ Flag indicating if the match is exact (i.e., with empty lower ranks).
111
+ '''
112
+ for idx in range(rank + 1):
113
+ taxon = RANKS[idx]
114
+ target_taxon = pred_taxon.split(" ")[idx]
115
+ df = df.filter(pl.col(taxon) == target_taxon)
116
+
117
+ if df.shape[0] == 0:
118
+ return None, np.nan, "", False
119
+
120
+ # First, try to find entries with empty lower ranks
121
+ exact_df = df.copy()
122
+ for lower_rank in RANKS[rank + 1:]:
123
+ exact_df = exact_df.filter((pl.col(lower_rank).is_null()) | (pl.col(lower_rank) == ""))
124
+
125
+ if exact_df.shape[0] > 0:
126
+ df_filtered = exact_df.sample()
127
+ full_name = " ".join(df_filtered.select(RANKS[:rank+1]).row(0))
128
+ return df_filtered["file_path"][0], df_filtered["taxonID"].cast(pl.String)[0], df_filtered["eol_page_id"].cast(pl.String)[0], full_name, True
129
+
130
+ # If no exact matches, return any entry with the specified rank
131
+ df_filtered = df.sample()
132
+ full_name = " ".join(df_filtered.select(RANKS[:rank+1]).row(0)) + " " + " ".join(df_filtered.select(RANKS[rank+1:]).row(0))
133
+ return df_filtered["file_path"][0], df_filtered["taxonID"].cast(pl.String)[0], df_filtered["eol_page_id"].cast(pl.String)[0], full_name, False
components/sync_samples_to_s3.bash ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ <<COMMENT
4
+ Usage:
5
+ bash sync_samples_to_s3.bash <BASE_DIR>
6
+
7
+ Dependencies:
8
+ - awscli (https://aws.amazon.com/cli/)
9
+ Credentials to export as environment variables:
10
+ - AWS_ACCESS_KEY_ID
11
+ - AWS_SECRET_ACCESS_KEY
12
+ COMMENT
13
+
14
+ # Check if a valid directory is provided as an argument
15
+ if [ -z "$1" ]; then
16
+ echo "Usage: $0 <BASE_DIR>"
17
+ exit 1
18
+ fi
19
+
20
+ if [ ! -d "$1" ]; then
21
+ echo "Error: $1 is not a valid directory"
22
+ exit 1
23
+ fi
24
+
25
+ BASE_DIR="$1"
26
+ S3_BUCKET="s3://treeoflife-200m-sample-images"
27
+
28
+ # Loop through all directories and sync them to S3
29
+ for dir in $BASE_DIR/*; do
30
+ if [ -d "$dir" ]; then
31
+ dir_name=$(basename "$dir")
32
+ aws s3 sync "$dir" "$S3_BUCKET/$dir_name/"
33
+ fi
34
+ done
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ open_clip_torch
2
+ torchvision
3
+ torch
4
+ gradio
5
+ polars
6
+ pillow
7
+ boto3
8
+ pybioclip