Initial commit

This commit is contained in:
Kasiaaaaaa committed 2026-09-22 11:52:03 +02:00
commit d89b82be4a
103 files changed
+23110

No files matched your search

+326
View File
@@ -0,0 +1,326 @@
import os
import sys
from resampy import resample
from scipy.signal import resample_poly
import nnresample
import soundfile as sf
import numpy as np
from pick import pick
from pyworld import pyworld as pw
from gender.cosgate import cosgate
import scipy.io as spio
from scipy import interpolate as spi
from tools.load_matrix import loadmat
np.set_printoptions(threshold=sys.maxsize)
def makeStim(options, trial, is_demo=False):
# trial["target"]["sound_file"] = 'dog_green_8.wav'
print "Reading soundfile '{}' as target...\n".format(
trial["target"]["sound_file"])
x, fs = sf.read(os.path.join(
options["target_corpus_path"], trial["target"]["sound_file"]))
# if fs != options["fs"]:
# x = resample(x, fs, options["fs"], filter='kaiser_fast')
# fs = options["fs"]
x_rms = np.sqrt(np.mean(x**2))
options["reference_rms"] = x_rms
if trial["tmr"] < np.inf:
x = (x / x_rms) * 10 ** (trial["tmr"]/20.0)
else:
x = x / x_rms
options["target_delay"] = 750e-3
options["masker_end_delay"] = 250e-3
target = np.array([])
target = np.append(target, np.zeros(
int(np.round(options["target_delay"] * fs))))
target = np.append(target, x)
target = np.append(target, np.zeros(
int(np.round(options["masker_end_delay"] * fs))))
masker, masker_dict = create_masker(options, trial, len(target))
masker_rms = np.sqrt(np.nanmean(masker**2))
if trial["tmr"] < np.inf:
masker = masker / masker_rms
else:
masker = 0 * masker
z = np.add(target, masker)
z_rms = np.sqrt(np.nanmean(z ** 2))
z = z/z_rms * options["reference_rms"]
info = {}
info["masker"] = masker_dict
return z, fs, info
def create_masker(options, trial, n_samples):
fs = options["fs"]
masker_dict = {}
masker = np.array([])
n_chunk = 1
while len(masker) < n_samples:
sound_file, _ = pick(options["masker_corpus"])
# sound_file = 'cat_pink_6.wav'
masker_dict["stim_" + str(n_chunk)] = {}
masker_dict["stim_" + str(n_chunk)]["soundfile"] = sound_file
y, fs = pyworld_process(os.path.join(
options["masker_corpus_path"], sound_file.strip()), trial["voice"]["dF0"], trial["voice"]["dVTL"], options)
# y = y * np.power(10, -options["attenuation_dB"]/20.0)
y = y * 10.0 ** (options["attenuation_dB"]/20)
chunk_duration = np.random.rand() * (options["masker_max_chunk_duration"] -
options["masker_min_chunk_duration"]) + options["masker_min_chunk_duration"]
chunk_duration = np.round(chunk_duration*fs)
chunk_start = np.random.randint(len(y)-chunk_duration)
chunk_ind = chunk_start + np.array([0, chunk_duration-1])
masker_dict["stim_" + str(n_chunk)]["chunk_indices"] = chunk_ind
chunk = y[int(chunk_ind[0]):int(chunk_ind[1])]
chunk = cosgate(chunk, fs, options["masker_chunk_ramp"])
masker = np.append(masker, chunk)
n_chunk = n_chunk + 1
masker = masker[:n_samples]
masker = cosgate(masker, fs, options["masker_ramp"])
return masker, masker_dict
def pyworld_process(wavIn, dF0, dVTL, options):
# dF0 = 0
# dVTL = 0
_, wavIn_file = os.path.split(wavIn)
wavIn_name, _ = os.path.splitext(wavIn_file)
cache_path = options["cache_path"]
wavOut = make_fname(wavIn, dF0, dVTL, cache_path)
if not os.path.exists(wavOut) or options["force_rebuild_straight_output"]:
if not os.path.exists(cache_path):
os.mkdir(cache_path)
mat = os.path.join(cache_path, wavIn_name + ".pyworld.mat")
f0 = []
fs = 0
sp = []
ap = []
x_rms = 0
if os.path.exists(mat):
load_mat = loadmat(mat)
f0 = load_mat['f0']
fs = load_mat['fs']
freq = load_mat['frequencies']
sp = load_mat['sp']
ap = load_mat['ap']
t = load_mat['temporal_positions']
x_rms = load_mat['x_rms']
else:
x, fs = sf.read(wavIn)
# if fs != options['fs']:
# x = resample(x, fs, options["fs"], filter='kaiser_best')
# fs = options["fs"]
_f0, t = pw.dio(x, fs)
f0, sp, ap = pw.wav2world(x, fs)
freq = np.arange(0, np.size(sp, axis=1),
dtype='float64') / (np.size(sp)) * fs/2
x_rms = np.sqrt(np.mean(x**2))
duration = len(x/fs)
# spio.savemat(mat, mdict={'fs': fs, 'f0': f0,
# 'sp': sp, 'ap': ap,
# 'x_rms': x_rms,
# 'frequencies': freq,
# 'temporal_positions': t,
# 'duration': duration
# })
f0 = f0 * 2.0 ** (dF0/12)
mapp = mapp * 2.0 ** -(dVTL/12)
f0 = f0 * mapp
nfft = (sp.shape[1]-1)*2
f = np.arange(sp.shape[1]) / float(nfft) * float(fs)
t = np.arange(sp.shape[0]) / pw.default_frame_period
sp = Fast2DInterp(t, f, sp, type="cubic")(t, f)
ap = Fast2DInterp(t, f, ap, type="cubic")(t, f)
# sp = sp_ap_creation(sp, t, f, mapp)
# ap = sp_ap_creation(ap, t, f, 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)
f0, sp, ap = regularize_arrays(f0, sp, ap)
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))
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
sf.write(wavOut, y, fs)
else:
y, fs = sf.read(wavOut)
return y, fs
def make_fname(wav, f0, vtl, destPath):
_, namext = os.path.split(wav)
name, ext = os.path.splitext(namext)
fname = "{}_dF0{}_dVTL{}{}".format(name, f0, vtl, ext)
fname = os.path.join(destPath, fname)
return fname
def sp_ap_creation(mat, temp, freq, vtl, type='cubic'):
'''
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 type == 'cubic':
f = spi.RectBivariateSpline(temp, freq, mat)
elif type == 'linear':
f = spi.interp2d(freq, temp, mat, kind='linear')
else:
raise ValueError('Interpolant type unknown: "%s"' % type)
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)
def regularize_arrays(*args):
"""
Making sure the arrays passed as arguments are in the right format for pyworld.
"""
out = list()
for x in args:
out.append(np.require(x, requirements='C'))
return tuple(out)
class Fast2DInterp():
"""
Creates an interpolant object based on ``scipy.interpolate.RectBivariateSpline`` but
dealing with out of range values.
The constructor is: ``Fast2DInterp(x, y, z, ofrv=None)`` where ``x`` and ``y``
are 1D arrays and ``z`` is a 2D array. The optional argument ``ofrv`` defines
the value used for out of range inputs. If ``ofrv`` is ``None``, then the
default behaviour of ``RectBivariateSpline`` is kept, i.e. the closest value is
returned.
The default type is ``linear``, which then makes use of ``scipy.interpolate.interp2d``.
With ``cubic``, the ``RectBivariateSpline`` is used.
Note that the class is not so useful in the end when used with ``linear``, but
is useful if you want to use cubic-splines.
"""
def __init__(self, x, y, z, ofrv=None, type='linear'):
self.type = type
if self.type == 'cubic':
self.interpolant = spi.RectBivariateSpline(x, y, z)
elif self.type == 'linear':
self.interpolant = spi.interp2d(y, x, z, kind='linear')
else:
raise ValueError('Interpolant type unknown: "%s"' % type)
self.x_range = (x[0], x[-1])
self.y_range = (y[0], y[-1])
# Out of range value:
self.ofrv = ofrv
def is_in_range(self, w, r):
return np.logical_and(w >= r[0], w <= r[1])
def __call__(self, x, y):
return self.interp(x, y)
def interp_(self, x, y):
if self.type == 'cubic':
return self.interpolant(x, y)
elif self.type == 'linear':
return self.interpolant(y, x)
def interp(self, x, y):
if (np.isscalar(x) or len(x) == 1) and (np.isscalar(y) or len(y) == 1):
if self.ofrv is not None:
if self.is_in_range(x, self.x_range) and self.is_in_range(y, self.y_range):
o = self.interp_(x, y)[0, 0]
else:
o = self.ofrv
else:
o = self.interp_(x, y)[0, 0]
else:
o = self.interp_(x, y)
if self.ofrv is not None:
s = np.logical_and(self.is_in_range(
xx, self.x_range), self.is_in_range(yy, self.y_range))
o[s] = self.ofrv
return o