Introduction

This is a program I wrote that employs Google Translate and ChatGPT to automate the translation of a text. Here is a summary of the process:

  • The program removes new line characters from the pasted text to improve translation accuracy.
  • The program sends the text to Google Translate.
  • The translated text is sent to OpenAI to improve flow.
  • The final output is written to a text file. The program appends newly translated text to the same file.

Here I present the code and explain how the program works.

Libraries

This is a Python code that utilizes Google Translate, OpenAI, and is run on a Mac.
First, we import the necessary libraries:


from deep_translator import GoogleTranslator
import openai
import os
            

OpenAI API Key

You can set up an API key with OpenAPI on the OpenAI platform site to access GPT models.
You will need to purchase API tokens. For this, navigate to Settings > Billing. The pricing is available there as well, and it varies for different models (GPT-3.5 is significantly cheaper than GPT-4, but this only becomes significant with large projects and extensive use).

# Set up the OpenAI API key directly for testing (replace the x's with your key).


openai.api_key = "xxxxxxxxxxxxxxxxx"
            
Remove New Line Characters

# Function to clean text by removing new line characters


def clean_text(text):
return text.replace("\n", " ")
            
Send to Google Translate

# Function to translate text using Google Translate (deep-translator)


def translate_text(text, source='ru', target='en'):
translator = GoogleTranslator(source=source, target=target)
return translator.translate(text)
            
Improve Flow with OpenAI

# Function to improve text flow using the new OpenAI Chat API


def improve_flow(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",  # Use "gpt-4" if you have access to GPT-4
        messages=[
            {"role": "system", "content": "You are a helpful assistant that improves the flow of translations."},
            {"role": "user", "content": f"Please improve the flow of this translation:\n\n{text}"}
        ]
    )
    return response['choices'][0]['message']['content']
            
Main Function

# Main function to automate translation and flow improvement


def automate_translation(text):
    # Step 1: Clean the text
    cleaned_text = clean_text(text)

    # Step 2: Translate the text
    translated_text = translate_text(cleaned_text)

    # Step 3: Improve the flow
    improved_text = improve_flow(translated_text)

    # Return the final result
    return improved_text
            
Read File

# Function to read text from a file and store it in a string


def read_file_to_string(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            original_text = file.read()
            print(f"Text copied from {file_path}")
            return original_text
    except FileNotFoundError:
        print(f"The file {file_path} was not found.")
        return None
    except Exception as e:
        print(f"An error occurred while reading {file_path}: {e}")
        return None
            
Append Text to File

# Function to append text to a file


def append_text_to_file(file_path, text):
  try:
      with open(file_path, 'a', encoding='utf-8') as file:  # 'a' mode for append
          file.write(text + '\n')  # Add newline character after text
      print(f"Text successfully appended to {file_path}")
  except Exception as e:
      print(f"An error occurred: {e}")
            
Loop Through Pasted Text

# Main block to loop over 1-9 files

          
if __name__ == "__main__":
    output_file = 'translated-output.txt'  # The file where translations will be appended

    # Loop over files 1.txt to 9.txt
    for i in range(1, 10):
        file_path = f'{i}.txt'  # Construct the file name dynamically (1.txt, 2.txt, ..., 9.txt)
        original_text = read_file_to_string(file_path)

        if original_text:
            final_output = automate_translation(original_text)
            if final_output:
                append_text_to_file(output_file, final_output)
            
How to Use

How to use the Auto-Translate-9Loop-GPT.py scripts:

*** To Get Started ***

Copy text for translation into a *.txt document. No need to remove newline characters. The program will do that automatically. I find that about 1/2-page at a time (per *.txt file) is optimal because there seems to be an issue with passing too much information through the API.

Save as 1.txt, 2.txt, ... 9.txt in the same folder the as *.py files.

The translator will automatically translate the text consecutively in these documents and write the translation into the "translation-output.txt" file, appending text until you are finished with the project.

*** To RUN the program ***

  • 1. Open Terminal
  • 2. Change environment:
    conda activate translate-env
  • 3. Change directory:
    cd ~/path   #(drag and drop the folder for Terminal to auto-populate the path)
  • 4. Run the program:
    python3 Auto-Translate-9Loop-GPT3-5.py
  • 5. When finished, exit the environment:
    conda deactivate

~ Enjoy!

Entire Program


from deep_translator import GoogleTranslator
import openai
import os

# Set up the OpenAI API key directly for testing (replace with your key)
openai.api_key = "xxxxxx"

# Function to clean text by removing new line characters
def clean_text(text):
    return text.replace("\n", " ")

# Function to translate text using Google Translate (deep-translator)
def translate_text(text, source='ru', target='en'):
    translator = GoogleTranslator(source=source, target=target)
    return translator.translate(text)

# Function to improve text flow using the new OpenAI Chat API
def improve_flow(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",  # Use "gpt-4" if you have access to GPT-4
        messages=[
            {"role": "system", "content": "You are a helpful assistant that improves the flow of translations."},
            {"role": "user", "content": f"Please improve the flow of this translation:\n\n{text}"}
        ]
    )
    return response['choices'][0]['message']['content']

# Main function to automate translation and flow improvement
def automate_translation(text):
    # Step 1: Clean the text
    cleaned_text = clean_text(text)

    # Step 2: Translate the text
    translated_text = translate_text(cleaned_text)

    # Step 3: Improve the flow
    improved_text = improve_flow(translated_text)

    # Return the final result
    return improved_text

# Function to read text from a file and store it in a string
def read_file_to_string(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            original_text = file.read()
            print(f"Text copied from {file_path}")
            return original_text
    except FileNotFoundError:
        print(f"The file {file_path} was not found.")
        return None
    except Exception as e:
        print(f"An error occurred while reading {file_path}: {e}")
        return None

# Function to append text to a file
def append_text_to_file(file_path, text):
    try:
        with open(file_path, 'a', encoding='utf-8') as file:  # 'a' mode for append
            file.write(text + '\n')  # Add newline character after text
        print(f"Text successfully appended to {file_path}")
    except Exception as e:
        print(f"An error occurred: {e}")

# Main block to loop over 1-9 files
if __name__ == "__main__":
    output_file = 'translated-output.txt'  # The file where translations will be appended

    # Loop over files 1.txt to 9.txt
    for i in range(1, 10):
        file_path = f'{i}.txt'  # Construct the file name dynamically (1.txt, 2.txt, ..., 9.txt)
        original_text = read_file_to_string(file_path)

        if original_text:
            final_output = automate_translation(original_text)
            if final_output:
                append_text_to_file(output_file, final_output)