ACloudCenter commited on
Commit
d6a4fb7
·
verified ·
1 Parent(s): d23a164

Emotion probe R1: CREMA-D same-actor emotion refs (NEU/ANG/SAD × 2 actors), same dialogue, 4 arms + F0/energy objective garnish

Browse files
Files changed (1) hide show
  1. emotion_probe.py +154 -0
emotion_probe.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """emotion_probe.py v1 — R1 zero-training emotion steering probe.
2
+ Question: does swapping the reference clip's EMOTION (same actor, CREMA-D same-sentence recordings)
3
+ change the generated speech's prosody? Arms: (N,N), (A,A), (S,S), (A,S) across the same 4-turn dialogue.
4
+ Objective garnish: mean F0 (yin) + RMS energy per generated wav. The ear check is the real instrument.
5
+ Prints EMOTION PROBE DONE. Pushes emo_*.wav + summary to ACloudCenter/vibevoice-emotion-probe.
6
+ """
7
+ import importlib.util
8
+ import json, os, sys, time
9
+ sys.path.insert(0, "/VibeVoice-classic")
10
+
11
+ import numpy as np
12
+ import soundfile as sf
13
+ import librosa
14
+ import torch
15
+ from huggingface_hub import HfApi, hf_hub_download
16
+ from vibevoice.modular.modeling_vibevoice_inference import VibeVoiceForConditionalGenerationInference
17
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor
18
+
19
+ _spec = importlib.util.spec_from_file_location("vibevoice.modular.lora_loading", "/vv-main/vibevoice/modular/lora_loading.py")
20
+ assert _spec is not None and _spec.loader is not None
21
+ _lora_loading = importlib.util.module_from_spec(_spec)
22
+ sys.modules[_spec.name] = _lora_loading
23
+ _spec.loader.exec_module(_lora_loading)
24
+ load_lora_assets = _lora_loading.load_lora_assets
25
+
26
+ MODEL = "microsoft/VibeVoice-1.5B"
27
+ ADAPTER_REPO = "ACloudCenter/vibevoice-lora-joint"
28
+ ADAPTER_SUB = "fullv3/lora"
29
+ OUT_REPO = "ACloudCenter/vibevoice-emotion-probe"
30
+ SR = 24000
31
+ device = "cuda"
32
+
33
+ DIALOGUE = (
34
+ "Speaker 1: You said you'd be home by six. It's almost nine.\n"
35
+ "Speaker 2: The meeting ran over, I told you it would.\n"
36
+ "Speaker 1: I sat here worrying for three hours.\n"
37
+ "Speaker 2: I'm sorry. Next time I'll call the moment it ends."
38
+ )
39
+
40
+ EMOS = ["NEU", "ANG", "SAD"] # CREMA-D emotion codes
41
+ ARMS = [("NEU", "NEU"), ("ANG", "ANG"), ("SAD", "SAD"), ("ANG", "SAD")]
42
+
43
+
44
+ def download_adapter(dest="/adapter"):
45
+ api = HfApi()
46
+ files = [f for f in api.list_repo_files(ADAPTER_REPO, repo_type="model") if f.startswith(ADAPTER_SUB + "/")]
47
+ assert len(files) >= 4, files
48
+ for f in files:
49
+ local = hf_hub_download(ADAPTER_REPO, f, repo_type="model")
50
+ with open(local, "rb") as fh:
51
+ data = fh.read()
52
+ name = f[len(ADAPTER_SUB) + 1:]
53
+ op = os.path.join(dest, name)
54
+ os.makedirs(os.path.dirname(op), exist_ok=True)
55
+ with open(op, "wb") as fh:
56
+ fh.write(data)
57
+ assert os.path.isfile(op) and os.path.getsize(op) == len(data)
58
+ print("ADAPTER OK", flush=True)
59
+
60
+
61
+ def build_emotion_refs():
62
+ """Load CREMA-D, pick 2 actors with >=2 clips in each of NEU/ANG/SAD, build concat prompts."""
63
+ from datasets import load_dataset
64
+ ds = load_dataset("zenitsu09/CREMAD-emotion-transcribed", split="train")
65
+ print(f"CREMA-D loaded: {len(ds)} rows", flush=True)
66
+ by_actor_emo = {}
67
+ for row in ds:
68
+ actor = str(row["original_filename"]).split("_")[0]
69
+ emo = str(row["emotion"]).upper()
70
+ key = (actor, emo)
71
+ if key not in by_actor_emo:
72
+ by_actor_emo[key] = []
73
+ if len(by_actor_emo[key]) < 3:
74
+ by_actor_emo[key].append(row["audio"])
75
+ actors = sorted({a for (a, e) in by_actor_emo if all(by_actor_emo.get((a, e)) for e in EMOS)})
76
+ print(f"actors with NEU+ANG+SAD: {len(actors)}", flush=True)
77
+ assert len(actors) >= 2, f"need 2 actors, found {len(actors)}"
78
+ os.makedirs("/refs", exist_ok=True)
79
+ prompts = {}
80
+ for actor in actors[:2]:
81
+ for emo in EMOS:
82
+ clips = []
83
+ for item in by_actor_emo[(actor, emo)]:
84
+ arr = item["array"]
85
+ sr = item["sampling_rate"]
86
+ if sr != SR:
87
+ arr = librosa.resample(arr.astype(np.float32), orig_sr=sr, target_sr=SR)
88
+ clips.append(arr.astype(np.float32))
89
+ gap = np.zeros(int(0.3 * SR), dtype=np.float32)
90
+ prompt = np.concatenate([clips[0], gap, clips[1], gap, clips[2]])[: int(8.0 * SR)]
91
+ path = f"/refs/{actor}_{emo}.wav"
92
+ sf.write(path, prompt, SR)
93
+ prompts[(actor, emo)] = path
94
+ print(f"REF {path}: {len(prompt)/SR:.1f}s from {len(clips)} clips", flush=True)
95
+ return actors[:2], prompts
96
+
97
+
98
+ def f0_energy(wav):
99
+ f0, _, _ = librosa.pyin(wav.astype(np.float64), fmin=60, fmax=400, sr=SR, frame_length=1024)
100
+ f0v = f0[~np.isnan(f0)]
101
+ return (round(float(np.mean(f0v)), 1) if len(f0v) else None,
102
+ round(float(np.sqrt(np.mean(wav ** 2))), 4))
103
+
104
+
105
+ def main():
106
+ api = HfApi()
107
+ print("EMOTION PROBE v1", flush=True)
108
+ download_adapter()
109
+ actors, prompts = build_emotion_refs()
110
+ a1, a2 = actors
111
+
112
+ model = VibeVoiceForConditionalGenerationInference.from_pretrained(
113
+ MODEL, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True,
114
+ attn_implementation="sdpa").to(device).eval()
115
+ report = load_lora_assets(model, "/adapter")
116
+ assert report.language_model and report.diffusion_head_full, "adapter load failed"
117
+ model.set_ddpm_inference_steps(num_steps=10)
118
+ print("MODEL LOADED (joint adapter)", flush=True)
119
+
120
+ proc = VibeVoiceProcessor.from_pretrained(MODEL)
121
+ os.makedirs("/out", exist_ok=True)
122
+
123
+ results = []
124
+ for e1, e2 in ARMS:
125
+ arm = f"{e1}_{e2}"
126
+ refs = [prompts[(a1, e1)], prompts[(a2, e2)]]
127
+ t0 = time.time()
128
+ with torch.inference_mode():
129
+ inputs = proc(text=[DIALOGUE], voice_samples=[refs],
130
+ padding=True, return_tensors="pt", return_attention_mask=True)
131
+ out = model.generate(**inputs, max_new_tokens=None, cfg_scale=1.3,
132
+ tokenizer=proc.tokenizer, generation_config={"do_sample": False})
133
+ gen_s = time.time() - t0
134
+ fn = f"emo_{arm}.wav"
135
+ proc.save_audio(out.speech_outputs[0], output_path=f"/out/{fn}")
136
+ wav = np.asarray(sf.read(f"/out/{fn}", dtype="float32")[0], dtype=np.float32)
137
+ audio_s = len(wav) / SR
138
+ f0, rms = f0_energy(wav)
139
+ results.append({"arm": arm, "refs": f"S1={a1}_{e1},S2={a2}_{e2}",
140
+ "audio_s": round(audio_s, 1), "gen_s": round(gen_s, 1),
141
+ "mean_f0": f0, "rms": rms})
142
+ api.upload_file(path_or_fileobj=f"/out/{fn}", path_in_repo=fn, repo_id=OUT_REPO)
143
+ print(f"{arm}: dur {audio_s:.1f}s f0 {f0} rms {rms}", flush=True)
144
+ torch.cuda.empty_cache()
145
+
146
+ with open("/out/summary.json", "w") as f:
147
+ json.dump({"actors": [a1, a2], "dialogue": DIALOGUE, "results": results}, f, indent=1)
148
+ api.upload_file(path_or_fileobj="/out/summary.json", path_in_repo="summary.json", repo_id=OUT_REPO)
149
+ print("SUMMARY:", json.dumps(results), flush=True)
150
+ print("EMOTION PROBE DONE", flush=True)
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()