File size: 11,391 Bytes
f1ef7e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
"""
CREMA-D metadata preparation script for the capstone sentiment analysis module.

This script scans CREMA-D audio files, extracts labels from filenames, maps them
to the project's unified emotion/sentiment labels, and creates a clean metadata
CSV for training, evaluation, and inference.

Run from ml-services:

    python -m src.data.cremad_dataset

Expected input:
    ml-services/data/raw/cremad/AudioWAV/*.wav

Generated outputs:
    ml-services/data/processed/cremad_metadata.csv
    ml-services/data/processed/cremad_summary.json
"""

import argparse
import json
import random
from collections import Counter, defaultdict
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Dict, List, Tuple

import pandas as pd

from src.data.label_mapping import (
    is_negative_emotion,
    map_cremad_emotion_code,
    map_cremad_intensity_code,
    map_emotion_to_sentiment,
)


PROJECT_ROOT = Path(__file__).resolve().parents[3]
ML_SERVICES_ROOT = PROJECT_ROOT / "ml-services"

DEFAULT_AUDIO_DIR = ML_SERVICES_ROOT / "data" / "raw" / "cremad" / "AudioWAV"
DEFAULT_OUTPUT_CSV = ML_SERVICES_ROOT / "data" / "processed" / "cremad_metadata.csv"
DEFAULT_OUTPUT_SUMMARY = ML_SERVICES_ROOT / "data" / "processed" / "cremad_summary.json"

RANDOM_SEED = 42


@dataclass
class CremadAudioRecord:
    """
    One parsed CREMA-D audio file record.

    CREMA-D filenames follow this structure:
        ActorID_SentenceCode_EmotionCode_IntensityCode.wav

    Example:
        1001_DFA_ANG_XX.wav
    """

    file_path: str
    filename: str
    actor_id: int
    sentence_code: str
    emotion_code: str
    intensity_code: str
    emotion_label: str
    sentiment_label: str
    intensity_label: str
    is_negative: bool
    split: str = "unassigned"


def parse_cremad_filename(file_path: Path) -> CremadAudioRecord:
    """
    Parse a CREMA-D filename and return a structured metadata record.

    Args:
        file_path: Path to one CREMA-D .wav file.

    Returns:
        CremadAudioRecord containing labels and metadata.

    Raises:
        ValueError: If the filename does not match the expected CREMA-D format.
    """
    filename = file_path.name
    stem = file_path.stem
    parts = stem.split("_")

    if len(parts) != 4:
        raise ValueError(
            f"Invalid CREMA-D filename format: {filename}. "
            "Expected format: ActorID_SentenceCode_EmotionCode_IntensityCode.wav"
        )

    actor_id_raw, sentence_code, emotion_code, intensity_code = parts

    try:
        actor_id = int(actor_id_raw)
    except ValueError as exc:
        raise ValueError(f"Invalid actor ID in filename: {filename}") from exc

    emotion = map_cremad_emotion_code(emotion_code)
    sentiment = map_emotion_to_sentiment(emotion)
    intensity = map_cremad_intensity_code(intensity_code)

    relative_file_path = file_path.relative_to(ML_SERVICES_ROOT)

    return CremadAudioRecord(

        file_path=str(relative_file_path),
        filename=filename,
        actor_id=actor_id,
        sentence_code=sentence_code,
        emotion_code=emotion_code.upper(),
        intensity_code=intensity_code.upper(),
        emotion_label=emotion.value,
        sentiment_label=sentiment.value,
        intensity_label=intensity,
        is_negative=is_negative_emotion(emotion),
    )


def scan_cremad_audio_files(audio_dir: Path) -> Tuple[List[CremadAudioRecord], List[str]]:
    """
    Scan CREMA-D audio files and parse metadata from filenames.

    Args:
        audio_dir: Directory containing CREMA-D .wav files.

    Returns:
        A tuple of valid records and warning messages.
    """
    if not audio_dir.exists():
        raise FileNotFoundError(
            f"CREMA-D audio directory not found: {audio_dir}\n"
            "Place the AudioWAV folder inside ml-services/data/raw/cremad/"
        )

    wav_files = sorted(audio_dir.glob("*.wav"))

    if not wav_files:
        raise FileNotFoundError(f"No .wav files found in: {audio_dir}")

    records: List[CremadAudioRecord] = []
    warnings: List[str] = []

    for file_path in wav_files:
        try:
            records.append(parse_cremad_filename(file_path))
        except ValueError as exc:
            warnings.append(str(exc))

    if not records:
        raise ValueError("No valid CREMA-D records were parsed.")

    return records, warnings


def create_speaker_independent_splits(
    records: List[CremadAudioRecord],
    train_ratio: float = 0.70,
    validation_ratio: float = 0.15,
    test_ratio: float = 0.15,
    seed: int = RANDOM_SEED,
) -> List[CremadAudioRecord]:
    """
    Assign train/validation/test splits by actor ID.

    This is important for professional ML evaluation because the same speaker
    should not appear in both training and testing. If the same actor appears
    across splits, the model may look better than it really is because it has
    already learned that speaker's voice characteristics.

    Args:
        records: Parsed CREMA-D records.
        train_ratio: Percentage of actors assigned to training.
        validation_ratio: Percentage of actors assigned to validation.
        test_ratio: Percentage of actors assigned to testing.
        seed: Random seed for reproducibility.

    Returns:
        Records with the split field assigned.
    """
    ratio_sum = train_ratio + validation_ratio + test_ratio
    if abs(ratio_sum - 1.0) > 1e-6:
        raise ValueError("train_ratio + validation_ratio + test_ratio must equal 1.0")

    actor_ids = sorted({record.actor_id for record in records})

    random.seed(seed)
    random.shuffle(actor_ids)

    total_actors = len(actor_ids)
    train_end = int(total_actors * train_ratio)
    validation_end = train_end + int(total_actors * validation_ratio)

    train_actors = set(actor_ids[:train_end])
    validation_actors = set(actor_ids[train_end:validation_end])
    test_actors = set(actor_ids[validation_end:])

    for record in records:
        if record.actor_id in train_actors:
            record.split = "train"
        elif record.actor_id in validation_actors:
            record.split = "validation"
        elif record.actor_id in test_actors:
            record.split = "test"
        else:
            record.split = "unassigned"

    return records


