from __future__ import annotations from pathlib import Path from typing import Any, Callable from .runtime import configure_tensorflow, configure_torch, cpu_voice_call import numpy as np from .asset_contract import load_manifest, need from .model_assets import resolve_model_asset from .audio_features import waveform_to_complex_spectrogram from .qualified_audio import decode_audio_file as to_waveform from .model_state import reloaded_variables_hash from .pixel_codec import quantize_rgb PAIRS = { "arcface": "ArcFace decoder", "facenet": "FaceNet decoder", } class SpeechToFace: def __init__(self, asset_dir: str | Path) -> None: self.asset_dir = Path(asset_dir) self._voices: dict[str, Any] = {} self._decoders: dict[str, Any] = {} self._manifests: dict[tuple[str, str], dict[str, Any]] = {} self._voice_output_devices: dict[str, str] = {} self._decoder_output_devices: dict[str, str] = {} def _manifest(self, part: str, pair: str) -> dict[str, Any]: if pair not in PAIRS: raise ValueError(f"Unknown pipeline {pair!r}") key = part, pair if key not in self._manifests: manifest = load_manifest(self.asset_dir, part, pair) other = self._manifests.get(("decoder" if part == "voice" else "voice", pair)) need( other is None or other["binding"] == manifest["binding"], "Crossed voice/decoder assets", ) self._manifests[key] = manifest return self._manifests[key] def voice(self, pair: str) -> Any: if pair not in self._voices: manifest = self._manifest("voice", pair) tf = configure_tensorflow() with tf.device("/CPU:0"): model = tf.keras.models.load_model( resolve_model_asset(self.asset_dir, manifest), compile=False, safe_mode=True, ) need( all(str(v.dtype) == "float32" for v in model.variables) and reloaded_variables_hash(model) == manifest["binding"]["voice_model_state_sha256"], "Loaded final voice model state differs", ) self._voices[pair] = model return self._voices[pair] def decoder(self, pair: str) -> Any: if pair not in self._decoders: manifest = self._manifest("decoder", pair) torch = configure_torch() from safetensors.torch import load_file from .native_wflw98_decoder import NativeWFLW98FaceDecoder state = load_file(str(resolve_model_asset(self.asset_dir, manifest)), device="cpu") model = NativeWFLW98FaceDecoder(state["warp.mean_landmarks"].clone()) model.load_state_dict(state, strict=True) model.cpu().eval().requires_grad_(False) need( all( p.dtype == torch.float32 and p.device.type == "cpu" for p in model.parameters() ), "Decoder must remain CPU float32", ) self._decoders[pair] = model return self._decoders[pair] def predict_fc7( self, audio_path: str | Path, pair: str, *, _audio_observer: Callable[[np.ndarray, np.ndarray], None] | None = None, ) -> np.ndarray: wave = to_waveform(audio_path) spectrogram = waveform_to_complex_spectrogram(wave) if _audio_observer is not None: _audio_observer(wave.copy(), spectrogram.copy()) return self.voice_stft(spectrogram, pair) def voice_stft( self, spectrogram: np.ndarray, pair: str, ) -> np.ndarray: need( spectrogram.dtype == np.float32 and spectrogram.shape == (598, 257, 2) and np.isfinite(spectrogram).all(), "Invalid STFT", ) result = cpu_voice_call(self.voice(pair), spectrogram[None]) self._voice_output_devices[pair] = result.device feature = result.numpy() need( feature.dtype == np.float32 and feature.shape == (1, 4096) and np.isfinite(feature).all(), "Final voice output differs", ) configure_tensorflow() return feature[0].copy() def raw_face(self, feature: np.ndarray, pair: str) -> np.ndarray: torch = configure_torch() values = np.asarray(feature) need( values.dtype == np.float32 and values.shape == (4096,) and np.isfinite(values).all(), "Invalid fc7", ) with torch.no_grad(): tensor = self.decoder(pair)(torch.from_numpy(values[None].copy()))["rendered_face"][0] need( tensor.dtype == torch.float32 and tensor.device.type == "cpu", "Decoder output must remain CPU float32", ) self._decoder_output_devices[pair] = str(tensor.device) result = tensor.cpu().numpy() configure_torch() return result def render_fc7( self, feature: np.ndarray, pair: str, *, _raw_observer: Callable[[np.ndarray], None] | None = None, ) -> np.ndarray: raw = self.raw_face(feature, pair) if _raw_observer is not None: _raw_observer(raw.copy()) pixels, _outside_fraction = quantize_rgb(raw) return pixels def infer( self, audio_path: str | Path, pair: str, *, _feature_observer: Callable[[np.ndarray], None] | None = None, _audio_observer: Callable[[np.ndarray, np.ndarray], None] | None = None, ) -> tuple[np.ndarray, np.ndarray]: feature = self.predict_fc7(audio_path, pair, _audio_observer=_audio_observer) if _feature_observer is not None: _feature_observer(feature.copy()) return feature, self.render_fc7(feature, pair) def __call__(self, audio_path: str, pair: str) -> np.ndarray: return self.infer(audio_path, pair)[1]