#!/usr/bin/env python3
"""Reproduce AmbientBlend's measured curves locally. Requires Python 3 and NumPy.

Download noise-spectra-four.json and the four WAV files named in contentUrl.
Place the WAV files in one folder, then run:
  python3 reproduce_noise_spectra.py --audio-dir ./audio

This script makes no network requests. Analysis code and measurement data are
provided under CC0: https://creativecommons.org/publicdomain/zero/1.0/
Audio reuse rights are described separately at https://ambientblend.com/audio-credits/
"""
import argparse
import hashlib
import json
from pathlib import Path
from urllib.parse import urlsplit
import wave
import numpy as np


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument('--data', type=Path, default=Path('noise-spectra-four.json'))
    cli.add_argument('--audio-dir', type=Path, default=Path('.'))
    args = cli.parse_args()
    data = json.loads(args.data.read_text())
    size, hop = data['windowSamples'], data['hopSamples']
    for curve in data['curves']:
        filename = Path(urlsplit(curve['contentUrl']).path).name
        audio = args.audio_dir / filename
        if hashlib.sha256(audio.read_bytes()).hexdigest() != curve['sha256']:
            raise ValueError(f'Audio hash mismatch: {filename}')
        with wave.open(str(audio)) as wav:
            if wav.getsampwidth() != 2 or wav.getnchannels() != 1:
                raise ValueError(f'Expected 16-bit mono WAV: {filename}')
            rate = wav.getframerate()
            samples = np.frombuffer(wav.readframes(wav.getnframes()), dtype='<i2').astype(float) / 32768
        frames = np.array([samples[i:i+size] * np.hanning(size) for i in range(0, len(samples)-size+1, hop)])
        density = np.mean(abs(np.fft.rfft(frames))**2, axis=0)
        frequency = np.fft.rfftfreq(size, 1/rate)
        edges = np.geomspace(*data['rangeHz'], data['bandCount']+1)
        centers = np.sqrt(edges[:-1]*edges[1:])
        power = np.array([density[(frequency >= a) & (frequency < b)].mean() for a, b in zip(edges[:-1], edges[1:])])
        db = 10*np.log10(np.maximum(power, 1e-20)/np.interp(data['referenceHz'], centers, power))
        if not np.allclose(db, curve['relativeDb'], atol=0.000001, rtol=0):
            raise ValueError(f'Measured points differ: {filename}')
        print(f"{curve['id']}: {len(db)} points reproduced; SHA-256 matches")


if __name__ == '__main__':
    main()
