Utilities¶
Preprocessing, annotation parsing, settings schema, evaluation, logging, and CPU-safe unpickling.
| Symbol | File | Role |
|---|---|---|
Preprocessing |
eso/utils/preprocessing.py |
Audio loading, optional filtering, mel-spectrogram generation. |
AnnotationReader |
eso/utils/AnnotationReader.py |
Parse SVL or compatible XML annotation files. |
Config and friends |
eso/utils/settings.py |
Typed configuration schema. One dataclass per section of the JSON. |
Evaluation |
eso/utils/Evaluation.py |
Sliding-window inference, bout reconstruction, comparison metrics. |
plot_chromosome · setup_logger · log_tensorboard |
eso/utils/logger.py |
Visualisation and logging helpers. |
CPU_Unpickler |
eso/utils/unpickler.py |
Unpickle GPU-trained tensors onto CPU. |
eso.utils.preprocessing¶
The audio-to-spectrogram pipeline. The class produces two datasets per species: a preprocessed one (low-pass filtered and downsampled, used to train the baseline) and an unprocessed one (used by ESO). Audio is segmented into fixed-length windows with a one-second overlap. Each segment is converted to a mel-spectrogram with a Hann window and a configurable hop length. Class balancing through time shifting, blending, and additive noise is also handled here.
AnnotationReader
¶
AnnotationReader(
path: str,
annotation_file_name: str,
file_type: str,
audio_extension: str,
positive_class: str,
)
Source code in eso/utils/AnnotationReader.py
positive_class
instance-attribute
¶
Initializes the AnnotationReader class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the directory containing the annotation and audio files. |
required |
annotation_file_name
|
str
|
The name of the annotation file (without extension) to be read. |
required |
file_type
|
str
|
The type of annotation file (e.g., "svl", "xml"). |
required |
audio_extension
|
str
|
The file extension for the associated audio files (e.g., ".wav", ".mp3"). |
required |
positive_class
|
str
|
The label representing the positive class in classification tasks. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
get_annotation_information
¶
Extract annotation information from an .svl XML file and return a DataFrame
with start times, end times, and labels for the annotations.
This method parses an XML annotation file (.svl format) to extract annotation
details including the start time, end time, and label for each annotation.
It processes the XML file, handles any confidence values, and adjusts labels
accordingly (e.g., using the positive class label for predicted annotations).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation_folder
|
str
|
The folder where the annotation file is located. |
required |
sufix_file
|
str
|
The suffix to append to the base annotation file name to get the full file name. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing: - pd.DataFrame: A DataFrame with three columns: - 'Start': The start time of the annotation in seconds. - 'End': The end time of the annotation in seconds. - 'Label': The label associated with the annotation. - str: The name of the corresponding audio file (with ".wav" extension). |
Raises:
| Type | Description |
|---|---|
Exception
|
If the annotation file does not contain valid annotation information. |
Source code in eso/utils/AnnotationReader.py
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 | |
get_annotation_information_testing
¶
Extract annotation information from a .svl XML file and return a DataFrame
with frame, value, duration, extent, and label for each annotation.
This method parses an XML annotation file (.svl format) to extract detailed
annotation information such as frame number, value, duration, extent, and label.
It also extracts the sample rate, start time, and end time from the file's metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
None
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing:
- pd.DataFrame: A DataFrame with columns:
- 'frame': The frame number from the annotation.
- 'value': The value associated with the annotation.
- 'duration': The duration of the annotation.
- 'extent': The extent of the annotation.
- 'label': The label associated with the annotation.
- int: The sample rate extracted from the |
Raises:
| Type | Description |
|---|---|
Exception
|
If the annotation file is not found or if it does not contain valid annotation information. |
Source code in eso/utils/AnnotationReader.py
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
dataframe_to_svl
¶
Convert a DataFrame of annotations to a .svl format XML string.
This method generates a .svl format XML string containing the annotations
from a DataFrame. The generated XML includes metadata such as the sample rate,
start time, end time, and annotation points (frame, value, duration, extent, and label).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataframe
|
DataFrame
|
A DataFrame containing the annotation information. The DataFrame should have the following columns: 'frame', 'value', 'duration', 'extent', and 'label'. |
required |
sample_rate
|
int
|
The sample rate of the audio associated with the annotations. |
required |
start_m
|
str
|
The start time (in seconds) of the annotation period. |
required |
end_m
|
str
|
The end time (in seconds) of the annotation period. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A string containing the XML in |
Notes
The function generates an XML document that includes:
- <model>: metadata about the annotation model, including sample rate, start time, and end time.
- <dataset>: contains <point> elements that represent individual annotations.
- <display>: defines the display settings for the annotation in the software.
Source code in eso/utils/AnnotationReader.py
Preprocessing
¶
Preprocessing(
species_folder: str,
sample_rate: int,
lowpass_cutoff: int,
downsample_rate: int,
nyquist_rate: int,
segment_duration: int,
positive_class: str,
negative_class: str,
nb_negative_class: int,
n_fft: int,
hop_length: int,
n_mels: int,
f_min: int,
f_max: int,
file_type: str,
audio_extension: str,
apply_preprocessing: bool = True,
)
Initialize the Preprocessing object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_folder
|
str
|
Path to the species folder containing audio and annotation data. |
required |
sample_rate
|
int
|
The sample rate for unprocessed audio files. |
required |
lowpass_cutoff
|
int
|
The cutoff frequency for the low-pass filter. |
required |
downsample_rate
|
int
|
The rate at which to downsample the audio. |
required |
nyquist_rate
|
int
|
The Nyquist rate, half of the sampling rate. |
required |
segment_duration
|
int
|
Duration of each audio segment in seconds. |
required |
positive_class
|
str
|
Label representing the positive class in the dataset. |
required |
negative_class
|
str
|
Label representing the negative class in the dataset. |
required |
nb_negative_class
|
int
|
Number of negative class samples. |
required |
n_fft
|
int
|
The length of the FFT window for spectrograms. |
required |
hop_length
|
int
|
The hop length for generating spectrograms. |
required |
n_mels
|
int
|
The number of mel bands to use in the spectrogram. |
required |
f_min
|
int
|
The minimum frequency for the mel filter bank. |
required |
f_max
|
int
|
The maximum frequency for the mel filter bank. |
required |
file_type
|
str
|
The type of annotation files to process (e.g., '.svl'). |
required |
audio_extension
|
str
|
The file extension for the audio files (e.g., '.wav'). |
required |
apply_preprocessing
|
bool
|
Whether to apply preprocessing steps like filtering and downsampling. Default is True. |
True
|
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in eso/utils/preprocessing.py
training_files
instance-attribute
¶
read_audio_file
¶
Load an audio file and return its waveform and sample rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name
|
str
|
Name of the audio file including the extension (e.g., "audio1.wav"). |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing: - np.ndarray: The audio waveform (amplitude values). - int: The sampling rate of the audio file. |
Source code in eso/utils/preprocessing.py
butter_lowpass_filter
¶
Apply a Butterworth low-pass filter to the input signal.
This method filters the input signal using a zero-phase Butterworth low-pass filter designed with the specified cutoff and Nyquist frequencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
The input signal (1D array) to be filtered. |
required |
cutoff_freq
|
float
|
The cutoff frequency of the low-pass filter (in Hz). |
required |
nyq_freq
|
float
|
The Nyquist frequency (typically half the sampling rate). |
required |
order
|
int
|
The order of the Butterworth filter. Default is 4. |
4
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The filtered signal with the same shape as the input. |
Source code in eso/utils/preprocessing.py
downsample_file
¶
Downsample an audio waveform to a specified sample rate.
This function resamples the input audio from the original sample rate to a new, lower sample rate using the 'kaiser_fast' resampling method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amplitudes
|
ndarray
|
The raw audio waveform (1D NumPy array of amplitude values). |
required |
original_sr
|
int
|
The original sampling rate of the audio signal (in Hz). |
required |
new_sample_rate
|
int
|
The desired sampling rate to downsample the audio to (in Hz). |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing:
- np.ndarray: The downsampled audio waveform.
- int: The new sampling rate (same as |
Source code in eso/utils/preprocessing.py
convert_single_to_image
¶
Convert an audio waveform into a normalized mel-spectrogram image.
This function computes the mel-spectrogram from a raw audio signal and applies normalization to scale the spectrogram values between 0 and 1. If preprocessing is enabled, user-defined frequency limits are used; otherwise, default frequency bounds are applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
The raw audio waveform (1D NumPy array of amplitude values). |
required |
sample_rate
|
int
|
The sampling rate of the audio signal (in Hz). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 2D NumPy array representing the normalized mel-spectrogram image. |
Source code in eso/utils/preprocessing.py
save_data_to_pickle
¶
Save the input data and labels to pickle files.
This function saves the spectrogram data (X) and their corresponding
labels (Y) into separate pickle files (X.pkl and Y.pkl) in the directory
specified by self.saved_data_path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
any
|
The data to be saved (e.g., spectrograms). Must be pickle-serializable. |
required |
Y
|
any
|
The corresponding labels for |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in eso/utils/preprocessing.py
load_data_from_pickle
¶
Load the data and labels from pickle files.
This function loads spectrogram data (X) and their corresponding
labels (Y) from pickle files (X.pkl and Y.pkl) located in the directory
specified by self.saved_data_path.
Returns:
| Name | Type | Description |
|---|---|---|
X |
any
|
The loaded data (e.g., spectrograms), as previously saved using |
Y |
any
|
The corresponding labels for |
Source code in eso/utils/preprocessing.py
create_dataset
¶
Create the dataset of audio segments and labels for machine learning.
This function reads audio files and their corresponding annotation files, applies preprocessing (optional low-pass filtering and downsampling), extracts labeled audio segments, and optionally augments the data to balance class distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation_folder
|
str or Path
|
Path to the folder containing the |
required |
sufix_file
|
str
|
Suffix to append to the annotation filenames for retrieval. |
required |
file_names
|
str or Path
|
Path to a CSV file containing a list of filenames to process (without extensions).
If None, uses |
None
|
augmentation
|
bool
|
Whether to perform data augmentation to balance the dataset. |
False
|
Returns:
| Type | Description |
|---|---|
tuple of np.ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the |
Notes
- Annotations are expected in
.svlformat, created with Sonic Visualiser, using the "boxes area" annotation layer. - Each annotation provides a labeled time segment which is then transformed into a training example.
- Augmentation methods include time shifting, noise addition, and mixing with negative samples to improve dataset balance.
Source code in eso/utils/preprocessing.py
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 | |
shuffle_files_names
¶
Shuffle audio file names and split them into training, testing, and validation sets.
This method scans the Audio folder inside the species directory for all
files with the specified audio extension. It then randomly shuffles and splits
the file names into training, testing, and validation sets according to the
specified proportions. The resulting file names (without extensions) are saved
as text files (train.txt, test.txt, validation.txt) inside the DataFiles
subdirectory of the species folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_size
|
float
|
Proportion of files to use for training. Default is 0.8. |
0.8
|
test_size
|
float
|
Proportion of files to use for testing. Default is 0.1. |
0.1
|
validation_size
|
float
|
Proportion of files to use for validation. Default is 0.1. |
0.1
|
Raises:
| Type | Description |
|---|---|
Exception
|
If no audio files are found in the specified audio directory. |
Notes
- The sum of
train_size,test_size, andvalidation_sizeshould be 1.0. - Output files are saved as plain text, with one file name (without extension) per line.
- The audio extension is read from
self.audio_extension, and the species folder fromself.species_folder.
Source code in eso/utils/preprocessing.py
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 | |
eso.utils.AnnotationReader¶
Parses Sonic Visualiser SVL files and equivalent XML annotation formats into a DataFrame of (filename, start_time, end_time, label) rows. The output is consumed by Preprocessing to mark presence and absence segments for training.
AnnotationReader
¶
AnnotationReader(
path: str,
annotation_file_name: str,
file_type: str,
audio_extension: str,
positive_class: str,
)
Source code in eso/utils/AnnotationReader.py
positive_class
instance-attribute
¶
Initializes the AnnotationReader class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the directory containing the annotation and audio files. |
required |
annotation_file_name
|
str
|
The name of the annotation file (without extension) to be read. |
required |
file_type
|
str
|
The type of annotation file (e.g., "svl", "xml"). |
required |
audio_extension
|
str
|
The file extension for the associated audio files (e.g., ".wav", ".mp3"). |
required |
positive_class
|
str
|
The label representing the positive class in classification tasks. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
get_annotation_information
¶
Extract annotation information from an .svl XML file and return a DataFrame
with start times, end times, and labels for the annotations.
This method parses an XML annotation file (.svl format) to extract annotation
details including the start time, end time, and label for each annotation.
It processes the XML file, handles any confidence values, and adjusts labels
accordingly (e.g., using the positive class label for predicted annotations).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation_folder
|
str
|
The folder where the annotation file is located. |
required |
sufix_file
|
str
|
The suffix to append to the base annotation file name to get the full file name. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing: - pd.DataFrame: A DataFrame with three columns: - 'Start': The start time of the annotation in seconds. - 'End': The end time of the annotation in seconds. - 'Label': The label associated with the annotation. - str: The name of the corresponding audio file (with ".wav" extension). |
Raises:
| Type | Description |
|---|---|
Exception
|
If the annotation file does not contain valid annotation information. |
Source code in eso/utils/AnnotationReader.py
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 | |
get_annotation_information_testing
¶
Extract annotation information from a .svl XML file and return a DataFrame
with frame, value, duration, extent, and label for each annotation.
This method parses an XML annotation file (.svl format) to extract detailed
annotation information such as frame number, value, duration, extent, and label.
It also extracts the sample rate, start time, and end time from the file's metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
None
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing:
- pd.DataFrame: A DataFrame with columns:
- 'frame': The frame number from the annotation.
- 'value': The value associated with the annotation.
- 'duration': The duration of the annotation.
- 'extent': The extent of the annotation.
- 'label': The label associated with the annotation.
- int: The sample rate extracted from the |
Raises:
| Type | Description |
|---|---|
Exception
|
If the annotation file is not found or if it does not contain valid annotation information. |
Source code in eso/utils/AnnotationReader.py
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
dataframe_to_svl
¶
Convert a DataFrame of annotations to a .svl format XML string.
This method generates a .svl format XML string containing the annotations
from a DataFrame. The generated XML includes metadata such as the sample rate,
start time, end time, and annotation points (frame, value, duration, extent, and label).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataframe
|
DataFrame
|
A DataFrame containing the annotation information. The DataFrame should have the following columns: 'frame', 'value', 'duration', 'extent', and 'label'. |
required |
sample_rate
|
int
|
The sample rate of the audio associated with the annotations. |
required |
start_m
|
str
|
The start time (in seconds) of the annotation period. |
required |
end_m
|
str
|
The end time (in seconds) of the annotation period. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A string containing the XML in |
Notes
The function generates an XML document that includes:
- <model>: metadata about the annotation model, including sample rate, start time, and end time.
- <dataset>: contains <point> elements that represent individual annotations.
- <display>: defines the display settings for the annotation in the software.
Source code in eso/utils/AnnotationReader.py
eso.utils.settings¶
The typed configuration schema. The JSON passed to ESO(settings_path=...) is validated against these dataclasses. Each top-level section of the file maps to one class. Unknown fields raise a ValueError at load time.
For a narrative walk-through of every field with recommended values from the paper, see Configuration.
BaseConfig
dataclass
¶
AlgorithmConfig
dataclass
¶
Bases: BaseConfig
GeneticOperatorConfig
dataclass
¶
GeneticOperatorConfig(
mutation_rate: float = 0.1,
crossover_rate: float = 0.8,
reproduction_rate: float = 0.1,
mutation_height_range: int = 5,
mutation_position_range: int = 20,
)
Bases: BaseConfig
SelectionOperatorConfig
dataclass
¶
Bases: BaseConfig
DataConfig
dataclass
¶
DataConfig(
force_recreate_dataset: bool = False,
keep_in_memory: bool = False,
species_folder: str = "",
train_size: float = 0.8,
test_size: float = 0.2,
reshuffle: bool = False,
positive_class: str = "",
negative_class: str = "",
)
Bases: BaseConfig
PreprocessingConfig
dataclass
¶
PreprocessingConfig(
sample_rate: int = 32000,
lowpass_cutoff: int = 2000,
downsample_rate: int = 4800,
nyquist_rate: int = 2400,
segment_duration: int = 4,
nb_negative_class: int = 20,
file_type: str = "svl",
audio_extension: str = ".wav",
n_fft: int = 1024,
hop_length: int = 256,
n_mels: int = 128,
f_min: int = 4000,
f_max: int = 9000,
)
Bases: BaseConfig
PopulationConfig
dataclass
¶
Bases: BaseConfig
GeneConfig
dataclass
¶
GeneConfig(
min_position: int = 0,
max_position: int = -1,
min_height: int = 4,
max_height: int = 16,
band_position: int = None,
band_height: int = None,
spec_height: int = None,
minimum_gene_height: int = None,
)
Bases: BaseConfig
ChromosomeConfig
dataclass
¶
ChromosomeConfig(
num_genes: int = None,
min_num_genes: int = 3,
max_num_genes: int = 10,
lambda_1: float = 0.5,
lambda_2: float = 0.5,
stack: bool = False,
baseline_parameters: float = None,
baseline_metric: int = None,
)
Bases: BaseConfig
ModelConfig
dataclass
¶
ModelConfig(
optimizer_name: str = "adam",
loss_function_name: str = "cross_entropy",
num_epochs: int = 1,
batch_size: int = 128,
learning_rate: float = 0.001,
shuffle: bool = True,
metric: str = "f1",
)
Bases: BaseConfig
ArchitectureConfig
dataclass
¶
ArchitectureConfig(
conv_layers: int = 1,
conv_filters: int = 8,
dropout_rate: float = 0.5,
conv_kernel: int = 8,
max_pooling_size: int = 4,
fc_units: int = 32,
fc_layers: int = 2,
conv_padding: str = None,
stride_maxpool: int = None,
)
Bases: BaseConfig
Config
dataclass
¶
Config(
_input: str = None,
algorithm: AlgorithmConfig = AlgorithmConfig(),
genetic_operator: GeneticOperatorConfig = GeneticOperatorConfig(),
selection_operator: SelectionOperatorConfig = SelectionOperatorConfig(),
data: DataConfig = DataConfig(),
preprocessing: PreprocessingConfig = PreprocessingConfig(),
population: PopulationConfig = PopulationConfig(),
gene: GeneConfig = GeneConfig(),
chromosome: ChromosomeConfig = ChromosomeConfig(),
model: ModelConfig = ModelConfig(),
cnn_architecture: ArchitectureConfig = ArchitectureConfig(),
)
Bases: BaseConfig
algorithm
class-attribute
instance-attribute
¶
algorithm: AlgorithmConfig = field(default_factory=AlgorithmConfig)
genetic_operator
class-attribute
instance-attribute
¶
genetic_operator: GeneticOperatorConfig = field(default_factory=GeneticOperatorConfig)
selection_operator
class-attribute
instance-attribute
¶
selection_operator: SelectionOperatorConfig = field(
default_factory=SelectionOperatorConfig
)
preprocessing
class-attribute
instance-attribute
¶
preprocessing: PreprocessingConfig = field(default_factory=PreprocessingConfig)
population
class-attribute
instance-attribute
¶
population: PopulationConfig = field(default_factory=PopulationConfig)
chromosome
class-attribute
instance-attribute
¶
chromosome: ChromosomeConfig = field(default_factory=ChromosomeConfig)
cnn_architecture
class-attribute
instance-attribute
¶
cnn_architecture: ArchitectureConfig = field(default_factory=ArchitectureConfig)
get_params
¶
eso.utils.Evaluation¶
Reproduces the evaluation protocol described in the paper. The class slides a window over each test audio file, applies the model (baseline or ESO chromosome) per window, groups consecutive positive predictions into calling bouts, and computes true positives, false positives, false negatives, and true negatives using a 25 percent overlap rule (10 percent for the Thyolo Alethe dataset). It also measures FLOPs via fvcore, RAM usage via psutil, and energy via CodeCarbon.
Preprocessing
¶
Preprocessing(
species_folder: str,
sample_rate: int,
lowpass_cutoff: int,
downsample_rate: int,
nyquist_rate: int,
segment_duration: int,
positive_class: str,
negative_class: str,
nb_negative_class: int,
n_fft: int,
hop_length: int,
n_mels: int,
f_min: int,
f_max: int,
file_type: str,
audio_extension: str,
apply_preprocessing: bool = True,
)
Initialize the Preprocessing object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_folder
|
str
|
Path to the species folder containing audio and annotation data. |
required |
sample_rate
|
int
|
The sample rate for unprocessed audio files. |
required |
lowpass_cutoff
|
int
|
The cutoff frequency for the low-pass filter. |
required |
downsample_rate
|
int
|
The rate at which to downsample the audio. |
required |
nyquist_rate
|
int
|
The Nyquist rate, half of the sampling rate. |
required |
segment_duration
|
int
|
Duration of each audio segment in seconds. |
required |
positive_class
|
str
|
Label representing the positive class in the dataset. |
required |
negative_class
|
str
|
Label representing the negative class in the dataset. |
required |
nb_negative_class
|
int
|
Number of negative class samples. |
required |
n_fft
|
int
|
The length of the FFT window for spectrograms. |
required |
hop_length
|
int
|
The hop length for generating spectrograms. |
required |
n_mels
|
int
|
The number of mel bands to use in the spectrogram. |
required |
f_min
|
int
|
The minimum frequency for the mel filter bank. |
required |
f_max
|
int
|
The maximum frequency for the mel filter bank. |
required |
file_type
|
str
|
The type of annotation files to process (e.g., '.svl'). |
required |
audio_extension
|
str
|
The file extension for the audio files (e.g., '.wav'). |
required |
apply_preprocessing
|
bool
|
Whether to apply preprocessing steps like filtering and downsampling. Default is True. |
True
|
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in eso/utils/preprocessing.py
training_files
instance-attribute
¶
read_audio_file
¶
Load an audio file and return its waveform and sample rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name
|
str
|
Name of the audio file including the extension (e.g., "audio1.wav"). |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing: - np.ndarray: The audio waveform (amplitude values). - int: The sampling rate of the audio file. |
Source code in eso/utils/preprocessing.py
butter_lowpass_filter
¶
Apply a Butterworth low-pass filter to the input signal.
This method filters the input signal using a zero-phase Butterworth low-pass filter designed with the specified cutoff and Nyquist frequencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
The input signal (1D array) to be filtered. |
required |
cutoff_freq
|
float
|
The cutoff frequency of the low-pass filter (in Hz). |
required |
nyq_freq
|
float
|
The Nyquist frequency (typically half the sampling rate). |
required |
order
|
int
|
The order of the Butterworth filter. Default is 4. |
4
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The filtered signal with the same shape as the input. |
Source code in eso/utils/preprocessing.py
downsample_file
¶
Downsample an audio waveform to a specified sample rate.
This function resamples the input audio from the original sample rate to a new, lower sample rate using the 'kaiser_fast' resampling method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amplitudes
|
ndarray
|
The raw audio waveform (1D NumPy array of amplitude values). |
required |
original_sr
|
int
|
The original sampling rate of the audio signal (in Hz). |
required |
new_sample_rate
|
int
|
The desired sampling rate to downsample the audio to (in Hz). |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing:
- np.ndarray: The downsampled audio waveform.
- int: The new sampling rate (same as |
Source code in eso/utils/preprocessing.py
convert_single_to_image
¶
Convert an audio waveform into a normalized mel-spectrogram image.
This function computes the mel-spectrogram from a raw audio signal and applies normalization to scale the spectrogram values between 0 and 1. If preprocessing is enabled, user-defined frequency limits are used; otherwise, default frequency bounds are applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
The raw audio waveform (1D NumPy array of amplitude values). |
required |
sample_rate
|
int
|
The sampling rate of the audio signal (in Hz). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 2D NumPy array representing the normalized mel-spectrogram image. |
Source code in eso/utils/preprocessing.py
save_data_to_pickle
¶
Save the input data and labels to pickle files.
This function saves the spectrogram data (X) and their corresponding
labels (Y) into separate pickle files (X.pkl and Y.pkl) in the directory
specified by self.saved_data_path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
any
|
The data to be saved (e.g., spectrograms). Must be pickle-serializable. |
required |
Y
|
any
|
The corresponding labels for |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in eso/utils/preprocessing.py
load_data_from_pickle
¶
Load the data and labels from pickle files.
This function loads spectrogram data (X) and their corresponding
labels (Y) from pickle files (X.pkl and Y.pkl) located in the directory
specified by self.saved_data_path.
Returns:
| Name | Type | Description |
|---|---|---|
X |
any
|
The loaded data (e.g., spectrograms), as previously saved using |
Y |
any
|
The corresponding labels for |
Source code in eso/utils/preprocessing.py
create_dataset
¶
Create the dataset of audio segments and labels for machine learning.
This function reads audio files and their corresponding annotation files, applies preprocessing (optional low-pass filtering and downsampling), extracts labeled audio segments, and optionally augments the data to balance class distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation_folder
|
str or Path
|
Path to the folder containing the |
required |
sufix_file
|
str
|
Suffix to append to the annotation filenames for retrieval. |
required |
file_names
|
str or Path
|
Path to a CSV file containing a list of filenames to process (without extensions).
If None, uses |
None
|
augmentation
|
bool
|
Whether to perform data augmentation to balance the dataset. |
False
|
Returns:
| Type | Description |
|---|---|
tuple of np.ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the |
Notes
- Annotations are expected in
.svlformat, created with Sonic Visualiser, using the "boxes area" annotation layer. - Each annotation provides a labeled time segment which is then transformed into a training example.
- Augmentation methods include time shifting, noise addition, and mixing with negative samples to improve dataset balance.
Source code in eso/utils/preprocessing.py
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 | |
shuffle_files_names
¶
Shuffle audio file names and split them into training, testing, and validation sets.
This method scans the Audio folder inside the species directory for all
files with the specified audio extension. It then randomly shuffles and splits
the file names into training, testing, and validation sets according to the
specified proportions. The resulting file names (without extensions) are saved
as text files (train.txt, test.txt, validation.txt) inside the DataFiles
subdirectory of the species folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_size
|
float
|
Proportion of files to use for training. Default is 0.8. |
0.8
|
test_size
|
float
|
Proportion of files to use for testing. Default is 0.1. |
0.1
|
validation_size
|
float
|
Proportion of files to use for validation. Default is 0.1. |
0.1
|
Raises:
| Type | Description |
|---|---|
Exception
|
If no audio files are found in the specified audio directory. |
Notes
- The sum of
train_size,test_size, andvalidation_sizeshould be 1.0. - Output files are saved as plain text, with one file name (without extension) per line.
- The audio extension is read from
self.audio_extension, and the species folder fromself.species_folder.
Source code in eso/utils/preprocessing.py
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 | |
AnnotationReader
¶
AnnotationReader(
path: str,
annotation_file_name: str,
file_type: str,
audio_extension: str,
positive_class: str,
)
Source code in eso/utils/AnnotationReader.py
positive_class
instance-attribute
¶
Initializes the AnnotationReader class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the directory containing the annotation and audio files. |
required |
annotation_file_name
|
str
|
The name of the annotation file (without extension) to be read. |
required |
file_type
|
str
|
The type of annotation file (e.g., "svl", "xml"). |
required |
audio_extension
|
str
|
The file extension for the associated audio files (e.g., ".wav", ".mp3"). |
required |
positive_class
|
str
|
The label representing the positive class in classification tasks. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
get_annotation_information
¶
Extract annotation information from an .svl XML file and return a DataFrame
with start times, end times, and labels for the annotations.
This method parses an XML annotation file (.svl format) to extract annotation
details including the start time, end time, and label for each annotation.
It processes the XML file, handles any confidence values, and adjusts labels
accordingly (e.g., using the positive class label for predicted annotations).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation_folder
|
str
|
The folder where the annotation file is located. |
required |
sufix_file
|
str
|
The suffix to append to the base annotation file name to get the full file name. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing: - pd.DataFrame: A DataFrame with three columns: - 'Start': The start time of the annotation in seconds. - 'End': The end time of the annotation in seconds. - 'Label': The label associated with the annotation. - str: The name of the corresponding audio file (with ".wav" extension). |
Raises:
| Type | Description |
|---|---|
Exception
|
If the annotation file does not contain valid annotation information. |
Source code in eso/utils/AnnotationReader.py
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 | |
get_annotation_information_testing
¶
Extract annotation information from a .svl XML file and return a DataFrame
with frame, value, duration, extent, and label for each annotation.
This method parses an XML annotation file (.svl format) to extract detailed
annotation information such as frame number, value, duration, extent, and label.
It also extracts the sample rate, start time, and end time from the file's metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
None
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing:
- pd.DataFrame: A DataFrame with columns:
- 'frame': The frame number from the annotation.
- 'value': The value associated with the annotation.
- 'duration': The duration of the annotation.
- 'extent': The extent of the annotation.
- 'label': The label associated with the annotation.
- int: The sample rate extracted from the |
Raises:
| Type | Description |
|---|---|
Exception
|
If the annotation file is not found or if it does not contain valid annotation information. |
Source code in eso/utils/AnnotationReader.py
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
dataframe_to_svl
¶
Convert a DataFrame of annotations to a .svl format XML string.
This method generates a .svl format XML string containing the annotations
from a DataFrame. The generated XML includes metadata such as the sample rate,
start time, end time, and annotation points (frame, value, duration, extent, and label).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataframe
|
DataFrame
|
A DataFrame containing the annotation information. The DataFrame should have the following columns: 'frame', 'value', 'duration', 'extent', and 'label'. |
required |
sample_rate
|
int
|
The sample rate of the audio associated with the annotations. |
required |
start_m
|
str
|
The start time (in seconds) of the annotation period. |
required |
end_m
|
str
|
The end time (in seconds) of the annotation period. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A string containing the XML in |
Notes
The function generates an XML document that includes:
- <model>: metadata about the annotation model, including sample rate, start time, and end time.
- <dataset>: contains <point> elements that represent individual annotations.
- <display>: defines the display settings for the annotation in the software.
Source code in eso/utils/AnnotationReader.py
Evaluation
¶
Evaluation(
species_folder: str,
settings,
overlap=0.25,
nb_to_group=2,
threshold=0.8,
chromosome=None,
apply_preprocessing: bool = True,
force_calc_spectrograms: bool = False,
logger=None,
log_path=None,
log_level=0,
save_folder: str = "Predictions",
)
Source code in eso/utils/Evaluation.py
logger
instance-attribute
¶
logger = setup_logger(logger=logger, log_path=log_path, log_level=log_level)
saved_data_folder
instance-attribute
¶
save_folder_spectrograms
instance-attribute
¶
save_spectrograms_path
instance-attribute
¶
prep
instance-attribute
¶
prep = Preprocessing(
**(dict()),
positive_class=positive_class,
negative_class=negative_class,
apply_preprocessing=apply_preprocessing_flag,
species_folder=species_folder
)
prediction_files
¶
Source code in eso/utils/Evaluation.py
comparison_predictions_annotations
¶
Source code in eso/utils/Evaluation.py
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 | |
testing_score
¶
Source code in eso/utils/Evaluation.py
run
¶
plot_chromosome
¶
plot_chromosome(
chromosome, image_height, title, results_path=None, name="current_best_chromosome"
)
Source code in eso/utils/logger.py
log_tensorboard
¶
log_tensorboard(
best_chromosome,
epoch,
writer,
tensorboard_log_dir,
image_height,
metric_name,
results_path=None,
)
Source code in eso/utils/logger.py
setup_tensorboard
¶
Source code in eso/utils/logger.py
setup_logger
¶
Source code in eso/utils/logger.py
eso.utils.logger¶
Visualisation and logging. plot_chromosome renders the selected bands on top of a representative spectrogram, in the style of Figure 4 in the paper. setup_logger configures Python's standard logging to write to both a file and the console. setup_tensorboard and log_tensorboard push generation-level fitness scalars and the best chromosome's band layout to TensorBoard.
plot_chromosome
¶
plot_chromosome(
chromosome, image_height, title, results_path=None, name="current_best_chromosome"
)
Source code in eso/utils/logger.py
log_tensorboard
¶
log_tensorboard(
best_chromosome,
epoch,
writer,
tensorboard_log_dir,
image_height,
metric_name,
results_path=None,
)
Source code in eso/utils/logger.py
setup_tensorboard
¶
Source code in eso/utils/logger.py
setup_logger
¶
Source code in eso/utils/logger.py
eso.utils.unpickler¶
CPU_Unpickler is a pickle.Unpickler subclass that redirects GPU-tensor loads to CPU. Use it when loading a chromosome saved on a CUDA host onto a CPU-only machine for inspection or inference.