8000 An implementation of “Signal reconstruction from melspectrogram based on bi-level consistency of full-band magnitude and phase" (iPALM-based mel-spectrogram inversion) in Python. · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Instantly share code, notes, and snippets.

@tam17aki
Last active January 19, 2025 14:39
Show Gist options
  • Save tam17aki/fa399bf28d2ba353a11fc56011a8a9c2 to your computer and use it in GitHub Desktop.
Save tam17aki/fa399bf28d2ba353a11fc56011a8a9c2 to your computer and use it in GitHub Desktop.
An implementation of “Signal reconstruction from melspectrogram based on bi-level consistency of full-band magnitude and phase" (iPALM-based mel-spectrogram inversion) in Python.
8000
# -*- coding: utf-8 -*-
"""Demonstration script for Mel-Spectrogram Inversion via iPALM.
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
< 8000 /td> import librosa
import numpy as np
import numpy.typing as npt
import soundfile as sf
from librosa.core.spectrum import istft, stft
from librosa.feature.spectral import melspectrogram
from pesq import pesq
from pystoi.stoi import stoi
from tqdm.auto import tqdm
class Arguments(NamedTuple):
"""Defines a class for miscellaneous configurations."""
in_file: str # input wav file
out_file: str # output (reconstructed) wav file
class FeatureConfig(NamedTuple):
"""Defines a class for configurations of feature extraction."""
n_mels: int # Number of Mel bins
n_fft: int = 1024 # FFT points
hop_length: int = 256 # Hop length
window: str = "hann" # Window type
class IPALMConfig(NamedTuple):
"""Defines a class for iPALM configurations."""
n_steps: int # Number of optimization steps
lambd: float # iPALM parameter
alpha: float # iPALM parameter
def parse_args() -> tuple[Arguments, FeatureConfig, IPALMConfig]:
"""Parse command line arguments.
Returns:
arguments (Arguments): Miscellaneous configurations.
feat_config (FeatureConfig): Configurations of feature extraction.
ipalm_config (IPALMConfig): Configurations of iPALM.
"""
parser = argparse.ArgumentParser(
description="Demonstration script of iPALM-based mel-spectrogram 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_mels", type=int, default="80", help="Number of Mel bins")
parser.add_argument(
"--n_steps", type=int, default="500", help="Number of optimization steps"
)
parser.add_argument("--lambd", type=float, default="10", help="iPALM parameter")
parser.add_argument("--alpha", type=float, default="0.9", help="iPALM parameter")
args = parser.parse_args()
arguments = Arguments(in_file=args.in_file, out_file=args.out_file)
feat_config = FeatureConfig(n_mels=args.n_mels)
ipalm_config = IPALMConfig(n_steps=args.n_steps, lambd=args.lambd, alpha=args.alpha)
return arguments, feat_config, ipalm_config
def update_x(
z: npt.NDArray[np.complex128], y: npt.NDArray[np.float64]
) -> npt.NDArray[np.complex128]:
"""Update X using the proximity operator.
Args:
z (npt.NDArray[np.complex128]): Complex STFT coefficients (Z).
y (npt.NDArray[np.float64]): Full band magnitude (Y).
Returns:
x_new (npt.NDArray[np.complex128]): Updated complex STFT coefficients (X).
"""
abs_z = np.abs(z)
abs_z = np.where(abs_z == 0, 1e-8, abs_z)
x_new: npt.NDArray[np.complex128] = y * z / abs_z
return x_new
def update_w(
e_pinv_e: npt.NDArray[np.float64],
e_pinv_m: npt.NDArray[np.float64],
y: npt.NDArray[np.float64],
) -> npt.NDArray[np.float64]:
"""Update W using the proximity operator.
Args:
e_pinv_e (npt.NDArray[np.float64]): Product of E and Moore-Penrose
pseudo-inverse of E (E^{†} @ E).
e_pinv_m (npt.NDArray[np.float64]): Product of M and Moore-Penrose
pseudo-inverse of E (E^{†} @ M).
y (npt.NDArray[np.complex128]): Full band magnitude (Y).
Returns:
w_new (npt.NDArray[np.float64]): Updated Full band magnitude (W).
"""
w_new: npt.NDArray[np.float64] = y - e_pinv_e @ y + e_pinv_m
return w_new
def update_z(
x: npt.NDArray[np.complex128], n_fft: int, hop_length: int, window: str
) -> npt.NDArray[np.complex128]:
"""Update Z by projecting onto the STFT domain.
Args:
x (npt.NDArray[np.complex128]): Complex STFT coefficients (X).
n_fft (int): FFT window size.
hop_length (int): Hop length.
window (str): Window type.
Returns:
z_new (npt.NDArray[np.complex128]): Updated complex STFT coefficients (Z).
"""
z_new = stft(
istft(x, hop_length=hop_length, window=window),
n_fft=n_fft,
hop_length=hop_length,
window=window,
)
return z_new
def update_y(
z: npt.NDArray[np.complex128], w: npt.NDArray[np.float64], lambd: float
) -> npt.NDArray[np.float64]:
"""Update Y using the proximity operator.
Args:
z (npt.NDArray[np.complex128]): Complex STFT coefficients (Z).
w (npt.NDArray[np.float64]): Full band magnitude (W).
lambd (float): iPALM parameter.
Returns:
y_new (npt.NDArray[np.float64]): Updated Full band magnitude (Y).
"""
y_new: npt.NDArray[np.float64] = np.maximum((np.abs(z) + lambd * w), 0)
y_new = y_new / (1 + lambd)
return y_new
def initialize_stft_from_mel(
mel_spec: npt.NDArray[np.float64], sr: int, n_fft: int
) -> npt.NDArray[np.complex128]:
"""Initialize STFT coefficients from mel-spectrogram using librosa.mel_to_stft.
Args:
mel_spec (npt.NDArray[np.float64]): Mel-spectrogram.
sr (int): Sampling rate.
n_fft (int): FFT size.
Returns:
npt.NDArray[np.complex128]: Initialized complex STFT coefficients.
"""
stft_coeffs: npt.NDArray[np.complex128] = librosa.feature.inverse.mel_to_stft(
mel_spec, sr=sr, n_fft=n_fft, power=1.0
)
random_phase = np.random.uniform(-np.pi, np.pi, stft_coeffs.shape)
random_complex: npt.NDArray[np.complex128] = np.exp(1j * random_phase)
return np.abs(stft_coeffs) * random_complex
def ipalm_mel_inversion(
mel_spec: npt.NDArray[np.float64],
sr: int,
feat_config: FeatureConfig,
ipalm_config: IPALMConfig,
) -> npt.NDArray[np.float64]:
"""Perform iPALM-based mel-spectrogram inversion.
This function implements mel-spectrogram inversion using the inertial Proximal
Alternating Linearized Minimization (iPALM) algorithm, as described in the
following paper:
"Signal reconstruction from mel-spectrogram based on bi-level consistency of
full-band magnitude and phase"
Yoshiki Masuyama, Natsuki Ueno, and Nobutaka Ono
In Proc. IEEE Workshop Appl. Signal Process. Audio Acoust. (WASPAA), Oct. 2023
Args:
mel_spec (npt.NDArray[np.float64]): Mel-spectrogram (M).
sr (int): Sampling rate.
feat_config (FeatureConfig): Configurations of feature extraction.
ipalm_config (IPALMConfig): Configurations of iPALM.
Returns:
reconstructed (npt.NDArray[np.float64]): Reconstructed time-domain signal.
"""
n_mels = mel_spec.shape[0]
mel_fbank = librosa.filters.mel(
sr=sr, n_fft=feat_config.n_fft, n_mels=n_mels
) # Mel-filterbank (E)
mel_fbank_pinv = np.linalg.pinv(
mel_fbank
) # Moore-Penrose pseudo-inverse of E (E^{†})
e_pinv_e = mel_fbank_pinv @ mel_fbank # E^{†} @ E
e_pinv_m = mel_fbank_pinv @ mel_spec # E^{†} @ M
z = initialize_stft_from_mel(mel_spec, sr, feat_config.n_fft)
z_old = z
y = np.abs(z)
for _ in tqdm(
range(ipalm_config.n_steps),
bar_format="{desc}: {percentage:3.0f}% ({n_fmt} of {total_fmt}) |{bar}|"
+ " Elapsed Time: {elapsed} ETA: {remaining} ",
ascii=" #",
):
x = update_x(z + ipalm_config.alpha * (z - z_old), y)
w = update_w(e_pinv_e, e_pinv_m, y)
z_old = z
z = update_z(x, feat_config.n_fft, feat_config.hop_length, feat_config.window)
y = update_y(z, w, ipalm_config.lambd)
return istft(z, hop_length=feat_config.hop_length, window=feat_config.window)
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, ipalm_config = parse_args()
orig_signal, sr = sf.read(args.in_file)
mel_spec = melspectrogram(
y=orig_signal,
sr=sr,
n_fft=feat_config.n_fft,
hop_length=feat_config.hop_length,
window=feat_config.window,
power=1.0,
)
reconst_signal = ipalm_mel_inversion(mel_spec, sr, feat_config, ipalm_config)
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,
)
estoi_score = calculate_estoi(orig_signal, reconst_signal, sr)
pesq_score = calculate_pesq(orig_signal, reconst_signal, sr)
scm_score = calculate_scm(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
0