Skip to content

Commit

Permalink
Add support for numpy arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
mpariente committed Dec 3, 2019
1 parent dde303e commit 3c046ec
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
20 changes: 20 additions & 0 deletions examples/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,23 @@
print('Computing scores for ', test)
scores = metrics(reference, test)
pprint.pprint(scores)

print('\nTrying RELATIVE metrics from numpy arrays: ')

import soundfile as sf
metrics = sm.load('relative', window)

reference = 'data/m2_script1_produced.wav'
ref_wav, rate = sf.read(reference)
tests = ['data/m2_script1_clean.wav',
'data/m2_script1_ipad_confroom1.wav',
'data/m2_script1_produced.wav']
for test in tests:
import pprint
print('Computing scores for ', test)
test_wav, test_rate = sf.read(test)
assert rate == test_rate
scores = metrics(ref_wav, test_wav, rate=rate)
pprint.pprint(scores)


22 changes: 18 additions & 4 deletions speechmetrics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def __init__(self, name, window, hop=None, verbose=False):
def test_window(self, audios, rate):
raise NotImplementedError

def test(self, *test_files):
def test(self, *test_files, array_rate=None):
"""loading sound files and making sure they all have the same lengths
(zero-padding to the largest).
Then, calling the `test_window` function that should be specialised
Expand All @@ -42,7 +42,21 @@ def test(self, *test_files):

for file in test_files:
# Loading sound file
audio, rate = sf.read(file, always_2d=True)
if isinstance(file, str):
audio, rate = sf.read(file, always_2d=True)
else:
rate = array_rate
if rate is None:
raise ValueError('Sampling rate needs to be specified '
'when feeding numpy arrays.')
audio = file
# Standardize shapes
if len(audio.shape) == 1:
audio = audio[:, None]
if len(audio.shape) != 2:
raise ValueError('Please provide 1D or 2D array, received '
'{}D array'.format(len(audio.shape)))

if self.fixed_rate is not None and rate != self.fixed_rate:
if self.verbose:
print(' [%s] preferred is %dkHz rate. resampling'
Expand Down Expand Up @@ -97,10 +111,10 @@ def __add__(self, metric):
def __str__(self):
return 'Metrics: ' + ' '.join([x.name for x in self.metrics])

def __call__(self, *files):
def __call__(self, *files, rate=None):
result = {}
for metric in self.metrics:
result_metric = metric.test(*files)
result_metric = metric.test(*files, array_rate=rate)
for name in result_metric.keys():
result[name] = result_metric[name]
return result
Expand Down

0 comments on commit 3c046ec

Please sign in to comment.