Search code examples
pythonopenai-api

How to translate a batch of txt files using gpt-4?


I'm working on a Python script to translate plain text files located on a folder from English to Spanish. However, I'm facing an issue where the script doesn't work with SDK version 1.0.0 or newer. I've tried but get errors like:

You tried to access openai.ChatCompletion, but this is no longer supported in openai
You tried to access openai.Completion, but this is no longer supported in openai

When I try to correct using information on the StackOverflow I get errors like this one:

AttributeError: module 'openai' has no attribute 'client'. Did you mean: 'Client'?

My current script is this one:

   for file_name in os.listdir(folder_path):
    if file_name.endswith('.txt'): 
        file_path = os.path.join(folder_path, file_name)
        
        with open(file_path, 'r') as file:
            text = file.read() 
            
            # Translate the tet
            response = openai.ChatCompletion.create(
              model="gpt-4",
              messages=[
                  {"role": "system", "content": "You are a helpful professional translator."},
                  {"role": "user", "content": f"Translate this English text to Spanish: '{text}'"}
              ]
            ) 

            translated_text = response['choices'][0]['message']['content'] 

            translated_file_path = os.path.join(folder_translated_path, file_name)
            
            with open(translated_file_path, 'w') as translated_file:
                translated_file.write(translated_text)

Thanks in advance.


Solution

  • try using

    from openai import OpenAI
    client = OpenAI()
    completion = client.chat.completions.create(model, messages)
    

    instead of

    openai.ChatCompletion.create(model, messages)
    

    There seems to be a syntax change in recent API updates.

    Reference from OpenAI API Reference