Spaces:
Runtime error
Runtime error
Create voice_assistent.py
Browse files- voice_assistent.py +156 -0
voice_assistent.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from vosk import Model, KaldiRecognizer # оффлайн-распознавание от Vosk
|
2 |
+
from vosk_tts import Model, Synth
|
3 |
+
import speech_recognition # распознавание пользовательской речи (Speech-To-Text)
|
4 |
+
import wave # создание и чтение аудиофайлов формата wav
|
5 |
+
import json # работа с json-файлами и json-строками
|
6 |
+
import os # работа с файловой системой
|
7 |
+
import requests
|
8 |
+
import IPython
|
9 |
+
from pydub import AudioSegment
|
10 |
+
from pydub.playback import play
|
11 |
+
import urllib.request
|
12 |
+
|
13 |
+
PATH_TO_MODEL = "C:/Users/user/Desktop/deepfake_sirius/Model"
|
14 |
+
PATH_TO_OUTPUT = "C:/Users/user/Desktop/deepfake_sirius/materials/audio"
|
15 |
+
|
16 |
+
|
17 |
+
k = "sk-YOVNQzHmpga9My3dwlSo9BQN907TuPZQXcHn50ztigTwm3I2"
|
18 |
+
files = [
|
19 |
+
("input_face", open("C:\\Users\\user\\Desktop\\deepfake_sirius\\materials\\scale_1200.jpg", "rb")),
|
20 |
+
("input_audio", open("C:\\Users\\user\\Desktop\\deepfake_sirius\\materials\\audio\\output.wav", "rb")),
|
21 |
+
]
|
22 |
+
payload = {}
|
23 |
+
|
24 |
+
|
25 |
+
class VoiceGenerator:
|
26 |
+
def __init__(self):
|
27 |
+
self.model = Model(model_path=PATH_TO_MODEL)
|
28 |
+
def generate(self, text, file_name='output.wav'):
|
29 |
+
synth = Synth(self.model)
|
30 |
+
path = os.path.join(PATH_TO_OUTPUT, file_name)
|
31 |
+
synth.synth(text, path)
|
32 |
+
return path
|
33 |
+
|
34 |
+
def record_and_recognize_audio(*args: tuple):
|
35 |
+
"""
|
36 |
+
Запись и распознавание аудио
|
37 |
+
"""
|
38 |
+
with microphone:
|
39 |
+
recognized_data = ""
|
40 |
+
|
41 |
+
# регулирование уровня окружающего шума
|
42 |
+
recognizer.adjust_for_ambient_noise(microphone, duration=2)
|
43 |
+
|
44 |
+
try:
|
45 |
+
print("Listening...")
|
46 |
+
audio = recognizer.listen(microphone, 5, 5)
|
47 |
+
|
48 |
+
with open("microphone-results.wav", "wb") as file:
|
49 |
+
file.write(audio.get_wav_data())
|
50 |
+
|
51 |
+
except speech_recognition.WaitTimeoutError:
|
52 |
+
print("Can you check if your microphone is on, please?")
|
53 |
+
return
|
54 |
+
|
55 |
+
# использование online-распознавания через Google
|
56 |
+
try:
|
57 |
+
print("Started recognition...")
|
58 |
+
recognized_data = recognizer.recognize_google(audio, language="ru").lower()
|
59 |
+
|
60 |
+
except speech_recognition.UnknownValueError:
|
61 |
+
pass
|
62 |
+
|
63 |
+
# в случае проблем с доступом в Интернет происходит попытка
|
64 |
+
# использовать offline-распознавание через Vosk
|
65 |
+
except speech_recognition.RequestError:
|
66 |
+
print("Trying to use offline recognition...")
|
67 |
+
recognized_data = use_offline_recognition()
|
68 |
+
|
69 |
+
return recognized_data
|
70 |
+
|
71 |
+
|
72 |
+
def use_offline_recognition():
|
73 |
+
"""
|
74 |
+
Переключение на оффлайн-распознавание речи
|
75 |
+
:return: распознанная фраза
|
76 |
+
"""
|
77 |
+
recognized_data = ""
|
78 |
+
try:
|
79 |
+
# проверка наличия модели на нужном языке в каталоге приложения
|
80 |
+
if not os.path.exists("models/vosk-model-small-ru-0.4"):
|
81 |
+
print("Please download the model from:\n"
|
82 |
+
"https://alphacephei.com/vosk/models and unpack as 'model' in the current folder.")
|
83 |
+
exit(1)
|
84 |
+
|
85 |
+
# анализ записанного в микрофон аудио (чтобы избежать повторов фразы)
|
86 |
+
wave_audio_file = wave.open("microphone-results.wav", "rb")
|
87 |
+
model = Model("models/vosk-model-small-ru-0.4")
|
88 |
+
offline_recognizer = KaldiRecognizer(model, wave_audio_file.getframerate())
|
89 |
+
|
90 |
+
data = wave_audio_file.readframes(wave_audio_file.getnframes())
|
91 |
+
if len(data) > 0:
|
92 |
+
if offline_recognizer.AcceptWaveform(data):
|
93 |
+
recognized_data = offline_recognizer.Result()
|
94 |
+
|
95 |
+
# получение данных распознанного текста из JSON-строки
|
96 |
+
# (чтобы можно было выдать по ней ответ)
|
97 |
+
recognized_data = json.loads(recognized_data)
|
98 |
+
recognized_data = recognized_data["text"]
|
99 |
+
except:
|
100 |
+
print("Sorry, speech service is unavailable. Try again later")
|
101 |
+
|
102 |
+
return recognized_data
|
103 |
+
|
104 |
+
|
105 |
+
def ask(request):
|
106 |
+
instruction = """
|
107 |
+
Ответь на запрос так, как ответил бы на него Павел Воля. Используй данные из биографии Павла Воли, если это потребуется. Отвечай на запрос в его стиле. Ответ должен содержать не болеее 10 предложений.
|
108 |
+
"""
|
109 |
+
result = requests.post(
|
110 |
+
url='https://llm.api.cloud.yandex.net/llm/v1alpha/instruct',
|
111 |
+
headers={
|
112 |
+
"Authorization": "Api-Key AQVNyVqBi-XoJ1cAo7VIxq6ztgXm3owqowtso5Qb",
|
113 |
+
},
|
114 |
+
json={
|
115 |
+
"model": "general",
|
116 |
+
"instruction_text": instruction,
|
117 |
+
"request_text": request,
|
118 |
+
"generation_options": {
|
119 |
+
"max_tokens": 1500,
|
120 |
+
"temperature": 0.5
|
121 |
+
}
|
122 |
+
}
|
123 |
+
)
|
124 |
+
data = json.loads(result.text)
|
125 |
+
return(data['result']['alternatives'][0]['text'])
|
126 |
+
|
127 |
+
|
128 |
+
if __name__ == "__main__":
|
129 |
+
# инициализация инструментов распознавания и ввода речи
|
130 |
+
recognizer = speech_recognition.Recognizer()
|
131 |
+
microphone = speech_recognition.Microphone()
|
132 |
+
vg = VoiceGenerator()
|
133 |
+
while True:
|
134 |
+
# старт записи речи с последующим выводом распознанной речи
|
135 |
+
# и удалением записанного в микрофон аудио
|
136 |
+
voice_input = record_and_recognize_audio()
|
137 |
+
os.remove("microphone-results.wav")
|
138 |
+
print(voice_input)
|
139 |
+
path_to_file = vg.generate(ask(voice_input))
|
140 |
+
print(path_to_file)
|
141 |
+
response = requests.post(
|
142 |
+
"https://api.gooey.ai/v2/Lipsync/form/",
|
143 |
+
headers={
|
144 |
+
"Authorization": "Bearer " + k,
|
145 |
+
},
|
146 |
+
files=files,
|
147 |
+
data={"json": json.dumps(payload)},
|
148 |
+
)
|
149 |
+
assert response.ok, response.content
|
150 |
+
#song = AudioSegment.from_wav(path_to_file)
|
151 |
+
result = response.json()
|
152 |
+
print(response.status_code, result["output"]["output_video"])
|
153 |
+
#play(song)
|
154 |
+
urllib.request.urlretrieve(result["output"]["output_video"], "C:\\Users\\user\\Desktop\\deepfake_sirius\\materials\\video.mp4")
|
155 |
+
os.startfile("C:\\Users\\user\\Desktop\\deepfake_sirius\\materials\\video.mp4")
|
156 |
+
break;
|