File size: 4,495 Bytes
55bf388
 
 
 
 
 
4defacc
 
55bf388
 
 
 
4defacc
 
 
 
 
a202342
 
4defacc
 
 
 
 
 
55bf388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4defacc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dca4123
4defacc
 
 
 
 
a202342
4defacc
 
 
 
 
 
55bf388
4defacc
 
 
 
 
 
55bf388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
169
import os
import gradio as gr
import numpy as np
import torch
import torchaudio
from typing import Tuple, Optional
import soundfile as sf
from s2st_inference import s2st_inference

SAMPLE_RATE = 16000
MAX_INPUT_LENGTH = 60  # seconds

S2UT_TAG = 'espnet/jiyang_tang_cvss-c_es-en_discrete_unit'
S2UT_DIR = 'model'
VOCODER_TAG = 'espnet/cvss-c_en_wavegan_hubert_vocoder'
VOCODER_DIR = 'vocoder'

NGPU = 0


def download_model(tag: str, out_dir: str):
    from huggingface_hub import snapshot_download

    return snapshot_download(repo_id=tag, local_dir=out_dir)


def s2st(
        audio_source: str,
        input_audio_mic: Optional[str],
        input_audio_file: Optional[str],
):
    if audio_source == 'file':
        input_path = input_audio_file
    else:
        input_path = input_audio_mic

    if input_path is None:
        gr.Error(f"Input audio is too long. Truncated to {MAX_INPUT_LENGTH} seconds.")
        return (None, None), None

    orig_wav, orig_sr = torchaudio.load(input_path)
    wav = torchaudio.functional.resample(orig_wav, orig_freq=orig_sr, new_freq=SAMPLE_RATE)
    max_length = int(MAX_INPUT_LENGTH * SAMPLE_RATE)
    if wav.shape[1] > max_length:
        wav = wav[:, :max_length]
        gr.Warning(f"Input audio is too long. Truncated to {MAX_INPUT_LENGTH} seconds.")

    wav = wav[0]  # mono

    # Download models
    os.makedirs(S2UT_DIR, exist_ok=True)
    os.makedirs(VOCODER_DIR, exist_ok=True)
    s2ut_path = download_model(S2UT_TAG, S2UT_DIR)
    vocoder_path = download_model(VOCODER_TAG, VOCODER_DIR)

    # Temporary change cwd to model dir so that it loads correctly
    cwd = os.getcwd()
    os.chdir(s2ut_path)

    # Translate wav
    out_wav = s2st_inference(
        wav,
        train_config=os.path.join(
            s2ut_path,
            'exp',
            's2st_train_s2st_discrete_unit_raw_fbank_es_en',
            'config.yaml',
        ),
        model_file=os.path.join(
            s2ut_path,
            'exp',
            's2st_train_s2st_discrete_unit_raw_fbank_es_en',
            '500epoch.pth',
        ),
        vocoder_file=os.path.join(
            vocoder_path,
            'checkpoint-450000steps.pkl',
        ),
        vocoder_config=os.path.join(
            vocoder_path,
            'config.yml',
        ),
        ngpu=NGPU,
    )

    # Restore working directory
    os.chdir(cwd)

    # Save result
    output_path = 'output.wav'
    sf.write(
        output_path,
        out_wav,
        16000,
        "PCM_16",
    )

    return output_path, f'Source: {audio_source}'


def update_audio_ui(audio_source: str) -> Tuple[dict, dict]:
    mic = audio_source == "microphone"
    return (
        gr.update(visible=mic, value=None),  # input_audio_mic
        gr.update(visible=not mic, value=None),  # input_audio_file
    )


def main():
    with gr.Blocks() as demo:
        with gr.Group():
            with gr.Row() as audio_box:
                audio_source = gr.Radio(
                    label="Audio source",
                    choices=["file", "microphone"],
                    value="file",
                )
                input_audio_mic = gr.Audio(
                    label="Input speech",
                    type="filepath",
                    source="microphone",
                    visible=False,
                )
                input_audio_file = gr.Audio(
                    label="Input speech",
                    type="filepath",
                    source="upload",
                    visible=True,
                )

            btn = gr.Button("Translate")

            with gr.Column():
                output_audio = gr.Audio(
                    label="Translated speech",
                    autoplay=False,
                    streaming=False,
                    type="numpy",
                )
                output_text = gr.Textbox(label="Translated text")

        audio_source.change(
            fn=update_audio_ui,
            inputs=audio_source,
            outputs=[
                input_audio_mic,
                input_audio_file,
            ],
            queue=False,
            api_name=False,
        )

        btn.click(
            fn=s2st,
            inputs=[
                audio_source,
                input_audio_mic,
                input_audio_file,
            ],
            outputs=[output_audio, output_text],
            api_name="run",
        )

        demo.queue(max_size=50).launch()


if __name__ == '__main__':
    main()