File size: 3,486 Bytes
1a3acb4
e72bdde
1a3acb4
 
e72bdde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a3acb4
e72bdde
 
1a3acb4
e72bdde
 
 
 
 
 
1a3acb4
e72bdde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""emo_data_prep.py v2 — R3 emotion-tagged training data.
Rows: "Speaker 0: <emotion> {transcription}" with audio = the acted clip (24 kHz) and
voice_prompts = [a DIFFERENT clip of the SAME actor+emotion] (list form, matching DailyTalk's
schema). Mixed with a DailyTalk sample (untagged) to prevent forgetting.
Outputs: /data/mixed_train.jsonl, /data/mixed_val.jsonl. Prints EMO PREP DONE.
"""
import json, os, random, sys
import numpy as np
import soundfile as sf
import librosa

SR = 24000
TAG = {"ANGRY": "<angry>", "SAD": "<sad>", "HAPPY": "<happy>",
       "NEUTRAL": "<neutral>", "DISGUST": "<disgust>", "FEARFUL": "<fearful>"}
CAP_PER_EMOTION = 250
DT_SAMPLE = 300
VAL_EMOTION = 45
VAL_DT = 15

random.seed(1234)


def main():
    from datasets import load_dataset
    ds = load_dataset("zenitsu09/CREMAD-emotion-transcribed", split="train")
    print(f"CREMA-D loaded: {len(ds)} rows", flush=True)

    os.makedirs("/emo/audio", exist_ok=True)
    rows = []
    count = {}
    n_emo = 0
    for row in ds:
        emo_raw = str(row["emotion"]).upper()
        emo = "ANGRY" if emo_raw.startswith("ANG") else emo_raw
        if emo not in TAG:
            continue
        if count.get(emo, 0) >= CAP_PER_EMOTION:
            continue
        count[emo] = count.get(emo, 0) + 1
        arr = np.asarray(row["audio"]["array"], dtype=np.float32)
        sr = row["audio"]["sampling_rate"]
        if sr != SR:
            arr = librosa.resample(arr, orig_sr=sr, target_sr=SR)
        text = str(row["transcription"]).strip()
        if text.startswith("<"):
            text = text.split(">", 1)[-1].strip()
        if not text or len(text) < 4:
            continue
        n_emo += 1
        fn = f"/emo/audio/e{n_emo:05d}_{emo.lower()}.wav"
        sf.write(fn, arr.astype(np.float32), SR)
        actor = str(row["original_filename"]).split("_")[0]
        rows.append({"text": f"Speaker 0: {TAG[emo]} {text}", "audio": fn,
                     "actor": actor, "emo": emo})
    print(f"emotion rows: {n_emo} ({count})", flush=True)

    groups = {}
    for r in rows:
        groups.setdefault((r["actor"], r["emo"]), []).append(r)
    paired = 0
    for r in rows:
        pool = [x for x in groups.get((r["actor"], r["emo"]), []) if x is not r]
        if pool:
            r["voice_prompts"] = [random.choice(pool)["audio"]]
            paired += 1
        else:
            r["voice_prompts"] = [r["audio"]]
    print(f"paired with different same-actor-same-emotion clip: {paired}/{n_emo}", flush=True)

    dt = [json.loads(l) for l in open("/data/train.jsonl")]
    random.shuffle(dt)
    dt_sample = dt[:DT_SAMPLE]
    print(f"dailytalk sample: {len(dt_sample)}", flush=True)
    assert all(isinstance(r.get("voice_prompts"), list) for r in dt_sample[:5]), "dt schema check"

    emo_rows = [{"text": r["text"], "audio": r["audio"], "voice_prompts": r["voice_prompts"]}
                for r in rows]
    random.shuffle(emo_rows)
    val = emo_rows[:VAL_EMOTION] + dt_sample[:VAL_DT]
    train = emo_rows[VAL_EMOTION:] + dt_sample[VAL_DT:]
    random.shuffle(train)
    random.shuffle(val)
    with open("/data/mixed_train.jsonl", "w") as f:
        for r in train:
            f.write(json.dumps(r) + "\n")
    with open("/data/mixed_val.jsonl", "w") as f:
        for r in val:
            f.write(json.dumps(r) + "\n")
    print(f"MIXED TRAIN {len(train)} / VAL {len(val)}", flush=True)
    print("EMO PREP DONE", flush=True)


if __name__ == "__main__":
    main()