File size: 3,066 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
"""Offline, lightweight MFCC-style log-spectrum/DCT analysis of local WAVs."""
import math
import pathlib
import wave


N = 256
HOP = 128
BANDS = 20
WINDOW = [0.54 - 0.46 * math.cos(2 * math.pi * i / (N - 1)) for i in range(N)]
COS = [[math.cos(2 * math.pi * k * i / N) for i in range(N)] for k in range(1, N // 2 + 1)]
SIN = [[math.sin(2 * math.pi * k * i / N) for i in range(N)] for k in range(1, N // 2 + 1)]


def samples_from_wav(path):
    with wave.open(str(path), "rb") as wav:
        width = wav.getsampwidth()
        channels = wav.getnchannels()
        raw = wav.readframes(wav.getnframes())
    assert width in (1, 2), f"unsupported sample width in {path}"
    data = []
    stride = width * channels
    for offset in range(0, len(raw), stride):
        channel_values = []
        for channel in range(channels):
            chunk = raw[offset + channel * width:offset + (channel + 1) * width]
            value = int.from_bytes(chunk, "little", signed=(width == 2))
            channel_values.append((value - 128) / 128 if width == 1 else value / 32768)
        data.append(sum(channel_values) / channels)
    return data


def feature(path):
    samples = samples_from_wav(path)
    starts = range(0, max(1, len(samples) - N + 1), HOP)
    frames = []
    for start in starts:
        frame = [(samples[start + i] if start + i < len(samples) else 0) * WINDOW[i] for i in range(N)]
        powers = []
        for cosine, sine in zip(COS, SIN):
            re = sum(x * c for x, c in zip(frame, cosine))
            im = sum(x * s for x, s in zip(frame, sine))
            powers.append(re * re + im * im)
        # Log-spaced spectral bands approximate a mel filter bank without external libraries.
        edges = [int(round(math.exp(math.log(1) + i / BANDS * math.log(len(powers))))) for i in range(BANDS + 1)]
        logs = [math.log1p(sum(powers[max(0, edges[i]-1):max(edges[i], edges[i+1])])) for i in range(BANDS)]
        frames.append([
            sum(value * math.cos(math.pi * coefficient * (band + .5) / BANDS)
                for band, value in enumerate(logs)) / BANDS
            for coefficient in range(13)
        ])
    return [sum(frame[i] for frame in frames) / len(frames) for i in range(13)]


root = pathlib.Path("Audio_Speech_Actors_01-24")
by_emotion = {"01": [], "03": []}
for path in sorted(root.rglob("*.wav")):
    parts = path.stem.split("-")
    if len(parts) >= 7 and parts[2] in by_emotion:
        by_emotion[parts[2]].append(feature(path))


def mean_features(items):
    assert items, "both target emotions need audio files"
    return [sum(row[i] for row in items) / len(items) for i in range(13)]


neutral = mean_features(by_emotion["01"])
happy = mean_features(by_emotion["03"])
diff = [round(abs(a - b), 3) for a, b in zip(neutral, happy)]
max_dim = max(range(13), key=lambda index: diff[index]) + 1
print(f'neutral_count: {len(by_emotion["01"])}')
print(f'happy_count: {len(by_emotion["03"])}')
print("mfcc_diff: [" + ", ".join(f"{value:.3f}" for value in diff) + "]")
print(f"max_diff_dim: {max_dim}")