File size: 7,970 Bytes
ef987bb | 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 | import ast
import math
import pathlib
import shutil
import subprocess
import sys
import wave
root = pathlib.Path.cwd()
audio_root = root / "Audio_Speech_Actors_01-24"
def run_candidate():
scripts = [root / 'analyze_ravdess.py']
assert scripts, "missing candidate analysis script"
errors = []
for script in scripts:
proc = subprocess.run(
[sys.executable, str(script)], cwd=root, capture_output=True,
text=True, timeout=30,
)
if proc.returncode == 0 and "neutral_count:" in proc.stdout:
return parse_output(proc.stdout)
errors.append(f"{script.name}: rc={proc.returncode}: {proc.stderr[-200:]}")
raise AssertionError("candidate did not print the required output: " + " | ".join(errors))
def parse_output(text: str):
lines = [line.strip() for line in text.splitlines() if line.strip()]
assert len(lines) == 4, f"expected exactly four lines, got {lines!r}"
assert [line.split(":", 1)[0] for line in lines] == [
"neutral_count", "happy_count", "mfcc_diff", "max_diff_dim"
], "output labels/order do not match the requested four-line contract"
neutral = int(lines[0].split(":", 1)[1])
happy = int(lines[1].split(":", 1)[1])
diff = ast.literal_eval(lines[2].split(":", 1)[1].strip())
dim = int(lines[3].split(":", 1)[1])
assert isinstance(diff, list) and len(diff) == 13, "mfcc_diff must contain 13 values"
assert all(isinstance(v, (int, float)) and math.isfinite(float(v)) and float(v) >= 0 for v in diff), (
"mfcc_diff values must be finite non-negative numbers"
)
assert 1 <= dim <= 13, "max_diff_dim must use one-based dimensions 1..13"
return neutral, happy, tuple(float(v) for v in diff), dim
def fixture(label: str) -> pathlib.Path:
matches = sorted(p for p in audio_root.rglob("*.wav") if p.name.split("-")[2] == label)
assert matches, f"missing fixture emotion code {label}"
return matches[0]
def case_1_recursive_discovery() -> None:
# ENHANCED_CASE_1: recursively nested neutral audio must be discovered and classified by filename.
baseline = run_candidate()
nested_dir = audio_root / "Actor_99" / "nested"
nested_dir.mkdir(parents=True, exist_ok=True)
added = nested_dir / "03-01-01-01-01-01-99.wav"
try:
shutil.copyfile(fixture("01"), added)
changed = run_candidate()
assert changed[0] == baseline[0] + 1, "nested neutral wav did not increase neutral_count"
assert changed[1] == baseline[1], "nested neutral wav must not change happy_count"
finally:
added.unlink(missing_ok=True)
def case_2_non_target_emotion_is_ignored() -> None:
# ENHANCED_CASE_2: a valid wav with an emotion other than 01/03 must not affect either aggregate.
baseline = run_candidate()
added = audio_root / "Actor_01" / "03-01-05-01-01-01-99.wav"
try:
shutil.copyfile(fixture("01"), added)
changed = run_candidate()
assert changed == baseline, "non-neutral/non-happy emotion code changed the requested output"
finally:
added.unlink(missing_ok=True)
def write_tone(path: pathlib.Path, half_period=10, sample_count=960) -> None:
rate = 8000
frames = bytearray()
for index in range(sample_count):
value = 26000 if (index // half_period) % 2 == 0 else -26000
frames.extend(int(value).to_bytes(2, "little", signed=True))
with wave.open(str(path), "wb") as output:
output.setnchannels(1)
output.setsampwidth(2)
output.setframerate(rate)
output.writeframes(bytes(frames))
def case_3_audio_content_changes_features() -> None:
# ENHANCED_CASE_3: feature differences must derive from wav samples, not only file counts/names.
baseline = run_candidate()
added = audio_root / "Actor_01" / "03-01-03-01-01-01-99.wav"
try:
write_tone(added)
changed = run_candidate()
assert changed[0] == baseline[0], "happy tone must not change neutral_count"
assert changed[1] == baseline[1] + 1, "happy tone did not increase happy_count"
assert changed[2] != baseline[2], "substantially different happy audio did not change mfcc_diff"
assert len(set(changed[2])) >= 3, "MFCC-style coefficients should not be copies of one scalar energy"
expected_dim = max(range(13), key=lambda index: changed[2][index]) + 1
assert changed[3] == expected_dim, "max_diff_dim does not identify a maximum difference"
finally:
added.unlink(missing_ok=True)
def case_4_frequency_and_label_invariance():
files = sorted(path for path in audio_root.rglob('*.wav') if path.stem.split('-')[2] in ('01', '03'))
originals = {path: path.read_bytes() for path in files}
try:
for path in files:
write_tone(path, 10 if path.stem.split('-')[2] == '01' else 4)
different = run_candidate()
assert any(value > 0 for value in different[2][1:]), 'equal-amplitude different spectra must produce nontrivial cepstral differences'
for path in files:
write_tone(path, 4 if path.stem.split('-')[2] == '01' else 10)
swapped = run_candidate()
assert swapped[2] == different[2], 'absolute class differences must be invariant to swapping both populations'
for path in files:
write_tone(path, 10)
identical = run_candidate()
assert all(value == 0 for value in identical[2]), 'identical per-file audio in both classes must have zero difference'
assert identical[3] == 1, 'all-zero tie selects the smallest dimension'
finally:
for path, data in originals.items():
path.write_bytes(data)
def case_5_files_have_equal_weight():
# Keep each waveform's exact bytes fixed across two runs. In the first,
# happy contains only A and neutral only B. Replacing one of the two
# neutral files with A must halve the gap between the class means, even
# though B has six times as many samples as A.
neutral = sorted(path for path in audio_root.rglob("*.wav") if path.stem.split("-")[2] == "01")
happy = sorted(path for path in audio_root.rglob("*.wav") if path.stem.split("-")[2] == "03")
assert len(neutral) == len(happy) == 2, "equal-weight control needs two files per class"
originals = {path: path.read_bytes() for path in neutral + happy}
try:
write_tone(happy[0], half_period=10)
short = happy[0].read_bytes()
happy[1].write_bytes(short)
write_tone(neutral[0], half_period=4, sample_count=5760)
neutral[1].write_bytes(neutral[0].read_bytes())
separate = run_candidate()
neutral[0].write_bytes(short)
mixed = run_candidate()
# The displayed gaps round the unrounded values to three decimals.
# Comparing twice the mixture with the original permits three half
# units of rounding error, accounting for both reported quantities.
for index, (gap, half_gap) in enumerate(zip(separate[2], mixed[2]), 1):
assert math.isclose(gap, 2 * half_gap, rel_tol=0.0, abs_tol=0.001500001), (
f"coefficient {index}: expected half of {gap:.3f}, got {half_gap:.3f}; "
"each WAV must have equal weight regardless of duration"
)
finally:
for path, data in originals.items():
path.write_bytes(data)
cases = [
("ENHANCED_CASE_1", case_1_recursive_discovery),
("ENHANCED_CASE_2", case_2_non_target_emotion_is_ignored),
("ENHANCED_CASE_3", case_3_audio_content_changes_features),
("ENHANCED_CASE_4", case_4_frequency_and_label_invariance),
("ENHANCED_CASE_5", case_5_files_have_equal_weight),
]
failed = []
for case_id, validator in cases:
try:
validator()
print(f"{case_id}: PASS")
except Exception as exc:
failed.append(case_id)
print(f"{case_id}: FAIL: {exc}", file=sys.stderr)
if failed:
raise SystemExit(1)
|