Giter VIP home page Giter VIP logo

speechpy's Introduction

image

image

image

image

image

image

image

image

Table of Contents

Documentation

This library provides most frequent used speech features including MFCCs and filterbank energies alongside with the log-energy of filterbanks. If you are interested to see what are MFCCs and how they are generated please refer to this wiki page.

image

Please refer to the following links for further informations:

SpeechPy Official Project Documentation

Paper

Which Python versions are supported

Currently, the package has been tested and verified using Python 2.7, 3.4 and 3.5.

Citation

If you used this package, please kindly cite it as follows:

@article{torfi2018speechpy,
  title={SpeechPy-A Library for Speech Processing and Recognition},
  author={Torfi, Amirsina},
  journal={arXiv preprint arXiv:1803.01094},
  year={2018}
     }

How to Install?

There are two possible ways for installation of this package: local installation and PyPi.

Local Installation

For local installation at first the repository must be cloned:

git clone https://github.com/astorfi/speech_feature_extraction.git

After cloning the reposity, root to the repository directory then execute:

python setup.py develop

Pypi

The package is available on PyPi. For direct installation simply execute the following:

pip install speechpy

What Features are supported?

  • Mel Frequency Cepstral Coefficients(MFCCs)
  • Filterbank Energies
  • Log Filterbank Energies

Please refer to SpeechPy Official Project Documentation for details about the supported features.

MFCC Features

pic1 pic2

The supported attributes for generating MFCC features can be seen by investigating the related function:

def mfcc(signal, sampling_frequency, frame_length=0.020, frame_stride=0.01,num_cepstral =13,
       num_filters=40, fft_length=512, low_frequency=0, high_frequency=None, dc_elimination=True):
  """Compute MFCC features from an audio signal.
  :param signal: the audio signal from which to compute features. Should be an N x 1 array
  :param sampling_frequency: the sampling frequency of the signal we are working with.
  :param frame_length: the length of each frame in seconds. Default is 0.020s
  :param frame_stride: the step between successive frames in seconds. Default is 0.02s (means no overlap)
  :param num_filters: the number of filters in the filterbank, default 40.
  :param fft_length: number of FFT points. Default is 512.
  :param low_frequency: lowest band edge of mel filters. In Hz, default is 0.
  :param high_frequency: highest band edge of mel filters. In Hz, default is samplerate/2
  :param num_cepstral: Number of cepstral coefficients.
  :param dc_elimination: hIf the first dc component should be eliminated or not.
  :returns: A numpy array of size (num_frames x num_cepstral) containing mfcc features.
  """

Filterbank Energy Features

def mfe(signal, sampling_frequency, frame_length=0.020, frame_stride=0.01,
      num_filters=40, fft_length=512, low_frequency=0, high_frequency=None):
    """Compute Mel-filterbank energy features from an audio signal.
    :param signal: the audio signal from which to compute features. Should be an N x 1 array
    :param sampling_frequency: the sampling frequency of the signal we are working with.
    :param frame_length: the length of each frame in seconds. Default is 0.020s
    :param frame_stride: the step between successive frames in seconds. Default is 0.02s (means no overlap)
    :param num_filters: the number of filters in the filterbank, default 40.
    :param fft_length: number of FFT points. Default is 512.
    :param low_frequency: lowest band edge of mel filters. In Hz, default is 0.
    :param high_frequency: highest band edge of mel filters. In Hz, default is samplerate/2
    :returns:
          features: the energy of fiterbank: num_frames x num_filters
          frame_energies: the energy of each frame: num_frames x 1
    """

log - Filterbank Energy Features

The attributes for log_filterbank energies are the same for filterbank energies too.

def lmfe(signal, sampling_frequency, frame_length=0.020, frame_stride=0.01,
         num_filters=40, fft_length=512, low_frequency=0, high_frequency=None):
    """Compute log Mel-filterbank energy features from an audio signal.
    :param signal: the audio signal from which to compute features. Should be an N x 1 array
    :param sampling_frequency: the sampling frequency of the signal we are working with.
    :param frame_length: the length of each frame in seconds. Default is 0.020s
    :param frame_stride: the step between successive frames in seconds. Default is 0.02s (means no overlap)
    :param num_filters: the number of filters in the filterbank, default 40.
    :param fft_length: number of FFT points. Default is 512.
    :param low_frequency: lowest band edge of mel filters. In Hz, default is 0.
    :param high_frequency: highest band edge of mel filters. In Hz, default is samplerate/2
    :returns:
          features: the energy of fiterbank: num_frames x num_filters
          frame_log_energies: the log energy of each frame: num_frames x 1
    """

