Deploy a basic "Google Translate" app on Python 2 Cloud Run (Docker)

1. Overview

This series of codelabs (self-paced, hands-on tutorials) aims to help developers understand the various options they have when deploying their applications. In this codelab, you will learn how to use the Google Cloud Translation API with Python and either run locally or deploy to a Cloud serverless compute platform (App Engine, Cloud Functions, or Cloud Run). The sample app found in this tutorial's repo can be deployed (at least) eight different ways with only minor configuration changes:

  1. Local Flask server (Python 2)
  2. Local Flask server (Python 3)
  3. App Engine (Python 2)
  4. App Engine (Python 3)
  5. Cloud Functions (Python 3)
  6. Cloud Run (Python 2 via Docker)
  7. Cloud Run (Python 3 via Docker)
  8. Cloud Run (Python 3 via Cloud Buildpacks)

This codelab focuses on deploying this app to the bolded platform(s) above.

You'll learn how to

What you'll need

Survey

How will you use this tutorial?

Read it and complete the exercises Read it only

How would you rate your experience with Python?

Novice Intermediate Proficient

How would you rate your experience with using Google Cloud services?

Novice Intermediate Proficient

2. Setup and requirements

Self-paced environment setup

  1. Sign-in to the Google Cloud Console and create a new project or reuse an existing one. If you don't already have a Gmail or Google Workspace account, you must create one.

96a9c957bc475304.png

b9a10ebdf5b5a448.png

a1e3c01a38fa61c2.png

  • The Project name is the display name for this project's participants. It is a character string not used by Google APIs, and you can update it at any time.
  • The Project ID must be unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a unique string; usually you don't care what it is. In most codelabs, you'll need to reference the Project ID (and it is typically identified as PROJECT_ID), so if you don't like it, generate another random one, or, you can try your own and see if it's available. Then it's "frozen" after the project is created.
  • There is a third value, a Project Number which some APIs use. Learn more about all three of these values in the documentation.
  1. Next, you'll need to enable billing in the Cloud Console in order to use Cloud resources/APIs. Running through this codelab shouldn't cost much, if anything at all. To shut down resources so you don't incur billing beyond this tutorial, follow any "clean-up" instructions found at the end of the codelab. New users of Google Cloud are eligible for the $300 USD Free Trial program.

3. Enable Translation API

Enabling Cloud APIs

In this section, you'll learn how to enable Google APIs in general. For our sample app, you'll enable the Cloud Translation API, Cloud Run, and Cloud Artifact Registry.

Introduction

Regardless of which Google API you want to use in your application, they must be enabled. The following example shows two ways to enable the Cloud Vision API. After you learn how to enable one Cloud API, you'll be able to enable other APIs because the process is similar.

Option 1: From Cloud Shell or your command-line interface

While enabling APIs from the Cloud Console is more common, some developers prefer doing everything from the command line. To do so, you need to look up an API's "service name." It looks like a URL: SERVICE_NAME.googleapis.com. You can find these in the Supported products chart, or you can programmatically query for them with the Google Discovery API.

Armed with this information, using Cloud Shell (or your local development environment with the gcloud command-line tool installed), you can enable an API, as follows:

gcloud services enable SERVICE_NAME.googleapis.com

For example, this command enables the Cloud Vision API:

gcloud services enable vision.googleapis.com

This command enables App Engine:

gcloud services enable appengine.googleapis.com

You can also enable multiple APIs with one request. For example, this command line enables Cloud Run, Cloud Artifact Registry, and the Cloud Translation API:

gcloud services enable artifactregistry.googleapis.com run.googleapis.com translate.googleapis.com

Option 2: From the Cloud Console

You can also enable the Vision API in the API Manager. From the Cloud Console, go to API Manager and select Library.

fb0f1d315f122d4a.png

If you wanted to enable the Cloud Vision API, start entering "vision" in the search bar, and anything that matches what you've entered so far will appear:

2275786a24f8f204.png

Select the API you're seeking to enable and click Enable:

2556f923b628e31.png

Cost

While many Google APIs can be used without fees, use of Google Cloud products & APIs is not free. When enabling Cloud APIs, you may be asked for an active billing account. It is, however, important to note that some Google Cloud products feature an "Always Free" tier (daily/monthly), which you have to exceed in order to incur billing charges; otherwise, your credit card (or specified billing instrument) won't be charged.

Users should reference the pricing information for any API before enabling, especially noting whether it has a free tier, and if so, what it is. If you were enabling the Cloud Vision API, you would check its pricing information page. Cloud Vision does have a free quota, and so long as you stay within its limits in aggregate (within each month), you should not incur any charges.

Pricing and free tiers vary between Google APIs. Examples:

Different Google products are billed differently, so be sure to reference your API's documentation for that information.

Summary

Now that you know how to enable Google APIs in general, go to the API Manager and enable the Cloud Translation API, Cloud Run, and Cloud Artifact Registry (if you haven't already). You enable the former because our application uses it. You enable the latter because that is where our container images are stored before being deployed to start your Cloud Run service, which is why you have to enable that. If you prefer to enable them all with the gcloud tool, issue the following command instead from your terminal:

gcloud services enable artifactregistry.googleapis.com run.googleapis.com translate.googleapis.com

While its monthly quota isn't listed in the overall "Always Free" tier summary page, the Translation API's pricing page states all users get a fixed amount of translated characters monthly. You shouldn't incur any charges from the API if you stay below that threshold. If there are any other Google Cloud related charges, they will be discussed at the end in the "Clean up" section.

4. Get the sample app code

Clone the code in the repo locally or in Cloud Shell (using the git clone command), or download the ZIP file from its green Code button as shown in the following screenshot:

5cd6110c4414cf65.png

Now that you have everything, create a full copy of the folder to do this specific tutorial, because it will likely involve deleting or changing the files. If you want to do a different deployment, you can start over by copying the original so you don't have to clone or download it again.

5. Tour of sample app

The sample app is a simple Google Translate derivative that prompts users to enter text in English and receive the equivalent translation of that text in Spanish. Now open the main.py file so we can see how it works. Omitting the commented lines about licensing, it looks like this at the top and bottom:

from flask import Flask, render_template, request
import google.auth
from google.cloud import translate

app = Flask(__name__)
_, PROJECT_ID = google.auth.default()
TRANSLATE = translate.TranslationServiceClient()
PARENT = 'projects/{}'.format(PROJECT_ID)
SOURCE, TARGET = ('en', 'English'), ('es', 'Spanish')

# . . . [translate() function definition] . . .

if __name__ == '__main__':
    import os
    app.run(debug=True, threaded=True, host='0.0.0.0',
            port=int(os.environ.get('PORT', 8080)))
  1. The imports bring in Flask functionality, the google.auth module, and the Cloud Translation API client library.
  2. The global variables represent the Flask app, the Cloud project ID, the Translation API client, the parent "location path" for Translation API calls, and the source and target languages. In this case, it's English (en) and Spanish (es), but feel free to change these values to other language codes supported by the Cloud Translation API.
  3. The large if block at the bottom is used in the tutorial for running this app locally—it utilizes the Flask development server to serve our app. This section is also here for the Cloud Run deployment tutorials in case the web server isn't bundled into the container. You are asked to enable bundling the server in the container, but in case you overlook this, the app code falls back to using the Flask development server. (It is not an issue with App Engine or Cloud Functions because those are sourced-based platforms, meaning Google Cloud provides and runs a default web server.)

Finally, in the middle of main.py is the heart of the application, the translate() function:

@app.route('/', methods=['GET', 'POST'])
def translate(gcf_request=None):
    """
    main handler - show form and possibly previous translation
    """

    # Flask Request object passed in for Cloud Functions
    # (use gcf_request for GCF but flask.request otherwise)
    local_request = gcf_request if gcf_request else request

    # reset all variables (GET)
    text = translated = None

    # if there is data to process (POST)
    if local_request.method == 'POST':
        text = local_request.form['text']
        data = {
            'contents': [text],
            'parent': PARENT,
            'target_language_code': TARGET[0],
        }
        # handle older call for backwards-compatibility
        try:
            rsp = TRANSLATE.translate_text(request=data)
        except TypeError:
            rsp = TRANSLATE.translate_text(**data)
        translated = rsp.translations[0].translated_text

    # create context & render template
    context = {
        'orig':  {'text': text, 'lc': SOURCE},
        'trans': {'text': translated, 'lc': TARGET},
    }
    return render_template('index.html', **context)

The primary function does the work of taking the user input, and calling the Translation API to do the heavy-lifting. Let's break it down:

  1. Check to see if requests are coming from Cloud Functions using the local_request variable. Cloud Functions sends in its own Flask Request object whereas all others (running locally or deploying to App Engine or Cloud Run) will get the request object directly from Flask.
  2. Reset the basic variables for the form. This is primarily for GET requests as POST requests will have data that replace these.
  3. If it's a POST, grab the text to translate, and create a JSON structure representing the API metadata requirement. Then call the API, falling back to a previous version of the API if the user is employing an older library.
  4. Regardless, format the actual results (POST) or no data (GET) into the template context and render.

The visual part of the application is in the template index.html file. It shows any previously translated results (blank otherwise) followed by the form asking for something to translate:

<!doctype html>
<html><head><title>My Google Translate 1990s</title><body>
<h2>My Google Translate (1990s edition)</h2>

{% if trans['text'] %}
    <h4>Previous translation</h4>
    <li><b>Original</b>:   {{ orig['text'] }}  (<i>{{ orig['lc'][0] }}</i>)</li>
    <li><b>Translated</b>: {{ trans['text'] }} (<i>{{ trans['lc'][0] }}</i>)</li>
{% endif %}

<h4>Enter <i>{{ orig['lc'][1] }}</i> text to translate to <i>{{ trans['lc'][1] }}</i>:</h4>
<form method="POST"><input name="text"><input type="submit"></form>
</body></html>

6. Deploy the service

Now you're ready to deploy your translation service to Cloud Run by running this command:

gcloud run deploy translate --source . --allow-unauthenticated --platform managed

The output should look as follows, and provide some prompts for next steps:

$ gcloud run deploy translate --source . --allow-unauthenticated --platform managed
Please specify a region:
 [1] asia-east1
 [2] asia-east2
. . . (other regions) . . .
 [28] us-west4
 [29] cancel
Please enter your numeric choice:  REGION_CHOICE

To make this the default region, run `gcloud config set run/region REGION`.

Deploying from source requires an Artifact Registry repository to
store build artifacts. A repository named [cloud-run-source-deploy] in
 region [REGION] will be created.

Do you want to continue (Y/n)?

This command is equivalent to running "gcloud builds submit --pack image=[IMAGE] ." and "gcloud run deploy translate --image [IMAGE]"

Building . . . and deploying container to Cloud Run service [translate] in project [PROJECT_ID] region [REGION]
✓ Building and deploying... Done.
  ✓ Creating Container Repository...
  ✓ Uploading sources...
  ✓ Building Container... Logs are available at [https://console.cloud.google.com/cloud-build/builds/60e1b
  9bb-b991-4b4e-8d8a-HASH?project=PROJECT_NUMBER].
  ✓ Creating Revision...
  ✓ Routing traffic...
  ✓ Setting IAM Policy...
Done.
Service [translate] revision [translate-00001-xyz] has been deployed and is serving 100 percent of traffic.
Service URL: https://SVC_NAME-HASH-REG_ABBR.a.run.app

Now that your app is available globally around the world, you should be able to reach it at the URL containing your project ID as shown in the deployment output:

169f6edf5f7d2068.png

Translate something to see it work!

31554e71cb80f1b4.png

7. Conclusion

Congratulations! You learned how to enable the Cloud Translation API, get the necessary credentials, and deploy a simple web app to Python 2 Cloud Run! You can learn more about this deployment from this table in the repo.

Clean up

The Cloud Translation API lets you perform a fixed amount of translated characters per month for free. App Engine also has a free quota, and the same goes for Cloud Functions and Cloud Run. You'll incur charges if either are exceeded. If you plan to continue to the next codelab, you don't have to shut down your app.

However, if you're not ready to go to the next tutorial yet or are concerned that the internet discovers the app that you've just deployed, disable your App Engine app, delete your Cloud Function, or disable your Cloud Run service to avoid incurring charges. When you're ready to move onto the next codelab, you can re-enable it. On the other hand, if you're not going to continue with this application or other codelabs and want to delete everything completely, you can shut down your project.

Also, deploying to a Google Cloud serverless compute platform incurs minor build and storage costs. Cloud Build has its own free quota as does Cloud Storage. For greater transparency, Cloud Build builds your application image, which is then stored in either the Cloud Container Registry or Artifact Registry, its successor. Storage of that image uses up some of that quota as does network egress when transferring that image to the service. However, you might live in a region that does not have such a free tier, so be aware of your storage usage to minimize potential costs.

8. Additional resources

In the following sections, you can find additional reading material as well as recommended exercises to augment your knowledge gained from completing this tutorial.

Additional study

Now that you have some experience with the Translation API under your belt, let's do some additional exercises to further develop your skills. To continue your learning path, modify our sample app to do the following:

  1. Complete all the other editions of this codelab for running locally or deploying to Google Cloud serverless compute platforms (see repo README).
  2. Complete this tutorial using another programming language.
  3. Change this application to support different source or target languages.
  4. Upgrade this application to be able to translate text into more than one language; change the template file to have a pulldown of supported target languages.

Learn more

Google App Engine

Google Cloud Functions

Google Cloud Run

Google Cloud Buildpacks, Container Registry, Artifact Registry

Google Cloud Translation and Google ML Kit

Other Google Cloud products/pages

Python and Flask

License

This tutorial is licensed under a Creative Commons Attribution 2.0 Generic License while the source code in the repo is licensed under Apache 2.