def records_to_dataframe(records: List[CremadAudioRecord]) -> pd.DataFrame:
    """
    Convert parsed records into a pandas DataFrame.
    """
    dataframe = pd.DataFrame([asdict(record) for record in records])

    ordered_columns = [
        "file_path",
        "filename",
        "actor_id",
        "sentence_code",
        "emotion_code",
        "emotion_label",
        "sentiment_label",
        "intensity_code",
        "intensity_label",
        "is_negative",
        "split",
    ]

    return dataframe[ordered_columns]


def build_dataset_summary(dataframe: pd.DataFrame, warnings: List[str]) -> Dict:
    """
    Build a dataset summary for report writing and debugging.
    """
    split_distribution = dataframe["split"].value_counts().to_dict()
    emotion_distribution = dataframe["emotion_label"].value_counts().to_dict()
    sentiment_distribution = dataframe["sentiment_label"].value_counts().to_dict()

    actors_by_split = {
        split: int(dataframe[dataframe["split"] == split]["actor_id"].nunique())
        for split in sorted(dataframe["split"].unique())
    }

    emotion_by_split = defaultdict(dict)
    for split in sorted(dataframe["split"].unique()):
        split_df = dataframe[dataframe["split"] == split]
        emotion_by_split[split] = split_df["emotion_label"].value_counts().to_dict()

    summary = {
        "dataset_name": "CREMA-D",
        "total_audio_files": int(len(dataframe)),
        "total_actors": int(dataframe["actor_id"].nunique()),
        "split_distribution": split_distribution,
        "actors_by_split": actors_by_split,
        "emotion_distribution": emotion_distribution,
        "sentiment_distribution": sentiment_distribution,
        "emotion_distribution_by_split": dict(emotion_by_split),
        "negative_class_count": int(dataframe["is_negative"].sum()),
        "non_negative_class_count": int((~dataframe["is_negative"]).sum()),
        "warnings_count": len(warnings),
        "warnings": warnings[:20],
    }

    return summary


def save_outputs(
    dataframe: pd.DataFrame,
    summary: Dict,
    output_csv: Path,
    output_summary: Path,
) -> None:
    """
    Save metadata CSV and summary JSON.
    """
    output_csv.parent.mkdir(parents=True, exist_ok=True)
    output_summary.parent.mkdir(parents=True, exist_ok=True)

    dataframe.to_csv(output_csv, index=False)

    with output_summary.open("w", encoding="utf-8") as file:
        json.dump(summary, file, indent=2)


def print_summary(summary: Dict, output_csv: Path, output_summary: Path) -> None:
    """
    Print a readable summary after metadata generation.
    """
    print("\nCREMA-D metadata preparation completed successfully.")
    print("-" * 60)
    print(f"Total audio files: {summary['total_audio_files']}")
    print(f"Total actors: {summary['total_actors']}")
    print(f"Split distribution: {summary['split_distribution']}")
    print(f"Actors by split: {summary['actors_by_split']}")
    print(f"Emotion distribution: {summary['emotion_distribution']}")
    print(f"Sentiment distribution: {summary['sentiment_distribution']}")
    print(f"Warnings: {summary['warnings_count']}")
    print("-" * 60)
    print(f"Saved metadata CSV to: {output_csv}")
    print(f"Saved summary JSON to: {output_summary}\n")


def prepare_cremad_metadata(
    audio_dir: Path = DEFAULT_AUDIO_DIR,
    output_csv: Path = DEFAULT_OUTPUT_CSV,
    output_summary: Path = DEFAULT_OUTPUT_SUMMARY,
) -> pd.DataFrame:
    """
    Main function used by scripts, notebooks, and future pipeline code.

    Args:
        audio_dir: Directory containing CREMA-D .wav files.
        output_csv: Destination path for metadata CSV.
        output_summary: Destination path for summary JSON.

    Returns:
        Metadata DataFrame.
    """
    records, warnings = scan_cremad_audio_files(audio_dir)
    records = create_speaker_independent_splits(records)
    dataframe = records_to_dataframe(records)
    summary = build_dataset_summary(dataframe, warnings)
    save_outputs(dataframe, summary, output_csv, output_summary)
    print_summary(summary, output_csv, output_summary)

    return dataframe


def parse_args() -> argparse.Namespace:
    """
    Parse command-line arguments.
    """
    parser = argparse.ArgumentParser(
        description="Prepare CREMA-D metadata for audio sentiment analysis."
    )

    parser.add_argument(
        "--audio-dir",
        type=Path,
        default=DEFAULT_AUDIO_DIR,
        help="Path to CREMA-D AudioWAV directory.",
    )

    parser.add_argument(
        "--output-csv",
        type=Path,
        default=DEFAULT_OUTPUT_CSV,
        help="Path where the metadata CSV will be saved.",
    )

    parser.add_argument(
        "--output-summary",
        type=Path,
        default=DEFAULT_OUTPUT_SUMMARY,
        help="Path where the dataset summary JSON will be saved.",
    )

    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()
    prepare_cremad_metadata(
        audio_dir=args.audio_dir,
        output_csv=args.output_csv,
        output_summary=args.output_summary,
    )