File size: 9,632 Bytes
1964793
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""
Inference script for CONGO-CMR-v1 (CBNet, Congo Basin species classifier)

CBNet (CongoBasinNet) supports conservation in the Congo Basin, in
particular Cameroon. It classifies 12 forest species and is a fine-tuned
version of SpeciesNet, trained on about 15,000 WWF Cameroon camera trap
images. Accuracy 0.902 and macro accuracy 0.817 on a held-out test set.

Model: CBNet v1
Input: 480x480 RGB crops, pixels scaled to [0, 1], no mean/std normalisation
Framework: Keras 3 with TensorFlow backend (EfficientNetV2M architecture)
Classes: 12 (see class_list.yaml, ids 1..12 -> scientific names)
Developer: Alexander Merdian-Tarko
License: MIT
Info: https://alexvmt.github.io/

The author saved the model with Keras 2.14, which Keras 3 refuses to load.
The model.keras shipped here is the same network re-saved in Keras 3: the
EfficientNetV2M graph was rebuilt layer for layer (same names, same
shapes, 12-class softmax head, no preprocessing layer) and the original
weights were loaded by layer name. Checked on 25 real crops against the
original in Keras 2.14: identical top-5 order on every crop, maximum
probability difference 3e-6.

Author: Peter van Lunteren
Created: 2026-11-02
"""

from __future__ import annotations

import os
import sys
from pathlib import Path

import numpy as np
import tensorflow as tf
import yaml
from keras import saving
from PIL import Image, ImageFile

# Keras backend. A Keras 3 .keras file is backend-agnostic. TensorFlow is
# what gives this env a GPU: tensorflow-metal on macOS and CUDA on Linux,
# where JAX in this env is CPU-only.
os.environ["KERAS_BACKEND"] = "tensorflow"

# Don't freak out over truncated images
ImageFile.LOAD_TRUNCATED_IMAGES = True

# The model's classes are scientific names with underscores
# (class_list.yaml, as the author trained it). The app shows a label as
# the species' common name, so the label the app stores is the English
# name; taxonomy.csv carries the same English names in model_class and
# the scientific names in the rank columns. Every class in class_list.yaml
# must have an entry here, or load_model() refuses to start: a missing
# entry would otherwise ship a label with no taxonomy row.
COMMON_NAMES: dict[str, str] = {
    "atherurus_africanus": "african brush-tailed porcupine",
    "cephalophus_callipygus": "peters's duiker",
    "cephalophus_dorsalis": "bay duiker",
    "cephalophus_silvicultor": "yellow-backed duiker",
    "cercocebus_torquatus": "red-capped mangabey",
    "cricetomys_emini": "emin's pouched rat",
    "loxodonta_cyclotis": "african forest elephant",
    "mandrillus_sphinx": "mandrill",
    "pan_troglodytes": "chimpanzee",
    "philantomba_monticola": "blue duiker",
    "potamochoerus_porcus": "red river hog",
    "tragelaphus_spekii": "sitatunga",
}


class ModelInference:
    """Keras inference implementation for the CBNet Congo Basin classifier."""

    def __init__(self, model_dir: Path, model_path: Path):
        """
        Initialize with model paths.

        Args:
            model_dir: Directory containing model files (including class_list.yaml)
            model_path: Path to the .keras model file
        """
        self.model_dir = model_dir
        self.model_path = model_path
        self.model = None
        self.img_size = 480  # SpeciesNet / EfficientNetV2M input size
        self.class_ids: list[str] | None = None

    def check_gpu(self) -> bool:
        """
        Check GPU availability for TensorFlow/Keras inference.

        Returns:
            True if GPU available, False otherwise
        """
        try:
            return len(tf.config.list_logical_devices("GPU")) > 0
        except Exception:
            return False

    def load_model(self) -> None:
        """
        Load the Keras model and the class list. Called once per worker.

        class_list.yaml maps the model's output index + 1 to the class, as
        the author documents it: `'1': atherurus_africanus, ...`. Output
        index i is class id i + 1, so the list is read in numeric key order.

        Raises:
            RuntimeError: If model loading fails
            FileNotFoundError: If model_path or class_list.yaml is missing
        """
        if not self.model_path.exists():
            raise FileNotFoundError(f"Model file not found: {self.model_path}")

        try:
            self.model = saving.load_model(str(self.model_path), compile=False)
        except Exception as e:
            raise RuntimeError(f"Failed to load Keras model from {self.model_path}: {e}") from e

        class_list_path = self.model_dir / "class_list.yaml"
        if not class_list_path.exists():
            raise FileNotFoundError(f"Class list file not found: {class_list_path}")

        try:
            with open(class_list_path, encoding="utf-8") as f:
                class_map = yaml.safe_load(f)
            by_id = {int(k): str(v).strip() for k, v in class_map.items()}
        except Exception as e:
            raise RuntimeError(f"Failed to load class labels from {class_list_path}: {e}") from e

        n = len(by_id)
        if sorted(by_id) != list(range(1, n + 1)):
            raise RuntimeError(
                f"{class_list_path} must hold ids 1..{n} without gaps, got {sorted(by_id)}"
            )
        n_out = int(self.model.outputs[0].shape[-1])
        if n_out != n:
            raise RuntimeError(
                f"Model has {n_out} outputs but class_list.yaml lists {n} classes"
            )

        missing = [by_id[i] for i in range(1, n + 1) if by_id[i] not in COMMON_NAMES]
        if missing:
            raise RuntimeError(
                f"No common name for model class(es) {missing}; add them to COMMON_NAMES"
            )
        self.class_ids = [COMMON_NAMES[by_id[i]] for i in range(1, n + 1)]

    def get_crop(
        self, image: Image.Image, bbox: tuple[float, float, float, float]
    ) -> Image.Image | None:
        """
        Crop the MegaDetector box out of the full image, as the author does.

        Direct crop, no padding or squaring: the box edges in pixels are the
        normalised coordinates times the image size, rounded. Resizing to the
        model input happens in get_tensor / get_classification.

        Args:
            image: PIL Image (full resolution)
            bbox: Normalized bounding box (x, y, width, height) in range [0.0, 1.0]

        Returns:
            Cropped PIL Image, or None if the box is empty
        """
        x, y, w, h = bbox
        if w <= 0 or h <= 0:
            print(
                f"[CONGO get_crop] Rejecting bbox with zero/negative dims: w={w}, h={h}",
                file=sys.stderr, flush=True,
            )
            return None

        im_width, im_height = image.size
        left = min(max(round(x * im_width), 0), im_width)
        top = min(max(round(y * im_height), 0), im_height)
        right = min(max(round((x + w) * im_width), 0), im_width)
        bottom = min(max(round((y + h) * im_height), 0), im_height)

        if right <= left or bottom <= top:
            print(
                f"[CONGO get_crop] Rejecting empty crop ({left},{top})-({right},{bottom}) "
                f"for bbox {bbox} on {im_width}x{im_height}",
                file=sys.stderr, flush=True,
            )
            return None

        return image.crop((left, top, right, bottom))

    def _preprocess(self, crop: Image.Image) -> np.ndarray:
        """Resize to 480x480 bicubic and scale pixels to [0, 1], as the author does."""
        resized = crop.convert("RGB").resize((self.img_size, self.img_size), Image.BICUBIC)
        return np.asarray(resized, dtype=np.float32) / 255.0

    def _to_classifications(self, probs: np.ndarray) -> list[list[str, float]]:
        return [[self.class_ids[i], float(probs[i])] for i in range(len(self.class_ids))]

    def get_classification(self, crop: Image.Image) -> list[list[str, float]]:
        """
        Run classification on one cropped image.

        Args:
            crop: Cropped PIL Image from get_crop()

        Returns:
            List of [class_name, confidence] lists for ALL classes, in model order.
            Sorting by confidence is handled by classification_worker.py.

        Raises:
            RuntimeError: If model not loaded or inference fails
        """
        if self.model is None or self.class_ids is None:
            raise RuntimeError("Model not loaded - call load_model() first")

        if crop is None:
            return []

        try:
            arr = self._preprocess(crop)
            probs = self.model.predict(arr[None], verbose=0)[0]
            return self._to_classifications(probs)
        except Exception as e:
            raise RuntimeError(f"Keras classification failed: {e}") from e

    def get_class_names(self) -> dict[str, str]:
        """
        Get mapping of class IDs to species names.

        Returns:
            Dict mapping class ID (1-indexed string) to the label the app stores,
            in the model's output order: {"1": class_ids[0], "2": class_ids[1], ...}
        """
        if self.class_ids is None:
            raise RuntimeError("Class IDs not loaded - call load_model() first")
        return {str(i + 1): name for i, name in enumerate(self.class_ids)}

    def get_tensor(self, crop: Image.Image):
        """Preprocess a crop into a float32 [480, 480, 3] array for batch inference."""
        return self._preprocess(crop)

    def classify_batch(self, batch):
        """Run inference on a batch of preprocessed arrays."""
        probs = self.model.predict(batch, verbose=0)
        return [self._to_classifications(p) for p in probs]