Skip to content

Instantly share code, notes, and snippets.

@tam17aki
Last active January 19, 2025 12:21
Show Gist options
  • Save tam17aki/b5f6beb94565d2a5ba892149614c23d5 to your computer and use it in GitHub Desktop.
Save tam17aki/b5f6beb94565d2a5ba892149614c23d5 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""Demonstration script for MFCC Inversion.
Copyright (C) 2025 by Akira TAMAMORI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import argparse
from typing import NamedTuple
import numpy as np
import numpy.typing as npt
import soundfile as sf
from librosa.feature.inverse import mfcc_to_audio, mfcc_to_mel
from librosa.feature.spectral import melspectrogram, mfcc
from pesq import pesq
from pystoi.stoi import stoi
class Arguments(NamedTuple):
"""Defines a class for miscellaneous configurations."""
in_file: str # input wav file
out_file: str # output (reconstructed) wav file
n_iter: int # Number of iterations for Griffin-Lim
class FeatureConfig(NamedTuple):
"""Defines a class for configurations of feature extraction."""
n_mfcc: int # Number of MFCC bins
n_fft: int = 1024 # FFT points
hop_length: int = 256 # Hop length
n_mels: int = 128 # Number of Mel bins
window: str = "hann" # Window type
def parse_args() -> tuple[Arguments, FeatureConfig]:
"""Parse command line arguments.
Returns:
arguments (Arguments): Miscellaneous configurations.
feat_config (FeatureConfig): Configurations of feature extraction.
"""
parser = argparse.ArgumentParser(
description="Demonstration script of MFCC inversion"
)
parser.add_argument("--in_file", type=str, default="in.wav", help="Input wav file")
parser.add_argument(
"--out_file",
type=str,
default="out.wav",
help="output (reconstructed) wav file",
)
parser.add_argument("--n_mfcc", type=int, default="80", help="Number of MFCC bins")
parser.add_argument(
"--n_iter", type=int, default="500", help="Number of iterations for Griffin-Lim"
)
args = parser.parse_args()
arguments = Arguments(
in_file=args.in_file, out_file=args.out_file, n_iter=args.n_iter
)
feat_config = FeatureConfig(n_mfcc=args.n_mfcc)
return arguments, feat_config
def calculate_estoi(
orig_signal: npt.NDArray[np.float64],
reconst_signal: npt.NDArray[np.float64],
sr: int,
) -> float:
"""Calculate Extended Short-Time Objective Intelligibility (ESTOI).
Args:
orig_signal (npt.NDArray[np.float64]): Original time-domain signal.
reconst_signal (npt.NDArray[np.float64]): Reconstructed time-domain signal.
sr (int): Sampling rate.
Returns:
float: ESTOI score.
"""
if orig_signal.size > reconst_signal.size:
orig_signal = orig_signal[: reconst_signal.size]
else:
reconst_signal = reconst_signal[: orig_signal.size]
estoi_score: float = stoi(orig_signal, reconst_signal, sr, extended=True)
return estoi_score
def calculate_pesq(
orig_signal: npt.NDArray[np.float64],
reconst_signal: npt.NDArray[np.float64],
sr: int,
) -> float:
"""Calculate Perceptual Evaluation of Speech Quality (PESQ).
Args:
orig_signal (npt.NDArray[np.float64]): Original time-domain signal.
reconst_signal (npt.NDArray[np.float64]): Reconstructed time-domain signal.
sr (int): Sampling rate.
Returns:
float: PESQ score.
"""
pesq_score: float = pesq(sr, orig_signal, reconst_signal, "wb")
return pesq_score
def calculate_scm(
orig_spec: npt.NDArray[np.float64],
reconst_spec: npt.NDArray[np.float64],
) -> float:
"""Calculate Spectral Convergence Measure (SCM).
Args:
orig_spec (npt.NDArray[np.float64]): Original mel-spectrogram.
reconst_spec (npt.NDArray[np.float64]): Reconstructed mel-spectrogram.
Returns:
scm_score (float): SCM value in dB.
"""
numerator = np.linalg.norm(np.abs(reconst_spec) - orig_spec)
denominator = np.linalg.norm(orig_spec)
if denominator == 0:
return -float("inf")
scm_score: float = 20 * np.log10(numerator / denominator)
return scm_score
def main() -> None:
"""Perform demonstration."""
args, feat_config = parse_args()
orig_signal, sr = sf.read(args.in_file)
mfcc_coef = mfcc(
y=orig_signal,
sr=sr,
n_mfcc=feat_config.n_mfcc,
n_fft=feat_config.n_fft,
hop_length=feat_config.hop_length,
window=feat_config.window,
power=1.0,
)
reconst_signal = mfcc_to_audio(
mfcc_coef,
n_mels=feat_config.n_mels,
sr=sr,
n_fft=feat_config.n_fft,
hop_length=feat_config.hop_length,
power=1.0,
n_iter=args.n_iter,
)
sf.write(args.out_file, reconst_signal, sr)
reconst_mel_spec = melspectrogram(
y=reconst_signal,
sr=sr,
n_fft=feat_config.n_fft,
hop_length=feat_config.hop_length,
window=feat_config.window,
power=1.0,
)
orig_mel_spec = mfcc_to_mel(mfcc_coef, n_mels=feat_config.n_mels)
estoi_score = calculate_estoi(orig_signal, reconst_signal, sr)
pesq_score = calculate_pesq(orig_signal, reconst_signal, sr)
scm_score = calculate_scm(orig_mel_spec, reconst_mel_spec)
print(
f"ESTOI = {estoi_score:.6f}, "
+ f"PESQ = {pesq_score:.6f}, "
+ f"SCM [dB] = {scm_score:.6f}"
)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment