Set up BioCLIP 2 app code based on BioCLIP demo

#1
.gitattributes CHANGED
@@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/Actinostola-abyssorum.png filter=lfs diff=lfs merge=lfs -text
37
+ examples/Amanita-muscaria.jpeg filter=lfs diff=lfs merge=lfs -text
38
+ examples/Carnegiea-gigantea.png filter=lfs diff=lfs merge=lfs -text
39
+ examples/Felis-catus.jpeg filter=lfs diff=lfs merge=lfs -text
40
+ examples/milk-snake.png filter=lfs diff=lfs merge=lfs -text
41
+ examples/Onoclea-sensibilis.jpg filter=lfs diff=lfs merge=lfs -text
42
+ examples/Phoca-vitulina.png filter=lfs diff=lfs merge=lfs -text
43
+ examples/Sarcoscypha-coccinea.jpeg filter=lfs diff=lfs merge=lfs -text
44
+ examples/Ursus-arctos.jpeg filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -8,6 +8,27 @@ sdk_version: 5.33.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ models:
12
+ - imageomics/bioclip-2
13
+ datasets:
14
+ - imageomics/TreeOfLife-200M
15
  ---
16
 
17
+ This app is modified from the original [BioCLIP Demo](https://huggingface.co/spaces/imageomics/bioclip-demo) to run inference with [BioCLIP 2](https://huggingface.co/imageomics/bioclip-2) and uses [pybioclip](https://github.com/Imageomics/pybioclip).
18
+
19
+ Due to space persistent storage limitations, embeddings are fetched from the [TreeOfLife-200M repo](https://huggingface.co/datasets/imageomics/TreeOfLife-200M). The images will be retrieved from an S3 bucket, as with the origin, described below.
20
+
21
+ Note that if this space is duplicated, the sample image portion **will not work**.
22
+
23
+ **bioclip-2/metadata.parquet:** metadata file for fetching [TreeOfLife-200M](https://huggingface.co/datasets/imageomics/TreeOfLife-200M) sample images (up to 3 available per taxa) from an S3 bucket.
24
+ - `uuid`: unique identifier for the image within the TreeOfLife-200M dataset.
25
+ - `eol_page_id`: identifier of EOL page for the most specific taxa of the image (where available). Note that an image's association to a particular page ID may change with updates to the EOL (or image provider's) hierarchy. However, EOL taxon page IDs are stable. "https://eol.org/pages/" + `eol_page_id` links to the page.
26
+ - `gbif_id`: identifier used by GBIF for the most specific taxa of the image (where available). "https://gbif.org/species/" + `taxonID` links to the page.
27
+ - `kingdom`: kingdom to which the subject of the image belongs (all `Animalia`).
28
+ - `phylum`: phylum to which the subject of the image belongs.
29
+ - `class`: class to which the subject of the image belongs.
30
+ - `order`: order to which the subject of the image belongs.
31
+ - `family`: family to which the subject of the image belongs.
32
+ - `genus`: genus to which the subject of the image belongs.
33
+ - `species`: species to which the subject of the image belongs.
34
+ - `file_path`: image filepath to fetch image from S3 bucket (`<folder>/<uuid>.jpg`, folders are first two characters of the `uuid`).
app.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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.parquet"
26
+ # Read page IDs as int
27
+ metadata_df = pl.read_parquet(METADATA_PATH, low_memory = False)
28
+ metadata_df = metadata_df.with_columns(pl.col(["eol_page_id", "gbif_id"]).cast(pl.Int64))
29
+
30
+ MODEL_STR = "hf-hub:imageomics/bioclip-2"
31
+ TOKENIZER_STR = "ViT-L-14"
32
+
33
+ txt_emb_npy = "https://huggingface.co/datasets/imageomics/TreeOfLife-200M/resolve/main/embeddings/txt_emb_species.npy"
34
+ txt_names_json = "embeddings/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
+ def zero_shot_classification(img, cls_str: str) -> dict[str, float]:
99
+ classes = [cls.strip() for cls in cls_str.split("\n") if cls.strip()]
100
+ classifier = CustomLabelsClassifier(
101
+ cls_ary = classes,
102
+ model_str = MODEL_STR, # remove this line once pybioclip uses BioCLIP 2
103
+ )
104
+ return classifier.predict(img)
105
+
106
+
107
+ def format_name(taxon, common):
108
+ taxon = " ".join(taxon)
109
+ if not common:
110
+ return taxon
111
+ return f"{taxon} ({common})"
112
+
113
+
114
+ @torch.no_grad()
115
+ def open_domain_classification(img, rank: int, return_all=False):
116
+ """
117
+ Predicts from the entire tree of life.
118
+ If targeting a higher rank than species, then this function predicts among all
119
+ species, then sums up species-level probabilities for the given rank.
120
+ """
121
+
122
+ logger.info(f"Starting open domain classification for rank: {rank}")
123
+ img = preprocess_img(img).to(device)
124
+ img_features = model.encode_image(img.unsqueeze(0))
125
+ img_features = F.normalize(img_features, dim=-1)
126
+
127
+ logits = (model.logit_scale.exp() * img_features @ txt_emb).squeeze()
128
+ probs = F.softmax(logits, dim=0)
129
+
130
+ if rank + 1 == len(ranks):
131
+ topk = probs.topk(k)
132
+ prediction_dict = {
133
+ format_name(*txt_names[i]): prob for i, prob in zip(topk.indices, topk.values)
134
+ }
135
+ logger.info(f"Top K predictions: {prediction_dict}")
136
+ top_prediction_name = format_name(*txt_names[topk.indices[0]]).split("(")[0]
137
+ logger.info(f"Top prediction name: {top_prediction_name}")
138
+ sample_img, taxon_url = get_sample(metadata_df, top_prediction_name, rank)
139
+ if return_all:
140
+ return prediction_dict, sample_img, taxon_url
141
+ return prediction_dict
142
+
143
+ output = collections.defaultdict(float)
144
+ for i in torch.nonzero(probs > min_prob).squeeze():
145
+ output[" ".join(txt_names[i][0][: rank + 1])] += probs[i]
146
+
147
+ topk_names = heapq.nlargest(k, output, key=output.get)
148
+ prediction_dict = {name: output[name] for name in topk_names}
149
+ logger.info(f"Top K names for output: {topk_names}")
150
+ logger.info(f"Prediction dictionary: {prediction_dict}")
151
+
152
+ top_prediction_name = topk_names[0]
153
+ logger.info(f"Top prediction name: {top_prediction_name}")
154
+ sample_img, taxon_url = get_sample(metadata_df, top_prediction_name, rank)
155
+ logger.info(f"Sample image and taxon URL: {sample_img}, {taxon_url}")
156
+
157
+ if return_all:
158
+ return prediction_dict, sample_img, taxon_url
159
+ return prediction_dict
160
+
161
+
162
+ def change_output(choice):
163
+ return gr.Label(num_top_classes=k, label=ranks[choice], show_label=True, value=None)
164
+
165
+
166
+ if __name__ == "__main__":
167
+ logger.info("Starting.")
168
+ model = create_model(MODEL_STR, output_dict=True, require_pretrained=True)
169
+ model = model.to(device)
170
+ logger.info("Created model.")
171
+
172
+ model = torch.compile(model)
173
+ logger.info("Compiled model.")
174
+
175
+ tokenizer = get_tokenizer(TOKENIZER_STR)
176
+
177
+ txt_emb = torch.from_numpy(np.load(txt_emb_npy, mmap_mode="r")).to(device)
178
+ with open(txt_names_json) as fd:
179
+ txt_names = json.load(fd)
180
+
181
+ done = txt_emb.any(axis=0).sum().item()
182
+ total = txt_emb.shape[1]
183
+ status_msg = ""
184
+ if done != total:
185
+ status_msg = f"{done}/{total} ({done / total * 100:.1f}%) indexed"
186
+
187
+ with gr.Blocks() as app:
188
+
189
+ with gr.Tab("Open-Ended"):
190
+ with gr.Row(variant = "panel", elem_id = "images_panel"):
191
+ with gr.Column():
192
+ img_input = gr.Image(height = 400, sources=["upload"])
193
+
194
+ with gr.Column():
195
+ # display sample image of top predicted taxon
196
+ sample_img = gr.Image(label = "Sample Image of Predicted Taxon",
197
+ height = 400,
198
+ show_download_button = False)
199
+
200
+ taxon_url = gr.HTML(label = "More Information",
201
+ elem_id = "url"
202
+ )
203
+
204
+ with gr.Row():
205
+ with gr.Column():
206
+ rank_dropdown = gr.Dropdown(
207
+ label="Taxonomic Rank",
208
+ info="Which taxonomic rank to predict. Fine-grained ranks (genus, species) are more challenging.",
209
+ choices=ranks,
210
+ value="Species",
211
+ type="index",
212
+ )
213
+ open_domain_btn = gr.Button("Submit", variant="primary")
214
+ with gr.Column():
215
+ open_domain_output = gr.Label(
216
+ num_top_classes=k,
217
+ label="Prediction",
218
+ show_label=True,
219
+ value=None,
220
+ )
221
+
222
+ with gr.Row():
223
+ gr.Examples(
224
+ examples=open_domain_examples,
225
+ inputs=[img_input, rank_dropdown],
226
+ cache_examples=True,
227
+ fn=lambda img, rank: open_domain_classification(img, rank, return_all=False),
228
+ outputs=[open_domain_output],
229
+ )
230
+
231
+ with gr.Tab("Zero-Shot"):
232
+ with gr.Row():
233
+ img_input_zs = gr.Image(height = 400, sources=["upload"])
234
+
235
+ with gr.Row():
236
+ with gr.Column():
237
+ classes_txt = gr.Textbox(
238
+ placeholder="Canis familiaris (dog)\nFelis catus (cat)\n...",
239
+ lines=3,
240
+ label="Classes",
241
+ show_label=True,
242
+ info="Use taxonomic names where possible; include common names if possible.",
243
+ )
244
+ zero_shot_btn = gr.Button("Submit", variant="primary")
245
+
246
+ with gr.Column():
247
+ zero_shot_output = gr.Label(
248
+ num_top_classes=k, label="Prediction", show_label=True
249
+ )
250
+
251
+ with gr.Row():
252
+ gr.Examples(
253
+ examples=zero_shot_examples,
254
+ inputs=[img_input_zs, classes_txt],
255
+ cache_examples=True,
256
+ fn=zero_shot_classification,
257
+ outputs=[zero_shot_output],
258
+ )
259
+
260
+ rank_dropdown.change(
261
+ fn=change_output, inputs=rank_dropdown, outputs=[open_domain_output]
262
+ )
263
+
264
+ open_domain_btn.click(
265
+ fn=lambda img, rank: open_domain_classification(img, rank, return_all=True),
266
+ inputs=[img_input, rank_dropdown],
267
+ outputs=[open_domain_output, sample_img, taxon_url],
268
+ )
269
+
270
+ zero_shot_btn.click(
271
+ fn=zero_shot_classification,
272
+ inputs=[img_input_zs, classes_txt],
273
+ outputs=zero_shot_output,
274
+ )
275
+
276
+ # Footer to point out to model and data from app page.
277
+ gr.Markdown(
278
+ """
279
+ 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/),
280
+ and for easier integration of BioCLIP 2, checkout [pybioclip](https://github.com/Imageomics/pybioclip).
281
+
282
+ To learn more about the data, check out our [TreeOfLife-200M Dataset](https://huggingface.co/datasets/imageomics/TreeOfLife-200M).
283
+ """
284
+ )
285
+
286
+ app.queue(max_size=20)
287
+ app.launch(share=True)
components/metadata.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6af05f1f8f08b0d447b9a4c18680c7de39551a05318f026d30c224a9bbe5283e
3
+ size 121162891
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, gbif_id, 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 gbif_id:
62
+ gbif_url = GBIF_URL + gbif_id
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
+ gbif_id: 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["gbif_id"].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["gbif_id"].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
examples/Actinostola-abyssorum.png ADDED

Git LFS Details

  • SHA256: cc56a3aedc6966da7add6093506ba3fc792b6dd2d3178878968c9c6978a4535a
  • Pointer size: 132 Bytes
  • Size of remote file: 1.13 MB
examples/Amanita-muscaria.jpeg ADDED

Git LFS Details

  • SHA256: c633755d4d45bc8bf86b4f4b889fc3f7acbeaa0e86cc69fce5f25165e21063eb
  • Pointer size: 132 Bytes
  • Size of remote file: 1.23 MB
examples/Carnegiea-gigantea.png ADDED

Git LFS Details

  • SHA256: 8e55ff224c0b9421b66c2feaf592f20ba473425b79a5e79abca1c8ca8a001e67
  • Pointer size: 131 Bytes
  • Size of remote file: 419 kB
examples/Felis-catus.jpeg ADDED

Git LFS Details

  • SHA256: 4d68c295156ee782524cc9f4269e3111743f7a12441f49c095b975000512829f
  • Pointer size: 131 Bytes
  • Size of remote file: 650 kB
examples/Onoclea-hintonii.jpg ADDED
examples/Onoclea-sensibilis.jpg ADDED

Git LFS Details

  • SHA256: 717422c709503a90941d965102e3bb04ebe1f7c805312446fcc28da0eeed08db
  • Pointer size: 131 Bytes
  • Size of remote file: 311 kB
examples/Phoca-vitulina.png ADDED

Git LFS Details

  • SHA256: c717b35bfc07ebc9b9afd041f62bd1744f69e7e40ed9a6eac3a14f11f1ebc7fc
  • Pointer size: 131 Bytes
  • Size of remote file: 455 kB
examples/Sarcoscypha-coccinea.jpeg ADDED

Git LFS Details

  • SHA256: 84dfec1fe373d375cd31f129dfd961dfa9d0b400575f9dd9610a08d900fd1cf9
  • Pointer size: 131 Bytes
  • Size of remote file: 409 kB
examples/Ursus-arctos.jpeg ADDED

Git LFS Details

  • SHA256: b1ead956025e2ef9afa71e352326a299881e575bfb42fae65ae2c157196e2e73
  • Pointer size: 131 Bytes
  • Size of remote file: 610 kB
examples/coral-snake.jpeg ADDED
examples/milk-snake.png ADDED

Git LFS Details

  • SHA256: 4c5820dfcdaa056903767cc7a3dade6e9e9d24c686fab9d457889879e80fa3ab
  • Pointer size: 131 Bytes
  • Size of remote file: 411 kB
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