#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 joba1
# SPDX-License-Identifier: AGPL-3.0-or-later
'''
chordsplay-stems: split a song into its instruments for ChordsPlay's practice mix.

  chordsplay-stems [--device gpu|auto|cpu] SONG OUT.webm

Writes OUT.webm, one Opus file with an independent stereo pair per stem (vocals, drums,
bass, piano, other, guitar); OUT.json, the manifest: the pairs, where the guitar is loud
and in the centre of the stereo image (often the lead or solo) and the song's tempo and
beats; and OUT.peaks.json, the peak level of each stem and of the song per 10 ms for
the waveforms. See docs/spec-practice.md.

Runs in its own Python environment with python-audio-separator (PyTorch); ChordsPlay
calls it through CHORDSPLAY_STEMS_COMMAND. Needs ffmpeg with libopus.

  --device gpu    (default) the GPU; fails with "GPU busy" when less than --gpu-mb is free
  --device auto   the GPU if enough of it is free, else the CPU (several minutes per song)
  --device cpu    always the CPU
  --free-ollama URL  when the GPU is busy, ask the Ollama server at URL (e.g.
                  http://127.0.0.1:11434) to unload its models first; Ollama loads them again
                  by itself on its next request
  --rest-db DB    for finding the beats: the stems other than drums and bass this much
                  quieter (default -6; needs beat_this, else librosa on the whole song)
  --model NAME    separation model (default BS-Roformer-SW.ckpt; must give a guitar stem)
  --model-dir DIR where the model is kept (default ~/.cache/chordsplay-stems)
  --kbits N       Opus bit rate per stereo pair (default 96: ~2.3 MB per minute for 6 pairs)

Exit codes: 0 done, 2 usage, 3 GPU busy, 1 anything else (message on stderr).
'''

import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile

STEMS = ['vocals', 'drums', 'bass', 'piano', 'other', 'guitar']   # order of the pairs, guitar last
PAN_CENTER = 0.35       # |pan| below this is the centre (pan: -1 hard left .. +1 hard right)
FFT = 4096
STEP_S = 0.5            # the timeline's resolution
LEAD_DB = -15           # lead: the guitar within this of its loudest step ...
LEAD_SMOOTH = 4         # ... its centre share averaged over this many steps (2 s) ...
LEAD_MARGIN = 0.10      # ... this much above the song's own median share (a guitar that is
                        #     always in the centre has no lead to show) ...
LEAD_MIN_S = 4          # ... for at least this long (gaps up to LEAD_GAP_S bridged)
LEAD_GAP_S = 1
PEAKS_PER_S = 100       # the waveforms' resolution
OLLAMA_WAIT_S = 30      # how long to wait for the GPU memory after unloading Ollama's models
EXIT_GPU_BUSY = 3


def fail(message, code=1):
    print('chordsplay-stems: ' + message, file=sys.stderr)
    sys.exit(code)


def gpu_free_mb():
    '''Free memory of the first GPU in MB, or None without an NVIDIA GPU.'''
    try:
        out = subprocess.run(['nvidia-smi', '--query-gpu=memory.free', '--format=csv,noheader,nounits'],
                             capture_output=True, text=True, timeout=20).stdout
        return int(out.split()[0])
    except (OSError, ValueError, IndexError, subprocess.SubprocessError):
        return None


def free_ollama(url, need_mb):
    """Ask Ollama to unload its models (it loads them again on the next request) and wait
    until need_mb of GPU memory are free. True if they are."""
    import time
    import urllib.request

    def call(path, body=None):
        req = urllib.request.Request(url.rstrip('/') + path, data=json.dumps(body).encode() if body else None,
                                     headers={'Content-Type': 'application/json'})
        with urllib.request.urlopen(req, timeout=30) as r:
            return json.load(r)
    try:
        for model in call('/api/ps').get('models', []):
            call('/api/generate', {'model': model['name'], 'keep_alive': 0})
            print('chordsplay-stems: unloaded Ollama model ' + model['name'], file=sys.stderr)
    except OSError as e:
        print('chordsplay-stems: Ollama not reachable: {}'.format(e), file=sys.stderr)
        return False
    end = time.monotonic() + OLLAMA_WAIT_S
    while time.monotonic() < end:
        if (gpu_free_mb() or 0) >= need_mb:
            return True
        time.sleep(1)
    return False


