├── tests ├── results.mat └── test_metrics.py ├── pyproject.toml ├── examples ├── 1_speech_16000_Hz.wav ├── 1_processed_16000_Hz.wav ├── 1_noisySpeech_16000_Hz.wav └── examplesForCalculatingMeasures.ipynb ├── pysepm ├── __init__.py ├── util.py ├── reverberationMeasures.py ├── intelligibilityMeasures.py └── qualityMeasures.py ├── setup.py ├── README.md └── LICENSE /tests/results.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmiph2/pysepm/HEAD/tests/results.mat -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "wheel", "Cython","numpy"] 3 | -------------------------------------------------------------------------------- /examples/1_speech_16000_Hz.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmiph2/pysepm/HEAD/examples/1_speech_16000_Hz.wav -------------------------------------------------------------------------------- /examples/1_processed_16000_Hz.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmiph2/pysepm/HEAD/examples/1_processed_16000_Hz.wav -------------------------------------------------------------------------------- /examples/1_noisySpeech_16000_Hz.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmiph2/pysepm/HEAD/examples/1_noisySpeech_16000_Hz.wav -------------------------------------------------------------------------------- /pysepm/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.1' 2 | 3 | 4 | from .qualityMeasures import fwSNRseg,SNRseg,llr,wss,composite,pesq,cepstrum_distance 5 | from .intelligibilityMeasures import stoi,csii,ncm 6 | from .reverberationMeasures import srr_seg,bsd,srmr 7 | 8 | 9 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup,find_packages 2 | 3 | setup( 4 | name='pysepm', 5 | version='0.1', 6 | description='Computes Objective Quality measures', 7 | author='Philipp Schmid', 8 | author_email='scdp@zhaw.ch', 9 | url='https://github.zhaw.ch/scdp/pysepm', 10 | license='MIT', 11 | install_requires=[ 12 | 'numpy', 13 | 'scipy', 14 | 'numba', 15 | 'pystoi', 16 | 'pesq @ https://github.com/ludlows/python-pesq/archive/master.zip#egg=pesq', 17 | 'SRMRpy @ https://github.com/jfsantos/SRMRpy/archive/master.zip#egg=SRMRpy', 18 | ], 19 | classifiers=[ 20 | 'Development Status :: 4 - Beta', 21 | 'Intended Audience :: Science/Research', 22 | 'License :: OSI Approved :: MIT License', 23 | 'Programming Language :: Python :: 3' 24 | ], 25 | packages=find_packages() 26 | ) 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pysepm - Python Speech Enhancement Performance Measures (Quality and Intelligibility) 2 | [![DOI](https://zenodo.org/badge/220233987.svg)](https://zenodo.org/badge/latestdoi/220233987) 3 | 4 | Python implementation of objective quality and intelligibilty measures mentioned in Philipos C. Loizou's great [Speech Enhancement Book](https://www.crcpress.com/Speech-Enhancement-Theory-and-Practice-Second-Edition/Loizou/p/book/9781138075573). The Python implementations are checked with the MATLAB implementations attached to the book (see [Link](https://crcpress.com/downloads/K14513/K14513_CD_Files.zip)) 5 | 6 | # Install with pip 7 | Install pysepm: 8 | ``` 9 | pip3 install https://github.com/schmiph2/pysepm/archive/master.zip 10 | ``` 11 | # Examples 12 | Please find a Jupyter Notebook with examples for all implemented measures in the [examples folder](https://github.com/schmiph2/pysepm/tree/master/examples). 13 | 14 | # Implemented Measures 15 | ## Speech Quality Measures 16 | + Segmental Signal-to-Noise Ratio (SNRseg) 17 | + Frequency-weighted Segmental SNR (fwSNRseg) 18 | + Log-likelihood Ratio (LLR) 19 | + Weighted Spectral Slope (WSS) 20 | + Perceptual Evaluation of Speech Quality (PESQ), ([python-pesq](https://github.com/ludlows/python-pesq) implementation by ludlows) 21 | + Composite Objective Speech Quality (composite) 22 | + Cepstrum Distance Objective Speech Quality Measure (CD) 23 | 24 | ## Speech Intelligibility Measures 25 | + Short-time objective intelligibility (STOI), ([pystoi](https://github.com/mpariente/pystoi) implementation by mpariente) 26 | + Coherence and speech intelligibility index (CSII) 27 | + Normalized-covariance measure (NCM) 28 | 29 | ## Dereverberation Measures (TODO) 30 | + Bark spectral distortion (BSD) 31 | + Scale-invariant signal to distortion ratio (SI-SDR) 32 | -------------------------------------------------------------------------------- /pysepm/util.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.signal import firls, upfirdn 3 | from scipy.signal.windows import kaiser 4 | 5 | from fractions import Fraction 6 | 7 | def extract_overlapped_windows(x,nperseg,noverlap,window=None): 8 | # source: https://github.com/scipy/scipy/blob/v1.2.1/scipy/signal/spectral.py 9 | step = nperseg - noverlap 10 | shape = x.shape[:-1]+((x.shape[-1]-noverlap)//step, nperseg) 11 | strides = x.strides[:-1]+(step*x.strides[-1], x.strides[-1]) 12 | result = np.lib.stride_tricks.as_strided(x, shape=shape, 13 | strides=strides) 14 | if window is not None: 15 | result = window * result 16 | return result 17 | 18 | def resample_matlab_like(x_orig,p,q): 19 | if len(x_orig.shape)>2: 20 | raise ValueError('x must be a vector or 2d matrix') 21 | 22 | if x_orig.shape[0]20.1]=barks[barks>20.1]+0.22*(barks[barks>20.1]-20.1) 31 | return np.squeeze(barks) 32 | 33 | def bark_to_hz(barks): 34 | barks = barks.copy() 35 | barks = np.asanyarray([barks]) 36 | barks[barks<2]=(barks[barks<2]-0.3)/0.85 37 | barks[barks>20.1]=(barks[barks>20.1]+4.422)/1.22 38 | freqs_hz = 1960 * (barks+0.53)/(26.28-barks) 39 | return np.squeeze(freqs_hz) 40 | 41 | def bark_frequencies(n_barks=128, fmin=0.0, fmax=11025.0): 42 | # 'Center freqs' of bark bands - uniformly spaced between limits 43 | min_bark = hz_to_bark(fmin) 44 | max_bark = hz_to_bark(fmax) 45 | 46 | barks = np.linspace(min_bark, max_bark, n_barks) 47 | 48 | return bark_to_hz(barks) 49 | 50 | def barks(fs, n_fft, n_barks=128, fmin=0.0, fmax=None, norm='area', dtype=np.float32): 51 | 52 | if fmax is None: 53 | fmax = float(fs) / 2 54 | 55 | 56 | # Initialize the weights 57 | n_barks = int(n_barks) 58 | weights = np.zeros((n_barks, int(1 + n_fft // 2)), dtype=dtype) 59 | 60 | # Center freqs of each FFT bin 61 | fftfreqs = np.linspace(0,float(fs) / 2,int(1 + n_fft//2), endpoint=True) 62 | 63 | # 'Center freqs' of mel bands - uniformly spaced between limits 64 | bark_f = bark_frequencies(n_barks + 2, fmin=fmin, fmax=fmax) 65 | 66 | fdiff = np.diff(bark_f) 67 | ramps = np.subtract.outer(bark_f, fftfreqs) 68 | 69 | for i in range(n_barks): 70 | # lower and upper slopes for all bins 71 | lower = -ramps[i] / fdiff[i] 72 | upper = ramps[i+2] / fdiff[i+1] 73 | 74 | # .. then intersect them with each other and zero 75 | weights[i] = np.maximum(0, np.minimum(lower, upper)) 76 | 77 | if norm in (1, 'area'): 78 | weightsPerBand=np.sum(weights,1); 79 | for i in range(weights.shape[0]): 80 | weights[i,:]=weights[i,:]/weightsPerBand[i] 81 | return weights 82 | 83 | def bsd(clean_speech, processed_speech, fs, frameLen=0.03, overlap=0.75): 84 | 85 | pre_emphasis_coeff = 0.95 86 | b = np.array([1]) 87 | a = np.array([1,pre_emphasis_coeff]) 88 | clean_speech = scipy.signal.lfilter(b,a,clean_speech) 89 | processed_speech = scipy.signal.lfilter(b,a,processed_speech) 90 | 91 | winlength = round(frameLen*fs) #window length in samples 92 | skiprate = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples 93 | max_freq = fs/2 #maximum bandwidth 94 | n_fft = 2**np.ceil(np.log2(2*winlength)) 95 | n_fftby2 = int(n_fft/2) 96 | num_frames = len(clean_speech)/skiprate-(winlength/skiprate)# number of frames 97 | 98 | hannWin=scipy.signal.windows.hann(winlength)#0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1))) 99 | f,t,Zxx=stft(clean_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False) 100 | clean_power_spec=np.square(np.sum(hannWin)*np.abs(Zxx)) 101 | f,t,Zxx=stft(processed_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False) 102 | enh_power_spec=np.square(np.sum(hannWin)*np.abs(Zxx)) 103 | 104 | bark_filt = barks(fs, n_fft, n_barks=32) 105 | clean_power_spec_bark= np.dot(bark_filt,clean_power_spec) 106 | enh_power_spec_bark= np.dot(bark_filt,enh_power_spec) 107 | 108 | clean_power_spec_bark_2=np.square(clean_power_spec_bark) 109 | diff_power_spec_2 = np.square(clean_power_spec_bark-enh_power_spec_bark) 110 | 111 | bsd = np.mean(np.sum(diff_power_spec_2,axis=0)/np.sum(clean_power_spec_bark_2,axis=0)) 112 | return bsd 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /tests/test_metrics.py: -------------------------------------------------------------------------------- 1 | from scipy.io import wavfile,loadmat 2 | import numpy as np 3 | import sys 4 | sys.path.append("../") 5 | import pysepm as pm 6 | import pytest 7 | import numpy.testing 8 | import librosa 9 | 10 | RTOL = 1e-12 11 | ATOL = 0 12 | 13 | resultsOrig = loadmat("results.mat") 14 | resultsOrig=resultsOrig['results'] 15 | 16 | 17 | 18 | freqs = [44100,22050,16000,8000] 19 | pairs = [['speech','noisySpeech'],['speech','processed']] 20 | testScenarios=[] 21 | pairCounter = 0 22 | for ii in range(1,4): 23 | for f in freqs: 24 | for pair in pairs: 25 | fileNameClean="{}_{}_{}_Hz.wav".format(ii,pair[0],f) 26 | fileNameNoisy="{}_{}_{}_Hz.wav".format(ii,pair[1],f) 27 | testScenarios.append(([fileNameClean,fileNameNoisy],resultsOrig[pairCounter])) 28 | pairCounter=pairCounter+1 29 | 30 | 31 | def load_preprocess_filepair(filePair,resample=False,fs_targ=16000): 32 | fs, cleanSig = wavfile.read('data/'+filePair[0]) 33 | fs, enhancedSig = wavfile.read('data/'+filePair[1]) 34 | 35 | if resample: 36 | if fs_targ == 16000 and fs !=8000: 37 | strParts=filePair[0].split('_') 38 | fileNameClean="{}_{}_{}_Hz.wav".format(strParts[0],strParts[1],16000) 39 | fs, cleanSig = wavfile.read('data/'+fileNameClean) 40 | 41 | strParts=filePair[1].split('_') 42 | fileNameNoisy="{}_{}_{}_Hz.wav".format(strParts[0],strParts[1],16000) 43 | fs, enhancedSig = wavfile.read('data/'+fileNameNoisy) 44 | 45 | elif fs_targ == 16000 and fs == 8000: 46 | pass 47 | else: 48 | 49 | cleanSig = librosa.core.resample(cleanSig, fs, fs_targ) 50 | enhancedSig = librosa.core.resample(enhancedSig, fs, fs_targ) 51 | fs = fs_targ 52 | 53 | return cleanSig,enhancedSig,fs 54 | 55 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 56 | def test_fwSNRseg(filePair,expected_vals): 57 | RTOL = 1e-12 58 | ATOL = 0 59 | 60 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair) 61 | numpy.testing.assert_allclose(pm.fwSNRseg(cleanSig, enhancedSig, fs), expected_vals[0], rtol=RTOL, atol=ATOL) 62 | 63 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 64 | def test_SNRseg(filePair,expected_vals): 65 | RTOL = 1e-12 66 | ATOL = 0 67 | 68 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair) 69 | numpy.testing.assert_allclose(pm.SNRseg(cleanSig, enhancedSig, fs), expected_vals[1], rtol=RTOL, atol=ATOL) 70 | 71 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 72 | def test_llr(filePair,expected_vals): 73 | RTOL = 5e-8 74 | ATOL = 0 75 | 76 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair) 77 | numpy.testing.assert_allclose(pm.llr(cleanSig, enhancedSig, fs), expected_vals[2], rtol=RTOL, atol=ATOL) 78 | 79 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 80 | def test_wss(filePair,expected_vals): 81 | RTOL = 1e-12 82 | ATOL = 0 83 | 84 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair) 85 | numpy.testing.assert_allclose(pm.wss(cleanSig, enhancedSig, fs), expected_vals[3], rtol=RTOL, atol=ATOL) 86 | 87 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 88 | def test_cepstrum_distance(filePair,expected_vals): 89 | RTOL = 1e-8 90 | ATOL = 0 91 | 92 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair) 93 | numpy.testing.assert_allclose(pm.cepstrum_distance(cleanSig, enhancedSig, fs), expected_vals[4], rtol=RTOL, atol=ATOL) 94 | 95 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 96 | def test_stoi(filePair,expected_vals): 97 | RTOL = 5e-3#5e-4 98 | ATOL = 0 99 | 100 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair,True,10e3) 101 | 102 | numpy.testing.assert_allclose(pm.stoi(cleanSig, enhancedSig, fs), expected_vals[5], rtol=RTOL, atol=ATOL) 103 | 104 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 105 | def test_csii(filePair,expected_vals): 106 | RTOL = 5e-4 107 | ATOL = 0 108 | 109 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair) 110 | CSIIh,CSIIm,CSIIl=pm.csii(cleanSig, enhancedSig, fs) 111 | numpy.testing.assert_allclose(CSIIh, expected_vals[6], rtol=RTOL, atol=ATOL) 112 | numpy.testing.assert_allclose(CSIIm, expected_vals[7], rtol=RTOL, atol=ATOL) 113 | numpy.testing.assert_allclose(CSIIl, expected_vals[8], rtol=RTOL, atol=ATOL) 114 | 115 | 116 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 117 | def test_pesq(filePair,expected_vals): 118 | RTOL = 5e-4 119 | ATOL = 0 120 | 121 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair,True,16e3) 122 | pesq_mos,mos_lqo=pm.pesq(cleanSig, enhancedSig, fs) 123 | numpy.testing.assert_allclose(mos_lqo, expected_vals[10], rtol=RTOL, atol=ATOL) 124 | 125 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 126 | def test_composite(filePair,expected_vals): 127 | RTOL = 5e-4 128 | ATOL = 0 129 | 130 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair,True,16e3) 131 | Csig,Cbak,Covl=pm.composite(cleanSig, enhancedSig, fs) 132 | numpy.testing.assert_allclose(Csig, expected_vals[11], rtol=RTOL, atol=ATOL) 133 | numpy.testing.assert_allclose(Cbak, expected_vals[12], rtol=RTOL, atol=ATOL) 134 | numpy.testing.assert_allclose(Covl, expected_vals[13], rtol=RTOL, atol=ATOL) 135 | 136 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 137 | def test_ncm(filePair,expected_vals): 138 | RTOL = 5e-6 139 | ATOL = 0 140 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair,True,16e3) 141 | numpy.testing.assert_allclose(pm.ncm(cleanSig, enhancedSig, fs), expected_vals[14], rtol=RTOL, atol=ATOL) 142 | 143 | 144 | @pytest.mark.parametrize('filePair,expected_vals', testScenarios) 145 | def test_srmr(filePair,expected_vals): 146 | RTOL = 5e-4 147 | ATOL = 0 148 | cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair,True,16e3) 149 | ratio = pm.srmr(enhancedSig, fs) 150 | numpy.testing.assert_allclose(ratio, expected_vals[15], rtol=RTOL, atol=ATOL) 151 | 152 | 153 | #@pytest.mark.parametrize('filePair,expected_vals', testScenarios) 154 | #def test_bsd(filePair,expected_vals): 155 | # cleanSig,enhancedSig,fs=load_preprocess_filepair(filePair) 156 | # bsd = pm.bsd(cleanSig, enhancedSig, fs) 157 | # numpy.testing.assert_allclose(bsd, 1e20, rtol=RTOL, atol=ATOL) 158 | -------------------------------------------------------------------------------- /pysepm/intelligibilityMeasures.py: -------------------------------------------------------------------------------- 1 | from scipy.signal import stft,resample,butter,lfilter,hilbert 2 | from scipy.interpolate import interp1d 3 | from pystoi import stoi as pystoi # https://github.com/mpariente/pystoi 4 | import numpy as np 5 | 6 | from .util import extract_overlapped_windows,resample_matlab_like 7 | 8 | stoi = pystoi 9 | 10 | def fwseg_noise(clean_speech, processed_speech,fs,frameLen=0.03, overlap=0.75): 11 | 12 | clean_length = len(clean_speech) 13 | processed_length = len(processed_speech) 14 | rms_all=np.linalg.norm(clean_speech)/np.sqrt(processed_length) 15 | 16 | winlength = round(frameLen*fs) #window length in samples 17 | skiprate = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples 18 | max_freq = fs/2 #maximum bandwidth 19 | num_crit = 16 # number of critical bands 20 | n_fft = int(2**np.ceil(np.log2(2*winlength))) 21 | n_fftby2 = int(n_fft/2) 22 | 23 | cent_freq=np.zeros((num_crit,)) 24 | bandwidth=np.zeros((num_crit,)) 25 | 26 | # ---------------------------------------------------------------------- 27 | # Critical Band Filter Definitions (Center Frequency and Bandwidths in Hz) 28 | # ---------------------------------------------------------------------- 29 | cent_freq[0] = 150.0000; bandwidth[0] = 100.0000; 30 | cent_freq[1] = 250.000; bandwidth[1] = 100.0000; 31 | cent_freq[2] = 350.000; bandwidth[2] = 100.0000; 32 | cent_freq[3] = 450.000; bandwidth[3] = 110.0000; 33 | cent_freq[4] = 570.000; bandwidth[4] = 120.0000; 34 | cent_freq[5] = 700.000; bandwidth[5] = 140.0000; 35 | cent_freq[6] = 840.000; bandwidth[6] = 150.0000; 36 | cent_freq[7] = 1000.000; bandwidth[7] = 160.000; 37 | cent_freq[8] = 1170.000; bandwidth[8] = 190.000; 38 | cent_freq[9] = 1370.000; bandwidth[9] = 210.000; 39 | cent_freq[10] = 1600.000; bandwidth[10]= 240.000; 40 | cent_freq[11] = 1850.000; bandwidth[11]= 280.000; 41 | cent_freq[12] = 2150.000; bandwidth[12]= 320.000; 42 | cent_freq[13] = 2500.000; bandwidth[13]= 380.000; 43 | cent_freq[14] = 2900.000; bandwidth[14]= 450.000; 44 | cent_freq[15] = 3400.000; bandwidth[15]= 550.000; 45 | 46 | Weight=np.array([0.0192,0.0312,0.0926,0.1031,0.0735,0.0611,0.0495,0.044,0.044,0.049,0.0486,0.0493, 0.049,0.0547,0.0555,0.0493]) 47 | 48 | # ---------------------------------------------------------------------- 49 | # Set up the critical band filters. Note here that Gaussianly shaped 50 | # filters are used. Also, the sum of the filter weights are equivalent 51 | # for each critical band filter. Filter less than -30 dB and set to 52 | # zero. 53 | # ---------------------------------------------------------------------- 54 | 55 | all_f0=np.zeros((num_crit,)) 56 | crit_filter=np.zeros((num_crit,int(n_fftby2))) 57 | g = np.zeros((num_crit,n_fftby2)) 58 | 59 | b = bandwidth; 60 | q = cent_freq/1000; 61 | p = 4*1000*q/b; # Eq. (7) 62 | 63 | #15.625=4000/256 64 | j = np.arange(0,n_fftby2) 65 | 66 | for i in range(num_crit): 67 | g[i,:]=np.abs(1-j*(fs/n_fft)/(q[i]*1000));# Eq. (9) 68 | crit_filter[i,:] = (1+p[i]*g[i,:])*np.exp(-p[i]*g[i,:]);# Eq. (8) 69 | 70 | num_frames = int(clean_length/skiprate-(winlength/skiprate)); # number of frames 71 | start = 0 # starting sample 72 | hannWin = 0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1))) 73 | 74 | f,t,clean_spec=stft(clean_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=False, boundary=None, padded=False) 75 | f,t,processed_spec=stft(processed_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=False, boundary=None, padded=False) 76 | 77 | clean_frames = extract_overlapped_windows(clean_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)],winlength,winlength-skiprate,None) 78 | rms_seg = np.linalg.norm(clean_frames,axis=-1)/np.sqrt(winlength); 79 | rms_db = 20*np.log10(rms_seg/rms_all); 80 | #-------------------------------------------------------------- 81 | # cal r2_high,r2_middle,r2_low 82 | highInd = np.where(rms_db>=0) 83 | highInd = highInd[0] 84 | middleInd = np.where((rms_db>=-10) & (rms_db<0)) 85 | middleInd = middleInd[0] 86 | lowInd = np.where(rms_db<-10) 87 | lowInd = lowInd[0] 88 | 89 | num_high = np.sum(clean_spec[0:n_fftby2,highInd]*np.conj(processed_spec[0:n_fftby2,highInd]),axis=-1) 90 | denx_high = np.sum(np.abs(clean_spec[0:n_fftby2,highInd])**2,axis=-1) 91 | deny_high = np.sum(np.abs(processed_spec[0:n_fftby2,highInd])**2,axis=-1); 92 | 93 | num_middle = np.sum(clean_spec[0:n_fftby2,middleInd]*np.conj(processed_spec[0:n_fftby2,middleInd]),axis=-1) 94 | denx_middle = np.sum(np.abs(clean_spec[0:n_fftby2,middleInd])**2,axis=-1) 95 | deny_middle = np.sum(np.abs(processed_spec[0:n_fftby2,middleInd])**2,axis=-1); 96 | 97 | num_low = np.sum(clean_spec[0:n_fftby2,lowInd]*np.conj(processed_spec[0:n_fftby2,lowInd]),axis=-1) 98 | denx_low = np.sum(np.abs(clean_spec[0:n_fftby2,lowInd])**2,axis=-1) 99 | deny_low = np.sum(np.abs(processed_spec[0:n_fftby2,lowInd])**2,axis=-1); 100 | 101 | num2_high = np.abs(num_high)**2; 102 | r2_high = num2_high/(denx_high*deny_high); 103 | 104 | num2_middle = np.abs(num_middle)**2; 105 | r2_middle = num2_middle/(denx_middle*deny_middle); 106 | 107 | num2_low = np.abs(num_low)**2; 108 | r2_low = num2_low/(denx_low*deny_low); 109 | #-------------------------------------------------------------- 110 | # cal distortion frame by frame 111 | 112 | clean_spec = np.abs(clean_spec); 113 | processed_spec = np.abs(processed_spec)**2; 114 | 115 | W_freq=Weight 116 | 117 | processed_energy = crit_filter.dot((processed_spec[0:n_fftby2,highInd].T*r2_high).T) 118 | de_processed_energy= crit_filter.dot((processed_spec[0:n_fftby2,highInd].T*(1-r2_high)).T) 119 | SDR = processed_energy/de_processed_energy;# Eq 13 in Kates (2005) 120 | SDRlog=10*np.log10(SDR); 121 | SDRlog_lim = SDRlog 122 | SDRlog_lim[SDRlog_lim<-15]=-15 123 | SDRlog_lim[SDRlog_lim>15]=15 # limit between [-15, 15] 124 | Tjm = (SDRlog_lim+15)/30; 125 | distortionh = W_freq.dot(Tjm)/np.sum(W_freq,axis=0) 126 | distortionh[distortionh<0]=0 127 | 128 | 129 | processed_energy = crit_filter.dot((processed_spec[0:n_fftby2,middleInd].T*r2_middle).T) 130 | de_processed_energy= crit_filter.dot((processed_spec[0:n_fftby2,middleInd].T*(1-r2_middle)).T) 131 | SDR = processed_energy/de_processed_energy;# Eq 13 in Kates (2005) 132 | SDRlog=10*np.log10(SDR); 133 | SDRlog_lim = SDRlog 134 | SDRlog_lim[SDRlog_lim<-15]=-15 135 | SDRlog_lim[SDRlog_lim>15]=15 # limit between [-15, 15] 136 | Tjm = (SDRlog_lim+15)/30; 137 | distortionm = W_freq.dot(Tjm)/np.sum(W_freq,axis=0) 138 | distortionm[distortionm<0]=0 139 | 140 | processed_energy = crit_filter.dot((processed_spec[0:n_fftby2,lowInd].T*r2_low).T) 141 | de_processed_energy= crit_filter.dot((processed_spec[0:n_fftby2,lowInd].T*(1-r2_low)).T) 142 | SDR = processed_energy/de_processed_energy;# Eq 13 in Kates (2005) 143 | SDRlog=10*np.log10(SDR); 144 | SDRlog_lim = SDRlog 145 | SDRlog_lim[SDRlog_lim<-15]=-15 146 | SDRlog_lim[SDRlog_lim>15]=15 # limit between [-15, 15] 147 | Tjm = (SDRlog_lim+15)/30; 148 | distortionl = W_freq.dot(Tjm)/np.sum(W_freq,axis=0) 149 | distortionl[distortionl<0]=0 150 | 151 | return distortionh,distortionm,distortionl 152 | 153 | 154 | def csii(clean_speech, processed_speech,sample_rate): 155 | sampleLen= min(len( clean_speech), len( processed_speech)) 156 | clean_speech= clean_speech[0: sampleLen] 157 | processed_speech= processed_speech[0: sampleLen] 158 | vec_CSIIh,vec_CSIIm,vec_CSIIl = fwseg_noise(clean_speech, processed_speech, sample_rate) 159 | 160 | CSIIh=np.mean(vec_CSIIh) 161 | CSIIm=np.mean(vec_CSIIm) 162 | CSIIl=np.mean(vec_CSIIl) 163 | return CSIIh,CSIIm,CSIIl 164 | 165 | 166 | 167 | def get_band(M,Fs): 168 | # This function sets the bandpass filter band edges. 169 | # It assumes that the sampling frequency is 8000 Hz. 170 | A = 165 171 | a = 2.1 172 | K = 1 173 | L = 35 174 | CF = 300; 175 | x_100 = (L/a)*np.log10(CF/A + K) 176 | CF = Fs/2-600 177 | x_8000 = (L/a)*np.log10(CF/A + K); 178 | LX = x_8000 - x_100 179 | x_step = LX / M 180 | x = np.arange(x_100,x_8000+x_step+1e-20,x_step) 181 | if len(x) == M: 182 | np.append(x,x_8000) 183 | 184 | BAND = A*(10**(a*x/L) - K) 185 | return BAND 186 | 187 | def get_ansis(BAND): 188 | fcenter=(BAND[0:-1]+BAND[1:])/2; 189 | 190 | # Data from Table B.1 in "ANSI (1997). S3.5–1997 Methods for Calculation of the Speech Intelligibility 191 | # Index. New York: American National Standards Institute." 192 | f=np.array([150,250,350,450,570,700,840,1000,1170,1370,1600,1850,2150,2500,2900,3400,4000,4800,5800,7000,8500]) 193 | BIF=np.array([0.0192,0.0312,0.0926,0.1031,0.0735,0.0611,0.0495,0.0440,0.0440,0.0490,0.0486,0.0493,0.0490,0.0547,0.0555,0.0493,0.0359,0.0387,0.0256,0.0219,0.0043]) 194 | f_ANSI = interp1d(f,BIF) 195 | ANSIs= f_ANSI(fcenter); 196 | return fcenter,ANSIs 197 | 198 | 199 | def ncm(clean_speech,processed_speech,fs): 200 | 201 | if fs != 8000 and fs != 16000: 202 | raise ValueError('fs must be either 8 kHz or 16 kHz') 203 | 204 | 205 | 206 | x= clean_speech # clean signal 207 | y= processed_speech # noisy signal 208 | F_SIGNAL = fs 209 | 210 | F_ENVELOPE = 32 # limits modulations to 0 Ly: 226 | x = x[0:Ly] 227 | if Ly > Lx: 228 | y = y[0:Lx] 229 | 230 | Lx = len(x); 231 | Ly = len(y); 232 | 233 | X_BANDS = np.zeros((Lx,M_CHANNELS)) 234 | Y_BANDS = np.zeros((Lx,M_CHANNELS)) 235 | 236 | # DESIGN BANDPASS FILTERS 237 | for a in range(M_CHANNELS): 238 | B_bp,A_bp = butter( 4 , np.array([BAND[a],BAND[a+1]])*(2/F_SIGNAL),btype='bandpass') 239 | X_BANDS[:,a] = lfilter( B_bp , A_bp , x ) 240 | Y_BANDS[:,a] = lfilter( B_bp , A_bp , y ) 241 | 242 | gcd = np.gcd(F_SIGNAL, F_ENVELOPE) 243 | # CALCULATE HILBERT ENVELOPES, and resample at F_ENVELOPE Hz 244 | analytic_x = hilbert( X_BANDS,axis=0); 245 | X = np.abs( analytic_x ); 246 | #X = resample( X , round(len(x)/F_SIGNAL*F_ENVELOPE)); 247 | X = resample_matlab_like(X,F_ENVELOPE,F_SIGNAL) 248 | analytic_y = hilbert( Y_BANDS,axis=0); 249 | Y = np.abs( analytic_y ); 250 | #Y = resample( Y , round(len(x)/F_SIGNAL*F_ENVELOPE)); 251 | Y = resample_matlab_like(Y,F_ENVELOPE,F_SIGNAL) 252 | ## ---compute weights based on clean signal's rms envelopes----- 253 | # 254 | Ldx, pp=X.shape 255 | p=3 # power exponent - see Eq. 12 256 | 257 | ro2 = np.zeros((M_CHANNELS,)) 258 | asnr = np.zeros((M_CHANNELS,)) 259 | TI = np.zeros((M_CHANNELS,)) 260 | 261 | for k in range(M_CHANNELS): 262 | x_tmp= X[ :, k] 263 | y_tmp= Y[ :, k] 264 | lambda_x= np.linalg.norm( x_tmp- np.mean( x_tmp))**2 265 | lambda_y= np.linalg.norm( y_tmp- np.mean( y_tmp))**2 266 | lambda_xy= np.sum( (x_tmp- np.mean( x_tmp))*(y_tmp- np.mean( y_tmp))) 267 | ro2[k]= (lambda_xy**2)/ (lambda_x*lambda_y) 268 | asnr[k]= 10*np.log10( (ro2[k]+ 1e-20)/ (1- ro2[k]+ 1e-20)); # Eq.9 in [1] 269 | 270 | if asnr[k]< -15: 271 | asnr[k]= -15 272 | elif asnr[k]> 15: 273 | asnr[k]= 15 274 | 275 | TI[k]= (asnr[k]+ 15)/ 30 # Eq.10 in [1] 276 | 277 | ncm_val= WEIGHT.dot(TI)/np.sum(WEIGHT) # Eq.11 278 | return ncm_val 279 | -------------------------------------------------------------------------------- /pysepm/qualityMeasures.py: -------------------------------------------------------------------------------- 1 | from scipy.signal import stft,get_window,correlate,resample 2 | from scipy.linalg import solve_toeplitz,toeplitz 3 | import scipy 4 | import pesq as pypesq # https://github.com/ludlows/python-pesq 5 | import numpy as np 6 | from numba import jit 7 | from .util import extract_overlapped_windows 8 | 9 | def SNRseg(clean_speech, processed_speech,fs, frameLen=0.03, overlap=0.75): 10 | eps=np.finfo(np.float64).eps 11 | 12 | winlength = round(frameLen*fs) #window length in samples 13 | skiprate = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples 14 | MIN_SNR = -10 # minimum SNR in dB 15 | MAX_SNR = 35 # maximum SNR in dB 16 | 17 | hannWin=0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1))) 18 | clean_speech_framed=extract_overlapped_windows(clean_speech,winlength,winlength-skiprate,hannWin) 19 | processed_speech_framed=extract_overlapped_windows(processed_speech,winlength,winlength-skiprate,hannWin) 20 | 21 | signal_energy = np.power(clean_speech_framed,2).sum(-1) 22 | noise_energy = np.power(clean_speech_framed-processed_speech_framed,2).sum(-1) 23 | 24 | segmental_snr = 10*np.log10(signal_energy/(noise_energy+eps)+eps) 25 | segmental_snr[segmental_snrMAX_SNR]=MAX_SNR 27 | segmental_snr=segmental_snr[:-1] # remove last frame -> not valid 28 | return np.mean(segmental_snr) 29 | 30 | def fwSNRseg(cleanSig, enhancedSig, fs, frameLen=0.03, overlap=0.75): 31 | if cleanSig.shape!=enhancedSig.shape: 32 | raise ValueError('The two signals do not match!') 33 | eps=np.finfo(np.float64).eps 34 | cleanSig=cleanSig.astype(np.float64)+eps 35 | enhancedSig=enhancedSig.astype(np.float64)+eps 36 | winlength = round(frameLen*fs) #window length in samples 37 | skiprate = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples 38 | max_freq = fs/2 #maximum bandwidth 39 | num_crit = 25# number of critical bands 40 | n_fft = 2**np.ceil(np.log2(2*winlength)) 41 | n_fftby2 = int(n_fft/2) 42 | gamma=0.2 43 | 44 | cent_freq=np.zeros((num_crit,)) 45 | bandwidth=np.zeros((num_crit,)) 46 | 47 | cent_freq[0] = 50.0000; bandwidth[0] = 70.0000; 48 | cent_freq[1] = 120.000; bandwidth[1] = 70.0000; 49 | cent_freq[2] = 190.000; bandwidth[2] = 70.0000; 50 | cent_freq[3] = 260.000; bandwidth[3] = 70.0000; 51 | cent_freq[4] = 330.000; bandwidth[4] = 70.0000; 52 | cent_freq[5] = 400.000; bandwidth[5] = 70.0000; 53 | cent_freq[6] = 470.000; bandwidth[6] = 70.0000; 54 | cent_freq[7] = 540.000; bandwidth[7] = 77.3724; 55 | cent_freq[8] = 617.372; bandwidth[8] = 86.0056; 56 | cent_freq[9] = 703.378; bandwidth[9] = 95.3398; 57 | cent_freq[10] = 798.717; bandwidth[10] = 105.411; 58 | cent_freq[11] = 904.128; bandwidth[11] = 116.256; 59 | cent_freq[12] = 1020.38; bandwidth[12] = 127.914; 60 | cent_freq[13] = 1148.30; bandwidth[13] = 140.423; 61 | cent_freq[14] = 1288.72; bandwidth[14] = 153.823; 62 | cent_freq[15] = 1442.54; bandwidth[15] = 168.154; 63 | cent_freq[16] = 1610.70; bandwidth[16] = 183.457; 64 | cent_freq[17] = 1794.16; bandwidth[17] = 199.776; 65 | cent_freq[18] = 1993.93; bandwidth[18] = 217.153; 66 | cent_freq[19] = 2211.08; bandwidth[19] = 235.631; 67 | cent_freq[20] = 2446.71; bandwidth[20] = 255.255; 68 | cent_freq[21] = 2701.97; bandwidth[21] = 276.072; 69 | cent_freq[22] = 2978.04; bandwidth[22] = 298.126; 70 | cent_freq[23] = 3276.17; bandwidth[23] = 321.465; 71 | cent_freq[24] = 3597.63; bandwidth[24] = 346.136; 72 | 73 | 74 | W=np.array([0.003,0.003,0.003,0.007,0.010,0.016,0.016,0.017,0.017,0.022,0.027,0.028,0.030,0.032,0.034,0.035,0.037,0.036,0.036,0.033,0.030,0.029,0.027,0.026, 75 | 0.026]) 76 | 77 | bw_min=bandwidth[0] 78 | min_factor = np.exp (-30.0 / (2.0 * 2.303));# % -30 dB point of filter 79 | 80 | all_f0=np.zeros((num_crit,)) 81 | crit_filter=np.zeros((num_crit,int(n_fftby2))) 82 | j = np.arange(0,n_fftby2) 83 | 84 | 85 | for i in range(num_crit): 86 | f0 = (cent_freq[i] / max_freq) * (n_fftby2) 87 | all_f0[i] = np.floor(f0); 88 | bw = (bandwidth[i] / max_freq) * (n_fftby2); 89 | norm_factor = np.log(bw_min) - np.log(bandwidth[i]); 90 | crit_filter[i,:] = np.exp (-11 *(((j - np.floor(f0))/bw)**2) + norm_factor) 91 | crit_filter[i,:] = crit_filter[i,:]*(crit_filter[i,:] > min_factor) 92 | 93 | num_frames = len(cleanSig)/skiprate-(winlength/skiprate)# number of frames 94 | start = 1 # starting sample 95 | #window = 0.5*(1 - cos(2*pi*(1:winlength).T/(winlength+1))); 96 | 97 | 98 | hannWin=0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1))) 99 | f,t,Zxx=stft(cleanSig[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False) 100 | clean_spec=np.abs(Zxx) 101 | clean_spec=clean_spec[:-1,:] 102 | clean_spec=(clean_spec/clean_spec.sum(0)) 103 | f,t,Zxx=stft(enhancedSig[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False) 104 | enh_spec=np.abs(Zxx) 105 | enh_spec=enh_spec[:-1,:] 106 | enh_spec=(enh_spec/enh_spec.sum(0)) 107 | 108 | clean_energy=(crit_filter.dot(clean_spec)) 109 | processed_energy=(crit_filter.dot(enh_spec)) 110 | error_energy=np.power(clean_energy-processed_energy,2) 111 | error_energy[error_energy35]=35 118 | 119 | return np.mean(distortion) 120 | @jit 121 | def lpcoeff(speech_frame, model_order): 122 | eps=np.finfo(np.float64).eps 123 | # ---------------------------------------------------------- 124 | # (1) Compute Autocorrelation Lags 125 | # ---------------------------------------------------------- 126 | winlength = max(speech_frame.shape) 127 | R = np.zeros((model_order+1,)) 128 | for k in range(model_order+1): 129 | if k==0: 130 | R[k]=np.sum(speech_frame[0:]*speech_frame[0:]) 131 | else: 132 | R[k]=np.sum(speech_frame[0:-k]*speech_frame[k:]) 133 | 134 | 135 | #R=scipy.signal.correlate(speech_frame,speech_frame) 136 | #R=R[len(speech_frame)-1:len(speech_frame)+model_order] 137 | # ---------------------------------------------------------- 138 | # (2) Levinson-Durbin 139 | # ---------------------------------------------------------- 140 | a = np.ones((model_order,)) 141 | a_past = np.ones((model_order,)) 142 | rcoeff = np.zeros((model_order,)) 143 | E = np.zeros((model_order+1,)) 144 | 145 | E[0]=R[0] 146 | 147 | for i in range(0,model_order): 148 | a_past[0:i] = a[0:i] 149 | 150 | sum_term = np.sum(a_past[0:i]*R[i:0:-1]) 151 | 152 | if E[i]==0.0: # prevents zero division error, numba doesn't allow try/except statements 153 | rcoeff[i]= np.inf 154 | else: 155 | rcoeff[i]=(R[i+1] - sum_term) / (E[i]) 156 | 157 | a[i]=rcoeff[i] 158 | #if i==0: 159 | # a[0:i] = a_past[0:i] - rcoeff[i]*np.array([]) 160 | #else: 161 | if i>0: 162 | a[0:i] = a_past[0:i] - rcoeff[i]*a_past[i-1::-1] 163 | 164 | E[i+1]=(1-rcoeff[i]*rcoeff[i])*E[i] 165 | 166 | acorr = R; 167 | refcoeff = rcoeff; 168 | lpparams = np.ones((model_order+1,)) 169 | lpparams[1:] = -a 170 | return(lpparams,R) 171 | 172 | def llr(clean_speech, processed_speech, fs, used_for_composite=False, frameLen=0.03, overlap=0.75): 173 | eps=np.finfo(np.float64).eps 174 | alpha = 0.95 175 | winlength = round(frameLen*fs) #window length in samples 176 | skiprate = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples 177 | if fs<10000: 178 | P = 10 # LPC Analysis Order 179 | else: 180 | P = 16 # this could vary depending on sampling frequency. 181 | 182 | hannWin=0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1))) 183 | clean_speech_framed=extract_overlapped_windows(clean_speech+eps,winlength,winlength-skiprate,hannWin) 184 | processed_speech_framed=extract_overlapped_windows(processed_speech+eps,winlength,winlength-skiprate,hannWin) 185 | numFrames=clean_speech_framed.shape[0] 186 | numerators = np.zeros((numFrames-1,)) 187 | denominators = np.zeros((numFrames-1,)) 188 | 189 | for ii in range(numFrames-1): 190 | A_clean,R_clean=lpcoeff(clean_speech_framed[ii,:],P) 191 | A_proc,R_proc=lpcoeff(processed_speech_framed[ii,:],P) 192 | 193 | numerators[ii]=A_proc.dot(toeplitz(R_clean).dot(A_proc.T)) 194 | denominators[ii]=A_clean.dot(toeplitz(R_clean).dot(A_clean.T)) 195 | 196 | 197 | frac=numerators/(denominators) 198 | frac[np.isnan(frac)]=np.inf 199 | frac[frac<=0]=1000 200 | distortion = np.log(frac) 201 | if not used_for_composite: 202 | distortion[distortion>2]=2 # this line is not in composite measure but in llr matlab implementation of loizou 203 | distortion = np.sort(distortion) 204 | distortion = distortion[:int(round(len(distortion)*alpha))] 205 | return np.mean(distortion) 206 | 207 | 208 | @jit 209 | def find_loc_peaks(slope,energy): 210 | num_crit = len(energy) 211 | 212 | loc_peaks=np.zeros_like(slope) 213 | 214 | for ii in range(len(slope)): 215 | n=ii 216 | if slope[ii]>0: 217 | while ((n 0)): 218 | n=n+1 219 | loc_peaks[ii]=energy[n-1] 220 | else: 221 | while ((n>=0) and (slope[n] <= 0)): 222 | n=n-1 223 | loc_peaks[ii]=energy[n+1] 224 | 225 | return loc_peaks 226 | 227 | 228 | 229 | def wss(clean_speech, processed_speech, fs, frameLen=0.03, overlap=0.75): 230 | 231 | Kmax = 20 # value suggested by Klatt, pg 1280 232 | Klocmax = 1 # value suggested by Klatt, pg 1280 233 | alpha = 0.95 234 | if clean_speech.shape!=processed_speech.shape: 235 | raise ValueError('The two signals do not match!') 236 | eps=np.finfo(np.float64).eps 237 | clean_speech=clean_speech.astype(np.float64)+eps 238 | processed_speech=processed_speech.astype(np.float64)+eps 239 | winlength = round(frameLen*fs) #window length in samples 240 | skiprate = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples 241 | max_freq = fs/2 #maximum bandwidth 242 | num_crit = 25# number of critical bands 243 | n_fft = 2**np.ceil(np.log2(2*winlength)) 244 | n_fftby2 = int(n_fft/2) 245 | 246 | cent_freq=np.zeros((num_crit,)) 247 | bandwidth=np.zeros((num_crit,)) 248 | 249 | cent_freq[0] = 50.0000; bandwidth[0] = 70.0000; 250 | cent_freq[1] = 120.000; bandwidth[1] = 70.0000; 251 | cent_freq[2] = 190.000; bandwidth[2] = 70.0000; 252 | cent_freq[3] = 260.000; bandwidth[3] = 70.0000; 253 | cent_freq[4] = 330.000; bandwidth[4] = 70.0000; 254 | cent_freq[5] = 400.000; bandwidth[5] = 70.0000; 255 | cent_freq[6] = 470.000; bandwidth[6] = 70.0000; 256 | cent_freq[7] = 540.000; bandwidth[7] = 77.3724; 257 | cent_freq[8] = 617.372; bandwidth[8] = 86.0056; 258 | cent_freq[9] = 703.378; bandwidth[9] = 95.3398; 259 | cent_freq[10] = 798.717; bandwidth[10] = 105.411; 260 | cent_freq[11] = 904.128; bandwidth[11] = 116.256; 261 | cent_freq[12] = 1020.38; bandwidth[12] = 127.914; 262 | cent_freq[13] = 1148.30; bandwidth[13] = 140.423; 263 | cent_freq[14] = 1288.72; bandwidth[14] = 153.823; 264 | cent_freq[15] = 1442.54; bandwidth[15] = 168.154; 265 | cent_freq[16] = 1610.70; bandwidth[16] = 183.457; 266 | cent_freq[17] = 1794.16; bandwidth[17] = 199.776; 267 | cent_freq[18] = 1993.93; bandwidth[18] = 217.153; 268 | cent_freq[19] = 2211.08; bandwidth[19] = 235.631; 269 | cent_freq[20] = 2446.71; bandwidth[20] = 255.255; 270 | cent_freq[21] = 2701.97; bandwidth[21] = 276.072; 271 | cent_freq[22] = 2978.04; bandwidth[22] = 298.126; 272 | cent_freq[23] = 3276.17; bandwidth[23] = 321.465; 273 | cent_freq[24] = 3597.63; bandwidth[24] = 346.136; 274 | 275 | 276 | W=np.array([0.003,0.003,0.003,0.007,0.010,0.016,0.016,0.017,0.017,0.022,0.027,0.028,0.030,0.032,0.034,0.035,0.037,0.036,0.036,0.033,0.030,0.029,0.027,0.026, 277 | 0.026]) 278 | 279 | bw_min=bandwidth[0] 280 | min_factor = np.exp (-30.0 / (2.0 * 2.303));# % -30 dB point of filter 281 | 282 | all_f0=np.zeros((num_crit,)) 283 | crit_filter=np.zeros((num_crit,int(n_fftby2))) 284 | j = np.arange(0,n_fftby2) 285 | 286 | 287 | for i in range(num_crit): 288 | f0 = (cent_freq[i] / max_freq) * (n_fftby2) 289 | all_f0[i] = np.floor(f0); 290 | bw = (bandwidth[i] / max_freq) * (n_fftby2); 291 | norm_factor = np.log(bw_min) - np.log(bandwidth[i]); 292 | crit_filter[i,:] = np.exp (-11 *(((j - np.floor(f0))/bw)**2) + norm_factor) 293 | crit_filter[i,:] = crit_filter[i,:]*(crit_filter[i,:] > min_factor) 294 | 295 | num_frames = len(clean_speech)/skiprate-(winlength/skiprate)# number of frames 296 | start = 1 # starting sample 297 | 298 | hannWin=0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1))) 299 | scale = np.sqrt(1.0 / hannWin.sum()**2) 300 | 301 | f,t,Zxx=stft(clean_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False) 302 | clean_spec=np.power(np.abs(Zxx)/scale,2) 303 | clean_spec=clean_spec[:-1,:] 304 | 305 | f,t,Zxx=stft(processed_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False) 306 | proc_spec=np.power(np.abs(Zxx)/scale,2) 307 | proc_spec=proc_spec[:-1,:] 308 | 309 | clean_energy=(crit_filter.dot(clean_spec)) 310 | log_clean_energy=10*np.log10(clean_energy) 311 | log_clean_energy[log_clean_energy<-100]=-100 312 | proc_energy=(crit_filter.dot(proc_spec)) 313 | log_proc_energy=10*np.log10(proc_energy) 314 | log_proc_energy[log_proc_energy<-100]=-100 315 | 316 | log_clean_energy_slope=np.diff(log_clean_energy,axis=0) 317 | log_proc_energy_slope=np.diff(log_proc_energy,axis=0) 318 | 319 | dBMax_clean = np.max(log_clean_energy,axis=0) 320 | dBMax_processed = np.max(log_proc_energy,axis=0) 321 | 322 | numFrames=log_clean_energy_slope.shape[-1] 323 | 324 | clean_loc_peaks=np.zeros_like(log_clean_energy_slope) 325 | proc_loc_peaks=np.zeros_like(log_proc_energy_slope) 326 | for ii in range(numFrames): 327 | clean_loc_peaks[:,ii]=find_loc_peaks(log_clean_energy_slope[:,ii],log_clean_energy[:,ii]) 328 | proc_loc_peaks[:,ii]=find_loc_peaks(log_proc_energy_slope[:,ii],log_proc_energy[:,ii]) 329 | 330 | 331 | Wmax_clean = Kmax / (Kmax + dBMax_clean - log_clean_energy[:-1,:]) 332 | Wlocmax_clean = Klocmax / ( Klocmax + clean_loc_peaks - log_clean_energy[:-1,:]) 333 | W_clean = Wmax_clean * Wlocmax_clean 334 | 335 | Wmax_proc = Kmax / (Kmax + dBMax_processed - log_proc_energy[:-1]) 336 | Wlocmax_proc = Klocmax / ( Klocmax + proc_loc_peaks - log_proc_energy[:-1,:]) 337 | W_proc = Wmax_proc * Wlocmax_proc 338 | 339 | W = (W_clean + W_proc)/2.0 340 | 341 | distortion=np.sum(W*(log_clean_energy_slope- log_proc_energy_slope)**2,axis=0) 342 | distortion=distortion/np.sum(W,axis=0) 343 | distortion = np.sort(distortion) 344 | distortion = distortion[:int(round(len(distortion)*alpha))] 345 | return np.mean(distortion) 346 | 347 | def pesq(clean_speech, processed_speech, fs): 348 | if fs == 8000: 349 | mos_lqo = pypesq.pesq(fs,clean_speech, processed_speech, 'nb') 350 | pesq_mos = 46607/14945 - (2000*np.log(1/(mos_lqo/4 - 999/4000) - 1))/2989#0.999 + ( 4.999-0.999 ) / ( 1+np.exp(-1.4945*pesq_mos+4.6607) ) 351 | elif fs == 16000: 352 | mos_lqo = pypesq.pesq(fs,clean_speech, processed_speech, 'wb') 353 | pesq_mos = np.NaN 354 | else: 355 | raise ValueError('fs must be either 8 kHz or 16 kHz') 356 | 357 | return pesq_mos,mos_lqo 358 | 359 | 360 | def composite(clean_speech, processed_speech, fs): 361 | wss_dist=wss(clean_speech, processed_speech, fs) 362 | llr_mean=llr(clean_speech, processed_speech, fs,used_for_composite=True) 363 | segSNR=SNRseg(clean_speech, processed_speech, fs) 364 | pesq_mos,mos_lqo = pesq(clean_speech, processed_speech,fs) 365 | 366 | if fs >= 16e3: 367 | used_pesq_val = mos_lqo 368 | else: 369 | used_pesq_val = pesq_mos 370 | 371 | Csig = 3.093 - 1.029*llr_mean + 0.603*used_pesq_val-0.009*wss_dist 372 | Csig = np.max((1,Csig)) 373 | Csig = np.min((5, Csig)) # limit values to [1, 5] 374 | Cbak = 1.634 + 0.478 *used_pesq_val - 0.007*wss_dist + 0.063*segSNR 375 | Cbak = np.max((1, Cbak)) 376 | Cbak = np.min((5,Cbak)) # limit values to [1, 5] 377 | Covl = 1.594 + 0.805*used_pesq_val - 0.512*llr_mean - 0.007*wss_dist 378 | Covl = np.max((1, Covl)) 379 | Covl = np.min((5, Covl)) # limit values to [1, 5] 380 | return Csig,Cbak,Covl 381 | 382 | @jit 383 | def lpc2cep(a): 384 | # 385 | # converts prediction to cepstrum coefficients 386 | # 387 | # Author: Philipos C. Loizou 388 | 389 | M=len(a); 390 | cep=np.zeros((M-1,)); 391 | 392 | cep[0]=-a[1] 393 | 394 | for k in range(2,M): 395 | ix=np.arange(1,k) 396 | vec1=cep[ix-1]*a[k-1:0:-1]*(ix) 397 | cep[k-1]=-(a[k]+np.sum(vec1)/k); 398 | return cep 399 | 400 | 401 | def cepstrum_distance(clean_speech, processed_speech, fs, frameLen=0.03, overlap=0.75): 402 | 403 | 404 | clean_length = len(clean_speech) 405 | processed_length = len(processed_speech) 406 | 407 | winlength = round(frameLen*fs) #window length in samples 408 | skiprate = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples 409 | 410 | if fs<10000: 411 | P = 10 # LPC Analysis Order 412 | else: 413 | P=16; # this could vary depending on sampling frequency. 414 | 415 | C=10*np.sqrt(2)/np.log(10) 416 | 417 | numFrames = int(clean_length/skiprate-(winlength/skiprate)); # number of frames 418 | 419 | hannWin=0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1))) 420 | clean_speech_framed=extract_overlapped_windows(clean_speech[0:int(numFrames)*skiprate+int(winlength-skiprate)],winlength,winlength-skiprate,hannWin) 421 | processed_speech_framed=extract_overlapped_windows(processed_speech[0:int(numFrames)*skiprate+int(winlength-skiprate)],winlength,winlength-skiprate,hannWin) 422 | distortion = np.zeros((numFrames,)) 423 | 424 | for ii in range(numFrames): 425 | A_clean,R_clean=lpcoeff(clean_speech_framed[ii,:],P) 426 | A_proc,R_proc=lpcoeff(processed_speech_framed[ii,:],P) 427 | 428 | C_clean=lpc2cep(A_clean) 429 | C_processed=lpc2cep(A_proc) 430 | distortion[ii] = min((10,C*np.linalg.norm(C_clean-C_processed))) 431 | 432 | IS_dist = distortion 433 | alpha=0.95 434 | IS_len= round( len( IS_dist)* alpha) 435 | IS = np.sort(IS_dist) 436 | cep_mean= np.mean( IS[ 0: IS_len]) 437 | return cep_mean -------------------------------------------------------------------------------- /examples/examplesForCalculatingMeasures.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from scipy.io import wavfile\n", 10 | "import sys\n", 11 | "sys.path.append(\"../\") \n", 12 | "import pysepm\n" 13 | ] 14 | }, 15 | { 16 | "cell_type": "markdown", 17 | "metadata": {}, 18 | "source": [ 19 | "# Load Audio Files" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 2, 25 | "metadata": {}, 26 | "outputs": [ 27 | { 28 | "name": "stderr", 29 | "output_type": "stream", 30 | "text": [ 31 | "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:1: WavFileWarning: Chunk (non-data) not understood, skipping it.\n", 32 | " \"\"\"Entry point for launching an IPython kernel.\n", 33 | "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:2: WavFileWarning: Chunk (non-data) not understood, skipping it.\n", 34 | " \n", 35 | "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:3: WavFileWarning: Chunk (non-data) not understood, skipping it.\n", 36 | " This is separate from the ipykernel package so we can avoid doing imports until\n" 37 | ] 38 | } 39 | ], 40 | "source": [ 41 | "fs, clean_speech = wavfile.read('1_speech_16000_Hz.wav')\n", 42 | "fs, noisy_speech = wavfile.read('1_noisySpeech_16000_Hz.wav')\n", 43 | "fs, enhanced_speech = wavfile.read('1_processed_16000_Hz.wav')" 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "# Calc Measures" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "## fwSNRseg" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 3, 63 | "metadata": {}, 64 | "outputs": [ 65 | { 66 | "data": { 67 | "text/plain": [ 68 | "5.677122381286333" 69 | ] 70 | }, 71 | "execution_count": 3, 72 | "metadata": {}, 73 | "output_type": "execute_result" 74 | } 75 | ], 76 | "source": [ 77 | "pysepm.fwSNRseg(clean_speech, noisy_speech, fs)" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": 4, 83 | "metadata": {}, 84 | "outputs": [ 85 | { 86 | "data": { 87 | "text/plain": [ 88 | "3.7018915637639442" 89 | ] 90 | }, 91 | "execution_count": 4, 92 | "metadata": {}, 93 | "output_type": "execute_result" 94 | } 95 | ], 96 | "source": [ 97 | "pysepm.fwSNRseg(clean_speech, enhanced_speech, fs)" 98 | ] 99 | }, 100 | { 101 | "cell_type": "markdown", 102 | "metadata": {}, 103 | "source": [ 104 | "## SNRseg" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 5, 110 | "metadata": {}, 111 | "outputs": [ 112 | { 113 | "data": { 114 | "text/plain": [ 115 | "-0.21686174881958412" 116 | ] 117 | }, 118 | "execution_count": 5, 119 | "metadata": {}, 120 | "output_type": "execute_result" 121 | } 122 | ], 123 | "source": [ 124 | "pysepm.SNRseg(clean_speech, noisy_speech, fs)" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": 6, 130 | "metadata": {}, 131 | "outputs": [ 132 | { 133 | "data": { 134 | "text/plain": [ 135 | "-1.2033705198493232" 136 | ] 137 | }, 138 | "execution_count": 6, 139 | "metadata": {}, 140 | "output_type": "execute_result" 141 | } 142 | ], 143 | "source": [ 144 | "pysepm.SNRseg(clean_speech, enhanced_speech, fs)" 145 | ] 146 | }, 147 | { 148 | "cell_type": "markdown", 149 | "metadata": {}, 150 | "source": [ 151 | "## LLR" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": 7, 157 | "metadata": {}, 158 | "outputs": [ 159 | { 160 | "data": { 161 | "text/plain": [ 162 | "1.2530765533868626" 163 | ] 164 | }, 165 | "execution_count": 7, 166 | "metadata": {}, 167 | "output_type": "execute_result" 168 | } 169 | ], 170 | "source": [ 171 | "pysepm.llr(clean_speech, noisy_speech, fs)" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": 8, 177 | "metadata": {}, 178 | "outputs": [ 179 | { 180 | "data": { 181 | "text/plain": [ 182 | "1.6044180854910925" 183 | ] 184 | }, 185 | "execution_count": 8, 186 | "metadata": {}, 187 | "output_type": "execute_result" 188 | } 189 | ], 190 | "source": [ 191 | "pysepm.llr(clean_speech, enhanced_speech, fs)" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "## WSS" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 9, 204 | "metadata": {}, 205 | "outputs": [ 206 | { 207 | "data": { 208 | "text/plain": [ 209 | "44.69861369131994" 210 | ] 211 | }, 212 | "execution_count": 9, 213 | "metadata": {}, 214 | "output_type": "execute_result" 215 | } 216 | ], 217 | "source": [ 218 | "pysepm.wss(clean_speech, noisy_speech, fs)" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": 10, 224 | "metadata": {}, 225 | "outputs": [ 226 | { 227 | "data": { 228 | "text/plain": [ 229 | "66.79548150633117" 230 | ] 231 | }, 232 | "execution_count": 10, 233 | "metadata": {}, 234 | "output_type": "execute_result" 235 | } 236 | ], 237 | "source": [ 238 | "pysepm.wss(clean_speech, enhanced_speech, fs)" 239 | ] 240 | }, 241 | { 242 | "cell_type": "markdown", 243 | "metadata": {}, 244 | "source": [ 245 | "## Cepstrum Distance (CD)" 246 | ] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "execution_count": 11, 251 | "metadata": {}, 252 | "outputs": [ 253 | { 254 | "data": { 255 | "text/plain": [ 256 | "7.187803223674154" 257 | ] 258 | }, 259 | "execution_count": 11, 260 | "metadata": {}, 261 | "output_type": "execute_result" 262 | } 263 | ], 264 | "source": [ 265 | "pysepm.cepstrum_distance(clean_speech, noisy_speech, fs)" 266 | ] 267 | }, 268 | { 269 | "cell_type": "code", 270 | "execution_count": 12, 271 | "metadata": {}, 272 | "outputs": [ 273 | { 274 | "data": { 275 | "text/plain": [ 276 | "8.308018500622689" 277 | ] 278 | }, 279 | "execution_count": 12, 280 | "metadata": {}, 281 | "output_type": "execute_result" 282 | } 283 | ], 284 | "source": [ 285 | "pysepm.cepstrum_distance(clean_speech, enhanced_speech, fs)" 286 | ] 287 | }, 288 | { 289 | "cell_type": "markdown", 290 | "metadata": {}, 291 | "source": [ 292 | "## STOI" 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "execution_count": 13, 298 | "metadata": {}, 299 | "outputs": [ 300 | { 301 | "data": { 302 | "text/plain": [ 303 | "0.8389211808320151" 304 | ] 305 | }, 306 | "execution_count": 13, 307 | "metadata": {}, 308 | "output_type": "execute_result" 309 | } 310 | ], 311 | "source": [ 312 | "pysepm.stoi(clean_speech, noisy_speech, fs)" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": 14, 318 | "metadata": {}, 319 | "outputs": [ 320 | { 321 | "data": { 322 | "text/plain": [ 323 | "0.661152205056174" 324 | ] 325 | }, 326 | "execution_count": 14, 327 | "metadata": {}, 328 | "output_type": "execute_result" 329 | } 330 | ], 331 | "source": [ 332 | "pysepm.stoi(clean_speech, enhanced_speech, fs)" 333 | ] 334 | }, 335 | { 336 | "cell_type": "markdown", 337 | "metadata": {}, 338 | "source": [ 339 | "## CSII" 340 | ] 341 | }, 342 | { 343 | "cell_type": "code", 344 | "execution_count": 15, 345 | "metadata": {}, 346 | "outputs": [ 347 | { 348 | "data": { 349 | "text/plain": [ 350 | "(0.7336988398405825, 0.4363089356143529, 0.018848854017316796)" 351 | ] 352 | }, 353 | "execution_count": 15, 354 | "metadata": {}, 355 | "output_type": "execute_result" 356 | } 357 | ], 358 | "source": [ 359 | "pysepm.csii(clean_speech, noisy_speech, fs)" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": 16, 365 | "metadata": {}, 366 | "outputs": [ 367 | { 368 | "data": { 369 | "text/plain": [ 370 | "(0.527623436040412, 0.2437425452887004, 0.010118033728508934)" 371 | ] 372 | }, 373 | "execution_count": 16, 374 | "metadata": {}, 375 | "output_type": "execute_result" 376 | } 377 | ], 378 | "source": [ 379 | "pysepm.csii(clean_speech, enhanced_speech, fs)" 380 | ] 381 | }, 382 | { 383 | "cell_type": "markdown", 384 | "metadata": {}, 385 | "source": [ 386 | "## PESQ" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": 17, 392 | "metadata": {}, 393 | "outputs": [ 394 | { 395 | "data": { 396 | "text/plain": [ 397 | "(nan, 1.1624178886413574)" 398 | ] 399 | }, 400 | "execution_count": 17, 401 | "metadata": {}, 402 | "output_type": "execute_result" 403 | } 404 | ], 405 | "source": [ 406 | "pysepm.pesq(clean_speech, noisy_speech, fs)" 407 | ] 408 | }, 409 | { 410 | "cell_type": "code", 411 | "execution_count": 18, 412 | "metadata": {}, 413 | "outputs": [ 414 | { 415 | "data": { 416 | "text/plain": [ 417 | "(nan, 1.0594704151153564)" 418 | ] 419 | }, 420 | "execution_count": 18, 421 | "metadata": {}, 422 | "output_type": "execute_result" 423 | } 424 | ], 425 | "source": [ 426 | "pysepm.pesq(clean_speech, enhanced_speech, fs)" 427 | ] 428 | }, 429 | { 430 | "cell_type": "markdown", 431 | "metadata": {}, 432 | "source": [ 433 | "## Composite" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "execution_count": 19, 439 | "metadata": {}, 440 | "outputs": [ 441 | { 442 | "data": { 443 | "text/plain": [ 444 | "(2.037992006581127, 1.8630831647556954, 1.5433156477547219)" 445 | ] 446 | }, 447 | "execution_count": 19, 448 | "metadata": {}, 449 | "output_type": "execute_result" 450 | } 451 | ], 452 | "source": [ 453 | "pysepm.composite(clean_speech, noisy_speech, fs)" 454 | ] 455 | }, 456 | { 457 | "cell_type": "code", 458 | "execution_count": 20, 459 | "metadata": {}, 460 | "outputs": [ 461 | { 462 | "data": { 463 | "text/plain": [ 464 | "(1.0, 1.5970461451303148, 1.0)" 465 | ] 466 | }, 467 | "execution_count": 20, 468 | "metadata": {}, 469 | "output_type": "execute_result" 470 | } 471 | ], 472 | "source": [ 473 | "pysepm.composite(clean_speech, enhanced_speech, fs)" 474 | ] 475 | }, 476 | { 477 | "cell_type": "markdown", 478 | "metadata": {}, 479 | "source": [ 480 | "## NCM" 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": 21, 486 | "metadata": {}, 487 | "outputs": [], 488 | "source": [ 489 | "pysepm.ncm(clean_speech, noisy_speech, fs)" 490 | ] 491 | }, 492 | { 493 | "cell_type": "code", 494 | "execution_count": 22, 495 | "metadata": {}, 496 | "outputs": [], 497 | "source": [ 498 | "pysepm.ncm(clean_speech, enhanced_speech, fs)" 499 | ] 500 | }, 501 | { 502 | "cell_type": "markdown", 503 | "metadata": {}, 504 | "source": [ 505 | "# SRMR" 506 | ] 507 | }, 508 | { 509 | "cell_type": "code", 510 | "execution_count": 23, 511 | "metadata": {}, 512 | "outputs": [ 513 | { 514 | "name": "stderr", 515 | "output_type": "stream", 516 | "text": [ 517 | "/usr/local/lib/python3.6/dist-packages/srmrpy/hilbert.py:69: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.\n", 518 | " h = h[ind]\n" 519 | ] 520 | }, 521 | { 522 | "data": { 523 | "text/plain": [ 524 | "3.2050299299144114" 525 | ] 526 | }, 527 | "execution_count": 23, 528 | "metadata": {}, 529 | "output_type": "execute_result" 530 | } 531 | ], 532 | "source": [ 533 | "pysepm.srmr(noisy_speech, fs)" 534 | ] 535 | }, 536 | { 537 | "cell_type": "code", 538 | "execution_count": 24, 539 | "metadata": {}, 540 | "outputs": [ 541 | { 542 | "data": { 543 | "text/plain": [ 544 | "7.317370449764798" 545 | ] 546 | }, 547 | "execution_count": 24, 548 | "metadata": {}, 549 | "output_type": "execute_result" 550 | } 551 | ], 552 | "source": [ 553 | "pysepm.srmr(enhanced_speech, fs)" 554 | ] 555 | }, 556 | { 557 | "cell_type": "markdown", 558 | "metadata": {}, 559 | "source": [ 560 | "# BSD" 561 | ] 562 | }, 563 | { 564 | "cell_type": "code", 565 | "execution_count": 10, 566 | "metadata": {}, 567 | "outputs": [ 568 | { 569 | "name": "stdout", 570 | "output_type": "stream", 571 | "text": [ 572 | "include pre-emphasis\n" 573 | ] 574 | }, 575 | { 576 | "data": { 577 | "text/plain": [ 578 | "38086949616.83964" 579 | ] 580 | }, 581 | "execution_count": 10, 582 | "metadata": {}, 583 | "output_type": "execute_result" 584 | } 585 | ], 586 | "source": [ 587 | "pysepm.bsd(clean_speech, noisy_speech, fs)" 588 | ] 589 | }, 590 | { 591 | "cell_type": "code", 592 | "execution_count": 11, 593 | "metadata": {}, 594 | "outputs": [ 595 | { 596 | "name": "stdout", 597 | "output_type": "stream", 598 | "text": [ 599 | "include pre-emphasis\n" 600 | ] 601 | }, 602 | { 603 | "data": { 604 | "text/plain": [ 605 | "51047508.139671564" 606 | ] 607 | }, 608 | "execution_count": 11, 609 | "metadata": {}, 610 | "output_type": "execute_result" 611 | } 612 | ], 613 | "source": [ 614 | "pysepm.bsd(clean_speech, enhanced_speech, fs)" 615 | ] 616 | }, 617 | { 618 | "cell_type": "markdown", 619 | "metadata": {}, 620 | "source": [ 621 | "# Measure Execution Times" 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": 25, 627 | "metadata": {}, 628 | "outputs": [ 629 | { 630 | "name": "stdout", 631 | "output_type": "stream", 632 | "text": [ 633 | "61.1 ms ± 667 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 634 | ] 635 | } 636 | ], 637 | "source": [ 638 | "%timeit pysepm.fwSNRseg(clean_speech, noisy_speech, fs)" 639 | ] 640 | }, 641 | { 642 | "cell_type": "code", 643 | "execution_count": 26, 644 | "metadata": {}, 645 | "outputs": [ 646 | { 647 | "name": "stdout", 648 | "output_type": "stream", 649 | "text": [ 650 | "14.5 ms ± 11.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" 651 | ] 652 | } 653 | ], 654 | "source": [ 655 | "%timeit pysepm.SNRseg(clean_speech, noisy_speech, fs)" 656 | ] 657 | }, 658 | { 659 | "cell_type": "code", 660 | "execution_count": 27, 661 | "metadata": {}, 662 | "outputs": [ 663 | { 664 | "name": "stdout", 665 | "output_type": "stream", 666 | "text": [ 667 | "113 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 668 | ] 669 | } 670 | ], 671 | "source": [ 672 | "%timeit pysepm.llr(clean_speech, noisy_speech, fs)" 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": 28, 678 | "metadata": {}, 679 | "outputs": [ 680 | { 681 | "name": "stdout", 682 | "output_type": "stream", 683 | "text": [ 684 | "80 ms ± 552 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 685 | ] 686 | } 687 | ], 688 | "source": [ 689 | "%timeit pysepm.wss(clean_speech, noisy_speech, fs)" 690 | ] 691 | }, 692 | { 693 | "cell_type": "code", 694 | "execution_count": 29, 695 | "metadata": {}, 696 | "outputs": [ 697 | { 698 | "name": "stdout", 699 | "output_type": "stream", 700 | "text": [ 701 | "92.5 ms ± 391 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 702 | ] 703 | } 704 | ], 705 | "source": [ 706 | "%timeit pysepm.cepstrum_distance(clean_speech, noisy_speech, fs)" 707 | ] 708 | }, 709 | { 710 | "cell_type": "code", 711 | "execution_count": 30, 712 | "metadata": {}, 713 | "outputs": [ 714 | { 715 | "name": "stdout", 716 | "output_type": "stream", 717 | "text": [ 718 | "143 ms ± 381 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 719 | ] 720 | } 721 | ], 722 | "source": [ 723 | "%timeit pysepm.stoi(clean_speech, noisy_speech, fs)" 724 | ] 725 | }, 726 | { 727 | "cell_type": "code", 728 | "execution_count": 31, 729 | "metadata": {}, 730 | "outputs": [ 731 | { 732 | "name": "stdout", 733 | "output_type": "stream", 734 | "text": [ 735 | "82.7 ms ± 450 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 736 | ] 737 | } 738 | ], 739 | "source": [ 740 | "%timeit pysepm.csii(clean_speech, noisy_speech, fs)" 741 | ] 742 | }, 743 | { 744 | "cell_type": "code", 745 | "execution_count": 32, 746 | "metadata": {}, 747 | "outputs": [ 748 | { 749 | "name": "stdout", 750 | "output_type": "stream", 751 | "text": [ 752 | "309 ms ± 510 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 753 | ] 754 | } 755 | ], 756 | "source": [ 757 | "%timeit pysepm.pesq(clean_speech, noisy_speech, fs)" 758 | ] 759 | }, 760 | { 761 | "cell_type": "code", 762 | "execution_count": 33, 763 | "metadata": {}, 764 | "outputs": [ 765 | { 766 | "name": "stdout", 767 | "output_type": "stream", 768 | "text": [ 769 | "521 ms ± 1.27 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 770 | ] 771 | } 772 | ], 773 | "source": [ 774 | "%timeit pysepm.composite(clean_speech, noisy_speech, fs)" 775 | ] 776 | }, 777 | { 778 | "cell_type": "code", 779 | "execution_count": 34, 780 | "metadata": {}, 781 | "outputs": [ 782 | { 783 | "name": "stdout", 784 | "output_type": "stream", 785 | "text": [ 786 | "5.13 s ± 13.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 787 | ] 788 | } 789 | ], 790 | "source": [ 791 | "%timeit pysepm.ncm(clean_speech, noisy_speech, fs)" 792 | ] 793 | }, 794 | { 795 | "cell_type": "code", 796 | "execution_count": 35, 797 | "metadata": {}, 798 | "outputs": [ 799 | { 800 | "name": "stderr", 801 | "output_type": "stream", 802 | "text": [ 803 | "/usr/local/lib/python3.6/dist-packages/srmrpy/hilbert.py:69: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.\n", 804 | " h = h[ind]\n" 805 | ] 806 | }, 807 | { 808 | "name": "stdout", 809 | "output_type": "stream", 810 | "text": [ 811 | "1.6 s ± 660 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 812 | ] 813 | } 814 | ], 815 | "source": [ 816 | "%timeit pysepm.srmr(clean_speech, fs)" 817 | ] 818 | }, 819 | { 820 | "cell_type": "code", 821 | "execution_count": 29, 822 | "metadata": {}, 823 | "outputs": [ 824 | { 825 | "name": "stdout", 826 | "output_type": "stream", 827 | "text": [ 828 | "include pre-emphasis\n", 829 | "bark filter not tested\n", 830 | "include pre-emphasis\n", 831 | "bark filter not tested\n", 832 | "include pre-emphasis\n", 833 | "bark filter not tested\n", 834 | "include pre-emphasis\n", 835 | "bark filter not tested\n", 836 | "include pre-emphasis\n", 837 | "bark filter not tested\n", 838 | "include pre-emphasis\n", 839 | "bark filter not tested\n", 840 | "include pre-emphasis\n", 841 | "bark filter not tested\n", 842 | "include pre-emphasis\n", 843 | "bark filter not tested\n", 844 | "include pre-emphasis\n", 845 | "bark filter not tested\n", 846 | "include pre-emphasis\n", 847 | "bark filter not tested\n", 848 | "include pre-emphasis\n", 849 | "bark filter not tested\n", 850 | "include pre-emphasis\n", 851 | "bark filter not tested\n", 852 | "include pre-emphasis\n", 853 | "bark filter not tested\n", 854 | "include pre-emphasis\n", 855 | "bark filter not tested\n", 856 | "include pre-emphasis\n", 857 | "bark filter not tested\n", 858 | "include pre-emphasis\n", 859 | "bark filter not tested\n", 860 | "include pre-emphasis\n", 861 | "bark filter not tested\n", 862 | "include pre-emphasis\n", 863 | "bark filter not tested\n", 864 | "include pre-emphasis\n", 865 | "bark filter not tested\n", 866 | "include pre-emphasis\n", 867 | "bark filter not tested\n", 868 | "include pre-emphasis\n", 869 | "bark filter not tested\n", 870 | "include pre-emphasis\n", 871 | "bark filter not tested\n", 872 | "include pre-emphasis\n", 873 | "bark filter not tested\n", 874 | "include pre-emphasis\n", 875 | "bark filter not tested\n", 876 | "include pre-emphasis\n", 877 | "bark filter not tested\n", 878 | "include pre-emphasis\n", 879 | "bark filter not tested\n", 880 | "include pre-emphasis\n", 881 | "bark filter not tested\n", 882 | "include pre-emphasis\n", 883 | "bark filter not tested\n", 884 | "include pre-emphasis\n", 885 | "bark filter not tested\n", 886 | "include pre-emphasis\n", 887 | "bark filter not tested\n", 888 | "include pre-emphasis\n", 889 | "bark filter not tested\n", 890 | "include pre-emphasis\n", 891 | "bark filter not tested\n", 892 | "include pre-emphasis\n", 893 | "bark filter not tested\n", 894 | "include pre-emphasis\n", 895 | "bark filter not tested\n", 896 | "include pre-emphasis\n", 897 | "bark filter not tested\n", 898 | "include pre-emphasis\n", 899 | "bark filter not tested\n", 900 | "include pre-emphasis\n", 901 | "bark filter not tested\n", 902 | "include pre-emphasis\n", 903 | "bark filter not tested\n", 904 | "include pre-emphasis\n", 905 | "bark filter not tested\n", 906 | "include pre-emphasis\n", 907 | "bark filter not tested\n", 908 | "include pre-emphasis\n", 909 | "bark filter not tested\n", 910 | "include pre-emphasis\n", 911 | "bark filter not tested\n", 912 | "include pre-emphasis\n", 913 | "bark filter not tested\n", 914 | "include pre-emphasis\n", 915 | "bark filter not tested\n", 916 | "include pre-emphasis\n", 917 | "bark filter not tested\n", 918 | "include pre-emphasis\n", 919 | "bark filter not tested\n", 920 | "include pre-emphasis\n", 921 | "bark filter not tested\n", 922 | "include pre-emphasis\n", 923 | "bark filter not tested\n", 924 | "include pre-emphasis\n", 925 | "bark filter not tested\n", 926 | "include pre-emphasis\n", 927 | "bark filter not tested\n", 928 | "include pre-emphasis\n", 929 | "bark filter not tested\n", 930 | "include pre-emphasis\n", 931 | "bark filter not tested\n", 932 | "include pre-emphasis\n", 933 | "bark filter not tested\n", 934 | "include pre-emphasis\n", 935 | "bark filter not tested\n", 936 | "include pre-emphasis\n", 937 | "bark filter not tested\n", 938 | "include pre-emphasis\n", 939 | "bark filter not tested\n", 940 | "include pre-emphasis\n", 941 | "bark filter not tested\n", 942 | "include pre-emphasis\n", 943 | "bark filter not tested\n", 944 | "include pre-emphasis\n", 945 | "bark filter not tested\n", 946 | "include pre-emphasis\n", 947 | "bark filter not tested\n", 948 | "include pre-emphasis\n", 949 | "bark filter not tested\n", 950 | "include pre-emphasis\n", 951 | "bark filter not tested\n", 952 | "include pre-emphasis\n", 953 | "bark filter not tested\n", 954 | "include pre-emphasis\n", 955 | "bark filter not tested\n", 956 | "include pre-emphasis\n", 957 | "bark filter not tested\n", 958 | "include pre-emphasis\n", 959 | "bark filter not tested\n", 960 | "include pre-emphasis\n", 961 | "bark filter not tested\n", 962 | "include pre-emphasis\n", 963 | "bark filter not tested\n", 964 | "include pre-emphasis\n", 965 | "bark filter not tested\n", 966 | "include pre-emphasis\n", 967 | "bark filter not tested\n", 968 | "include pre-emphasis\n", 969 | "bark filter not tested\n", 970 | "include pre-emphasis\n", 971 | "bark filter not tested\n", 972 | "include pre-emphasis\n", 973 | "bark filter not tested\n", 974 | "include pre-emphasis\n", 975 | "bark filter not tested\n", 976 | "include pre-emphasis\n", 977 | "bark filter not tested\n", 978 | "include pre-emphasis\n", 979 | "bark filter not tested\n", 980 | "include pre-emphasis\n", 981 | "bark filter not tested\n", 982 | "include pre-emphasis\n", 983 | "bark filter not tested\n", 984 | "include pre-emphasis\n", 985 | "bark filter not tested\n", 986 | "include pre-emphasis\n", 987 | "bark filter not tested\n", 988 | "include pre-emphasis\n", 989 | "bark filter not tested\n", 990 | "37.9 ms ± 319 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 991 | ] 992 | } 993 | ], 994 | "source": [ 995 | "%timeit pysepm.bsd(clean_speech, noisy_speech, fs)" 996 | ] 997 | }, 998 | { 999 | "cell_type": "code", 1000 | "execution_count": null, 1001 | "metadata": {}, 1002 | "outputs": [], 1003 | "source": [] 1004 | } 1005 | ], 1006 | "metadata": { 1007 | "kernelspec": { 1008 | "display_name": "Python 3", 1009 | "language": "python", 1010 | "name": "python3" 1011 | }, 1012 | "language_info": { 1013 | "codemirror_mode": { 1014 | "name": "ipython", 1015 | "version": 3 1016 | }, 1017 | "file_extension": ".py", 1018 | "mimetype": "text/x-python", 1019 | "name": "python", 1020 | "nbconvert_exporter": "python", 1021 | "pygments_lexer": "ipython3", 1022 | "version": "3.6.9" 1023 | } 1024 | }, 1025 | "nbformat": 4, 1026 | "nbformat_minor": 4 1027 | } 1028 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------