Stack Frames

In Stack_Frames function, the stack of frames will be generated from the signal.

def stack_frames(sig, sampling_frequency, frame_length=0.020, frame_stride=0.020, Filter=lambda x: numpy.ones((x,)),
             zero_padding=True):
    """Frame a signal into overlapping frames.
    :param sig: The audio signal to frame of size (N,).
    :param sampling_frequency: The sampling frequency of the signal.
    :param frame_length: The length of the frame in second.
    :param frame_stride: The stride between frames.
    :param Filter: The time-domain filter for applying to each frame. By default it is one so nothing will be changed.
    :param zero_padding: If the samples is not a multiple of frame_length(number of frames sample), zero padding will
             be done for generating last frame.
    :returns: Array of frames. size: number_of_frames x frame_len.
    """

Post Processing

There are some post-processing operation that are supported in speechpy.

Global cepstral mean and variance normalization (CMVN)

This function performs global cepstral mean and variance normalization (CMVN) to remove the channel effects. The code assumes that there is one observation per row.

def cmvn(vec, variance_normalization=False):
    """
    This function is aimed to perform global ``cepstral mean and variance normalization``
    (CMVN) on input feature vector "vec". The code assumes that there is one observation per row.

    :param:
          vec: input feature matrix (size:(num_observation,num_features))
          variance_normalization: If the variance normilization should be performed or not.
    :return:
          The mean(or mean+variance) normalized feature vector.
    """

Local cepstral mean and variance normalization (CMVN) over a sliding window

This function performs local cepstral mean and variance normalization (CMVN) over sliding windows. The code assumes that there is one observation per row.

def cmvnw(vec, win_size=301, variance_normalization=False):
    """
    This function is aimed to perform local cepstral mean and variance normalization on a sliding window.
    (CMVN) on input feature vector "vec". The code assumes that there is one observation per row.
    :param
          vec: input feature matrix (size:(num_observation,num_features))
          win_size: The size of sliding window for local normalization and should be odd.
                    default=301 which is around 3s if 100 Hz rate is considered(== 10ms frame stide)
          variance_normalization: If the variance normilization should be performed or not.

    :return: The mean(or mean+variance) normalized feature vector.
    """

Tests

SpeechPy includes some unit tests. To run the tests, cd into the speechpy/tests directory and run:

python -m pytest

For installing the requirements you only need to install pytest.

Example

The test example can be seen in test/test.py as below:

import scipy.io.wavfile as wav
import numpy as np
import speechpy
import os

file_name = os.path.join(os.path.dirname(os.path.abspath(__file__)),'Alesis-Sanctuary-QCard-AcoustcBas-C2.wav')
fs, signal = wav.read(file_name)
signal = signal[:,0]

# Example of pre-emphasizing.
signal_preemphasized = speechpy.processing.preemphasis(signal, cof=0.98)

# Example of staching frames
frames = speechpy.processing.stack_frames(signal, sampling_frequency=fs, frame_length=0.020, frame_stride=0.01, filter=lambda x: np.ones((x,)),
         zero_padding=True)

# Example of extracting power spectrum
power_spectrum = speechpy.processing.power_spectrum(frames, fft_points=512)
print('power spectrum shape=', power_spectrum.shape)

############# Extract MFCC features #############
mfcc = speechpy.feature.mfcc(signal, sampling_frequency=fs, frame_length=0.020, frame_stride=0.01,
             num_filters=40, fft_length=512, low_frequency=0, high_frequency=None)
mfcc_cmvn = speechpy.processing.cmvnw(mfcc,win_size=301,variance_normalization=True)
print('mfcc(mean + variance normalized) feature shape=', mfcc_cmvn.shape)

