Addax-Data-Science commited on
Commit
1964793
·
verified ·
1 Parent(s): 951e66d

CBNet v1, Keras 3 re-save of alexvmt/CBNet

Browse files
Files changed (6) hide show
  1. .gitattributes +1 -0
  2. README.md +7 -0
  3. class_list.yaml +12 -0
  4. inference.py +245 -0
  5. model.keras +3 -0
  6. taxonomy.csv +13 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ model.keras filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ ---
2
+ {}
3
+ ---
4
+
5
+ This repository contains open-source models redistributed for easy integration with [AddaxAI](https://addaxdatascience.com/addaxai/), hosted by [Addax Data Science](https://addaxdatascience.com/). Each model retains its original license (see license files) and attribution. We comply with all original license terms. Users must review and comply with individual model licenses before use. See below for detailed model information including original sources, licenses, and attributions.
6
+
7
+ For the owner, license, citation and links of this model, see the [AddaxAI model zoo](https://docs.addaxai.com/docs/reference/model-zoo).
class_list.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '1': atherurus_africanus
2
+ '10': philantomba_monticola
3
+ '11': potamochoerus_porcus
4
+ '12': tragelaphus_spekii
5
+ '2': cephalophus_callipygus
6
+ '3': cephalophus_dorsalis
7
+ '4': cephalophus_silvicultor
8
+ '5': cercocebus_torquatus
9
+ '6': cricetomys_emini
10
+ '7': loxodonta_cyclotis
11
+ '8': mandrillus_sphinx
12
+ '9': pan_troglodytes
inference.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script for CONGO-CMR-v1 (CBNet, Congo Basin species classifier)
3
+
4
+ CBNet (CongoBasinNet) supports conservation in the Congo Basin, in
5
+ particular Cameroon. It classifies 12 forest species and is a fine-tuned
6
+ version of SpeciesNet, trained on about 15,000 WWF Cameroon camera trap
7
+ images. Accuracy 0.902 and macro accuracy 0.817 on a held-out test set.
8
+
9
+ Model: CBNet v1
10
+ Input: 480x480 RGB crops, pixels scaled to [0, 1], no mean/std normalisation
11
+ Framework: Keras 3 with TensorFlow backend (EfficientNetV2M architecture)
12
+ Classes: 12 (see class_list.yaml, ids 1..12 -> scientific names)
13
+ Developer: Alexander Merdian-Tarko
14
+ License: MIT
15
+ Info: https://alexvmt.github.io/
16
+
17
+ The author saved the model with Keras 2.14, which Keras 3 refuses to load.
18
+ The model.keras shipped here is the same network re-saved in Keras 3: the
19
+ EfficientNetV2M graph was rebuilt layer for layer (same names, same
20
+ shapes, 12-class softmax head, no preprocessing layer) and the original
21
+ weights were loaded by layer name. Checked on 25 real crops against the
22
+ original in Keras 2.14: identical top-5 order on every crop, maximum
23
+ probability difference 3e-6.
24
+
25
+ Author: Peter van Lunteren
26
+ Created: 2026-11-02
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import os
32
+ import sys
33
+ from pathlib import Path
34
+
35
+ import numpy as np
36
+ import tensorflow as tf
37
+ import yaml
38
+ from keras import saving
39
+ from PIL import Image, ImageFile
40
+
41
+ # Keras backend. A Keras 3 .keras file is backend-agnostic. TensorFlow is
42
+ # what gives this env a GPU: tensorflow-metal on macOS and CUDA on Linux,
43
+ # where JAX in this env is CPU-only.
44
+ os.environ["KERAS_BACKEND"] = "tensorflow"
45
+
46
+ # Don't freak out over truncated images
47
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
48
+
49
+ # The model's classes are scientific names with underscores
50
+ # (class_list.yaml, as the author trained it). The app shows a label as
51
+ # the species' common name, so the label the app stores is the English
52
+ # name; taxonomy.csv carries the same English names in model_class and
53
+ # the scientific names in the rank columns. Every class in class_list.yaml
54
+ # must have an entry here, or load_model() refuses to start: a missing
55
+ # entry would otherwise ship a label with no taxonomy row.
56
+ COMMON_NAMES: dict[str, str] = {
57
+ "atherurus_africanus": "african brush-tailed porcupine",
58
+ "cephalophus_callipygus": "peters's duiker",
59
+ "cephalophus_dorsalis": "bay duiker",
60
+ "cephalophus_silvicultor": "yellow-backed duiker",
61
+ "cercocebus_torquatus": "red-capped mangabey",
62
+ "cricetomys_emini": "emin's pouched rat",
63
+ "loxodonta_cyclotis": "african forest elephant",
64
+ "mandrillus_sphinx": "mandrill",
65
+ "pan_troglodytes": "chimpanzee",
66
+ "philantomba_monticola": "blue duiker",
67
+ "potamochoerus_porcus": "red river hog",
68
+ "tragelaphus_spekii": "sitatunga",
69
+ }
70
+
71
+
72
+ class ModelInference:
73
+ """Keras inference implementation for the CBNet Congo Basin classifier."""
74
+
75
+ def __init__(self, model_dir: Path, model_path: Path):
76
+ """
77
+ Initialize with model paths.
78
+
79
+ Args:
80
+ model_dir: Directory containing model files (including class_list.yaml)
81
+ model_path: Path to the .keras model file
82
+ """
83
+ self.model_dir = model_dir
84
+ self.model_path = model_path
85
+ self.model = None
86
+ self.img_size = 480 # SpeciesNet / EfficientNetV2M input size
87
+ self.class_ids: list[str] | None = None
88
+
89
+ def check_gpu(self) -> bool:
90
+ """
91
+ Check GPU availability for TensorFlow/Keras inference.
92
+
93
+ Returns:
94
+ True if GPU available, False otherwise
95
+ """
96
+ try:
97
+ return len(tf.config.list_logical_devices("GPU")) > 0
98
+ except Exception:
99
+ return False
100
+
101
+ def load_model(self) -> None:
102
+ """
103
+ Load the Keras model and the class list. Called once per worker.
104
+
105
+ class_list.yaml maps the model's output index + 1 to the class, as
106
+ the author documents it: `'1': atherurus_africanus, ...`. Output
107
+ index i is class id i + 1, so the list is read in numeric key order.
108
+
109
+ Raises:
110
+ RuntimeError: If model loading fails
111
+ FileNotFoundError: If model_path or class_list.yaml is missing
112
+ """
113
+ if not self.model_path.exists():
114
+ raise FileNotFoundError(f"Model file not found: {self.model_path}")
115
+
116
+ try:
117
+ self.model = saving.load_model(str(self.model_path), compile=False)
118
+ except Exception as e:
119
+ raise RuntimeError(f"Failed to load Keras model from {self.model_path}: {e}") from e
120
+
121
+ class_list_path = self.model_dir / "class_list.yaml"
122
+ if not class_list_path.exists():
123
+ raise FileNotFoundError(f"Class list file not found: {class_list_path}")
124
+
125
+ try:
126
+ with open(class_list_path, encoding="utf-8") as f:
127
+ class_map = yaml.safe_load(f)
128
+ by_id = {int(k): str(v).strip() for k, v in class_map.items()}
129
+ except Exception as e:
130
+ raise RuntimeError(f"Failed to load class labels from {class_list_path}: {e}") from e
131
+
132
+ n = len(by_id)
133
+ if sorted(by_id) != list(range(1, n + 1)):
134
+ raise RuntimeError(
135
+ f"{class_list_path} must hold ids 1..{n} without gaps, got {sorted(by_id)}"
136
+ )
137
+ n_out = int(self.model.outputs[0].shape[-1])
138
+ if n_out != n:
139
+ raise RuntimeError(
140
+ f"Model has {n_out} outputs but class_list.yaml lists {n} classes"
141
+ )
142
+
143
+ missing = [by_id[i] for i in range(1, n + 1) if by_id[i] not in COMMON_NAMES]
144
+ if missing:
145
+ raise RuntimeError(
146
+ f"No common name for model class(es) {missing}; add them to COMMON_NAMES"
147
+ )
148
+ self.class_ids = [COMMON_NAMES[by_id[i]] for i in range(1, n + 1)]
149
+
150
+ def get_crop(
151
+ self, image: Image.Image, bbox: tuple[float, float, float, float]
152
+ ) -> Image.Image | None:
153
+ """
154
+ Crop the MegaDetector box out of the full image, as the author does.
155
+
156
+ Direct crop, no padding or squaring: the box edges in pixels are the
157
+ normalised coordinates times the image size, rounded. Resizing to the
158
+ model input happens in get_tensor / get_classification.
159
+
160
+ Args:
161
+ image: PIL Image (full resolution)
162
+ bbox: Normalized bounding box (x, y, width, height) in range [0.0, 1.0]
163
+
164
+ Returns:
165
+ Cropped PIL Image, or None if the box is empty
166
+ """
167
+ x, y, w, h = bbox
168
+ if w <= 0 or h <= 0:
169
+ print(
170
+ f"[CONGO get_crop] Rejecting bbox with zero/negative dims: w={w}, h={h}",
171
+ file=sys.stderr, flush=True,
172
+ )
173
+ return None
174
+
175
+ im_width, im_height = image.size
176
+ left = min(max(round(x * im_width), 0), im_width)
177
+ top = min(max(round(y * im_height), 0), im_height)
178
+ right = min(max(round((x + w) * im_width), 0), im_width)
179
+ bottom = min(max(round((y + h) * im_height), 0), im_height)
180
+
181
+ if right <= left or bottom <= top:
182
+ print(
183
+ f"[CONGO get_crop] Rejecting empty crop ({left},{top})-({right},{bottom}) "
184
+ f"for bbox {bbox} on {im_width}x{im_height}",
185
+ file=sys.stderr, flush=True,
186
+ )
187
+ return None
188
+
189
+ return image.crop((left, top, right, bottom))
190
+
191
+ def _preprocess(self, crop: Image.Image) -> np.ndarray:
192
+ """Resize to 480x480 bicubic and scale pixels to [0, 1], as the author does."""
193
+ resized = crop.convert("RGB").resize((self.img_size, self.img_size), Image.BICUBIC)
194
+ return np.asarray(resized, dtype=np.float32) / 255.0
195
+
196
+ def _to_classifications(self, probs: np.ndarray) -> list[list[str, float]]:
197
+ return [[self.class_ids[i], float(probs[i])] for i in range(len(self.class_ids))]
198
+
199
+ def get_classification(self, crop: Image.Image) -> list[list[str, float]]:
200
+ """
201
+ Run classification on one cropped image.
202
+
203
+ Args:
204
+ crop: Cropped PIL Image from get_crop()
205
+
206
+ Returns:
207
+ List of [class_name, confidence] lists for ALL classes, in model order.
208
+ Sorting by confidence is handled by classification_worker.py.
209
+
210
+ Raises:
211
+ RuntimeError: If model not loaded or inference fails
212
+ """
213
+ if self.model is None or self.class_ids is None:
214
+ raise RuntimeError("Model not loaded - call load_model() first")
215
+
216
+ if crop is None:
217
+ return []
218
+
219
+ try:
220
+ arr = self._preprocess(crop)
221
+ probs = self.model.predict(arr[None], verbose=0)[0]
222
+ return self._to_classifications(probs)
223
+ except Exception as e:
224
+ raise RuntimeError(f"Keras classification failed: {e}") from e
225
+
226
+ def get_class_names(self) -> dict[str, str]:
227
+ """
228
+ Get mapping of class IDs to species names.
229
+
230
+ Returns:
231
+ Dict mapping class ID (1-indexed string) to the label the app stores,
232
+ in the model's output order: {"1": class_ids[0], "2": class_ids[1], ...}
233
+ """
234
+ if self.class_ids is None:
235
+ raise RuntimeError("Class IDs not loaded - call load_model() first")
236
+ return {str(i + 1): name for i, name in enumerate(self.class_ids)}
237
+
238
+ def get_tensor(self, crop: Image.Image):
239
+ """Preprocess a crop into a float32 [480, 480, 3] array for batch inference."""
240
+ return self._preprocess(crop)
241
+
242
+ def classify_batch(self, batch):
243
+ """Run inference on a batch of preprocessed arrays."""
244
+ probs = self.model.predict(batch, verbose=0)
245
+ return [self._to_classifications(p) for p in probs]
model.keras ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66a3fcaf94043daca6dc304b21c2e8b4160afb6c5a3c8fa58d936849242e1357
3
+ size 215045556
taxonomy.csv ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model_class,class,order,family,genus,species,variant
2
+ african brush-tailed porcupine,mammalia,rodentia,hystricidae,atherurus,africanus,
3
+ peters's duiker,mammalia,artiodactyla,bovidae,cephalophus,callipygus,
4
+ bay duiker,mammalia,artiodactyla,bovidae,cephalophus,dorsalis,
5
+ yellow-backed duiker,mammalia,artiodactyla,bovidae,cephalophus,silvicultor,
6
+ red-capped mangabey,mammalia,primates,cercopithecidae,cercocebus,torquatus,
7
+ emin's pouched rat,mammalia,rodentia,nesomyidae,cricetomys,emini,
8
+ african forest elephant,mammalia,proboscidea,elephantidae,loxodonta,cyclotis,
9
+ mandrill,mammalia,primates,cercopithecidae,mandrillus,sphinx,
10
+ chimpanzee,mammalia,primates,hominidae,pan,troglodytes,
11
+ blue duiker,mammalia,artiodactyla,bovidae,philantomba,monticola,
12
+ red river hog,mammalia,artiodactyla,suidae,potamochoerus,porcus,
13
+ sitatunga,mammalia,artiodactyla,bovidae,tragelaphus,spekii,