File size: 16,824 Bytes
ee563a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import json
import os
import datasets
from datasets import Features, Value, DatasetInfo, SplitGenerator, BuilderConfig, LargeList, Sequence



TASKS = [
    "word_localization",
    "advertisement_localization",
    "named_entity_localization",
    "speaker_number_estimation",
    "entire_duration",
    "event_duration",
    "emotion_ranking",
    "emotion_reasoning",
]

_DOCUMENT_DATASET_VERSION = "1.0.0"




# --- Main Dataset Builder Class ---
class BLAB(datasets.GeneratorBasedBuilder):
    """class BLAB(object): A dataset builder supporting various audio QA tasks,
    each with its own specific data schema.
    """
    BUILDER_CONFIGS = [
        BuilderConfig(
            name=task,
            version=datasets.Version(_DOCUMENT_DATASET_VERSION),
            description=f"BLAB dataset for task: {task}",
        ) for task in TASKS
    ]

    def _info(self):
        """Defines the dataset schema (features) based on the selected task configuration."""
        # --- Schema Definitions for each individual task ---

        if self.config.name == "word_localization":
            return DatasetInfo(
                features=Features({
                    "video_url": Value("string"),
                    "audio": Value("string"),
                    "question": Value("string"),
                    "groundtruth": LargeList(
                        feature=Features({
                            "word": Value("string"),
                            "start": Value("float32"),
                            "end": Value("float32"),
                        })
                    )
                }),
                description="Schema for the Word Localization task: segmenting and labeling words.",
                license="MIT",
            )

        elif self.config.name == "advertisement_localization":
            return DatasetInfo(
                features=Features({
                    "video_url": Value("string"),
                    "audio": Value("string"),
                    "question": Value("string"),
                    "groundtruth": Features({
                        "ads_segment": LargeList(
                            feature=Features({
                                "text": Value("string"),
                                "start": Value("float32"),
                                "end": Value("float32"),
                            }),
                        ),
                        "word_timestamp": LargeList(
                            feature=Features({
                                "word": Value("string"),
                                "start": Value("float32"),
                                "end": Value("float32"),
                            }),
                        ),
                    })
                }),
                description="Schema for Advertisement Localization task: identifying ad segments and their transcripts.",
                # ... (other metadata)
            )

        elif self.config.name == "named_entity_localization":
            return DatasetInfo(
                features=Features({
                    "video_url": Value("string"),
                    "audio": Value("string"),
                    "question": Value("string"),
                    "groundtruth": Features({
                        "entities": LargeList(
                            feature=Features({
                                "entity_type": Value("string"),
                                "entity": Value("string"),
                                "start": Value("float32"),
                                "end": Value("float32"),
                            }),
                        ),
                        "word_timestamp": LargeList(
                            feature=Features({
                                "word": Value("string"),
                                "start": Value("float32"),
                                "end": Value("float32"),
                            }),
                        ),
                    })
                }),
                description="Schema for Named Entity Localization task: identifying specific entities and their timestamps.",
                # ... (other metadata)
            )

        elif self.config.name == "speaker_number_estimation":
            return DatasetInfo(
                features=Features({
                    "video_url": Value("string"),
                    "audio": Value("string"),
                    "question": Value("string"),
                    "groundtruth": Sequence(Value("int32"))
                }),
                description="Schema for Speaker Number Estimation task: counting speakers in a segment.",
                # ... (other metadata)
            )

        elif self.config.name == "entire_duration":
            return DatasetInfo(
                features=Features({
                    "video_url": Value("string"),
                    "audio": Value("string"),
                    "question": Value("string"),
                    "groundtruth": Value("float32")
                }),
                description="Schema for Entire Duration task: determining the total duration of an audio.",

            )

        elif self.config.name == "event_duration":
            return DatasetInfo(
                features=Features({
                    "video_url": Value("string"),
                    "audio": Value("string"),
                    "question": Value("string"),
                    "groundtruth": Value("float32"),
                    "answer_type": Value("string"),
                }),
                description="Schema for Event Duration task: identifying and timing specific events.",
                # ... (other metadata)
            )

        elif self.config.name == "emotion_ranking":
            return DatasetInfo(
                features=Features({
                    "video_url": Value("string"),
                    "audio": Value("string"),
                    "question": Value("string"),
                    "type": Value("string"),
                    "correct_option": Value("string"),
                    "option_A": Value("string"),
                    "option_B": Value("string"),
                    "option_C": Value("string"),
                    "option_D": Value("string"),
                    "option_E": Value("string"),
                    "correct_answer": Value("string"), # Stores the correct_answer string
                }),
                description="Schema for Emotion Ranking task: selecting the best emotion option.",
                # ... (other metadata)
            )

        elif self.config.name == "emotion_reasoning":
            return DatasetInfo(
                features=Features({
                    "video_url": Value("string"),
                    "audio": Value("string"),
                    "question": Value("string"),
                    "type": Value("string"),
                    "correct_option": Value("string"),
                    "option_A": Value("string"),
                    "option_B": Value("string"),
                    "option_C": Value("string"),
                    "option_D": Value("string"),
                    "correct_answer": Value("string"), # Stores the correct_answer string
                }),
                description="Schema for Emotion Reasoning task: explaining emotional context.",
                # ... (other metadata)
            )
        else:
            raise ValueError(f"Unknown config name: {self.config.name}")

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators based on the selected task configuration."""
        data_files = {}

        if self.config.name == "word_localization":
            data_files = {"word_localization": "blab_long_audio/word_localization.json"}
        elif self.config.name == "advertisement_localization":
            data_files = {"advertisement_localization": "blab_long_audio/advertisement_localization.json"}
        elif self.config.name == "named_entity_localization":
            data_files = {"named_entity_localization": "blab_long_audio/named_entity_localization.json"}
        elif self.config.name == "speaker_number_estimation":
            data_files = {"speaker_number_estimation": "blab_long_audio/speaker_number_estimation.json"}
        elif self.config.name == "entire_duration":
            data_files = {"entire_duration": "blab_long_audio/entire_duration.json"}
        elif self.config.name == "event_duration":
            data_files = {"event_duration": "blab_long_audio/event_duration.json"}
        elif self.config.name == "emotion_ranking":
            data_files = {"emotion_ranking": "blab_long_audio/emotion_ranking.json"}
        elif self.config.name == "emotion_reasoning":
            data_files = {"emotion_reasoning": "blab_long_audio/emotion_reasoning.json"}
        else:
            raise ValueError(f"Unknown config name: {self.config.name}")

        resolved_data_files = dl_manager.download_and_extract(data_files)

        generators = []
        for split_name, filepath in resolved_data_files.items():
            generators.append(
                SplitGenerator(
                    name=split_name,
                    gen_kwargs={"filepath": filepath}
                )
            )
        return generators

    def _generate_examples(self, filepath):
        """Yields examples from the dataset files, parsing data based on the active config."""
        with open(filepath, 'r', encoding='utf-8') as f:
            all_data = json.load(f) # For .json files, load the entire array

            for id_, data in enumerate(all_data):
                try:
                    # Common fields for all tasks (handle missing with .get)
                    video_url = data.get("video_url", None)
                    audio = data.get("audio", None)
                    question = data.get("question", None)
                    #answer_type = data.get("answer_type", None)

                    example = {
                        "video_url": video_url,
                        "audio": audio,
                        "question": question,
                        #"answer_type": answer_type # Include as it's a common field in your schemas
                    }

                    # --- Task-specific groundtruth and other fields ---
                    if self.config.name == "word_localization":
                        raw_groundtruth = data.get("groundtruth", [])
                        processed_groundtruth = []
                        for item in raw_groundtruth:
                            if isinstance(item, dict):
                                processed_groundtruth.append({
                                    "word": item.get("word", None),
                                    "start": item.get("start", None),
                                    "end": item.get("end", None),
                                })
                        example["groundtruth"] = processed_groundtruth

                    elif self.config.name == "advertisement_localization":
                        raw_groundtruth = data.get("groundtruth", {})
                        raw_ads_segments = raw_groundtruth.get("ads_segment", [])
                        processed_ads_segments = []
                        for ad_item in raw_ads_segments:
                            if isinstance(ad_item, dict):
                                processed_ads_segments.append({
                                    "text": ad_item.get("text", None),
                                    "start": ad_item.get("start", None),
                                    "end": ad_item.get("end", None),
                                })
                        raw_word_timestamps = raw_groundtruth.get("word_timestamp", [])
                        processed_word_timestamps = []
                        for word_item in raw_word_timestamps:
                            if isinstance(word_item, dict):
                                processed_word_timestamps.append({
                                    "word": word_item.get("word", None),
                                    "start": word_item.get("start", None),
                                    "end": word_item.get("end", None),
                                })
                        example["groundtruth"] = {
                            "ads_segment": processed_ads_segments,
                            "word_timestamp": processed_word_timestamps,
                        }

                    elif self.config.name == "named_entity_localization":
                        raw_groundtruth = data.get("groundtruth", {})
                        raw_entities = raw_groundtruth.get("entities", [])
                        processed_entities = []
                        for entity_item in raw_entities:
                            if isinstance(entity_item, dict):
                                processed_entities.append({
                                    "entity_type": entity_item.get("entity_type", None),
                                    "entity": entity_item.get("entity", None),
                                    "start": entity_item.get("start", None),
                                    "end": entity_item.get("end", None),
                                })
                        raw_word_timestamps = raw_groundtruth.get("word_timestamp", [])
                        processed_word_timestamps = []
                        for word_item in raw_word_timestamps:
                            if isinstance(word_item, dict):
                                processed_word_timestamps.append({
                                    "word": word_item.get("word", None),
                                    "start": word_item.get("start", None),
                                    "end": word_item.get("end", None),
                                })
                        example["groundtruth"] = {
                            "entities": processed_entities,
                            "word_timestamp": processed_word_timestamps,
                        }

                    elif self.config.name == "speaker_number_estimation":
                        raw_groundtruth = data.get("groundtruth", None)
                        processed_groundtruth = []
                        if raw_groundtruth is not None:
                            if isinstance(raw_groundtruth, list):
                                processed_groundtruth = [int(x) for x in raw_groundtruth if isinstance(x, (int, float))]
                            elif isinstance(raw_groundtruth, (int, float)):
                                processed_groundtruth = [int(raw_groundtruth)]

                        example["groundtruth"] = processed_groundtruth

                    elif self.config.name == "entire_duration":
                        example["groundtruth"] = data.get("groundtruth", None) # Assuming float

                    elif self.config.name == "event_duration":
                        example["groundtruth"] = data.get("groundtruth", None)
                        example["answer_type"] = data.get("answer_type", None)

                    elif self.config.name == "emotion_ranking":
                        example["type"] = data.get("type", None)
                        example["correct_option"] = data.get("correct_option", None)
                        example["option_A"] = data.get("option_A", None)
                        example["option_B"] = data.get("option_B", None)
                        example["option_C"] = data.get("option_C", None)
                        example["option_D"] = data.get("option_D", None)
                        example["option_E"] = data.get("option_E", None)
                        example["correct_answer"] = data.get("correct_answer", None)

                    elif self.config.name == "emotion_reasoning":
                        example["type"] = data.get("type", None)
                        example["correct_option"] = data.get("correct_option", None)
                        example["option_A"] = data.get("option_A", None)
                        example["option_B"] = data.get("option_B", None)
                        example["option_C"] = data.get("option_C", None)
                        example["option_D"] = data.get("option_D", None)
                        example["correct_answer"] = data.get("correct_answer", None)

                    else:
                        raise ValueError(f"Unknown config name: {self.config.name}. This should not happen if BUILDER_CONFIGS and _info are consistent.")

                    yield id_, example

                except Exception as e:
                    print(f"Error processing example {id_} in {filepath} for config {self.config.name}: {e}")