File size: 5,401 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
from __future__ import annotations

import os
from pathlib import Path
from threading import Lock, Thread
from typing import Any

from s2f import runtime as _runtime

os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"

import gradio as gr

from s2f.pipeline import PAIRS, SpeechToFace
from example_data import load_examples

ASSETS = Path(os.environ.get("S2F_ASSETS", Path(__file__).parent / "assets"))
MODEL = SpeechToFace(ASSETS)
_PAIR_LOAD_LOCKS = {pair: Lock() for pair in PAIRS}
_MODEL_LOAD_LOCK = Lock()
_READY_PAIRS: set[str] = set()
EXAMPLES = load_examples(Path(os.environ.get("S2F_EXAMPLES", Path(__file__).parent / "examples")))

TITLE = "Speech2Face"
INTRO = (
    "Record or upload about six seconds of speech. It guesses a frontal, neutral face: "
    "a rough, average-looking estimate, not the speaker's real face. "
    "Do not use it to identify anyone."
)
STORY = (
    "Follows Speech2Face (Oh et al., 2019) and Cole et al. (2017), with substitutions: "
    "voice to VGG-Face features to face. Trained on AVSpeech and VGGFace2."
)
CREDITS = (
    "**Credits**\n"
    "- Speech2Face: Oh et al., CVPR 2019. Face decoder: Cole et al., CVPR 2017. "
    "This is an independent version with substitutions.\n"
    "- AVSpeech (Ephrat et al., 2018): annotations © Google LLC, "
    "[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). "
    "The videos belong to their owners.\n"
    "- VGGFace2 (Cao et al., 2018). No images are included.\n"
    "- VGG-Face (Parkhi et al., 2015), CC BY-NC 4.0. Not included; these models depend on it.\n"
    "- The faces can reflect biases in the training data.\n"
    "- Licence: [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/), "
    "non-commercial use only."
)


def warm_models() -> None:
    failed = False
    for pair in PAIRS:
        try:
            with _PAIR_LOAD_LOCKS[pair]:
                if pair not in _READY_PAIRS:
                    with _MODEL_LOAD_LOCK:
                        MODEL.voice(pair)
                        MODEL.decoder(pair)
                        _READY_PAIRS.add(pair)
        except Exception:
            if not failed:
                print("Model warm-up failed; requests will retry loading.", flush=True)
                failed = True


def generate(audio: str | None, pair_label: str) -> Any:
    if audio is None:
        raise gr.Error("Record or upload a voice first.")
    pair = next(key for key, label in PAIRS.items() if label == pair_label)
    with _PAIR_LOAD_LOCKS[pair]:
        if pair not in _READY_PAIRS:
            with _MODEL_LOAD_LOCK:
                result = MODEL(audio, pair)
                _READY_PAIRS.add(pair)
                return result
    return MODEL(audio, pair)


def load_example(index: int | str | None) -> tuple[str | None, str | None, None]:
    if index is None:
        return None, None, None
    item = EXAMPLES[int(index)]
    return item["audio"], item["audio"], None


with gr.Blocks(title=TITLE, analytics_enabled=False) as demo:
    gr.Markdown(f"# {TITLE}\n{INTRO}")
    with gr.Tab("Try it"):
        with gr.Row():
            with gr.Column():
                audio = gr.Audio(
                    sources=["microphone", "upload"],
                    type="filepath",
                    format=None,
                    label="Your voice (about 6 s)",
                    buttons=[],
                )
                pair = gr.Radio(list(PAIRS.values()), value=PAIRS["arcface"], label="Decoder")
                button = gr.Button("Generate face", variant="primary")
            with gr.Column():
                face = gr.Image(label="Generated face", type="numpy", height=320)
        button.click(generate, inputs=[audio, pair], outputs=face)
        if EXAMPLES:
            with gr.Accordion("Examples", open=True):
                gr.Markdown(
                    "CC BY covers these clips; it does not give consent from the people shown."
                )
                gr.Markdown("To request removal of an example, use this Space's Community tab.")
                with gr.Row():
                    with gr.Column():
                        example = gr.Dropdown(
                            [(f"Example {i + 1}", i) for i in range(len(EXAMPLES))],
                            value=0,
                            label="Example voice",
                        )
                        load_button = gr.Button("Load example")
                        example_audio = gr.Audio(
                            type="filepath",
                            format=None,
                            label="Example voice",
                            interactive=False,
                            buttons=[],
                        )
                load_button.click(
                    load_example,
                    inputs=example,
                    outputs=[audio, example_audio, face],
                )
    with gr.Tab("How it was built"):
        gr.Markdown(f"{STORY}\n\n{CREDITS}")
        if EXAMPLES:
            example_credits = gr.Textbox(
                value="\n\n".join(
                    f"Example {i + 1}: {item['credit']}" for i, item in enumerate(EXAMPLES)
                ),
                label="Example credits",
                lines=12,
                interactive=False,
            )

if __name__ == "__main__":
    Thread(target=warm_models, daemon=True).start()
    demo.launch()