BatBot API
BatBot is the machine learning interface for the Kitware BatAI project. This page specifies the Python API to interact with all of the algorithms and machine learning models that have been pretrained for inference in a production environment.
Environment Variables
The BatBot API and CLI have environment variables (envars) that allow you to configure global settings and configurations.
BATBOT_VERBOSEor the legacyVERBOSE(default: not set)A verbosity flag that can be set to turn on debug logging. Defaults to “not set”, which translates to no debug logging. Setting this value to anything will turn on debug logging (e.g.,
VERBOSE=1).
BATBOT_CLASSIFIER_CONFIGor the legacyCLASSIFIER_CONFIG(default:mobilenet)Selects the classifier model configuration.
BATBOT_CLASSIFIER_BATCH_SIZEor the legacyCLASSIFIER_BATCH_SIZE(default:10)Limits the number of 224-by-224 spectrogram windows sent to ONNX Runtime in one inference call.
BATBOT_REDUCED(default: not set)Set to
1to limit each ONNX Runtime session to two intra-op and inter-op threads. This can reduce contention when using several workers.
BATBOT_CACHE_DIR(default: Pooch’s platform-specific user cache)Overrides the model/example cache root. Native paths, environment variables, and the home-directory shorthand are supported. Containers default to
/tmp/batbot-cacheso non-root and arbitrary-UID runs can cache models.
Spectrogram
- batbot.spectrogram.calculate_astar_grid_and_endpoints(segment, index, segmentmask, peak, canvas, kernel=7, output_path='.')[source]
- batbot.spectrogram.calculate_harmonic_and_echo_flags(original, index, segmentmask, harmonic, echo, canvas, kernel=5, output_path='.')[source]
- batbot.spectrogram.calculate_window_and_stride(stft_db, duration, window_size_ms=12, strides_per_window=3, time_vec=None)[source]
- batbot.spectrogram.compute_wrapper(wav_filepath, out_file_stem=None, output_folder=None, fast_mode=False, force_overwrite=False, quiet=False, annotations=None, bitdepth=16, mask_secondary_effects=False, plot_uncompressed_amplitude=False, include_original_sr=False, time_buffer_ms=1.0, debug=False, **kwargs)[source]
Compute the spectrograms for a given input WAV and saves them to disk.
If a given spectrogram has already been rendered to disk, it will not be recomputed.
- Parameters:
wav_filepath (str) – WAV filepath (relative or absolute) to compute spectrograms for.
ext (str, optional) – The file extension of the resulting spectrogram files. If this value is not specified, it will use the same extension as wav_filepath. Passed as input to
batbot.spectrogram.spectrogram_filepath(). Defaults toNone.**kwargs – keyword arguments passed to
batbot.spectrogram.spectrogram_grid()
- Returns:
the original WAV file’s sample rate.
the original WAV file’s duration in seconds.
tuple of spectrogram’s (width, height) in pixels
tuple of spectrogram’s (min, max) frequency
list of spectrogram filepaths, split by 50k horizontal pixels
- Return type:
tuple ( int, float, tuple (int), list ( str ) )
- batbot.spectrogram.create_coarse_candidates(stft_db, window, stride, threshold_stddev=3.0, min_band_idx=None)[source]
- batbot.spectrogram.extract_contour_keypoints(path, canvas, index, peak, contour_smoothing_sigma=5, output_path='.')[source]
- batbot.spectrogram.filter_candidates_to_ranges(stft_db, candidates, window=16, skew_stddev=2.0, area_percent=0.1, min_band_idx=None, output_path=None, fast_mode=False, quiet=False)[source]
- batbot.spectrogram.filter_contour(segment, index, med_db=None, std_db=None, kernel=5, output_path='.')[source]
- batbot.spectrogram.find_contour_and_peak(segment, index, max_locations, peak_db=None, peak_db_std=None, threshold_std=2.0, sigma=5, output_path='.', threshold=None)[source]
- batbot.spectrogram.find_contour_connected_components(segment, index, locations, sequence=4, output_path='.')[source]
- batbot.spectrogram.find_harmonic(segmentmask, index, freq_offset, kernel=15, output_path='.')[source]
- batbot.spectrogram.gain_stft(stft_db, gain_db=120.0, autogain_stddev=5.0, max_band_idx=None)[source]
- batbot.spectrogram.generate_waveplot(waveform, stft_db, hop_length=16, size_multiplier=4, bg_color=(240, 255, 255), fg_color=(237, 149, 100), zero_color=(0, 0, 0))[source]
- batbot.spectrogram.get_debug_path(output_folder, wav_filepath, enabled, purge=True, ensure=True)[source]
- batbot.spectrogram.load_stft(wav_filepath, sr=250000.0, n_fft=512, window='blackmanharris', win_length=256, hop_length=16, fast_mode=False, use_original_sr=False)[source]
- batbot.spectrogram.normalize_contour(segment, index, dtype=None, blur=True, kernel=5, output_path='.')[source]
- batbot.spectrogram.plot_chirp_candidates(stft_db, candidate_dbs, ranges, reject_idxs, output_path='.', output_filename='candidates.png')[source]
- batbot.spectrogram.plot_histogram(image, ignore_zeros=False, max_val=None, smoothing=128, min_band_idx=None, csum_threshold=0.95, output_path='.', output_filename='histogram.png')[source]
- batbot.spectrogram.refine_contour(segment, index, max_locations, segmentmask, peak, output_path='.')[source]
- batbot.spectrogram.remove_harmonic_and_echo(segment, index, harmonic, echo, threshold, med_db=None, std_db=None, kernel=15, output_path='.')[source]
- batbot.spectrogram.significant_contour_path(begin, end, freq_step, time_step, min_bandwidth_khz=6000.0, min_duration_ms=2.0)[source]
Classifier
Classify BatBot spectrograms with the MobileNet ONNX model.
The low-level pre(), predict(), and post() functions retain
the Scoutbot-style pipeline. Classifier is the preferred API for
repeated work because it owns and reuses its ONNX Runtime session.
- class batbot.classifier.BulkClassification[source]
Bases:
TypedDictJSON-compatible bulk classification response.
- results: list[ClassificationResult | ClassificationFailure]
- summary: ClassificationSummary
- class batbot.classifier.ClassificationFailure[source]
Bases:
TypedDictInput that could not be classified during fault-tolerant bulk work.
- error: str
- path: str
- class batbot.classifier.ClassificationResult[source]
Bases:
TypedDictSuccessful classification serialized by the Python API and CLI.
- confidence: float
- label: str
- path: str
- scores: dict[str, float]
- spectrogram_paths: NotRequired[list[str]]
- top: list[TopPrediction]
- window_count: int
- class batbot.classifier.ClassificationSummary[source]
Bases:
TypedDictAggregate species and confidence statistics.
- classified: int
- failed: int
- label_counts: dict[str, int]
- mean_confidence: float | None
- noise_count: int
- species_counts: dict[str, int]
- total: int
- class batbot.classifier.Classifier(config: str | ClassifierConfig | None = 'mobilenet', batch_size: int = 10, providers: Sequence[str] | None = None, top_k: int = 5, pull: bool = False, sessions: MutableMapping[str, Any] | None = None, num_workers: int = 1)[source]
Bases:
objectReusable classifier that owns a lazily-created ONNX Runtime session.
- classify(inputs: str | PathLike[str] | Iterable[str | PathLike[str]], top_k: int | None = None, progress: bool | None = None) list[ClassificationResult][source]
Classify one or more spectrogram images.
- classify_bulk(inputs: str | PathLike[str] | Iterable[str | PathLike[str]], input_type: Literal['auto', 'spectrogram', 'wav'] = 'auto', recursive: bool = True, top_k: int | None = None, spectrogram_output: str | PathLike[str] | None = None, preprocess_workers: int = 1, progress: bool = True) BulkClassification[source]
Classify a directory tree using this session.
- classify_wav(filepath: str | PathLike[str], top_k: int | None = None, output_folder: str | PathLike[str] | None = None, out_file_stem: str | PathLike[str] | None = None, keep_spectrograms: bool = False, progress: bool = True) ClassificationResult[source]
Generate spectrograms and classify a WAV using this session.
- property session: Any
Return this classifier’s validated, reusable ONNX session.
- class batbot.classifier.ClassifierConfig(key: str, filename: str, url: str, sha256: str, classes: tuple[str, ...], resource_package: str = 'batbot.classifier', resource_parts: tuple[str, ...] = ('models', 'onnx'))[source]
Bases:
objectImmutable description of an ONNX classifier model.
- classes: tuple[str, ...]
- filename: str
- key: str
- resource_package: str
- resource_parts: tuple[str, ...]
- sha256: str
- url: str
- class batbot.classifier.ImageFilePathList(filepaths: Iterable[str | PathLike[str]], targets: Iterable[Any] | None = None, transform: Callable[[ndarray[tuple[Any, ...], dtype[uint8]]], ndarray[tuple[Any, ...], dtype[uint8]]] | None = None, target_transform: Callable[[Any], Any] | None = None)[source]
Bases:
objectSmall, dependency-free equivalent of Scoutbot’s image path dataset.
- class batbot.classifier.TopPrediction[source]
Bases:
TypedDictOne ranked classifier prediction.
- confidence: float
- label: str
- batbot.classifier.classify(inputs: str | PathLike[str] | Iterable[str | PathLike[str]], batch_size: int = 10, config: str | ClassifierConfig | None = 'mobilenet', providers: Sequence[str] | None = None, top_k: int = 5, sessions: MutableMapping[str, Any] | None = None, num_workers: int = 1, progress: bool | None = None) list[ClassificationResult][source]
Classify spectrograms with a one-shot or externally shared session.
- batbot.classifier.classify_bulk(inputs: str | PathLike[str] | Iterable[str | PathLike[str]], input_type: Literal['auto', 'spectrogram', 'wav'] = 'auto', recursive: bool = True, batch_size: int = 10, config: str | ClassifierConfig | None = 'mobilenet', providers: Sequence[str] | None = None, top_k: int = 5, spectrogram_output: str | PathLike[str] | None = None, num_workers: int = 1, preprocess_workers: int = 1, progress: bool = True, *, _runner: Classifier | None = None) BulkClassification[source]
Preprocess WAVs in bounded batches and reuse one ONNX inference session.
preprocess_workerscontrols separate spectrogram processes, whilenum_workerscontrols inference threads. Progress is written to stderr and can be disabled independently of BatBot’s logging settings.
- batbot.classifier.classify_wav(filepath: str | PathLike[str], batch_size: int = 10, config: str | ClassifierConfig | None = 'mobilenet', providers: Sequence[str] | None = None, top_k: int = 5, output_folder: str | PathLike[str] | None = None, out_file_stem: str | PathLike[str] | None = None, keep_spectrograms: bool = False, sessions: MutableMapping[str, Any] | None = None, num_workers: int = 1, progress: bool = True, *, _runner: Classifier | None = None) ClassificationResult[source]
Generate spectrograms for a WAV file and return one prediction.
- batbot.classifier.discover_inputs(inputs: str | PathLike[str] | Iterable[str | PathLike[str]], input_type: Literal['auto', 'spectrogram', 'wav'] = 'auto', recursive: bool = True) list[str][source]
Resolve files and directories into deterministic classifier inputs.
- batbot.classifier.fetch(pull: bool = False, config: str | ClassifierConfig | None = 'mobilenet') str[source]
Return a verified local model, downloading the mirror when necessary.
- batbot.classifier.post(gen: Iterable[tuple[ndarray[Any, Any], str | ClassifierConfig]]) list[dict[str, float]][source]
Associate raw model scores with labels for each spectrogram.
- batbot.classifier.pre(inputs: str | PathLike[str] | Iterable[str | PathLike[str]], batch_size: int = 10, config: str | ClassifierConfig | None = 'mobilenet') Iterator[tuple[ndarray[Any, Any], str]][source]
Load spectrograms and yield their model-ready sliding windows.
- batbot.classifier.predict(gen: Iterable[tuple[ndarray[Any, Any], str | ClassifierConfig]], batch_size: int = 10, providers: Sequence[str] | None = None, pull: bool = False, sessions: MutableMapping[str, Any] | None = None, total: int | None = None, num_workers: int = 1, progress: bool | None = None) Iterator[tuple[ndarray[Any, Any], str]][source]
Run ordered ONNX inference, optionally across multiple worker threads.
- batbot.classifier.resolve_config(config: str | ClassifierConfig | None = None) ClassifierConfig[source]
Resolve a configuration name or return an existing configuration.
- batbot.classifier.summarize(results: Sequence[ClassificationResult | ClassificationFailure]) ClassificationSummary[source]
Generate species counts and basic confidence statistics.
Image loading and windowing for the BatBot species classifier.
- class batbot.classifier.dataloader.ImageFilePathList(filepaths: Iterable[str | PathLike[str]], targets: Iterable[Any] | None = None, transform: Callable[[ndarray[tuple[Any, ...], dtype[uint8]]], ndarray[tuple[Any, ...], dtype[uint8]]] | None = None, target_transform: Callable[[Any], Any] | None = None)[source]
Bases:
objectSmall, dependency-free equivalent of Scoutbot’s image path dataset.
Pipeline
High-level BatBot processing APIs.
Heavy dependencies are imported inside the functions that use them so that a
plain import batbot remains inexpensive and does not initialize logging or
create files on disk.
- batbot.api.batch(filepaths: Sequence[str | Path], config: str | None = None, clean: bool = True, num_workers: int = 1, *, preprocess_workers: int = 1, progress: bool = True, providers: Sequence[str] | None = None, spectrogram_output: str | Path | None = None) list[ClassificationItem][source]
Preprocess and classify WAV files or directories using one ONNX session.
Results include per-file failures.
cleanremains for API compatibility; usespectrogram_outputto retain generated images.
- batbot.api.fetch(pull: bool = False, config: str | None = None) str[source]
Return the local ONNX classifier model path.
- batbot.api.parallel_pipeline(in_file_chunks: Sequence[Sequence[str]], out_stem_chunks: Sequence[Sequence[str | None]] | None = None, fast_mode: bool = False, force_overwrite: bool = False, num_workers: int = 0, threaded: bool = False, quiet: bool = False, desc: str | None = None) tuple[list[str], list[str], list[str | None], list[tuple[str, Exception]]] | None[source]
Run spectrogram processing chunks concurrently.
- batbot.api.pipeline(filepath: str | Path, out_file_stem: str | None = None, output_folder: str | None = None, fast_mode: bool = False, force_overwrite: bool = False, quiet: bool = False, plot_uncompressed_amplitude: bool = False, include_original_sr: bool = False, time_buffer_ms: float = 1.0, debug: bool = False) tuple[list[str], list[str], str | None][source]
Generate spectrograms and metadata for one WAV file.
- batbot.api.pipeline_multi_wrapper(filepaths: Sequence[str], out_file_stems: Sequence[str | None] | None = None, fast_mode: bool = False, force_overwrite: bool = False, worker_position: int | None = None, quiet: bool = False, tqdm_lock: Any = None) tuple[list[str], list[str], list[str | None], list[tuple[str, Exception]]][source]
Run
pipeline()for a chunk while retaining per-file failures.
Utilities
BatBot utilities file for common and handy functions.