import hashlib import json from pathlib import Path import re import shutil import subprocess import numpy as np import soundfile as sf from scipy.signal import find_peaks HERE = Path(__file__).resolve().parent BASELINE = HERE.parent / "giant-coltrane-guitar-01" PROJECT = HERE.parents[1] PROTECTED = [BASELINE / name for name in ("score.json", "phrasing.json", "guitar.wav", "mix.wav", "rhythm.wav")] PROTECTED += [PROJECT / "instruments/music2" / name for name in ("guitar-dsp.mjs", "guitar-fill.mjs", "dsp.mjs", "synth.mjs")] def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def loudness(path): result = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", str(path), "-af", "loudnorm=I=-23:TP=-1:LRA=11:print_format=json", "-f", "null", "-"], check=True, capture_output=True, text=True) matches = re.findall(r"\{[^{}]*\}", result.stderr, flags=re.S) values = json.loads(matches[-1]) return float(values["input_i"]) def export(name, audio, rate): if not np.isfinite(audio).all() or np.max(np.abs(audio)) >= .999: raise ValueError(f"Unsafe output: {name}") path = HERE / f"{name}.wav" sf.write(path, audio, rate, subtype="PCM_24") subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(path), "-c:a", "libmp3lame", "-b:a", "192k", str(HERE / f"{name}.mp3")], check=True) def estimate_pitch(audio, rate): signal = audio[round(.12 * rate):round(.75 * rate), 0] fft_size = 1 << (2 * len(signal) - 1).bit_length() centered = signal - np.mean(signal) spectrum = np.fft.rfft(centered, fft_size) correlation = np.fft.irfft(spectrum * spectrum.conj(), fft_size)[:len(signal)] correlation /= np.arange(len(signal), 0, -1) lower, upper = round(rate / 1800), round(rate / 70) peaks, _ = find_peaks(correlation[lower:upper]) if not len(peaks): raise ValueError("No unconstrained pitch-correlation peak") lags = peaks + lower best = int(lags[np.argmax(correlation[lags])]) denominator = correlation[best - 1] - 2 * correlation[best] + correlation[best + 1] offset = .5 * (correlation[best - 1] - correlation[best + 1]) / denominator if denominator else 0 return rate / (best + offset) def main(): hashes = {str(path.relative_to(PROJECT)): digest(path) for path in PROTECTED} old, rate = sf.read(BASELINE / "guitar.wav") rhythm, rhythm_rate = sf.read(BASELINE / "rhythm.wav") raw, raw_rate = sf.read(HERE / "guitar-raw.wav") if rate != 44100 or rhythm_rate != rate or raw_rate != rate or raw.shape != old.shape or rhythm.shape != old.shape: raise ValueError("Lead/backing sample rates or frame counts differ") start, end = round(19.7 * rate), round(58.1 * rate) sf.write(HERE / "reference-solo.wav", old[start:end], rate, subtype="PCM_24") sf.write(HERE / "candidate-solo-raw.wav", raw[start:end], rate, subtype="PCM_24") reference_lufs = loudness(HERE / "reference-solo.wav") candidate_lufs = loudness(HERE / "candidate-solo-raw.wav") gain_db = reference_lufs - candidate_lufs gain = 10 ** (gain_db / 20) weight = np.zeros(len(old)) weight[start:end] = 1 fade = round(.012 * rate) ramp = np.linspace(0, 1, fade) ramp = ramp ** 2 * (3 - 2 * ramp) weight[start:start + fade] = ramp weight[end - fade:end] = ramp[::-1] matched_gain = gain for attempt in range(200): guitar = old * (1 - weight[:, None]) + raw * gain * weight[:, None] mix = guitar + rhythm if np.max(np.abs(mix)) < .94: break gain *= .97 else: raise ValueError("Cannot preserve the head and backing with requested headroom") for name, audio in (("guitar", guitar), ("mix", mix), ("solo-guitar", guitar[start:end]), ("solo-band", mix[start:end]), ("baseline-solo-guitar", old[start:end]), ("baseline-solo-band", old[start:end] + rhythm[start:end])): export(name, audio, rate) shutil.copyfile(BASELINE / "rhythm.wav", HERE / "rhythm.wav") probe_old, probe_rate = sf.read(HERE / "probe-old-raw.wav") probe_new, new_rate = sf.read(HERE / "probe-new-raw.wav") if probe_rate != rate or new_rate != rate or probe_old.shape != probe_new.shape: raise ValueError("Probe shape mismatch") probe_gain_db = loudness(HERE / "probe-old-raw.wav") - loudness(HERE / "probe-new-raw.wav") probe_new *= 10 ** (probe_gain_db / 20) probe_safety = min(1, .88 / max(np.max(np.abs(probe_old)), np.max(np.abs(probe_new)))) export("probe-old", probe_old * probe_safety, rate) export("probe-new", probe_new * probe_safety, rate) pitch_checks = [] for pitch in [55, 64, 66, 72, 79]: audio, probe_rate = sf.read(HERE / f"dry-{pitch}.wav") measured = estimate_pitch(audio, probe_rate) target = 440 * 2 ** ((pitch - 69) / 12) cents = 1200 * np.log2(measured / target) pitch_checks.append({"midi": pitch, "frequencyHz": measured, "cents": float(cents)}) if abs(cents) > 20: raise ValueError(f"Pitch mismatch at MIDI {pitch}: {cents:.1f} cents") exported, exported_rate = sf.read(HERE / "guitar.wav") model = json.loads((HERE / "model-report.json").read_text()) checks = { "scoreByteIdentical": digest(HERE / "score.json") == digest(BASELINE / "score.json"), "phrasingByteIdentical": digest(HERE / "phrasing.json") == digest(BASELINE / "phrasing.json"), "rhythmByteIdentical": digest(HERE / "rhythm.wav") == digest(BASELINE / "rhythm.wav"), "headPcmIdentical": exported_rate == rate and np.array_equal(exported[:start], old[:start]), "returnAndEndingPcmIdentical": np.array_equal(exported[end:], old[end:]), "protectedSourcesUnchanged": hashes == {str(path.relative_to(PROJECT)): digest(path) for path in PROTECTED}, "freeEnergyDecreasesAtFiveProbePitches": all(probe["freeEnergyDecreases"] for probe in model["probes"]), "allSamplesFinite": bool(np.isfinite(mix).all()), "mixHeadroom": float(np.max(np.abs(mix))) < .94, } report = { "status": "New guitar-source experiment, unapproved; not a saxophone", "change": "Physical string motion, pluck release and pickup; same solo notes, timing and backing", "sampleFree": True, "paidApiCalls": 0, "durationSeconds": len(mix) / rate, "soloSpanSeconds": [19.7, 58.1], "referenceSoloLufs": reference_lufs, "candidateRawSoloLufs": candidate_lufs, "soloGainDb": float(20 * np.log10(gain)), "headroomAdjustmentDb": float(20 * np.log10(gain / matched_gain)), "exportedSoloLufs": loudness(HERE / "solo-guitar.wav"), "probeMatchGainDb": probe_gain_db, "probeSharedSafetyGain": float(probe_safety), "mixPeak": float(np.max(np.abs(mix))), "pitchChecks": pitch_checks, "checks": checks, "sourceSHA256": hashes, "localSourceSHA256": {name: digest(HERE / name) for name in ("string_model.mjs", "render.mjs", "compare.py", "score.json", "phrasing.json")}, "limits": model["limits"] + ["Loudness matching is not a listening verdict", "The original head remains unchanged; only the solo span tests the new model"], } (HERE / "report.json").write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") if not all(checks.values()): raise AssertionError(checks) print(json.dumps({key: value for key, value in report.items() if key not in ["sourceSHA256", "localSourceSHA256", "limits"]}, indent=2)) if __name__ == "__main__": main()