Skip to content
Merged
Show file tree
Hide file tree
Changes from 47 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
8ba3376
samples: adds samples to client library (#68)
telpirion Jun 21, 2021
f9361df
chore(deps): update dependency google-cloud-media-translation to v0.4…
renovate-bot Jun 26, 2021
078520f
chore(deps): update dependency google-cloud-media-translation to v0.5…
renovate-bot Jul 3, 2021
ba05dae
feat: add Samples section to CONTRIBUTING.rst (#87)
gcf-owl-bot[bot] Jul 22, 2021
8c88f0e
chore(deps): update dependency google-cloud-media-translation to v0.5…
renovate-bot Jul 22, 2021
cab6b91
chore(deps): update dependency google-cloud-media-translation to v0.5…
renovate-bot Jul 28, 2021
0318215
chore: fix INSTALL_LIBRARY_FROM_SOURCE in noxfile.py (#96)
gcf-owl-bot[bot] Aug 11, 2021
6ad2b82
chore: drop mention of Python 2.7 from templates (#98)
gcf-owl-bot[bot] Aug 13, 2021
1f95c46
chore(deps): update dependency pytest to v6.2.5 (#103)
renovate-bot Aug 30, 2021
9a3e4e3
chore: blacken samples noxfile template (#107)
gcf-owl-bot[bot] Sep 17, 2021
970a6a4
chore(deps): update dependency google-cloud-media-translation to v0.5…
renovate-bot Sep 27, 2021
f28d5b0
chore: fail samples nox session if python version is missing (#113)
gcf-owl-bot[bot] Sep 30, 2021
e663f65
chore(deps): update dependency google-cloud-media-translation to v0.6…
renovate-bot Oct 7, 2021
f7b47d8
chore(python): Add kokoro configs for python 3.10 samples testing (#121)
gcf-owl-bot[bot] Oct 8, 2021
50e0889
chore(deps): update dependency google-cloud-media-translation to v0.7…
renovate-bot Oct 25, 2021
e70f5ba
chore(deps): update dependency google-cloud-media-translation to v0.7…
renovate-bot Nov 2, 2021
46a66f4
chore(python): run blacken session for all directories with a noxfile…
gcf-owl-bot[bot] Nov 11, 2021
0749d31
chore(samples): Add check for tests in directory (#143)
gcf-owl-bot[bot] Jan 11, 2022
e179faf
chore(python): Noxfile recognizes that tests can live in a folder (#147)
gcf-owl-bot[bot] Jan 19, 2022
ef72c06
chore(deps): update dependency pytest to v7 (#154)
renovate-bot Feb 14, 2022
7ade5cb
chore(deps): update all dependencies (#159)
renovate-bot Feb 28, 2022
d599e49
chore: Adding support for pytest-xdist and pytest-parallel (#166)
gcf-owl-bot[bot] Mar 4, 2022
2e6b6ce
chore(deps): update dependency google-cloud-media-translation to v0.8…
renovate-bot Mar 7, 2022
84eea1b
chore(deps): update dependency pytest to v7.1.0 (#170)
renovate-bot Mar 13, 2022
8508809
chore(deps): update dependency pytest to v7.1.1 (#171)
renovate-bot Mar 19, 2022
fe9abe0
chore(python): use black==22.3.0 (#172)
gcf-owl-bot[bot] Mar 28, 2022
af4cb0f
chore(python): add nox session to sort python imports (#183)
gcf-owl-bot[bot] Apr 21, 2022
8ad6bb6
chore(deps): update dependency pytest to v7.1.2 (#186)
renovate-bot Apr 25, 2022
f4eac6e
fix: require python 3.7+ (#201)
gcf-owl-bot[bot] Jul 6, 2022
f6b31f7
chore(deps): update all dependencies (#196)
renovate-bot Jul 7, 2022
dff5ba3
chore(deps): update all dependencies (#208)
renovate-bot Aug 2, 2022
24f3a21
chore(deps): update dependency google-cloud-media-translation to v0.9…
renovate-bot Aug 17, 2022
42036fe
chore(deps): update dependency pytest to v7.1.3 (#224)
renovate-bot Sep 6, 2022
1e690db
chore: detect samples tests in nested directories (#230)
gcf-owl-bot[bot] Sep 13, 2022
0b13de1
chore(deps): update dependency google-cloud-media-translation to v0.9…
renovate-bot Oct 4, 2022
76e34d2
chore(deps): update dependency google-cloud-media-translation to v0.9…
renovate-bot Oct 18, 2022
92021df
chore(deps): update dependency pytest to v7.2.0 (#238)
renovate-bot Oct 26, 2022
f74e32c
chore(python): drop flake8-import-order in samples noxfile (#243)
gcf-owl-bot[bot] Nov 26, 2022
419a936
chore(deps): update dependency google-cloud-media-translation to v0.1…
renovate-bot Dec 15, 2022
d3a3653
chore(deps): update dependency pyaudio to v0.2.13 (#250)
renovate-bot Jan 4, 2023
aeed738
chore(python): add support for python 3.11 (#251)
gcf-owl-bot[bot] Jan 6, 2023
43f9155
chore(deps): update dependency google-cloud-media-translation to v0.1…
renovate-bot Jan 10, 2023
3bc33f4
chore(deps): update dependency pytest to v7.2.1 (#255)
renovate-bot Jan 14, 2023
b4479c1
chore(deps): update dependency google-cloud-media-translation to v0.1…
renovate-bot Jan 24, 2023
2ff8a71
chore(deps): update dependency pytest to v7.2.2 (#266)
renovate-bot Mar 3, 2023
2fb082b
chore(deps): update dependency google-cloud-media-translation to v0.1…
renovate-bot Apr 6, 2023
6c3777c
Merge remote-tracking branch 'migration/main' into python-media-trans…
cojenco Apr 12, 2023
558918b
update nox files and codeowners
cojenco Apr 12, 2023
e953cd0
address comments update blunderbuss
cojenco Apr 13, 2023
e9a7ec5
Merge branch 'main' into python-media-translation-migration
cojenco Apr 13, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
292 changes: 292 additions & 0 deletions media-translation/snippets/noxfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,292 @@
# Copyright 2019 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
#
# http://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.

from __future__ import print_function

import glob
import os
from pathlib import Path
import sys
from typing import Callable, Dict, Optional

import nox

# WARNING - WARNING - WARNING - WARNING - WARNING
# WARNING - WARNING - WARNING - WARNING - WARNING
# DO NOT EDIT THIS FILE EVER!
# WARNING - WARNING - WARNING - WARNING - WARNING
# WARNING - WARNING - WARNING - WARNING - WARNING

BLACK_VERSION = "black==22.3.0"
ISORT_VERSION = "isort==5.10.1"

# Copy `noxfile_config.py` to your directory and modify it instead.

# `TEST_CONFIG` dict is a configuration hook that allows users to
# modify the test configurations. The values here should be in sync
# with `noxfile_config.py`. Users will copy `noxfile_config.py` into
# their directory and modify it.

TEST_CONFIG = {
# You can opt out from the test for specific Python versions.
"ignored_versions": [],
# Old samples are opted out of enforcing Python type hints
# All new samples should feature them
"enforce_type_hints": False,
# An envvar key for determining the project id to use. Change it
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
# build specific Cloud project. You can also use your own string
# to use your own Cloud project.
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
# If you need to use a specific version of pip,
# change pip_version_override to the string representation
# of the version number, for example, "20.2.4"
"pip_version_override": None,
# A dictionary you want to inject into your test. Don't put any
# secrets here. These values will override predefined values.
"envs": {},
}


try:
# Ensure we can import noxfile_config in the project's directory.
sys.path.append(".")
from noxfile_config import TEST_CONFIG_OVERRIDE
except ImportError as e:
print("No user noxfile_config found: detail: {}".format(e))
TEST_CONFIG_OVERRIDE = {}

# Update the TEST_CONFIG with the user supplied values.
TEST_CONFIG.update(TEST_CONFIG_OVERRIDE)


def get_pytest_env_vars() -> Dict[str, str]:
"""Returns a dict for pytest invocation."""
ret = {}

# Override the GCLOUD_PROJECT and the alias.
env_key = TEST_CONFIG["gcloud_project_env"]
# This should error out if not set.
ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key]

# Apply user supplied envs.
ret.update(TEST_CONFIG["envs"])
return ret


# DO NOT EDIT - automatically generated.
# All versions used to test samples.
ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"]

# Any default versions that should be ignored.
IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"]

TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])

INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in (
"True",
"true",
)

# Error if a python version is missing
nox.options.error_on_missing_interpreters = True

#
# Style Checks
#


# Linting with flake8.
#
# We ignore the following rules:
# E203: whitespace before ‘:’
# E266: too many leading ‘#’ for block comment
# E501: line too long
# I202: Additional newline in a section of imports
#
# We also need to specify the rules which are ignored by default:
# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121']
FLAKE8_COMMON_ARGS = [
"--show-source",
"--builtin=gettext",
"--max-complexity=20",
"--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py",
"--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202",
"--max-line-length=88",
]


@nox.session
def lint(session: nox.sessions.Session) -> None:
if not TEST_CONFIG["enforce_type_hints"]:
session.install("flake8")
else:
session.install("flake8", "flake8-annotations")

args = FLAKE8_COMMON_ARGS + [
".",
]
session.run("flake8", *args)


#
# Black
#


@nox.session
def blacken(session: nox.sessions.Session) -> None:
"""Run black. Format code to uniform standard."""
session.install(BLACK_VERSION)
python_files = [path for path in os.listdir(".") if path.endswith(".py")]

session.run("black", *python_files)


#
# format = isort + black
#


@nox.session
def format(session: nox.sessions.Session) -> None:
"""
Run isort to sort imports. Then run black
to format code to uniform standard.
"""
session.install(BLACK_VERSION, ISORT_VERSION)
python_files = [path for path in os.listdir(".") if path.endswith(".py")]

# Use the --fss option to sort imports using strict alphabetical order.
# See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections
session.run("isort", "--fss", *python_files)
session.run("black", *python_files)


#
# Sample Tests
#


PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"]


def _session_tests(
session: nox.sessions.Session, post_install: Callable = None
) -> None:
# check for presence of tests
test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob(
"**/test_*.py", recursive=True
)
test_list.extend(glob.glob("**/tests", recursive=True))

if len(test_list) == 0:
print("No tests found, skipping directory.")
return

if TEST_CONFIG["pip_version_override"]:
pip_version = TEST_CONFIG["pip_version_override"]
session.install(f"pip=={pip_version}")
"""Runs py.test for a particular project."""
concurrent_args = []
if os.path.exists("requirements.txt"):
if os.path.exists("constraints.txt"):
session.install("-r", "requirements.txt", "-c", "constraints.txt")
else:
session.install("-r", "requirements.txt")
with open("requirements.txt") as rfile:
packages = rfile.read()

if os.path.exists("requirements-test.txt"):
if os.path.exists("constraints-test.txt"):
session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt")
else:
session.install("-r", "requirements-test.txt")
with open("requirements-test.txt") as rtfile:
packages += rtfile.read()

if INSTALL_LIBRARY_FROM_SOURCE:
session.install("-e", _get_repo_root())

if post_install:
post_install(session)

if "pytest-parallel" in packages:
concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"])
elif "pytest-xdist" in packages:
concurrent_args.extend(["-n", "auto"])

session.run(
"pytest",
*(PYTEST_COMMON_ARGS + session.posargs + concurrent_args),
# Pytest will return 5 when no tests are collected. This can happen
# on travis where slow and flaky tests are excluded.
# See http://doc.pytest.org/en/latest/_modules/_pytest/main.html
success_codes=[0, 5],
env=get_pytest_env_vars(),
)


@nox.session(python=ALL_VERSIONS)
def py(session: nox.sessions.Session) -> None:
"""Runs py.test for a sample using the specified version of Python."""
if session.python in TESTED_VERSIONS:
_session_tests(session)
else:
session.skip(
"SKIPPED: {} tests are disabled for this sample.".format(session.python)
)


#
# Readmegen
#


def _get_repo_root() -> Optional[str]:
"""Returns the root folder of the project."""
# Get root of this repository. Assume we don't have directories nested deeper than 10 items.
p = Path(os.getcwd())
for i in range(10):
if p is None:
break
if Path(p / ".git").exists():
return str(p)
# .git is not available in repos cloned via Cloud Build
# setup.py is always in the library's root, so use that instead
# https://github.com/googleapis/synthtool/issues/792
if Path(p / "setup.py").exists():
return str(p)
p = p.parent
raise Exception("Unable to detect repository root.")


GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")])


@nox.session
@nox.parametrize("path", GENERATED_READMES)
def readmegen(session: nox.sessions.Session, path: str) -> None:
"""(Re-)generates the readme for a sample."""
session.install("jinja2", "pyyaml")
dir_ = os.path.dirname(path)

if os.path.exists(os.path.join(dir_, "requirements.txt")):
session.install("-r", os.path.join(dir_, "requirements.txt"))

in_file = os.path.join(dir_, "README.rst.in")
session.run(
"python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file
)
1 change: 1 addition & 0 deletions media-translation/snippets/requirements-test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest==7.2.2
3 changes: 3 additions & 0 deletions media-translation/snippets/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
google-cloud-media-translation==0.11.2
pyaudio==0.2.13
six==1.16.0
Binary file added media-translation/snippets/resources/audio.raw
Binary file not shown.
71 changes: 71 additions & 0 deletions media-translation/snippets/translate_from_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# 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
#
# http://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.

"""Cloud Media Translation sample application.

Example usage:
python translate_from_file.py resources/audio.raw
"""

# [START mediatranslation_translate_from_file]
from google.cloud import mediatranslation


def translate_from_file(file_path="path/to/your/file"):
client = mediatranslation.SpeechTranslationServiceClient()

# The `sample_rate_hertz` field is not required for FLAC and WAV (Linear16)
# encoded data. Other audio encodings must provide the sampling rate.
audio_config = mediatranslation.TranslateSpeechConfig(
audio_encoding="linear16",
source_language_code="en-US",
target_language_code="fr-FR",
)

streaming_config = mediatranslation.StreamingTranslateSpeechConfig(
audio_config=audio_config, single_utterance=True
)

def request_generator(config, audio_file_path):

# The first request contains the configuration.
# Note that audio_content is explicitly set to None.
yield mediatranslation.StreamingTranslateSpeechRequest(streaming_config=config)

with open(audio_file_path, "rb") as audio:
while True:
chunk = audio.read(4096)
if not chunk:
break
yield mediatranslation.StreamingTranslateSpeechRequest(
audio_content=chunk
)

requests = request_generator(streaming_config, file_path)
responses = client.streaming_translate_speech(requests)

for response in responses:
# Once the transcription settles, the response contains the
# is_final result. The other results will be for subsequent portions of
# the audio.
print(f"Response: {response}")
result = response.result
translation = result.text_translation_result.translation

if result.text_translation_result.is_final:
print("\nFinal translation: {0}".format(translation))
break

print("\nPartial translation: {0}".format(translation))
# [END mediatranslation_translate_from_file]
27 changes: 27 additions & 0 deletions media-translation/snippets/translate_from_file_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# 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
#
# http://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.

import os
import re

import translate_from_file

RESOURCES = os.path.join(os.path.dirname(__file__), "resources")


def test_translate_streaming(capsys):
translate_from_file.translate_from_file(os.path.join(RESOURCES, "audio.raw"))
out, err = capsys.readouterr()

assert re.search(r"Partial translation", out, re.DOTALL | re.I)
Loading