mfcc_feature_cube = speechpy.feature.extract_derivative_feature(mfcc)
print('mfcc feature cube shape=', mfcc_feature_cube.shape)

############# Extract logenergy features #############
logenergy = speechpy.feature.lmfe(signal, sampling_frequency=fs, frame_length=0.020, frame_stride=0.01,
             num_filters=40, fft_length=512, low_frequency=0, high_frequency=None)
logenergy_feature_cube = speechpy.feature.extract_derivative_feature(logenergy)
print('logenergy features=', logenergy.shape)

For ectracting the feature at first, the signal samples will be stacked into frames. The features are computed for each frame in the stacked frames collection.

Dependencies

Two packages of Scipy and NumPy are the required dependencies which will be installed automatically by running the setup.py file.

Acknowledgements

This work is based upon a work supported by the Center for Identification Technology Research and the National Science Foundation under Grant #1650474.

Contributing

When contributing to this repository, you are more than welcome to discuss your feedback with any of the owners of this repository. For typos, please do not create a pull request. Instead, declare them in issues or email the repository owner. For technical and conceptual questions please feel free to directly contact the repository owner. Before asking general questions related to the concepts and techniques provided in this project, please make sure to read and understand its associated paper.

Pull Request Process

Please consider the following criterions in order to help us in a better way:

  1. The pull request is mainly expected to be a code script suggestion or improvement.
  2. A pull request related to non-code-script sections is expected to make a significant difference in the documentation. Otherwise, it is expected to be announced in the issues section.
  3. Ensure any install or build dependencies are removed before the end of the layer when doing a build and creating a pull request.
  4. Add comments with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters.
  5. You may merge the Pull Request in once you have the sign-off of at least one other developer, or if you do not have permission to do that, you may request the owner to merge it for you if you believe all checks are passed.

Declaring issues

For declaring issues, you can directly email the repository owner. However, preferably please create an issue as it might be the issue that other repository followers may encounter. That way, the question to other developers will be answered as well.

Final Note

We are looking forward to your kind feedback. Please help us to improve this open source project and make our work better. For contribution, please create a pull request and we will investigate it promptly. Once again, we appreciate your kind feedback and elaborate code inspections.

Disclaimer

Although by dramatic chages, some portion of this library is inspired by the python speech features library.

We clain the following advantages for our library:

  1. More accurate operations have been performed for the mel-frequency calculations.
  2. The package supports different Python versions.
  3. The feature are generated in a more organized way as cubic features.
  4. The package is well-tested and integrated.
  5. The package is up-to-date and actively developing.
  6. The package has been used for research purposes.
  7. Exceptions and extreme cases are handled in this library.

speechpy's People

Contributors

arfon avatar astorfi avatar matthewscholefield avatar omaraltayyan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

speechpy's Issues

MFCC Feature

Respected Sir,
Greetings of the day !!!

Sir first of all thank you so much for such amazing library you shared with us.

Sir I am using SpeechPy library for extracting the MFCC of audio signal.

Sir I have an audio signal of 16kHz, 32bit float PCM, Mono channel. I am using framelength 100ms with 50% overlapping.

I used below code for extraction of MFCC,

fs, signal = wav.read("b0.wav")
signal = signal / abs(max(signal)) #Convert into double
mfcc = speechpy.feature.mfcc (signal , sampling_frequency=fs, frame_length=0.1, frame_stride=0.05, num_filters=40, fft_length=2048, low_frequency=0, high_frequency=None)

Respected Sir, I got confusion because I used python_speech_features library also to extract mfcc and for verification of my result. But both are giving different result.

mfcc1 = python_speech_features.base.mfcc(signal, samplerate=fs, winlen=0.1, winstep=0.05, numcep=13, nfilt=26, nfft=2048, lowfreq=0, highfreq=None, preemph=0.97, ceplifter=22, appendEnergy=True)

I wanted to know where I am doing mistake.

My Questions Are:

  1. Is the above code sequence is correct to extract mfcc using speechpy library ?

  2. While using speechpy.feature.mfcc function, preemphasis operation is not performed? That is the reason both library are giving different result.

