""" This script normalizes all stimuli to the same loudness and upmixes them from mono to stereo """
import soundfile as sf
import pyloudnorm as pyln

def normalize_loudness(y, sampling_rate, lufs = -23):
    """
    Normalizes the signal y to the specified number of LUFS. 
    By default, the loudness is normalized to -23 LUFS according to the EBU R 128 standard.
    """
    # measure the loudness first 
    meter = pyln.Meter(sampling_rate)
    loudness = meter.integrated_loudness(y)
    # loudness normalize audio
    return pyln.normalize.loudness(y, loudness, lufs)


if __name__ == "__main__":    
    from pathlib import Path
    from tqdm import tqdm
    import numpy as np
    
    t_silence_s = 0.1
    wav_path = "."
    out_path = Path(wav_path) / "normalized"
    out_path.mkdir(exist_ok=True)
    for wav in tqdm(Path(wav_path).glob('*.wav')):
        data, sr = sf.read(str(wav))
        # Zero padding
        if len(data.shape) < 2:
            data = np.pad(data, (int(sr * t_silence_s), int(sr * t_silence_s)))
        else:
            data = np.pad(data, ((int(sr * t_silence_s), int(sr * t_silence_s)), (0, 0)))
        normalized = normalize_loudness(data, sr)
        # Write as stereo file
        if len(normalized.shape) < 2:
           normalized = np.asarray([normalized, normalized]).T
        sf.write(str(out_path / wav.name), normalized, sr)