#!/usr/bin/env python3
"""Stream audio to a Ground State Foundry model and get the output back live.

  pip install websockets numpy
  export GSF_API_KEY=gsf_...
  python gsf_stream.py --model antflash-us input.wav output.wav        # a file, sent at real-time pace
  python gsf_stream.py --model nearfield --mic output.wav              # the microphone (pip install sounddevice); Ctrl-C to stop
  options: --nf (Nearfield voice isolation first)  --up (Ant Flash: upscale output to 48 kHz)

Input can be any PCM WAV (mono or stereo, any rate); it is sent as 16 kHz mono. Output is a WAV at the model's
rate. Streams are billed per minute open (or of audio sent, if more). One stream lasts at most 14 minutes; for longer audio this
script opens a new stream and carries on (Ant Flash re-learns the voice in the first 3 seconds of each stream).
Docs: https://groundstatefoundry.com/models/skill
"""
import argparse, asyncio, base64, json, os, sys, time, wave

import numpy as np
import websockets

STREAM_URL = os.environ.get("GSF_STREAM_URL", "wss://stream.groundstatefoundry.com")
PIECE = 1600                                    # 100 ms at 16 kHz
CODES = {401: "API key not valid (check GSF_API_KEY)", 402: "no credit left: POST /v1/credits/request",
         403: "account disabled", 429: "rate limited: slow down"}