Should we have to perform seprately preemphasis using below code then we have to give the output of preemphasis to mfcc?

signal_preemphasized = speechpy.processing.preemphasis(signal, cof=0.98)

  1. Why both library are giving different result ?

Its my humble request respected Sir Please response to my query. I am not getting clarification. What to use and which is correct.

I am sorry for my poor English.

Remove animation from logo

Hi when I'm working with a project I like to have the docs open on the side, but would rather not have an animated logo flashing. :)

How about Delta and DeltaDelta

Hi,
I was wondering calculating MFCCs how can I add Delta and Deltadeltas to my coefficients? Should I go with 39 in num_cepstral?
Thanks

Installing release 2.3 appears to install 2.2

I have installed SpeechPy as part of my review of the package. Installing the package, I found a minor issue with the version number: I explicitly checked out the '2.3' release for installation whereas the install script output refers to version 2.2:

$ python setup.py develop
running develop
running egg_info
creating speechpy.egg-info
writing speechpy.egg-info/PKG-INFO
writing dependency_links to speechpy.egg-info/dependency_links.txt
writing requirements to speechpy.egg-info/requires.txt
writing top-level names to speechpy.egg-info/top_level.txt
writing manifest file 'speechpy.egg-info/SOURCES.txt'
reading manifest file 'speechpy.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'speechpy.egg-info/SOURCES.txt'
running build_ext
Creating /home/tha/.conda/envs/joss-review-tmp/lib/python3.6/site-packages/speechpy.egg-link (link to .)
Adding speechpy 2.2 to easy-install.pth file

Installed /home/tha/other-repo/speechpy
Processing dependencies for speechpy==2.2
Searching for numpy==1.14.3
Best match: numpy 1.14.3
Adding numpy 1.14.3 to easy-install.pth file

Using /home/tha/.conda/envs/joss-review-tmp/lib/python3.6/site-packages
Searching for scipy==1.1.0
Best match: scipy 1.1.0
Adding scipy 1.1.0 to easy-install.pth file

Using /home/tha/.conda/envs/joss-review-tmp/lib/python3.6/site-packages
Finished processing dependencies for speechpy==2.2

I suspect this is just some configuration text string that was not properly updated for the 2.3 release?

stack frames calculation

Hi Amirsina,

First of all, great project!

I noticed in the mfcc the last frame_length of the signal buffer is always missing. When the number of stack frames is calculated (in the function stack_frames), the sample_buffer is decreased with the frame_length before it is divided in a number of stack frames.

See snippet:

numframes = (int(math.ceil((length_signal
- frame_sample_length) / frame_stride)))

On a 1 second sample buffer this is hardly noticeable, but if we run the mfcc on smaller buffers this becomes significant.

If the calculation is done in this way:

    numframes = (int(math.ceil((length_signal
                                  - (frame_sample_length - frame_stride)) / frame_stride)))

The full sample buffer is used if frame_sample_length equals the frame_stride and adjusted correctly on differences between the frame_length and frame_stride.

pre-emphasis

Hi, it seems that pre-emphasis is not implemented. Will you add this in the future?

raw spectrogram

Hi

First of all thank you for your nice library. As raw features become popular in DNN models, is there any plan to add raw spectrogram feature extraction?

I know there are the same implementation in both numpy and scipy, but I think it is more justice to have all features (MFCC, LMFB and spectrogram) normalized in the same fashion and do a comparative analysis about their advantages on each other.

best regards

Possibly out of date citation request?

The README says to cite as "astorfi/speech_feature_extraction: SpeechPy", but the repo name is speechpy, so I'm thinking maybe this part of the README is out of date and it should say that one should cite as "storfi/speechpy: SpeechPy" or maybe "storfi/speechpy: Speech recognition and feature extraction" or something?

filter bank shape

Hi, I found that in your feature.py line 44:

# Initial definition
    filterbank = np.zeros([num_filter, fftpoints])

    # The triangular function for each filter
    for i in range(0, num_filter):
        left = int(freq_index[i])
        middle = int(freq_index[i + 1])
        right = int(freq_index[i + 2])
        z = np.linspace(left, right, num=right - left + 1)
        filterbank[i, left:right + 1] = functions.triangle(z, left=left, middle=middle, right=right)

    return filterbank

