Skip to main content

Bioacoustics & Machine Learning Applications

Project description

bioamla

PyPI version Python License: MIT CI Docs Code style: Ruff

A Python library and CLI for bioacoustics and machine-learning applications — audio I/O and signal processing, acoustic indices, event detection, spectrogram visualization, embedding clustering, species catalogs, datasets, and AST-based ML inference.

Prerelease: 0.2.x is a ground-up rebuild. APIs may still change.

Design

bioamla is organized by domain, not by layer. Each domain is a focused subpackage you import directly:

Import What it does
bioamla.audio audio I/O, analysis, signal processing (filter/denoise/normalize/resample/segment), playback
bioamla.viz spectrograms, mel/MFCC, waveform plots
bioamla.indices acoustic indices — ACI, ADI, AEI, BIO, NDSI, spectral/temporal entropy
bioamla.detect event detection — energy, RIBBIT, peaks, accelerating-pattern
bioamla.cluster embedding dimensionality reduction, clustering, novelty detection
bioamla.catalogs external catalogs — Xeno-canto, iNaturalist, eBird, Macaulay, HuggingFace
bioamla.datasets dataset merge / augment / licensing, annotation conversion, labeled-clip extraction
bioamla.ml Audio Spectrogram Transformer (AST) inference, training, embeddings
bioamla.batch generic batch engine (directory + CSV-metadata modes)
bioamla.system system dependency checks, version & environment info

Two conventions matter for consumers:

  • Errors are exceptions. Functions return plain data and raise from a single hierarchy rooted at bioamla.exceptions.BioamlaError (e.g. AudioLoadError, InvalidInputError, DependencyError). Catch the base class to handle everything.
  • Batteries included. A single pip install bioamla installs the full analysis/ML runtime stack — audio/signal/indices/detect/viz, the PyTorch + AST ML stack, clustering, and playback. Heavy imports are still lazy, so import bioamla and bioamla --help stay fast and don't load torch until you actually call a feature that needs it. The command-line interface lives in a thin [cli] extra (pip install bioamla[cli]) — the library never imports it.

Install

Requires Python ≥ 3.10. Install into a virtual environment so bioamla's dependency stack (PyTorch, librosa, transformers, …) stays isolated from other projects and your system Python:

python -m venv .venv && source .venv/bin/activate    # or: uv venv / conda create -n bioamla
pip install bioamla                 # the full analysis/ML library

pip install "bioamla[cli]"          # + the `bioamla` command-line interface
pip install "bioamla[dev]"          # + contributor tooling (pytest, ruff, mkdocs; includes [cli])

The bioamla console command needs the [cli] extra; on a library-only install it prints an install hint pointing you to pip install bioamla[cli].

System dependencies

Beyond the Python packages, bioamla needs a working FFmpeg install on the host:

  • FFmpeg shared libraries (libav*), major version 4–8 — used by torchcodec (the backend behind torchaudio.load) to decode audio for waveform loading, AST inference/training, and HuggingFace dataset materialization.
  • The ffmpeg/ffprobe CLI — used by pydub to encode non-WAV formats (FLAC/MP3/OGG/M4A) and to read metadata. (Plain WAV I/O works without FFmpeg.)

Both come from a single FFmpeg install:

sudo apt-get install -y ffmpeg            # Debian/Ubuntu
sudo dnf install -y ffmpeg-free           # Fedora/RHEL
brew install ffmpeg                        # macOS
conda install -c conda-forge 'ffmpeg<9'    # conda env (no root); pin to a supported major version

Run bioamla system deps to check what's available. Without FFmpeg, audio decode/encode features raise a clear error (and the affected tests skip rather than fail).

Configuration (API keys)

The bioamla.catalogs providers need API keys to reach their services:

Variable Used by Get a key
EBIRD_API_KEY eBird catalog https://ebird.org/api/keygen
XC_API_KEY Xeno-canto catalog https://xeno-canto.org/account
HF_TOKEN HuggingFace push/pull (datasets, models) https://huggingface.co/settings/tokens

You can either export these as environment variables, or drop them in a .env file in your working directory — bioamla loads it automatically on import (for both the CLI and library use). A real exported variable always takes precedence over the file.

# .env
EBIRD_API_KEY=your_key_here
XC_API_KEY=your_key_here
HF_TOKEN=your_token_here

Keys are only required for the catalog/HuggingFace features that use them; the rest of the library works without any configuration.

Library quickstart

from bioamla.audio import load_audio_data
from bioamla.indices import compute_all_indices
from bioamla.viz import generate_spectrogram
from bioamla.exceptions import BioamlaError

try:
    audio = load_audio_data("recording.wav")          # -> AudioData (mono float32 + sample_rate)

    idx = compute_all_indices(audio.samples, audio.sample_rate, include_entropy=True)
    print(idx.aci, idx.ndsi, idx.h_spectral)

    generate_spectrogram("recording.wav", output_path="spec.png")
except BioamlaError as e:
    print(f"failed: {e}")

AST inference:

from bioamla.ml import predict_file
pred = predict_file("frog.wav", model_path="bioamla/scp-frogs")
print(pred.predicted_label, pred.confidence)