def read_wav(path):
    with wave.open(path) as w:
        if w.getsampwidth() != 2: sys.exit("input must be 16-bit PCM WAV")
        sr, ch = w.getframerate(), w.getnchannels(); x = np.frombuffer(w.readframes(w.getnframes()), "<i2").astype(np.float32) / 32768
    x = x.reshape(-1, ch).mean(1)
    if sr != 16000:
        try:
            from scipy.signal import resample_poly; from math import gcd
            g = gcd(sr, 16000); x = resample_poly(x, 16000 // g, sr // g).astype(np.float32)
        except ImportError:
            x = np.interp(np.arange(0, len(x) * 16000 / sr) * sr / 16000, np.arange(len(x)), x).astype(np.float32)
    return x


def b64(x): return base64.b64encode((np.clip(x, -1, 1) * 32767).astype("<i2").tobytes()).decode()


async def one_stream(key, model, nf, up, source, sink, budget_s):
    """Run one stream: send pieces from `source` (an async iterator of float32 16 kHz arrays) until it ends or
    budget_s of audio has gone, collect output into sink(list). Returns ("done"|"more", stats)."""
    try:
        ws = await websockets.connect(STREAM_URL, additional_headers={"Authorization": f"Bearer {key}"}, max_size=None)
    except websockets.InvalidStatus as e:
        code = e.response.status_code; sys.exit(f"could not connect: {code} {CODES.get(code, '')}")
    sr = None; algo = 0.0; worker = None; ready = asyncio.Event(); ended = asyncio.Event(); sent = 0; lag = []; t0 = None; why = ""

    async def recv():
        nonlocal sr, algo, worker, why
        async for raw in ws:
            m = json.loads(raw); t = m.get("t")
            if t == "route":
                worker = m["worker"]
                if sr: ready.set()
            elif t == "ready":
                sr = m["sr"]; algo = m.get("algo_ms", 0) / 1000
                if worker: ready.set()
                print(f"ready: {model} -> {sr} Hz, model look-ahead {m['algo_ms']} ms" + (" (cold start)" if m.get("cold") else ""), file=sys.stderr)
            elif t == "status": print("server:", m.get("msg"), file=sys.stderr)
            elif t == "out":
                y = np.frombuffer(base64.b64decode(m["pcm"]), "<i2").astype(np.float32) / 32768; sink.append(y)
                if t0: lag.append(time.time() - t0 - m["end"] / sr + algo)   # output sample k is input time k/sr - look-ahead
            elif t == "error":
                why = m.get("code", "error"); print("error:", m.get("code"), m.get("msg"), file=sys.stderr); ready.set(); ended.set(); return
            elif t == "end": why = why or m.get("reason", ""); ended.set(); return

    rt = asyncio.create_task(recv())
    await ws.send(json.dumps({"action": "start", "model": model, "nf": int(nf), "up": int(up)}))
    await asyncio.wait_for(ready.wait(), 120)
    if not sr: rt.cancel(); await ws.close(); sys.exit(f"stream did not start: {why}")
    t0 = time.time(); more = False
    async for x in source:
        if ended.is_set(): break
        await ws.send(json.dumps({"action": "audio", "to": worker, "n": sent, "pcm": b64(x)})); sent += len(x)
        if sent / 16000 >= budget_s: more = True; break
    if not ended.is_set():
        z = b64(np.zeros(PIECE, np.float32))
        for _ in range(10): await ws.send(json.dumps({"action": "audio", "to": worker, "n": sent, "pcm": z})); sent += PIECE  # flush the tail
        await asyncio.sleep(1.5)
        await ws.send(json.dumps({"action": "stop", "to": worker}))
        try: await asyncio.wait_for(ended.wait(), 10)
        except asyncio.TimeoutError: pass
    rt.cancel(); await ws.close()
    if why == "out_of_credit": sys.exit("stopped: out of credit")
    if lag: print(f"behind the input: median {np.median(lag):.2f} s (includes the network)", file=sys.stderr)
    return ("more" if more else "done"), sr


async def file_source(x, start):
    """Yield 100 ms pieces from `start` on, at real-time pace (the models work in real time)."""
    t = time.time(); i = start[0]
    while i < len(x):
        await asyncio.sleep(max(0, (i - start[0]) / 16000 - (time.time() - t)))
        yield x[i:i + PIECE]; i += PIECE; start[1] = i


async def mic_source(stop):
    import sounddevice as sd
    q = asyncio.Queue(); loop = asyncio.get_running_loop()
    with sd.InputStream(samplerate=16000, channels=1, dtype="float32", blocksize=PIECE,
                        callback=lambda d, f, t, s: loop.call_soon_threadsafe(q.put_nowait, d[:, 0].copy())):
        print("listening; Ctrl-C to stop", file=sys.stderr)
        while not stop.is_set(): yield await q.get()


async def main():
    a = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    a.add_argument("--model", required=True, choices=["antflash-us", "antflash-ar", "upscaler", "nearfield"])
    a.add_argument("--nf", action="store_true"); a.add_argument("--up", action="store_true"); a.add_argument("--mic", action="store_true")
    a.add_argument("paths", nargs="+", help="input.wav output.wav, or with --mic just output.wav")
    o = a.parse_args(); key = os.environ.get("GSF_API_KEY") or sys.exit("set GSF_API_KEY")
    out_path = o.paths[-1]; chunks = []; sr = None
    if o.mic:
        import signal
        stop = asyncio.Event(); asyncio.get_running_loop().add_signal_handler(signal.SIGINT, stop.set)
        _, sr = await one_stream(key, o.model, o.nf, o.up, mic_source(stop), chunks, 14 * 60)
    else:
        x = read_wav(o.paths[0]); pos = [0, 0]
        while pos[0] < len(x):
            state, sr = await one_stream(key, o.model, o.nf, o.up, file_source(x, pos), chunks, 14 * 60)
            if state == "done": break
            pos[0] = pos[1]; print(f"continuing at {pos[0] / 16000:.0f} s in a new stream", file=sys.stderr)
    y = np.concatenate(chunks) if chunks else np.zeros(0, np.float32)
    with wave.open(out_path, "wb") as w:
        w.setnchannels(1); w.setsampwidth(2); w.setframerate(sr or 16000); w.writeframes((np.clip(y, -1, 1) * 32767).astype("<i2").tobytes())
    print(f"wrote {out_path}: {len(y) / (sr or 16000):.1f} s at {sr} Hz", file=sys.stderr)


if __name__ == "__main__":
    try: asyncio.run(main())
    except KeyboardInterrupt: pass
