Last active
January 23, 2025 03:49
-
-
Save tam17aki/23a700353260ae5be63b764218d6e481 to your computer and use it in GitHub Desktop.
An implementation of "Mel-Spectrogram Inversion via Alternating Direction Method of Multipliers" in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
"""Demonstration script for Mel-Spectrogram Inversion via ADMM. | |
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 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 ADMMConfig(NamedTuple): | |
"""Defines a class for ADMM configurations.""" | |
n_steps: int # Number of optimization steps | |
lambd: float # ADMM parameter | |
rho: float # ADMM parameter | |
def parse_args() -> tuple[Arguments, FeatureConfig, ADMMConfig]: | |
"""Parse command line arguments. | |
Returns: | |
arguments (Arguments): Miscellaneous configurations. | |
feat_config (FeatureConfig): Configurations of feature extraction. | |
admm_config (ADMMConfig): Configurations of ADMM. | |
""" | |
parser = argparse.ArgumentParser( | |
description="Demonstration script of ADMM-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="5000", help="ADMM parameter") | |
parser.add_argument("--rho", type=float, default="0.1", help="ADMM 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) | |
admm_config = ADMMConfig(n_steps=args.n_steps, lambd=args.lambd, rho=args.rho) | |
return arguments, feat_config, admm_config | |
def prox_pos(x: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]: | |
"""Proximity operator for non-negative constraint. | |
Args: | |
x (npt.NDArray[np.float64]): Input array. | |
Returns: | |
npt.NDArray[np.float64]: Non-negative version of input array. | |
""" | |
return np.maximum(x, 0) | |
def update_x( | |
y: npt.NDArray[np.float64], | |
z: npt.NDArray[np.complex128], | |
v: npt.NDArray[np.complex128], | |
config: ADMMConfig, | |
) -> npt.NDArray[np.complex128]: | |
"""Update complex STFT coefficients using the proximity operator. | |
Args: | |
y (npt.NDArray[np.float64]): Magnitude of STFT (Y). | |
z (npt.NDArray[np.complex128]): Complex STFT coefficients (Z). | |
v (npt.NDArray[np.complex128]): Dual variable (V). | |
config (Config): Configurations of ADMM. | |
Returns: | |
x_new (npt.NDArray[np.complex128]): Updated complex STFT coefficients (X). | |
""" | |
rho = config.rho | |
psi = z + v | |
abs_psi = np.abs(psi) | |
abs_psi = np.where(abs_psi == 0, 1e-8, abs_psi) | |
x_new_ = (y + rho * abs_psi) / (1 + rho) | |
x_new: npt.NDArray[np.complex128] = x_new_ * psi / abs_psi | |
return x_new | |
def update_w( | |
inv_mat: npt.NDArray[np.float64], | |
etm: npt.NDArray[np.float64], | |
y: npt.NDArray[np.float64], | |
u: npt.NDArray[np.float64], | |
config: ADMMConfig, | |
) -> npt.NDArray[np.float64]: | |
"""Update full-band magnitude using the linear system solution. | |
Args: | |
inv_mat (npt.NDArray[np.float64]): Inverse matrix in the algorithm. | |
etm (npt.NDArray[np.float64]): Product of tranpose of E and M (E^T @ M). | |
y (npt.NDArray[np.float64]): Magnitude of STFT (Y). | |
u (npt.NDArray[np.float64]): Dual variable (U). | |
config (ADMMConfig): Configurations of ADMM. | |
Returns: | |
w_new (npt.NDArray[np.float64]): Updated full-band magnitude (W). | |
""" | |
rho = config.rho | |
lambd = config.lambd | |
w_new = inv_mat @ (lambd * etm + rho * (y + u)) | |
return w_new | |
def update_z( | |
x: npt.NDArray[np.complex128], | |
v: npt.NDArray[np.complex128], | |
config: FeatureConfig, | |
) -> npt.NDArray[np.complex128]: | |
"""Update complex STFT coefficients by projecting onto the STFT domain. | |
Args: | |
x (npt.NDArray[np.complex128]): Complex STFT coefficients (X). | |
v (npt.NDArray[np.complex128]): Dual variable (V). | |
config (FeatureConfig): Configurations of feature extraction. | |
Returns: | |
z_new (npt.NDArray[np.complex128]): Updated complex STFT coefficients (Z). | |
""" | |
n_fft = config.n_fft | |
hop_length = config.hop_length | |
window = config.window | |
z_new = stft( | |
istft(x - v, hop_length=hop_length, window=window), | |
n_fft=n_fft, | |
hop_length=hop_length, | |
window=window, | |
) | |
return z_new | |
def update_y( | |
x: npt.NDArray[np.complex128], | |
w: npt.NDArray[np.float64], | |
u: npt.NDArray[np.float64], | |
config: ADMMConfig, | |
) -> npt.NDArray[np.float64]: | |
"""Update magnitude of STFT using proximity operator with non-negative constraint. | |
Args: | |
x (npt.NDArray[np.complex128]): Complex STFT coefficients (X). | |
w (npt.NDArray[np.float64]): Full-band magnitude (W). | |
u (npt.NDArray[np.float64]): Dual variable (U). | |
config (ADMMConfig): Configurations of ADMM. | |
Returns: | |
y_new (npt.NDArray[np.float64]): Updated magnitude of STFT (Y). | |
""" | |
rho = config.rho | |
y_new = prox_pos((np.abs(x) + rho * (w - u))) / (1 + rho) | |
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 admm_mel_inversion( | |
mel_spec: npt.NDArray[np.float64], | |
sr: int, | |
feat_config: FeatureConfig, | |
admm_config: ADMMConfig, | |
) -> npt.NDArray[np.float64]: | |
"""Perform ADMM-based mel-spectrogram inversion. | |
This function implements mel-spectrogram inversion using the Alternating Direction | |
Method of Multipliers (ADMM) algorithm, as described in the following paper: | |
"Mel-Spectrogram Inversion via Alternating Direction Method of Multipliers" | |
Yoshiki Masuyama, Natsuki Ueno, and Nobutaka Ono | |
arXiv:2501.05557, 2025 | |
Args: | |
mel_spec (npt.NDArray[np.float64]): Mel spectrogram. | |
sr (int): Sampling rate. | |
feat_config (FeatureConfig): Configurations of feature extraction. | |
admm_config (ADMMConfig): Configurations of ADMM. | |
Returns: | |
npt.NDArray[np.float64]: Reconstructed time-domain signal. | |
""" | |
n_mels = mel_spec.shape[0] | |
mel_filt = librosa.filters.mel(sr=sr, n_fft=feat_config.n_fft, n_mels=n_mels) | |
x = initialize_stft_from_mel(mel_spec, sr, feat_config.n_fft) | |
z = x | |
v = np.zeros_like(x, dtype=np.complex128) | |
y = np.abs(x) | |
w = y | |
u = np.zeros_like(y) | |
ete = np.dot(mel_filt.T, mel_filt) | |
etm = np.dot(mel_filt.T, mel_spec) | |
inv_mat = np.linalg.inv( | |
admm_config.lambd * ete + admm_config.rho * np.eye(ete.shape[0]) | |
) | |
for _ in tqdm( | |
range(admm_config.n_steps), | |
bar_format="{desc}: {percentage:3.0f}% ({n_fmt} of {total_fmt}) |{bar}|" | |
+ " Elapsed Time: {elapsed} ETA: {remaining} ", | |
ascii=" #", | |
): | |
x = update_x(y, z, v, admm_config) | |
w = update_w(inv_mat, etm, y, u, admm_config) | |
z = update_z(x, v, feat_config) | |
y = update_y(np.abs(x), w, u, admm_config) | |
v = v + z - x | |
u = u + y - w | |
return istft(x, 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, admm_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 = admm_mel_inversion(mel_spec, sr, feat_config, admm_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