5

My workflow for a single image: I go to https://translate.google.com/, click the "Images" button, click "Browse your computer" to choose an image, translate, download the translated image. This works very well for a single image or a small number of images. However now I have a large number of images (50+).

Can I somehow do this in bulk (in batch)? I am asking specifically about graphical in-place translation, which preserves the layout, where the original text is replaced in the image itself.

(One thing I already tried, instead of using images, use a multipage PDF. But Google Translate does not work for scanned PDFs. However it does work for images.)

2 Answers 2

3

It's not possible via https://translate.google.com/. Furthermore, the Cloud Translation API doesn't seem to take images as input. However you could try to stich images together into 1 image:

2

I have successfully done this using this Python code:

import os
from google.cloud import translate_v2 as translate

def upload_and_translate(input_dir, output_dir, target_language):
    """Uploads all images in a directory, translates them using Google Translate, and downloads the translated images to a specified output directory.

    Args:
        input_dir: The directory containing the images to be translated.
        output_dir: The directory to which the translated images will be downloaded.
        target_language: The target language for the translation.
    """

    # Create a Google Translate client.
    client = translate.Client()

    # Get a list of all the files in the input directory.
    files = os.listdir(input_dir)

    # Iterate over the files and upload them to Google Translate.
    for file in files:
        with open(os.path.join(input_dir, file), "rb") as f:
            # Upload the image to Google Translate.
            response = client.translate_image(
                f,
                target_language=target_language,
            )

            # Download the translated image.
            with open(os.path.join(output_dir, file), "wb") as f:
                f.write(response.translated_image)

# Example usage:
if __name__ == "__main__":
    input_dir = "path/to/input/directory"
    output_dir = "path/to/output/directory"
    target_language = "es"
    upload_and_translate(input_dir, output_dir, target_language)

To use the provided code, follow these steps:

Python:

  1. Install the google-cloud-translate library using
    pip install google-cloud-translate
    
  2. Save the code as a Python file, for example, upload_and_translate.py.
  3. Replace the values of input_dir, output_dir, and target_language with your desired values.
  4. Run the script using
    python upload_and_translate.py
    

Not the answer you're looking for? Browse other questions tagged or ask your own question.