"""RULE-coreml.md: the Core ML encoder on a Mac (ONNX Runtime's Core ML provider, CPU and Neural Engine). `prepare` writes expected.f32: the turn-taker's outputs here on openyap.py's 230 hops, for the phone to compare with. Also prints the hop times here. `features` writes the CallHome features for turns.py (RULE.md parts 1 and 2), as `port.py features` does. Run once. A model for both streams at once gets both windows in one prediction, as on the phone. python -I -B phone_coreml.py prepare --model export/l15.static.b2.fp16.onnx python -I -B phone_coreml.py features --model export/l15.static.b2.fp16.onnx --out runs/coreml """ from __future__ import annotations import argparse import json import sys import time from pathlib import Path import numpy as np HERE = Path(__file__).parent sys.path[:0] = [str(HERE), str(HERE.parent)] # vendor/ is one level up import coreml_try as ct # noqa: E402 import openyap as pb # noqa: E402 import port # noqa: E402 import tyger_ref as tr # noqa: E402 from l15 import LogMel # noqa: E402 from vendor.tyger_s2s.constants import SPEAK # noqa: E402 class Encoder: """window -> (frames, 1024); log-mels padded on the right to 801 frames; all-zero windows cached by length.""" def __init__(self, model: Path, units: str = "CPUAndNeuralEngine"): self.sess = ct.session(model, units) self.mel = LogMel(np.load(HERE / "data" / "mel_filters.npy")) self.dtype = np.float16 if "float16" in self.sess.get_inputs()[0].type else np.float32 self._zero: dict[int, np.ndarray] = {} def __call__(self, wav: np.ndarray) -> np.ndarray: if not wav.any() and len(wav) in self._zero: return self._zero[len(wav)] mel = self.mel(wav) x = np.zeros((1, 801, 128), self.dtype) x[0, :len(mel)] = mel out = self.sess.run(None, {"mel": x})[0][0, :(len(mel) - 1) // 8 + 1].astype(np.float32) if not wav.any(): self._zero[len(wav)] = out return out class PairEncoder(Encoder): """Both streams' windows -> their (frames, 1024), one prediction.""" def pair(self, win_u: np.ndarray, win_a: np.ndarray): mels = [self.mel(w) for w in (win_u, win_a)] x = np.zeros((2, 801, 128), self.dtype) for i, m in enumerate(mels): x[i, :len(m)] = m out = self.sess.run(None, {"mel": x})[0].astype(np.float32) n = (len(mels[0]) - 1) // 8 + 1 return out[0, :n], out[1, :n] def hop_frames(self, win_u, win_a): hu, ha = self.pair(win_u, win_a) act = tr.frame_energy(win_u) n = min(tr.HOP_FRAMES, len(hu), len(ha), len(act)) return hu[-n:], ha[-n:], act[-n:] def run(self, user, agent): hus, has, acts = zip(*(self.hop_frames(u, a) for u, a in tr.hops(user, agent))) return np.concatenate(hus), np.concatenate(has), np.concatenate(acts) def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("command", choices=["prepare", "features"]) parser.add_argument("--model", type=Path, required=True) parser.add_argument("--out", type=Path) args = parser.parse_args() two = ".b2." in args.model.name encode = (PairEncoder if two else Encoder)(args.model) hop_frames = encode.hop_frames if two else (lambda u, a: tr.hop_frames(encode, u, a)) if args.command == "features": args.out.mkdir(parents=True, exist_ok=False) for name, mode, user, agent in tr.segments(0): hu, ha, act = encode.run(user, agent) if two else tr.run(encode, user, agent) np.savez(args.out / f"{name}-{mode}.npz", hu=hu, ha=ha, act=act) print(name, mode, len(act), flush=True) return user, agent = pb.audio() tt = port.TurnTaker(HERE / "export" / "turn_taker.onnx", 2) outs, times = [], [] for win_u, win_a in tr.hops(user, agent): t0 = time.perf_counter() hu, ha, act = hop_frames(win_u, win_a) for i in range(len(act)): outs.append(tt(hu[i], ha[i], float(act[i]), SPEAK)) times.append((time.perf_counter() - t0) * 1e3) outs = np.stack(outs).astype("