File size: 7,264 Bytes
d1d6816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import numpy as np
import matplotlib
from pathlib import Path
import shutil
from tqdm import tqdm
from tools import save_results, VAE_out_put_to_spc, show_spc


def test_reconstruction(encoder, decoder, data, n_sample=5, f=0, path_name="./data/test_reconstruction", save_data=False):
    """Generate and show reconstruction results. Randomly reconstruct 'n_sample' samples in 'data'.
    You can manually set the index of the first reconstructed sample by 'f'.

    Parameters
    ----------
    encoder: keras.engine.functional.Functional
        The VAE encoder.
    decoder: keras.engine.functional.Functional
        Sample rate of the audio to generate.
    data: numpy array
        The VAE decoder.
    n_sample: int
        Number of samples to reconstruct.
    f: int
        Index of the first reconstructed sample.
    path_name: String
        Path to save the results.
    save_data: bool
        Whether save the results.

    Returns
    -------
    """
    if save_data:
        if Path(path_name).exists():
            shutil.rmtree(path_name)
        Path(path_name).mkdir(parents=True, exist_ok=True)
        
    for i in range(n_sample):
        index = np.random.randint(np.shape(data)[0])
        if i == 0:
            index = f
        print("######################################################")
        print(f"index: {index}")

        input = data[index]
        print(f"Original:")
        show_spc(VAE_out_put_to_spc(input))
        if save_data:
            save_results(VAE_out_put_to_spc(input), f"{path_name}/origin_{index}.png", f"{path_name}/origin_{index}.wav")

        input = data[index:index + 1]
        timbre_encode = encoder.predict(input)[0]

        encode = timbre_encode

        reconstruction = decoder.predict(encode)[0]
        reconstruction = VAE_out_put_to_spc(reconstruction)
        reconstruction = np.minimum(5000, reconstruction)
        print(f"Reconstruction:")
        show_spc(reconstruction)
        if save_data:
            save_results(reconstruction, f"{path_name}/reconstruction_{index}.png", f"{path_name}/reconstruction_{index}.wav")
            
            
def test_interpulation(data0, data1, encoder, decoder, path_name = "./data/test_interpolation", save_data=False):
    """Generate new sounds by latent space interpolation.

    Parameters
    ----------
    data0: numpy array
        First input for interpolation.
    data1: numpy array
        Second input for interpolation.
    encoder: keras.engine.functional.Functional
        The VAE encoder.
    decoder: keras.engine.functional.Functional
        Sample rate of the audio to generate.
    path_name: String
        Path to save the results.
    save_data: bool
        Whether save the results.

    Returns
    -------
    """
    if save_data:
        if Path(path_name).exists():
            shutil.rmtree(path_name)
        Path(path_name).mkdir(parents=True, exist_ok=True)

    if save_data:
        save_results(VAE_out_put_to_spc(data0), f"{path_name}/origin_0.png", f"{path_name}/origin_0.wav")
        save_results(VAE_out_put_to_spc(data1), f"{path_name}/origin_1.png", f"{path_name}/origin_1.wav")

    print("First Original:")
    show_spc(VAE_out_put_to_spc(data0))
    print("Second Original:")
    show_spc(VAE_out_put_to_spc(data1))
    print("######################################################")
    print("Interpolations:")
    data0 = np.reshape(data0, (1, 512, 256, 1))
    data1 = np.reshape(data1, (1, 512, 256, 1))
    timbre_encode0 = encoder.predict(data0)[0]
    timbre_encode1 = encoder.predict(data1)[0]

    n_f = 8
    for i in tqdm(range(n_f+1)):
        rate = 1 - i/n_f
        new_timbre = rate * timbre_encode0 + (1-rate) * timbre_encode1
        output = decoder.predict(new_timbre)
    
        spc = np.reshape(VAE_out_put_to_spc(output), (512,256))
        if save_data:
            save_results(spc, f"{path_name}/test_interpolation_{i}.png", f"{path_name}/test_interpolation_{i}.wav")
        show_spc(spc)
            
            
def test_random_sampling(decoder, n_sample=20, mu=np.zeros(20), sigma=np.ones(20), save_data = False, path_name = "./data/test_random_sampling"):
    """Generate new sounds by random sampling in the latent space.

    Parameters
    ----------
    decoder: keras.engine.functional.Functional
        Sample rate of the audio to generate.
    path_name: String
        Path to save the results.
    save_data: bool
        Whether save the results.

    Returns
    -------
    """
    if save_data:
        if Path(path_name).exists():
            shutil.rmtree(path_name)
        Path(path_name).mkdir(parents=True, exist_ok=True)

    for i in tqdm(range(n_sample)):
        off_set = np.random.normal(mu,np.square(sigma))
        new_timbre = np.reshape(off_set, (1,20))
    
        output = decoder.predict(new_timbre)
        
        spc = np.reshape(VAE_out_put_to_spc(output), (512,256))
        if save_data:
            save_results(spc, f"{path_name}/random_sampling_{i}.png", f"{path_name}/random_sampling_{i}.wav")
        show_spc(spc)
            

def test_style_transform(original, encoder, decoder, perceptual_label_predictor, n_samples=10, save_data = False, goal=0, direction=0, path_name = "./data/test_style_transform"):
    """Generate new sounds by latent space interpolation.

    Parameters
    ----------
    original: numpy array
        Original for style transform.
    encoder: keras.engine.functional.Functional
        The VAE encoder.
    decoder: keras.engine.functional.Functional
        Sample rate of the audio to generate.
    perceptual_label_predictor: keras.engine.functional.Functional
        Model that selects the output.
    path_name: String
        Path to save the results.
    save_data: bool
        Whether save the results.

    Returns
    -------
    """
    if save_data:
        if Path(path_name).exists():
            shutil.rmtree(path_name)
        Path(path_name).mkdir(parents=True, exist_ok=True)
        save_results(VAE_out_put_to_spc(original), f"{path_name}/origin.png", f"{path_name}/origin.wav")
    labels_names = ["metallic", "warm", "breathy", "evolving", "aggressiv"]
    timbre_dim = 20

    print("Original:")
    show_spc(VAE_out_put_to_spc(original))
    print("######################################################")
    original_code = encoder.predict(np.reshape(original, (1,512,256,1)))[0]
    new_encodes = np.zeros((n_samples, timbre_dim)) + original_code
    
    new_encodes = [new_encode + np.random.normal(np.zeros(timbre_dim) * 0.2,np.ones(timbre_dim)) for new_encode in new_encodes]
    new_encodes = np.array(new_encodes, dtype=np.float32)
    perceptual_labels = perceptual_label_predictor.predict(new_encodes)[:,goal]

    if direction == 0:
        best_index = np.argmin(perceptual_labels)
        suffix = f"less_{labels_names[goal]}"
    else:
        best_index = np.argmax(perceptual_labels)
        suffix = f"more_{labels_names[goal]}"

    output = decoder.predict(new_encodes[best_index:best_index+1])
        
    spc = np.reshape(VAE_out_put_to_spc(output), (512,256))
    if save_data:
        save_results(spc, f"{path_name}/{suffix}.png", f"{path_name}/{suffix}.wav")
    print("Manipulated (suffix):")
    show_spc(spc)