import os
import azure.cognitiveservices.speech as speechsdk
import pyperclip
import time
import csv
import requests
import uuid
from translate import Translator
from colorama import init, Fore, Style
### TRANSLATE PART
def translate_german_to_polish(german_sentence):
# Add your key and endpoint
key = "XXX" # TRANSLATE AZURE KEY
endpoint = "https://api.cognitive.microsofttranslator.com"
# Replace this with the location (region) of your Azure Translator Text API resource.
location = "eastus" # You have to CHANGE IT to your server
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'from': 'de', # Translate from German
'to': 'pl' # Translate to Polish
}
headers = {
'Ocp-Apim-Subscription-Key': key,
# location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# Replace the German sentence in the body.
body = [{'text': german_sentence}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
# Check if the response contains 'translations' and if it's not empty
if isinstance(response, list) and 'translations' in response[0]:
translations_list = response[0]['translations']
if len(translations_list) > 0:
# Extract the translated text from the first translation
translated_text = translations_list[0]['text']
else:
translated_text = "Translation failed."
else:
translated_text = "Translation failed."
return translated_text
# Example usage:
#translated_text = translate_german_to_polish(german_sentence)
#print("Translated sentence:", translated_text)
init(autoreset=True) # Initialize colorama for automatic color reset
SPEECH_KEY = 'XXX' # here your Speech_KEY for azure
SPEECH_REGION = 'https://eastus.tts.speech.azure.com/' # you have to change it !!!
# This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
speech_config = speechsdk.SpeechConfig(subscription=os.environ.get('SPEECH_KEY'), region=os.environ.get('SPEECH_REGION'))
# Customize TTS settings (adjust speed using SSML)
#speech_config.speech_synthesis_voice_name = 'de-DE-AmalaNeural' # Set a VOICE NAME
"""
German voices
de-DE-KatjaNeural (Female)
de-DE-ConradNeural1 (Male)
de-DE-AmalaNeural (Female)
de-DE-BerndNeural (Male)
de-DE-ChristophNeural (Male)
de-DE-ElkeNeural (Female)
de-DE-GiselaNeural (Female, Child)
de-DE-KasperNeural (Male)
de-DE-KillianNeural (Male)
de-DE-KlarissaNeural (Female)
de-DE-KlausNeural (Male)
de-DE-LouisaNeural (Female)
de-DE-MajaNeural (Female)
de-DE-RalfNeural (Male)
de-DE-TanjaNeural (Female)"""
speech_config.speech_synthesis_voice_name = 'de-DE-MajaNeural'
# Function to generate SSML with speed adjustment
def generate_ssml(text, rate):
return f"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='de-DE'><voice name='{speech_config.speech_synthesis_voice_name}'><prosody rate='{rate}'>{text}</prosody></voice></speak>"
audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True)
speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
def translate_text(text, target_language):
translator = Translator(to_lang=target_language, from_lang='de')
translated_text = translator.translate(text)
return translated_text
# Initialize previous clipboard content
prev_clipboard_text = pyperclip.paste()
# Create an empty list to store clipboard and translation data
data_list = []
YELLOW = '\033[93m'
while True:
# Wait for clipboard text to change
while pyperclip.paste() == prev_clipboard_text:
time.sleep(1) # Wait for 1 second before checking again
# Clipboard text has changed, get the updated text
text = pyperclip.paste()
prev_clipboard_text = text
# Translate clipboard text from German to Polish
target_language = 'pl'
#translated_text = translate_text(text, target_language)
translated_text = translate_german_to_polish(text)
# Synthesize the original German text to the default speaker with adjusted speed
speech_ssml = generate_ssml(text, rate='15%') # Adjust speed by setting the rate attribute in SSML
speech_synthesizer.speak_ssml_async(speech_ssml).get()
# Print the original German text and translated text with line separation
print("{}".format(text))
print(Fore.YELLOW + "{}".format(translated_text.strip()))
#print(Style.RESET_ALL) # Reset text color to default after printing
# Append the clipboard text and translation to the data_list
data_list.append((text, translated_text))
# Add a line separator after each query for better readability
print("-" * 50)
# Write the clipboard and translation data to the CSV file
with open("data_read_translate.csv", mode='w', newline='', encoding='utf-8') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(['Original Text (German)', 'Translated Text (Polish)'])
csv_writer.writerows(data_list)