forked from kahst/BirdNET-Analyzer
-
Notifications
You must be signed in to change notification settings - Fork 5
/
segments.py
305 lines (234 loc) · 9.55 KB
/
segments.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
154
155
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""Extract segments from audio files based on BirdNET detections.
Can be used to save the segments of the audio files for each detection.
"""
import argparse
import os
from multiprocessing import Pool
import numpy as np
import audio
import config as cfg
import utils
# Set numpy random seed
np.random.seed(cfg.RANDOM_SEED)
def detectRType(line: str):
"""Detects the type of result file.
Args:
line: First line of text.
Returns:
Either "table", "r", "kaleidoscope", "csv" or "audacity".
"""
if line.lower().startswith("selection"):
return "table"
elif line.lower().startswith("filepath"):
return "r"
elif line.lower().startswith("indir"):
return "kaleidoscope"
elif line.lower().startswith("start (s)"):
return "csv"
else:
return "audacity"
def parseFolders(apath: str, rpath: str, allowed_result_filetypes: list[str] = ["txt", "csv"]) -> list[dict]:
"""Read audio and result files.
Reads all audio files and BirdNET output inside directory recursively.
Args:
apath: Path to search for audio files.
rpath: Path to search for result files.
allowed_result_filetypes: List of extensions for the result files.
Returns:
A list of {"audio": path_to_audio, "result": path_to_result }.
"""
data = {}
apath = apath.replace("/", os.sep).replace("\\", os.sep)
rpath = rpath.replace("/", os.sep).replace("\\", os.sep)
# Get all audio files
for root, _, files in os.walk(apath):
for f in files:
if f.rsplit(".", 1)[-1].lower() in cfg.ALLOWED_FILETYPES:
data[f.rsplit(".", 1)[0]] = {"audio": os.path.join(root, f), "result": ""}
# Get all result files
for root, _, files in os.walk(rpath):
for f in files:
if f.rsplit(".", 1)[-1] in allowed_result_filetypes and ".bat." in f:
data[f.split(".bat.", 1)[0]]["result"] = os.path.join(root, f)
# Convert to list
flist = [f for f in data.values() if f["result"]]
print(f"Found {len(flist)} audio files with valid result file.")
return flist
def parseFiles(flist: list[dict], max_segments=100):
"""Extracts the segments for all files.
Args:
flist: List of dict with {"audio": path_to_audio, "result": path_to_result }.
max_segments: Number of segments per species.
Returns:
TODO @kahst
"""
species_segments: dict[str, list] = {}
for f in flist:
# Paths
afile = f["audio"]
rfile = f["result"]
# Get all segments for result file
segments = findSegments(afile, rfile)
# Parse segments by species
for s in segments:
if s["species"] not in species_segments:
species_segments[s["species"]] = []
species_segments[s["species"]].append(s)
# Shuffle segments for each species and limit to max_segments
for s in species_segments:
np.random.shuffle(species_segments[s])
species_segments[s] = species_segments[s][:max_segments]
# Make dict of segments per audio file
segments: dict[str, list] = {}
seg_cnt = 0
for s in species_segments:
for seg in species_segments[s]:
if seg["audio"] not in segments:
segments[seg["audio"]] = []
segments[seg["audio"]].append(seg)
seg_cnt += 1
print(f"Found {seg_cnt} segments in {len(segments)} audio files.")
# Convert to list
flist = [tuple(e) for e in segments.items()]
return flist
def findSegments(afile: str, rfile: str):
"""Extracts the segments for an audio file from the results file
Args:
afile: Path to the audio file.
rfile: Path to the result file.
Returns:
A list of dicts in the form of
{"audio": afile, "start": start, "end": end, "species": species, "confidence": confidence}
"""
segments: list[dict] = []
# Open and parse result file
lines = utils.readLines(rfile)
# Auto-detect result type
rtype = detectRType(lines[0])
# Get start and end times based on rtype
confidence = 0
start = end = 0.0
species = ""
for i, line in enumerate(lines):
if rtype == "table" and i > 0:
d = line.split("\t")
start = float(d[3])
end = float(d[4])
species = d[-2]
confidence = float(d[-1])
elif rtype == "audacity":
d = line.split("\t")
start = float(d[0])
end = float(d[1])
species = d[2].split(", ")[1]
confidence = float(d[-1])
elif rtype == "r" and i > 0:
d = line.split(",")
start = float(d[1])
end = float(d[2])
species = d[4]
confidence = float(d[5])
elif rtype == "kaleidoscope" and i > 0:
d = line.split(",")
start = float(d[3])
end = float(d[4]) + start
species = d[5]
confidence = float(d[7])
elif rtype == "csv" and i > 0:
d = line.split(",")
start = float(d[0])
end = float(d[1])
species = d[3]
confidence = float(d[4])
# Check if confidence is high enough
if confidence >= cfg.MIN_CONFIDENCE:
segments.append({"audio": afile, "start": start, "end": end, "species": species, "confidence": confidence})
return segments
def extractSegments(item: tuple[tuple[str, list[dict]], float, dict[str]]):
"""Saves each segment separately.
Creates an audio file for each species segment.
Args:
item: A tuple that contains ((audio file path, segments), segment length, config)
"""
# Paths and config
afile = item[0][0]
segments = item[0][1]
seg_length = item[1]
cfg.set_config(item[2])
# Status
print(f"Extracting segments from {afile}")
try:
# Open audio file
sig, _ = audio.openAudioFile(afile, cfg.SAMPLE_RATE)
except Exception as ex:
print(f"Error: Cannot open audio file {afile}", flush=True)
utils.writeErrorLog(ex)
return
# Extract segments
for seg_cnt, seg in enumerate(segments, 1):
try:
# Get start and end times
start = int(seg["start"] * cfg.SAMPLE_RATE)
end = int(seg["end"] * cfg.SAMPLE_RATE)
offset = ((seg_length * cfg.SAMPLE_RATE) - (end - start)) // 2
start = max(0, start - offset)
end = min(len(sig), end + offset)
# Make sure segment is long enough
if end > start:
# Get segment raw audio from signal
seg_sig = sig[int(start) : int(end)]
# Make output path
outpath = os.path.join(cfg.OUTPUT_PATH, seg["species"])
os.makedirs(outpath, exist_ok=True)
# Save segment
seg_name = "{:.3f}_{}_{}.wav".format(
seg["confidence"], seg_cnt, seg["audio"].rsplit(os.sep, 1)[-1].rsplit(".", 1)[0]
)
seg_path = os.path.join(outpath, seg_name)
audio.saveSignal(seg_sig, seg_path)
except Exception as ex:
# Write error log
print(f"Error: Cannot extract segments from {afile}.", flush=True)
utils.writeErrorLog(ex)
return False
return True
if __name__ == "__main__":
# Parse arguments
parser = argparse.ArgumentParser(description="Extract segments from audio files based on BirdNET detections.")
parser.add_argument("--audio", default="put-your-files-here/", help="Path to folder containing audio files.")
parser.add_argument("--results", default="put-your-files-here/results", help="Path to folder containing result files.")
parser.add_argument("--o", default="put-your-files-here/segments/", help="Output folder path for extracted segments.")
parser.add_argument(
"--min_conf", type=float, default=0.1, help="Minimum confidence threshold. Values in [0.01, 0.99]. Defaults to 0.1."
)
parser.add_argument("--max_segments", type=int, default=100, help="Number of randomly extracted segments per species.")
parser.add_argument(
"--seg_length", type=float, default=3.0, help="Length of extracted segments in seconds. Defaults to 3.0."
)
parser.add_argument("--threads", type=int, default=4, help="Number of CPU threads.")
args = parser.parse_args()
# Parse audio and result folders
cfg.FILE_LIST = parseFolders(args.audio, args.results)
# Set output folder
cfg.OUTPUT_PATH = args.o
# Set number of threads
cfg.CPU_THREADS = int(args.threads)
# Set confidence threshold
cfg.MIN_CONFIDENCE = max(0.01, min(0.99, float(args.min_conf)))
# Parse file list and make list of segments
cfg.FILE_LIST = parseFiles(cfg.FILE_LIST, max(1, int(args.max_segments)))
# Add config items to each file list entry.
# We have to do this for Windows which does not
# support fork() and thus each process has to
# have its own config. USE LINUX!
flist = [(entry, max(cfg.SIG_LENGTH, float(args.seg_length)), cfg.get_config()) for entry in cfg.FILE_LIST]
# Extract segments
if cfg.CPU_THREADS < 2:
for entry in flist:
extractSegments(entry)
else:
with Pool(cfg.CPU_THREADS) as p:
p.map(extractSegments, flist)
# A few examples to test
# python3 segments.py --audio example/ --results example/ --o example/segments/
# python3 segments.py --audio example/ --results example/ --o example/segments/ --seg_length 5.0 --min_conf 0.1 --max_segments 100 --threads 4