def choose_device(device, need_mb, ollama=None):
    '''True: use the GPU. Exits with EXIT_GPU_BUSY for --device gpu without enough memory.'''
    if device == 'cpu':
        return False
    free = gpu_free_mb()
    if free is not None and free < need_mb and ollama and free_ollama(ollama, need_mb):
        free = gpu_free_mb()
    if free is not None and free >= need_mb:
        return True
    if device == 'auto':
        return False
    if free is None:
        fail('no GPU found (use --device auto or cpu)')
    fail(f'GPU busy: {free} MB free, {need_mb} MB needed', EXIT_GPU_BUSY)


def separate(song, work, model, model_dir, gpu):
    '''The model's stems as WAV files in work: {stem name: path}.'''
    env = dict(os.environ)
    if not gpu:
        env['CUDA_VISIBLE_DEVICES'] = ''
    tool = shutil.which('audio-separator') or os.path.join(os.path.dirname(sys.executable), 'audio-separator')
    # the separator names its files after the input: give it a plain name; and decoded to WAV
    # by ffmpeg, which reads any format (the separator's reader can't open .m4a, for one)
    plain = os.path.join(work, 'song.wav')
    dec = subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', song, '-vn', '-c:a', 'pcm_f32le', plain],
                         capture_output=True, text=True)
    if dec.returncode != 0:
        fail('could not decode the song: ' + (dec.stderr.strip().splitlines() or ['?'])[-1][-300:])
    run = subprocess.run([tool, '--model_filename', model, '--model_file_dir', model_dir,
                          '--output_dir', work, '--output_format', 'WAV', plain],
                         capture_output=True, text=True, env=env)
    if run.returncode != 0:
        errors = [line for line in (run.stderr + run.stdout).splitlines() if 'ERROR' in line]
        fail('separation failed: ' + (errors[-1] if errors else 'exit code {}'.format(run.returncode))[-400:])
    found = {}
    for name in os.listdir(work):
        low = name.lower()
        for stem in STEMS:
            if low.startswith('song_') and f'({stem})' in low and low.endswith('.wav'):
                found[stem] = os.path.join(work, name)
    missing = [s for s in STEMS if s not in found]
    if missing:
        fail('the model gave no ' + ', '.join(missing) + ' stem (it must give six, guitar included)')
    return found


def guitar_timeline(path):
    """Per STEP_S: the guitar's level (dB below its loudest step) and the share of its
    energy in the centre of the stereo image (0..1)."""
    import numpy as np
    import soundfile as sf
    from scipy.signal import stft

    x, sr = sf.read(path, always_2d=True)
    if x.shape[1] == 1:
        x = np.repeat(x, 2, axis=1)
    hop = FFT // 4
    _, _, sl = stft(x[:, 0], sr, nperseg=FFT, noverlap=FFT - hop)
    _, _, sr_ = stft(x[:, 1], sr, nperseg=FFT, noverlap=FFT - hop)
    al, ar = np.abs(sl), np.abs(sr_)
    energy = al ** 2 + ar ** 2
    pan = (ar - al) / (al + ar + 1e-9)
    center = (np.abs(pan) < PAN_CENTER) * energy
    # each frame into the step of its time (frame k is centred at k * hop): a whole number of
    # frames per step would drift (22 for 21.5 put 1:24 at 1:26, 2 % per step)
    step_of = (np.arange(energy.shape[1]) * hop / sr / STEP_S).astype(int)
    n = int(step_of[-1]) + 1 if step_of.size else 0
    total = np.bincount(step_of, weights=energy.sum(axis=0), minlength=n)
    mid = np.bincount(step_of, weights=center.sum(axis=0), minlength=n)
    db = 10 * np.log10(total / max(total.max(), 1e-12) + 1e-12)
    share = np.where(total > 0, mid / np.maximum(total, 1e-12), 0)
    # lead: loud guitar whose centre share is high for this song (records differ a lot)
    smooth = np.convolve(share, np.ones(LEAD_SMOOTH) / LEAD_SMOOTH, mode='same')
    audible = db > LEAD_DB
    limit = np.median(share[audible]) + LEAD_MARGIN if audible.any() else 2
    lead = runs(audible & (smooth > max(limit, 0.5)), int(LEAD_MIN_S / STEP_S), int(LEAD_GAP_S / STEP_S))
    return {'step': STEP_S,
            'guitar_db': [max(-99, int(round(v))) for v in db],
            'guitar_center': [round(float(v), 2) for v in share],
            'lead': [int(v) for v in lead]}


