forked from GoogleCloudPlatform/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslate_v3_translate_text.py
More file actions
74 lines (62 loc) · 2.54 KB
/
translate_v3_translate_text.py
File metadata and controls
74 lines (62 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START translate_v3_translate_text]
import os
# Import the Google Cloud Translation library.
# [START translate_v3_import_client_library]
from google.cloud import translate_v3
# [END translate_v3_import_client_library]
PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")
def translate_text(
text: str = "YOUR_TEXT_TO_TRANSLATE",
source_language_code: str = "en-US",
target_language_code: str = "fr",
) -> translate_v3.TranslationServiceClient:
"""Translate Text from a Source language to a Target language.
Args:
text: The content to translate.
source_language_code: The code of the source language.
target_language_code: The code of the target language.
For example: "fr" for French, "es" for Spanish, etc.
Find available languages and codes here:
https://cloud.google.com/translate/docs/languages#neural_machine_translation_model
"""
# Initialize Translation client.
client = translate_v3.TranslationServiceClient()
parent = f"projects/{PROJECT_ID}/locations/global"
# MIME type of the content to translate.
# Supported MIME types:
# https://cloud.google.com/translate/docs/supported-formats
mime_type = "text/plain"
# Translate text from the source to the target language.
response = client.translate_text(
contents=[text],
parent=parent,
mime_type=mime_type,
source_language_code=source_language_code,
target_language_code=target_language_code,
)
# Display the translation for the text.
# For example, for "Hello! How are you doing today?":
# Translated text: Bonjour comment vas-tu aujourd'hui?
for translation in response.translations:
print(f"Translated text: {translation.translated_text}")
return response
# [END translate_v3_translate_text]
if __name__ == "__main__":
translate_text(
text="Hello! How are you doing today?",
source_language_code="en-US",
target_language_code="fr"
)