You use fftpoints directly to initialize, but as you use 512 as default, I think it should be 257 corresponding to FFT results.
I also checked other libraries such as python_speech_features and librosa, they all make it NFFT//2 + 1.
I just want to make sure the differences, thanks.

Speechpy Animation

Hey there,

Thanks for your awesome library! I have a very minor request.

  • The animation on the documentation page cant be stopped or hidden so I feel like getting eye cancer

Not sure if others have the problem but maybe you can set the looping to False?

Thanks.

negative dimensions are not allowed

When I used speechpy.feature.lmfe to get the log mfcc, the error occured. "negative dimensions are not allowed,ERROR”. Could you help me with the problem. Thanks

cmvnw: Division by zero

In encountered the following warning during the variance normalization of the speech features:

RuntimeWarning: divide by zero encountered in true_divide

cmvnw
This is probably not the desired behavior, I don't know what the best solution in this case is though.

A feature request:How can I judge user intentions ?

Hello,
I have a need for speech recognition now, and I have read many documents of this project, but I am still not sure whether this project can meet my need:

Now I have hundreds of thousands of wav audio files, which are only one to five seconds and divided into two categories, one is positive answer, the other is negative answer, but I do not have the text information corresponding to each wav file, now my demand is whether I can use this project to make intention judgment?

For example, if I input an audio data, then I can get the intention expressed by this audio, but there is no text corresponding to this audio

Any help will be greatly appreciated!

Correct wav format?

Im trying to extract mfcc features from audio of a video file.

I tried FFMPEG:

def extractAudioFromVideo(video, audio_out="out.wav"):
	cmd="ffmpeg -i {} -acodec pcm_s16le -ac 1 -ar 16000 {}".format(video, audio_out)
	os.system(cmd)
	return audio_out

def extractAudioMFCC(file_name="out.wav"):
	fs, signal = wav.read(file_name)
	signal = signal[:,0]

	############# Extract MFCC features #############
	mfcc = speechpy.feature.mfcc(signal, sampling_frequency=fs, frame_length=0.020, frame_stride=0.01,num_filters=40, fft_length=512, low_frequency=0, high_frequency=None)
	mfcc_cmvn = speechpy.processing.cmvnw(mfcc,win_size=301,variance_normalization=True)
	print('mfcc(mean + variance normalized) feature shape=', mfcc_cmvn.shape)


extractAudioMFCC("test.mp4", audio_out="out.wav")
extractAudioMFCC("out.wav")

The error I get:

Traceback (most recent call last):
File "TWK.py", line 99, in
extractAudioMFCC()
File "TWK.py", line 22, in extractAudioMFCC
signal = signal[:,0]
IndexError: too many indices for array

Am I using the wrong wav format?

Extracting log mel filterbank features

Thanks very much for the great library! It's my default library for speech processing now.

Just want to double check on the following, I want to extract 40-dimensional log mel filterbank feautres from sliding a Hamming window of width 25ms with an overlap of 10ms. Does the code below extract the right features? I am a bit uncertain whether frame_stride=0.01 creates overlap of 10ms..

fs, signal = wav.read(file_path)
lmfe = speechpy.feature.lmfe(signal, sampling_frequency=fs, frame_length=0.025, frame_stride=0.01, num_filters=40, fft_length=512, low_frequency=0, high_frequency=None)

Thanks!

no module main

Hi tryinig to use this in windows 7 64 bits 3.5 python
by pip or by git
no errors during the pip install

when i import pyspeech got this one :

import speechpy


ImportError Traceback (most recent call last)
in ()
----> 1 import speechpy

c:\anaconda3\lib\site-packages\speechpy_init_.py in ()
----> 1 from main import *
2 from processing import *

ImportError: No module named 'main'

Animated logo makes it difficult to read documentation

Hi,

Thanks for sharing your work. It looks interesting and I'd like to dig into it more. However I find it very difficult to work with the documentation here and on read the docs because of the blinking logo.

The animations in the graph are great. The logo however, is a serious drawback.

Thanks again.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.