Spaces:
Runtime error
Runtime error
Auxiliarytrinket
commited on
Commit
•
814f850
1
Parent(s):
b78ea10
Update app.py
Browse files
app.py
CHANGED
@@ -3,66 +3,63 @@ import numpy as np
|
|
3 |
import torch
|
4 |
from datasets import load_dataset
|
5 |
|
6 |
-
from transformers import AutoTokenizer, VitsModel, pipeline
|
7 |
|
8 |
-
|
9 |
-
device_name = "cuda:0" if torch.cuda.is_available() else "cpu"
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
my_awesome_translator = huggingface_pipeline("translation", model="Helsinki-NLP/opus-mt-en-ru")
|
14 |
|
15 |
-
#
|
16 |
-
|
17 |
-
|
18 |
-
return translator_model(speech_recognition_result['text'])[0]['translation_text']
|
19 |
|
20 |
-
# Модели для синтеза голоса
|
21 |
-
speech_synthesis_model = VitsModel.from_pretrained("facebook/mms-tts-rus")
|
22 |
-
text_tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-rus")
|
23 |
|
24 |
-
#
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
27 |
with torch.no_grad():
|
28 |
-
|
29 |
-
return
|
30 |
-
|
31 |
-
# Функция для обработки речи и ее перевода
|
32 |
-
def process_speech_to_speech_translation(input_audio):
|
33 |
-
translated_text = translate_audio(input_audio)
|
34 |
-
synthesized_speech = custom_speech_synthesis(translated_text)
|
35 |
-
synthesized_speech = (synthesized_speech.numpy() * 32767).astype(np.int16)
|
36 |
-
return 16000, synthesized_speech[0]
|
37 |
-
|
38 |
-
# Новое название и описание для интерфейса
|
39 |
-
interface_title = "Speech Translation and Synthesis"
|
40 |
-
interface_description = """
|
41 |
-
Experience the magic of speech-to-speech translation! Our innovative system translates your speech and synthesizes it in Russian. This demo utilizes cutting-edge models for speech recognition, translation, and text-to-speech synthesis.
|
42 |
-
"""
|
43 |
|
44 |
|
45 |
-
|
|
|
|
|
|
|
|
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
title=title,
|
52 |
description=description,
|
53 |
)
|
54 |
|
55 |
-
#
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
title=
|
61 |
-
description=
|
62 |
)
|
63 |
|
64 |
-
# Запускаем интерфейс
|
65 |
with demo:
|
66 |
gr.TabbedInterface([mic_translate, file_translate], ["Microphone", "Audio File"])
|
67 |
|
68 |
-
demo.launch()
|
|
|
3 |
import torch
|
4 |
from datasets import load_dataset
|
5 |
|
6 |
+
from transformers import AutoTokenizer, VitsModel, pipeline
|
7 |
|
8 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
|
|
9 |
|
10 |
+
asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-tiny", device=device) #Тут добавил tiny, потому что модель станет более компактной
|
11 |
+
translater = pipeline("translation", model="Helsinki-NLP/opus-mt-en-ru") # Инициализация модели для перевода текста на русский язык
|
|
|
12 |
|
13 |
+
def translate(audio, translater: pipeline = translater): # Определение функции для перевода аудио в текст
|
14 |
+
outputs = asr_pipe(audio, max_new_tokens=256, generate_kwargs={"task": "translate"}) # Получение текстового представления аудио
|
15 |
+
return translater(outputs['text'])[0]['translation_text'] # Возврат переведенного текста
|
|
|
16 |
|
|
|
|
|
|
|
17 |
|
18 |
+
model = VitsModel.from_pretrained("facebook/mms-tts-rus") # Загрузка модели для генерации речи на русском языке
|
19 |
+
tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-rus") # Загрузка токенизатора для модели
|
20 |
+
|
21 |
+
def synthesise(text: str, tokenizer: AutoTokenizer = tokenizer, model: VitsModel = model): # Определение функции для синтеза речи из текста
|
22 |
+
inputs = tokenizer(text, return_tensors="pt") # Создание токенизированного представления текста
|
23 |
+
# print(inputs)
|
24 |
with torch.no_grad():
|
25 |
+
output = model(**inputs).waveform # Генерация аудиофайла из текста
|
26 |
+
return output.cpu() # Возврат полученной речи
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
|
29 |
+
def speech_to_speech_translation(audio): # Определение функции для перевода и синтеза речи
|
30 |
+
translated_text = translate(audio) # Перевод аудио в текст
|
31 |
+
synthesised_speech = synthesise(translated_text) # Генерация речи на русском языке из переведенного текста
|
32 |
+
synthesised_speech = (synthesised_speech.numpy() * 32767).astype(np.int16) # Преобразование и нормализация речи
|
33 |
+
return 16000, synthesised_speech[0] # Возврат частоты дискретизации и синтезированной речи
|
34 |
|
35 |
+
|
36 |
+
title = "Cascaded STST"
|
37 |
+
description = """
|
38 |
+
Demo for cascaded speech-to-speech translation (STST), mapping from source speech in multi language to target speech in Russian. Demo uses OpenAI's [Whisper Tiny](https://huggingface.co/openai/whisper-tiny) model for speech translation, and Facebook's
|
39 |
+
[mms-tts-rus](https://huggingface.co/acebook/mms-tts-rus) model for text-to-speech:
|
40 |
+
![Cascaded STST](https://huggingface.co/datasets/huggingface-course/audio-course-images/resolve/main/s2st_cascaded.png "Diagram of cascaded speech to speech translation")
|
41 |
+
"""
|
42 |
+
|
43 |
+
demo = gr.Blocks() # Создание блока для интерфейса
|
44 |
+
|
45 |
+
mic_translate = gr.Interface( # Создание интерфейса для микрофона
|
46 |
+
fn=speech_to_speech_translation, # Используемая функция
|
47 |
+
inputs=gr.Audio(source="microphone", type="filepath"), # Ввод с микрофона
|
48 |
+
outputs=gr.Audio(label="Generated Speech", type="numpy"), # Вывод сгенерированной речи
|
49 |
title=title,
|
50 |
description=description,
|
51 |
)
|
52 |
|
53 |
+
file_translate = gr.Interface( # Создание интерфейса для загрузки аудиофайла
|
54 |
+
fn=speech_to_speech_translation,
|
55 |
+
inputs=gr.Audio(source="upload", type="filepath"),
|
56 |
+
outputs=gr.Audio(label="Generated Speech", type="numpy"),
|
57 |
+
examples=[["./test_2.wav"]],
|
58 |
+
title=title,
|
59 |
+
description=description,
|
60 |
)
|
61 |
|
|
|
62 |
with demo:
|
63 |
gr.TabbedInterface([mic_translate, file_translate], ["Microphone", "Audio File"])
|
64 |
|
65 |
+
demo.launch()
|