Skip to content

Commit b535a5f

Browse files
fix(translate): update sample translate_text to unify across languages (#13395)
* fix(translate): update sample `translate_text` and unify across languages * fix(translate): fix call to `translate_text` in CLI * fix(translate): implement support to list[str] in `translate_text` sample
1 parent 50c3386 commit b535a5f

File tree

2 files changed

+50
-18
lines changed

2 files changed

+50
-18
lines changed

translate/samples/snippets/snippets.py

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
https://cloud.google.com/translate/docs.
2222
"""
2323

24+
from __future__ import annotations
25+
2426
import argparse
2527

2628

@@ -116,30 +118,60 @@ def translate_text_with_model(target: str, text: str, model: str = "nmt") -> dic
116118

117119

118120
# [START translate_translate_text]
119-
def translate_text(target: str, text: str) -> dict:
120-
"""Translates text into the target language.
121-
122-
Target must be an ISO 639-1 language code.
123-
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
121+
def translate_text(
122+
text: str | bytes | list[str] = "¡Hola amigos y amigas!",
123+
target_language: str = "en",
124+
source_language: str | None = None,
125+
) -> dict:
126+
"""Translates a given text into the specified target language.
127+
128+
Find a list of supported languages and codes here:
129+
https://cloud.google.com/translate/docs/languages#nmt
130+
131+
Args:
132+
text: The text to translate. Can be a string, bytes or a list of strings.
133+
If bytes, it will be decoded as UTF-8.
134+
target_language: The ISO 639 language code to translate the text into
135+
(e.g., 'en' for English, 'es' for Spanish).
136+
source_language: Optional. The ISO 639 language code of the input text
137+
(e.g., 'fr' for French). If None, the API will attempt
138+
to detect the source language automatically.
139+
140+
Returns:
141+
A dictionary containing the translation results.
124142
"""
143+
125144
from google.cloud import translate_v2 as translate
126145

127146
translate_client = translate.Client()
128147

129148
if isinstance(text, bytes):
130-
text = text.decode("utf-8")
149+
text = [text.decode("utf-8")]
131150

132-
# Text can also be a sequence of strings, in which case this method
133-
# will return a sequence of results for each text.
134-
result = translate_client.translate(text, target_language=target)
151+
if isinstance(text, str):
152+
text = [text]
135153

136-
print("Text: {}".format(result["input"]))
137-
print("Translation: {}".format(result["translatedText"]))
138-
print("Detected source language: {}".format(result["detectedSourceLanguage"]))
154+
# If a string is supplied, a single dictionary will be returned.
155+
# In case a list of strings is supplied, this method
156+
# will return a list of dictionaries.
139157

140-
return result
158+
# Find more information about translate function here:
159+
# https://cloud.google.com/python/docs/reference/translate/latest/google.cloud.translate_v2.client.Client#google_cloud_translate_v2_client_Client_translate
160+
results = translate_client.translate(
161+
values=text,
162+
target_language=target_language,
163+
source_language=source_language
164+
)
141165

166+
for result in results:
167+
if "detectedSourceLanguage" in result:
168+
print(f"Detected source language: {result['detectedSourceLanguage']}")
142169

170+
print(f"Input text: {result['input']}")
171+
print(f"Translated text: {result['translatedText']}")
172+
print()
173+
174+
return results
143175
# [END translate_translate_text]
144176

145177

@@ -178,4 +210,4 @@ def translate_text(target: str, text: str) -> dict:
178210
elif args.command == "list-languages-with-target":
179211
list_languages_with_target(args.target)
180212
elif args.command == "translate-text":
181-
translate_text(args.target, args.text)
213+
translate_text(text=args.text, target_language=args.target)

translate/samples/snippets/snippets_test.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,13 @@ def test_list_languages_with_target(capsys: pytest.LogCaptureFixture) -> None:
3838

3939

4040
def test_translate_text(capsys: pytest.LogCaptureFixture) -> None:
41-
result = snippets.translate_text("is", "Hello world")
41+
result = snippets.translate_text(text="Hello world", target_language="is")
4242
out, _ = capsys.readouterr()
43-
assert "Halló heimur" in result["translatedText"]
43+
assert "Halló heimur" in result[0]["translatedText"]
4444

4545

4646
def test_translate_utf8(capsys: pytest.LogCaptureFixture) -> None:
4747
text = "파인애플 13개"
48-
result = snippets.translate_text("en", text)
48+
result = snippets.translate_text(text=text, target_language="en")
4949
out, _ = capsys.readouterr()
50-
assert "13 pineapples" in result["translatedText"]
50+
assert "13 pineapples" in result[0]["translatedText"]

0 commit comments

Comments
 (0)