-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathload_birdclef.py
More file actions
286 lines (222 loc) · 8.07 KB
/
Copy pathload_birdclef.py
File metadata and controls
286 lines (222 loc) · 8.07 KB
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
import logging
import os
from collections import OrderedDict
from pathlib import Path
from typing import Optional
import pandas as pd
def load_birdclef(path: Path, min_per_class: int = 0) -> Optional[pd.DataFrame]:
"""
Loads the birdclef dataset
"""
if not os.path.isfile(path):
logging.error("Invalid path for birdclef")
return None
df = pd.read_csv(path)
# Drop rare classes
if min_per_class > 0:
keep_labels = df["primary_label"].value_counts()
keep_labels = keep_labels[keep_labels >= min_per_class].index
df = df[df["primary_label"].isin(keep_labels)].reset_index(drop=True)
# Drop unnamed column
df = df.loc[:, ~df.columns.str.contains("^Unnamed")]
# Add group key based on auther + time to prevent straddeling
df["group_key"] = df["author"] + df["time"]
return df
def create_label_mapping(df: pd.DataFrame) -> dict:
"""
The primary labels are stored seperately from the scientific names and need
to be mapped so that we can trace back the birdnet requirements for the future
soundscape predictions.
"""
mapping = df.groupby("scientific_name")["primary_label"].first().to_dict()
return mapping
def expand_birdclef(df: pd.DataFrame) -> Optional[pd.DataFrame]:
"""
Expands the dataframe so we can maximize the dataset. It creates
a new dataset in which each row is a single detection.
"""
rows = []
def expand_row(row):
# Map the cell to a list
preds = eval(row["predictions"], {"OrderedDict": OrderedDict})
if len(preds) == 0:
return
new_rows = []
for pred in preds:
# Get the first ordered dict item
first = next(iter(pred[1].items()))
r = {
"path": row["path"],
"file": row["filename"],
"start": pred[0][0],
"end": pred[0][1],
"scientific_name": first[0].split("_")[0],
"common_name": first[0].split("_")[1],
"confidence": first[1],
"group_key": row["group_key"],
}
new_rows.append(r)
rows.extend(new_rows)
df.apply(expand_row, axis=1)
return pd.DataFrame(rows)
def load_and_clean_birdclef(
path: Path, min_per_class: int = 0, allow_cache=False
) -> Optional[pd.DataFrame]:
"""
This function:
- Loads the dataframe
- Maps the birdnet predictions to individual rows with primary labels
"""
# First check if we have it cached
if allow_cache and os.path.isfile(Path("cache/cleaned_birdnet_clef.csv")):
logging.info("Found cached birndet_clef dataframe!")
return pd.read_csv("cache/cleaned_birdnet_clef.csv")
birdclef_df = load_birdclef(path, min_per_class=min_per_class)
if birdclef_df is None:
return None
label_mapping = create_label_mapping(birdclef_df)
expanded_df = expand_birdclef(birdclef_df)
if expanded_df is None:
return None
# Add the primary labels to each row
expanded_df["primary_label"] = expanded_df.apply(
(
lambda row: (
label_mapping[row["scientific_name"]]
if row["scientific_name"] in label_mapping.keys()
else None
)
),
axis=1,
)
# Drop the none columns
expanded_df = expanded_df.dropna(subset=["primary_label"])
# Output to cache
os.makedirs("cache", exist_ok=True)
expanded_df.to_csv("cache/cleaned_birdnet_clef.csv")
return expanded_df
def load_and_clean_custom(
path: Path, min_per_class: int = 0, allow_cache=True
) -> Optional[pd.DataFrame]:
"""
This function:
- Loads the dataframe
- Maps the birdnet predictions to individual rows with primary labels
"""
# First check if we have it cached
if allow_cache and os.path.isfile(Path("cache/cleaned_custom.csv")):
logging.info("Found cached custom dataframe!")
return pd.read_csv("cache/cleaned_custom.csv")
# We can reuse the birdcelf loader
custom_df = load_birdclef(path, min_per_class=min_per_class)
if custom_df is None:
return None
label_mapping = create_label_mapping(custom_df)
expanded_df = expand_birdclef(custom_df)
if expanded_df is None:
return None
# Add the primary labels to each row
expanded_df["primary_label"] = expanded_df.apply(
(
lambda row: (
label_mapping[row["scientific_name"]]
if row["scientific_name"] in label_mapping.keys()
else None
)
),
axis=1,
)
# Drop the none columns
expanded_df = expanded_df.dropna(subset=["primary_label"])
# Output to cache
os.makedirs("cache", exist_ok=True)
expanded_df.to_csv("cache/cleaned_custom.csv")
return expanded_df
def load_soundscapes(path: Path) -> Optional[pd.DataFrame]:
"""
Loads the soundscape dataset
"""
if not os.path.isfile(path):
logging.error("Invalid path for soundscapes")
return None
df = pd.read_csv(path)
df["group_key"] = df["date"]
return df
def expand_soundscapes(df: pd.DataFrame) -> Optional[pd.DataFrame]:
"""
Expands the dataframe so we can maximize the dataset. It creates
a new dataset in which each row is a single detection.
"""
rows = []
def expand_row(row):
# Map the cell to a list
preds = eval(row["predictions"], {"OrderedDict": OrderedDict})
if len(preds) == 0:
return
new_rows = []
for pred in preds:
# Soundscape predictions can be empty
if (len(pred[1].items())) > 0:
# Get the first ordered dict item
first = next(iter(pred[1].items()))
r = {
"path": row["path"],
"start": pred[0][0],
"end": pred[0][1],
"scientific_name": first[0].split("_")[0],
"common_name": first[0].split("_")[1],
"confidence": first[1],
"group_key": row["group_key"],
}
else:
r = {
"path": row["path"],
"start": pred[0][0],
"end": pred[0][1],
"scientific_name": "nocall",
"common_name": "nocall",
"confidence": 100.0,
"group_key": row["group_key"],
}
new_rows.append(r)
rows.extend(new_rows)
df.apply(expand_row, axis=1)
return pd.DataFrame(rows)
def load_and_clean_soundscapes(
birdclef_path: Path, soundscape_path: Path, allow_cache=True
) -> Optional[pd.DataFrame]:
"""
This function:
- Loads the dataframe
- Maps the birdnet predictions to individual rows with primary labels
"""
# First check if we have it cached
if allow_cache and os.path.isfile(Path("cache/cleaned_birdnet_soundscape.csv")):
logging.info("Found cached cleaned_birdnet_soundscape dataframe!")
return pd.read_csv("cache/cleaned_birdnet_soundscape.csv")
# We also need the raw birdclef dataframe to create the mapping
birdclef_df = load_birdclef(birdclef_path, min_per_class=0)
soundscape_df = load_soundscapes(soundscape_path)
if birdclef_df is None or soundscape_df is None:
return None
label_mapping = create_label_mapping(birdclef_df)
expanded_df = expand_soundscapes(soundscape_df)
if expanded_df is None:
return None
# Add the primary labels to each row
expanded_df["primary_label"] = expanded_df.apply(
(
lambda row: (
label_mapping[row["scientific_name"]]
if row["scientific_name"] in label_mapping.keys()
else "nocall"
)
),
axis=1,
)
# Drop the none columns
expanded_df = expanded_df.dropna(subset=["primary_label"])
# Output to cache
os.makedirs("cache", exist_ok=True)
expanded_df.to_csv("cache/cleaned_birdnet_soundscape.csv")
return expanded_df