fast-vibevoice-notes / emo4_data_prep.py
ACloudCenter's picture
emo4 prep: FULL RAVDESS (noise-floor filtered, actor-paired) + clean-filtered CREMA-D + DailyTalk sample → mixed_train/val
0bf8c06 verified
Raw History Blame Contribute Delete
5.34 kB
"""emo4_data_prep.py — top-quality emotion data: CLEAN sources only.
Sources: (1) FULL RAVDESS speech (24 US actors, 8 emotions, 48 kHz lab recordings — keep clips with
noise floor < 0.001), actor-paired voice prompts (different clip, same actor+emotion);
(2) CREMA-D clips that PASS the same noise filter (most fail — that's the point);
(3) DailyTalk sample (untagged, anti-forgetting).
Noise floor = 10th-percentile frame RMS (the metric that separated clean from webcam-mic in the probe).
Outputs: /data/emo4_train.jsonl, /data/emo4_val.jsonl. Prints EMO4 PREP DONE.
"""
import json, os, random, sys
import numpy as np
import soundfile as sf
import librosa
SR = 24000
FLOOR_MAX = 0.001
TAG = {"neutral": "<neutral>", "calm": "<calm>", "happy": "<happy>", "sad": "<sad>",
"angry": "<angry>", "fearful": "<fearful>", "disgust": "<disgust>", "surprised": "<surprised>",
"ANGRY": "<angry>", "SAD": "<sad>", "HAPPY": "<happy>", "NEUTRAL": "<neutral>",
"DISGUST": "<disgust>", "FEARFUL": "<fearful>"}
CAP_RAVDESS = 200 # per emotion (8 × 200 = 1600 max; dataset has 1440 total)
CAP_CREMAD = 100 # per emotion (only clean clips pass the filter)
DT_SAMPLE = 300
VAL_FRAC = 0.06
random.seed(2024)
def noise_floor(wav, sr=SR):
frame = int(0.025 * sr)
n = len(wav) // frame
if n < 4:
return 1.0
fr = wav[: n * frame].reshape(n, frame)
rms = np.sqrt((fr ** 2).mean(axis=1) + 1e-12)
return float(np.percentile(rms, 10))
def resample_to_24k(arr, sr):
arr = np.asarray(arr, dtype=np.float32)
return librosa.resample(arr, orig_sr=sr, target_sr=SR) if sr != SR else arr
def main():
from datasets import load_dataset
os.makedirs("/emo4/audio", exist_ok=True)
rows = []
count = {}
# ---- 1) FULL RAVDESS (clean by construction, still filtered) ----
dsr = load_dataset("confit/ravdess-parquet", "fold1", split="train")
print(f"RAVDESS fold1 train: {len(dsr)} rows", flush=True)
n_rav = 0
kept, rejected = 0, 0
for row in dsr:
emo = str(row["emotion"]).lower()
if emo not in TAG or count.get(("R", emo), 0) >= CAP_RAVDESS:
continue
arr = resample_to_24k(row["audio"]["array"], row["audio"]["sampling_rate"])
if noise_floor(arr) > FLOOR_MAX:
rejected += 1
continue
kept += 1
actor = str(row["file"]).replace(".wav", "").split("-")[-1].zfill(2)
count[("R", emo)] = count.get(("R", emo), 0) + 1
n_rav += 1
fn = f"/emo4/audio/r{n_rav:05d}_{emo}.wav"
sf.write(fn, arr, SR)
rows.append({"text": f"Speaker 0: {TAG[emo]} Don't forget a jacket.",
"audio": fn, "actor": f"R{actor}", "emo": emo})
print(f"RAVDESS kept {kept} (rejected {rejected} noisy) — {n_rav} rows", flush=True)
# ---- 2) CREMA-D, noise-filtered (expect heavy rejection) ----
dsc = load_dataset("zenitsu09/CREMAD-emotion-transcribed", split="train")
n_cre = 0
for row in dsc:
emo_raw = str(row["emotion"]).upper()
emo = "ANGRY" if emo_raw.startswith("ANG") else emo_raw
if emo not in TAG or count.get(("C", emo), 0) >= CAP_CREMAD:
continue
arr = resample_to_24k(row["audio"]["array"], row["audio"]["sampling_rate"])
if noise_floor(arr) > FLOOR_MAX:
continue
count[("C", emo)] = count.get(("C", emo), 0) + 1
n_cre += 1
fn = f"/emo4/audio/c{n_cre:05d}_{emo.lower()}.wav"
sf.write(fn, arr, SR)
text = str(row["transcription"]).strip()
if text.startswith("<"):
text = text.split(">", 1)[-1].strip()
actor = str(row["original_filename"]).split("_")[0]
rows.append({"text": f"Speaker 0: {TAG[emo]} {text}", "audio": fn,
"actor": f"C{actor}", "emo": emo})
print(f"CREMA-D clean survivors: {n_cre} rows", flush=True)
# ---- 3) actor-paired voice prompts (different clip, same actor+emotion) ----
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"actor-paired prompts: {paired}/{len(rows)}", flush=True)
# ---- 4) DailyTalk anti-forgetting sample ----
dt = [json.loads(l) for l in open("/data/train.jsonl")]
random.shuffle(dt)
dt_sample = dt[:DT_SAMPLE]
emo_rows = [{"text": r["text"], "audio": r["audio"], "voice_prompts": r["voice_prompts"]}
for r in rows]
random.shuffle(emo_rows)
n_val = max(60, int(len(emo_rows) * VAL_FRAC))
val = emo_rows[:n_val] + dt_sample[:20]
train = emo_rows[n_val:] + dt_sample[20:]
random.shuffle(train)
random.shuffle(val)
with open("/data/emo4_train.jsonl", "w") as f:
for r in train:
f.write(json.dumps(r) + "\n")
with open("/data/emo4_val.jsonl", "w") as f:
for r in val:
f.write(json.dumps(r) + "\n")
print(f"EMO4 TRAIN {len(train)} / VAL {len(val)}", flush=True)
print("EMO4 PREP DONE", flush=True)
if __name__ == "__main__":
main()