### Run training with example data Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/train-a-custom-model.md Initiate a training run using the example dataset and targets configuration files. This command uses the same dataset for training and validation for simplicity. ```bash batdetect2 train \ example_data/dataset.yaml \ --val-dataset example_data/dataset.yaml \ --targets example_data/targets.yaml ``` -------------------------------- ### Train with Outputs Configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of providing an outputs configuration file. ```shell batdetect2 train --outputs-config TRAIN_DATASET ``` -------------------------------- ### Install and Run BatDetect2 with uv Source: https://github.com/macaodha/batdetect2/blob/main/README.md Install BatDetect2 using uv and test its command-line interface. ```bash uvx batdetect2 ``` ```bash uv tool install batdetect2 ``` ```bash batdetect2 ``` -------------------------------- ### Train with Logging Configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of specifying a logging configuration file. ```shell batdetect2 train --logging-config TRAIN_DATASET ``` -------------------------------- ### Train with Audio Configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of specifying an audio configuration file. ```shell batdetect2 train --audio-config TRAIN_DATASET ``` -------------------------------- ### Train with Training Configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of providing a custom training configuration file. ```shell batdetect2 train --training-config TRAIN_DATASET ``` -------------------------------- ### Install BatDetect2 Pre-release Source: https://github.com/macaodha/batdetect2/blob/main/README.md Use these commands to install the pre-release version of batdetect2. Ensure you have uv installed for the first two commands. ```bash uvx --from batdetect2==2.0.0b1 batdetect2 ``` ```bash uv tool install batdetect2==2.0.0b1 ``` ```bash pip install batdetect2==2.0.0b1 ``` -------------------------------- ### Train with Log Directory Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of specifying the directory where training logs will be written. ```shell batdetect2 train --log-dir TRAIN_DATASET ``` -------------------------------- ### Train with Targets Configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of providing a custom targets configuration file. ```shell batdetect2 train --targets TRAIN_DATASET ``` -------------------------------- ### Train with Evaluation Configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of providing an evaluation configuration file. ```shell batdetect2 train --evaluation-config TRAIN_DATASET ``` -------------------------------- ### Train with Checkpoint Directory Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of specifying the directory where checkpoints will be saved. ```shell batdetect2 train --ckpt-dir TRAIN_DATASET ``` -------------------------------- ### Train with Inference Configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of specifying an inference configuration file. ```shell batdetect2 train --inference-config TRAIN_DATASET ``` -------------------------------- ### Train with Model Configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of specifying a model configuration file. This cannot be used with the `--model` option. ```shell batdetect2 train --model-config TRAIN_DATASET ``` -------------------------------- ### Install BatDetect2 Source: https://context7.com/macaodha/batdetect2/llms.txt Install BatDetect2 using various package managers. Python 3.10-3.13 is supported. ```bash # One-off run (no permanent install) uvx batdetect2==2.0.0b1 ``` ```bash # Permanent tool install (uv) uv tool install batdetect2==2.0.0b1 ``` ```bash # Add to a uv project uv add batdetect2==2.0.0b1 ``` ```bash # pip pip install batdetect2==2.0.0b1 ``` -------------------------------- ### Example dataset configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/train-a-custom-model.md Define the dataset configuration in YAML format, specifying the location of audio recordings and annotations. ```yaml name: example dataset description: Only for demonstration purposes sources: - format: batdetect2 name: Example Data description: Examples included for testing batdetect2 annotations_dir: example_data/anns audio_dir: example_data/audio ``` -------------------------------- ### Install BatDetect2 with Pip Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/getting_started.md Installs BatDetect2 using pip. It is recommended to create and activate a virtual environment first to avoid conflicts. ```bash pip install batdetect2 ``` ```bash python -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Train with Experiment and Run Names Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of specifying experiment and run names for logging backends. ```shell batdetect2 train --experiment-name --run-name TRAIN_DATASET ``` -------------------------------- ### Continue Training from Checkpoint Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of continuing training from an existing checkpoint using the `--model` option. ```shell batdetect2 train --model TRAIN_DATASET ``` -------------------------------- ### Train with Number of Epochs Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of setting the maximum number of training epochs. ```shell batdetect2 train --num-epochs TRAIN_DATASET ``` -------------------------------- ### Example targets configuration Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/train-a-custom-model.md Define the targets configuration in YAML format to map annotations to detection and classification outputs for training. ```yaml detection_target: name: bat match_if: name: all_of conditions: - name: has_tag tag: { key: event, value: Echolocation } - name: not condition: name: has_tag tag: { key: class, value: Unknown } assign_tags: - key: class value: Bat classification_targets: - name: myomys tags: - key: class value: Myotis mystacinus - name: pippip tags: - key: class value: Pipistrellus pipistrellus ``` -------------------------------- ### Train with Base Directory Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of specifying a base directory to resolve relative paths within dataset configurations. ```shell batdetect2 train --base-dir TRAIN_DATASET ``` -------------------------------- ### Process Directory with Parquet Output Format Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/save-predictions-in-different-output-formats.md Use the `--format` flag for quick experiments to specify the output format. This example saves predictions in the parquet format. ```bash batdetect2 process directory \ path/to/model.ckpt \ path/to/audio_dir \ path/to/outputs \ --format parquet ``` -------------------------------- ### Load Model with BatDetect2API.from_checkpoint Source: https://context7.com/macaodha/batdetect2/llms.txt Load a trained model using BatDetect2API.from_checkpoint. Supports bundled aliases, local checkpoints, and Hugging Face URIs. For Hugging Face support, install with `pip install batdetect2[huggingface]`. ```python from batdetect2 import BatDetect2API # 1. Load the default bundled UK model api = BatDetect2API.from_checkpoint() ``` ```python # 2. Load the same model by its alias api = BatDetect2API.from_checkpoint("uk_same") ``` ```python # 3. Load from a local checkpoint produced by a training run api = BatDetect2API.from_checkpoint("outputs/checkpoints/epoch=19-step=20.ckpt") ``` ```python # 4. Load from Hugging Face (requires: pip install batdetect2[huggingface]) api = BatDetect2API.from_checkpoint("hf://owner/repo/path/to/model.ckpt") ``` -------------------------------- ### Install BatDetect2 CLI Permanently Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/getting_started.md Installs the BatDetect2 command-line interface to be always available in your terminal. Use the upgrade command for future updates. ```bash uv tool install batdetect2 ``` ```bash uv tool upgrade batdetect2 ``` ```bash batdetect2 ``` -------------------------------- ### Train with Random Seed Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of setting a random seed for reproducibility. ```shell batdetect2 train --seed TRAIN_DATASET ``` -------------------------------- ### Clone repository and navigate Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/run-inference-on-folder.md Clone the BatDetect2 repository and change the current directory to the repository root. This is useful for following the tutorial with example files. ```bash git clone https://github.com/macaodha/batdetect2.git cd batdetect2 ``` -------------------------------- ### Outputs Configuration for Raw Format Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/save-predictions-in-different-output-formats.md Configure output formats and transforms using a YAML file for reproducible runs. This example sets the format to 'raw' and includes class scores, features, and geometry. ```yaml format: name: raw include_class_scores: true include_features: true include_geometry: true transform: detection_transforms: [] clip_transforms: [] ``` -------------------------------- ### Train with Data Loading Workers Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of setting the number of worker processes for loading training and validation data. ```shell batdetect2 train --train-workers --val-workers TRAIN_DATASET ``` -------------------------------- ### Train with Validation Dataset Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/train.md Example of using the `batdetect2 train` command with a specified validation dataset. ```shell batdetect2 train --val-dataset TRAIN_DATASET ``` -------------------------------- ### Try BatDetect2 Temporarily Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/getting_started.md Use this command to run BatDetect2 without a permanent installation. It downloads and executes the code and dependencies in a temporary environment. ```bash uvx batdetect2 ``` -------------------------------- ### Process audio with a Hugging Face URI (CLI) Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/choose-a-model.md Use a Hugging Face URI to specify a model checkpoint for CLI processing. Ensure the optional Hugging Face dependency is installed. ```bash batdetect2 process directory \ path/to/audio \ path/to/outputs \ --model hf://owner/repo/path/to/model.ckpt ``` -------------------------------- ### Prepare for PCA Plotting Source: https://github.com/macaodha/batdetect2/blob/main/batdetect2_notebook.ipynb Installs the seaborn library if needed and imports necessary libraries (seaborn, PCA) for plotting the feature projections. ```python # We will use seaborn to plot the PCA projection of the features # Make sure it is installed by running the following line # %pip install seaborn import seaborn as sns from sklearn.decomposition import PCA ``` -------------------------------- ### Build Model with BatDetect2API.from_config Source: https://context7.com/macaodha/batdetect2/llms.txt Construct a new, untrained BatDetect2API instance from configuration objects. This is used for starting new training runs without an existing checkpoint. ```python from batdetect2.api_v2 import BatDetect2API from batdetect2.models import ModelConfig from batdetect2.audio import AudioConfig from batdetect2.train import TrainingConfig api = BatDetect2API.from_config( model_config=ModelConfig(), audio_config=AudioConfig(samplerate=256000), train_config=TrainingConfig(num_epochs=50), ) ``` -------------------------------- ### BatDetect2API.from_config Source: https://context7.com/macaodha/batdetect2/llms.txt Constructs a new untrained BatDetect2API instance from configuration objects. This is used when starting a brand-new training run without an existing checkpoint. ```APIDOC ## BatDetect2API.from_config — Build a model from scratch ### Description Constructs a new untrained `BatDetect2API` instance from configuration objects instead of loading weights from disk. Used when starting a brand-new training run without an existing checkpoint. ### Method `BatDetect2API.from_config(model_config: ModelConfig, audio_config: AudioConfig, train_config: TrainingConfig) -> BatDetect2API` ### Parameters #### Request Body - **model_config** (ModelConfig) - Required - Configuration for the model architecture. - **audio_config** (AudioConfig) - Required - Configuration for audio loading and processing. - **train_config** (TrainingConfig) - Required - Configuration for the training process. ### Request Example ```python from batdetect2.api_v2 import BatDetect2API from batdetect2.models import ModelConfig from batdetect2.audio import AudioConfig from batdetect2.train import TrainingConfig api = BatDetect2API.from_config( model_config=ModelConfig(), audio_config=AudioConfig(samplerate=256000), train_config=TrainingConfig(num_epochs=50), ) ``` ``` -------------------------------- ### Example Training Metrics CSV Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/train-a-custom-model.md This CSV file contains validation metrics per epoch, including Mean Average Precision (mAP), detection AP, and total validation loss. Ensure a validation dataset is provided to generate these metrics. ```csv classification/mean_average_precision,detection/average_precision,epoch,total_loss/val 0.10041624307632446,0.3697187900543213,0,4070.3515625 0.11328697204589844,0.346899151802063,1,3941.6455078125 0.1388484090566635,0.36171725392341614,2,3776.323974609375 ``` -------------------------------- ### Prepare Data for Finetuning Source: https://github.com/macaodha/batdetect2/blob/main/src/batdetect2/finetune/readme.md Use this script to split annotated audio data into training and validation sets. Specify dataset name, paths to audio and annotations, and an output directory. Consider using `--rand_seed` for different splits or `--train_file` and `--test_file` for custom file lists. ```python python prep_data_finetune.py dataset_name path_to_audio/ path_to_annotations/ path_to_output_anns/ ``` ```python python prep_data_finetune.py dataset_name path_to_audio/ path_to_annotations/ path_to_output/ --train_file path_to_file/list_of_train_files.txt --test_file path_to_file/list_of_test_files.txt ``` ```python python prep_data_finetune.py dataset_name path_to_audio/audio/ path_to_annotations/anns/ path_to_output/ --input_class_names "Histiotus;Molossidae;Lasiurus;Myotis;Rhogeesa;Vespertilionidae" --output_class_names "Group One;Group One;Group One;Group Two;Group Two;Group Three" ``` -------------------------------- ### get_class_scores Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/api.md Get class scores as `(class_name, score)` pairs. ```APIDOC ## get_class_scores ### Description Get class scores as `(class_name, score)` pairs. ### Parameters - **detection** (Detection) - Detection whose class scores will be returned. - **include_top_class** (bool) - If `False`, omit the highest-scoring class from the result. Defaults to True. - **sort_descending** (bool) - If `True`, sort scores from highest to lowest. Defaults to True. ### Returns list[tuple[str, float]] - Class-score pairs for the detection. ``` -------------------------------- ### Synchronize Dependencies with uv Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/development/index.md Use the 'uv sync' command to manage project dependencies and set up the development environment. ```bash uv sync ``` -------------------------------- ### Create a File List for BatDetect2 Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/run-inference-on-folder.md Create a text file where each line specifies the path to an audio recording you want to process. This allows for selective inference on a custom set of files. ```text path/to/audio/file_001.wav path/to/audio/file_002.wav path/to/audio/file_010.wav ``` -------------------------------- ### Load Default Checkpoint and Process File Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/api.md Loads the default BatDetect2 checkpoint and processes a single audio file. Ensure 'recording.wav' exists. ```python from batdetect2.api_v2 import BatDetect2API api = BatDetect2API.from_checkpoint() prediction = api.process_file("recording.wav") ``` -------------------------------- ### from_checkpoint Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/api.md Build an API instance from a saved checkpoint. ```APIDOC ## from_checkpoint ### Description Build an API instance from a saved checkpoint. ### Parameters - **path** (data.PathLike | str | None) - Checkpoint path, bundled checkpoint alias, or Hugging Face URI. If omitted, the default bundled checkpoint is used. - **audio_config** (AudioConfig | None) - Audio config override. - **train_config** (TrainingConfig | None) - Training config override. - **evaluation_config** (EvaluationConfig | None) - Evaluation config override. - **inference_config** (InferenceConfig | None) - Inference config override. - **outputs_config** (OutputsConfig | None) - Output config override. - **logging_config** (AppLoggingConfig | None) - Logging config override. ### Returns BatDetect2API - Configured API instance. ``` -------------------------------- ### Check Source Loading with Data Summary Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/configure-aoef-dataset.md Run a data summary on your dataset configuration to verify that the AOEF source loads correctly. Replace `path/to/dataset.yaml` with the actual path to your configuration file. ```bash batdetect2 data summary path/to/dataset.yaml ``` -------------------------------- ### build_default_target_config Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/targets.md Builds a default target configuration object, typically used as a starting point for custom configurations. ```APIDOC ### batdetect2.targets.build_default_target_config(class_names: list[str]) -> [TargetConfig](#batdetect2.targets.TargetConfig) Build a default target configuration object. ## Parameters class_names : A list of class names to include in the default configuration. ``` -------------------------------- ### Configure BatDetect2 Run Source: https://github.com/macaodha/batdetect2/blob/main/batdetect2_notebook.ipynb Sets up the configuration parameters for the BatDetect2 model, such as detection threshold and time expansion factor. ```python # Configure the run config = api.get_config( detection_threshold=0.3, time_expansion_factor=1, max_duration=3, ) ``` -------------------------------- ### from_config Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/api.md Build an API instance from config objects. Use this when you want to create a new model without loading a saved checkpoint. ```APIDOC ## from_config ### Description Build an API instance from config objects. Use this when you want to create a new model without loading a saved checkpoint. ### Parameters - **model_config** (ModelConfig | None) - Model config. If omitted, the default model config is used. - **targets_config** (TargetConfig | None) - Target config. If omitted, the default target config is used. - **audio_config** (AudioConfig | None) - Audio config. If omitted, the default audio config is used. - **train_config** (TrainingConfig | None) - Training config. If omitted, the default training config is used. - **evaluation_config** (EvaluationConfig | None) - Evaluation config. If omitted, the default evaluation config is used. - **inference_config** (InferenceConfig | None) - Inference config. If omitted, the default inference config is used. - **outputs_config** (OutputsConfig | None) - Output config. If omitted, the default outputs config is used. - **logging_config** (AppLoggingConfig | None) - Logging config. If omitted, the default logging config is used. ### Returns BatDetect2API - Configured API instance. ``` -------------------------------- ### Run BatDetect2 on a directory with default settings Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/run-inference-on-folder.md Process all supported audio files in a specified input directory and save the results to an output directory using the default UK model. BatDetect2 will create the output directory if it does not exist. ```bash batdetect2 process directory \ path/to/audio \ path/to/outputs ``` ```bash batdetect2 process directory \ example_data/audio \ example_outputs/first_run ``` -------------------------------- ### Configure Finetuning Parameters Source: https://github.com/macaodha/batdetect2/blob/main/src/batdetect2/finetune/readme.md Adjust the number of training epochs using the `--num_epochs` flag. To train a model from scratch instead of finetuning, use the `--train_from_scratch` flag. ```python python finetune_model.py --num_epochs 400 ... ``` ```python python finetune_model.py --train_from_scratch ... ``` -------------------------------- ### Get ranked class scores for a detection Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/inspect-class-scores-in-python.md Iterate through all class scores for a given detection. Requires initializing BatDetect2API and processing an audio file. ```python from pathlib import Path from batdetect2.api_v2 import BatDetect2API api = BatDetect2API.from_checkpoint(Path("path/to/model.ckpt")) prediction = api.process_file(Path("path/to/audio.wav")) for detection in prediction.detections: print("detection score:", detection.detection_score) for class_name, score in api.get_class_scores(detection): print(class_name, score) ``` -------------------------------- ### Load Checkpoint and Process Directory Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/api.md Loads a specified checkpoint ('uk_same') and processes all audio files in a directory. Predictions are then saved to the 'outputs/' directory. Ensure the 'audio' directory exists. ```python from pathlib import Path api = BatDetect2API.from_checkpoint("uk_same") predictions = api.process_directory("audio") api.save_predictions(predictions, "outputs/") ``` -------------------------------- ### Train from a Checkpoint Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/fine-tune-from-a-checkpoint.md Use the `--model` argument to specify a checkpoint file for fine-tuning. Do not combine `--model` with `--model-config`. ```bash batdetect2 train \ path/to/train_dataset.yaml \ --val-dataset path/to/val_dataset.yaml \ --model path/to/model.ckpt \ --training-config path/to/training.yaml ``` -------------------------------- ### BatDetect2API.process_audio Source: https://context7.com/macaodha/batdetect2/llms.txt Performs inference on a raw NumPy waveform array. This method is suitable when audio data is already loaded into memory, for example, from another processing stage. ```APIDOC ## `BatDetect2API.process_audio` — Inference on a raw waveform array Accepts a NumPy waveform array (already loaded into memory) and returns a list of `Detection` objects. Useful when audio is produced by another part of the pipeline rather than read from disk. ```python import numpy as np from batdetect2 import BatDetect2API api = BatDetect2API.from_checkpoint() # Load audio manually, then run inference audio = api.load_audio("example_data/audio/20180627_215323-RHIFER-LR_0_0.5.wav") print(f"Audio shape: {audio.shape}") # e.g. (128000,) detections = api.process_audio(audio, detection_threshold=0.3) for det in detections: print(api.get_top_class_name(det), det.detection_score) ``` ``` -------------------------------- ### Typical Training Output Directory Structure Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/train-a-custom-model.md This structure shows the default layout of files generated during training, including checkpoints, logs, and configuration details. ```text outputs/ checkpoints/ epoch=19-step=20.ckpt logs/ version_0/ metrics.csv hparams.yaml training_artifacts/ train_dataset.yaml val_dataset.yaml targets.yaml train_class_summary.csv val_class_summary.csv ``` -------------------------------- ### Get Top Class Name from Detection Source: https://context7.com/macaodha/batdetect2/llms.txt Retrieves the string name of the highest-scoring classification class for a Detection object. Requires processing audio or spectrogram first. ```python from batdetect2 import BatDetect2API api = BatDetect2API.from_checkpoint() prediction = api.process_file("example_data/audio/20180627_215323-RHIFER-LR_0_0.5.wav") for det in prediction.detections: species = api.get_top_class_name(det) print(species) # e.g. "Rhinolophus ferrumequinum" ``` -------------------------------- ### Process audio with a local model checkpoint (CLI) Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/choose-a-model.md Use a local path to specify a model checkpoint file when processing audio with the CLI. Ensure the path to the model file is correct. ```bash batdetect2 process directory \ path/to/audio \ path/to/outputs \ --model path/to/model.ckpt ``` -------------------------------- ### Process audio with a bundled model alias (CLI) Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/choose-a-model.md Specify a bundled model alias, such as 'uk_same', using the --model flag in the CLI for processing audio. This is convenient for using pre-packaged models. ```bash batdetect2 process directory \ path/to/audio \ path/to/outputs \ --model uk_same ``` -------------------------------- ### Evaluate Checkpoint on Test Dataset Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/evaluate.md Use this command to load a model checkpoint, run evaluations on the provided test dataset, and save the resulting metrics and artifacts to the specified output directory. Configure various aspects like audio, evaluation, inference, outputs, and logging through separate configuration files. ```shell batdetect2 evaluate [OPTIONS] TEST_DATASET ``` -------------------------------- ### Filter Annotation Projects by Task State Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/configure-aoef-dataset.md When `annotations_path` points to an AnnotationProject, you can filter annotations by task state using the `filter` option. This example shows how to include only completed and verified annotations, while excluding issues. ```yaml sources: - name: whombat_verified format: aoef audio_dir: /path/to/audio annotations_path: /path/to/project_export.aoef filter: only_completed: true only_verified: true exclude_issues: true ``` -------------------------------- ### Initialize BatDetect2 API and Process File Source: https://context7.com/macaodha/batdetect2/llms.txt Load a BatDetect2 model from a checkpoint and process a single audio file. This demonstrates the basic usage of the Python API for inference. ```python from batdetect2 import BatDetect2API api = BatDetect2API.from_checkpoint() pred = api.process_file("example_data/audio/20180627_215323-RHIFER-LR_0_0.5.wav") ``` -------------------------------- ### Get Feature Vector for a Detection Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/inspect-detection-features-in-python.md Access the feature vector for a specific detection using `api.get_detection_features`. This method returns the internal model representation for the detection. Ensure the BatDetect2API is initialized with a model checkpoint and audio files are processed. ```python from pathlib import Path from batdetect2.api_v2 import BatDetect2API api = BatDetect2API.from_checkpoint(Path("path/to/model.ckpt")) prediction = api.process_file(Path("path/to/audio.wav")) for detection in prediction.detections: features = api.get_detection_features(detection) print(features.shape) ``` -------------------------------- ### process_directory Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/api.md Runs inference on all supported audio files within a specified directory. ```APIDOC ## process_directory(audio_dir: data.PathLike, detection_threshold: float | None = None) -> list[ClipDetections] ### Description Run inference on all supported audio files in a directory. ### Parameters - **audio_dir** (data.PathLike) - Description: Directory containing audio files. - **detection_threshold** (float | None) - Description: Detection score threshold override. ### Returns - **list[ClipDetections]** - Description: Predictions for all supported audio files found in the directory. ``` -------------------------------- ### Train BatDetect2 Model from Scratch Source: https://context7.com/macaodha/batdetect2/llms.txt Use this command to train a new BatDetect2 model using specified training and validation datasets. Ensure dataset and targets configurations are correctly defined. ```bash batdetect2 train \ example_data/dataset.yaml \ --val-dataset example_data/dataset.yaml \ --targets example_data/targets.yaml \ --num-epochs 50 \ --seed 42 ``` -------------------------------- ### Create BatDetect2API instance Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/integrate-with-a-python-pipeline.md Instantiate the BatDetect2API using the default UK model checkpoint. This is the first step for any Python-based BatDetect2 workflow. ```python from batdetect2 import BatDetect2API # If you don't specify a checkpoint the default model will be loaded api = BatDetect2API.from_checkpoint() ``` -------------------------------- ### Use Audio Configuration in CLI Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/configure-audio-preprocessing.md Apply custom audio preprocessing configurations during CLI inference or evaluation using the `--audio-config` flag. ```bash batdetect2 process directory \ path/to/model.ckpt \ path/to/audio_dir \ path/to/outputs \ --audio-config path/to/audio.yaml ``` -------------------------------- ### Run BatDetect2 on Audio Folder Source: https://github.com/macaodha/batdetect2/blob/main/README.md Process audio files in a directory using the default UK model and save outputs. You can also specify a custom model checkpoint. ```bash batdetect2 process directory example_data/audio outputs ``` ```bash batdetect2 process directory --model path/to/checkpoint.ckpt example_data/audio outputs ``` -------------------------------- ### Finetune BatDetect2 Model Source: https://github.com/macaodha/batdetect2/blob/main/src/batdetect2/finetune/readme.md Execute this script to finetune the BatDetect2 model using prepared training and testing data splits. Provide paths to audio, the generated TRAIN.json and TEST.json files, and the pre-trained model checkpoint. ```python python finetune_model.py path_to_audio/ path_to_train/TRAIN.json path_to_train/TEST.json ../../models/Net2DFast_UK_same.pth.tar ``` -------------------------------- ### Load a local model checkpoint (Python) Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/choose-a-model.md Instantiate the BatDetect2API with a local model checkpoint file path in Python. This allows for programmatic control over model selection. ```python from batdetect2.api_v2 import BatDetect2API api = BatDetect2API.from_checkpoint("path/to/model.ckpt") ``` -------------------------------- ### BatDetect2API.process_directory Source: https://context7.com/macaodha/batdetect2/llms.txt Discovers all supported audio files in a directory and runs inference on each one, returning a list of ClipDetections objects. ```APIDOC ## BatDetect2API.process_directory — Batch inference on a folder ### Description Discovers all supported audio files in a directory and runs inference on each one, returning a list of `ClipDetections` — one per file. ### Method `BatDetect2API.process_directory(directory_path: str, detection_threshold: float = 0.0) -> List[ClipDetections]` ### Parameters #### Path Parameters - **directory_path** (str) - Required - Path to the directory containing audio files. #### Query Parameters - **detection_threshold** (float) - Optional - Minimum detection score threshold for calls. Defaults to 0.0. ### Response #### Success Response (200) - **List[ClipDetections]** - A list where each element is a `ClipDetections` object for a processed audio file. ### Request Example ```python from batdetect2 import BatDetect2API api = BatDetect2API.from_checkpoint() results = api.process_directory("example_data/audio", detection_threshold=0.3) for clip_dets in results: fname = clip_dets.clip.recording.path.name n = len(clip_dets.detections) print(f"{fname}: {n} detection(s)") # Example output: # 20170701_213954-MYOMYS-LR_0_0.5.wav: 3 detection(s) # 20180530_213516-EPTSER-LR_0_0.5.wav: 2 detection(s) # 20180627_215323-RHIFER-LR_0_0.5.wav: 1 detection(s) ``` ``` -------------------------------- ### process_files Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/api.md Runs inference on multiple audio files, with options for batching and configuration. ```APIDOC ## process_files(audio_files: Sequence[data.PathLike], batch_size: int | None = None, num_workers: int = 0, audio_config: AudioConfig | None = None, inference_config: InferenceConfig | None = None, output_config: OutputsConfig | None = None, detection_threshold: float | None = None) -> list[ClipDetections] ### Description Run inference on multiple audio files. ### Parameters - **audio_files** (Sequence[data.PathLike]) - Description: Audio file paths. - **batch_size** (int | None) - Description: Batch size override. - **num_workers** (int) - Description: Number of worker processes for audio loading. - **audio_config** (AudioConfig | None) - Description: Audio config override. - **inference_config** (InferenceConfig | None) - Description: Inference config override. - **output_config** (OutputsConfig | None) - Description: Output config override. - **detection_threshold** (float | None) - Description: Detection score threshold override. ### Returns - **list[ClipDetections]** - Description: Predictions for each input file. ``` -------------------------------- ### process_file Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/api.md Runs inference on a single audio file. ```APIDOC ## process_file(audio_file: data.PathLike, batch_size: int | None = None, detection_threshold: float | None = None) -> ClipDetections ### Description Run inference on one audio file. ### Parameters - **audio_file** (data.PathLike) - Description: Path to the audio file. - **batch_size** (int | None) - Description: Batch size override. If omitted, the inference config value is used. - **detection_threshold** (float | None) - Description: Detection score threshold override. ### Returns - **ClipDetections** - Description: Predictions for the full recording. ``` -------------------------------- ### BatDetect2API.from_checkpoint Source: https://context7.com/macaodha/batdetect2/llms.txt Loads a trained BatDetect2 model from a checkpoint file, alias, or Hugging Face URI. This is the primary method for initializing the API for inference or further training. ```APIDOC ## BatDetect2API.from_checkpoint — Load a model ### Description Loads a trained model from a local checkpoint file, a bundled alias (`uk_same`), or a Hugging Face URI and returns a fully configured `BatDetect2API` instance ready for inference, evaluation, or training. ### Method `BatDetect2API.from_checkpoint(checkpoint_path: str = "uk_same") -> BatDetect2API` ### Parameters #### Path Parameters - **checkpoint_path** (str) - Optional - Path to a local checkpoint file, a bundled alias (e.g., "uk_same"), or a Hugging Face URI (e.g., "hf://owner/repo/path/to/model.ckpt"). Defaults to "uk_same". ### Request Example ```python from batdetect2 import BatDetect2API # Load the default bundled UK model api = BatDetect2API.from_checkpoint() # Load the same model by its alias api = BatDetect2API.from_checkpoint("uk_same") # Load from a local checkpoint produced by a training run api = BatDetect2API.from_checkpoint("outputs/checkpoints/epoch=19-step=20.ckpt") # Load from Hugging Face (requires: pip install batdetect2[huggingface]) api = BatDetect2API.from_checkpoint("hf://owner/repo/path/to/model.ckpt") ``` ``` -------------------------------- ### Process audio using lower-level methods Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/tutorials/integrate-with-a-python-pipeline.md Load audio manually, generate a spectrogram, and then process the spectrogram for finer control over the inference pipeline. This is useful for inspecting intermediate steps or processing specific segments. ```python from batdetect2 import BatDetect2API api = BatDetect2API.from_checkpoint() audio = api.load_audio("path/to/audio.wav") print(audio.shape) spec = api.generate_spectrogram(audio) print(spec.shape) detections = api.process_spectrogram(spec) print(len(detections)) ``` -------------------------------- ### Summarize Dataset Information Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/data.md This command displays the dataset size and an optional class summary based on configured targets. It prints the number of annotated clips and a per-class summary table if targets are provided. ```shell batdetect2 data summary [OPTIONS] DATASET_CONFIG ``` -------------------------------- ### Process Directory Input Mode Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/how_to/choose-an-inference-input-mode.md Use `process directory` when recordings are organized in a single directory tree and BatDetect2 should discover audio files automatically. This is the simplest mode for initial runs. ```bash batdetect2 process directory \ path/to/model.ckpt \ path/to/audio_dir \ path/to/outputs ``` -------------------------------- ### Finetune Command Usage Source: https://github.com/macaodha/batdetect2/blob/main/docs/source/reference/cli/finetune.md Basic usage of the `batdetect2 finetune` command. Specify the training dataset and optionally provide paths for targets, model, validation dataset, and other configuration files. ```shell batdetect2 finetune [OPTIONS] TRAIN_DATASET ```