Я немного растерялся. Я получаю ошибку 400 (неверный тип) из Google TTS-API.
Что я пытаюсь сделать: извлечь текст из PDF и использовать выходную строку в качестве входных данных для TTS. Тип txt = convert_pdf_to_txt ("test.pdf") является строкой. Так в чем же проблема? Если я изменю ввод на любую другую строку, она будет работать. Вот код:
from google.cloud import texttospeech
from google.oauth2 import service_account
import os
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = io.StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,
password=password,
caching=caching,
check_extractable=True):
interpreter.process_page(page)
fp.close()
device.close()
text = retstr.getvalue()
retstr.close()
return text
txt = convert_pdf_to_txt("test.pdf")
# Language settings
# de-DE, en-US
language = "de-DE"
# de-DE-Wavenet-B, en-US-Wavenet-D
language_model = "de-DE-Wavenet-B"
# Credentials for Google's API
credentials_path = os.path.dirname(os.path.realpath(__file__)) + os.sep + 'credentials.json'
credentials = service_account.Credentials.from_service_account_file(credentials_path)
client = texttospeech.TextToSpeechClient(credentials=credentials)
# Set the text input to be synthesized
synthesis_input = texttospeech.types.SynthesisInput(text=txt)
voice = texttospeech.types.VoiceSelectionParams(
language_code=language,
name=language_model,
ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL)
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
# Perform the text-to-speech request on the text input with the selected
# voice parameters and audio file type
response = client.synthesize_speech(synthesis_input, voice, audio_config)
# The response's audio_content is binary.
with open('output.mp3', 'wb') as out:
# Write the response to the output file.
out.write(response.audio_content)
print('Audio content written to file "output.mp3"')
Будет ли вывод:
google.api_core.exceptions.InvalidArgument: 400 Request contains an invalid argument.