Skip to content

Commit 042e659

Browse files
telpiriongcf-owl-bot[bot]
authored andcommitted
samples: adds samples to client library (#68)
* samples: adds samples to client library * fix: remove deprecated field * fix: renamed region tags * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 8b6f13d commit 042e659

File tree

7 files changed

+534
-0
lines changed

7 files changed

+534
-0
lines changed

media-translation/snippets/noxfile.py

Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
# Copyright 2019 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+
from __future__ import print_function
16+
17+
import os
18+
from pathlib import Path
19+
import sys
20+
from typing import Callable, Dict, List, Optional
21+
22+
import nox
23+
24+
25+
# WARNING - WARNING - WARNING - WARNING - WARNING
26+
# WARNING - WARNING - WARNING - WARNING - WARNING
27+
# DO NOT EDIT THIS FILE EVER!
28+
# WARNING - WARNING - WARNING - WARNING - WARNING
29+
# WARNING - WARNING - WARNING - WARNING - WARNING
30+
31+
# Copy `noxfile_config.py` to your directory and modify it instead.
32+
33+
34+
# `TEST_CONFIG` dict is a configuration hook that allows users to
35+
# modify the test configurations. The values here should be in sync
36+
# with `noxfile_config.py`. Users will copy `noxfile_config.py` into
37+
# their directory and modify it.
38+
39+
TEST_CONFIG = {
40+
# You can opt out from the test for specific Python versions.
41+
'ignored_versions': ["2.7"],
42+
43+
# Old samples are opted out of enforcing Python type hints
44+
# All new samples should feature them
45+
'enforce_type_hints': False,
46+
47+
# An envvar key for determining the project id to use. Change it
48+
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
49+
# build specific Cloud project. You can also use your own string
50+
# to use your own Cloud project.
51+
'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT',
52+
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
53+
# If you need to use a specific version of pip,
54+
# change pip_version_override to the string representation
55+
# of the version number, for example, "20.2.4"
56+
"pip_version_override": None,
57+
# A dictionary you want to inject into your test. Don't put any
58+
# secrets here. These values will override predefined values.
59+
'envs': {},
60+
}
61+
62+
63+
try:
64+
# Ensure we can import noxfile_config in the project's directory.
65+
sys.path.append('.')
66+
from noxfile_config import TEST_CONFIG_OVERRIDE
67+
except ImportError as e:
68+
print("No user noxfile_config found: detail: {}".format(e))
69+
TEST_CONFIG_OVERRIDE = {}
70+
71+
# Update the TEST_CONFIG with the user supplied values.
72+
TEST_CONFIG.update(TEST_CONFIG_OVERRIDE)
73+
74+
75+
def get_pytest_env_vars() -> Dict[str, str]:
76+
"""Returns a dict for pytest invocation."""
77+
ret = {}
78+
79+
# Override the GCLOUD_PROJECT and the alias.
80+
env_key = TEST_CONFIG['gcloud_project_env']
81+
# This should error out if not set.
82+
ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key]
83+
84+
# Apply user supplied envs.
85+
ret.update(TEST_CONFIG['envs'])
86+
return ret
87+
88+
89+
# DO NOT EDIT - automatically generated.
90+
# All versions used to tested samples.
91+
ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"]
92+
93+
# Any default versions that should be ignored.
94+
IGNORED_VERSIONS = TEST_CONFIG['ignored_versions']
95+
96+
TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])
97+
98+
INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False))
99+
#
100+
# Style Checks
101+
#
102+
103+
104+
def _determine_local_import_names(start_dir: str) -> List[str]:
105+
"""Determines all import names that should be considered "local".
106+
107+
This is used when running the linter to insure that import order is
108+
properly checked.
109+
"""
110+
file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)]
111+
return [
112+
basename
113+
for basename, extension in file_ext_pairs
114+
if extension == ".py"
115+
or os.path.isdir(os.path.join(start_dir, basename))
116+
and basename not in ("__pycache__")
117+
]
118+
119+
120+
# Linting with flake8.
121+
#
122+
# We ignore the following rules:
123+
# E203: whitespace before ‘:’
124+
# E266: too many leading ‘#’ for block comment
125+
# E501: line too long
126+
# I202: Additional newline in a section of imports
127+
#
128+
# We also need to specify the rules which are ignored by default:
129+
# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121']
130+
FLAKE8_COMMON_ARGS = [
131+
"--show-source",
132+
"--builtin=gettext",
133+
"--max-complexity=20",
134+
"--import-order-style=google",
135+
"--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py",
136+
"--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202",
137+
"--max-line-length=88",
138+
]
139+
140+
141+
@nox.session
142+
def lint(session: nox.sessions.Session) -> None:
143+
if not TEST_CONFIG['enforce_type_hints']:
144+
session.install("flake8", "flake8-import-order")
145+
else:
146+
session.install("flake8", "flake8-import-order", "flake8-annotations")
147+
148+
local_names = _determine_local_import_names(".")
149+
args = FLAKE8_COMMON_ARGS + [
150+
"--application-import-names",
151+
",".join(local_names),
152+
"."
153+
]
154+
session.run("flake8", *args)
155+
#
156+
# Black
157+
#
158+
159+
160+
@nox.session
161+
def blacken(session: nox.sessions.Session) -> None:
162+
session.install("black")
163+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
164+
165+
session.run("black", *python_files)
166+
167+
#
168+
# Sample Tests
169+
#
170+
171+
172+
PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"]
173+
174+
175+
def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None:
176+
if TEST_CONFIG["pip_version_override"]:
177+
pip_version = TEST_CONFIG["pip_version_override"]
178+
session.install(f"pip=={pip_version}")
179+
"""Runs py.test for a particular project."""
180+
if os.path.exists("requirements.txt"):
181+
if os.path.exists("constraints.txt"):
182+
session.install("-r", "requirements.txt", "-c", "constraints.txt")
183+
else:
184+
session.install("-r", "requirements.txt")
185+
186+
if os.path.exists("requirements-test.txt"):
187+
if os.path.exists("constraints-test.txt"):
188+
session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt")
189+
else:
190+
session.install("-r", "requirements-test.txt")
191+
192+
if INSTALL_LIBRARY_FROM_SOURCE:
193+
session.install("-e", _get_repo_root())
194+
195+
if post_install:
196+
post_install(session)
197+
198+
session.run(
199+
"pytest",
200+
*(PYTEST_COMMON_ARGS + session.posargs),
201+
# Pytest will return 5 when no tests are collected. This can happen
202+
# on travis where slow and flaky tests are excluded.
203+
# See http://doc.pytest.org/en/latest/_modules/_pytest/main.html
204+
success_codes=[0, 5],
205+
env=get_pytest_env_vars()
206+
)
207+
208+
209+
@nox.session(python=ALL_VERSIONS)
210+
def py(session: nox.sessions.Session) -> None:
211+
"""Runs py.test for a sample using the specified version of Python."""
212+
if session.python in TESTED_VERSIONS:
213+
_session_tests(session)
214+
else:
215+
session.skip("SKIPPED: {} tests are disabled for this sample.".format(
216+
session.python
217+
))
218+
219+
220+
#
221+
# Readmegen
222+
#
223+
224+
225+
def _get_repo_root() -> Optional[str]:
226+
""" Returns the root folder of the project. """
227+
# Get root of this repository. Assume we don't have directories nested deeper than 10 items.
228+
p = Path(os.getcwd())
229+
for i in range(10):
230+
if p is None:
231+
break
232+
if Path(p / ".git").exists():
233+
return str(p)
234+
# .git is not available in repos cloned via Cloud Build
235+
# setup.py is always in the library's root, so use that instead
236+
# https://github.com/googleapis/synthtool/issues/792
237+
if Path(p / "setup.py").exists():
238+
return str(p)
239+
p = p.parent
240+
raise Exception("Unable to detect repository root.")
241+
242+
243+
GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")])
244+
245+
246+
@nox.session
247+
@nox.parametrize("path", GENERATED_READMES)
248+
def readmegen(session: nox.sessions.Session, path: str) -> None:
249+
"""(Re-)generates the readme for a sample."""
250+
session.install("jinja2", "pyyaml")
251+
dir_ = os.path.dirname(path)
252+
253+
if os.path.exists(os.path.join(dir_, "requirements.txt")):
254+
session.install("-r", os.path.join(dir_, "requirements.txt"))
255+
256+
in_file = os.path.join(dir_, "README.rst.in")
257+
session.run(
258+
"python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file
259+
)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pytest==6.2.4
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
google-cloud-media-translation==0.2.0
2+
pyaudio==0.2.11
3+
six==1.16.0
56.6 KB
Binary file not shown.
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Copyright 2020 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+
"""Cloud Media Translation sample application.
16+
17+
Example usage:
18+
python translate_from_file.py resources/audio.raw
19+
"""
20+
21+
# [START mediatranslation_translate_from_file]
22+
from google.cloud import mediatranslation
23+
24+
25+
def translate_from_file(file_path="path/to/your/file"):
26+
client = mediatranslation.SpeechTranslationServiceClient()
27+
28+
# The `sample_rate_hertz` field is not required for FLAC and WAV (Linear16)
29+
# encoded data. Other audio encodings must provide the sampling rate.
30+
audio_config = mediatranslation.TranslateSpeechConfig(
31+
audio_encoding="linear16",
32+
source_language_code="en-US",
33+
target_language_code="fr-FR",
34+
)
35+
36+
streaming_config = mediatranslation.StreamingTranslateSpeechConfig(
37+
audio_config=audio_config, single_utterance=True
38+
)
39+
40+
def request_generator(config, audio_file_path):
41+
42+
# The first request contains the configuration.
43+
# Note that audio_content is explicitly set to None.
44+
yield mediatranslation.StreamingTranslateSpeechRequest(streaming_config=config)
45+
46+
with open(audio_file_path, "rb") as audio:
47+
while True:
48+
chunk = audio.read(4096)
49+
if not chunk:
50+
break
51+
yield mediatranslation.StreamingTranslateSpeechRequest(
52+
audio_content=chunk
53+
)
54+
55+
requests = request_generator(streaming_config, file_path)
56+
responses = client.streaming_translate_speech(requests)
57+
58+
for response in responses:
59+
# Once the transcription settles, the response contains the
60+
# is_final result. The other results will be for subsequent portions of
61+
# the audio.
62+
print(f"Response: {response}")
63+
result = response.result
64+
translation = result.text_translation_result.translation
65+
66+
if result.text_translation_result.is_final:
67+
print("\nFinal translation: {0}".format(translation))
68+
break
69+
70+
print("\nPartial translation: {0}".format(translation))
71+
# [END mediatranslation_translate_from_file]
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Copyright 2020 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 os
16+
import re
17+
18+
import translate_from_file
19+
20+
RESOURCES = os.path.join(os.path.dirname(__file__), 'resources')
21+
22+
23+
def test_translate_streaming(capsys):
24+
translate_from_file.translate_from_file(
25+
os.path.join(RESOURCES, 'audio.raw'))
26+
out, err = capsys.readouterr()
27+
28+
assert re.search(r'Partial translation', out, re.DOTALL | re.I)

0 commit comments

Comments
 (0)