CLI quickstart

bioamla --help                                  # all command groups
bioamla audio info recording.wav                # metadata
bioamla audio filter in.wav out.wav --bandpass-low 500 --bandpass-high 8000
bioamla indices compute recording.wav           # ACI/ADI/AEI/BIO/NDSI + entropy
bioamla detect energy recording.wav             # energy-based detections
bioamla audio visualize recording.wav -o spec.png

# Audio editing transforms (deterministic, single-file):
bioamla audio pitch-shift in.wav out.wav --steps 2
bioamla audio time-stretch in.wav out.wav --rate 1.2
bioamla audio add-noise in.wav out.wav --snr-db 15

# Batch — over a directory or a CSV metadata file (with a `file_name` column):
bioamla batch index --input-dir ./recordings --output-dir ./out
bioamla batch index --input-file meta.csv --output-dir ./out   # merges results into the CSV
bioamla batch audio convert --input-dir ./wavs --output-dir ./flac --format flac

# Catalogs, models, datasets, system:
bioamla catalogs xc search --species "Hyla cinerea"
bioamla catalogs hf pull-dataset ashraq/esc50 ./esc50      # Hub dataset -> labeled-folder layout
bioamla catalogs hf cache --datasets                       # inspect/purge the HF cache (--purge)
bioamla models ast predict frog.wav --model-path bioamla/scp-frogs
bioamla models ast predict soundscape.wav --segment-seconds 3 -o preds.csv   # classify each 3s segment
bioamla models ast train --train-dataset ashraq/esc50      # grab-and-go: train off a Hub id directly
bioamla models ast train --train-dataset ./esc50 --config train.toml   # or from local data + a config
bioamla system deps                                                    # check system deps

Every command is self-documenting (bioamla <group> <command> --help), and the full command tree is in the CLI reference. The API reference documents the library.

Two kinds of augmentation

bioamla keeps a deliberate boundary between audio editing and the pre-training augmentation layer:

  • Editing ops (bioamla.audiopitch_shift, time_stretch, add_noise, apply_gain, plus filter/denoise/normalize/resample/trim) are deterministic single-file transforms you apply with explicit parameters.
  • The augmentation layer (bioamla.datasets.create_augmentation_pipeline) is the randomized, range+probability pipeline used both for synthetic dataset generation (dataset augment) and on-the-fly during models ast train.

Example workflows

Runnable end-to-end studies wired from the CLI live in examples/ — each is a self-contained shell script (see the examples README): catalog → annotate → dataset → train → publish, fine-tuning from a Hub dataset, soundscape analysis, embedding clustering, and iNaturalist clip inference.

Development

make install        # uv sync --extra dev (full stack + tooling)
make test           # pytest
make check          # lint + format-check + test

make install brings in the full runtime stack plus contributor tooling, so the whole test suite runs.

Contributing

Contributions are welcome — see CONTRIBUTING.md for setup and conventions, and the Code of Conduct. Security issues should be reported privately per our Security Policy.

Citation

If you use bioamla in your research, please cite it. Machine-readable metadata lives in CITATION.cff — GitHub's "Cite this repository" button generates APA and BibTeX from it.

Each release is archived on Zenodo with a DOI. Prefer citing the DOI for the specific version you used; otherwise cite the repository:

@software{mcmeen_bioamla,
  author  = {McMeen, John},
  title   = {bioamla: Bioacoustics \& Machine Learning Applications},
  year    = {2026},
  license = {MIT},
  url     = {https://github.com/jmcmeen/bioamla}
}

License

MIT License — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bioamla-0.2.3.tar.gz (226.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bioamla-0.2.3-py3-none-any.whl (277.6 kB view details)

Uploaded Python 3

File details

Details for the file bioamla-0.2.3.tar.gz.

File metadata

  • Download URL: bioamla-0.2.3.tar.gz
  • Upload date:
  • Size: 226.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for bioamla-0.2.3.tar.gz
Algorithm Hash digest
SHA256 415c9b27f3ac8c3fbd7e958009c671b7161e28f466fe63f3cd0d1b6218ff0c15
MD5 493351894c6852fd79557c1c68c25369
BLAKE2b-256 52c511f778a33c46592989c6596ccc598065f0452922ef8857f2e58c77ad58a8

See more details on using hashes here.

Provenance

The following attestation bundles were made for bioamla-0.2.3.tar.gz:

Publisher: publish.yml on jmcmeen/bioamla

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file bioamla-0.2.3-py3-none-any.whl.

File metadata

  • Download URL: bioamla-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 277.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for bioamla-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 ebd85335fb30f7fd63ad7a8d4234da8d8ac5068b3a48bc09687d459f08383261
MD5 73f94ed0e281453aaf2fcdebe2a34797
BLAKE2b-256 d0f1c3dc4b54ba8ccaa9e6fd9394fbbfe6123b4c380084fe4790fa9aefc11869

See more details on using hashes here.

Provenance

The following attestation bundles were made for bioamla-0.2.3-py3-none-any.whl:

Publisher: publish.yml on jmcmeen/bioamla

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page