Monday | 15 APR 2024
[ previous ]
[ next ]

Using Google Cloud for Translations

Date: 2024-02-24

I tried out Google Cloud for the first time and it went pretty well. I wanted to try out the translations API and it looked like the easiest way was going to be to use the cloud option. I would have preferred to do it on my own server but I'm more interested in the problem than the tooling around it so I went with GCP.

I was able to sign up for Google Cloud and get the 300$ in free credits but I did have to give my credit card. I imagine this might be harder for others though there may be a way to get access without giving any information.

Once I had access, it was quite straightforward. I followed the tutorial at:

The core of it is that you need to start the cloud console. This spins up an ephemeral VM with a home directory that is persistent.

Once the VM is spun up, get the project ID by doing:

gcloud config list project

This will be needed in the python program. The tutorial has it as an environment variable but as this is a one off and I'm not checking this in anywhere, I'm hardcoding the value.

We also need to enable the translate service:

gcloud services enable

Once we have the project id, and the service is enabled, it's time to install google-cloud-translate.

virtualenv venv-translate
source venv-translate/bin/activate
pip install google-cloud-translate

We install the translate package inside a virtual environment.

Now for the code:

from os import environ

from import translate

PROJECT_ID = "something-something-123"
PARENT = f"projects/{PROJECT_ID}"

text = "something to translate"

client = translate.TranslationServiceClient()
response = client.translate_text(parent=PARENT,contents=[text],target_language="de")

translation = response.translations[0].translated_text


This will use the google translate API to translate the text.

Some closing thoughts, the VM is snazzy, uploading and downloading work pretty well and the idea of having an ephemeral VM is cool.

It is slow and painful when typing so it was easier to write my file on my server and upload it. Iteration was slow this way.

I also ran into rate limit issues and Service Unavailable errors. Might have been the same thing. I waited a bit and re-ran it and it went smoothly. I could have fixed this by batching things but this is a one off so I didn't spend too much time optimizing it. I may need to for future though.