Run this model with HF Jobs
Run Addax-Data-Science/TAS-BB-v1 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Addax-Data-Science/TAS-BB-v1. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Addax-Data-Science/TAS-BB-v1 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Addax-Data-Science/TAS-BB-v1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use Addax-Data-Science/TAS-BB-v1 with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://Addax-Data-Science/TAS-BB-v1") - Notebooks
- Google Colab
- Kaggle
Upload inference.py
Browse files19 unmodified lines20212223242580 unmodified lines10610710810911011111211311411511611711811912012112212312443 unmodified lines16816917017117217323 unmodified lines1971981992002012022032042052062072082091 unmodified line2112122132142152162172182192202212222232245 unmodified lines2302312322332342351 unmodified line2372382392402412425 unmodified lines2482492502512522532542552562572582592602613 unmodified lines2652662672682692702712722731 unmodified line27527627727827928028119 unmodified linesfrom __future__ import annotationsimport osfrom pathlib import Pathimport cv280 unmodified linesexcept Exception as e:raise RuntimeError(f"Failed to load class_list.yaml: {e}") from e# Build class_ids list based on YAML format# The YAML can be formatted as either {int: str} or {str: int}inv_class = {v: k for k, v in self.class_map.items()}# Check if keys are numeric (int:label format) or string (label:int format)formatted_int_label = self._can_all_keys_be_converted_to_int(self.class_map)if formatted_int_label:# Format: {0: "species1", 1: "species2", ...}self.class_ids = [self.class_map[i] for i in sorted(inv_class.values())]else:# Format: {"species1": 0, "species2": 1, ...}self.class_ids = sorted(inv_class.values())def _can_all_keys_be_converted_to_int(self, d: dict) -> bool:"""43 unmodified lines# Check for invalid bounding boxes (zero or negative dimensions)if w_box <= 0 or h_box <= 0:return None# Convert normalized coordinates to pixel coordinates23 unmodified linescrop_height = bottom - topif crop_width <= 0 or crop_height <= 0:return None# Crop imageimage_cropped = image.crop((left, top, right, bottom))return image_croppeddef get_classification(self, crop: Image.Image) -> list[tuple[str, float]]:"""Run MEWC-Keras classification on cropped image.1 unmodified line1. Convert PIL Image to numpy array2. Resize to 384x384 (MEWC input size)3. Run model prediction4. Return all class probabilitiesArgs:crop: Cropped PIL ImageReturns:List of (class_name, confidence) tuples for ALL classes, in model order.Example: [("tasmanian_pademelon", 0.50674), ("bennetts_wallaby", 0.46682), ...]Raises:RuntimeError: If model not loaded or inference fails5 unmodified linesraise RuntimeError("Class IDs not loaded - call load_model() first")if crop is None:return []try:1 unmodified lineimg = np.array(crop)if img.size == 0:return []# Resize to MEWC input size (384x384)5 unmodified lines# Run prediction (verbose=0 suppresses progress bar)pred = self.model.predict(img, verbose=0)[0]# Build list of (class_name, confidence) tuples# class_ids is already in the correct order from class_list.yamlclassifications = []for i in range(len(pred)):class_name = self.class_ids[i] # Get species name from class_list.yamlconfidence = float(pred[i])classifications.append((class_name, confidence))return classificationsexcept Exception as e:3 unmodified lines"""Get mapping of class IDs to species names from class_list.yaml.Returns:Dict mapping class ID (1-indexed string) to species nameExample: {"1": "bait", "2": "unknown_animal", ...}Raises:RuntimeError: If class_ids not loaded1 unmodified lineif self.class_ids is None:raise RuntimeError("Class IDs not loaded - call load_model() first")# Build 1-indexed mappingclass_names = {}for i, class_name in enumerate(self.class_ids):class_id_str = str(i + 1) # 1-indexed19 unmodified lines2021222324252680 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413543 unmodified lines17918018118218318418523 unmodified lines2092102112122132142152162172182192202212222232242252262272281 unmodified line2302312322332342352362372382392402412422432445 unmodified lines2502512522532542552561 unmodified line2582592602612622632645 unmodified lines2702712722732742752762772782792802812822832842853 unmodified lines2892902912922932942952962972982993003013023031 unmodified line30530630730830931031131219 unmodified linesfrom __future__ import annotationsimport osimport sysfrom pathlib import Pathimport cv280 unmodified linesexcept Exception as e:raise RuntimeError(f"Failed to load class_list.yaml: {e}") from e# The YAML can be formatted as either {int_str: species_name} or {species_name: int}# IMPORTANT: The model was trained using LEXICOGRAPHIC sorting of YAML keys!# This means '10' comes before '2' in the sorted order, which creates a specific# class ordering that the model learned during training. We MUST use the same# lexicographic sort to match the model's expectations.# Check if keys are numeric (int:label format) or string (label:int format)formatted_int_label = self._can_all_keys_be_converted_to_int(self.class_map)if formatted_int_label:# Format: {'0': 'species1', '1': 'species2', ...}# Sort keys LEXICOGRAPHICALLY (as strings) to match model training# This creates: ['0', '1', '10', '100', '108', '11', '117', '118', '12', '13', '14', ...]inv_class = {v: k for k, v in self.class_map.items()}yaml_keys_sorted = sorted(inv_class.values()) # Lexicographic sort on string keys# Build dense list: model_output[i] → class_ids[i] = species at yaml_keys_sorted[i]self.class_ids = [self.class_map[yaml_key] for yaml_key in yaml_keys_sorted]else:# Format: {"species1": 0, "species2": 1, ...}# Invert to create list where list[i] = speciesinv_class = {v: k for k, v in self.class_map.items()}self.class_ids = [inv_class[i] for i in sorted(inv_class.keys())]def _can_all_keys_be_converted_to_int(self, d: dict) -> bool:"""43 unmodified lines# Check for invalid bounding boxes (zero or negative dimensions)if w_box <= 0 or h_box <= 0:print(f"[TAS get_crop] Rejecting bbox with zero/negative dims: w={w_box}, h={h_box}", file=sys.stderr, flush=True)return None# Convert normalized coordinates to pixel coordinates23 unmodified linescrop_height = bottom - topif crop_width <= 0 or crop_height <= 0:print(f"[TAS get_crop] Rejecting bbox after clipping - crop size {crop_width:.1f}x{crop_height:.1f}\n"f" Original bbox: x={x1:.4f}, y={y1:.4f}, w={w_box:.4f}, h={h_box:.4f}\n"f" Image size: {im_width}x{im_height}\n"f" Pixel coords after clip: ({left:.1f},{top:.1f}) to ({right:.1f},{bottom:.1f})",file=sys.stderr, flush=True)return None# Crop imageimage_cropped = image.crop((left, top, right, bottom))return image_croppeddef get_classification(self, crop: Image.Image) -> list[list[str, float]]:"""Run MEWC-Keras classification on cropped image.1 unmodified line1. Convert PIL Image to numpy array2. Resize to 384x384 (MEWC input size)3. Run model prediction4. Return all class probabilities (unsorted - worker handles sorting)Args:crop: Cropped PIL ImageReturns:List of [class_name, confidence] lists for ALL classes, in model order.Example: [["unknown_animal", 0.00234], ["tasmanian_pademelon", 0.50674], ...]NOTE: Sorting by confidence is handled by classification_worker.pyRaises:RuntimeError: If model not loaded or inference fails5 unmodified linesraise RuntimeError("Class IDs not loaded - call load_model() first")if crop is None:print("[TAS get_classification] Received None crop, returning empty", file=sys.stderr, flush=True)return []try:1 unmodified lineimg = np.array(crop)if img.size == 0:print("[TAS get_classification] Zero-size numpy array, returning empty", file=sys.stderr, flush=True)return []# Resize to MEWC input size (384x384)5 unmodified lines# Run prediction (verbose=0 suppresses progress bar)pred = self.model.predict(img, verbose=0)[0]# Build list of [class_name, confidence] pairs (as lists, not tuples!)# class_ids is already in the correct order from class_list.yamlclassifications = []for i in range(len(pred)):class_name = self.class_ids[i] # Get species name from class_list.yamlconfidence = float(pred[i])classifications.append([class_name, confidence])# NOTE: Sorting by confidence is handled by classification_worker.py# Model developers don't need to sort - just return all class predictionsreturn classificationsexcept Exception as e:3 unmodified lines"""Get mapping of class IDs to species names from class_list.yaml.Returns a 1-indexed contiguous mapping that matches the model's output order.The model was trained with lexicographic sorting of YAML keys, so we createa simple 1-indexed mapping: {1: species_at_position_0, 2: species_at_position_1, ...}This matches the MegaDetector JSON format and the original MEWC implementation.Returns:Dict mapping class ID (1-indexed string) to species nameExample: {"1": "unknown_animal", "2": "tasmanian_pademelon", ..., "10": "fallow_deer", ...}Raises:RuntimeError: If class_ids not loaded1 unmodified lineif self.class_ids is None:raise RuntimeError("Class IDs not loaded - call load_model() first")# Build 1-indexed mapping: model position i → JSON ID str(i+1)# class_ids[0] → "1", class_ids[1] → "2", ..., class_ids[9] → "10" (fallow_deer)class_names = {}for i, class_name in enumerate(self.class_ids):class_id_str = str(i + 1) # 1-indexed
inference.py+45-14