def runs(flags, min_len, max_gap):
    """flags with gaps up to max_gap filled, then only runs of at least min_len kept."""
    out = list(flags)
    n = len(out)
    i = 0
    while i < n:                     # bridge short gaps between two marked steps
        if not out[i]:
            j = i
            while j < n and not out[j]:
                j += 1
            if 0 < i and j < n and j - i <= max_gap:
                out[i:j] = [True] * (j - i)
            i = j
        else:
            i += 1
    i = 0
    while i < n:                     # drop runs that are too short
        if out[i]:
            j = i
            while j < n and out[j]:
                j += 1
            if j - i < min_len:
                out[i:j] = [False] * (j - i)
            i = j
        else:
            i += 1
    return [bool(v) for v in out]


def peaks(path, rate=44100):
    """The peak level (both channels) per 1/PEAKS_PER_S s, as bytes 0..255 (linear)."""
    import librosa
    import numpy as np

    y, sr = librosa.load(path, sr=rate, mono=False)
    y = np.atleast_2d(y)
    a = np.abs(y).max(axis=0)
    per = sr // PEAKS_PER_S
    n = len(a) // per
    p = a[:n * per].reshape(n, per).max(axis=1) if n else np.zeros(0)
    return np.clip(np.round(p * 255), 0, 255).astype(np.uint8).tobytes()


def rhythm_mix(stems, rest_db):
    """Drums and bass at full level, the other stems rest_db quieter: the beat as a listener
    finds it (keyboards and synths mislead a beat tracker less), and where drums and bass
    pause the rest still carries a beat, while an intro without rhythm stays quiet."""
    import numpy as np
    import soundfile as sf

    g = 10 ** (rest_db / 20)
    mix, sr = None, None
    for stem in STEMS:
        x, sr = sf.read(stems[stem], always_2d=True)
        x = x.mean(axis=1) * (1.0 if stem in ('drums', 'bass') else g)
        mix = x if mix is None else mix[:len(x)] + x[:len(mix)]
    return mix.astype('float32'), sr


def beats_of(stems, song, rest_db, gpu, model_dir):
    """Tempo (bpm) and beat times (s): beat_this (JKU, 2024) on the rhythm mix; without
    beat_this installed, librosa's tracker on the whole song (less exact, constant tempo).
    The tempo may be half or double the felt one: the page lets you halve or double it."""
    import numpy as np
    try:
        os.environ.setdefault('TORCH_HOME', model_dir)      # its checkpoint goes next to the model
        from beat_this.inference import Audio2Beats
    except ImportError:
        Audio2Beats = None
    if Audio2Beats is not None:
        signal, sr = rhythm_mix(stems, rest_db)
        tracker = Audio2Beats(checkpoint_path='final0', device='cuda' if gpu else 'cpu', dbn=False)
        times, _ = tracker(signal, sr)
        times = np.asarray(times, dtype=float)
        if len(times) < 4:
            return None, [], 'beat_this'
        tempo = 60 / float(np.median(np.diff(times)))
        return round(tempo, 1), [round(float(t), 3) for t in times], 'beat_this'
    import librosa
    y, sr = librosa.load(song, sr=22050, mono=True)
    tempo, frames = librosa.beat.beat_track(y=y, sr=sr)
    times = librosa.frames_to_time(frames, sr=sr)
    tempo = float(np.atleast_1d(tempo)[0])
    if tempo <= 0 or len(times) < 4:
        return None, [], 'librosa'
    return round(tempo, 1), [round(float(t), 3) for t in times], 'librosa'


