Code:
# Обработчик голосовых сообщений
@bot.message_handler(content_types=['voice'])
def handle_voice(message):
try:
# Получаем информацию о файле
file_info = bot.get_file(message.voice.file_id)
file_path = file_info.file_path
# Скачиваем голосовое сообщение
downloaded_file = bot.download_file(file_path)
# Сохраняем голосовое сообщение в формате MP3 на диск
with open("voice.mp3", "wb") as voice_file:
voice_file.write(downloaded_file)
# Транскрибируем голосовое сообщение с помощью OpenAI Whisper API
transcript = transcribe_audio("voice.mp3")
if transcript is not None:
bot.send_message(message.chat.id, "Текст из голосового сообщения:\n" + transcript)
else:
bot.send_message(message.chat.id, "Не удалось распознать голосовое сообщение.")
except Exception as e:
bot.send_message(message.chat.id, f"Произошла ошибка при обработке голосового сообщения: {str(e)}")
def transcribe_audio(audio_file_path):
try:
with open(audio_file_path, "rb") as audio_file:
# Отправляем аудиофайл на транскрибацию с помощью OpenAI Whisper API
headers = {
"Authorization": f"Bearer {openai.api_key}",
}
files = {"file": audio_file}
data = {
"model": "whisper-1", # Укажите желаемую модель Whisper API
"response_format": "text", # Формат вывода текста
"language": "ru", # Укажите язык входного аудио, если известен
"prompt": "Прошу транскрибировать следующее аудио: ",
}
response = requests.post("https://api.openai.com/v1/audio/transcriptions", headers=headers, data=data, files=files)
if response.status_code == 200:
transcription_data = response.json()
transcript = transcription_data.get("text")
return transcript
else:
return f"Произошла ошибка при транскрибации голосового сообщения: {response.text}"
except Exception as e:
return str(e)