Skip to content

Commit 0db551b

Browse files
feat: Hardcoded samples to be migrated - Text Translation Samples (#12531)
* Revised and corrected NMT model Sample and test * Added Gemini translation sample
1 parent 76a2b80 commit 0db551b

File tree

6 files changed

+121
-29
lines changed

6 files changed

+121
-29
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
google-cloud-translate==3.16.0
22
google-cloud-storage==2.9.0
33
google-cloud-automl==2.11.1
4+
google-cloud-aiplatform[vertexai]

translate/samples/snippets/snippets_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,13 @@ def test_list_languages(capsys: pytest.LogCaptureFixture) -> None:
2828
out, _ = capsys.readouterr()
2929
for language in results:
3030
print("{name} ({language})".format(**language))
31-
assert "Afrikaans" in [r["name"] for r in results]
31+
assert "Abkhaz" in results[0]["name"]
3232

3333

3434
def test_list_languages_with_target(capsys: pytest.LogCaptureFixture) -> None:
3535
results = snippets.list_languages_with_target("is")
3636
out, _ = capsys.readouterr()
37-
assert "afríkanska" in [r["name"] for r in results]
37+
assert "abkasíska" in results[0]["name"]
3838

3939

4040
def test_translate_text(capsys: pytest.LogCaptureFixture) -> None:

translate/samples/snippets/translate_v3_translate_text.py

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,39 +14,48 @@
1414

1515
# [START translate_v3_translate_text]
1616
# Imports the Google Cloud Translation library
17-
from google.cloud import translate
17+
import os
1818

19+
from google.cloud import translate_v3
1920

20-
# Initialize Translation client
21-
def translate_text(
22-
text: str = "YOUR_TEXT_TO_TRANSLATE", project_id: str = "YOUR_PROJECT_ID"
23-
) -> translate.TranslationServiceClient:
24-
"""Translating Text."""
25-
26-
client = translate.TranslationServiceClient()
27-
28-
location = "global"
21+
PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")
2922

30-
parent = f"projects/{project_id}/locations/{location}"
3123

32-
# Translate text from English to French
33-
# Detail on supported types can be found here:
34-
# https://cloud.google.com/translate/docs/supported-formats
24+
# Initialize Translation client
25+
def translate_text(
26+
text: str = "YOUR_TEXT_TO_TRANSLATE",
27+
language_code: str = "fr",
28+
) -> translate_v3.TranslationServiceClient:
29+
"""Translating Text from English.
30+
Args:
31+
text: The content to translate.
32+
language_code: The language code for the translation.
33+
E.g. "fr" for French, "es" for Spanish, etc.
34+
Available languages: https://cloud.google.com/translate/docs/languages#neural_machine_translation_model
35+
"""
36+
37+
client = translate_v3.TranslationServiceClient()
38+
parent = f"projects/{PROJECT_ID}/locations/global"
39+
# Translate text from English to chosen language
40+
# Supported mime types: # https://cloud.google.com/translate/docs/supported-formats
3541
response = client.translate_text(
36-
request={
37-
"parent": parent,
38-
"contents": [text],
39-
"mime_type": "text/plain", # mime types: text/plain, text/html
40-
"source_language_code": "en-US",
41-
"target_language_code": "fr",
42-
}
42+
contents=[text],
43+
target_language_code=language_code,
44+
parent=parent,
45+
mime_type="text/plain",
46+
source_language_code="en-US",
4347
)
4448

4549
# Display the translation for each input text provided
4650
for translation in response.translations:
4751
print(f"Translated text: {translation.translated_text}")
52+
# Example response:
53+
# Translated text: Bonjour comment vas-tu aujourd'hui?
4854

4955
return response
5056

5157

5258
# [END translate_v3_translate_text]
59+
60+
if __name__ == "__main__":
61+
translate_text(text="Hello! How are you doing today?", language_code="fr")

translate/samples/snippets/translate_v3_translate_text_test.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,12 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import os
16-
1715
import pytest
1816

1917
import translate_v3_translate_text
2018

2119

22-
PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"]
23-
24-
2520
def test_translate_text(capsys: pytest.LogCaptureFixture) -> None:
26-
response = translate_v3_translate_text.translate_text("Hello World!", PROJECT_ID)
21+
response = translate_v3_translate_text.translate_text("Hello World!", "fr")
2722
out, _ = capsys.readouterr()
2823
assert "Bonjour le monde" in response.translations[0].translated_text
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Copyright 2024 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+
# https://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 aiplatform_gemini_translate]
16+
import os
17+
18+
import vertexai
19+
from vertexai.generative_models import GenerationResponse, GenerativeModel, Part
20+
21+
PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")
22+
23+
24+
def translate_text(text: str, target_language_code: str = "fr") -> GenerationResponse:
25+
"""Translates the given text to the specified target language using the Gemini model.
26+
Args:
27+
text (str): The text to be translated.
28+
target_language_code (str): The language code of the target language. Defaults to "fr" (French).
29+
Available language codes: https://cloud.google.com/translate/docs/languages#neural_machine_translation_model
30+
Returns:
31+
responses: The response from the model containing the translated text.
32+
"""
33+
# Initializes the Vertex AI with the specified project and location
34+
vertexai.init(project=PROJECT_ID, location="europe-west2")
35+
36+
model = GenerativeModel("gemini-1.0-pro")
37+
38+
# Configuration for the text generation
39+
generation_config = {
40+
"candidate_count": 1,
41+
"max_output_tokens": 50,
42+
"temperature": 0.1,
43+
"top_k": 1,
44+
"top_p": 1.0,
45+
}
46+
47+
# Creates a prompt with the text to be translated and the target language code
48+
promt = Part.from_text(
49+
f"TEXT_TO_TRANSLATE:{text}. TARGET_LANGUAGE_CODE:{target_language_code}."
50+
)
51+
52+
responses = model.generate_content(
53+
contents=[promt],
54+
generation_config=generation_config,
55+
)
56+
57+
print(responses.candidates[0].content.text)
58+
# Example response:
59+
# Bonjour ! Comment allez-vous aujourd'hui ?
60+
61+
return responses
62+
63+
64+
# [END aiplatform_gemini_translate]
65+
66+
if __name__ == "__main__":
67+
translate_text(text="Hello! How are you doing today?", target_language_code="fr")
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Copyright 2024 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+
import translate_with_gemini
16+
17+
18+
def test_translate_text_with_gemini() -> None:
19+
response = translate_with_gemini.translate_text("Hello World!", "fr")
20+
assert "Bonjour le monde" in response.candidates[0].content.text

0 commit comments

Comments
 (0)