simulok 0.1.0__py3-none-any.whl

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/__init__.py 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