Question: How to add Azure TTS to Renpy

Timbalanderio

New Member
Apr 19, 2018
2
1
Question: How to add Azure TTS to Renpy?

I tried with ChatGPT to find a solution but nothing works. Maybe someone can help. I can not read anymore and windows TTS is low quality. Thank you for help!.

Edit: I was able to copy text to clipboard and with another python script (external from game ) to read text from clipboard.
 
Last edited:

Timbalanderio

New Member
Apr 19, 2018
2
1
I made it with CHATGPT, so it is a mess.

I used to_clipboard script to copy text from game to clipboard. https://f95zone.to/threads/text-to-clipboard.71608/


put it in game folder , and save it as to_clipboard.rpy
Python:
init python:
    import inspect
    import pygame.scrap
    import re

    def to_clipboard(event, **kwargs):
        if event == "begin":
            d = inspect.currentframe().f_back.f_locals
            line = "%s" % (d.get("what"))
            line = line.replace('[None]', '')
            line = re.sub(r'{.+?}', '', line)
            pygame.scrap.put(pygame.scrap.SCRAP_TEXT, line.encode("utf-8"))
    config.all_character_callbacks.append(to_clipboard)

For my solution you need a microsoft azure cloud account. It is FREE. You need to Create Speech KEY and Translate KEY. You can find how to do it on youtube.

It translates from German to Polish. And uses German TTS. For english you have to change few things here is list of voices:

en-GB-SoniaNeural (Female)
en-GB-RyanNeural (Male)
en-GB-LibbyNeural (Female)
en-GB-AbbiNeural (Female)
en-GB-AlfieNeural (Male)
en-GB-BellaNeural (Female)
en-GB-ElliotNeural (Male)
en-GB-EthanNeural (Male)
en-GB-HollieNeural (Female)
en-GB-MaisieNeural (Female, Child)
en-GB-NoahNeural (Male)
en-GB-OliverNeural (Male)
en-GB-OliviaNeural (Female)
en-GB-ThomasNeural (Male)




Here is python script. You need to install python and some libraries using PIP install. You dont know how ? Ask CHATGPT

put it whenever you want it, just run it from cmd window.
Python:
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)
 
Last edited:
  • Like
Reactions: temrix

temrix

Newbie
Aug 15, 2020
17
13
Thank you for this, works like a charm after some tweaking! Hopefully I won't use my free limit too fast haha