@clazy13

IDE не видет библиотеку from google.cloud import texttospeech(Но texttospeech читает), что делать?

У меня есть код для преобразования голосовых в текст, с последующей обработкой текста в голосовое сообщение
Но почему-то в моем коде IDE не видит - from google.cloud не видит, но видит import texttospeech
6571b58a19873136540064.png
Вот фотка где видно, что других библиотеки выделяются зеленым, а google.cloud - нет
И программа выдает ошибку:
raise exceptions.DefaultCredentialsError(_CLOUD_SDK_MISSING_CREDENTIALS)
google.auth.exceptions.DefaultCredentialsError: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/exter... for more information.

Код:
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage 
from aiogram.utils import executor
import speech_recognition as sr
import librosa
import soundfile as sf
from google.cloud import texttospeech
import os
TOKEN_API = ''

bot = Bot(TOKEN_API)

dp = Dispatcher(bot, storage=MemoryStorage())
client = texttospeech.TextToSpeechClient()

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'C:\Programmirovanie\IDE\Microsoft VS Code\exctazy_bot\skript_anonimka\goggletexttospeech-96f1ecee0681.json'

async def on_startup(_):
    print('Бот запущен')

@dp.message_handler(content_types=types.ContentType.VOICE)
async def start(message: types.Message):
    print(1)
    recognizer = sr.Recognizer()
        # Получение аудио из голосового сообщения
    file_id = message.voice.file_id
    file = await bot.get_file(file_id)
    file_path = file.file_path
    voice_file = await bot.download_file(file_path, "audio.ogg")  
    audio_data, sample_rate = librosa.load('audio.ogg')
    sf.write('audio.wav', audio_data, sample_rate)
    
    with sr.AudioFile('audio.wav') as source:
        audio = recognizer.record(source)
        text = recognizer.recognize_google(audio, language="ru-RU")
        # Вывод текста
    await message.reply("Распознанный текст:" + text)

        # Синтез нового голосового сообщения

    synthesis_input = texttospeech.SynthesisInput(text=text)
    voice = texttospeech.VoiceSelectionParams(
        language_code="ru-RU",
        name="ru-RU-Wavenet-A",  # Выбираем женский голос ru-RU-Wavenet-A
    )
    audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)

    response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)

    with open("output.mp3", "wb") as out:
        out.write(response.audio_content)

    with open("output.mp3", "rb") as audio:
        await bot.send_voice(message.chat.id, audio)


if __name__ == '__main__':
    executor.start_polling(dp, on_startup=on_startup,skip_updates=True)
  • Вопрос задан
  • 86 просмотров
Пригласить эксперта
Ответы на вопрос 1
@maximq
QA Engineer
Ошибка не связана с импортом. У вас client не принимает значение, которое вы задали с помощью os.environ.
Укажите явно, вместо:
client = texttospeech.TextToSpeechClient()
Впишите:
credentials = service_account.Credentials.from_service_account_file('C:\Programmirovanie\IDE\Microsoft VS Code\exctazy_bot\skript_anonimka\goggletexttospeech-96f1ecee0681.json')
client = texttospeech.TextToSpeechClient(credentials=credentials)


А ещё отредактируйте вопрос и удалите api token бота
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы