simulok 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- simulok-0.1.0/LICENSE +22 -0
- simulok-0.1.0/PKG-INFO +17 -0
- simulok-0.1.0/README.md +86 -0
- simulok-0.1.0/pyproject.toml +29 -0
- simulok-0.1.0/setup.cfg +4 -0
- simulok-0.1.0/src/simulok/__init__.py +0 -0
- simulok-0.1.0/src/simulok/audio_extraction.py +307 -0
- simulok-0.1.0/src/simulok/audio_preparation.py +476 -0
- simulok-0.1.0/src/simulok/call.py +140 -0
- simulok-0.1.0/src/simulok/call_catalog.py +642 -0
- simulok-0.1.0/src/simulok/catalog_builder.py +142 -0
- simulok-0.1.0/src/simulok/events.py +208 -0
- simulok-0.1.0/src/simulok/geometry.py +352 -0
- simulok-0.1.0/src/simulok/noise.py +117 -0
- simulok-0.1.0/src/simulok/propagation.py +163 -0
- simulok-0.1.0/src/simulok/scenario.py +272 -0
- simulok-0.1.0/src/simulok/simulation.py +338 -0
- simulok-0.1.0/src/simulok/source_positions.py +185 -0
- simulok-0.1.0/src/simulok/sources.py +67 -0
- simulok-0.1.0/src/simulok/visualization.py +262 -0
- simulok-0.1.0/src/simulok.egg-info/PKG-INFO +17 -0
- simulok-0.1.0/src/simulok.egg-info/SOURCES.txt +42 -0
- simulok-0.1.0/src/simulok.egg-info/dependency_links.txt +1 -0
- simulok-0.1.0/src/simulok.egg-info/requires.txt +8 -0
- simulok-0.1.0/src/simulok.egg-info/top_level.txt +1 -0
- simulok-0.1.0/tests/test_audio_extraction.py +330 -0
- simulok-0.1.0/tests/test_audio_preparation.py +641 -0
- simulok-0.1.0/tests/test_call.py +450 -0
- simulok-0.1.0/tests/test_call_catalog.py +320 -0
- simulok-0.1.0/tests/test_catalog_builder.py +211 -0
- simulok-0.1.0/tests/test_catalog_contract_v1.py +512 -0
- simulok-0.1.0/tests/test_catalog_descriptive_filenames.py +101 -0
- simulok-0.1.0/tests/test_catalog_integrity.py +76 -0
- simulok-0.1.0/tests/test_events.py +256 -0
- simulok-0.1.0/tests/test_geometry.py +317 -0
- simulok-0.1.0/tests/test_noise.py +162 -0
- simulok-0.1.0/tests/test_persistent_audio_preparation.py +462 -0
- simulok-0.1.0/tests/test_prepared_catalog_independence.py +63 -0
- simulok-0.1.0/tests/test_propagation.py +173 -0
- simulok-0.1.0/tests/test_recorder_config.py +144 -0
- simulok-0.1.0/tests/test_scenario.py +215 -0
- simulok-0.1.0/tests/test_simulation.py +209 -0
- simulok-0.1.0/tests/test_source_positions.py +157 -0
- simulok-0.1.0/tests/test_sources.py +97 -0
simulok-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Universidad de Antioquia
|
|
4
|
+
Author: Jonathan Gallego Londoño
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
simulok-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simulok
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A reproducible synthetic acoustic recording generator
|
|
5
|
+
Author: Jonathan Gallego Londoño
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/jongalon/simulok
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: numpy<3,>=2
|
|
11
|
+
Requires-Dist: soundfile<0.15,>=0.14
|
|
12
|
+
Requires-Dist: scipy<1.17,>=1.16
|
|
13
|
+
Requires-Dist: matplotlib
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest<10,>=9; extra == "dev"
|
|
16
|
+
Requires-Dist: ipykernel; extra == "dev"
|
|
17
|
+
Dynamic: license-file
|
simulok-0.1.0/README.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# Simulok
|
|
2
|
+
|
|
3
|
+
**Simulok** is a Python package for generating reproducible synthetic acoustic recordings for scientific research. It connects audio preparation, scenario configuration, and simulation so researchers can generate recordings under controlled acoustic conditions. Source localization and benchmark development are separate workflows.
|
|
4
|
+
|
|
5
|
+
## Development status
|
|
6
|
+
|
|
7
|
+
Simulok is under active development. Version `0.1.0` is planned as the first release.
|
|
8
|
+
|
|
9
|
+
- Extract vocalizations from audio using Raven selection tables. Use `Call` to represent one vocalization and `CallCatalog` to store a portable collection with metadata and annotations.
|
|
10
|
+
- Use `prepare_catalog()` to resample and normalize the vocalizations and save a reusable catalog of mono audio.
|
|
11
|
+
- Configure recorder arrays, sources, and stationary events in two-dimensional scenarios. Save scenarios and set propagation or noise overrides for individual events.
|
|
12
|
+
- Simulate individual events or full scenarios. Export synchronized floating-point WAV files for each recorder, event metadata as JSON, and a recording index as CSV for a full scenario export.
|
|
13
|
+
|
|
14
|
+
The current model uses stationary sources and recorders at equal heights, free-field propagation with integer-sample delays, and optional seeded white Gaussian noise. Moving sources, continuous event mixing, reverberation, and input denoising are outside this release scope. See the [model assumptions and limits](docs/QUICKSTART.md#model-assumptions-and-reproducibility).
|
|
15
|
+
|
|
16
|
+
## Installation from source
|
|
17
|
+
|
|
18
|
+
Simulok requires Python 3.11 or later. The commands below use Git and Conda. While the repository is private, authenticate to GitHub with an account that has access before cloning.
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
git clone https://github.com/jongalon/simulok.git
|
|
22
|
+
cd simulok
|
|
23
|
+
conda create --name simulok python=3.11
|
|
24
|
+
conda activate simulok
|
|
25
|
+
python -m pip install -e .
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The editable installation lets you import Simulok from the Conda environment while working on the checkout. Check the installation and the installed version with the following command.
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
python -c "import simulok; from importlib.metadata import version; print(version('simulok'))"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
For the test runner and notebook kernel support, install the `dev` extra from the checkout root.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
python -m pip install -e ".[dev]"
|
|
38
|
+
python -m pytest
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Run an example
|
|
42
|
+
|
|
43
|
+
Follow the [quickstart](docs/QUICKSTART.md) to generate a tone, prepare a catalog, and export a complete simulation using Python. It creates its own input audio.
|
|
44
|
+
|
|
45
|
+
Open the notebooks with the `simulok` environment as the Python kernel. Start with [E01 — Free-field propagation](notebooks/E01_free_field_compact.ipynb), which generates a synthetic chirp and runs a clean simulation. Then run [E02 — Ambient noise](notebooks/E02_ambient_noise_validation.ipynb), which uses the outputs of E01 as its reference.
|
|
46
|
+
|
|
47
|
+
For a real-audio workflow, see [audio extraction](notebooks/audio_extraction.ipynb), [catalog building](notebooks/build_real_call_catalog.ipynb), and [catalog preparation](notebooks/build_real_calls_v2.ipynb). These notebooks expect local input audio or catalogs for their re-execution. A fresh clone includes the data attribution records. Input audio, local catalogs, and generated recordings are stored outside Git.
|
|
48
|
+
|
|
49
|
+
## User guides
|
|
50
|
+
|
|
51
|
+
- [Vocalizations and catalogs](docs/CALL_CATALOG.md) for Raven extraction, audio preparation, portability, and SHA-256 verification.
|
|
52
|
+
- [Scenarios and results](docs/QUICKSTART.md#read-the-results) for export, interpretation, and adapting the quickstart.
|
|
53
|
+
|
|
54
|
+
## Repository layout
|
|
55
|
+
|
|
56
|
+
- `src/simulok/` — Python package source.
|
|
57
|
+
- `tests/` — Automated tests.
|
|
58
|
+
- `notebooks/` — Examples and validation experiments.
|
|
59
|
+
- `docs/` — Technical references, including [Call](docs/CALL.md) and [CallCatalog](docs/CALL_CATALOG.md).
|
|
60
|
+
- `simulok_data/` — Local input data and catalogs, alongside the tracked attribution records.
|
|
61
|
+
- `outputs/` — Generated experiment and simulation files.
|
|
62
|
+
|
|
63
|
+
## Versioning and releases
|
|
64
|
+
|
|
65
|
+
- [Versioning policy](VERSIONING.md)
|
|
66
|
+
- [Release management guide](docs/RELEASE_GUIDE.md)
|
|
67
|
+
- [Versioning decision matrix](docs/VERSIONING_MATRIX.md)
|
|
68
|
+
- [Changelog](CHANGELOG.md)
|
|
69
|
+
|
|
70
|
+
## Report a problem
|
|
71
|
+
|
|
72
|
+
Open a [GitHub issue](https://github.com/jongalon/simulok/issues) with the Simulok and Python versions, your operating system, and the steps and error message. Use a small synthetic input when possible and remove private paths and restricted recordings.
|
|
73
|
+
|
|
74
|
+
## Citation
|
|
75
|
+
|
|
76
|
+
Simulok was developed by **Jonathan Gallego Londoño** at the **Universidad de Antioquia**, which holds the copyright in the project's own software and documentation. Cite the software using [CITATION.cff](CITATION.cff). For development runs, also record the exact commit and computing environment in your experiment records.
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
Simulok's source code, original documentation, and notebook code are licensed under the [MIT License](LICENSE). External dependencies retain their own licenses. See the [third-party notices](THIRD_PARTY_NOTICES.md).
|
|
81
|
+
|
|
82
|
+
Third-party recordings and datasets retain their original licenses. The five Xeno-canto source recordings and the Simulok excerpts and adaptations derived from them are governed by [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/). See the [recording attribution and changes](simulok_data/DATA_LICENSES.csv), [notebook media notices](notebooks/README.md), and [historical data notices](HISTORICAL_DATA_NOTICES.md).
|
|
83
|
+
|
|
84
|
+
Fully artificial datasets released by the Simulok project are offered under [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/) to the extent that applicable rights exist. A dataset containing material from different sources may have separate terms for each component.
|
|
85
|
+
|
|
86
|
+
The MIT License does not automatically apply to recordings or datasets generated using Simulok. Users are responsible for ensuring that they have the necessary rights and permissions to use, modify, and distribute their input materials and resulting datasets.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "simulok"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A reproducible synthetic acoustic recording generator"
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
authors = [{name = "Jonathan Gallego Londoño"}]
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = [
|
|
14
|
+
"numpy>=2,<3",
|
|
15
|
+
"soundfile>=0.14,<0.15",
|
|
16
|
+
"scipy>=1.16,<1.17",
|
|
17
|
+
"matplotlib",
|
|
18
|
+
]
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
dev = [
|
|
21
|
+
"pytest>=9,<10",
|
|
22
|
+
"ipykernel",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Repository = "https://github.com/jongalon/simulok"
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
simulok-0.1.0/setup.cfg
ADDED
|
File without changes
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
|
|
2
|
+
"""Utilities for extracting audio segments from annotated recordings."""
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import csv
|
|
6
|
+
import math
|
|
7
|
+
import soundfile as sf
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def select_channel(audio: np.ndarray, channel: int = 0) -> np.ndarray:
|
|
12
|
+
"""Select one channel from a mono or multichannel audio signal.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
audio : numpy.ndarray
|
|
17
|
+
Audio samples with shape (samples,) or (samples, channels).
|
|
18
|
+
channel : int, default 0
|
|
19
|
+
Zero-based channel index.
|
|
20
|
+
|
|
21
|
+
Returns
|
|
22
|
+
-------
|
|
23
|
+
numpy.ndarray
|
|
24
|
+
One-dimensional array containing the selected channel.
|
|
25
|
+
|
|
26
|
+
Raises
|
|
27
|
+
------
|
|
28
|
+
TypeError
|
|
29
|
+
If the channel index is not an integer.
|
|
30
|
+
ValueError
|
|
31
|
+
If the audio shape is invalid.
|
|
32
|
+
IndexError
|
|
33
|
+
If the channel index is out of range.
|
|
34
|
+
"""
|
|
35
|
+
if not isinstance(channel, (int, np.integer)) or isinstance(channel, (bool, np.bool_)):
|
|
36
|
+
raise TypeError("channel must be an integer")
|
|
37
|
+
|
|
38
|
+
if audio.ndim not in (1, 2):
|
|
39
|
+
raise ValueError("audio must be a 1D or 2D array")
|
|
40
|
+
|
|
41
|
+
if audio.size == 0:
|
|
42
|
+
raise ValueError("audio cannot be empty")
|
|
43
|
+
|
|
44
|
+
if audio.ndim == 1:
|
|
45
|
+
if channel != 0:
|
|
46
|
+
raise IndexError("mono audio only has channel 0")
|
|
47
|
+
return audio
|
|
48
|
+
|
|
49
|
+
if channel < 0 or channel >= audio.shape[1]:
|
|
50
|
+
raise IndexError("channel index is out of range")
|
|
51
|
+
|
|
52
|
+
return audio[:, channel]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def load_raven_selections(file_path: str | Path) -> list[dict]:
|
|
56
|
+
"""Load time intervals from a Raven selection table.
|
|
57
|
+
|
|
58
|
+
Parameters
|
|
59
|
+
----------
|
|
60
|
+
file_path : str or pathlib.Path
|
|
61
|
+
Path to a tab-delimited Raven selection table.
|
|
62
|
+
|
|
63
|
+
Returns
|
|
64
|
+
-------
|
|
65
|
+
list of dict
|
|
66
|
+
Selection identifiers and start/end times in seconds.
|
|
67
|
+
|
|
68
|
+
Raises
|
|
69
|
+
------
|
|
70
|
+
ValueError
|
|
71
|
+
If required columns are missing or intervals are invalid.
|
|
72
|
+
"""
|
|
73
|
+
required_columns = {
|
|
74
|
+
"Selection",
|
|
75
|
+
"Begin Time (s)",
|
|
76
|
+
"End Time (s)",
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
selections = []
|
|
80
|
+
seen_selections = set()
|
|
81
|
+
|
|
82
|
+
with Path(file_path).open("r", encoding="utf-8-sig", newline="") as file:
|
|
83
|
+
reader = csv.DictReader(file, delimiter="\t")
|
|
84
|
+
|
|
85
|
+
if not required_columns.issubset(reader.fieldnames or []):
|
|
86
|
+
raise ValueError("Missing required Raven columns")
|
|
87
|
+
|
|
88
|
+
for row in reader:
|
|
89
|
+
try:
|
|
90
|
+
selection_id = int(row["Selection"])
|
|
91
|
+
start_time = float(row["Begin Time (s)"])
|
|
92
|
+
end_time = float(row["End Time (s)"])
|
|
93
|
+
except (ValueError, TypeError) as error:
|
|
94
|
+
raise ValueError("Invalid Raven selection values") from error
|
|
95
|
+
|
|
96
|
+
if selection_id < 1:
|
|
97
|
+
raise ValueError("Selection identifiers must be positive")
|
|
98
|
+
|
|
99
|
+
if not (math.isfinite(start_time) and math.isfinite(end_time)):
|
|
100
|
+
raise ValueError("Selection times must be finite")
|
|
101
|
+
|
|
102
|
+
if start_time < 0 or end_time <= start_time:
|
|
103
|
+
raise ValueError("Invalid selection time interval")
|
|
104
|
+
|
|
105
|
+
# Skip identical selections exported from multiple Raven views.
|
|
106
|
+
selection_key = (selection_id, start_time, end_time)
|
|
107
|
+
if selection_key in seen_selections:
|
|
108
|
+
continue
|
|
109
|
+
seen_selections.add(selection_key)
|
|
110
|
+
|
|
111
|
+
selections.append({
|
|
112
|
+
"selection": selection_id,
|
|
113
|
+
"start_time": start_time,
|
|
114
|
+
"end_time": end_time,
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
return selections
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def extract_audio(
|
|
121
|
+
audio: np.ndarray,
|
|
122
|
+
sample_rate: int,
|
|
123
|
+
start_time: float,
|
|
124
|
+
end_time: float,
|
|
125
|
+
) -> np.ndarray:
|
|
126
|
+
"""Extract an audio segment using a time interval in seconds.
|
|
127
|
+
|
|
128
|
+
Parameters
|
|
129
|
+
----------
|
|
130
|
+
audio : numpy.ndarray
|
|
131
|
+
One-dimensional audio signal.
|
|
132
|
+
sample_rate : int
|
|
133
|
+
Sampling frequency in Hz.
|
|
134
|
+
start_time : float
|
|
135
|
+
Segment start time in seconds.
|
|
136
|
+
end_time : float
|
|
137
|
+
Segment end time in seconds.
|
|
138
|
+
|
|
139
|
+
Returns
|
|
140
|
+
-------
|
|
141
|
+
numpy.ndarray
|
|
142
|
+
Extracted audio samples, without signal processing.
|
|
143
|
+
|
|
144
|
+
Raises
|
|
145
|
+
------
|
|
146
|
+
TypeError
|
|
147
|
+
If sample_rate is not an integer.
|
|
148
|
+
ValueError
|
|
149
|
+
If the audio, sample rate, or interval is invalid.
|
|
150
|
+
"""
|
|
151
|
+
if not isinstance(audio, np.ndarray) or audio.ndim != 1:
|
|
152
|
+
raise ValueError("audio must be a 1D NumPy array")
|
|
153
|
+
|
|
154
|
+
if audio.size == 0:
|
|
155
|
+
raise ValueError("audio cannot be empty")
|
|
156
|
+
|
|
157
|
+
if not isinstance(sample_rate, (int, np.integer)) or isinstance(
|
|
158
|
+
sample_rate, (bool, np.bool_)
|
|
159
|
+
):
|
|
160
|
+
raise TypeError("sample_rate must be an integer")
|
|
161
|
+
|
|
162
|
+
if sample_rate <= 0:
|
|
163
|
+
raise ValueError("sample_rate must be positive")
|
|
164
|
+
|
|
165
|
+
if not (math.isfinite(start_time) and math.isfinite(end_time)):
|
|
166
|
+
raise ValueError("Segment times must be finite")
|
|
167
|
+
|
|
168
|
+
if start_time < 0 or end_time <= start_time:
|
|
169
|
+
raise ValueError("Invalid segment time interval")
|
|
170
|
+
|
|
171
|
+
duration = len(audio) / sample_rate
|
|
172
|
+
|
|
173
|
+
if end_time > duration:
|
|
174
|
+
raise ValueError("Segment exceeds audio duration")
|
|
175
|
+
|
|
176
|
+
start_sample = round(start_time * sample_rate)
|
|
177
|
+
end_sample = round(end_time * sample_rate)
|
|
178
|
+
|
|
179
|
+
if start_sample >= end_sample:
|
|
180
|
+
raise ValueError("Segment contains no samples")
|
|
181
|
+
|
|
182
|
+
return audio[start_sample:end_sample]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def extract_audio_segments(
|
|
186
|
+
audio_path: str | Path,
|
|
187
|
+
raven_path: str | Path,
|
|
188
|
+
output_dir: str | Path,
|
|
189
|
+
channel: int = 0,
|
|
190
|
+
) -> list[dict]:
|
|
191
|
+
"""Extract Raven selections into individual mono WAV files.
|
|
192
|
+
|
|
193
|
+
Preserve the original sample rate and WAV subtype.
|
|
194
|
+
Generate a CSV manifest containing extraction provenance.
|
|
195
|
+
|
|
196
|
+
Parameters
|
|
197
|
+
----------
|
|
198
|
+
audio_path : str or pathlib.Path
|
|
199
|
+
Original WAV recording.
|
|
200
|
+
raven_path : str or pathlib.Path
|
|
201
|
+
Raven selection table.
|
|
202
|
+
output_dir : str or pathlib.Path
|
|
203
|
+
Directory for extracted WAV files and manifest.
|
|
204
|
+
channel : int, default 0
|
|
205
|
+
Zero-based channel index.
|
|
206
|
+
|
|
207
|
+
Returns
|
|
208
|
+
-------
|
|
209
|
+
list of dict
|
|
210
|
+
Extraction records included in the CSV manifest.
|
|
211
|
+
"""
|
|
212
|
+
audio_path = Path(audio_path).resolve()
|
|
213
|
+
raven_path = Path(raven_path).resolve()
|
|
214
|
+
output_dir = Path(output_dir).resolve()
|
|
215
|
+
|
|
216
|
+
# Read source metadata and audio.
|
|
217
|
+
audio_info = sf.info(audio_path)
|
|
218
|
+
audio, sample_rate = sf.read(audio_path)
|
|
219
|
+
|
|
220
|
+
mono_audio = select_channel(audio, channel)
|
|
221
|
+
selections = load_raven_selections(raven_path)
|
|
222
|
+
|
|
223
|
+
manifest_path = output_dir / "extraction_manifest.csv"
|
|
224
|
+
|
|
225
|
+
fieldnames = [
|
|
226
|
+
"output_file",
|
|
227
|
+
"source_file",
|
|
228
|
+
"raven_file",
|
|
229
|
+
"raven_selection",
|
|
230
|
+
"start_s",
|
|
231
|
+
"end_s",
|
|
232
|
+
"start_sample",
|
|
233
|
+
"end_sample",
|
|
234
|
+
"channel",
|
|
235
|
+
"sample_rate",
|
|
236
|
+
"subtype",
|
|
237
|
+
]
|
|
238
|
+
|
|
239
|
+
# Prepare and validate all segments before writing files.
|
|
240
|
+
records = []
|
|
241
|
+
segments = []
|
|
242
|
+
output_paths = set()
|
|
243
|
+
|
|
244
|
+
for selection in selections:
|
|
245
|
+
selection_id = selection["selection"]
|
|
246
|
+
start_time = selection["start_time"]
|
|
247
|
+
end_time = selection["end_time"]
|
|
248
|
+
|
|
249
|
+
segment = extract_audio(
|
|
250
|
+
mono_audio,
|
|
251
|
+
sample_rate,
|
|
252
|
+
start_time,
|
|
253
|
+
end_time,
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
start_sample = round(start_time * sample_rate)
|
|
257
|
+
end_sample = round(end_time * sample_rate)
|
|
258
|
+
|
|
259
|
+
filename = f"{audio_path.stem}_call_{selection_id:03d}.wav"
|
|
260
|
+
destination = output_dir / filename
|
|
261
|
+
|
|
262
|
+
if destination in output_paths:
|
|
263
|
+
raise ValueError(f"Duplicate output filename: {filename}")
|
|
264
|
+
|
|
265
|
+
if destination.exists():
|
|
266
|
+
raise FileExistsError(f"Output file already exists: {destination}")
|
|
267
|
+
|
|
268
|
+
output_paths.add(destination)
|
|
269
|
+
|
|
270
|
+
records.append({
|
|
271
|
+
"output_file": filename,
|
|
272
|
+
"source_file": str(audio_path),
|
|
273
|
+
"raven_file": str(raven_path),
|
|
274
|
+
"raven_selection": selection_id,
|
|
275
|
+
"start_s": start_time,
|
|
276
|
+
"end_s": end_time,
|
|
277
|
+
"start_sample": start_sample,
|
|
278
|
+
"end_sample": end_sample,
|
|
279
|
+
"channel": channel,
|
|
280
|
+
"sample_rate": sample_rate,
|
|
281
|
+
"subtype": audio_info.subtype,
|
|
282
|
+
})
|
|
283
|
+
|
|
284
|
+
segments.append((destination, segment))
|
|
285
|
+
|
|
286
|
+
if manifest_path.exists():
|
|
287
|
+
raise FileExistsError(f"Manifest already exists: {manifest_path}")
|
|
288
|
+
|
|
289
|
+
# Write individual WAV files.
|
|
290
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
291
|
+
|
|
292
|
+
for destination, segment in segments:
|
|
293
|
+
sf.write(
|
|
294
|
+
destination,
|
|
295
|
+
segment,
|
|
296
|
+
sample_rate,
|
|
297
|
+
format="WAV",
|
|
298
|
+
subtype=audio_info.subtype,
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
# Write the extraction manifest.
|
|
302
|
+
with manifest_path.open("w", newline="", encoding="utf-8") as file:
|
|
303
|
+
writer = csv.DictWriter(file, fieldnames=fieldnames)
|
|
304
|
+
writer.writeheader()
|
|
305
|
+
writer.writerows(records)
|
|
306
|
+
|
|
307
|
+
return records
|