Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migrate code from googleapis/python-media-translation #9604

Merged
merged 50 commits into from
Apr 13, 2023
Merged
Show file tree
Hide file tree
Changes from 48 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
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
/language/**/* @GoogleCloudPlatform/dee-data-ai @GoogleCloudPlatform/python-samples-reviewers
/logging/**/* @GoogleCloudPlatform/dee-observability @GoogleCloudPlatform/python-samples-reviewers
/media_cdn/**/* @justin-mp @msampathkumar @GoogleCloudPlatform/python-samples-reviewers
/media-translation/**/* @GoogleCloudPlatform/dee-data-ai @GoogleCloudPlatform/python-samples-reviewers
/memorystore/**/* @GoogleCloudPlatform/python-samples-reviewers
/ml_engine/**/* @ivanmkc @GoogleCloudPlatform/python-samples-reviewers
/monitoring/**/* @GoogleCloudPlatform/dee-observability @GoogleCloudPlatform/python-samples-reviewers
Expand Down
3 changes: 0 additions & 3 deletions media-translation/README.md

This file was deleted.

42 changes: 42 additions & 0 deletions media-translation/snippets/noxfile_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Copyright 2021 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.

# Default TEST_CONFIG_OVERRIDE for python repos.

# You can copy this file into your directory, then it will be imported from
# the noxfile.py.

# The source of truth:
# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/noxfile_config.py

TEST_CONFIG_OVERRIDE = {
# You can opt out from the test for specific Python versions.
"ignored_versions": ["2.7", "3.6"],
# 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": {},
}
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)
175 changes: 175 additions & 0 deletions media-translation/snippets/translate_from_mic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# 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 API sample application using a microphone.

Example usage:
python translate_from_mic.py
"""

# [START mediatranslation_translate_from_mic]
from __future__ import division

import itertools

from google.cloud import mediatranslation as media
import pyaudio
from six.moves import queue

# Audio recording parameters
RATE = 16000
CHUNK = int(RATE / 10) # 100ms
SpeechEventType = media.StreamingTranslateSpeechResponse.SpeechEventType


class MicrophoneStream:
"""Opens a recording stream as a generator yielding the audio chunks."""

def __init__(self, rate, chunk):
self._rate = rate
self._chunk = chunk

# Create a thread-safe buffer of audio data
self._buff = queue.Queue()
self.closed = True

def __enter__(self):
self._audio_interface = pyaudio.PyAudio()
self._audio_stream = self._audio_interface.open(
format=pyaudio.paInt16,
channels=1,
rate=self._rate,
input=True,
frames_per_buffer=self._chunk,
# Run the audio stream asynchronously to fill the buffer object.
# This is necessary so that the input device's buffer doesn't
# overflow while the calling thread makes network requests, etc.
stream_callback=self._fill_buffer,
)

self.closed = False

return self

def __exit__(self, type=None, value=None, traceback=None):
self._audio_stream.stop_stream()
self._audio_stream.close()
self.closed = True
# Signal the generator to terminate so that the client's
# streaming_recognize method will not block the process termination.
self._buff.put(None)
self._audio_interface.terminate()

def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
"""Continuously collect data from the audio stream, into the buffer."""
self._buff.put(in_data)
return None, pyaudio.paContinue

def exit(self):
self.__exit__()

def generator(self):
while not self.closed:
# Use a blocking get() to ensure there's at least one chunk of
# data, and stop iteration if the chunk is None, indicating the
# end of the audio stream.
chunk = self._buff.get()
if chunk is None:
return
data = [chunk]

# Now consume whatever other data's still buffered.
while True:
try:
chunk = self._buff.get(block=False)
if chunk is None:
return
data.append(chunk)
except queue.Empty:
break

yield b"".join(data)


def listen_print_loop(responses):
"""Iterates through server responses and prints them.

The responses passed is a generator that will block until a response
is provided by the server.
"""
translation = ""
for response in responses:
# Once the transcription settles, the response contains the
# END_OF_SINGLE_UTTERANCE event.
if response.speech_event_type == SpeechEventType.END_OF_SINGLE_UTTERANCE:

print("\nFinal translation: {0}".format(translation))
return 0

result = response.result
translation = result.text_translation_result.translation

print("\nPartial translation: {0}".format(translation))


def do_translation_loop():
print("Begin speaking...")

client = media.SpeechTranslationServiceClient()

speech_config = media.TranslateSpeechConfig(
audio_encoding="linear16",
source_language_code="en-US",
target_language_code="es-ES",
)

config = media.StreamingTranslateSpeechConfig(
audio_config=speech_config, single_utterance=True
)

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

with MicrophoneStream(RATE, CHUNK) as stream:
audio_generator = stream.generator()
mic_requests = (
media.StreamingTranslateSpeechRequest(audio_content=content)
for content in audio_generator
)

requests = itertools.chain(iter([first_request]), mic_requests)

responses = client.streaming_translate_speech(requests)

# Print the translation responses as they arrive
result = listen_print_loop(responses)
if result == 0:
stream.exit()


def main():
while True:
print()
option = input("Press any key to translate or 'q' to quit: ")

if option.lower() == "q":
break

do_translation_loop()


if __name__ == "__main__":
main()
# [END mediatranslation_translate_from_mic]