benmcewen commited on
Commit
fbeb49a
·
verified ·
1 Parent(s): 5f6c530

Update WABAD.py

Browse files
Files changed (1) hide show
  1. WABAD.py +216 -72
WABAD.py CHANGED
@@ -1,72 +1,216 @@
1
- import datasets
2
- import pandas as pd
3
- import os
4
- import ast
5
-
6
-
7
- class WABADBuilderConfig(datasets.BuilderConfig):
8
- def __init__(self, location_dir, **kwargs):
9
- super().__init__(**kwargs)
10
- self.location_dir = location_dir
11
-
12
- class WABADDataset(datasets.GeneratorBasedBuilder):
13
- BUILDER_CONFIGS = [
14
- WABADBuilderConfig(name="BAM", location_dir="BAM", description="BAM location"),
15
- WABADBuilderConfig(name="ARD", location_dir="ARD", description="ARD location"),
16
- # add more locations here
17
- ]
18
-
19
- def _info(self):
20
- return datasets.DatasetInfo(
21
- features=datasets.Features({
22
- "audio": datasets.Audio(),
23
- "labels": datasets.Sequence(datasets.Value("int32")),
24
- "site_ID": datasets.Value("string"),
25
- # any other metadata
26
- })
27
- )
28
-
29
- def _split_generators(self, dl_manager):
30
- config_dir = self.config.location_dir
31
-
32
- # Use the correct dataset URL format and download specific files
33
- train_url = f"https://huggingface.co/datasets/benmcewen/WABAD/resolve/main/{config_dir}/{config_dir}_metadata_train.parquet"
34
- test_url = f"https://huggingface.co/datasets/benmcewen/WABAD/resolve/main/{config_dir}/{config_dir}_metadata_test.parquet"
35
-
36
- # Download the parquet files
37
- train_file = dl_manager.download(train_url)
38
- test_file = dl_manager.download(test_url)
39
-
40
- return [
41
- datasets.SplitGenerator(
42
- name=datasets.Split.TRAIN,
43
- gen_kwargs={
44
- "parquet_file": train_file,
45
- "config_dir": config_dir
46
- },
47
- ),
48
- datasets.SplitGenerator(
49
- name=datasets.Split.TEST,
50
- gen_kwargs={
51
- "parquet_file": test_file,
52
- "config_dir": config_dir
53
- },
54
- )
55
- ]
56
-
57
- def _generate_examples(self, parquet_file, config_dir):
58
- df = pd.read_parquet(parquet_file)
59
- for idx, row in df.iterrows():
60
- # Download audio file on demand
61
- audio_url = f"https://huggingface.co/datasets/benmcewen/WABAD/resolve/main/{config_dir}/audio/{os.path.basename(row['filepath'])}"
62
-
63
- labels = row["labels"]
64
- if isinstance(labels, str):
65
- labels = ast.literal_eval(labels)
66
-
67
- yield idx, {
68
- "audio": {"path": audio_url, "bytes": None}, # Let datasets handle the download
69
- "labels": labels,
70
- "site_ID": row.get("site_ID", self.config.name),
71
- # other metadata
72
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+ import pandas as pd
3
+ import os
4
+ import ast
5
+ import zipfile
6
+ from pathlib import Path
7
+
8
+
9
+ def _extract_zip_to_folder(zip_path, output_dir):
10
+ """Extract zip file to output directory, similar to BirdSet's tar extraction"""
11
+ # Check if data already exists
12
+ if not os.path.isfile(output_dir) and os.path.isdir(output_dir) and os.listdir(output_dir):
13
+ return output_dir
14
+
15
+ os.makedirs(output_dir, exist_ok=True)
16
+
17
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
18
+ for member in zip_ref.infolist():
19
+ if not member.is_dir():
20
+ # Extract file to output directory
21
+ member.filename = os.path.basename(member.filename)
22
+ zip_ref.extract(member, path=output_dir)
23
+
24
+ return output_dir
25
+
26
+
27
+ def _extract_and_delete_zip(dl_dir: dict, cache_dir: str = None) -> dict:
28
+ """Extract downloaded zip files and delete archives immediately, similar to BirdSet"""
29
+ audio_paths = {name: [] for name, data in dl_dir.items() if name.startswith('audio_')}
30
+
31
+ for name, data in dl_dir.items():
32
+ if not name.startswith('audio_'):
33
+ continue
34
+
35
+ # Extract zip file
36
+ directory, filename = os.path.split(data)
37
+ output_dir = os.path.join(cache_dir or directory, "extracted", filename.split(".")[0])
38
+ audio_path = _extract_zip_to_folder(data, output_dir)
39
+
40
+ # Clean up
41
+ os.remove(data)
42
+ # Remove lock files if they exist (datasets >3.0.0)
43
+ if os.path.exists(f"{data}.lock"):
44
+ os.remove(f"{data}.lock")
45
+ if os.path.exists(f"{data}.json"):
46
+ os.remove(f"{data}.json")
47
+
48
+ # Store the base name without 'audio_' prefix
49
+ base_name = name.replace('audio_', '')
50
+ audio_paths[base_name] = audio_path
51
+
52
+ return audio_paths
53
+
54
+
55
+ class WABADBuilderConfig(datasets.BuilderConfig):
56
+ def __init__(self, location_dir, **kwargs):
57
+ super().__init__(**kwargs)
58
+ self.location_dir = location_dir
59
+
60
+
61
+ class WABADDataset(datasets.GeneratorBasedBuilder):
62
+ """WABAD: World Acoustic Bird Audio Dataset"""
63
+
64
+ # Batch size to prevent memory issues
65
+ DEFAULT_WRITER_BATCH_SIZE = 500
66
+
67
+ BUILDER_CONFIGS = [
68
+ WABADBuilderConfig(name="BUR", location_dir="BUR", description="BUR location"),
69
+ # Add more locations here as needed
70
+ ]
71
+
72
+ def _info(self):
73
+ return datasets.DatasetInfo(
74
+ description="WABAD: World Acoustic Bird Audio Dataset",
75
+ features=datasets.Features({
76
+ "audio": datasets.Audio(sampling_rate=48_000, mono=True, decode=False),
77
+ "filename": datasets.Value("string"),
78
+ "filepath": datasets.Value("string"),
79
+ "labels": datasets.Sequence(datasets.Value("int32")),
80
+ "species": datasets.Sequence(datasets.Value("string")),
81
+ "site_ID": datasets.Value("string"),
82
+ "study_area": datasets.Value("string"),
83
+ "recording_location": datasets.Value("string"),
84
+ "biome": datasets.Value("string"),
85
+ "latitude": datasets.Value("string"),
86
+ "longitude": datasets.Value("string"),
87
+ "recorder": datasets.Value("string"),
88
+ "omnidirectional": datasets.Value("string"),
89
+ "sampling_rate": datasets.Value("string"),
90
+ "recording_date": datasets.Value("string"),
91
+ "min_annotated": datasets.Value("int32"),
92
+ "contact": datasets.Value("string"),
93
+ "reference": datasets.Value("string"),
94
+ })
95
+ )
96
+
97
+ def _split_generators(self, dl_manager):
98
+ config_dir = self.config.location_dir
99
+ base_url = f"https://huggingface.co/datasets/benmcewen/WABAD/resolve/main/{config_dir}"
100
+
101
+ # Download metadata and audio files
102
+ dl_dir = dl_manager.download({
103
+ "meta_train": f"{base_url}/{config_dir}_metadata_train.parquet",
104
+ "meta_test": f"{base_url}/{config_dir}_metadata_test.parquet",
105
+ "audio_train": f"{base_url}/audio.zip", # Assuming same zip for both splits
106
+ "audio_test": f"{base_url}/audio.zip",
107
+ })
108
+
109
+ # Extract zip files and clean up
110
+ audio_paths = _extract_and_delete_zip(dl_dir, dl_manager.download_config.cache_dir) if not dl_manager.is_streaming else {}
111
+
112
+ return [
113
+ datasets.SplitGenerator(
114
+ name=datasets.Split.TRAIN,
115
+ gen_kwargs={
116
+ "audio_archive_iterator": dl_manager.iter_archive(dl_dir["audio_train"]) if dl_manager.is_streaming else None,
117
+ "audio_extracted_path": audio_paths.get("train") if not dl_manager.is_streaming else None,
118
+ "meta_path": dl_dir["meta_train"],
119
+ "split": "train"
120
+ },
121
+ ),
122
+ datasets.SplitGenerator(
123
+ name=datasets.Split.TEST,
124
+ gen_kwargs={
125
+ "audio_archive_iterator": dl_manager.iter_archive(dl_dir["audio_test"]) if dl_manager.is_streaming else None,
126
+ "audio_extracted_path": audio_paths.get("test") if not dl_manager.is_streaming else None,
127
+ "meta_path": dl_dir["meta_test"],
128
+ "split": "test"
129
+ },
130
+ )
131
+ ]
132
+
133
+ def _generate_examples(self, audio_archive_iterator, audio_extracted_path, meta_path, split):
134
+ # Load metadata
135
+ metadata = pd.read_parquet(meta_path)
136
+ if metadata.index.name != "filename":
137
+ # Set filename as index for easier lookup
138
+ if "filename" in metadata.columns:
139
+ metadata.index = metadata["filename"]
140
+ else:
141
+ # Fallback: extract filename from filepath
142
+ metadata.index = metadata["filepath"].apply(lambda x: os.path.basename(x))
143
+
144
+ idx = 0
145
+
146
+ # Handle streaming case
147
+ if audio_archive_iterator:
148
+ for audio_path_in_archive, audio_file in audio_archive_iterator:
149
+ file_name = os.path.basename(audio_path_in_archive)
150
+
151
+ # Find matching metadata rows
152
+ if file_name in metadata.index:
153
+ rows = metadata.loc[[file_name]] if isinstance(metadata.loc[file_name], pd.Series) else metadata.loc[metadata.index == file_name]
154
+ audio_bytes = audio_file.read()
155
+
156
+ for _, row in (rows.to_frame().T if isinstance(rows, pd.Series) else rows).iterrows():
157
+ yield idx, self._metadata_from_row(row, audio_bytes=audio_bytes)
158
+ idx += 1
159
+
160
+ # Handle non-streaming case
161
+ elif audio_extracted_path:
162
+ audio_files = os.listdir(audio_extracted_path)
163
+
164
+ for audio_file in audio_files:
165
+ if audio_file in metadata.index:
166
+ row_data = metadata.loc[audio_file]
167
+
168
+ # Handle case where there might be multiple rows for same filename
169
+ if isinstance(row_data, pd.DataFrame):
170
+ for _, row in row_data.iterrows():
171
+ audio_path = os.path.join(audio_extracted_path, audio_file)
172
+ yield idx, self._metadata_from_row(row, audio_path=audio_path)
173
+ idx += 1
174
+ else:
175
+ audio_path = os.path.join(audio_extracted_path, audio_file)
176
+ yield idx, self._metadata_from_row(row_data, audio_path=audio_path)
177
+ idx += 1
178
+
179
+ def _metadata_from_row(self, row, audio_path=None, audio_bytes=None):
180
+ """Convert metadata row to example format"""
181
+ # Parse labels if they're stored as strings
182
+ labels = row.get("labels", [])
183
+ if isinstance(labels, str):
184
+ try:
185
+ labels = ast.literal_eval(labels)
186
+ except (ValueError, SyntaxError):
187
+ labels = []
188
+
189
+ # Parse species if it's stored as string
190
+ species = row.get("species", [])
191
+ if isinstance(species, str):
192
+ try:
193
+ species = ast.literal_eval(species)
194
+ except (ValueError, SyntaxError):
195
+ species = [species] if species else []
196
+
197
+ return {
198
+ "audio": {"path": audio_path, "bytes": audio_bytes} if audio_bytes else audio_path,
199
+ "filename": row.get("filename", ""),
200
+ "filepath": row.get("filepath", ""),
201
+ "labels": labels,
202
+ "species": species,
203
+ "site_ID": row.get("site_ID", self.config.name),
204
+ "study_area": row.get("study_area", ""),
205
+ "recording_location": row.get("recording_location", ""),
206
+ "biome": row.get("biome", ""),
207
+ "latitude": str(row.get("latitude", "")),
208
+ "longitude": str(row.get("longitude", "")),
209
+ "recorder": row.get("recorder", ""),
210
+ "omnidirectional": row.get("omnidirectional", ""),
211
+ "sampling_rate": row.get("sampling_rate", ""),
212
+ "recording_date": str(row.get("recording_date", "")),
213
+ "min_annotated": int(row.get("min_annotated", 0)) if pd.notna(row.get("min_annotated")) else 0,
214
+ "contact": row.get("contact", ""),
215
+ "reference": row.get("reference", ""),
216
+ }