# -------------------------------------------------------------------------- # Authors: # ------ MATlAB ------ # 2010-03-16: Etienne Gaudrain # 2011-10-20: Etienne Gaudrain # 2013-04-22: Etienne Gaudrain # 2017-03-27: Etienne Gaudrain # ------ Python ------ # 2020-02-10: Luke Meyer < l.meyer.5@student.rug.nl > # Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s). # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY # without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see < http: // www.gnu.org/licenses/>. # -------------------------------------------------------------------------- from pyworld import pyworld as pw import numpy as np import os import math import warnings import logging from time import clock from scipy import interpolate import scipy.io as spio from scipy.signal import butter, filtfilt import soundfile as sf from playsound import playsound from resampy import resample import random import collections import matplotlib.pyplot as plt # from audiotsm import phasevocoder # from audiotsm.io.wav import WavReader, WavWriter from tools.load_matrix import loadmat from gender_removeSilence import removeSilence import sys # -- Uncomment for when using the MATLAB/Python API --- # import matlab.engine # future = matlab.engine.start_matlab(async=True) # eng = future.result() # eng.addpath('../Nao-PICKA scripts/Expe_files/lib/STRAIGHTV40_006b') time_logger = logging.getLogger("time_logger") expe_logger = logging.getLogger("expe_logger") def makeStimuli(options, trial): ''' Generates the stimuli files for a given trial and how the trial has been specified ''' x = np.array([]) t = clock() y, fs = straight_process( trial["word"], trial["f0"], trial["vtl"], None, options) y = y * np.power(10, -options["attenuation_dB"]/20.0) stim_time = clock() - t time_logger.info( "Time to generate single stimulus: {}".format(stim_time)) if fs != options["fs"]: y = resample(y, options["fs"], fs, filter="kaiser_fast") options["fs"] = fs # dl = int(round(options["word_duration"]*fs) - len(y)) # if dl > 0: # # Adds padding because the syllable signal is too short # npad_L = int(math.floor(dl/20)) # npad_R = int(dl-npad_L) # nr = int(math.floor(1e-3 * fs)) # y[0:nr] = y[0:nr] * np.linspace(0, 1, num=nr).conj().T # y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T # y = np.concatenate( # (np.zeros((npad_L,)), y, np.zeros((npad_R,)))) # elif dl < 0: # # The synthesised signal is too long # y = y[0:len(y)-dl] # nr = int(math.floor(1e-3 * fs)) # 1 ms linear ramp at the end # y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T # else: # nr = int(math.floor(1e-3 * fs)) # y[0:nr] = y[0:nr] * np.linspace(0, 1, num=nr).conj().T # y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T # x = np.concatenate((x, y)) print "%s -- F0: %5.1f Hz, VTL: %4.2f \n" % ( trial["word"], trial["f0"], trial["vtl"]) if options["lowpass"] != None: b, a = butter(4, (options["lowpass"] * 2.0)/fs, 'low') x = filtfilt(b, a, y) if options["ear"] == 'right': x = np.matrix([np.zeros(np.size(x))], x) elif options["ear"] == 'left': x = np.matrix([x], [np.zeros(np.size(x))]) elif options["ear"] == 'both': x = np.tile(x, (2, 1)).T else: raise ValueError( "Options.ear = {} is not implemented.".format(options["ear"])) return x, fs def straight_process(word, nb_st, vtl, d, options): ''' Generates the individual stimuli files ''' wavIn = os.path.join(options["sound_path"], word + ".wav") wavOut = make_fname( wavIn, nb_st, vtl, d, options["tmp_path"]) y = [] if not os.path.exists(wavOut) or options["force_rebuild_sylls"]: mat = os.path.join(options["sound_path_store"], word + '.pyworld.mat') # Intialise variables so they are accessible in the correct scope f0 = [] fs = 0 sp = [] ap = [] freq = [] temp_pos = [] x_rms = 0 if os.path.exists(mat): # Load the data from the .mat file load_mat = loadmat(mat) f0 = load_mat['f0'] fs = load_mat['fs'] sp = np.array(load_mat['sp']) ap = np.array(load_mat['ap']) # Needed for PyWorld freq = np.array(load_mat["frequencies"]) temp_pos = np.array(load_mat["temporal_positions"]) x_rms = load_mat['x_rms'] else: pass x, fs = sf.read(wavIn) try: x = x[:, 0] except IndexError: x = x[:] x = np.ascontiguousarray(x, dtype=np.float) # --- Using PyWORLD script _f0, t = pw.dio(x, fs) f0 = pw.stonemask(x, _f0, t, fs) sp = pw.cheaptrick(x, f0, t, fs) ap = pw.d4c(x, f0, t, fs) freq = np.arange(0, np.size(sp, axis=1), dtype='float64') / (np.size(sp)) * fs/2 temp_pos = t duration = len(x/fs) x_rms = np.sqrt(np.mean(x**2)) spio.savemat(mat, mdict={'fs': fs, 'f0': f0, 'sp': sp, 'ap': ap, 'x_rms': x_rms, 'frequencies': freq, 'temporal_positions': t, 'duration': duration }) f0[np.where(f0 != 0)] = f0[np.where(f0 != 0)] * \ np.power(2, (nb_st/12)) mapp = 1 * np.power(2, -(vtl/12)) sp = sp_ap_creation(sp, temp_pos, freq, mapp) ap = sp_ap_creation(ap, temp_pos, freq, mapp) if f0.flags['C_CONTIGUOUS']: f0 = np.ascontiguousarray(f0, dtype=np.float) sp = np.ascontiguousarray( sp, dtype=np.float) ap = np.ascontiguousarray( ap, dtype=np.float) y_mat = pw.synthesize(f0, sp, ap, fs) y = np.array(y_mat) y = y / np.sqrt(np.mean(y**2)) * x_rms my = np.amax(np.absolute(y)) y_magnitude_factor = 0 if np.amax(np.absolute(y)) > 1: expe_logger.warn("Output was normalised for {}".format(wavOut)) y_magnitude_factor = my/0.98 y = 0.98 * y / np.amax(np.absolute(y)) else: y_magnitude_factor = 1.0 # y = removeSilence(y, fs, 50e-3) sf.write(wavOut, y, fs) y, fs = sf.read(wavOut) # axes = np.arange(0, len(y)) # ax.plot(axes, y) # fig.savefig("test1.png") # plt.show() else: y, fs = sf.read(wavOut) return y, fs def make_fname(wav, f0, vtl, d, destPath): '''Generates the file name for the new stimulus''' _, namext = os.path.split(wav) name, ext = os.path.splitext(namext) try: int(math.floor(f0)) except ValueError as e: print e if d == None: fname = "%s_GPR%d_VTL%.2f" % ( name, int(math.floor(f0)), vtl) else: fname = "%s_GPR%d_VTL%.2f_D%d" % ( name, int(math.floor(f0)), vtl, int(math.floor(d*1e3))) fname = os.path.join(destPath, fname + ext) return fname def sp_ap_creation(mat, temp, freq, vtl): ''' Interpolates the spectrogram and aperiodicity, respectively using the same temporal positions, but new freq that takes into account the ser value (ser = np.power(2, -dVTL/12)). Ser is usually provided by the defined options in expe_build_conditions ''' # x = np.arange(1, mat.shape[1]+1) # y = np.arange(1, mat.shape[0]+1) # f = interpolate.interp2d(x, y, mat, kind='cubic') f = interpolate.RectBivariateSpline(temp, freq, mat) if vtl != 0.0: interp = f(temp, freq.T/vtl) else: interp = f(temp, freq.T/1.0) return interp # xs = np.arange(1, spe["spectrogram"].shape[1]+1) # ys = np.arange(1, spe["spectrogram"].shape[0]+1) # fis = interp2d(xs, ys, spe["spectrogram"], 'cubic') # spe["spectrogram"] = fis(spe["temporal_positions"], # spe["frequencies"]/ser)