Spaces:
Sleeping

File size: 6,163 Bytes
5a5e72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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]