|
| 1 | +# Copyright 2023 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START bigquery_remote_function_translation] |
| 16 | +from typing import List |
| 17 | + |
| 18 | +import flask |
| 19 | +import functions_framework |
| 20 | +from google.api_core.retry import Retry |
| 21 | +from google.cloud import translate |
| 22 | + |
| 23 | +# Construct a Translation Client object |
| 24 | +translate_client = translate.TranslationServiceClient() |
| 25 | + |
| 26 | + |
| 27 | +# Register an HTTP function with the Functions Framework |
| 28 | +@functions_framework.http |
| 29 | +def handle_translation(request: flask.Request) -> flask.Response: |
| 30 | + """BigQuery remote function to translate input text. |
| 31 | +
|
| 32 | + Args: |
| 33 | + request: HTTP request from BigQuery |
| 34 | + https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#input_format |
| 35 | +
|
| 36 | + Returns: |
| 37 | + HTTP response to BigQuery |
| 38 | + https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#output_format |
| 39 | + """ |
| 40 | + try: |
| 41 | + # Parse request data as JSON |
| 42 | + request_json = request.get_json() |
| 43 | + # Get the project of the query |
| 44 | + caller = request_json["caller"] |
| 45 | + project = extract_project_from_caller(caller) |
| 46 | + if project is None: |
| 47 | + return flask.make_response( |
| 48 | + flask.jsonify( |
| 49 | + { |
| 50 | + "errorMessage": ( |
| 51 | + 'project can\'t be extracted from "caller":' |
| 52 | + f" {caller}." |
| 53 | + ) |
| 54 | + } |
| 55 | + ), |
| 56 | + 400, |
| 57 | + ) |
| 58 | + # Get the target language code, default is Spanish ("es") |
| 59 | + context = request_json.get("userDefinedContext", {}) |
| 60 | + target = context.get("target_language", "es") |
| 61 | + |
| 62 | + calls = request_json["calls"] |
| 63 | + translated = translate_text( |
| 64 | + [call[0] for call in calls], project, target |
| 65 | + ) |
| 66 | + |
| 67 | + return flask.jsonify({"replies": translated}) |
| 68 | + except Exception as err: |
| 69 | + return flask.make_response( |
| 70 | + flask.jsonify( |
| 71 | + {"errorMessage": f"Unexpected error {type(err)}:{err}"} |
| 72 | + ), |
| 73 | + 400, |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +def extract_project_from_caller(job: str) -> str: |
| 78 | + """Extract project id from full resource name of a BigQuery job. |
| 79 | +
|
| 80 | + Args: |
| 81 | + job: full resource name of a BigQuery job, like |
| 82 | + "//bigquery.googleapi.com/projects/<project>/jobs/<job_id>" |
| 83 | +
|
| 84 | + Returns: |
| 85 | + project id which is contained in the full resource name of the job. |
| 86 | + """ |
| 87 | + path = job.split("/") |
| 88 | + return path[4] if len(path) > 4 else None |
| 89 | + |
| 90 | + |
| 91 | +def translate_text( |
| 92 | + calls: List[str], project: str, target_language_code: str |
| 93 | +) -> List[str]: |
| 94 | + """Translates the input text to specified language using Translation API. |
| 95 | +
|
| 96 | + Args: |
| 97 | + calls: a list of input text to translate. |
| 98 | + project: the project where the translate service will be used. |
| 99 | + target_language_code: The ISO-639 language code to use for translation |
| 100 | + of the input text. See |
| 101 | + https://cloud.google.com/translate/docs/advanced/discovering-supported-languages-v3#supported-target |
| 102 | + for the supported language list. |
| 103 | +
|
| 104 | + Returns: |
| 105 | + a list of translated text. |
| 106 | + """ |
| 107 | + location = "<your location>" |
| 108 | + parent = f"projects/{project}/locations/{location}" |
| 109 | + # Call the Translation API, passing a list of values and the target language |
| 110 | + response = translate_client.translate_text( |
| 111 | + request={ |
| 112 | + "parent": parent, |
| 113 | + "contents": calls, |
| 114 | + "target_language_code": target_language_code, |
| 115 | + "mime_type": "text/plain", |
| 116 | + }, |
| 117 | + retry=Retry(), |
| 118 | + ) |
| 119 | + # Convert the translated value to a list and return it |
| 120 | + return [ |
| 121 | + translation.translated_text for translation in response.translations |
| 122 | + ] |
| 123 | + |
| 124 | + |
| 125 | +# [END bigquery_remote_function_translation] |
0 commit comments