def encode(pairs, out, kbits):
    '''One Opus/WebM file with the stereo files of pairs (in order) as independent channels.'''
    cmd = ['ffmpeg', '-v', 'error', '-y']
    for _, path in pairs:
        cmd += ['-i', path]
    n = len(pairs)
    # each input to exactly two channels at the stems' rate, then all side by side
    graph = ''.join(f'[{i}:a]aresample=44100,aformat=channel_layouts=stereo[s{i}];' for i in range(n))
    graph += ''.join(f'[s{i}]' for i in range(n)) + f'amerge=inputs={n}[all]'
    cmd += ['-filter_complex', graph, '-map', '[all]', '-c:a', 'libopus', '-mapping_family', '255',
            '-b:a', f'{kbits * n}k', '-f', 'webm', out]
    run = subprocess.run(cmd, capture_output=True, text=True)
    if run.returncode != 0:
        fail('encoding failed: ' + run.stderr.strip()[-400:])


def main():
    parser = argparse.ArgumentParser(description='Split a song into stems for ChordsPlay\'s practice mix.')
    parser.add_argument('song')
    parser.add_argument('out', help='output file, .webm; the manifest goes next to it as .json')
    parser.add_argument('--device', choices=['gpu', 'auto', 'cpu'], default='gpu')
    parser.add_argument('--gpu-mb', type=int, default=4000, help='free GPU memory needed (MB)')
    parser.add_argument('--model', default='BS-Roformer-SW.ckpt')
    parser.add_argument('--free-ollama', metavar='URL',
                        help='when the GPU is busy, unload the models of the Ollama server at URL first')
    parser.add_argument('--kbits', type=int, default=96, help='Opus kbit/s per stereo pair')
    parser.add_argument('--rest-db', type=float, default=-6,
                        help='level of the stems other than drums and bass for the beat tracker (dB)')
    parser.add_argument('--model-dir', default=os.path.expanduser('~/.cache/chordsplay-stems'))
    args = parser.parse_args()
    if not os.path.isfile(args.song):
        fail('no such file: ' + args.song, 2)
    if not args.out.endswith('.webm'):
        fail('the output must end in .webm', 2)
    gpu = choose_device(args.device, args.gpu_mb, args.free_ollama)
    os.makedirs(args.model_dir, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix='chordsplay-stems-') as work:
        stems = separate(args.song, work, args.model, args.model_dir, gpu)
        decoded = os.path.join(work, 'song.wav')     # the song as WAV: every reader opens that
        pairs = [(stem, stems[stem]) for stem in STEMS]
        encode(pairs, args.out, args.kbits)
        meta = {'version': 5, 'model': os.path.splitext(args.model)[0], 'channels': 2 * len(pairs),
                'device': 'gpu' if gpu else 'cpu',
                'stems': [{'name': stem, 'pair': i} for i, (stem, _) in enumerate(pairs)]}
        # analysis only adds to the mix: if it fails, the stems are still usable
        try:
            meta['timeline'] = guitar_timeline(stems['guitar'])
        except Exception as e:      # noqa: BLE001
            print('chordsplay-stems: no guitar timeline: {}'.format(e), file=sys.stderr)
        try:
            tempo, beats, tracker = beats_of(stems, decoded, args.rest_db, gpu, args.model_dir)
            if tempo:
                meta['tempo'], meta['beats'], meta['beat_tracker'] = tempo, beats, tracker
        except Exception as e:      # noqa: BLE001
            print('chordsplay-stems: no beats: {}'.format(e), file=sys.stderr)
        try:
            import base64
            tracks = {'song': decoded, **{stem: stems[stem] for stem in STEMS}}
            data = {'rate': PEAKS_PER_S,
                    'tracks': {name: base64.b64encode(peaks(path)).decode() for name, path in tracks.items()}}
            with open(os.path.splitext(args.out)[0] + '.peaks.json', 'w') as f:
                json.dump(data, f)
        except Exception as e:      # noqa: BLE001
            print('chordsplay-stems: no waveforms: {}'.format(e), file=sys.stderr)
    with open(os.path.splitext(args.out)[0] + '.json', 'w') as f:
        json.dump(meta, f, indent=1)


if __name__ == '__main__':
    main()
