I am a complete beginner
I am trying to send a text via voice input using DeepL API and see the translation as output. Speech to text works, but it throws an error when executing the translator.translate_text_deepl().
main.py
import speech_recognition
import translator
recognizer = speech_recognition.Recognizer()
while True:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
text = recognizer.recognize_google(audio, language="de-DE")
print(f"Record: {text}")
translated_text = translator.translate_text_deepl(text, "en")
print(f"Translated text: {translated_text}")
except speech_recognition.UnknownValueError():
recognizer = speech_recognition.Recognizer()
continue
translator.py
import requests
def translate_text_deepl(text, target_language):
api_key = "MY_API_Key"
url = "https://api.deepl.com/v2/translate"
data = {
"auth_key": api_key,
"text": text,
"target_lang": target_language
}
response = requests.post(url, data=data)
result = response.json()
return result["translations"][0]["text"]
DeepL offers an official Python client library, you might find that easier to use. It might resolve the error you get, or give you more information about what is going wrong.
To use it change your translator.py file to:
import deepl
def translate_text_deepl(text, target_language):
translator = deepl.Translator("MY_API_Key")
return translator.translate_text(text, target_lang=target_language)