From 00a269086f2ecec95aa57fdf0b606b614dfa70b9 Mon Sep 17 00:00:00 2001 From: Dan O'Meara Date: Wed, 5 Aug 2020 11:19:26 -0700 Subject: [PATCH] feat!: migrate API to microgenerator (#31) * Add new "quickstart" samples [(#547)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/547) * Quickstart tests [(#569)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/569) * Add tests for quickstarts * Update secrets * Add translate samples [(#574)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/574) * Generate most non-appengine readmes Change-Id: I3779282126cdd05b047194d356932b9995484115 * Update requirements.txt * added model in the sample [(#650)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/650) * added with and without model separately [(#657)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/657) * Translate API no longer requires an API key. [(#659)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/659) * Auto-update dependencies. [(#715)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/715) * Changes default model to premium [(#749)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/749) * Updates readme template to show credential auth instead of api key. [(#802)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/802) * Updates translate version to match speech and language. [(#843)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/843) * Translate update [(#886)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/886) * Remove cloud config fixture [(#887)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/887) * Remove cloud config fixture * Fix client secrets * Fix bigtable instance * Unicode for translation * Adds check for translated text * Unicode for translation * Unicode for translation * Unicode for translation * missing newline * Adds six for 2/3 compatibility * Changes encoding style. * Fix unicode * renaming of the product to Google Translation API [(#910)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/910) * Update translate readme * Re-generate all readmes * Fix README rst links [(#962)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/962) * Fix README rst links * Update all READMEs * Auto-update dependencies. [(#1004)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1004) * Auto-update dependencies. * Fix natural language samples * Fix pubsub iam samples * Fix language samples * Fix bigquery samples * Auto-update dependencies. [(#1055)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1055) * Auto-update dependencies. * Explicitly use latest bigtable client Change-Id: Id71e9e768f020730e4ca9514a0d7ebaa794e7d9e * Revert language update for now Change-Id: I8867f154e9a5aae00d0047c9caf880e5e8f50c53 * Remove pdb. smh Change-Id: I5ff905fadc026eebbcd45512d4e76e003e3b2b43 * Auto-update dependencies. [(#1093)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1093) * Auto-update dependencies. * Fix storage notification poll sample Change-Id: I6afbc79d15e050531555e4c8e51066996717a0f3 * Fix spanner samples Change-Id: I40069222c60d57e8f3d3878167591af9130895cb * Drop coverage because it's not useful Change-Id: Iae399a7083d7866c3c7b9162d0de244fbff8b522 * Try again to fix flaky logging test Change-Id: I6225c074701970c17c426677ef1935bb6d7e36b4 * Update all generated readme auth instructions [(#1121)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1121) Change-Id: I03b5eaef8b17ac3dc3c0339fd2c7447bd3e11bd2 * Added Link to Python Setup Guide [(#1158)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1158) * Update Readme.rst to add Python setup guide As requested in b/64770713. This sample is linked in documentation https://cloud.google.com/bigtable/docs/scaling, and it would make more sense to update the guide here than in the documentation. * Update README.rst * Update README.rst * Update README.rst * Update README.rst * Update README.rst * Update install_deps.tmpl.rst * Updated readmegen scripts and re-generated related README files * Fixed the lint error * Auto-update dependencies. [(#1186)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1186) * Fixed failed tests on Kokoro (Spanner + Translate) [(#1192)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1192) * Fixed failed tests on Kokoro (Spanner + Translate) * Update quickstart_test.py * Added "Open in Cloud Shell" buttons to README files [(#1254)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1254) * Auto-update dependencies. [(#1377)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1377) * Auto-update dependencies. * Update requirements.txt * Regenerate the README files and fix the Open in Cloud Shell link for some samples [(#1441)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1441) * Update READMEs to fix numbering and add git clone [(#1464)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1464) * Add translate region tags [(#1488)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1488) * Add region tags * Added end region tags * Linting errors fixed * Include the comma in the translation [(#1787)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1787) * Auto-update dependencies. [(#1980)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1980) * Auto-update dependencies. * Update requirements.txt * Update requirements.txt * Translation v3beta1 samples [(#2084)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2084) * Add in progress beta snippets Change-Id: I2cd8ddc2307a8e40d56ce7e493749dc05c34d164 * Add google-cloud-storage dependency Change-Id: Iff7bc9b2c82b1e829580a3d4ad628087dbeee8be * Non-'global' location required for BatchTranslateText Change-Id: I5198aa6368a088e8f5ee295dc55a5e9e4ca8f494 * Upgrade google-cloud-translate to 1.4.0 1.4.0 includes the new v3beta1 alongside V2 Change-Id: I5adfe78ea7e78d84678db343cd84516e3d05491f * Update Translate samples You can now provide your own glossary ID The tests now run within a randomly created bucket (deleted after each test) Change-Id: I5cb2680cd0e9e43c85932a6a0dc19e6fab5008c5 * pytest.fixture for random test bucket Change-Id: I8e816ed4c95a6235347a29849044b4cab02d40a8 * flake8 spec fixes Change-Id: I4932bcf856a9498b01d9661c90c6b45ee2958ee1 * Added pytest fixture for creating glossary (WIP) Change-Id: Iddb5ecbf0eefb9efd2243dc4bc56b585102e9351 * Add assertions, remove placeholder TODOs Change-Id: If1eb20bca5bfcc87dd0652d5488b2188afa626af * fixing translate-with-glossary bug [(#2323)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2323) * Translate beta samples fix [(#2327)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2327) * fixing translate-with-glossary bug * tests passing * reverting to python3 compatibility * snippets test fix * Using glossaries with tts and vision tutorial sample code [(#2325)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2325) * fixing translate-with-glossary bug * initial commit * adding resources * adding more resources * glossary accomodates upper case words * finished hybrid glossaries tutorial sample code * Revert "fixing translate-with-glossary bug" This reverts commit 6a9f7ca3f68239a862106fcbcd9c73649ce36c77. * lint fix for tests. TODO src lint fix * lint * it's the final lint-down * adding README * implementing @nnegrey's feedback * lint * lint * extracting files from cloud-client * lint comment test * fixing comments per @beccasaurus * removing redundant directory * implementing @nnegrey's feedback * lint * lint * handling glossary-already-exists exception * lint * adding ssml functionality * fixing imports per @nnegrey * fixed import comment * more specific exceptions import * removing period from copyright * fix: refactored MP3 file creation test for Hybrid glossaries samples [(#2379)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2379) * fix: refactored MP3 file creation test * fix: lint * Fix variable names in comments [(#2400)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2400) * Adds updates for samples profiler ... vision [(#2439)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2439) * Update v2 samples to explicitly use v2 library [(#2498)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2498) * fix: translate test [(#2671)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2671) * fix: translate test * Add unicode formatting * automl: add natural language sentiment analysis ga samples [(#2677)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2677) * automl: add natural language sentiment analysis ga samples * Add links to documentation * Update tests to use centralized project * Fix environment variable, make translate test less flaky * fix region tag typo [(#2731)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2731) * Migrate published samples [(#2759)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2759) Migrate from tmp-generated-samples branch 615c08e Remove boilerplate Update copyright date Blacken Remove unused imports Shorten docstrings Remove CLI Set defaults in function definition Add link to supported types guide Inline function arguments Co-authored-by: Leah E. Cole <6719667+leahecole@users.noreply.github.com> * translate v3 snippets [(#2745)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2745) * translate text v3 * added translate text with glossary snippets * finished glossary tests * removed overlapping files * added encoding tag * added more descriptive docs and broke down tests * Update translate/cloud-client/translate_v3_create_glossary.py Co-Authored-By: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> * Update translate/cloud-client/translate_v3_create_glossary.py Co-Authored-By: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> * fixed test for translate with glossary * fixed lint Co-authored-by: Michelle Casbon Co-authored-by: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> * Translate: migrate published samples [(#2768)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2768) Migrate from tmp-generated-samples branch 615c08e Remove boilerplate Update copyright date Blacken Remove unused imports * Translate: migrate published glossaries samples [(#2769)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2769) Migrate from tmp-generated-samples branch fef998b Remove boilerplate Update copyright date Blacken Remove unused imports Shorten docstrings Remove CLI * translate: increase timeout [(#2937)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2937) * Translate: migrate published v3 translate batch samples [(#2914)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2914) * Translate: migrate published b v3 tch samples * added missing requirements * extended wait time * inlined some vals and specified input and output * added link to supported file types & modified default values of input uri * fixed small nit * chore(deps): update dependency google-cloud-storage to v1.26.0 [(#3046)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3046) * chore(deps): update dependency google-cloud-storage to v1.26.0 * chore(deps): specify dependencies by python version * chore: up other deps to try to remove errors Co-authored-by: Leah E. Cole <6719667+leahecole@users.noreply.github.com> Co-authored-by: Leah Cole * chore(deps): update dependency google-cloud-translate to v1.7.0 [(#3084)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3084) This PR contains the following updates: | Package | Update | Change | |---|---|---| | [google-cloud-translate](https://togithub.com/googleapis/python-translate) | minor | `==1.6.0` -> `==1.7.0` | --- ### Release Notes
googleapis/python-translate ### [`v1.7.0`](https://togithub.com/googleapis/python-translate/blob/master/CHANGELOG.md#​170) [Compare Source](https://togithub.com/googleapis/python-translate/compare/v1.6.0...v1.7.0) 10-07-2019 14:57 PDT ##### Implementation Changes - Update docstrings, client confg (via synth). ([#​9411](https://togithub.com/googleapis/google-cloud-python/pull/9411)) - Remove send / receive message size limit (via synth). ([#​8974](https://togithub.com/googleapis/google-cloud-python/pull/8974)) ##### New Features - Add support for V3 of the API. ([#​9020](https://togithub.com/googleapis/google-cloud-python/pull/9020)) - Make `parent` argument required for all client methods in v3beta1; add `labels` argument (via synth). ([#​9354](https://togithub.com/googleapis/google-cloud-python/pull/9354)) - Add client options to translate_v2. ([#​8737](https://togithub.com/googleapis/google-cloud-python/pull/8737)) ##### Dependencies - Bump minimum version for google-api-core to 1.14.0. ([#​8709](https://togithub.com/googleapis/google-cloud-python/pull/8709)) ##### Documentation - Fix links to reference documentation. ([#​8884](https://togithub.com/googleapis/google-cloud-python/pull/8884)) - Link to googleapis.dev documentation in READMEs. ([#​8705](https://togithub.com/googleapis/google-cloud-python/pull/8705)) ##### Internal / Testing Changes - Update `ListGlossaries` method annotation (via synth) ([#​9385](https://togithub.com/googleapis/google-cloud-python/pull/9385)) - Fix intersphinx reference to requests ([#​9294](https://togithub.com/googleapis/google-cloud-python/pull/9294)) - Remove CI for gh-pages, use googleapis.dev for api_core refs. ([#​9085](https://togithub.com/googleapis/google-cloud-python/pull/9085)) - Update intersphinx mapping for requests. ([#​8805](https://togithub.com/googleapis/google-cloud-python/pull/8805))
--- ### Renovate configuration :date: **Schedule**: At any time (no schedule defined). :vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied. :recycle: **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. :no_bell: **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#GoogleCloudPlatform/python-docs-samples). * translate: fix tests [(#3087)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3087) Fix: https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3018 * translate-v3: samples [(#3034)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3034) * translate with custom model, get supported langs * inlined small nit * added encoding to model test * added missing region tags and link to supported langs * inlined text-to-translate * directly inlined contents * revert text-translate vars * reversed inlined text params * small nit Co-authored-by: Leah E. Cole <6719667+leahecole@users.noreply.github.com> * chore(deps): update dependency google-cloud-vision to v0.42.0 [(#3170)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3170) * chore(deps): update dependency google-cloud-texttospeech to v1 [(#3210)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3210) Co-authored-by: gcf-merge-on-green[bot] <60162190+gcf-merge-on-green[bot]@users.noreply.github.com> * chore(deps): update dependency google-cloud-translate to v2 [(#3211)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3211) This PR contains the following updates: | Package | Update | Change | |---|---|---| | [google-cloud-translate](https://togithub.com/googleapis/python-translate) | major | `==1.7.0` -> `==2.0.1` | --- ### Release Notes
googleapis/python-translate ### [`v2.0.1`](https://togithub.com/googleapis/python-translate/blob/master/CHANGELOG.md#​201-httpswwwgithubcomgoogleapispython-translatecomparev200v201-2020-01-31) [Compare Source](https://togithub.com/googleapis/python-translate/compare/v2.0.0...v2.0.1) ### [`v2.0.0`](https://togithub.com/googleapis/python-translate/blob/master/CHANGELOG.md#​200) [Compare Source](https://togithub.com/googleapis/python-translate/compare/v1.7.0...v2.0.0) 10-23-2019 11:13 PDT ##### New Features - Make v3 the default client. ([#​9498](https://togithub.com/googleapis/google-cloud-python/pull/9498)) ##### Internal / Testing Changes - Add VPC-SC system tests. ([#​9272](https://togithub.com/googleapis/google-cloud-python/pull/9272))
--- ### Renovate configuration :date: **Schedule**: At any time (no schedule defined). :vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied. :recycle: **Rebasing**: Never, or you tick the rebase/retry checkbox. :no_bell: **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#GoogleCloudPlatform/python-docs-samples). * Simplify noxfile setup. [(#2806)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2806) * chore(deps): update dependency requests to v2.23.0 * Simplify noxfile and add version control. * Configure appengine/standard to only test Python 2.7. * Update Kokokro configs to match noxfile. * Add requirements-test to each folder. * Remove Py2 versions from everything execept appengine/standard. * Remove conftest.py. * Remove appengine/standard/conftest.py * Remove 'no-sucess-flaky-report' from pytest.ini. * Add GAE SDK back to appengine/standard tests. * Fix typo. * Roll pytest to python 2 version. * Add a bunch of testing requirements. * Remove typo. * Add appengine lib directory back in. * Add some additional requirements. * Fix issue with flake8 args. * Even more requirements. * Readd appengine conftest.py. * Add a few more requirements. * Even more Appengine requirements. * Add webtest for appengine/standard/mailgun. * Add some additional requirements. * Add workaround for issue with mailjet-rest. * Add responses for appengine/standard/mailjet. Co-authored-by: Renovate Bot * Update dependency google-cloud-vision to v1 [(#3227)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3227) This PR contains the following updates: | Package | Update | Change | |---|---|---| | [google-cloud-vision](https://togithub.com/googleapis/python-vision) | major | `==0.42.0` -> `==1.0.0` | --- ### Release Notes
googleapis/python-vision ### [`v1.0.0`](https://togithub.com/googleapis/python-vision/blob/master/CHANGELOG.md#​100-httpswwwgithubcomgoogleapispython-visioncomparev0420v100-2020-02-28) [Compare Source](https://togithub.com/googleapis/python-vision/compare/v0.42.0...v1.0.0) ##### Features - bump release status to GA ([#​11](https://www.github.com/googleapis/python-vision/issues/11)) ([2129bde](https://www.github.com/googleapis/python-vision/commit/2129bdedfa0dca85c5adc5350bff10d4a485df77))
--- ### Renovate configuration :date: **Schedule**: At any time (no schedule defined). :vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied. :recycle: **Rebasing**: Never, or you tick the rebase/retry checkbox. :no_bell: **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#GoogleCloudPlatform/python-docs-samples). * translate: make test generic [(#3386)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3386) Fix: https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3381 * [translate] fix: mark some tests as flaky [(#3495)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3495) tests which involve LRO. fixes #2875 * testing: replace @flaky with @pytest.mark.flaky [(#3496)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3496) * testing: replace @flaky with @pytest.mark.flaky * lint * mark few tests as flaky that involves LRO polling. * lint * chore(deps): update dependency google-cloud-storage to v1.28.0 [(#3260)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3260) Co-authored-by: Takashi Matsuo * translate: fix glossary leak issue [(#3572)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3572) * fix glossary leak issue * removed try/catch from teardown methods, removed sample_ prefix from all other methods * added specific exceptions to tests, added backoff tags to tests * fixed the lint issues * reordered imports * moved backoff inside methd and removed Retry * corrected import nit * chore: some lint fixes [(#3751)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3751) * chore: some lint fixes * longer timeout, more retries * disable detect_test.py::test_async_detect_document * chore(deps): update dependency google-cloud-storage to v1.28.1 [(#3785)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3785) * chore(deps): update dependency google-cloud-storage to v1.28.1 * [asset] testing: use uuid instead of time Co-authored-by: Takashi Matsuo * [translate] fix hybrid glossaries tests [(#3936)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3936) * testing: start using btlr [(#3959)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3959) * testing: start using btlr The binary is at gs://cloud-devrel-kokoro-resources/btlr/v0.0.1/btlr * add period after DIFF_FROM * use array for btlr args * fix websocket tests * add debug message * wait longer for the server to spin up * dlp: bump the wait timeout to 10 minutes * [run] copy noxfile.py to child directory to avoid gcloud issue * [iam] fix: only display description when the key exists * use uuid4 instead of uuid1 * [iot] testing: use the same format for registry id * Stop asserting Out of memory not in the output * fix missing imports * [dns] testing: more retries with delay * [dlp] testing: longer timeout * use the max-concurrency flag * use 30 workers * [monitoring] use multiple projects * [dlp] testing: longer timeout * Replace GCLOUD_PROJECT with GOOGLE_CLOUD_PROJECT. [(#4022)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4022) * remove whitelist replace with allowlist [(#4050)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4050) * chore(deps): update dependency google-cloud-storage to v1.29.0 [(#4040)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4040) * chore(deps): update dependency google-cloud-texttospeech to v2.1.0 [(#4147)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4147) * testing(translate): parameterize the timeout [(#4247)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4247) fixes #4239 (by specifying a longer timeout) * chore(deps): update dependency pytest to v5.4.3 [(#4279)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4279) * chore(deps): update dependency pytest to v5.4.3 * specify pytest for python 2 in appengine Co-authored-by: Leah Cole * Update dependency flaky to v3.7.0 [(#4300)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4300) * testing(translate): bump the timeout for operations [(#4258)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4258) fixes #4220 * chore: update templates * chore: narrows samples CODEOWNERS to .py only * chore: wip migration to microgenerator client, units, docs complete * feat!: move API to python microgenerator * docs: readmegen updates * chore: add build config for docs-presubmit * chore: rm protos * chore: uses PROJECT_ID env var in system test * chore: clarifies examples in migration guide * chore: adds explicit variable Co-authored-by: Jason Dobry Co-authored-by: Jon Wayne Parrott Co-authored-by: Puneith Kaul Co-authored-by: DPE bot Co-authored-by: Gus Class Co-authored-by: florencep Co-authored-by: Bill Prin Co-authored-by: michaelawyu Co-authored-by: Frank Natividad Co-authored-by: Averi Kitsch Co-authored-by: Charles Engelke Co-authored-by: Rebecca Taylor Co-authored-by: Elizabeth Crowdus Co-authored-by: Noah Negrey Co-authored-by: Leah E. Cole <6719667+leahecole@users.noreply.github.com> Co-authored-by: Michelle Casbon Co-authored-by: Mike <45373284+munkhuushmgl@users.noreply.github.com> Co-authored-by: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> Co-authored-by: WhiteSource Renovate Co-authored-by: Leah Cole Co-authored-by: gcf-merge-on-green[bot] <60162190+gcf-merge-on-green[bot]@users.noreply.github.com> Co-authored-by: Takashi Matsuo Co-authored-by: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> --- packages/google-cloud-translate/.coveragerc | 6 +- packages/google-cloud-translate/README.rst | 5 +- packages/google-cloud-translate/UPGRADING.md | 184 + .../google-cloud-translate/docs/UPGRADING.md | 1 + .../docs/gapic/v3/api.rst | 6 - .../docs/gapic/v3/types.rst | 5 - .../docs/gapic/v3beta1/api.rst | 6 - .../docs/gapic/v3beta1/types.rst | 5 - .../google-cloud-translate/docs/index.rst | 32 +- .../docs/translate_v3/services.rst | 6 + .../docs/translate_v3/types.rst | 5 + .../docs/translate_v3beta1/services.rst | 6 + .../docs/translate_v3beta1/types.rst | 5 + packages/google-cloud-translate/docs/v3.rst | 8 - .../google-cloud-translate/docs/v3beta1.rst | 8 - .../google/cloud/translate/__init__.py | 88 + .../google/cloud/translate/py.typed | 2 + .../google/cloud/translate_v3/__init__.py | 81 +- .../cloud/translate_v3/gapic/__init__.py | 0 .../google/cloud/translate_v3/gapic/enums.py | 91 - .../gapic/translation_service_client.py | 1099 ----- .../translation_service_client_config.py | 82 - .../translate_v3/gapic/transports/__init__.py | 0 .../translation_service_grpc_transport.py | 234 - .../cloud/translate_v3/proto/__init__.py | 0 .../proto/translation_service.proto | 926 ---- .../proto/translation_service_pb2.py | 4050 ----------------- .../proto/translation_service_pb2_grpc.py | 411 -- .../google/cloud/translate_v3/py.typed | 2 + .../cloud/translate_v3/services/__init__.py | 16 + .../services/translation_service/__init__.py | 24 + .../translation_service/async_client.py | 912 ++++ .../services/translation_service/client.py | 1068 +++++ .../services/translation_service/pagers.py | 148 + .../transports/__init__.py | 38 + .../translation_service/transports/base.py | 230 + .../translation_service/transports/grpc.py | 463 ++ .../transports/grpc_asyncio.py | 461 ++ .../google/cloud/translate_v3/types.py | 54 - .../cloud/translate_v3/types/__init__.py | 77 + .../translate_v3/types/translation_service.py | 1028 +++++ .../cloud/translate_v3beta1/__init__.py | 81 +- .../cloud/translate_v3beta1/gapic/__init__.py | 0 .../gapic/translation_service_client.py | 1096 ----- .../translation_service_client_config.py | 82 - .../gapic/transports/__init__.py | 0 .../translation_service_grpc_transport.py | 234 - .../cloud/translate_v3beta1/proto/__init__.py | 0 .../proto/translation_service.proto | 902 ---- .../proto/translation_service_pb2.py | 4042 ---------------- .../proto/translation_service_pb2_grpc.py | 411 -- .../google/cloud/translate_v3beta1/py.typed | 2 + .../translate_v3beta1/services/__init__.py | 16 + .../services/translation_service/__init__.py | 24 + .../translation_service/async_client.py | 799 ++++ .../services/translation_service/client.py | 954 ++++ .../services/translation_service/pagers.py | 148 + .../transports/__init__.py | 38 + .../translation_service/transports/base.py | 230 + .../translation_service/transports/grpc.py | 463 ++ .../transports/grpc_asyncio.py | 461 ++ .../google/cloud/translate_v3beta1/types.py | 54 - .../cloud/translate_v3beta1/types/__init__.py | 77 + .../types/translation_service.py | 1020 +++++ packages/google-cloud-translate/mypy.ini | 3 + packages/google-cloud-translate/noxfile.py | 15 +- .../samples/snippets/beta_snippets.py | 80 +- .../snippets/hybrid_glossaries/README.rst | 23 +- .../hybrid_glossaries/hybrid_tutorial.py | 21 +- .../translate_v3_batch_translate_text.py | 15 +- ...e_v3_batch_translate_text_with_glossary.py | 18 +- .../snippets/translate_v3_create_glossary.py | 2 +- .../snippets/translate_v3_delete_glossary.py | 4 +- .../snippets/translate_v3_detect_language.py | 4 +- .../snippets/translate_v3_get_glossary.py | 2 +- .../translate_v3_get_supported_languages.py | 2 +- ..._v3_get_supported_languages_with_target.py | 5 +- .../snippets/translate_v3_list_glossary.py | 6 +- .../snippets/translate_v3_translate_text.py | 17 +- ...anslate_v3_translate_text_with_glossary.py | 22 +- .../translate_v3_translate_text_with_model.py | 22 +- .../scripts/fixup_translation_v3_keywords.py | 185 + .../fixup_translation_v3beta1_keywords.py | 185 + packages/google-cloud-translate/setup.py | 18 +- .../google-cloud-translate/synth.metadata | 8 +- packages/google-cloud-translate/synth.py | 76 +- .../test_utils/credentials.json.enc | 49 - .../scripts/circleci/get_tagged_package.py | 64 - .../scripts/circleci/twine_upload.sh | 36 - .../test_utils/scripts/get_target_packages.py | 268 -- .../scripts/get_target_packages_kokoro.py | 98 - .../test_utils/scripts/run_emulator.py | 199 - .../test_utils/scripts/update_docs.sh | 93 - .../test_utils/setup.py | 64 - .../test_utils/test_utils/__init__.py | 0 .../test_utils/test_utils/imports.py | 38 - .../test_utils/test_utils/retry.py | 207 - .../test_utils/test_utils/system.py | 81 - .../test_utils/test_utils/vpcsc_config.py | 118 - .../google-cloud-translate/tests/system.py | 73 +- .../tests/unit/gapic/translate_v3/__init__.py | 1 + .../translate_v3/test_translation_service.py | 2543 +++++++++++ .../unit/gapic/translate_v3beta1/__init__.py | 1 + .../test_translation_service.py | 2424 ++++++++++ .../v3/test_translation_service_client_v3.py | 470 -- ...test_translation_service_client_v3beta1.py | 470 -- 106 files changed, 14740 insertions(+), 16297 deletions(-) create mode 100644 packages/google-cloud-translate/UPGRADING.md create mode 120000 packages/google-cloud-translate/docs/UPGRADING.md delete mode 100644 packages/google-cloud-translate/docs/gapic/v3/api.rst delete mode 100644 packages/google-cloud-translate/docs/gapic/v3/types.rst delete mode 100644 packages/google-cloud-translate/docs/gapic/v3beta1/api.rst delete mode 100644 packages/google-cloud-translate/docs/gapic/v3beta1/types.rst create mode 100644 packages/google-cloud-translate/docs/translate_v3/services.rst create mode 100644 packages/google-cloud-translate/docs/translate_v3/types.rst create mode 100644 packages/google-cloud-translate/docs/translate_v3beta1/services.rst create mode 100644 packages/google-cloud-translate/docs/translate_v3beta1/types.rst delete mode 100644 packages/google-cloud-translate/docs/v3.rst delete mode 100644 packages/google-cloud-translate/docs/v3beta1.rst create mode 100644 packages/google-cloud-translate/google/cloud/translate/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate/py.typed delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/gapic/__init__.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/gapic/enums.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/gapic/translation_service_client.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/gapic/translation_service_client_config.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/gapic/transports/__init__.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/gapic/transports/translation_service_grpc_transport.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/proto/__init__.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service.proto delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service_pb2.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service_pb2_grpc.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/py.typed create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/async_client.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/client.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/pagers.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/base.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/grpc.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/grpc_asyncio.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/types.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/types/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3/types/translation_service.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/__init__.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/translation_service_client_config.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/transports/__init__.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/transports/translation_service_grpc_transport.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/__init__.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service.proto delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service_pb2.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service_pb2_grpc.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/py.typed create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/async_client.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/client.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/pagers.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/base.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/grpc.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/grpc_asyncio.py delete mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/types.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/types/__init__.py create mode 100644 packages/google-cloud-translate/google/cloud/translate_v3beta1/types/translation_service.py create mode 100644 packages/google-cloud-translate/mypy.ini create mode 100644 packages/google-cloud-translate/scripts/fixup_translation_v3_keywords.py create mode 100644 packages/google-cloud-translate/scripts/fixup_translation_v3beta1_keywords.py delete mode 100644 packages/google-cloud-translate/test_utils/credentials.json.enc delete mode 100644 packages/google-cloud-translate/test_utils/scripts/circleci/get_tagged_package.py delete mode 100755 packages/google-cloud-translate/test_utils/scripts/circleci/twine_upload.sh delete mode 100644 packages/google-cloud-translate/test_utils/scripts/get_target_packages.py delete mode 100644 packages/google-cloud-translate/test_utils/scripts/get_target_packages_kokoro.py delete mode 100644 packages/google-cloud-translate/test_utils/scripts/run_emulator.py delete mode 100755 packages/google-cloud-translate/test_utils/scripts/update_docs.sh delete mode 100644 packages/google-cloud-translate/test_utils/setup.py delete mode 100644 packages/google-cloud-translate/test_utils/test_utils/__init__.py delete mode 100644 packages/google-cloud-translate/test_utils/test_utils/imports.py delete mode 100644 packages/google-cloud-translate/test_utils/test_utils/retry.py delete mode 100644 packages/google-cloud-translate/test_utils/test_utils/system.py delete mode 100644 packages/google-cloud-translate/test_utils/test_utils/vpcsc_config.py create mode 100644 packages/google-cloud-translate/tests/unit/gapic/translate_v3/__init__.py create mode 100644 packages/google-cloud-translate/tests/unit/gapic/translate_v3/test_translation_service.py create mode 100644 packages/google-cloud-translate/tests/unit/gapic/translate_v3beta1/__init__.py create mode 100644 packages/google-cloud-translate/tests/unit/gapic/translate_v3beta1/test_translation_service.py delete mode 100644 packages/google-cloud-translate/tests/unit/gapic/v3/test_translation_service_client_v3.py delete mode 100644 packages/google-cloud-translate/tests/unit/gapic/v3beta1/test_translation_service_client_v3beta1.py diff --git a/packages/google-cloud-translate/.coveragerc b/packages/google-cloud-translate/.coveragerc index dd39c8546c41..b6b6f7b3d218 100644 --- a/packages/google-cloud-translate/.coveragerc +++ b/packages/google-cloud-translate/.coveragerc @@ -32,4 +32,8 @@ omit = */gapic/*.py */proto/*.py */core/*.py - */site-packages/*.py \ No newline at end of file + */site-packages/*.py + google/cloud/__init__.py + google/cloud/translate.py + google/cloud/translate/__init__.py + google/cloud/translation*/*.py \ No newline at end of file diff --git a/packages/google-cloud-translate/README.rst b/packages/google-cloud-translate/README.rst index 1ca13ab74749..2d09f1479e86 100644 --- a/packages/google-cloud-translate/README.rst +++ b/packages/google-cloud-translate/README.rst @@ -55,11 +55,12 @@ dependencies. Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Python >= 3.5 +Python >= 3.6 Deprecated Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^ -Python == 2.7. Python 2.7 support will be removed on January 1, 2020. +Python == 2.7. +The last version of this library compatible with Python 2.7 is google-cloud-translate==2.0.1. Mac/Linux diff --git a/packages/google-cloud-translate/UPGRADING.md b/packages/google-cloud-translate/UPGRADING.md new file mode 100644 index 000000000000..7c564789b81b --- /dev/null +++ b/packages/google-cloud-translate/UPGRADING.md @@ -0,0 +1,184 @@ +# 3.0.0 Migration Guide + +The 3.0 release of the `google-cloud-translate` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage. + +If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-translate/issues). + +## Supported Python Versions + +> **WARNING**: Breaking change + +The 3.0.0 release requires Python 3.6+. + + +## Method Calls + +> **WARNING**: Breaking change + +Methods expect request objects. We provide a script that will convert most common use cases. + +* Install the library + +```py +python3 -m pip install google-cloud-translate +``` + +* The script `fixup_translation_{version}_keywords.py` is shipped with the library. It expects +an input directory (with the code to convert) and an empty destination directory. + +```sh +$ fixup_translation_v3_keywords.py --input-directory .samples/ --output-directory samples/ +``` + +**Before:** +```py +from google.cloud import translate + +client = translate.TranslationServiceClient() +parent = client.location_path("", "") +text = "Good morning!" + +response = client.translate_text( + parent=parent, + contents=[text], + mime_type="text/plain", + source_language_code="en-US", + target_language_code="fr", +) +``` + + +**After:** +```py +from google.cloud import translate + +client = translate.TranslationServiceClient() +parent = "projects//locations/" +text = "Good morning!" + +response = client.translate_text( + request={ + "parent": parent, + "contents": [text], + "mime_type": "text/plain", + "source_language_code": "en-US", + "target_language_code": "fr" + } +) +``` + +### More Details + +In `google-cloud-translate<3.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters. + +**Before:** +```py + def translate_text( + self, + contents, + target_language_code, + parent, + mime_type=None, + source_language_code=None, + model=None, + glossary_config=None, + labels=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): +``` + +In the 3.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional. + +Some methods have additional keyword only parameters. The available parameters depend on the [`google.api.method_signature` annotation](https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3/translation_service.proto#L55) specified by the API producer. + + +**After:** +```py + def translate_text( + self, + request: translation_service.TranslateTextRequest = None, + *, + parent: str = None, + target_language_code: str = None, + contents: Sequence[str] = None, + model: str = None, + mime_type: str = None, + source_language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateTextResponse: +``` + +> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive. +> Passing both will result in an error. + + +Both of these calls are valid: + +```py +response = client.translate_text( + request={ + "parent": parent, + "target_language_code": target_language_code, + "contents": contents + } +) +``` + +```py +response = client.translate_text( + parent=parent, + target_language_code=target_language_code, + contents=contents +) +``` + +This call is invalid because it mixes `request` with a keyword argument `target_language_code`. Executing this code +will result in an error. + +```py +response = client.translate_text( + request={ + "parent": parent, + "contents": contents, + }, + target_language_code=target_language_code +) +``` + + + +## Enums and types + + +> **WARNING**: Breaking change + +The submodule `enums` (containing enum classes for long running operation State) has been removed. + +The submodule `types` is still present. When using the primary version module alias (`translate`) +it is possible to access the types classes directly. + +```py +from google.cloud import translate # the primary version is imported by default + +client = translate.TranslationServiceClient() + +glossary_config = client.TranslateTextGlossaryConfig( + glossary=glossary_path +) +``` + +When a specific version is imported, the full module name must be specified to access types classes. + +```py +from google.cloud import translate_v3beta1 as translate + +client = translate.TranslationServiceClient() + +glossary_config = client.types.TranslateTextGlossaryConfig( + glossary=glossary_path +) +``` diff --git a/packages/google-cloud-translate/docs/UPGRADING.md b/packages/google-cloud-translate/docs/UPGRADING.md new file mode 120000 index 000000000000..01097c8c0fb8 --- /dev/null +++ b/packages/google-cloud-translate/docs/UPGRADING.md @@ -0,0 +1 @@ +../UPGRADING.md \ No newline at end of file diff --git a/packages/google-cloud-translate/docs/gapic/v3/api.rst b/packages/google-cloud-translate/docs/gapic/v3/api.rst deleted file mode 100644 index e16ef6a89d51..000000000000 --- a/packages/google-cloud-translate/docs/gapic/v3/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Translation API -================================ - -.. automodule:: google.cloud.translate_v3 - :members: - :inherited-members: \ No newline at end of file diff --git a/packages/google-cloud-translate/docs/gapic/v3/types.rst b/packages/google-cloud-translate/docs/gapic/v3/types.rst deleted file mode 100644 index fb83ab0657b6..000000000000 --- a/packages/google-cloud-translate/docs/gapic/v3/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Translation API Client -====================================== - -.. automodule:: google.cloud.translate_v3.types - :members: \ No newline at end of file diff --git a/packages/google-cloud-translate/docs/gapic/v3beta1/api.rst b/packages/google-cloud-translate/docs/gapic/v3beta1/api.rst deleted file mode 100644 index 4d46ad1362b4..000000000000 --- a/packages/google-cloud-translate/docs/gapic/v3beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Translation API -================================ - -.. automodule:: google.cloud.translate_v3beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/packages/google-cloud-translate/docs/gapic/v3beta1/types.rst b/packages/google-cloud-translate/docs/gapic/v3beta1/types.rst deleted file mode 100644 index 8b9725da3b1d..000000000000 --- a/packages/google-cloud-translate/docs/gapic/v3beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Translation API Client -====================================== - -.. automodule:: google.cloud.translate_v3beta1.types - :members: \ No newline at end of file diff --git a/packages/google-cloud-translate/docs/index.rst b/packages/google-cloud-translate/docs/index.rst index 5289f58cd2a0..cbb4edc45d88 100644 --- a/packages/google-cloud-translate/docs/index.rst +++ b/packages/google-cloud-translate/docs/index.rst @@ -13,15 +13,41 @@ want to import from ``google.cloud.translate_v3beta1`` in lieu of ``google.cloud.translate``. The previous release ``v2`` is also available. Import from ``google.cloud.translate_v2`` to use this release. - +v3 API Reference +---------------- .. toctree:: :maxdepth: 2 - v3 - v3beta1 + Client (v3) + Types (v3) + +v3beta1 API Reference +--------------------- +.. toctree:: + :maxdepth: 2 + + Client (v3beta1) + Types (v3beta1) + +v2 API Reference +---------------- +.. toctree:: + :maxdepth: 2 + v2 +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 3.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING + + Changelog --------- diff --git a/packages/google-cloud-translate/docs/translate_v3/services.rst b/packages/google-cloud-translate/docs/translate_v3/services.rst new file mode 100644 index 000000000000..8400587ead48 --- /dev/null +++ b/packages/google-cloud-translate/docs/translate_v3/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Translation v3 API +============================================ + +.. automodule:: google.cloud.translate_v3.services.translation_service + :members: + :inherited-members: diff --git a/packages/google-cloud-translate/docs/translate_v3/types.rst b/packages/google-cloud-translate/docs/translate_v3/types.rst new file mode 100644 index 000000000000..a126067f732b --- /dev/null +++ b/packages/google-cloud-translate/docs/translate_v3/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Translation v3 API +========================================= + +.. automodule:: google.cloud.translate_v3.types + :members: diff --git a/packages/google-cloud-translate/docs/translate_v3beta1/services.rst b/packages/google-cloud-translate/docs/translate_v3beta1/services.rst new file mode 100644 index 000000000000..eb522c991b0e --- /dev/null +++ b/packages/google-cloud-translate/docs/translate_v3beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Translation v3beta1 API +================================================= + +.. automodule:: google.cloud.translate_v3beta1.services.translation_service + :members: + :inherited-members: diff --git a/packages/google-cloud-translate/docs/translate_v3beta1/types.rst b/packages/google-cloud-translate/docs/translate_v3beta1/types.rst new file mode 100644 index 000000000000..aaf049734b1b --- /dev/null +++ b/packages/google-cloud-translate/docs/translate_v3beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Translation v3beta1 API +============================================== + +.. automodule:: google.cloud.translate_v3beta1.types + :members: diff --git a/packages/google-cloud-translate/docs/v3.rst b/packages/google-cloud-translate/docs/v3.rst deleted file mode 100644 index b6b8cd17e1e6..000000000000 --- a/packages/google-cloud-translate/docs/v3.rst +++ /dev/null @@ -1,8 +0,0 @@ -v3 -=== - -.. toctree:: - :maxdepth: 2 - - gapic/v3/api - gapic/v3/types diff --git a/packages/google-cloud-translate/docs/v3beta1.rst b/packages/google-cloud-translate/docs/v3beta1.rst deleted file mode 100644 index 368aed30e243..000000000000 --- a/packages/google-cloud-translate/docs/v3beta1.rst +++ /dev/null @@ -1,8 +0,0 @@ -v3beta1 -======= - -.. toctree:: - :maxdepth: 2 - - gapic/v3beta1/api - gapic/v3beta1/types diff --git a/packages/google-cloud-translate/google/cloud/translate/__init__.py b/packages/google-cloud-translate/google/cloud/translate/__init__.py new file mode 100644 index 000000000000..8c9024db945d --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from google.cloud.translate_v3.services.translation_service.async_client import ( + TranslationServiceAsyncClient, +) +from google.cloud.translate_v3.services.translation_service.client import ( + TranslationServiceClient, +) +from google.cloud.translate_v3.types.translation_service import BatchTranslateMetadata +from google.cloud.translate_v3.types.translation_service import BatchTranslateResponse +from google.cloud.translate_v3.types.translation_service import ( + BatchTranslateTextRequest, +) +from google.cloud.translate_v3.types.translation_service import CreateGlossaryMetadata +from google.cloud.translate_v3.types.translation_service import CreateGlossaryRequest +from google.cloud.translate_v3.types.translation_service import DeleteGlossaryMetadata +from google.cloud.translate_v3.types.translation_service import DeleteGlossaryRequest +from google.cloud.translate_v3.types.translation_service import DeleteGlossaryResponse +from google.cloud.translate_v3.types.translation_service import DetectLanguageRequest +from google.cloud.translate_v3.types.translation_service import DetectLanguageResponse +from google.cloud.translate_v3.types.translation_service import DetectedLanguage +from google.cloud.translate_v3.types.translation_service import GcsDestination +from google.cloud.translate_v3.types.translation_service import GcsSource +from google.cloud.translate_v3.types.translation_service import GetGlossaryRequest +from google.cloud.translate_v3.types.translation_service import ( + GetSupportedLanguagesRequest, +) +from google.cloud.translate_v3.types.translation_service import Glossary +from google.cloud.translate_v3.types.translation_service import GlossaryInputConfig +from google.cloud.translate_v3.types.translation_service import InputConfig +from google.cloud.translate_v3.types.translation_service import ListGlossariesRequest +from google.cloud.translate_v3.types.translation_service import ListGlossariesResponse +from google.cloud.translate_v3.types.translation_service import OutputConfig +from google.cloud.translate_v3.types.translation_service import SupportedLanguage +from google.cloud.translate_v3.types.translation_service import SupportedLanguages +from google.cloud.translate_v3.types.translation_service import ( + TranslateTextGlossaryConfig, +) +from google.cloud.translate_v3.types.translation_service import TranslateTextRequest +from google.cloud.translate_v3.types.translation_service import TranslateTextResponse +from google.cloud.translate_v3.types.translation_service import Translation + +__all__ = ( + "BatchTranslateMetadata", + "BatchTranslateResponse", + "BatchTranslateTextRequest", + "CreateGlossaryMetadata", + "CreateGlossaryRequest", + "DeleteGlossaryMetadata", + "DeleteGlossaryRequest", + "DeleteGlossaryResponse", + "DetectLanguageRequest", + "DetectLanguageResponse", + "DetectedLanguage", + "GcsDestination", + "GcsSource", + "GetGlossaryRequest", + "GetSupportedLanguagesRequest", + "Glossary", + "GlossaryInputConfig", + "InputConfig", + "ListGlossariesRequest", + "ListGlossariesResponse", + "OutputConfig", + "SupportedLanguage", + "SupportedLanguages", + "TranslateTextGlossaryConfig", + "TranslateTextRequest", + "TranslateTextResponse", + "Translation", + "TranslationServiceAsyncClient", + "TranslationServiceClient", +) diff --git a/packages/google-cloud-translate/google/cloud/translate/py.typed b/packages/google-cloud-translate/google/cloud/translate/py.typed new file mode 100644 index 000000000000..dd819a47cefe --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-translation package uses inline types. diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3/__init__.py index e595cf3513b3..b7cd2fe07916 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v3/__init__.py +++ b/packages/google-cloud-translate/google/cloud/translate_v3/__init__.py @@ -1,42 +1,77 @@ # -*- coding: utf-8 -*- -# + # 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 absolute_import -import sys -import warnings - -from google.cloud.translate_v3 import types -from google.cloud.translate_v3.gapic import translation_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class TranslationServiceClient(translation_service_client.TranslationServiceClient): - __doc__ = translation_service_client.TranslationServiceClient.__doc__ +from .services.translation_service import TranslationServiceClient +from .types.translation_service import BatchTranslateMetadata +from .types.translation_service import BatchTranslateResponse +from .types.translation_service import BatchTranslateTextRequest +from .types.translation_service import CreateGlossaryMetadata +from .types.translation_service import CreateGlossaryRequest +from .types.translation_service import DeleteGlossaryMetadata +from .types.translation_service import DeleteGlossaryRequest +from .types.translation_service import DeleteGlossaryResponse +from .types.translation_service import DetectLanguageRequest +from .types.translation_service import DetectLanguageResponse +from .types.translation_service import DetectedLanguage +from .types.translation_service import GcsDestination +from .types.translation_service import GcsSource +from .types.translation_service import GetGlossaryRequest +from .types.translation_service import GetSupportedLanguagesRequest +from .types.translation_service import Glossary +from .types.translation_service import GlossaryInputConfig +from .types.translation_service import InputConfig +from .types.translation_service import ListGlossariesRequest +from .types.translation_service import ListGlossariesResponse +from .types.translation_service import OutputConfig +from .types.translation_service import SupportedLanguage +from .types.translation_service import SupportedLanguages +from .types.translation_service import TranslateTextGlossaryConfig +from .types.translation_service import TranslateTextRequest +from .types.translation_service import TranslateTextResponse +from .types.translation_service import Translation __all__ = ( - "types", + "BatchTranslateMetadata", + "BatchTranslateResponse", + "BatchTranslateTextRequest", + "CreateGlossaryMetadata", + "CreateGlossaryRequest", + "DeleteGlossaryMetadata", + "DeleteGlossaryRequest", + "DeleteGlossaryResponse", + "DetectLanguageRequest", + "DetectLanguageResponse", + "DetectedLanguage", + "GcsDestination", + "GcsSource", + "GetGlossaryRequest", + "GetSupportedLanguagesRequest", + "Glossary", + "GlossaryInputConfig", + "InputConfig", + "ListGlossariesRequest", + "ListGlossariesResponse", + "OutputConfig", + "SupportedLanguage", + "SupportedLanguages", + "TranslateTextGlossaryConfig", + "TranslateTextRequest", + "TranslateTextResponse", + "Translation", "TranslationServiceClient", ) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3/gapic/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/enums.py b/packages/google-cloud-translate/google/cloud/translate_v3/gapic/enums.py deleted file mode 100644 index 051328dab5b6..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/enums.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class BatchTranslateMetadata(object): - class State(enum.IntEnum): - """ - State of the job. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - RUNNING (int): Request is being processed. - SUCCEEDED (int): The batch is processed, and at least one item was successfully - processed. - FAILED (int): The batch is done and no item was successfully processed. - CANCELLING (int): Request is in the process of being canceled after caller invoked - longrunning.Operations.CancelOperation on the request id. - CANCELLED (int): The batch is done after the user has called the - longrunning.Operations.CancelOperation. Any records processed before the - cancel command are output as specified in the request. - """ - - STATE_UNSPECIFIED = 0 - RUNNING = 1 - SUCCEEDED = 2 - FAILED = 3 - CANCELLING = 4 - CANCELLED = 5 - - -class CreateGlossaryMetadata(object): - class State(enum.IntEnum): - """ - Enumerates the possible states that the creation request can be in. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - RUNNING (int): Request is being processed. - SUCCEEDED (int): The glossary was successfully created. - FAILED (int): Failed to create the glossary. - CANCELLING (int): Request is in the process of being canceled after caller invoked - longrunning.Operations.CancelOperation on the request id. - CANCELLED (int): The glossary creation request was successfully canceled. - """ - - STATE_UNSPECIFIED = 0 - RUNNING = 1 - SUCCEEDED = 2 - FAILED = 3 - CANCELLING = 4 - CANCELLED = 5 - - -class DeleteGlossaryMetadata(object): - class State(enum.IntEnum): - """ - Enumerates the possible states that the creation request can be in. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - RUNNING (int): Request is being processed. - SUCCEEDED (int): The glossary was successfully deleted. - FAILED (int): Failed to delete the glossary. - CANCELLING (int): Request is in the process of being canceled after caller invoked - longrunning.Operations.CancelOperation on the request id. - CANCELLED (int): The glossary deletion request was successfully canceled. - """ - - STATE_UNSPECIFIED = 0 - RUNNING = 1 - SUCCEEDED = 2 - FAILED = 3 - CANCELLING = 4 - CANCELLED = 5 diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/translation_service_client.py b/packages/google-cloud-translate/google/cloud/translate_v3/gapic/translation_service_client.py deleted file mode 100644 index 3852f06c1921..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/translation_service_client.py +++ /dev/null @@ -1,1099 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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. - -"""Accesses the google.cloud.translation.v3 TranslationService API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import google.api_core.protobuf_helpers -import grpc - -from google.cloud.translate_v3.gapic import translation_service_client_config -from google.cloud.translate_v3.gapic.transports import ( - translation_service_grpc_transport, -) -from google.cloud.translate_v3.proto import translation_service_pb2 -from google.cloud.translate_v3.proto import translation_service_pb2_grpc -from google.longrunning import operations_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-translate", -).version - - -class TranslationServiceClient(object): - """Provides natural language translation operations.""" - - SERVICE_ADDRESS = "translate.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.translation.v3.TranslationService" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - TranslationServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def glossary_path(cls, project, location, glossary): - """Return a fully-qualified glossary string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/glossaries/{glossary}", - project=project, - location=location, - glossary=glossary, - ) - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.TranslationServiceGrpcTransport, - Callable[[~.Credentials, type], ~.TranslationServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = translation_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=translation_service_grpc_transport.TranslationServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = translation_service_grpc_transport.TranslationServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def translate_text( - self, - contents, - target_language_code, - parent, - mime_type=None, - source_language_code=None, - model=None, - glossary_config=None, - labels=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Translates input text and returns translated text. - - Example: - >>> from google.cloud import translate_v3 - >>> - >>> client = translate_v3.TranslationServiceClient() - >>> - >>> # TODO: Initialize `contents`: - >>> contents = [] - >>> - >>> # TODO: Initialize `target_language_code`: - >>> target_language_code = '' - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> response = client.translate_text(contents, target_language_code, parent) - - Args: - contents (list[str]): Required. The content of the input in string format. - We recommend the total content be less than 30k codepoints. - Use BatchTranslateText for larger text. - target_language_code (str): Required. The BCP-47 language code to use for translation of the input - text, set to one of the language codes listed in Language Support. - parent (str): Required. Project or location to make a call. Must refer to a - caller's project. - - Format: ``projects/{project-number-or-id}`` or - ``projects/{project-number-or-id}/locations/{location-id}``. - - For global calls, use - ``projects/{project-number-or-id}/locations/global`` or - ``projects/{project-number-or-id}``. - - Non-global location is required for requests using AutoML models or - custom glossaries. - - Models and glossaries must be within the same region (have same - location-id), otherwise an INVALID_ARGUMENT (400) error is returned. - mime_type (str): Optional. The format of the source text, for example, "text/html", - "text/plain". If left blank, the MIME type defaults to "text/html". - source_language_code (str): Optional. The BCP-47 language code of the input text if - known, for example, "en-US" or "sr-Latn". Supported language codes are - listed in Language Support. If the source language isn't specified, the API - attempts to identify the source language automatically and returns the - source language within the response. - model (str): Optional. The ``model`` type requested for this translation. - - The format depends on model type: - - - AutoML Translation models: - ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` - - - General (built-in) models: - ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` - - For global (non-regionalized) requests, use ``location-id`` ``global``. - For example, - ``projects/{project-number-or-id}/locations/global/models/general/nmt``. - - If missing, the system decides which google base model to use. - glossary_config (Union[dict, ~google.cloud.translate_v3.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary must be within the - same region (have the same location-id) as the model, otherwise an - INVALID_ARGUMENT (400) error is returned. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3.types.TranslateTextGlossaryConfig` - labels (dict[str -> str]): Optional. The labels with user-defined metadata for the request. - - Label keys and values can be no longer than 63 characters - (Unicode codepoints), can only contain lowercase letters, numeric - characters, underscores and dashes. International characters are allowed. - Label values are optional. Label keys must start with a letter. - - See https://cloud.google.com/translate/docs/labels for more information. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3.types.TranslateTextResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "translate_text" not in self._inner_api_calls: - self._inner_api_calls[ - "translate_text" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.translate_text, - default_retry=self._method_configs["TranslateText"].retry, - default_timeout=self._method_configs["TranslateText"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.TranslateTextRequest( - contents=contents, - target_language_code=target_language_code, - parent=parent, - mime_type=mime_type, - source_language_code=source_language_code, - model=model, - glossary_config=glossary_config, - labels=labels, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["translate_text"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def detect_language( - self, - parent, - model=None, - content=None, - mime_type=None, - labels=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Detects the language of text within a request. - - Example: - >>> from google.cloud import translate_v3 - >>> - >>> client = translate_v3.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> response = client.detect_language(parent) - - Args: - parent (str): Required. Project or location to make a call. Must refer to a - caller's project. - - Format: ``projects/{project-number-or-id}/locations/{location-id}`` or - ``projects/{project-number-or-id}``. - - For global calls, use - ``projects/{project-number-or-id}/locations/global`` or - ``projects/{project-number-or-id}``. - - Only models within the same region (has same location-id) can be used. - Otherwise an INVALID_ARGUMENT (400) error is returned. - model (str): Optional. The language detection model to be used. - - Format: - ``projects/{project-number-or-id}/locations/{location-id}/models/language-detection/{model-id}`` - - Only one language detection model is currently supported: - ``projects/{project-number-or-id}/locations/{location-id}/models/language-detection/default``. - - If not specified, the default model is used. - content (str): The content of the input stored as a string. - mime_type (str): Optional. The format of the source text, for example, "text/html", - "text/plain". If left blank, the MIME type defaults to "text/html". - labels (dict[str -> str]): Optional. The labels with user-defined metadata for the request. - - Label keys and values can be no longer than 63 characters - (Unicode codepoints), can only contain lowercase letters, numeric - characters, underscores and dashes. International characters are allowed. - Label values are optional. Label keys must start with a letter. - - See https://cloud.google.com/translate/docs/labels for more information. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3.types.DetectLanguageResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "detect_language" not in self._inner_api_calls: - self._inner_api_calls[ - "detect_language" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.detect_language, - default_retry=self._method_configs["DetectLanguage"].retry, - default_timeout=self._method_configs["DetectLanguage"].timeout, - client_info=self._client_info, - ) - - # Sanity check: We have some fields which are mutually exclusive; - # raise ValueError if more than one is sent. - google.api_core.protobuf_helpers.check_oneof(content=content,) - - request = translation_service_pb2.DetectLanguageRequest( - parent=parent, - model=model, - content=content, - mime_type=mime_type, - labels=labels, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["detect_language"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_supported_languages( - self, - parent, - display_language_code=None, - model=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns a list of supported languages for translation. - - Example: - >>> from google.cloud import translate_v3 - >>> - >>> client = translate_v3.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> response = client.get_supported_languages(parent) - - Args: - parent (str): Required. Project or location to make a call. Must refer to a - caller's project. - - Format: ``projects/{project-number-or-id}`` or - ``projects/{project-number-or-id}/locations/{location-id}``. - - For global calls, use - ``projects/{project-number-or-id}/locations/global`` or - ``projects/{project-number-or-id}``. - - Non-global location is required for AutoML models. - - Only models within the same region (have same location-id) can be used, - otherwise an INVALID_ARGUMENT (400) error is returned. - display_language_code (str): Optional. The language to use to return localized, human readable names - of supported languages. If missing, then display names are not returned - in a response. - model (str): Optional. Get supported languages of this model. - - The format depends on model type: - - - AutoML Translation models: - ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` - - - General (built-in) models: - ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` - - Returns languages supported by the specified model. If missing, we get - supported languages of Google general base (PBMT) model. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3.types.SupportedLanguages` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_supported_languages" not in self._inner_api_calls: - self._inner_api_calls[ - "get_supported_languages" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_supported_languages, - default_retry=self._method_configs["GetSupportedLanguages"].retry, - default_timeout=self._method_configs["GetSupportedLanguages"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.GetSupportedLanguagesRequest( - parent=parent, display_language_code=display_language_code, model=model, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_supported_languages"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def batch_translate_text( - self, - parent, - source_language_code, - target_language_codes, - input_configs, - output_config, - models=None, - glossaries=None, - labels=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Translates a large volume of text in asynchronous batch mode. - This function provides real-time output as the inputs are being processed. - If caller cancels a request, the partial results (for an input file, it's - all or nothing) may still be available on the specified output location. - - This call returns immediately and you can - use google.longrunning.Operation.name to poll the status of the call. - - Example: - >>> from google.cloud import translate_v3 - >>> - >>> client = translate_v3.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `source_language_code`: - >>> source_language_code = '' - >>> - >>> # TODO: Initialize `target_language_codes`: - >>> target_language_codes = [] - >>> - >>> # TODO: Initialize `input_configs`: - >>> input_configs = [] - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.batch_translate_text(parent, source_language_code, target_language_codes, input_configs, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. Location to make a call. Must refer to a caller's project. - - Format: ``projects/{project-number-or-id}/locations/{location-id}``. - - The ``global`` location is not supported for batch translation. - - Only AutoML Translation models or glossaries within the same region - (have the same location-id) can be used, otherwise an INVALID_ARGUMENT - (400) error is returned. - source_language_code (str): Required. Source language code. - target_language_codes (list[str]): Required. Specify up to 10 language codes here. - input_configs (list[Union[dict, ~google.cloud.translate_v3.types.InputConfig]]): Required. Input configurations. - The total number of files matched should be <= 1000. - The total content size should be <= 100M Unicode codepoints. - The files must use UTF-8 encoding. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3.types.InputConfig` - output_config (Union[dict, ~google.cloud.translate_v3.types.OutputConfig]): Required. Output configuration. - If 2 input configs match to the same file (that is, same input path), - we don't generate output for duplicate inputs. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3.types.OutputConfig` - models (dict[str -> str]): Optional. The models to use for translation. Map's key is target - language code. Map's value is model name. Value can be a built-in - general model, or an AutoML Translation model. - - The value format depends on model type: - - - AutoML Translation models: - ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` - - - General (built-in) models: - ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` - - If the map is empty or a specific model is not requested for a language - pair, then default google model (nmt) is used. - glossaries (dict[str -> Union[dict, ~google.cloud.translate_v3.types.TranslateTextGlossaryConfig]]): Optional. Glossaries to be applied for translation. - It's keyed by target language code. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3.types.TranslateTextGlossaryConfig` - labels (dict[str -> str]): Optional. The labels with user-defined metadata for the request. - - Label keys and values can be no longer than 63 characters - (Unicode codepoints), can only contain lowercase letters, numeric - characters, underscores and dashes. International characters are allowed. - Label values are optional. Label keys must start with a letter. - - See https://cloud.google.com/translate/docs/labels for more information. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_translate_text" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_translate_text" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_translate_text, - default_retry=self._method_configs["BatchTranslateText"].retry, - default_timeout=self._method_configs["BatchTranslateText"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.BatchTranslateTextRequest( - parent=parent, - source_language_code=source_language_code, - target_language_codes=target_language_codes, - input_configs=input_configs, - output_config=output_config, - models=models, - glossaries=glossaries, - labels=labels, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["batch_translate_text"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - translation_service_pb2.BatchTranslateResponse, - metadata_type=translation_service_pb2.BatchTranslateMetadata, - ) - - def create_glossary( - self, - parent, - glossary, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a glossary and returns the long-running operation. Returns - NOT_FOUND, if the project doesn't exist. - - Example: - >>> from google.cloud import translate_v3 - >>> - >>> client = translate_v3.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `glossary`: - >>> glossary = {} - >>> - >>> response = client.create_glossary(parent, glossary) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The project name. - glossary (Union[dict, ~google.cloud.translate_v3.types.Glossary]): Required. The glossary to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3.types.Glossary` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_glossary" not in self._inner_api_calls: - self._inner_api_calls[ - "create_glossary" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_glossary, - default_retry=self._method_configs["CreateGlossary"].retry, - default_timeout=self._method_configs["CreateGlossary"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.CreateGlossaryRequest( - parent=parent, glossary=glossary, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["create_glossary"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - translation_service_pb2.Glossary, - metadata_type=translation_service_pb2.CreateGlossaryMetadata, - ) - - def list_glossaries( - self, - parent, - page_size=None, - filter_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists glossaries in a project. Returns NOT_FOUND, if the project - doesn't exist. - - Example: - >>> from google.cloud import translate_v3 - >>> - >>> client = translate_v3.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_glossaries(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_glossaries(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The name of the project from which to list all of the glossaries. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - filter_ (str): Optional. Filter specifying constraints of a list operation. - Filtering is not supported yet, and the parameter currently has no effect. - If missing, no filtering is performed. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.translate_v3.types.Glossary` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_glossaries" not in self._inner_api_calls: - self._inner_api_calls[ - "list_glossaries" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_glossaries, - default_retry=self._method_configs["ListGlossaries"].retry, - default_timeout=self._method_configs["ListGlossaries"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.ListGlossariesRequest( - parent=parent, page_size=page_size, filter=filter_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_glossaries"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="glossaries", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_glossary( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist. - - Example: - >>> from google.cloud import translate_v3 - >>> - >>> client = translate_v3.TranslationServiceClient() - >>> - >>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]') - >>> - >>> response = client.get_glossary(name) - - Args: - name (str): Required. The name of the glossary to retrieve. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3.types.Glossary` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_glossary" not in self._inner_api_calls: - self._inner_api_calls[ - "get_glossary" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_glossary, - default_retry=self._method_configs["GetGlossary"].retry, - default_timeout=self._method_configs["GetGlossary"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.GetGlossaryRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_glossary"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_glossary( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a glossary, or cancels glossary construction if the glossary - isn't created yet. Returns NOT_FOUND, if the glossary doesn't exist. - - Example: - >>> from google.cloud import translate_v3 - >>> - >>> client = translate_v3.TranslationServiceClient() - >>> - >>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]') - >>> - >>> response = client.delete_glossary(name) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Required. The name of the glossary to delete. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_glossary" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_glossary" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_glossary, - default_retry=self._method_configs["DeleteGlossary"].retry, - default_timeout=self._method_configs["DeleteGlossary"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.DeleteGlossaryRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["delete_glossary"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - translation_service_pb2.DeleteGlossaryResponse, - metadata_type=translation_service_pb2.DeleteGlossaryMetadata, - ) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/translation_service_client_config.py b/packages/google-cloud-translate/google/cloud/translate_v3/gapic/translation_service_client_config.py deleted file mode 100644 index 2aa726c4eec6..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/translation_service_client_config.py +++ /dev/null @@ -1,82 +0,0 @@ -config = { - "interfaces": { - "google.cloud.translation.v3.TranslationService": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - }, - "methods": { - "TranslateText": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DetectLanguage": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetSupportedLanguages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "BatchTranslateText": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateGlossary": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "ListGlossaries": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetGlossary": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "DeleteGlossary": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/transports/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3/gapic/transports/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/transports/translation_service_grpc_transport.py b/packages/google-cloud-translate/google/cloud/translate_v3/gapic/transports/translation_service_grpc_transport.py deleted file mode 100644 index 9aad4a9a962f..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3/gapic/transports/translation_service_grpc_transport.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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 google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.translate_v3.proto import translation_service_pb2_grpc - - -class TranslationServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.translation.v3 TranslationService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-translation", - ) - - def __init__( - self, channel=None, credentials=None, address="translate.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "translation_service_stub": translation_service_pb2_grpc.TranslationServiceStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="translate.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def translate_text(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.translate_text`. - - Translates input text and returns translated text. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].TranslateText - - @property - def detect_language(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.detect_language`. - - Detects the language of text within a request. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].DetectLanguage - - @property - def get_supported_languages(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.get_supported_languages`. - - Returns a list of supported languages for translation. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].GetSupportedLanguages - - @property - def batch_translate_text(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.batch_translate_text`. - - Translates a large volume of text in asynchronous batch mode. - This function provides real-time output as the inputs are being processed. - If caller cancels a request, the partial results (for an input file, it's - all or nothing) may still be available on the specified output location. - - This call returns immediately and you can - use google.longrunning.Operation.name to poll the status of the call. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].BatchTranslateText - - @property - def create_glossary(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.create_glossary`. - - Creates a glossary and returns the long-running operation. Returns - NOT_FOUND, if the project doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].CreateGlossary - - @property - def list_glossaries(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.list_glossaries`. - - Lists glossaries in a project. Returns NOT_FOUND, if the project - doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].ListGlossaries - - @property - def get_glossary(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.get_glossary`. - - Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].GetGlossary - - @property - def delete_glossary(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.delete_glossary`. - - Deletes a glossary, or cancels glossary construction if the glossary - isn't created yet. Returns NOT_FOUND, if the glossary doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].DeleteGlossary diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/proto/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3/proto/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service.proto b/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service.proto deleted file mode 100644 index ad43831c29b0..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service.proto +++ /dev/null @@ -1,926 +0,0 @@ -// 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. -// - -syntax = "proto3"; - -package google.cloud.translation.v3; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/timestamp.proto"; - -option cc_enable_arenas = true; -option csharp_namespace = "Google.Cloud.Translate.V3"; -option go_package = "google.golang.org/genproto/googleapis/cloud/translate/v3;translate"; -option java_multiple_files = true; -option java_outer_classname = "TranslationServiceProto"; -option java_package = "com.google.cloud.translate.v3"; -option php_namespace = "Google\\Cloud\\Translate\\V3"; -option ruby_package = "Google::Cloud::Translate::V3"; - -// Proto file for the Cloud Translation API (v3 GA). - -// Provides natural language translation operations. -service TranslationService { - option (google.api.default_host) = "translate.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-translation"; - - // Translates input text and returns translated text. - rpc TranslateText(TranslateTextRequest) returns (TranslateTextResponse) { - option (google.api.http) = { - post: "/v3/{parent=projects/*/locations/*}:translateText" - body: "*" - additional_bindings { - post: "/v3/{parent=projects/*}:translateText" - body: "*" - } - }; - option (google.api.method_signature) = - "parent,target_language_code,contents"; - option (google.api.method_signature) = - "parent,model,mime_type,source_language_code,target_language_code,contents"; - } - - // Detects the language of text within a request. - rpc DetectLanguage(DetectLanguageRequest) returns (DetectLanguageResponse) { - option (google.api.http) = { - post: "/v3/{parent=projects/*/locations/*}:detectLanguage" - body: "*" - additional_bindings { - post: "/v3/{parent=projects/*}:detectLanguage" - body: "*" - } - }; - option (google.api.method_signature) = "parent,model,mime_type,content"; - } - - // Returns a list of supported languages for translation. - rpc GetSupportedLanguages(GetSupportedLanguagesRequest) - returns (SupportedLanguages) { - option (google.api.http) = { - get: "/v3/{parent=projects/*/locations/*}/supportedLanguages" - additional_bindings { get: "/v3/{parent=projects/*}/supportedLanguages" } - }; - option (google.api.method_signature) = "parent,model,display_language_code"; - } - - // Translates a large volume of text in asynchronous batch mode. - // This function provides real-time output as the inputs are being processed. - // If caller cancels a request, the partial results (for an input file, it's - // all or nothing) may still be available on the specified output location. - // - // This call returns immediately and you can - // use google.longrunning.Operation.name to poll the status of the call. - rpc BatchTranslateText(BatchTranslateTextRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v3/{parent=projects/*/locations/*}:batchTranslateText" - body: "*" - }; - option (google.longrunning.operation_info) = { - response_type: "BatchTranslateResponse" - metadata_type: "BatchTranslateMetadata" - }; - } - - // Creates a glossary and returns the long-running operation. Returns - // NOT_FOUND, if the project doesn't exist. - rpc CreateGlossary(CreateGlossaryRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v3/{parent=projects/*/locations/*}/glossaries" - body: "glossary" - }; - option (google.api.method_signature) = "parent,glossary"; - option (google.longrunning.operation_info) = { - response_type: "Glossary" - metadata_type: "CreateGlossaryMetadata" - }; - } - - // Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't - // exist. - rpc ListGlossaries(ListGlossariesRequest) returns (ListGlossariesResponse) { - option (google.api.http) = { - get: "/v3/{parent=projects/*/locations/*}/glossaries" - }; - option (google.api.method_signature) = "parent"; - } - - // Gets a glossary. Returns NOT_FOUND, if the glossary doesn't - // exist. - rpc GetGlossary(GetGlossaryRequest) returns (Glossary) { - option (google.api.http) = { - get: "/v3/{name=projects/*/locations/*/glossaries/*}" - }; - option (google.api.method_signature) = "name"; - } - - // Deletes a glossary, or cancels glossary construction - // if the glossary isn't created yet. - // Returns NOT_FOUND, if the glossary doesn't exist. - rpc DeleteGlossary(DeleteGlossaryRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - delete: "/v3/{name=projects/*/locations/*/glossaries/*}" - }; - option (google.api.method_signature) = "name"; - option (google.longrunning.operation_info) = { - response_type: "DeleteGlossaryResponse" - metadata_type: "DeleteGlossaryMetadata" - }; - } -} - -// Configures which glossary should be used for a specific target language, -// and defines options for applying that glossary. -message TranslateTextGlossaryConfig { - // Required. Specifies the glossary used for this translation. Use - // this format: projects/*/locations/*/glossaries/* - string glossary = 1 [(google.api.field_behavior) = REQUIRED]; - - // Optional. Indicates match is case-insensitive. - // Default value is false if missing. - bool ignore_case = 2 [(google.api.field_behavior) = OPTIONAL]; -} - -// The request message for synchronous translation. -message TranslateTextRequest { - // Required. The content of the input in string format. - // We recommend the total content be less than 30k codepoints. - // Use BatchTranslateText for larger text. - repeated string contents = 1 [(google.api.field_behavior) = REQUIRED]; - - // Optional. The format of the source text, for example, "text/html", - // "text/plain". If left blank, the MIME type defaults to "text/html". - string mime_type = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The BCP-47 language code of the input text if - // known, for example, "en-US" or "sr-Latn". Supported language codes are - // listed in Language Support. If the source language isn't specified, the API - // attempts to identify the source language automatically and returns the - // source language within the response. - string source_language_code = 4 [(google.api.field_behavior) = OPTIONAL]; - - // Required. The BCP-47 language code to use for translation of the input - // text, set to one of the language codes listed in Language Support. - string target_language_code = 5 [(google.api.field_behavior) = REQUIRED]; - - // Required. Project or location to make a call. Must refer to a caller's - // project. - // - // Format: `projects/{project-number-or-id}` or - // `projects/{project-number-or-id}/locations/{location-id}`. - // - // For global calls, use `projects/{project-number-or-id}/locations/global` or - // `projects/{project-number-or-id}`. - // - // Non-global location is required for requests using AutoML models or - // custom glossaries. - // - // Models and glossaries must be within the same region (have same - // location-id), otherwise an INVALID_ARGUMENT (400) error is returned. - string parent = 8 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Optional. The `model` type requested for this translation. - // - // The format depends on model type: - // - // - AutoML Translation models: - // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - // - // - General (built-in) models: - // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, - // `projects/{project-number-or-id}/locations/{location-id}/models/general/base` - // - // - // For global (non-regionalized) requests, use `location-id` `global`. - // For example, - // `projects/{project-number-or-id}/locations/global/models/general/nmt`. - // - // If missing, the system decides which google base model to use. - string model = 6 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Glossary to be applied. The glossary must be - // within the same region (have the same location-id) as the model, otherwise - // an INVALID_ARGUMENT (400) error is returned. - TranslateTextGlossaryConfig glossary_config = 7 - [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The labels with user-defined metadata for the request. - // - // Label keys and values can be no longer than 63 characters - // (Unicode codepoints), can only contain lowercase letters, numeric - // characters, underscores and dashes. International characters are allowed. - // Label values are optional. Label keys must start with a letter. - // - // See https://cloud.google.com/translate/docs/labels for more information. - map labels = 10 [(google.api.field_behavior) = OPTIONAL]; -} - -message TranslateTextResponse { - // Text translation responses with no glossary applied. - // This field has the same length as - // [`contents`][google.cloud.translation.v3.TranslateTextRequest.contents]. - repeated Translation translations = 1; - - // Text translation responses if a glossary is provided in the request. - // This can be the same as - // [`translations`][google.cloud.translation.v3.TranslateTextResponse.translations] - // if no terms apply. This field has the same length as - // [`contents`][google.cloud.translation.v3.TranslateTextRequest.contents]. - repeated Translation glossary_translations = 3; -} - -// A single translation response. -message Translation { - // Text translated into the target language. - string translated_text = 1; - - // Only present when `model` is present in the request. - // `model` here is normalized to have project number. - // - // For example: - // If the `model` requested in TranslationTextRequest is - // `projects/{project-id}/locations/{location-id}/models/general/nmt` then - // `model` here would be normalized to - // `projects/{project-number}/locations/{location-id}/models/general/nmt`. - string model = 2; - - // The BCP-47 language code of source text in the initial request, detected - // automatically, if no source language was passed within the initial - // request. If the source language was passed, auto-detection of the language - // does not occur and this field is empty. - string detected_language_code = 4; - - // The `glossary_config` used for this translation. - TranslateTextGlossaryConfig glossary_config = 3; -} - -// The request message for language detection. -message DetectLanguageRequest { - // Required. Project or location to make a call. Must refer to a caller's - // project. - // - // Format: `projects/{project-number-or-id}/locations/{location-id}` or - // `projects/{project-number-or-id}`. - // - // For global calls, use `projects/{project-number-or-id}/locations/global` or - // `projects/{project-number-or-id}`. - // - // Only models within the same region (has same location-id) can be used. - // Otherwise an INVALID_ARGUMENT (400) error is returned. - string parent = 5 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Optional. The language detection model to be used. - // - // Format: - // `projects/{project-number-or-id}/locations/{location-id}/models/language-detection/{model-id}` - // - // Only one language detection model is currently supported: - // `projects/{project-number-or-id}/locations/{location-id}/models/language-detection/default`. - // - // If not specified, the default model is used. - string model = 4 [(google.api.field_behavior) = OPTIONAL]; - - // Required. The source of the document from which to detect the language. - oneof source { - // The content of the input stored as a string. - string content = 1; - } - - // Optional. The format of the source text, for example, "text/html", - // "text/plain". If left blank, the MIME type defaults to "text/html". - string mime_type = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The labels with user-defined metadata for the request. - // - // Label keys and values can be no longer than 63 characters - // (Unicode codepoints), can only contain lowercase letters, numeric - // characters, underscores and dashes. International characters are allowed. - // Label values are optional. Label keys must start with a letter. - // - // See https://cloud.google.com/translate/docs/labels for more information. - map labels = 6 [(google.api.field_behavior) = OPTIONAL]; -} - -// The response message for language detection. -message DetectedLanguage { - // The BCP-47 language code of source content in the request, detected - // automatically. - string language_code = 1; - - // The confidence of the detection result for this language. - float confidence = 2; -} - -// The response message for language detection. -message DetectLanguageResponse { - // A list of detected languages sorted by detection confidence in descending - // order. The most probable language first. - repeated DetectedLanguage languages = 1; -} - -// The request message for discovering supported languages. -message GetSupportedLanguagesRequest { - // Required. Project or location to make a call. Must refer to a caller's - // project. - // - // Format: `projects/{project-number-or-id}` or - // `projects/{project-number-or-id}/locations/{location-id}`. - // - // For global calls, use `projects/{project-number-or-id}/locations/global` or - // `projects/{project-number-or-id}`. - // - // Non-global location is required for AutoML models. - // - // Only models within the same region (have same location-id) can be used, - // otherwise an INVALID_ARGUMENT (400) error is returned. - string parent = 3 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Optional. The language to use to return localized, human readable names - // of supported languages. If missing, then display names are not returned - // in a response. - string display_language_code = 1 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Get supported languages of this model. - // - // The format depends on model type: - // - // - AutoML Translation models: - // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - // - // - General (built-in) models: - // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, - // `projects/{project-number-or-id}/locations/{location-id}/models/general/base` - // - // - // Returns languages supported by the specified model. - // If missing, we get supported languages of Google general base (PBMT) model. - string model = 2 [(google.api.field_behavior) = OPTIONAL]; -} - -// The response message for discovering supported languages. -message SupportedLanguages { - // A list of supported language responses. This list contains an entry - // for each language the Translation API supports. - repeated SupportedLanguage languages = 1; -} - -// A single supported language response corresponds to information related -// to one supported language. -message SupportedLanguage { - // Supported language code, generally consisting of its ISO 639-1 - // identifier, for example, 'en', 'ja'. In certain cases, BCP-47 codes - // including language and region identifiers are returned (for example, - // 'zh-TW' and 'zh-CN') - string language_code = 1; - - // Human readable name of the language localized in the display language - // specified in the request. - string display_name = 2; - - // Can be used as source language. - bool support_source = 3; - - // Can be used as target language. - bool support_target = 4; -} - -// The Google Cloud Storage location for the input content. -message GcsSource { - // Required. Source data URI. For example, `gs://my_bucket/my_object`. - string input_uri = 1; -} - -// Input configuration for BatchTranslateText request. -message InputConfig { - // Optional. Can be "text/plain" or "text/html". - // For `.tsv`, "text/html" is used if mime_type is missing. - // For `.html`, this field must be "text/html" or empty. - // For `.txt`, this field must be "text/plain" or empty. - string mime_type = 1 [(google.api.field_behavior) = OPTIONAL]; - - // Required. Specify the input. - oneof source { - // Required. Google Cloud Storage location for the source input. - // This can be a single file (for example, - // `gs://translation-test/input.tsv`) or a wildcard (for example, - // `gs://translation-test/*`). If a file extension is `.tsv`, it can - // contain either one or two columns. The first column (optional) is the id - // of the text request. If the first column is missing, we use the row - // number (0-based) from the input file as the ID in the output file. The - // second column is the actual text to be - // translated. We recommend each row be <= 10K Unicode codepoints, - // otherwise an error might be returned. - // Note that the input tsv must be RFC 4180 compliant. - // - // You could use https://github.com/Clever/csvlint to check potential - // formatting errors in your tsv file. - // csvlint --delimiter='\t' your_input_file.tsv - // - // The other supported file extensions are `.txt` or `.html`, which is - // treated as a single large chunk of text. - GcsSource gcs_source = 2; - } -} - -// The Google Cloud Storage location for the output content. -message GcsDestination { - // Required. There must be no files under 'output_uri_prefix'. - // 'output_uri_prefix' must end with "/" and start with "gs://", otherwise an - // INVALID_ARGUMENT (400) error is returned. - string output_uri_prefix = 1; -} - -// Output configuration for BatchTranslateText request. -message OutputConfig { - // Required. The destination of output. - oneof destination { - // Google Cloud Storage destination for output content. - // For every single input file (for example, gs://a/b/c.[extension]), we - // generate at most 2 * n output files. (n is the # of target_language_codes - // in the BatchTranslateTextRequest). - // - // Output files (tsv) generated are compliant with RFC 4180 except that - // record delimiters are '\n' instead of '\r\n'. We don't provide any way to - // change record delimiters. - // - // While the input files are being processed, we write/update an index file - // 'index.csv' under 'output_uri_prefix' (for example, - // gs://translation-test/index.csv) The index file is generated/updated as - // new files are being translated. The format is: - // - // input_file,target_language_code,translations_file,errors_file, - // glossary_translations_file,glossary_errors_file - // - // input_file is one file we matched using gcs_source.input_uri. - // target_language_code is provided in the request. - // translations_file contains the translations. (details provided below) - // errors_file contains the errors during processing of the file. (details - // below). Both translations_file and errors_file could be empty - // strings if we have no content to output. - // glossary_translations_file and glossary_errors_file are always empty - // strings if the input_file is tsv. They could also be empty if we have no - // content to output. - // - // Once a row is present in index.csv, the input/output matching never - // changes. Callers should also expect all the content in input_file are - // processed and ready to be consumed (that is, no partial output file is - // written). - // - // The format of translations_file (for target language code 'trg') is: - // gs://translation_test/a_b_c_'trg'_translations.[extension] - // - // If the input file extension is tsv, the output has the following - // columns: - // Column 1: ID of the request provided in the input, if it's not - // provided in the input, then the input row number is used (0-based). - // Column 2: source sentence. - // Column 3: translation without applying a glossary. Empty string if there - // is an error. - // Column 4 (only present if a glossary is provided in the request): - // translation after applying the glossary. Empty string if there is an - // error applying the glossary. Could be same string as column 3 if there is - // no glossary applied. - // - // If input file extension is a txt or html, the translation is directly - // written to the output file. If glossary is requested, a separate - // glossary_translations_file has format of - // gs://translation_test/a_b_c_'trg'_glossary_translations.[extension] - // - // The format of errors file (for target language code 'trg') is: - // gs://translation_test/a_b_c_'trg'_errors.[extension] - // - // If the input file extension is tsv, errors_file contains the following: - // Column 1: ID of the request provided in the input, if it's not - // provided in the input, then the input row number is used (0-based). - // Column 2: source sentence. - // Column 3: Error detail for the translation. Could be empty. - // Column 4 (only present if a glossary is provided in the request): - // Error when applying the glossary. - // - // If the input file extension is txt or html, glossary_error_file will be - // generated that contains error details. glossary_error_file has format of - // gs://translation_test/a_b_c_'trg'_glossary_errors.[extension] - GcsDestination gcs_destination = 1; - } -} - -// The batch translation request. -message BatchTranslateTextRequest { - // Required. Location to make a call. Must refer to a caller's project. - // - // Format: `projects/{project-number-or-id}/locations/{location-id}`. - // - // The `global` location is not supported for batch translation. - // - // Only AutoML Translation models or glossaries within the same region (have - // the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) - // error is returned. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. Source language code. - string source_language_code = 2 [(google.api.field_behavior) = REQUIRED]; - - // Required. Specify up to 10 language codes here. - repeated string target_language_codes = 3 - [(google.api.field_behavior) = REQUIRED]; - - // Optional. The models to use for translation. Map's key is target language - // code. Map's value is model name. Value can be a built-in general model, - // or an AutoML Translation model. - // - // The value format depends on model type: - // - // - AutoML Translation models: - // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - // - // - General (built-in) models: - // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, - // `projects/{project-number-or-id}/locations/{location-id}/models/general/base` - // - // - // If the map is empty or a specific model is - // not requested for a language pair, then default google model (nmt) is used. - map models = 4 [(google.api.field_behavior) = OPTIONAL]; - - // Required. Input configurations. - // The total number of files matched should be <= 1000. - // The total content size should be <= 100M Unicode codepoints. - // The files must use UTF-8 encoding. - repeated InputConfig input_configs = 5 - [(google.api.field_behavior) = REQUIRED]; - - // Required. Output configuration. - // If 2 input configs match to the same file (that is, same input path), - // we don't generate output for duplicate inputs. - OutputConfig output_config = 6 [(google.api.field_behavior) = REQUIRED]; - - // Optional. Glossaries to be applied for translation. - // It's keyed by target language code. - map glossaries = 7 - [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The labels with user-defined metadata for the request. - // - // Label keys and values can be no longer than 63 characters - // (Unicode codepoints), can only contain lowercase letters, numeric - // characters, underscores and dashes. International characters are allowed. - // Label values are optional. Label keys must start with a letter. - // - // See https://cloud.google.com/translate/docs/labels for more information. - map labels = 9 [(google.api.field_behavior) = OPTIONAL]; -} - -// State metadata for the batch translation operation. -message BatchTranslateMetadata { - // State of the job. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is being processed. - RUNNING = 1; - - // The batch is processed, and at least one item was successfully - // processed. - SUCCEEDED = 2; - - // The batch is done and no item was successfully processed. - FAILED = 3; - - // Request is in the process of being canceled after caller invoked - // longrunning.Operations.CancelOperation on the request id. - CANCELLING = 4; - - // The batch is done after the user has called the - // longrunning.Operations.CancelOperation. Any records processed before the - // cancel command are output as specified in the request. - CANCELLED = 5; - } - - // The state of the operation. - State state = 1; - - // Number of successfully translated characters so far (Unicode codepoints). - int64 translated_characters = 2; - - // Number of characters that have failed to process so far (Unicode - // codepoints). - int64 failed_characters = 3; - - // Total number of characters (Unicode codepoints). - // This is the total number of codepoints from input files times the number of - // target languages and appears here shortly after the call is submitted. - int64 total_characters = 4; - - // Time when the operation was submitted. - google.protobuf.Timestamp submit_time = 5; -} - -// Stored in the -// [google.longrunning.Operation.response][google.longrunning.Operation.response] -// field returned by BatchTranslateText if at least one sentence is translated -// successfully. -message BatchTranslateResponse { - // Total number of characters (Unicode codepoints). - int64 total_characters = 1; - - // Number of successfully translated characters (Unicode codepoints). - int64 translated_characters = 2; - - // Number of characters that have failed to process (Unicode codepoints). - int64 failed_characters = 3; - - // Time when the operation was submitted. - google.protobuf.Timestamp submit_time = 4; - - // The time when the operation is finished and - // [google.longrunning.Operation.done][google.longrunning.Operation.done] is - // set to true. - google.protobuf.Timestamp end_time = 5; -} - -// Input configuration for glossaries. -message GlossaryInputConfig { - // Required. Specify the input. - oneof source { - // Required. Google Cloud Storage location of glossary data. - // File format is determined based on the filename extension. API returns - // [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file - // formats. Wildcards are not allowed. This must be a single file in one of - // the following formats: - // - // For unidirectional glossaries: - // - // - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated. - // The first column is source text. The second column is target text. - // The file must not contain headers. That is, the first row is data, not - // column names. - // - // - TMX (`.tmx`): TMX file with parallel data defining source/target term - // pairs. - // - // For equivalent term sets glossaries: - // - // - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms - // in multiple languages. The format is defined for Google Translation - // Toolkit and documented in [Use a - // glossary](https://support.google.com/translatortoolkit/answer/6306379?hl=en). - GcsSource gcs_source = 1; - } -} - -// Represents a glossary built from user provided data. -message Glossary { - option (google.api.resource) = { - type: "translate.googleapis.com/Glossary" - pattern: "projects/{project}/locations/{location}/glossaries/{glossary}" - }; - - // Used with unidirectional glossaries. - message LanguageCodePair { - // Required. The BCP-47 language code of the input text, for example, - // "en-US". Expected to be an exact match for GlossaryTerm.language_code. - string source_language_code = 1; - - // Required. The BCP-47 language code for translation output, for example, - // "zh-CN". Expected to be an exact match for GlossaryTerm.language_code. - string target_language_code = 2; - } - - // Used with equivalent term set glossaries. - message LanguageCodesSet { - // The BCP-47 language code(s) for terms defined in the glossary. - // All entries are unique. The list contains at least two entries. - // Expected to be an exact match for GlossaryTerm.language_code. - repeated string language_codes = 1; - } - - // Required. The resource name of the glossary. Glossary names have the form - // `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`. - string name = 1; - - // Languages supported by the glossary. - oneof languages { - // Used with unidirectional glossaries. - LanguageCodePair language_pair = 3; - - // Used with equivalent term set glossaries. - LanguageCodesSet language_codes_set = 4; - } - - // Required. Provides examples to build the glossary from. - // Total glossary must not exceed 10M Unicode codepoints. - GlossaryInputConfig input_config = 5; - - // Output only. The number of entries defined in the glossary. - int32 entry_count = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; - - // Output only. When CreateGlossary was called. - google.protobuf.Timestamp submit_time = 7 - [(google.api.field_behavior) = OUTPUT_ONLY]; - - // Output only. When the glossary creation was finished. - google.protobuf.Timestamp end_time = 8 - [(google.api.field_behavior) = OUTPUT_ONLY]; -} - -// Request message for CreateGlossary. -message CreateGlossaryRequest { - // Required. The project name. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The glossary to create. - Glossary glossary = 2 [(google.api.field_behavior) = REQUIRED]; -} - -// Request message for GetGlossary. -message GetGlossaryRequest { - // Required. The name of the glossary to retrieve. - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "translate.googleapis.com/Glossary" - } - ]; -} - -// Request message for DeleteGlossary. -message DeleteGlossaryRequest { - // Required. The name of the glossary to delete. - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "translate.googleapis.com/Glossary" - } - ]; -} - -// Request message for ListGlossaries. -message ListGlossariesRequest { - // Required. The name of the project from which to list all of the glossaries. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Optional. Requested page size. The server may return fewer glossaries than - // requested. If unspecified, the server picks an appropriate default. - int32 page_size = 2 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. A token identifying a page of results the server should return. - // Typically, this is the value of [ListGlossariesResponse.next_page_token] - // returned from the previous call to `ListGlossaries` method. - // The first page is returned if `page_token`is empty or missing. - string page_token = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Filter specifying constraints of a list operation. - // Filtering is not supported yet, and the parameter currently has no effect. - // If missing, no filtering is performed. - string filter = 4 [(google.api.field_behavior) = OPTIONAL]; -} - -// Response message for ListGlossaries. -message ListGlossariesResponse { - // The list of glossaries for a project. - repeated Glossary glossaries = 1; - - // A token to retrieve a page of results. Pass this value in the - // [ListGlossariesRequest.page_token] field in the subsequent call to - // `ListGlossaries` method to retrieve the next page of results. - string next_page_token = 2; -} - -// Stored in the -// [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata] -// field returned by CreateGlossary. -message CreateGlossaryMetadata { - // Enumerates the possible states that the creation request can be in. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is being processed. - RUNNING = 1; - - // The glossary was successfully created. - SUCCEEDED = 2; - - // Failed to create the glossary. - FAILED = 3; - - // Request is in the process of being canceled after caller invoked - // longrunning.Operations.CancelOperation on the request id. - CANCELLING = 4; - - // The glossary creation request was successfully canceled. - CANCELLED = 5; - } - - // The name of the glossary that is being created. - string name = 1; - - // The current state of the glossary creation operation. - State state = 2; - - // The time when the operation was submitted to the server. - google.protobuf.Timestamp submit_time = 3; -} - -// Stored in the -// [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata] -// field returned by DeleteGlossary. -message DeleteGlossaryMetadata { - // Enumerates the possible states that the creation request can be in. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is being processed. - RUNNING = 1; - - // The glossary was successfully deleted. - SUCCEEDED = 2; - - // Failed to delete the glossary. - FAILED = 3; - - // Request is in the process of being canceled after caller invoked - // longrunning.Operations.CancelOperation on the request id. - CANCELLING = 4; - - // The glossary deletion request was successfully canceled. - CANCELLED = 5; - } - - // The name of the glossary that is being deleted. - string name = 1; - - // The current state of the glossary deletion operation. - State state = 2; - - // The time when the operation was submitted to the server. - google.protobuf.Timestamp submit_time = 3; -} - -// Stored in the -// [google.longrunning.Operation.response][google.longrunning.Operation.response] -// field returned by DeleteGlossary. -message DeleteGlossaryResponse { - // The name of the deleted glossary. - string name = 1; - - // The time when the operation was submitted to the server. - google.protobuf.Timestamp submit_time = 2; - - // The time when the glossary deletion is finished and - // [google.longrunning.Operation.done][google.longrunning.Operation.done] is - // set to true. - google.protobuf.Timestamp end_time = 3; -} diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service_pb2.py b/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service_pb2.py deleted file mode 100644 index 0f45c91a6d89..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service_pb2.py +++ /dev/null @@ -1,4050 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/translate_v3/proto/translation_service.proto - -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/translate_v3/proto/translation_service.proto", - package="google.cloud.translation.v3", - syntax="proto3", - serialized_options=b"\n\035com.google.cloud.translate.v3B\027TranslationServiceProtoP\001ZBgoogle.golang.org/genproto/googleapis/cloud/translate/v3;translate\370\001\001\252\002\031Google.Cloud.Translate.V3\312\002\031Google\\Cloud\\Translate\\V3\352\002\034Google::Cloud::Translate::V3", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/translate_v3/proto/translation_service.proto\x12\x1bgoogle.cloud.translation.v3\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a#google/longrunning/operations.proto\x1a\x1fgoogle/protobuf/timestamp.proto"N\n\x1bTranslateTextGlossaryConfig\x12\x15\n\x08glossary\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x18\n\x0bignore_case\x18\x02 \x01(\x08\x42\x03\xe0\x41\x01"\xb5\x03\n\x14TranslateTextRequest\x12\x15\n\x08\x63ontents\x18\x01 \x03(\tB\x03\xe0\x41\x02\x12\x16\n\tmime_type\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12!\n\x14source_language_code\x18\x04 \x01(\tB\x03\xe0\x41\x01\x12!\n\x14target_language_code\x18\x05 \x01(\tB\x03\xe0\x41\x02\x12\x39\n\x06parent\x18\x08 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x12\n\x05model\x18\x06 \x01(\tB\x03\xe0\x41\x01\x12V\n\x0fglossary_config\x18\x07 \x01(\x0b\x32\x38.google.cloud.translation.v3.TranslateTextGlossaryConfigB\x03\xe0\x41\x01\x12R\n\x06labels\x18\n \x03(\x0b\x32=.google.cloud.translation.v3.TranslateTextRequest.LabelsEntryB\x03\xe0\x41\x01\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\xa0\x01\n\x15TranslateTextResponse\x12>\n\x0ctranslations\x18\x01 \x03(\x0b\x32(.google.cloud.translation.v3.Translation\x12G\n\x15glossary_translations\x18\x03 \x03(\x0b\x32(.google.cloud.translation.v3.Translation"\xa8\x01\n\x0bTranslation\x12\x17\n\x0ftranslated_text\x18\x01 \x01(\t\x12\r\n\x05model\x18\x02 \x01(\t\x12\x1e\n\x16\x64\x65tected_language_code\x18\x04 \x01(\t\x12Q\n\x0fglossary_config\x18\x03 \x01(\x0b\x32\x38.google.cloud.translation.v3.TranslateTextGlossaryConfig"\x9f\x02\n\x15\x44\x65tectLanguageRequest\x12\x39\n\x06parent\x18\x05 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x12\n\x05model\x18\x04 \x01(\tB\x03\xe0\x41\x01\x12\x11\n\x07\x63ontent\x18\x01 \x01(\tH\x00\x12\x16\n\tmime_type\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12S\n\x06labels\x18\x06 \x03(\x0b\x32>.google.cloud.translation.v3.DetectLanguageRequest.LabelsEntryB\x03\xe0\x41\x01\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x08\n\x06source"=\n\x10\x44\x65tectedLanguage\x12\x15\n\rlanguage_code\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02"Z\n\x16\x44\x65tectLanguageResponse\x12@\n\tlanguages\x18\x01 \x03(\x0b\x32-.google.cloud.translation.v3.DetectedLanguage"\x91\x01\n\x1cGetSupportedLanguagesRequest\x12\x39\n\x06parent\x18\x03 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12"\n\x15\x64isplay_language_code\x18\x01 \x01(\tB\x03\xe0\x41\x01\x12\x12\n\x05model\x18\x02 \x01(\tB\x03\xe0\x41\x01"W\n\x12SupportedLanguages\x12\x41\n\tlanguages\x18\x01 \x03(\x0b\x32..google.cloud.translation.v3.SupportedLanguage"p\n\x11SupportedLanguage\x12\x15\n\rlanguage_code\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x16\n\x0esupport_source\x18\x03 \x01(\x08\x12\x16\n\x0esupport_target\x18\x04 \x01(\x08"\x1e\n\tGcsSource\x12\x11\n\tinput_uri\x18\x01 \x01(\t"m\n\x0bInputConfig\x12\x16\n\tmime_type\x18\x01 \x01(\tB\x03\xe0\x41\x01\x12<\n\ngcs_source\x18\x02 \x01(\x0b\x32&.google.cloud.translation.v3.GcsSourceH\x00\x42\x08\n\x06source"+\n\x0eGcsDestination\x12\x19\n\x11output_uri_prefix\x18\x01 \x01(\t"e\n\x0cOutputConfig\x12\x46\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32+.google.cloud.translation.v3.GcsDestinationH\x00\x42\r\n\x0b\x64\x65stination"\x88\x06\n\x19\x42\x61tchTranslateTextRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12!\n\x14source_language_code\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12"\n\x15target_language_codes\x18\x03 \x03(\tB\x03\xe0\x41\x02\x12W\n\x06models\x18\x04 \x03(\x0b\x32\x42.google.cloud.translation.v3.BatchTranslateTextRequest.ModelsEntryB\x03\xe0\x41\x01\x12\x44\n\rinput_configs\x18\x05 \x03(\x0b\x32(.google.cloud.translation.v3.InputConfigB\x03\xe0\x41\x02\x12\x45\n\routput_config\x18\x06 \x01(\x0b\x32).google.cloud.translation.v3.OutputConfigB\x03\xe0\x41\x02\x12_\n\nglossaries\x18\x07 \x03(\x0b\x32\x46.google.cloud.translation.v3.BatchTranslateTextRequest.GlossariesEntryB\x03\xe0\x41\x01\x12W\n\x06labels\x18\t \x03(\x0b\x32\x42.google.cloud.translation.v3.BatchTranslateTextRequest.LabelsEntryB\x03\xe0\x41\x01\x1a-\n\x0bModelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1ak\n\x0fGlossariesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12G\n\x05value\x18\x02 \x01(\x0b\x32\x38.google.cloud.translation.v3.TranslateTextGlossaryConfig:\x02\x38\x01\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\xce\x02\n\x16\x42\x61tchTranslateMetadata\x12H\n\x05state\x18\x01 \x01(\x0e\x32\x39.google.cloud.translation.v3.BatchTranslateMetadata.State\x12\x1d\n\x15translated_characters\x18\x02 \x01(\x03\x12\x19\n\x11\x66\x61iled_characters\x18\x03 \x01(\x03\x12\x18\n\x10total_characters\x18\x04 \x01(\x03\x12/\n\x0bsubmit_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"e\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07RUNNING\x10\x01\x12\r\n\tSUCCEEDED\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\x0e\n\nCANCELLING\x10\x04\x12\r\n\tCANCELLED\x10\x05"\xcb\x01\n\x16\x42\x61tchTranslateResponse\x12\x18\n\x10total_characters\x18\x01 \x01(\x03\x12\x1d\n\x15translated_characters\x18\x02 \x01(\x03\x12\x19\n\x11\x66\x61iled_characters\x18\x03 \x01(\x03\x12/\n\x0bsubmit_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"]\n\x13GlossaryInputConfig\x12<\n\ngcs_source\x18\x01 \x01(\x0b\x32&.google.cloud.translation.v3.GcsSourceH\x00\x42\x08\n\x06source"\xfa\x04\n\x08Glossary\x12\x0c\n\x04name\x18\x01 \x01(\t\x12O\n\rlanguage_pair\x18\x03 \x01(\x0b\x32\x36.google.cloud.translation.v3.Glossary.LanguageCodePairH\x00\x12T\n\x12language_codes_set\x18\x04 \x01(\x0b\x32\x36.google.cloud.translation.v3.Glossary.LanguageCodesSetH\x00\x12\x46\n\x0cinput_config\x18\x05 \x01(\x0b\x32\x30.google.cloud.translation.v3.GlossaryInputConfig\x12\x18\n\x0b\x65ntry_count\x18\x06 \x01(\x05\x42\x03\xe0\x41\x03\x12\x34\n\x0bsubmit_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12\x31\n\x08\x65nd_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x1aN\n\x10LanguageCodePair\x12\x1c\n\x14source_language_code\x18\x01 \x01(\t\x12\x1c\n\x14target_language_code\x18\x02 \x01(\t\x1a*\n\x10LanguageCodesSet\x12\x16\n\x0elanguage_codes\x18\x01 \x03(\t:e\xea\x41\x62\n!translate.googleapis.com/Glossary\x12=projects/{project}/locations/{location}/glossaries/{glossary}B\x0b\n\tlanguages"\x90\x01\n\x15\x43reateGlossaryRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12<\n\x08glossary\x18\x02 \x01(\x0b\x32%.google.cloud.translation.v3.GlossaryB\x03\xe0\x41\x02"M\n\x12GetGlossaryRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!translate.googleapis.com/Glossary"P\n\x15\x44\x65leteGlossaryRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!translate.googleapis.com/Glossary"\x98\x01\n\x15ListGlossariesRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12\x13\n\x06\x66ilter\x18\x04 \x01(\tB\x03\xe0\x41\x01"l\n\x16ListGlossariesResponse\x12\x39\n\nglossaries\x18\x01 \x03(\x0b\x32%.google.cloud.translation.v3.Glossary\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\x88\x02\n\x16\x43reateGlossaryMetadata\x12\x0c\n\x04name\x18\x01 \x01(\t\x12H\n\x05state\x18\x02 \x01(\x0e\x32\x39.google.cloud.translation.v3.CreateGlossaryMetadata.State\x12/\n\x0bsubmit_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"e\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07RUNNING\x10\x01\x12\r\n\tSUCCEEDED\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\x0e\n\nCANCELLING\x10\x04\x12\r\n\tCANCELLED\x10\x05"\x88\x02\n\x16\x44\x65leteGlossaryMetadata\x12\x0c\n\x04name\x18\x01 \x01(\t\x12H\n\x05state\x18\x02 \x01(\x0e\x32\x39.google.cloud.translation.v3.DeleteGlossaryMetadata.State\x12/\n\x0bsubmit_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"e\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07RUNNING\x10\x01\x12\r\n\tSUCCEEDED\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\x0e\n\nCANCELLING\x10\x04\x12\r\n\tCANCELLED\x10\x05"\x85\x01\n\x16\x44\x65leteGlossaryResponse\x12\x0c\n\x04name\x18\x01 \x01(\t\x12/\n\x0bsubmit_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\x8e\x10\n\x12TranslationService\x12\xd4\x02\n\rTranslateText\x12\x31.google.cloud.translation.v3.TranslateTextRequest\x1a\x32.google.cloud.translation.v3.TranslateTextResponse"\xdb\x01\x82\xd3\xe4\x93\x02\x62"1/v3/{parent=projects/*/locations/*}:translateText:\x01*Z*"%/v3/{parent=projects/*}:translateText:\x01*\xda\x41$parent,target_language_code,contents\xda\x41Iparent,model,mime_type,source_language_code,target_language_code,contents\x12\x87\x02\n\x0e\x44\x65tectLanguage\x12\x32.google.cloud.translation.v3.DetectLanguageRequest\x1a\x33.google.cloud.translation.v3.DetectLanguageResponse"\x8b\x01\x82\xd3\xe4\x93\x02\x64"2/v3/{parent=projects/*/locations/*}:detectLanguage:\x01*Z+"&/v3/{parent=projects/*}:detectLanguage:\x01*\xda\x41\x1eparent,model,mime_type,content\x12\x97\x02\n\x15GetSupportedLanguages\x12\x39.google.cloud.translation.v3.GetSupportedLanguagesRequest\x1a/.google.cloud.translation.v3.SupportedLanguages"\x91\x01\x82\xd3\xe4\x93\x02\x66\x12\x36/v3/{parent=projects/*/locations/*}/supportedLanguagesZ,\x12*/v3/{parent=projects/*}/supportedLanguages\xda\x41"parent,model,display_language_code\x12\xe1\x01\n\x12\x42\x61tchTranslateText\x12\x36.google.cloud.translation.v3.BatchTranslateTextRequest\x1a\x1d.google.longrunning.Operation"t\x82\xd3\xe4\x93\x02;"6/v3/{parent=projects/*/locations/*}:batchTranslateText:\x01*\xca\x41\x30\n\x16\x42\x61tchTranslateResponse\x12\x16\x42\x61tchTranslateMetadata\x12\xdc\x01\n\x0e\x43reateGlossary\x12\x32.google.cloud.translation.v3.CreateGlossaryRequest\x1a\x1d.google.longrunning.Operation"w\x82\xd3\xe4\x93\x02:"./v3/{parent=projects/*/locations/*}/glossaries:\x08glossary\xda\x41\x0fparent,glossary\xca\x41"\n\x08Glossary\x12\x16\x43reateGlossaryMetadata\x12\xba\x01\n\x0eListGlossaries\x12\x32.google.cloud.translation.v3.ListGlossariesRequest\x1a\x33.google.cloud.translation.v3.ListGlossariesResponse"?\x82\xd3\xe4\x93\x02\x30\x12./v3/{parent=projects/*/locations/*}/glossaries\xda\x41\x06parent\x12\xa4\x01\n\x0bGetGlossary\x12/.google.cloud.translation.v3.GetGlossaryRequest\x1a%.google.cloud.translation.v3.Glossary"=\x82\xd3\xe4\x93\x02\x30\x12./v3/{name=projects/*/locations/*/glossaries/*}\xda\x41\x04name\x12\xd5\x01\n\x0e\x44\x65leteGlossary\x12\x32.google.cloud.translation.v3.DeleteGlossaryRequest\x1a\x1d.google.longrunning.Operation"p\x82\xd3\xe4\x93\x02\x30*./v3/{name=projects/*/locations/*/glossaries/*}\xda\x41\x04name\xca\x41\x30\n\x16\x44\x65leteGlossaryResponse\x12\x16\x44\x65leteGlossaryMetadata\x1a~\xca\x41\x18translate.googleapis.com\xd2\x41`https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-translationB\xd8\x01\n\x1d\x63om.google.cloud.translate.v3B\x17TranslationServiceProtoP\x01ZBgoogle.golang.org/genproto/googleapis/cloud/translate/v3;translate\xf8\x01\x01\xaa\x02\x19Google.Cloud.Translate.V3\xca\x02\x19Google\\Cloud\\Translate\\V3\xea\x02\x1cGoogle::Cloud::Translate::V3b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_BATCHTRANSLATEMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.translation.v3.BatchTranslateMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCEEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLING", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3229, - serialized_end=3330, -) -_sym_db.RegisterEnumDescriptor(_BATCHTRANSLATEMETADATA_STATE) - -_CREATEGLOSSARYMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.translation.v3.CreateGlossaryMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCEEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLING", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3229, - serialized_end=3330, -) -_sym_db.RegisterEnumDescriptor(_CREATEGLOSSARYMETADATA_STATE) - -_DELETEGLOSSARYMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.translation.v3.DeleteGlossaryMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCEEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLING", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3229, - serialized_end=3330, -) -_sym_db.RegisterEnumDescriptor(_DELETEGLOSSARYMETADATA_STATE) - - -_TRANSLATETEXTGLOSSARYCONFIG = _descriptor.Descriptor( - name="TranslateTextGlossaryConfig", - full_name="google.cloud.translation.v3.TranslateTextGlossaryConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="glossary", - full_name="google.cloud.translation.v3.TranslateTextGlossaryConfig.glossary", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ignore_case", - full_name="google.cloud.translation.v3.TranslateTextGlossaryConfig.ignore_case", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=275, - serialized_end=353, -) - - -_TRANSLATETEXTREQUEST_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.translation.v3.TranslateTextRequest.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3.TranslateTextRequest.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3.TranslateTextRequest.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=748, - serialized_end=793, -) - -_TRANSLATETEXTREQUEST = _descriptor.Descriptor( - name="TranslateTextRequest", - full_name="google.cloud.translation.v3.TranslateTextRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="contents", - full_name="google.cloud.translation.v3.TranslateTextRequest.contents", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.translation.v3.TranslateTextRequest.mime_type", - index=1, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_language_code", - full_name="google.cloud.translation.v3.TranslateTextRequest.source_language_code", - index=2, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_language_code", - full_name="google.cloud.translation.v3.TranslateTextRequest.target_language_code", - index=3, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3.TranslateTextRequest.parent", - index=4, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.translation.v3.TranslateTextRequest.model", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossary_config", - full_name="google.cloud.translation.v3.TranslateTextRequest.glossary_config", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.translation.v3.TranslateTextRequest.labels", - index=7, - number=10, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_TRANSLATETEXTREQUEST_LABELSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=356, - serialized_end=793, -) - - -_TRANSLATETEXTRESPONSE = _descriptor.Descriptor( - name="TranslateTextResponse", - full_name="google.cloud.translation.v3.TranslateTextResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="translations", - full_name="google.cloud.translation.v3.TranslateTextResponse.translations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossary_translations", - full_name="google.cloud.translation.v3.TranslateTextResponse.glossary_translations", - index=1, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=796, - serialized_end=956, -) - - -_TRANSLATION = _descriptor.Descriptor( - name="Translation", - full_name="google.cloud.translation.v3.Translation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="translated_text", - full_name="google.cloud.translation.v3.Translation.translated_text", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.translation.v3.Translation.model", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detected_language_code", - full_name="google.cloud.translation.v3.Translation.detected_language_code", - index=2, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossary_config", - full_name="google.cloud.translation.v3.Translation.glossary_config", - index=3, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=959, - serialized_end=1127, -) - - -_DETECTLANGUAGEREQUEST_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.translation.v3.DetectLanguageRequest.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3.DetectLanguageRequest.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3.DetectLanguageRequest.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=748, - serialized_end=793, -) - -_DETECTLANGUAGEREQUEST = _descriptor.Descriptor( - name="DetectLanguageRequest", - full_name="google.cloud.translation.v3.DetectLanguageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3.DetectLanguageRequest.parent", - index=0, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.translation.v3.DetectLanguageRequest.model", - index=1, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.translation.v3.DetectLanguageRequest.content", - index=2, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.translation.v3.DetectLanguageRequest.mime_type", - index=3, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.translation.v3.DetectLanguageRequest.labels", - index=4, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_DETECTLANGUAGEREQUEST_LABELSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="source", - full_name="google.cloud.translation.v3.DetectLanguageRequest.source", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1130, - serialized_end=1417, -) - - -_DETECTEDLANGUAGE = _descriptor.Descriptor( - name="DetectedLanguage", - full_name="google.cloud.translation.v3.DetectedLanguage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.translation.v3.DetectedLanguage.language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.translation.v3.DetectedLanguage.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1419, - serialized_end=1480, -) - - -_DETECTLANGUAGERESPONSE = _descriptor.Descriptor( - name="DetectLanguageResponse", - full_name="google.cloud.translation.v3.DetectLanguageResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="languages", - full_name="google.cloud.translation.v3.DetectLanguageResponse.languages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1482, - serialized_end=1572, -) - - -_GETSUPPORTEDLANGUAGESREQUEST = _descriptor.Descriptor( - name="GetSupportedLanguagesRequest", - full_name="google.cloud.translation.v3.GetSupportedLanguagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3.GetSupportedLanguagesRequest.parent", - index=0, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_language_code", - full_name="google.cloud.translation.v3.GetSupportedLanguagesRequest.display_language_code", - index=1, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.translation.v3.GetSupportedLanguagesRequest.model", - index=2, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1575, - serialized_end=1720, -) - - -_SUPPORTEDLANGUAGES = _descriptor.Descriptor( - name="SupportedLanguages", - full_name="google.cloud.translation.v3.SupportedLanguages", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="languages", - full_name="google.cloud.translation.v3.SupportedLanguages.languages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1722, - serialized_end=1809, -) - - -_SUPPORTEDLANGUAGE = _descriptor.Descriptor( - name="SupportedLanguage", - full_name="google.cloud.translation.v3.SupportedLanguage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.translation.v3.SupportedLanguage.language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.translation.v3.SupportedLanguage.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="support_source", - full_name="google.cloud.translation.v3.SupportedLanguage.support_source", - index=2, - number=3, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="support_target", - full_name="google.cloud.translation.v3.SupportedLanguage.support_target", - index=3, - number=4, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1811, - serialized_end=1923, -) - - -_GCSSOURCE = _descriptor.Descriptor( - name="GcsSource", - full_name="google.cloud.translation.v3.GcsSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_uri", - full_name="google.cloud.translation.v3.GcsSource.input_uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1925, - serialized_end=1955, -) - - -_INPUTCONFIG = _descriptor.Descriptor( - name="InputConfig", - full_name="google.cloud.translation.v3.InputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.translation.v3.InputConfig.mime_type", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.translation.v3.InputConfig.gcs_source", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="source", - full_name="google.cloud.translation.v3.InputConfig.source", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1957, - serialized_end=2066, -) - - -_GCSDESTINATION = _descriptor.Descriptor( - name="GcsDestination", - full_name="google.cloud.translation.v3.GcsDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="output_uri_prefix", - full_name="google.cloud.translation.v3.GcsDestination.output_uri_prefix", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2068, - serialized_end=2111, -) - - -_OUTPUTCONFIG = _descriptor.Descriptor( - name="OutputConfig", - full_name="google.cloud.translation.v3.OutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_destination", - full_name="google.cloud.translation.v3.OutputConfig.gcs_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="destination", - full_name="google.cloud.translation.v3.OutputConfig.destination", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=2113, - serialized_end=2214, -) - - -_BATCHTRANSLATETEXTREQUEST_MODELSENTRY = _descriptor.Descriptor( - name="ModelsEntry", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.ModelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.ModelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.ModelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2792, - serialized_end=2837, -) - -_BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY = _descriptor.Descriptor( - name="GlossariesEntry", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.GlossariesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.GlossariesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.GlossariesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2839, - serialized_end=2946, -) - -_BATCHTRANSLATETEXTREQUEST_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=748, - serialized_end=793, -) - -_BATCHTRANSLATETEXTREQUEST = _descriptor.Descriptor( - name="BatchTranslateTextRequest", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_language_code", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.source_language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_language_codes", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.target_language_codes", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="models", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.models", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="input_configs", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.input_configs", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.output_config", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossaries", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.glossaries", - index=6, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.translation.v3.BatchTranslateTextRequest.labels", - index=7, - number=9, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _BATCHTRANSLATETEXTREQUEST_MODELSENTRY, - _BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY, - _BATCHTRANSLATETEXTREQUEST_LABELSENTRY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2217, - serialized_end=2993, -) - - -_BATCHTRANSLATEMETADATA = _descriptor.Descriptor( - name="BatchTranslateMetadata", - full_name="google.cloud.translation.v3.BatchTranslateMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.translation.v3.BatchTranslateMetadata.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="translated_characters", - full_name="google.cloud.translation.v3.BatchTranslateMetadata.translated_characters", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="failed_characters", - full_name="google.cloud.translation.v3.BatchTranslateMetadata.failed_characters", - index=2, - number=3, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_characters", - full_name="google.cloud.translation.v3.BatchTranslateMetadata.total_characters", - index=3, - number=4, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3.BatchTranslateMetadata.submit_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_BATCHTRANSLATEMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2996, - serialized_end=3330, -) - - -_BATCHTRANSLATERESPONSE = _descriptor.Descriptor( - name="BatchTranslateResponse", - full_name="google.cloud.translation.v3.BatchTranslateResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="total_characters", - full_name="google.cloud.translation.v3.BatchTranslateResponse.total_characters", - index=0, - number=1, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="translated_characters", - full_name="google.cloud.translation.v3.BatchTranslateResponse.translated_characters", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="failed_characters", - full_name="google.cloud.translation.v3.BatchTranslateResponse.failed_characters", - index=2, - number=3, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3.BatchTranslateResponse.submit_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.translation.v3.BatchTranslateResponse.end_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3333, - serialized_end=3536, -) - - -_GLOSSARYINPUTCONFIG = _descriptor.Descriptor( - name="GlossaryInputConfig", - full_name="google.cloud.translation.v3.GlossaryInputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.translation.v3.GlossaryInputConfig.gcs_source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="source", - full_name="google.cloud.translation.v3.GlossaryInputConfig.source", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=3538, - serialized_end=3631, -) - - -_GLOSSARY_LANGUAGECODEPAIR = _descriptor.Descriptor( - name="LanguageCodePair", - full_name="google.cloud.translation.v3.Glossary.LanguageCodePair", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="source_language_code", - full_name="google.cloud.translation.v3.Glossary.LanguageCodePair.source_language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_language_code", - full_name="google.cloud.translation.v3.Glossary.LanguageCodePair.target_language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4030, - serialized_end=4108, -) - -_GLOSSARY_LANGUAGECODESSET = _descriptor.Descriptor( - name="LanguageCodesSet", - full_name="google.cloud.translation.v3.Glossary.LanguageCodesSet", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_codes", - full_name="google.cloud.translation.v3.Glossary.LanguageCodesSet.language_codes", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4110, - serialized_end=4152, -) - -_GLOSSARY = _descriptor.Descriptor( - name="Glossary", - full_name="google.cloud.translation.v3.Glossary", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3.Glossary.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_pair", - full_name="google.cloud.translation.v3.Glossary.language_pair", - index=1, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_codes_set", - full_name="google.cloud.translation.v3.Glossary.language_codes_set", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.translation.v3.Glossary.input_config", - index=3, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="entry_count", - full_name="google.cloud.translation.v3.Glossary.entry_count", - index=4, - number=6, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3.Glossary.submit_time", - index=5, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.translation.v3.Glossary.end_time", - index=6, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_GLOSSARY_LANGUAGECODEPAIR, _GLOSSARY_LANGUAGECODESSET,], - enum_types=[], - serialized_options=b"\352Ab\n!translate.googleapis.com/Glossary\022=projects/{project}/locations/{location}/glossaries/{glossary}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="languages", - full_name="google.cloud.translation.v3.Glossary.languages", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=3634, - serialized_end=4268, -) - - -_CREATEGLOSSARYREQUEST = _descriptor.Descriptor( - name="CreateGlossaryRequest", - full_name="google.cloud.translation.v3.CreateGlossaryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3.CreateGlossaryRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossary", - full_name="google.cloud.translation.v3.CreateGlossaryRequest.glossary", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4271, - serialized_end=4415, -) - - -_GETGLOSSARYREQUEST = _descriptor.Descriptor( - name="GetGlossaryRequest", - full_name="google.cloud.translation.v3.GetGlossaryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3.GetGlossaryRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!translate.googleapis.com/Glossary", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4417, - serialized_end=4494, -) - - -_DELETEGLOSSARYREQUEST = _descriptor.Descriptor( - name="DeleteGlossaryRequest", - full_name="google.cloud.translation.v3.DeleteGlossaryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3.DeleteGlossaryRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!translate.googleapis.com/Glossary", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4496, - serialized_end=4576, -) - - -_LISTGLOSSARIESREQUEST = _descriptor.Descriptor( - name="ListGlossariesRequest", - full_name="google.cloud.translation.v3.ListGlossariesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3.ListGlossariesRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.translation.v3.ListGlossariesRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.translation.v3.ListGlossariesRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.translation.v3.ListGlossariesRequest.filter", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4579, - serialized_end=4731, -) - - -_LISTGLOSSARIESRESPONSE = _descriptor.Descriptor( - name="ListGlossariesResponse", - full_name="google.cloud.translation.v3.ListGlossariesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="glossaries", - full_name="google.cloud.translation.v3.ListGlossariesResponse.glossaries", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.translation.v3.ListGlossariesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4733, - serialized_end=4841, -) - - -_CREATEGLOSSARYMETADATA = _descriptor.Descriptor( - name="CreateGlossaryMetadata", - full_name="google.cloud.translation.v3.CreateGlossaryMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3.CreateGlossaryMetadata.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.translation.v3.CreateGlossaryMetadata.state", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3.CreateGlossaryMetadata.submit_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_CREATEGLOSSARYMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4844, - serialized_end=5108, -) - - -_DELETEGLOSSARYMETADATA = _descriptor.Descriptor( - name="DeleteGlossaryMetadata", - full_name="google.cloud.translation.v3.DeleteGlossaryMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3.DeleteGlossaryMetadata.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.translation.v3.DeleteGlossaryMetadata.state", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3.DeleteGlossaryMetadata.submit_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_DELETEGLOSSARYMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5111, - serialized_end=5375, -) - - -_DELETEGLOSSARYRESPONSE = _descriptor.Descriptor( - name="DeleteGlossaryResponse", - full_name="google.cloud.translation.v3.DeleteGlossaryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3.DeleteGlossaryResponse.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3.DeleteGlossaryResponse.submit_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.translation.v3.DeleteGlossaryResponse.end_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5378, - serialized_end=5511, -) - -_TRANSLATETEXTREQUEST_LABELSENTRY.containing_type = _TRANSLATETEXTREQUEST -_TRANSLATETEXTREQUEST.fields_by_name[ - "glossary_config" -].message_type = _TRANSLATETEXTGLOSSARYCONFIG -_TRANSLATETEXTREQUEST.fields_by_name[ - "labels" -].message_type = _TRANSLATETEXTREQUEST_LABELSENTRY -_TRANSLATETEXTRESPONSE.fields_by_name["translations"].message_type = _TRANSLATION -_TRANSLATETEXTRESPONSE.fields_by_name[ - "glossary_translations" -].message_type = _TRANSLATION -_TRANSLATION.fields_by_name[ - "glossary_config" -].message_type = _TRANSLATETEXTGLOSSARYCONFIG -_DETECTLANGUAGEREQUEST_LABELSENTRY.containing_type = _DETECTLANGUAGEREQUEST -_DETECTLANGUAGEREQUEST.fields_by_name[ - "labels" -].message_type = _DETECTLANGUAGEREQUEST_LABELSENTRY -_DETECTLANGUAGEREQUEST.oneofs_by_name["source"].fields.append( - _DETECTLANGUAGEREQUEST.fields_by_name["content"] -) -_DETECTLANGUAGEREQUEST.fields_by_name[ - "content" -].containing_oneof = _DETECTLANGUAGEREQUEST.oneofs_by_name["source"] -_DETECTLANGUAGERESPONSE.fields_by_name["languages"].message_type = _DETECTEDLANGUAGE -_SUPPORTEDLANGUAGES.fields_by_name["languages"].message_type = _SUPPORTEDLANGUAGE -_INPUTCONFIG.fields_by_name["gcs_source"].message_type = _GCSSOURCE -_INPUTCONFIG.oneofs_by_name["source"].fields.append( - _INPUTCONFIG.fields_by_name["gcs_source"] -) -_INPUTCONFIG.fields_by_name[ - "gcs_source" -].containing_oneof = _INPUTCONFIG.oneofs_by_name["source"] -_OUTPUTCONFIG.fields_by_name["gcs_destination"].message_type = _GCSDESTINATION -_OUTPUTCONFIG.oneofs_by_name["destination"].fields.append( - _OUTPUTCONFIG.fields_by_name["gcs_destination"] -) -_OUTPUTCONFIG.fields_by_name[ - "gcs_destination" -].containing_oneof = _OUTPUTCONFIG.oneofs_by_name["destination"] -_BATCHTRANSLATETEXTREQUEST_MODELSENTRY.containing_type = _BATCHTRANSLATETEXTREQUEST -_BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY.fields_by_name[ - "value" -].message_type = _TRANSLATETEXTGLOSSARYCONFIG -_BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY.containing_type = _BATCHTRANSLATETEXTREQUEST -_BATCHTRANSLATETEXTREQUEST_LABELSENTRY.containing_type = _BATCHTRANSLATETEXTREQUEST -_BATCHTRANSLATETEXTREQUEST.fields_by_name[ - "models" -].message_type = _BATCHTRANSLATETEXTREQUEST_MODELSENTRY -_BATCHTRANSLATETEXTREQUEST.fields_by_name["input_configs"].message_type = _INPUTCONFIG -_BATCHTRANSLATETEXTREQUEST.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_BATCHTRANSLATETEXTREQUEST.fields_by_name[ - "glossaries" -].message_type = _BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY -_BATCHTRANSLATETEXTREQUEST.fields_by_name[ - "labels" -].message_type = _BATCHTRANSLATETEXTREQUEST_LABELSENTRY -_BATCHTRANSLATEMETADATA.fields_by_name[ - "state" -].enum_type = _BATCHTRANSLATEMETADATA_STATE -_BATCHTRANSLATEMETADATA.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_BATCHTRANSLATEMETADATA_STATE.containing_type = _BATCHTRANSLATEMETADATA -_BATCHTRANSLATERESPONSE.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_BATCHTRANSLATERESPONSE.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GLOSSARYINPUTCONFIG.fields_by_name["gcs_source"].message_type = _GCSSOURCE -_GLOSSARYINPUTCONFIG.oneofs_by_name["source"].fields.append( - _GLOSSARYINPUTCONFIG.fields_by_name["gcs_source"] -) -_GLOSSARYINPUTCONFIG.fields_by_name[ - "gcs_source" -].containing_oneof = _GLOSSARYINPUTCONFIG.oneofs_by_name["source"] -_GLOSSARY_LANGUAGECODEPAIR.containing_type = _GLOSSARY -_GLOSSARY_LANGUAGECODESSET.containing_type = _GLOSSARY -_GLOSSARY.fields_by_name["language_pair"].message_type = _GLOSSARY_LANGUAGECODEPAIR -_GLOSSARY.fields_by_name["language_codes_set"].message_type = _GLOSSARY_LANGUAGECODESSET -_GLOSSARY.fields_by_name["input_config"].message_type = _GLOSSARYINPUTCONFIG -_GLOSSARY.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GLOSSARY.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GLOSSARY.oneofs_by_name["languages"].fields.append( - _GLOSSARY.fields_by_name["language_pair"] -) -_GLOSSARY.fields_by_name["language_pair"].containing_oneof = _GLOSSARY.oneofs_by_name[ - "languages" -] -_GLOSSARY.oneofs_by_name["languages"].fields.append( - _GLOSSARY.fields_by_name["language_codes_set"] -) -_GLOSSARY.fields_by_name[ - "language_codes_set" -].containing_oneof = _GLOSSARY.oneofs_by_name["languages"] -_CREATEGLOSSARYREQUEST.fields_by_name["glossary"].message_type = _GLOSSARY -_LISTGLOSSARIESRESPONSE.fields_by_name["glossaries"].message_type = _GLOSSARY -_CREATEGLOSSARYMETADATA.fields_by_name[ - "state" -].enum_type = _CREATEGLOSSARYMETADATA_STATE -_CREATEGLOSSARYMETADATA.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_CREATEGLOSSARYMETADATA_STATE.containing_type = _CREATEGLOSSARYMETADATA -_DELETEGLOSSARYMETADATA.fields_by_name[ - "state" -].enum_type = _DELETEGLOSSARYMETADATA_STATE -_DELETEGLOSSARYMETADATA.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DELETEGLOSSARYMETADATA_STATE.containing_type = _DELETEGLOSSARYMETADATA -_DELETEGLOSSARYRESPONSE.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DELETEGLOSSARYRESPONSE.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -DESCRIPTOR.message_types_by_name[ - "TranslateTextGlossaryConfig" -] = _TRANSLATETEXTGLOSSARYCONFIG -DESCRIPTOR.message_types_by_name["TranslateTextRequest"] = _TRANSLATETEXTREQUEST -DESCRIPTOR.message_types_by_name["TranslateTextResponse"] = _TRANSLATETEXTRESPONSE -DESCRIPTOR.message_types_by_name["Translation"] = _TRANSLATION -DESCRIPTOR.message_types_by_name["DetectLanguageRequest"] = _DETECTLANGUAGEREQUEST -DESCRIPTOR.message_types_by_name["DetectedLanguage"] = _DETECTEDLANGUAGE -DESCRIPTOR.message_types_by_name["DetectLanguageResponse"] = _DETECTLANGUAGERESPONSE -DESCRIPTOR.message_types_by_name[ - "GetSupportedLanguagesRequest" -] = _GETSUPPORTEDLANGUAGESREQUEST -DESCRIPTOR.message_types_by_name["SupportedLanguages"] = _SUPPORTEDLANGUAGES -DESCRIPTOR.message_types_by_name["SupportedLanguage"] = _SUPPORTEDLANGUAGE -DESCRIPTOR.message_types_by_name["GcsSource"] = _GCSSOURCE -DESCRIPTOR.message_types_by_name["InputConfig"] = _INPUTCONFIG -DESCRIPTOR.message_types_by_name["GcsDestination"] = _GCSDESTINATION -DESCRIPTOR.message_types_by_name["OutputConfig"] = _OUTPUTCONFIG -DESCRIPTOR.message_types_by_name[ - "BatchTranslateTextRequest" -] = _BATCHTRANSLATETEXTREQUEST -DESCRIPTOR.message_types_by_name["BatchTranslateMetadata"] = _BATCHTRANSLATEMETADATA -DESCRIPTOR.message_types_by_name["BatchTranslateResponse"] = _BATCHTRANSLATERESPONSE -DESCRIPTOR.message_types_by_name["GlossaryInputConfig"] = _GLOSSARYINPUTCONFIG -DESCRIPTOR.message_types_by_name["Glossary"] = _GLOSSARY -DESCRIPTOR.message_types_by_name["CreateGlossaryRequest"] = _CREATEGLOSSARYREQUEST -DESCRIPTOR.message_types_by_name["GetGlossaryRequest"] = _GETGLOSSARYREQUEST -DESCRIPTOR.message_types_by_name["DeleteGlossaryRequest"] = _DELETEGLOSSARYREQUEST -DESCRIPTOR.message_types_by_name["ListGlossariesRequest"] = _LISTGLOSSARIESREQUEST -DESCRIPTOR.message_types_by_name["ListGlossariesResponse"] = _LISTGLOSSARIESRESPONSE -DESCRIPTOR.message_types_by_name["CreateGlossaryMetadata"] = _CREATEGLOSSARYMETADATA -DESCRIPTOR.message_types_by_name["DeleteGlossaryMetadata"] = _DELETEGLOSSARYMETADATA -DESCRIPTOR.message_types_by_name["DeleteGlossaryResponse"] = _DELETEGLOSSARYRESPONSE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TranslateTextGlossaryConfig = _reflection.GeneratedProtocolMessageType( - "TranslateTextGlossaryConfig", - (_message.Message,), - { - "DESCRIPTOR": _TRANSLATETEXTGLOSSARYCONFIG, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Configures which glossary should be used for a specific target - language, and defines options for applying that glossary. - - Attributes: - glossary: - Required. Specifies the glossary used for this translation. - Use this format: projects/\ */locations/*/glossaries/\* - ignore_case: - Optional. Indicates match is case-insensitive. Default value - is false if missing. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.TranslateTextGlossaryConfig) - }, -) -_sym_db.RegisterMessage(TranslateTextGlossaryConfig) - -TranslateTextRequest = _reflection.GeneratedProtocolMessageType( - "TranslateTextRequest", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _TRANSLATETEXTREQUEST_LABELSENTRY, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.TranslateTextRequest.LabelsEntry) - }, - ), - "DESCRIPTOR": _TRANSLATETEXTREQUEST, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The request message for synchronous translation. - - Attributes: - contents: - Required. The content of the input in string format. We - recommend the total content be less than 30k codepoints. Use - BatchTranslateText for larger text. - mime_type: - Optional. The format of the source text, for example, - “text/html”, “text/plain”. If left blank, the MIME type - defaults to “text/html”. - source_language_code: - Optional. The BCP-47 language code of the input text if known, - for example, “en-US” or “sr-Latn”. Supported language codes - are listed in Language Support. If the source language isn’t - specified, the API attempts to identify the source language - automatically and returns the source language within the - response. - target_language_code: - Required. The BCP-47 language code to use for translation of - the input text, set to one of the language codes listed in - Language Support. - parent: - Required. Project or location to make a call. Must refer to a - caller’s project. Format: ``projects/{project-number-or-id}`` - or ``projects/{project-number-or-id}/locations/{location- - id}``. For global calls, use ``projects/{project-number-or- - id}/locations/global`` or ``projects/{project-number-or-id}``. - Non-global location is required for requests using AutoML - models or custom glossaries. Models and glossaries must be - within the same region (have same location-id), otherwise an - INVALID_ARGUMENT (400) error is returned. - model: - Optional. The ``model`` type requested for this translation. - The format depends on model type: - AutoML Translation - models: ``projects/{project-number-or- - id}/locations/{location-id}/models/{model-id}`` - General - (built-in) models: ``projects/{project-number-or- - id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-number-or-id}/locations/{location- - id}/models/general/base`` For global (non-regionalized) - requests, use ``location-id`` ``global``. For example, - ``projects/{project-number-or- - id}/locations/global/models/general/nmt``. If missing, the - system decides which google base model to use. - glossary_config: - Optional. Glossary to be applied. The glossary must be within - the same region (have the same location-id) as the model, - otherwise an INVALID_ARGUMENT (400) error is returned. - labels: - Optional. The labels with user-defined metadata for the - request. Label keys and values can be no longer than 63 - characters (Unicode codepoints), can only contain lowercase - letters, numeric characters, underscores and dashes. - International characters are allowed. Label values are - optional. Label keys must start with a letter. See - https://cloud.google.com/translate/docs/labels for more - information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.TranslateTextRequest) - }, -) -_sym_db.RegisterMessage(TranslateTextRequest) -_sym_db.RegisterMessage(TranslateTextRequest.LabelsEntry) - -TranslateTextResponse = _reflection.GeneratedProtocolMessageType( - "TranslateTextResponse", - (_message.Message,), - { - "DESCRIPTOR": _TRANSLATETEXTRESPONSE, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """ - Attributes: - translations: - Text translation responses with no glossary applied. This - field has the same length as [``contents``][google.cloud.trans - lation.v3.TranslateTextRequest.contents]. - glossary_translations: - Text translation responses if a glossary is provided in the - request. This can be the same as [``translations``][google.clo - ud.translation.v3.TranslateTextResponse.translations] if no - terms apply. This field has the same length as [``contents``][ - google.cloud.translation.v3.TranslateTextRequest.contents]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.TranslateTextResponse) - }, -) -_sym_db.RegisterMessage(TranslateTextResponse) - -Translation = _reflection.GeneratedProtocolMessageType( - "Translation", - (_message.Message,), - { - "DESCRIPTOR": _TRANSLATION, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """A single translation response. - - Attributes: - translated_text: - Text translated into the target language. - model: - Only present when ``model`` is present in the request. - ``model`` here is normalized to have project number. For - example: If the ``model`` requested in TranslationTextRequest - is ``projects/{project-id}/locations/{location- - id}/models/general/nmt`` then ``model`` here would be - normalized to ``projects/{project-number}/locations/{location- - id}/models/general/nmt``. - detected_language_code: - The BCP-47 language code of source text in the initial - request, detected automatically, if no source language was - passed within the initial request. If the source language was - passed, auto-detection of the language does not occur and this - field is empty. - glossary_config: - The ``glossary_config`` used for this translation. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.Translation) - }, -) -_sym_db.RegisterMessage(Translation) - -DetectLanguageRequest = _reflection.GeneratedProtocolMessageType( - "DetectLanguageRequest", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _DETECTLANGUAGEREQUEST_LABELSENTRY, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.DetectLanguageRequest.LabelsEntry) - }, - ), - "DESCRIPTOR": _DETECTLANGUAGEREQUEST, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The request message for language detection. - - Attributes: - parent: - Required. Project or location to make a call. Must refer to a - caller’s project. Format: ``projects/{project-number-or- - id}/locations/{location-id}`` or ``projects/{project-number- - or-id}``. For global calls, use ``projects/{project-number- - or-id}/locations/global`` or ``projects/{project-number-or- - id}``. Only models within the same region (has same location- - id) can be used. Otherwise an INVALID_ARGUMENT (400) error is - returned. - model: - Optional. The language detection model to be used. Format: - ``projects/{project-number-or-id}/locations/{location- - id}/models/language-detection/{model-id}`` Only one language - detection model is currently supported: ``projects/{project- - number-or-id}/locations/{location-id}/models/language- - detection/default``. If not specified, the default model is - used. - source: - Required. The source of the document from which to detect the - language. - content: - The content of the input stored as a string. - mime_type: - Optional. The format of the source text, for example, - “text/html”, “text/plain”. If left blank, the MIME type - defaults to “text/html”. - labels: - Optional. The labels with user-defined metadata for the - request. Label keys and values can be no longer than 63 - characters (Unicode codepoints), can only contain lowercase - letters, numeric characters, underscores and dashes. - International characters are allowed. Label values are - optional. Label keys must start with a letter. See - https://cloud.google.com/translate/docs/labels for more - information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.DetectLanguageRequest) - }, -) -_sym_db.RegisterMessage(DetectLanguageRequest) -_sym_db.RegisterMessage(DetectLanguageRequest.LabelsEntry) - -DetectedLanguage = _reflection.GeneratedProtocolMessageType( - "DetectedLanguage", - (_message.Message,), - { - "DESCRIPTOR": _DETECTEDLANGUAGE, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The response message for language detection. - - Attributes: - language_code: - The BCP-47 language code of source content in the request, - detected automatically. - confidence: - The confidence of the detection result for this language. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.DetectedLanguage) - }, -) -_sym_db.RegisterMessage(DetectedLanguage) - -DetectLanguageResponse = _reflection.GeneratedProtocolMessageType( - "DetectLanguageResponse", - (_message.Message,), - { - "DESCRIPTOR": _DETECTLANGUAGERESPONSE, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The response message for language detection. - - Attributes: - languages: - A list of detected languages sorted by detection confidence in - descending order. The most probable language first. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.DetectLanguageResponse) - }, -) -_sym_db.RegisterMessage(DetectLanguageResponse) - -GetSupportedLanguagesRequest = _reflection.GeneratedProtocolMessageType( - "GetSupportedLanguagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSUPPORTEDLANGUAGESREQUEST, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The request message for discovering supported languages. - - Attributes: - parent: - Required. Project or location to make a call. Must refer to a - caller’s project. Format: ``projects/{project-number-or-id}`` - or ``projects/{project-number-or-id}/locations/{location- - id}``. For global calls, use ``projects/{project-number-or- - id}/locations/global`` or ``projects/{project-number-or-id}``. - Non-global location is required for AutoML models. Only - models within the same region (have same location-id) can be - used, otherwise an INVALID_ARGUMENT (400) error is returned. - display_language_code: - Optional. The language to use to return localized, human - readable names of supported languages. If missing, then - display names are not returned in a response. - model: - Optional. Get supported languages of this model. The format - depends on model type: - AutoML Translation models: - ``projects/{project-number-or-id}/locations/{location- - id}/models/{model-id}`` - General (built-in) models: - ``projects/{project-number-or-id}/locations/{location- - id}/models/general/nmt``, ``projects/{project-number-or- - id}/locations/{location-id}/models/general/base`` Returns - languages supported by the specified model. If missing, we get - supported languages of Google general base (PBMT) model. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.GetSupportedLanguagesRequest) - }, -) -_sym_db.RegisterMessage(GetSupportedLanguagesRequest) - -SupportedLanguages = _reflection.GeneratedProtocolMessageType( - "SupportedLanguages", - (_message.Message,), - { - "DESCRIPTOR": _SUPPORTEDLANGUAGES, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The response message for discovering supported languages. - - Attributes: - languages: - A list of supported language responses. This list contains an - entry for each language the Translation API supports. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.SupportedLanguages) - }, -) -_sym_db.RegisterMessage(SupportedLanguages) - -SupportedLanguage = _reflection.GeneratedProtocolMessageType( - "SupportedLanguage", - (_message.Message,), - { - "DESCRIPTOR": _SUPPORTEDLANGUAGE, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """A single supported language response corresponds to information - related to one supported language. - - Attributes: - language_code: - Supported language code, generally consisting of its ISO 639-1 - identifier, for example, ‘en’, ‘ja’. In certain cases, BCP-47 - codes including language and region identifiers are returned - (for example, ‘zh-TW’ and ‘zh-CN’) - display_name: - Human readable name of the language localized in the display - language specified in the request. - support_source: - Can be used as source language. - support_target: - Can be used as target language. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.SupportedLanguage) - }, -) -_sym_db.RegisterMessage(SupportedLanguage) - -GcsSource = _reflection.GeneratedProtocolMessageType( - "GcsSource", - (_message.Message,), - { - "DESCRIPTOR": _GCSSOURCE, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The Google Cloud Storage location for the input content. - - Attributes: - input_uri: - Required. Source data URI. For example, - ``gs://my_bucket/my_object``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.GcsSource) - }, -) -_sym_db.RegisterMessage(GcsSource) - -InputConfig = _reflection.GeneratedProtocolMessageType( - "InputConfig", - (_message.Message,), - { - "DESCRIPTOR": _INPUTCONFIG, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Input configuration for BatchTranslateText request. - - Attributes: - mime_type: - Optional. Can be “text/plain” or “text/html”. For ``.tsv``, - “text/html” is used if mime_type is missing. For ``.html``, - this field must be “text/html” or empty. For ``.txt``, this - field must be “text/plain” or empty. - source: - Required. Specify the input. - gcs_source: - Required. Google Cloud Storage location for the source input. - This can be a single file (for example, ``gs://translation- - test/input.tsv``) or a wildcard (for example, - ``gs://translation-test/*``). If a file extension is ``.tsv``, - it can contain either one or two columns. The first column - (optional) is the id of the text request. If the first column - is missing, we use the row number (0-based) from the input - file as the ID in the output file. The second column is the - actual text to be translated. We recommend each row be <= 10K - Unicode codepoints, otherwise an error might be returned. Note - that the input tsv must be RFC 4180 compliant. You could use - https://github.com/Clever/csvlint to check potential - formatting errors in your tsv file. csvlint –delimiter=‘:raw- - latex:`\t`’ your_input_file.tsv The other supported file - extensions are ``.txt`` or ``.html``, which is treated as a - single large chunk of text. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.InputConfig) - }, -) -_sym_db.RegisterMessage(InputConfig) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The Google Cloud Storage location for the output content. - - Attributes: - output_uri_prefix: - Required. There must be no files under ‘output_uri_prefix’. - ‘output_uri_prefix’ must end with “/” and start with “gs://”, - otherwise an INVALID_ARGUMENT (400) error is returned. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Output configuration for BatchTranslateText request. - - Attributes: - destination: - Required. The destination of output. - gcs_destination: - Google Cloud Storage destination for output content. For every - single input file (for example, gs://a/b/c.[extension]), we - generate at most 2 \* n output files. (n is the # of - target_language_codes in the BatchTranslateTextRequest). - Output files (tsv) generated are compliant with RFC 4180 - except that record delimiters are ``\\\\n`` instead of - ``\\\\r\\\\n``. We don’t provide any way to - change record delimiters. While the input files are being - processed, we write/update an index file ‘index.csv’ under - ‘output_uri_prefix’ (for example, gs://translation- - test/index.csv) The index file is generated/updated as new - files are being translated. The format is: - input_file,target_language_code,translations_file,errors_file, - glossary_translations_file,glossary_errors_file input_file is - one file we matched using gcs_source.input_uri. - target_language_code is provided in the request. - translations_file contains the translations. (details provided - below) errors_file contains the errors during processing of - the file. (details below). Both translations_file and - errors_file could be empty strings if we have no content to - output. glossary_translations_file and glossary_errors_file - are always empty strings if the input_file is tsv. They could - also be empty if we have no content to output. Once a row is - present in index.csv, the input/output matching never changes. - Callers should also expect all the content in input_file are - processed and ready to be consumed (that is, no partial output - file is written). The format of translations_file (for target - language code ‘trg’) is: - gs://translation_test/a_b_c\_‘trg’\_translations.[extension] - If the input file extension is tsv, the output has the - following columns: Column 1: ID of the request provided in the - input, if it’s not provided in the input, then the input row - number is used (0-based). Column 2: source sentence. Column 3: - translation without applying a glossary. Empty string if there - is an error. Column 4 (only present if a glossary is provided - in the request): translation after applying the glossary. - Empty string if there is an error applying the glossary. Could - be same string as column 3 if there is no glossary applied. - If input file extension is a txt or html, the translation is - directly written to the output file. If glossary is requested, - a separate glossary_translations_file has format of gs://trans - lation_test/a_b_c\_‘trg’\_glossary_translations.[extension] - The format of errors file (for target language code ‘trg’) is: - gs://translation_test/a_b_c\_‘trg’\_errors.[extension] If the - input file extension is tsv, errors_file contains the - following: Column 1: ID of the request provided in the input, - if it’s not provided in the input, then the input row number - is used (0-based). Column 2: source sentence. Column 3: Error - detail for the translation. Could be empty. Column 4 (only - present if a glossary is provided in the request): Error when - applying the glossary. If the input file extension is txt or - html, glossary_error_file will be generated that contains - error details. glossary_error_file has format of gs://translat - ion_test/a_b_c\_‘trg’\_glossary_errors.[extension] - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -BatchTranslateTextRequest = _reflection.GeneratedProtocolMessageType( - "BatchTranslateTextRequest", - (_message.Message,), - { - "ModelsEntry": _reflection.GeneratedProtocolMessageType( - "ModelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATETEXTREQUEST_MODELSENTRY, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.BatchTranslateTextRequest.ModelsEntry) - }, - ), - "GlossariesEntry": _reflection.GeneratedProtocolMessageType( - "GlossariesEntry", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.BatchTranslateTextRequest.GlossariesEntry) - }, - ), - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATETEXTREQUEST_LABELSENTRY, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.BatchTranslateTextRequest.LabelsEntry) - }, - ), - "DESCRIPTOR": _BATCHTRANSLATETEXTREQUEST, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """The batch translation request. - - Attributes: - parent: - Required. Location to make a call. Must refer to a caller’s - project. Format: ``projects/{project-number-or- - id}/locations/{location-id}``. The ``global`` location is not - supported for batch translation. Only AutoML Translation - models or glossaries within the same region (have the same - location-id) can be used, otherwise an INVALID_ARGUMENT (400) - error is returned. - source_language_code: - Required. Source language code. - target_language_codes: - Required. Specify up to 10 language codes here. - models: - Optional. The models to use for translation. Map’s key is - target language code. Map’s value is model name. Value can be - a built-in general model, or an AutoML Translation model. The - value format depends on model type: - AutoML Translation - models: ``projects/{project-number-or- - id}/locations/{location-id}/models/{model-id}`` - General - (built-in) models: ``projects/{project-number-or- - id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-number-or-id}/locations/{location- - id}/models/general/base`` If the map is empty or a specific - model is not requested for a language pair, then default - google model (nmt) is used. - input_configs: - Required. Input configurations. The total number of files - matched should be <= 1000. The total content size should be <= - 100M Unicode codepoints. The files must use UTF-8 encoding. - output_config: - Required. Output configuration. If 2 input configs match to - the same file (that is, same input path), we don’t generate - output for duplicate inputs. - glossaries: - Optional. Glossaries to be applied for translation. It’s keyed - by target language code. - labels: - Optional. The labels with user-defined metadata for the - request. Label keys and values can be no longer than 63 - characters (Unicode codepoints), can only contain lowercase - letters, numeric characters, underscores and dashes. - International characters are allowed. Label values are - optional. Label keys must start with a letter. See - https://cloud.google.com/translate/docs/labels for more - information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.BatchTranslateTextRequest) - }, -) -_sym_db.RegisterMessage(BatchTranslateTextRequest) -_sym_db.RegisterMessage(BatchTranslateTextRequest.ModelsEntry) -_sym_db.RegisterMessage(BatchTranslateTextRequest.GlossariesEntry) -_sym_db.RegisterMessage(BatchTranslateTextRequest.LabelsEntry) - -BatchTranslateMetadata = _reflection.GeneratedProtocolMessageType( - "BatchTranslateMetadata", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATEMETADATA, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """State metadata for the batch translation operation. - - Attributes: - state: - The state of the operation. - translated_characters: - Number of successfully translated characters so far (Unicode - codepoints). - failed_characters: - Number of characters that have failed to process so far - (Unicode codepoints). - total_characters: - Total number of characters (Unicode codepoints). This is the - total number of codepoints from input files times the number - of target languages and appears here shortly after the call is - submitted. - submit_time: - Time when the operation was submitted. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.BatchTranslateMetadata) - }, -) -_sym_db.RegisterMessage(BatchTranslateMetadata) - -BatchTranslateResponse = _reflection.GeneratedProtocolMessageType( - "BatchTranslateResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATERESPONSE, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Stored in the [google.longrunning.Operation.response][google.longrunni - ng.Operation.response] field returned by BatchTranslateText if at - least one sentence is translated successfully. - - Attributes: - total_characters: - Total number of characters (Unicode codepoints). - translated_characters: - Number of successfully translated characters (Unicode - codepoints). - failed_characters: - Number of characters that have failed to process (Unicode - codepoints). - submit_time: - Time when the operation was submitted. - end_time: - The time when the operation is finished and [google.longrunnin - g.Operation.done][google.longrunning.Operation.done] is set to - true. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.BatchTranslateResponse) - }, -) -_sym_db.RegisterMessage(BatchTranslateResponse) - -GlossaryInputConfig = _reflection.GeneratedProtocolMessageType( - "GlossaryInputConfig", - (_message.Message,), - { - "DESCRIPTOR": _GLOSSARYINPUTCONFIG, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Input configuration for glossaries. - - Attributes: - source: - Required. Specify the input. - gcs_source: - Required. Google Cloud Storage location of glossary data. File - format is determined based on the filename extension. API - returns [google.rpc.Code.INVALID_ARGUMENT] for unsupported - URI-s and file formats. Wildcards are not allowed. This must - be a single file in one of the following formats: For - unidirectional glossaries: - TSV/CSV (``.tsv``/``.csv``): 2 - column file, tab- or comma-separated. The first column is - source text. The second column is target text. The file - must not contain headers. That is, the first row is data, - not column names. - TMX (``.tmx``): TMX file with parallel - data defining source/target term pairs. For equivalent - term sets glossaries: - CSV (``.csv``): Multi-column CSV - file defining equivalent glossary terms in multiple - languages. The format is defined for Google Translation - Toolkit and documented in `Use a glossary `__. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.GlossaryInputConfig) - }, -) -_sym_db.RegisterMessage(GlossaryInputConfig) - -Glossary = _reflection.GeneratedProtocolMessageType( - "Glossary", - (_message.Message,), - { - "LanguageCodePair": _reflection.GeneratedProtocolMessageType( - "LanguageCodePair", - (_message.Message,), - { - "DESCRIPTOR": _GLOSSARY_LANGUAGECODEPAIR, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Used with unidirectional glossaries. - - Attributes: - source_language_code: - Required. The BCP-47 language code of the input text, for - example, “en-US”. Expected to be an exact match for - GlossaryTerm.language_code. - target_language_code: - Required. The BCP-47 language code for translation output, for - example, “zh-CN”. Expected to be an exact match for - GlossaryTerm.language_code. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.Glossary.LanguageCodePair) - }, - ), - "LanguageCodesSet": _reflection.GeneratedProtocolMessageType( - "LanguageCodesSet", - (_message.Message,), - { - "DESCRIPTOR": _GLOSSARY_LANGUAGECODESSET, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Used with equivalent term set glossaries. - - Attributes: - language_codes: - The BCP-47 language code(s) for terms defined in the glossary. - All entries are unique. The list contains at least two - entries. Expected to be an exact match for - GlossaryTerm.language_code. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.Glossary.LanguageCodesSet) - }, - ), - "DESCRIPTOR": _GLOSSARY, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Represents a glossary built from user provided data. - - Attributes: - name: - Required. The resource name of the glossary. Glossary names - have the form ``projects/{project-number-or- - id}/locations/{location-id}/glossaries/{glossary-id}``. - languages: - Languages supported by the glossary. - language_pair: - Used with unidirectional glossaries. - language_codes_set: - Used with equivalent term set glossaries. - input_config: - Required. Provides examples to build the glossary from. Total - glossary must not exceed 10M Unicode codepoints. - entry_count: - Output only. The number of entries defined in the glossary. - submit_time: - Output only. When CreateGlossary was called. - end_time: - Output only. When the glossary creation was finished. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.Glossary) - }, -) -_sym_db.RegisterMessage(Glossary) -_sym_db.RegisterMessage(Glossary.LanguageCodePair) -_sym_db.RegisterMessage(Glossary.LanguageCodesSet) - -CreateGlossaryRequest = _reflection.GeneratedProtocolMessageType( - "CreateGlossaryRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEGLOSSARYREQUEST, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Request message for CreateGlossary. - - Attributes: - parent: - Required. The project name. - glossary: - Required. The glossary to create. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.CreateGlossaryRequest) - }, -) -_sym_db.RegisterMessage(CreateGlossaryRequest) - -GetGlossaryRequest = _reflection.GeneratedProtocolMessageType( - "GetGlossaryRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETGLOSSARYREQUEST, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Request message for GetGlossary. - - Attributes: - name: - Required. The name of the glossary to retrieve. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.GetGlossaryRequest) - }, -) -_sym_db.RegisterMessage(GetGlossaryRequest) - -DeleteGlossaryRequest = _reflection.GeneratedProtocolMessageType( - "DeleteGlossaryRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEGLOSSARYREQUEST, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Request message for DeleteGlossary. - - Attributes: - name: - Required. The name of the glossary to delete. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.DeleteGlossaryRequest) - }, -) -_sym_db.RegisterMessage(DeleteGlossaryRequest) - -ListGlossariesRequest = _reflection.GeneratedProtocolMessageType( - "ListGlossariesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTGLOSSARIESREQUEST, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Request message for ListGlossaries. - - Attributes: - parent: - Required. The name of the project from which to list all of - the glossaries. - page_size: - Optional. Requested page size. The server may return fewer - glossaries than requested. If unspecified, the server picks an - appropriate default. - page_token: - Optional. A token identifying a page of results the server - should return. Typically, this is the value of - [ListGlossariesResponse.next_page_token] returned from the - previous call to ``ListGlossaries`` method. The first page is - returned if ``page_token``\ is empty or missing. - filter: - Optional. Filter specifying constraints of a list operation. - Filtering is not supported yet, and the parameter currently - has no effect. If missing, no filtering is performed. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.ListGlossariesRequest) - }, -) -_sym_db.RegisterMessage(ListGlossariesRequest) - -ListGlossariesResponse = _reflection.GeneratedProtocolMessageType( - "ListGlossariesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTGLOSSARIESRESPONSE, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Response message for ListGlossaries. - - Attributes: - glossaries: - The list of glossaries for a project. - next_page_token: - A token to retrieve a page of results. Pass this value in the - [ListGlossariesRequest.page_token] field in the subsequent - call to ``ListGlossaries`` method to retrieve the next page of - results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.ListGlossariesResponse) - }, -) -_sym_db.RegisterMessage(ListGlossariesResponse) - -CreateGlossaryMetadata = _reflection.GeneratedProtocolMessageType( - "CreateGlossaryMetadata", - (_message.Message,), - { - "DESCRIPTOR": _CREATEGLOSSARYMETADATA, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Stored in the [google.longrunning.Operation.metadata][google.longrunni - ng.Operation.metadata] field returned by CreateGlossary. - - Attributes: - name: - The name of the glossary that is being created. - state: - The current state of the glossary creation operation. - submit_time: - The time when the operation was submitted to the server. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.CreateGlossaryMetadata) - }, -) -_sym_db.RegisterMessage(CreateGlossaryMetadata) - -DeleteGlossaryMetadata = _reflection.GeneratedProtocolMessageType( - "DeleteGlossaryMetadata", - (_message.Message,), - { - "DESCRIPTOR": _DELETEGLOSSARYMETADATA, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Stored in the [google.longrunning.Operation.metadata][google.longrunni - ng.Operation.metadata] field returned by DeleteGlossary. - - Attributes: - name: - The name of the glossary that is being deleted. - state: - The current state of the glossary deletion operation. - submit_time: - The time when the operation was submitted to the server. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.DeleteGlossaryMetadata) - }, -) -_sym_db.RegisterMessage(DeleteGlossaryMetadata) - -DeleteGlossaryResponse = _reflection.GeneratedProtocolMessageType( - "DeleteGlossaryResponse", - (_message.Message,), - { - "DESCRIPTOR": _DELETEGLOSSARYRESPONSE, - "__module__": "google.cloud.translate_v3.proto.translation_service_pb2", - "__doc__": """Stored in the [google.longrunning.Operation.response][google.longrunni - ng.Operation.response] field returned by DeleteGlossary. - - Attributes: - name: - The name of the deleted glossary. - submit_time: - The time when the operation was submitted to the server. - end_time: - The time when the glossary deletion is finished and [google.lo - ngrunning.Operation.done][google.longrunning.Operation.done] - is set to true. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3.DeleteGlossaryResponse) - }, -) -_sym_db.RegisterMessage(DeleteGlossaryResponse) - - -DESCRIPTOR._options = None -_TRANSLATETEXTGLOSSARYCONFIG.fields_by_name["glossary"]._options = None -_TRANSLATETEXTGLOSSARYCONFIG.fields_by_name["ignore_case"]._options = None -_TRANSLATETEXTREQUEST_LABELSENTRY._options = None -_TRANSLATETEXTREQUEST.fields_by_name["contents"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["mime_type"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["source_language_code"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["target_language_code"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["parent"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["model"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["glossary_config"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["labels"]._options = None -_DETECTLANGUAGEREQUEST_LABELSENTRY._options = None -_DETECTLANGUAGEREQUEST.fields_by_name["parent"]._options = None -_DETECTLANGUAGEREQUEST.fields_by_name["model"]._options = None -_DETECTLANGUAGEREQUEST.fields_by_name["mime_type"]._options = None -_DETECTLANGUAGEREQUEST.fields_by_name["labels"]._options = None -_GETSUPPORTEDLANGUAGESREQUEST.fields_by_name["parent"]._options = None -_GETSUPPORTEDLANGUAGESREQUEST.fields_by_name["display_language_code"]._options = None -_GETSUPPORTEDLANGUAGESREQUEST.fields_by_name["model"]._options = None -_INPUTCONFIG.fields_by_name["mime_type"]._options = None -_BATCHTRANSLATETEXTREQUEST_MODELSENTRY._options = None -_BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY._options = None -_BATCHTRANSLATETEXTREQUEST_LABELSENTRY._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["parent"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["source_language_code"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["target_language_codes"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["models"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["input_configs"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["output_config"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["glossaries"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["labels"]._options = None -_GLOSSARY.fields_by_name["entry_count"]._options = None -_GLOSSARY.fields_by_name["submit_time"]._options = None -_GLOSSARY.fields_by_name["end_time"]._options = None -_GLOSSARY._options = None -_CREATEGLOSSARYREQUEST.fields_by_name["parent"]._options = None -_CREATEGLOSSARYREQUEST.fields_by_name["glossary"]._options = None -_GETGLOSSARYREQUEST.fields_by_name["name"]._options = None -_DELETEGLOSSARYREQUEST.fields_by_name["name"]._options = None -_LISTGLOSSARIESREQUEST.fields_by_name["parent"]._options = None -_LISTGLOSSARIESREQUEST.fields_by_name["page_size"]._options = None -_LISTGLOSSARIESREQUEST.fields_by_name["page_token"]._options = None -_LISTGLOSSARIESREQUEST.fields_by_name["filter"]._options = None - -_TRANSLATIONSERVICE = _descriptor.ServiceDescriptor( - name="TranslationService", - full_name="google.cloud.translation.v3.TranslationService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\030translate.googleapis.com\322A`https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-translation", - create_key=_descriptor._internal_create_key, - serialized_start=5514, - serialized_end=7576, - methods=[ - _descriptor.MethodDescriptor( - name="TranslateText", - full_name="google.cloud.translation.v3.TranslationService.TranslateText", - index=0, - containing_service=None, - input_type=_TRANSLATETEXTREQUEST, - output_type=_TRANSLATETEXTRESPONSE, - serialized_options=b'\202\323\344\223\002b"1/v3/{parent=projects/*/locations/*}:translateText:\001*Z*"%/v3/{parent=projects/*}:translateText:\001*\332A$parent,target_language_code,contents\332AIparent,model,mime_type,source_language_code,target_language_code,contents', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DetectLanguage", - full_name="google.cloud.translation.v3.TranslationService.DetectLanguage", - index=1, - containing_service=None, - input_type=_DETECTLANGUAGEREQUEST, - output_type=_DETECTLANGUAGERESPONSE, - serialized_options=b'\202\323\344\223\002d"2/v3/{parent=projects/*/locations/*}:detectLanguage:\001*Z+"&/v3/{parent=projects/*}:detectLanguage:\001*\332A\036parent,model,mime_type,content', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSupportedLanguages", - full_name="google.cloud.translation.v3.TranslationService.GetSupportedLanguages", - index=2, - containing_service=None, - input_type=_GETSUPPORTEDLANGUAGESREQUEST, - output_type=_SUPPORTEDLANGUAGES, - serialized_options=b'\202\323\344\223\002f\0226/v3/{parent=projects/*/locations/*}/supportedLanguagesZ,\022*/v3/{parent=projects/*}/supportedLanguages\332A"parent,model,display_language_code', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="BatchTranslateText", - full_name="google.cloud.translation.v3.TranslationService.BatchTranslateText", - index=3, - containing_service=None, - input_type=_BATCHTRANSLATETEXTREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002;"6/v3/{parent=projects/*/locations/*}:batchTranslateText:\001*\312A0\n\026BatchTranslateResponse\022\026BatchTranslateMetadata', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateGlossary", - full_name="google.cloud.translation.v3.TranslationService.CreateGlossary", - index=4, - containing_service=None, - input_type=_CREATEGLOSSARYREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002:"./v3/{parent=projects/*/locations/*}/glossaries:\010glossary\332A\017parent,glossary\312A"\n\010Glossary\022\026CreateGlossaryMetadata', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListGlossaries", - full_name="google.cloud.translation.v3.TranslationService.ListGlossaries", - index=5, - containing_service=None, - input_type=_LISTGLOSSARIESREQUEST, - output_type=_LISTGLOSSARIESRESPONSE, - serialized_options=b"\202\323\344\223\0020\022./v3/{parent=projects/*/locations/*}/glossaries\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetGlossary", - full_name="google.cloud.translation.v3.TranslationService.GetGlossary", - index=6, - containing_service=None, - input_type=_GETGLOSSARYREQUEST, - output_type=_GLOSSARY, - serialized_options=b"\202\323\344\223\0020\022./v3/{name=projects/*/locations/*/glossaries/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteGlossary", - full_name="google.cloud.translation.v3.TranslationService.DeleteGlossary", - index=7, - containing_service=None, - input_type=_DELETEGLOSSARYREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b"\202\323\344\223\0020*./v3/{name=projects/*/locations/*/glossaries/*}\332A\004name\312A0\n\026DeleteGlossaryResponse\022\026DeleteGlossaryMetadata", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_TRANSLATIONSERVICE) - -DESCRIPTOR.services_by_name["TranslationService"] = _TRANSLATIONSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service_pb2_grpc.py b/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service_pb2_grpc.py deleted file mode 100644 index 66b1b6cf004d..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3/proto/translation_service_pb2_grpc.py +++ /dev/null @@ -1,411 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.translate_v3.proto import ( - translation_service_pb2 as google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) - - -class TranslationServiceStub(object): - """Proto file for the Cloud Translation API (v3 GA). - - Provides natural language translation operations. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.TranslateText = channel.unary_unary( - "/google.cloud.translation.v3.TranslationService/TranslateText", - request_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.TranslateTextRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.TranslateTextResponse.FromString, - ) - self.DetectLanguage = channel.unary_unary( - "/google.cloud.translation.v3.TranslationService/DetectLanguage", - request_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DetectLanguageRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DetectLanguageResponse.FromString, - ) - self.GetSupportedLanguages = channel.unary_unary( - "/google.cloud.translation.v3.TranslationService/GetSupportedLanguages", - request_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.GetSupportedLanguagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.SupportedLanguages.FromString, - ) - self.BatchTranslateText = channel.unary_unary( - "/google.cloud.translation.v3.TranslationService/BatchTranslateText", - request_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.BatchTranslateTextRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.CreateGlossary = channel.unary_unary( - "/google.cloud.translation.v3.TranslationService/CreateGlossary", - request_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.CreateGlossaryRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.ListGlossaries = channel.unary_unary( - "/google.cloud.translation.v3.TranslationService/ListGlossaries", - request_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.ListGlossariesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.ListGlossariesResponse.FromString, - ) - self.GetGlossary = channel.unary_unary( - "/google.cloud.translation.v3.TranslationService/GetGlossary", - request_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.GetGlossaryRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.Glossary.FromString, - ) - self.DeleteGlossary = channel.unary_unary( - "/google.cloud.translation.v3.TranslationService/DeleteGlossary", - request_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DeleteGlossaryRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - - -class TranslationServiceServicer(object): - """Proto file for the Cloud Translation API (v3 GA). - - Provides natural language translation operations. - """ - - def TranslateText(self, request, context): - """Translates input text and returns translated text. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DetectLanguage(self, request, context): - """Detects the language of text within a request. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSupportedLanguages(self, request, context): - """Returns a list of supported languages for translation. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def BatchTranslateText(self, request, context): - """Translates a large volume of text in asynchronous batch mode. - This function provides real-time output as the inputs are being processed. - If caller cancels a request, the partial results (for an input file, it's - all or nothing) may still be available on the specified output location. - - This call returns immediately and you can - use google.longrunning.Operation.name to poll the status of the call. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateGlossary(self, request, context): - """Creates a glossary and returns the long-running operation. Returns - NOT_FOUND, if the project doesn't exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListGlossaries(self, request, context): - """Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't - exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetGlossary(self, request, context): - """Gets a glossary. Returns NOT_FOUND, if the glossary doesn't - exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteGlossary(self, request, context): - """Deletes a glossary, or cancels glossary construction - if the glossary isn't created yet. - Returns NOT_FOUND, if the glossary doesn't exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_TranslationServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "TranslateText": grpc.unary_unary_rpc_method_handler( - servicer.TranslateText, - request_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.TranslateTextRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.TranslateTextResponse.SerializeToString, - ), - "DetectLanguage": grpc.unary_unary_rpc_method_handler( - servicer.DetectLanguage, - request_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DetectLanguageRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DetectLanguageResponse.SerializeToString, - ), - "GetSupportedLanguages": grpc.unary_unary_rpc_method_handler( - servicer.GetSupportedLanguages, - request_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.GetSupportedLanguagesRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.SupportedLanguages.SerializeToString, - ), - "BatchTranslateText": grpc.unary_unary_rpc_method_handler( - servicer.BatchTranslateText, - request_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.BatchTranslateTextRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "CreateGlossary": grpc.unary_unary_rpc_method_handler( - servicer.CreateGlossary, - request_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.CreateGlossaryRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "ListGlossaries": grpc.unary_unary_rpc_method_handler( - servicer.ListGlossaries, - request_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.ListGlossariesRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.ListGlossariesResponse.SerializeToString, - ), - "GetGlossary": grpc.unary_unary_rpc_method_handler( - servicer.GetGlossary, - request_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.GetGlossaryRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.Glossary.SerializeToString, - ), - "DeleteGlossary": grpc.unary_unary_rpc_method_handler( - servicer.DeleteGlossary, - request_deserializer=google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DeleteGlossaryRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.translation.v3.TranslationService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class TranslationService(object): - """Proto file for the Cloud Translation API (v3 GA). - - Provides natural language translation operations. - """ - - @staticmethod - def TranslateText( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3.TranslationService/TranslateText", - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.TranslateTextRequest.SerializeToString, - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.TranslateTextResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DetectLanguage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3.TranslationService/DetectLanguage", - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DetectLanguageRequest.SerializeToString, - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DetectLanguageResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetSupportedLanguages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3.TranslationService/GetSupportedLanguages", - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.GetSupportedLanguagesRequest.SerializeToString, - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.SupportedLanguages.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def BatchTranslateText( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3.TranslationService/BatchTranslateText", - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.BatchTranslateTextRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateGlossary( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3.TranslationService/CreateGlossary", - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.CreateGlossaryRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListGlossaries( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3.TranslationService/ListGlossaries", - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.ListGlossariesRequest.SerializeToString, - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.ListGlossariesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetGlossary( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3.TranslationService/GetGlossary", - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.GetGlossaryRequest.SerializeToString, - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.Glossary.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteGlossary( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3.TranslationService/DeleteGlossary", - google_dot_cloud_dot_translate__v3_dot_proto_dot_translation__service__pb2.DeleteGlossaryRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/py.typed b/packages/google-cloud-translate/google/cloud/translate_v3/py.typed new file mode 100644 index 000000000000..dd819a47cefe --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-translation package uses inline types. diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/__init__.py new file mode 100644 index 000000000000..42ffdf2bc43d --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# 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. +# diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/__init__.py new file mode 100644 index 000000000000..e24427116f9f --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from .client import TranslationServiceClient +from .async_client import TranslationServiceAsyncClient + +__all__ = ( + "TranslationServiceClient", + "TranslationServiceAsyncClient", +) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/async_client.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/async_client.py new file mode 100644 index 000000000000..66552ce73511 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/async_client.py @@ -0,0 +1,912 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.translate_v3.services.translation_service import pagers +from google.cloud.translate_v3.types import translation_service +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import TranslationServiceTransport +from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport +from .client import TranslationServiceClient + + +class TranslationServiceAsyncClient: + """Provides natural language translation operations.""" + + _client: TranslationServiceClient + + DEFAULT_ENDPOINT = TranslationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TranslationServiceClient.DEFAULT_MTLS_ENDPOINT + + glossary_path = staticmethod(TranslationServiceClient.glossary_path) + + from_service_account_file = TranslationServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(TranslationServiceClient).get_transport_class, + type(TranslationServiceClient), + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, TranslationServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the translation service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TranslationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = TranslationServiceClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def translate_text( + self, + request: translation_service.TranslateTextRequest = None, + *, + parent: str = None, + target_language_code: str = None, + contents: Sequence[str] = None, + model: str = None, + mime_type: str = None, + source_language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateTextResponse: + r"""Translates input text and returns translated text. + + Args: + request (:class:`~.translation_service.TranslateTextRequest`): + The request object. The request message for synchronous + translation. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: ``projects/{project-number-or-id}`` or + ``projects/{project-number-or-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Non-global location is required for requests using + AutoML models or custom glossaries. + + Models and glossaries must be within the same region + (have same location-id), otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target_language_code (:class:`str`): + Required. The BCP-47 language code to + use for translation of the input text, + set to one of the language codes listed + in Language Support. + This corresponds to the ``target_language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (:class:`Sequence[str]`): + Required. The content of the input in + string format. We recommend the total + content be less than 30k codepoints. Use + BatchTranslateText for larger text. + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. The ``model`` type requested for this + translation. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` + + For global (non-regionalized) requests, use + ``location-id`` ``global``. For example, + ``projects/{project-number-or-id}/locations/global/models/general/nmt``. + + If missing, the system decides which google base model + to use. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mime_type (:class:`str`): + Optional. The format of the source + text, for example, "text/html", + "text/plain". If left blank, the MIME + type defaults to "text/html". + This corresponds to the ``mime_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source_language_code (:class:`str`): + Optional. The BCP-47 language code of + the input text if known, for example, + "en-US" or "sr-Latn". Supported language + codes are listed in Language Support. If + the source language isn't specified, the + API attempts to identify the source + language automatically and returns the + source language within the response. + This corresponds to the ``source_language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.TranslateTextResponse: + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any( + [ + parent, + target_language_code, + contents, + model, + mime_type, + source_language_code, + ] + ): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.TranslateTextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if target_language_code is not None: + request.target_language_code = target_language_code + if contents is not None: + request.contents = contents + if model is not None: + request.model = model + if mime_type is not None: + request.mime_type = mime_type + if source_language_code is not None: + request.source_language_code = source_language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.translate_text, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def detect_language( + self, + request: translation_service.DetectLanguageRequest = None, + *, + parent: str = None, + model: str = None, + mime_type: str = None, + content: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.DetectLanguageResponse: + r"""Detects the language of text within a request. + + Args: + request (:class:`~.translation_service.DetectLanguageRequest`): + The request object. The request message for language + detection. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: + ``projects/{project-number-or-id}/locations/{location-id}`` + or ``projects/{project-number-or-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Only models within the same region (has same + location-id) can be used. Otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. The language detection model to be used. + + Format: + ``projects/{project-number-or-id}/locations/{location-id}/models/language-detection/{model-id}`` + + Only one language detection model is currently + supported: + ``projects/{project-number-or-id}/locations/{location-id}/models/language-detection/default``. + + If not specified, the default model is used. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mime_type (:class:`str`): + Optional. The format of the source + text, for example, "text/html", + "text/plain". If left blank, the MIME + type defaults to "text/html". + This corresponds to the ``mime_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + content (:class:`str`): + The content of the input stored as a + string. + This corresponds to the ``content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.DetectLanguageResponse: + The response message for language + detection. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, model, mime_type, content]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.DetectLanguageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if model is not None: + request.model = model + if mime_type is not None: + request.mime_type = mime_type + if content is not None: + request.content = content + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.detect_language, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_supported_languages( + self, + request: translation_service.GetSupportedLanguagesRequest = None, + *, + parent: str = None, + model: str = None, + display_language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.SupportedLanguages: + r"""Returns a list of supported languages for + translation. + + Args: + request (:class:`~.translation_service.GetSupportedLanguagesRequest`): + The request object. The request message for discovering + supported languages. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: ``projects/{project-number-or-id}`` or + ``projects/{project-number-or-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Non-global location is required for AutoML models. + + Only models within the same region (have same + location-id) can be used, otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. Get supported languages of this model. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` + + Returns languages supported by the specified model. If + missing, we get supported languages of Google general + base (PBMT) model. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_language_code (:class:`str`): + Optional. The language to use to + return localized, human readable names + of supported languages. If missing, then + display names are not returned in a + response. + This corresponds to the ``display_language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.SupportedLanguages: + The response message for discovering + supported languages. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, model, display_language_code]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.GetSupportedLanguagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if model is not None: + request.model = model + if display_language_code is not None: + request.display_language_code = display_language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_supported_languages, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def batch_translate_text( + self, + request: translation_service.BatchTranslateTextRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Translates a large volume of text in asynchronous + batch mode. This function provides real-time output as + the inputs are being processed. If caller cancels a + request, the partial results (for an input file, it's + all or nothing) may still be available on the specified + output location. + This call returns immediately and you can + use google.longrunning.Operation.name to poll the status + of the call. + + Args: + request (:class:`~.translation_service.BatchTranslateTextRequest`): + The request object. The batch translation request. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.BatchTranslateResponse``: + Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by BatchTranslateText if at least one + sentence is translated successfully. + + """ + # Create or coerce a protobuf request object. + + request = translation_service.BatchTranslateTextRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_translate_text, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + translation_service.BatchTranslateResponse, + metadata_type=translation_service.BatchTranslateMetadata, + ) + + # Done; return the response. + return response + + async def create_glossary( + self, + request: translation_service.CreateGlossaryRequest = None, + *, + parent: str = None, + glossary: translation_service.Glossary = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a glossary and returns the long-running operation. + Returns NOT_FOUND, if the project doesn't exist. + + Args: + request (:class:`~.translation_service.CreateGlossaryRequest`): + The request object. Request message for CreateGlossary. + parent (:class:`str`): + Required. The project name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + glossary (:class:`~.translation_service.Glossary`): + Required. The glossary to create. + This corresponds to the ``glossary`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.Glossary``: Represents a + glossary built from user provided data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, glossary]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.CreateGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if glossary is not None: + request.glossary = glossary + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_glossary, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + translation_service.Glossary, + metadata_type=translation_service.CreateGlossaryMetadata, + ) + + # Done; return the response. + return response + + async def list_glossaries( + self, + request: translation_service.ListGlossariesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGlossariesAsyncPager: + r"""Lists glossaries in a project. Returns NOT_FOUND, if the project + doesn't exist. + + Args: + request (:class:`~.translation_service.ListGlossariesRequest`): + The request object. Request message for ListGlossaries. + parent (:class:`str`): + Required. The name of the project + from which to list all of the + glossaries. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListGlossariesAsyncPager: + Response message for ListGlossaries. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.ListGlossariesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_glossaries, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListGlossariesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_glossary( + self, + request: translation_service.GetGlossaryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.Glossary: + r"""Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + exist. + + Args: + request (:class:`~.translation_service.GetGlossaryRequest`): + The request object. Request message for GetGlossary. + name (:class:`str`): + Required. The name of the glossary to + retrieve. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.Glossary: + Represents a glossary built from user + provided data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.GetGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_glossary, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_glossary( + self, + request: translation_service.DeleteGlossaryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a glossary, or cancels glossary construction if the + glossary isn't created yet. Returns NOT_FOUND, if the glossary + doesn't exist. + + Args: + request (:class:`~.translation_service.DeleteGlossaryRequest`): + The request object. Request message for DeleteGlossary. + name (:class:`str`): + Required. The name of the glossary to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.DeleteGlossaryResponse``: + Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by DeleteGlossary. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.DeleteGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_glossary, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + translation_service.DeleteGlossaryResponse, + metadata_type=translation_service.DeleteGlossaryMetadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-translation", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("TranslationServiceAsyncClient",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/client.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/client.py new file mode 100644 index 000000000000..097743cb6b32 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/client.py @@ -0,0 +1,1068 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from collections import OrderedDict +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.translate_v3.services.translation_service import pagers +from google.cloud.translate_v3.types import translation_service +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import TranslationServiceTransport +from .transports.grpc import TranslationServiceGrpcTransport +from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport + + +class TranslationServiceClientMeta(type): + """Metaclass for the TranslationService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[TranslationServiceTransport]] + _transport_registry["grpc"] = TranslationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TranslationServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[TranslationServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class TranslationServiceClient(metaclass=TranslationServiceClientMeta): + """Provides natural language translation operations.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "translate.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def glossary_path(project: str, location: str, glossary: str,) -> str: + """Return a fully-qualified glossary string.""" + return "projects/{project}/locations/{location}/glossaries/{glossary}".format( + project=project, location=location, glossary=glossary, + ) + + @staticmethod + def parse_glossary_path(path: str) -> Dict[str, str]: + """Parse a glossary path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/glossaries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, TranslationServiceTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the translation service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TranslationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TranslationServiceTransport): + # transport is a TranslationServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def translate_text( + self, + request: translation_service.TranslateTextRequest = None, + *, + parent: str = None, + target_language_code: str = None, + contents: Sequence[str] = None, + model: str = None, + mime_type: str = None, + source_language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateTextResponse: + r"""Translates input text and returns translated text. + + Args: + request (:class:`~.translation_service.TranslateTextRequest`): + The request object. The request message for synchronous + translation. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: ``projects/{project-number-or-id}`` or + ``projects/{project-number-or-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Non-global location is required for requests using + AutoML models or custom glossaries. + + Models and glossaries must be within the same region + (have same location-id), otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target_language_code (:class:`str`): + Required. The BCP-47 language code to + use for translation of the input text, + set to one of the language codes listed + in Language Support. + This corresponds to the ``target_language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (:class:`Sequence[str]`): + Required. The content of the input in + string format. We recommend the total + content be less than 30k codepoints. Use + BatchTranslateText for larger text. + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. The ``model`` type requested for this + translation. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` + + For global (non-regionalized) requests, use + ``location-id`` ``global``. For example, + ``projects/{project-number-or-id}/locations/global/models/general/nmt``. + + If missing, the system decides which google base model + to use. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mime_type (:class:`str`): + Optional. The format of the source + text, for example, "text/html", + "text/plain". If left blank, the MIME + type defaults to "text/html". + This corresponds to the ``mime_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source_language_code (:class:`str`): + Optional. The BCP-47 language code of + the input text if known, for example, + "en-US" or "sr-Latn". Supported language + codes are listed in Language Support. If + the source language isn't specified, the + API attempts to identify the source + language automatically and returns the + source language within the response. + This corresponds to the ``source_language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.TranslateTextResponse: + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [ + parent, + target_language_code, + contents, + model, + mime_type, + source_language_code, + ] + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.TranslateTextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.TranslateTextRequest): + request = translation_service.TranslateTextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if target_language_code is not None: + request.target_language_code = target_language_code + if contents is not None: + request.contents = contents + if model is not None: + request.model = model + if mime_type is not None: + request.mime_type = mime_type + if source_language_code is not None: + request.source_language_code = source_language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.translate_text] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def detect_language( + self, + request: translation_service.DetectLanguageRequest = None, + *, + parent: str = None, + model: str = None, + mime_type: str = None, + content: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.DetectLanguageResponse: + r"""Detects the language of text within a request. + + Args: + request (:class:`~.translation_service.DetectLanguageRequest`): + The request object. The request message for language + detection. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: + ``projects/{project-number-or-id}/locations/{location-id}`` + or ``projects/{project-number-or-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Only models within the same region (has same + location-id) can be used. Otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. The language detection model to be used. + + Format: + ``projects/{project-number-or-id}/locations/{location-id}/models/language-detection/{model-id}`` + + Only one language detection model is currently + supported: + ``projects/{project-number-or-id}/locations/{location-id}/models/language-detection/default``. + + If not specified, the default model is used. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mime_type (:class:`str`): + Optional. The format of the source + text, for example, "text/html", + "text/plain". If left blank, the MIME + type defaults to "text/html". + This corresponds to the ``mime_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + content (:class:`str`): + The content of the input stored as a + string. + This corresponds to the ``content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.DetectLanguageResponse: + The response message for language + detection. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, model, mime_type, content]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.DetectLanguageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.DetectLanguageRequest): + request = translation_service.DetectLanguageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if model is not None: + request.model = model + if mime_type is not None: + request.mime_type = mime_type + if content is not None: + request.content = content + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.detect_language] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_supported_languages( + self, + request: translation_service.GetSupportedLanguagesRequest = None, + *, + parent: str = None, + model: str = None, + display_language_code: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.SupportedLanguages: + r"""Returns a list of supported languages for + translation. + + Args: + request (:class:`~.translation_service.GetSupportedLanguagesRequest`): + The request object. The request message for discovering + supported languages. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: ``projects/{project-number-or-id}`` or + ``projects/{project-number-or-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Non-global location is required for AutoML models. + + Only models within the same region (have same + location-id) can be used, otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. Get supported languages of this model. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` + + Returns languages supported by the specified model. If + missing, we get supported languages of Google general + base (PBMT) model. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_language_code (:class:`str`): + Optional. The language to use to + return localized, human readable names + of supported languages. If missing, then + display names are not returned in a + response. + This corresponds to the ``display_language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.SupportedLanguages: + The response message for discovering + supported languages. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, model, display_language_code]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.GetSupportedLanguagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.GetSupportedLanguagesRequest): + request = translation_service.GetSupportedLanguagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if model is not None: + request.model = model + if display_language_code is not None: + request.display_language_code = display_language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_supported_languages] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def batch_translate_text( + self, + request: translation_service.BatchTranslateTextRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Translates a large volume of text in asynchronous + batch mode. This function provides real-time output as + the inputs are being processed. If caller cancels a + request, the partial results (for an input file, it's + all or nothing) may still be available on the specified + output location. + This call returns immediately and you can + use google.longrunning.Operation.name to poll the status + of the call. + + Args: + request (:class:`~.translation_service.BatchTranslateTextRequest`): + The request object. The batch translation request. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.BatchTranslateResponse``: + Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by BatchTranslateText if at least one + sentence is translated successfully. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.BatchTranslateTextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.BatchTranslateTextRequest): + request = translation_service.BatchTranslateTextRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_translate_text] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + translation_service.BatchTranslateResponse, + metadata_type=translation_service.BatchTranslateMetadata, + ) + + # Done; return the response. + return response + + def create_glossary( + self, + request: translation_service.CreateGlossaryRequest = None, + *, + parent: str = None, + glossary: translation_service.Glossary = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a glossary and returns the long-running operation. + Returns NOT_FOUND, if the project doesn't exist. + + Args: + request (:class:`~.translation_service.CreateGlossaryRequest`): + The request object. Request message for CreateGlossary. + parent (:class:`str`): + Required. The project name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + glossary (:class:`~.translation_service.Glossary`): + Required. The glossary to create. + This corresponds to the ``glossary`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.Glossary``: Represents a + glossary built from user provided data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, glossary]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.CreateGlossaryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.CreateGlossaryRequest): + request = translation_service.CreateGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if glossary is not None: + request.glossary = glossary + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_glossary] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + translation_service.Glossary, + metadata_type=translation_service.CreateGlossaryMetadata, + ) + + # Done; return the response. + return response + + def list_glossaries( + self, + request: translation_service.ListGlossariesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGlossariesPager: + r"""Lists glossaries in a project. Returns NOT_FOUND, if the project + doesn't exist. + + Args: + request (:class:`~.translation_service.ListGlossariesRequest`): + The request object. Request message for ListGlossaries. + parent (:class:`str`): + Required. The name of the project + from which to list all of the + glossaries. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListGlossariesPager: + Response message for ListGlossaries. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.ListGlossariesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.ListGlossariesRequest): + request = translation_service.ListGlossariesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_glossaries] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListGlossariesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_glossary( + self, + request: translation_service.GetGlossaryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.Glossary: + r"""Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + exist. + + Args: + request (:class:`~.translation_service.GetGlossaryRequest`): + The request object. Request message for GetGlossary. + name (:class:`str`): + Required. The name of the glossary to + retrieve. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.Glossary: + Represents a glossary built from user + provided data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.GetGlossaryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.GetGlossaryRequest): + request = translation_service.GetGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_glossary] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_glossary( + self, + request: translation_service.DeleteGlossaryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a glossary, or cancels glossary construction if the + glossary isn't created yet. Returns NOT_FOUND, if the glossary + doesn't exist. + + Args: + request (:class:`~.translation_service.DeleteGlossaryRequest`): + The request object. Request message for DeleteGlossary. + name (:class:`str`): + Required. The name of the glossary to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.DeleteGlossaryResponse``: + Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by DeleteGlossary. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.DeleteGlossaryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.DeleteGlossaryRequest): + request = translation_service.DeleteGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_glossary] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + translation_service.DeleteGlossaryResponse, + metadata_type=translation_service.DeleteGlossaryMetadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-translation", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("TranslationServiceClient",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/pagers.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/pagers.py new file mode 100644 index 000000000000..51347139c1d9 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/pagers.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.translate_v3.types import translation_service + + +class ListGlossariesPager: + """A pager for iterating through ``list_glossaries`` requests. + + This class thinly wraps an initial + :class:`~.translation_service.ListGlossariesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``glossaries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGlossaries`` requests and continue to iterate + through the ``glossaries`` field on the + corresponding responses. + + All the usual :class:`~.translation_service.ListGlossariesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., translation_service.ListGlossariesResponse], + request: translation_service.ListGlossariesRequest, + response: translation_service.ListGlossariesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.translation_service.ListGlossariesRequest`): + The initial request object. + response (:class:`~.translation_service.ListGlossariesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = translation_service.ListGlossariesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[translation_service.ListGlossariesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[translation_service.Glossary]: + for page in self.pages: + yield from page.glossaries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGlossariesAsyncPager: + """A pager for iterating through ``list_glossaries`` requests. + + This class thinly wraps an initial + :class:`~.translation_service.ListGlossariesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``glossaries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGlossaries`` requests and continue to iterate + through the ``glossaries`` field on the + corresponding responses. + + All the usual :class:`~.translation_service.ListGlossariesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[translation_service.ListGlossariesResponse]], + request: translation_service.ListGlossariesRequest, + response: translation_service.ListGlossariesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.translation_service.ListGlossariesRequest`): + The initial request object. + response (:class:`~.translation_service.ListGlossariesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = translation_service.ListGlossariesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[translation_service.ListGlossariesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[translation_service.Glossary]: + async def async_generator(): + async for page in self.pages: + for response in page.glossaries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/__init__.py new file mode 100644 index 000000000000..b977312dd928 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import TranslationServiceTransport +from .grpc import TranslationServiceGrpcTransport +from .grpc_asyncio import TranslationServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[TranslationServiceTransport]] +_transport_registry["grpc"] = TranslationServiceGrpcTransport +_transport_registry["grpc_asyncio"] = TranslationServiceGrpcAsyncIOTransport + + +__all__ = ( + "TranslationServiceTransport", + "TranslationServiceGrpcTransport", + "TranslationServiceGrpcAsyncIOTransport", +) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/base.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/base.py new file mode 100644 index 000000000000..d32c016c761f --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/base.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- + +# 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 abc +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.translate_v3.types import translation_service +from google.longrunning import operations_pb2 as operations # type: ignore + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-translation", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class TranslationServiceTransport(abc.ABC): + """Abstract transport class for TranslationService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ) + + def __init__( + self, + *, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.translate_text: gapic_v1.method.wrap_method( + self.translate_text, default_timeout=None, client_info=_client_info, + ), + self.detect_language: gapic_v1.method.wrap_method( + self.detect_language, default_timeout=None, client_info=_client_info, + ), + self.get_supported_languages: gapic_v1.method.wrap_method( + self.get_supported_languages, + default_timeout=None, + client_info=_client_info, + ), + self.batch_translate_text: gapic_v1.method.wrap_method( + self.batch_translate_text, + default_timeout=None, + client_info=_client_info, + ), + self.create_glossary: gapic_v1.method.wrap_method( + self.create_glossary, default_timeout=None, client_info=_client_info, + ), + self.list_glossaries: gapic_v1.method.wrap_method( + self.list_glossaries, default_timeout=None, client_info=_client_info, + ), + self.get_glossary: gapic_v1.method.wrap_method( + self.get_glossary, default_timeout=None, client_info=_client_info, + ), + self.delete_glossary: gapic_v1.method.wrap_method( + self.delete_glossary, default_timeout=None, client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def translate_text( + self, + ) -> typing.Callable[ + [translation_service.TranslateTextRequest], + typing.Union[ + translation_service.TranslateTextResponse, + typing.Awaitable[translation_service.TranslateTextResponse], + ], + ]: + raise NotImplementedError() + + @property + def detect_language( + self, + ) -> typing.Callable[ + [translation_service.DetectLanguageRequest], + typing.Union[ + translation_service.DetectLanguageResponse, + typing.Awaitable[translation_service.DetectLanguageResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_supported_languages( + self, + ) -> typing.Callable[ + [translation_service.GetSupportedLanguagesRequest], + typing.Union[ + translation_service.SupportedLanguages, + typing.Awaitable[translation_service.SupportedLanguages], + ], + ]: + raise NotImplementedError() + + @property + def batch_translate_text( + self, + ) -> typing.Callable[ + [translation_service.BatchTranslateTextRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def create_glossary( + self, + ) -> typing.Callable[ + [translation_service.CreateGlossaryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def list_glossaries( + self, + ) -> typing.Callable[ + [translation_service.ListGlossariesRequest], + typing.Union[ + translation_service.ListGlossariesResponse, + typing.Awaitable[translation_service.ListGlossariesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_glossary( + self, + ) -> typing.Callable[ + [translation_service.GetGlossaryRequest], + typing.Union[ + translation_service.Glossary, typing.Awaitable[translation_service.Glossary] + ], + ]: + raise NotImplementedError() + + @property + def delete_glossary( + self, + ) -> typing.Callable[ + [translation_service.DeleteGlossaryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("TranslationServiceTransport",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/grpc.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/grpc.py new file mode 100644 index 000000000000..f8ee5ef542e0 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/grpc.py @@ -0,0 +1,463 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.translate_v3.types import translation_service +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import TranslationServiceTransport + + +class TranslationServiceGrpcTransport(TranslationServiceTransport): + """gRPC backend transport for TranslationService. + + Provides natural language translation operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def translate_text( + self, + ) -> Callable[ + [translation_service.TranslateTextRequest], + translation_service.TranslateTextResponse, + ]: + r"""Return a callable for the translate text method over gRPC. + + Translates input text and returns translated text. + + Returns: + Callable[[~.TranslateTextRequest], + ~.TranslateTextResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "translate_text" not in self._stubs: + self._stubs["translate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/TranslateText", + request_serializer=translation_service.TranslateTextRequest.serialize, + response_deserializer=translation_service.TranslateTextResponse.deserialize, + ) + return self._stubs["translate_text"] + + @property + def detect_language( + self, + ) -> Callable[ + [translation_service.DetectLanguageRequest], + translation_service.DetectLanguageResponse, + ]: + r"""Return a callable for the detect language method over gRPC. + + Detects the language of text within a request. + + Returns: + Callable[[~.DetectLanguageRequest], + ~.DetectLanguageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "detect_language" not in self._stubs: + self._stubs["detect_language"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/DetectLanguage", + request_serializer=translation_service.DetectLanguageRequest.serialize, + response_deserializer=translation_service.DetectLanguageResponse.deserialize, + ) + return self._stubs["detect_language"] + + @property + def get_supported_languages( + self, + ) -> Callable[ + [translation_service.GetSupportedLanguagesRequest], + translation_service.SupportedLanguages, + ]: + r"""Return a callable for the get supported languages method over gRPC. + + Returns a list of supported languages for + translation. + + Returns: + Callable[[~.GetSupportedLanguagesRequest], + ~.SupportedLanguages]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_supported_languages" not in self._stubs: + self._stubs["get_supported_languages"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/GetSupportedLanguages", + request_serializer=translation_service.GetSupportedLanguagesRequest.serialize, + response_deserializer=translation_service.SupportedLanguages.deserialize, + ) + return self._stubs["get_supported_languages"] + + @property + def batch_translate_text( + self, + ) -> Callable[ + [translation_service.BatchTranslateTextRequest], operations.Operation + ]: + r"""Return a callable for the batch translate text method over gRPC. + + Translates a large volume of text in asynchronous + batch mode. This function provides real-time output as + the inputs are being processed. If caller cancels a + request, the partial results (for an input file, it's + all or nothing) may still be available on the specified + output location. + This call returns immediately and you can + use google.longrunning.Operation.name to poll the status + of the call. + + Returns: + Callable[[~.BatchTranslateTextRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_translate_text" not in self._stubs: + self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/BatchTranslateText", + request_serializer=translation_service.BatchTranslateTextRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["batch_translate_text"] + + @property + def create_glossary( + self, + ) -> Callable[[translation_service.CreateGlossaryRequest], operations.Operation]: + r"""Return a callable for the create glossary method over gRPC. + + Creates a glossary and returns the long-running operation. + Returns NOT_FOUND, if the project doesn't exist. + + Returns: + Callable[[~.CreateGlossaryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_glossary" not in self._stubs: + self._stubs["create_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/CreateGlossary", + request_serializer=translation_service.CreateGlossaryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["create_glossary"] + + @property + def list_glossaries( + self, + ) -> Callable[ + [translation_service.ListGlossariesRequest], + translation_service.ListGlossariesResponse, + ]: + r"""Return a callable for the list glossaries method over gRPC. + + Lists glossaries in a project. Returns NOT_FOUND, if the project + doesn't exist. + + Returns: + Callable[[~.ListGlossariesRequest], + ~.ListGlossariesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_glossaries" not in self._stubs: + self._stubs["list_glossaries"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/ListGlossaries", + request_serializer=translation_service.ListGlossariesRequest.serialize, + response_deserializer=translation_service.ListGlossariesResponse.deserialize, + ) + return self._stubs["list_glossaries"] + + @property + def get_glossary( + self, + ) -> Callable[ + [translation_service.GetGlossaryRequest], translation_service.Glossary + ]: + r"""Return a callable for the get glossary method over gRPC. + + Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + exist. + + Returns: + Callable[[~.GetGlossaryRequest], + ~.Glossary]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_glossary" not in self._stubs: + self._stubs["get_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/GetGlossary", + request_serializer=translation_service.GetGlossaryRequest.serialize, + response_deserializer=translation_service.Glossary.deserialize, + ) + return self._stubs["get_glossary"] + + @property + def delete_glossary( + self, + ) -> Callable[[translation_service.DeleteGlossaryRequest], operations.Operation]: + r"""Return a callable for the delete glossary method over gRPC. + + Deletes a glossary, or cancels glossary construction if the + glossary isn't created yet. Returns NOT_FOUND, if the glossary + doesn't exist. + + Returns: + Callable[[~.DeleteGlossaryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_glossary" not in self._stubs: + self._stubs["delete_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/DeleteGlossary", + request_serializer=translation_service.DeleteGlossaryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["delete_glossary"] + + +__all__ = ("TranslationServiceGrpcTransport",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/grpc_asyncio.py b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..7fb7d890683f --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/services/translation_service/transports/grpc_asyncio.py @@ -0,0 +1,461 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.translate_v3.types import translation_service +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import TranslationServiceTransport +from .grpc import TranslationServiceGrpcTransport + + +class TranslationServiceGrpcAsyncIOTransport(TranslationServiceTransport): + """gRPC AsyncIO backend transport for TranslationService. + + Provides natural language translation operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def translate_text( + self, + ) -> Callable[ + [translation_service.TranslateTextRequest], + Awaitable[translation_service.TranslateTextResponse], + ]: + r"""Return a callable for the translate text method over gRPC. + + Translates input text and returns translated text. + + Returns: + Callable[[~.TranslateTextRequest], + Awaitable[~.TranslateTextResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "translate_text" not in self._stubs: + self._stubs["translate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/TranslateText", + request_serializer=translation_service.TranslateTextRequest.serialize, + response_deserializer=translation_service.TranslateTextResponse.deserialize, + ) + return self._stubs["translate_text"] + + @property + def detect_language( + self, + ) -> Callable[ + [translation_service.DetectLanguageRequest], + Awaitable[translation_service.DetectLanguageResponse], + ]: + r"""Return a callable for the detect language method over gRPC. + + Detects the language of text within a request. + + Returns: + Callable[[~.DetectLanguageRequest], + Awaitable[~.DetectLanguageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "detect_language" not in self._stubs: + self._stubs["detect_language"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/DetectLanguage", + request_serializer=translation_service.DetectLanguageRequest.serialize, + response_deserializer=translation_service.DetectLanguageResponse.deserialize, + ) + return self._stubs["detect_language"] + + @property + def get_supported_languages( + self, + ) -> Callable[ + [translation_service.GetSupportedLanguagesRequest], + Awaitable[translation_service.SupportedLanguages], + ]: + r"""Return a callable for the get supported languages method over gRPC. + + Returns a list of supported languages for + translation. + + Returns: + Callable[[~.GetSupportedLanguagesRequest], + Awaitable[~.SupportedLanguages]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_supported_languages" not in self._stubs: + self._stubs["get_supported_languages"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/GetSupportedLanguages", + request_serializer=translation_service.GetSupportedLanguagesRequest.serialize, + response_deserializer=translation_service.SupportedLanguages.deserialize, + ) + return self._stubs["get_supported_languages"] + + @property + def batch_translate_text( + self, + ) -> Callable[ + [translation_service.BatchTranslateTextRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the batch translate text method over gRPC. + + Translates a large volume of text in asynchronous + batch mode. This function provides real-time output as + the inputs are being processed. If caller cancels a + request, the partial results (for an input file, it's + all or nothing) may still be available on the specified + output location. + This call returns immediately and you can + use google.longrunning.Operation.name to poll the status + of the call. + + Returns: + Callable[[~.BatchTranslateTextRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_translate_text" not in self._stubs: + self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/BatchTranslateText", + request_serializer=translation_service.BatchTranslateTextRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["batch_translate_text"] + + @property + def create_glossary( + self, + ) -> Callable[ + [translation_service.CreateGlossaryRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the create glossary method over gRPC. + + Creates a glossary and returns the long-running operation. + Returns NOT_FOUND, if the project doesn't exist. + + Returns: + Callable[[~.CreateGlossaryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_glossary" not in self._stubs: + self._stubs["create_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/CreateGlossary", + request_serializer=translation_service.CreateGlossaryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["create_glossary"] + + @property + def list_glossaries( + self, + ) -> Callable[ + [translation_service.ListGlossariesRequest], + Awaitable[translation_service.ListGlossariesResponse], + ]: + r"""Return a callable for the list glossaries method over gRPC. + + Lists glossaries in a project. Returns NOT_FOUND, if the project + doesn't exist. + + Returns: + Callable[[~.ListGlossariesRequest], + Awaitable[~.ListGlossariesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_glossaries" not in self._stubs: + self._stubs["list_glossaries"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/ListGlossaries", + request_serializer=translation_service.ListGlossariesRequest.serialize, + response_deserializer=translation_service.ListGlossariesResponse.deserialize, + ) + return self._stubs["list_glossaries"] + + @property + def get_glossary( + self, + ) -> Callable[ + [translation_service.GetGlossaryRequest], + Awaitable[translation_service.Glossary], + ]: + r"""Return a callable for the get glossary method over gRPC. + + Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + exist. + + Returns: + Callable[[~.GetGlossaryRequest], + Awaitable[~.Glossary]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_glossary" not in self._stubs: + self._stubs["get_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/GetGlossary", + request_serializer=translation_service.GetGlossaryRequest.serialize, + response_deserializer=translation_service.Glossary.deserialize, + ) + return self._stubs["get_glossary"] + + @property + def delete_glossary( + self, + ) -> Callable[ + [translation_service.DeleteGlossaryRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the delete glossary method over gRPC. + + Deletes a glossary, or cancels glossary construction if the + glossary isn't created yet. Returns NOT_FOUND, if the glossary + doesn't exist. + + Returns: + Callable[[~.DeleteGlossaryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_glossary" not in self._stubs: + self._stubs["delete_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3.TranslationService/DeleteGlossary", + request_serializer=translation_service.DeleteGlossaryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["delete_glossary"] + + +__all__ = ("TranslationServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/types.py b/packages/google-cloud-translate/google/cloud/translate_v3/types.py deleted file mode 100644 index d95b3650278e..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3/types.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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 absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.translate_v3.proto import translation_service_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 - - -_shared_modules = [ - operations_pb2, - any_pb2, - timestamp_pb2, - status_pb2, -] - -_local_modules = [ - translation_service_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.translate_v3.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/types/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3/types/__init__.py new file mode 100644 index 000000000000..60c0f41d7ae4 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/types/__init__.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from .translation_service import ( + TranslateTextGlossaryConfig, + TranslateTextRequest, + TranslateTextResponse, + Translation, + DetectLanguageRequest, + DetectedLanguage, + DetectLanguageResponse, + GetSupportedLanguagesRequest, + SupportedLanguages, + SupportedLanguage, + GcsSource, + InputConfig, + GcsDestination, + OutputConfig, + BatchTranslateTextRequest, + BatchTranslateMetadata, + BatchTranslateResponse, + GlossaryInputConfig, + Glossary, + CreateGlossaryRequest, + GetGlossaryRequest, + DeleteGlossaryRequest, + ListGlossariesRequest, + ListGlossariesResponse, + CreateGlossaryMetadata, + DeleteGlossaryMetadata, + DeleteGlossaryResponse, +) + + +__all__ = ( + "TranslateTextGlossaryConfig", + "TranslateTextRequest", + "TranslateTextResponse", + "Translation", + "DetectLanguageRequest", + "DetectedLanguage", + "DetectLanguageResponse", + "GetSupportedLanguagesRequest", + "SupportedLanguages", + "SupportedLanguage", + "GcsSource", + "InputConfig", + "GcsDestination", + "OutputConfig", + "BatchTranslateTextRequest", + "BatchTranslateMetadata", + "BatchTranslateResponse", + "GlossaryInputConfig", + "Glossary", + "CreateGlossaryRequest", + "GetGlossaryRequest", + "DeleteGlossaryRequest", + "ListGlossariesRequest", + "ListGlossariesResponse", + "CreateGlossaryMetadata", + "DeleteGlossaryMetadata", + "DeleteGlossaryResponse", +) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/types/translation_service.py b/packages/google-cloud-translate/google/cloud/translate_v3/types/translation_service.py new file mode 100644 index 000000000000..9da6d491dee6 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3/types/translation_service.py @@ -0,0 +1,1028 @@ +# -*- coding: utf-8 -*- + +# 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 proto # type: ignore + + +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.translation.v3", + manifest={ + "TranslateTextGlossaryConfig", + "TranslateTextRequest", + "TranslateTextResponse", + "Translation", + "DetectLanguageRequest", + "DetectedLanguage", + "DetectLanguageResponse", + "GetSupportedLanguagesRequest", + "SupportedLanguages", + "SupportedLanguage", + "GcsSource", + "InputConfig", + "GcsDestination", + "OutputConfig", + "BatchTranslateTextRequest", + "BatchTranslateMetadata", + "BatchTranslateResponse", + "GlossaryInputConfig", + "Glossary", + "CreateGlossaryRequest", + "GetGlossaryRequest", + "DeleteGlossaryRequest", + "ListGlossariesRequest", + "ListGlossariesResponse", + "CreateGlossaryMetadata", + "DeleteGlossaryMetadata", + "DeleteGlossaryResponse", + }, +) + + +class TranslateTextGlossaryConfig(proto.Message): + r"""Configures which glossary should be used for a specific + target language, and defines options for applying that glossary. + + Attributes: + glossary (str): + Required. Specifies the glossary used for this translation. + Use this format: projects/\ */locations/*/glossaries/\* + ignore_case (bool): + Optional. Indicates match is case- + nsensitive. Default value is false if missing. + """ + + glossary = proto.Field(proto.STRING, number=1) + + ignore_case = proto.Field(proto.BOOL, number=2) + + +class TranslateTextRequest(proto.Message): + r"""The request message for synchronous translation. + + Attributes: + contents (Sequence[str]): + Required. The content of the input in string + format. We recommend the total content be less + than 30k codepoints. Use BatchTranslateText for + larger text. + mime_type (str): + Optional. The format of the source text, for + example, "text/html", "text/plain". If left + blank, the MIME type defaults to "text/html". + source_language_code (str): + Optional. The BCP-47 language code of the + input text if known, for example, "en-US" or + "sr-Latn". Supported language codes are listed + in Language Support. If the source language + isn't specified, the API attempts to identify + the source language automatically and returns + the source language within the response. + target_language_code (str): + Required. The BCP-47 language code to use for + translation of the input text, set to one of the + language codes listed in Language Support. + parent (str): + Required. Project or location to make a call. Must refer to + a caller's project. + + Format: ``projects/{project-number-or-id}`` or + ``projects/{project-number-or-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Non-global location is required for requests using AutoML + models or custom glossaries. + + Models and glossaries must be within the same region (have + same location-id), otherwise an INVALID_ARGUMENT (400) error + is returned. + model (str): + Optional. The ``model`` type requested for this translation. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` + + For global (non-regionalized) requests, use ``location-id`` + ``global``. For example, + ``projects/{project-number-or-id}/locations/global/models/general/nmt``. + + If missing, the system decides which google base model to + use. + glossary_config (~.translation_service.TranslateTextGlossaryConfig): + Optional. Glossary to be applied. The glossary must be + within the same region (have the same location-id) as the + model, otherwise an INVALID_ARGUMENT (400) error is + returned. + labels (Sequence[~.translation_service.TranslateTextRequest.LabelsEntry]): + Optional. The labels with user-defined + metadata for the request. + Label keys and values can be no longer than 63 + characters (Unicode codepoints), can only + contain lowercase letters, numeric characters, + underscores and dashes. International characters + are allowed. Label values are optional. Label + keys must start with a letter. + See + https://cloud.google.com/translate/docs/labels + for more information. + """ + + contents = proto.RepeatedField(proto.STRING, number=1) + + mime_type = proto.Field(proto.STRING, number=3) + + source_language_code = proto.Field(proto.STRING, number=4) + + target_language_code = proto.Field(proto.STRING, number=5) + + parent = proto.Field(proto.STRING, number=8) + + model = proto.Field(proto.STRING, number=6) + + glossary_config = proto.Field( + proto.MESSAGE, number=7, message=TranslateTextGlossaryConfig, + ) + + labels = proto.MapField(proto.STRING, proto.STRING, number=10) + + +class TranslateTextResponse(proto.Message): + r""" + + Attributes: + translations (Sequence[~.translation_service.Translation]): + Text translation responses with no glossary applied. This + field has the same length as + [``contents``][google.cloud.translation.v3.TranslateTextRequest.contents]. + glossary_translations (Sequence[~.translation_service.Translation]): + Text translation responses if a glossary is provided in the + request. This can be the same as + [``translations``][google.cloud.translation.v3.TranslateTextResponse.translations] + if no terms apply. This field has the same length as + [``contents``][google.cloud.translation.v3.TranslateTextRequest.contents]. + """ + + translations = proto.RepeatedField(proto.MESSAGE, number=1, message="Translation",) + + glossary_translations = proto.RepeatedField( + proto.MESSAGE, number=3, message="Translation", + ) + + +class Translation(proto.Message): + r"""A single translation response. + + Attributes: + translated_text (str): + Text translated into the target language. + model (str): + Only present when ``model`` is present in the request. + ``model`` here is normalized to have project number. + + For example: If the ``model`` requested in + TranslationTextRequest is + ``projects/{project-id}/locations/{location-id}/models/general/nmt`` + then ``model`` here would be normalized to + ``projects/{project-number}/locations/{location-id}/models/general/nmt``. + detected_language_code (str): + The BCP-47 language code of source text in + the initial request, detected automatically, if + no source language was passed within the initial + request. If the source language was passed, + auto-detection of the language does not occur + and this field is empty. + glossary_config (~.translation_service.TranslateTextGlossaryConfig): + The ``glossary_config`` used for this translation. + """ + + translated_text = proto.Field(proto.STRING, number=1) + + model = proto.Field(proto.STRING, number=2) + + detected_language_code = proto.Field(proto.STRING, number=4) + + glossary_config = proto.Field( + proto.MESSAGE, number=3, message=TranslateTextGlossaryConfig, + ) + + +class DetectLanguageRequest(proto.Message): + r"""The request message for language detection. + + Attributes: + parent (str): + Required. Project or location to make a call. Must refer to + a caller's project. + + Format: + ``projects/{project-number-or-id}/locations/{location-id}`` + or ``projects/{project-number-or-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Only models within the same region (has same location-id) + can be used. Otherwise an INVALID_ARGUMENT (400) error is + returned. + model (str): + Optional. The language detection model to be used. + + Format: + ``projects/{project-number-or-id}/locations/{location-id}/models/language-detection/{model-id}`` + + Only one language detection model is currently supported: + ``projects/{project-number-or-id}/locations/{location-id}/models/language-detection/default``. + + If not specified, the default model is used. + content (str): + The content of the input stored as a string. + mime_type (str): + Optional. The format of the source text, for + example, "text/html", "text/plain". If left + blank, the MIME type defaults to "text/html". + labels (Sequence[~.translation_service.DetectLanguageRequest.LabelsEntry]): + Optional. The labels with user-defined + metadata for the request. + Label keys and values can be no longer than 63 + characters (Unicode codepoints), can only + contain lowercase letters, numeric characters, + underscores and dashes. International characters + are allowed. Label values are optional. Label + keys must start with a letter. + See + https://cloud.google.com/translate/docs/labels + for more information. + """ + + parent = proto.Field(proto.STRING, number=5) + + model = proto.Field(proto.STRING, number=4) + + content = proto.Field(proto.STRING, number=1, oneof="source") + + mime_type = proto.Field(proto.STRING, number=3) + + labels = proto.MapField(proto.STRING, proto.STRING, number=6) + + +class DetectedLanguage(proto.Message): + r"""The response message for language detection. + + Attributes: + language_code (str): + The BCP-47 language code of source content in + the request, detected automatically. + confidence (float): + The confidence of the detection result for + this language. + """ + + language_code = proto.Field(proto.STRING, number=1) + + confidence = proto.Field(proto.FLOAT, number=2) + + +class DetectLanguageResponse(proto.Message): + r"""The response message for language detection. + + Attributes: + languages (Sequence[~.translation_service.DetectedLanguage]): + A list of detected languages sorted by + detection confidence in descending order. The + most probable language first. + """ + + languages = proto.RepeatedField(proto.MESSAGE, number=1, message=DetectedLanguage,) + + +class GetSupportedLanguagesRequest(proto.Message): + r"""The request message for discovering supported languages. + + Attributes: + parent (str): + Required. Project or location to make a call. Must refer to + a caller's project. + + Format: ``projects/{project-number-or-id}`` or + ``projects/{project-number-or-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-number-or-id}/locations/global`` or + ``projects/{project-number-or-id}``. + + Non-global location is required for AutoML models. + + Only models within the same region (have same location-id) + can be used, otherwise an INVALID_ARGUMENT (400) error is + returned. + display_language_code (str): + Optional. The language to use to return + localized, human readable names of supported + languages. If missing, then display names are + not returned in a response. + model (str): + Optional. Get supported languages of this model. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` + + Returns languages supported by the specified model. If + missing, we get supported languages of Google general base + (PBMT) model. + """ + + parent = proto.Field(proto.STRING, number=3) + + display_language_code = proto.Field(proto.STRING, number=1) + + model = proto.Field(proto.STRING, number=2) + + +class SupportedLanguages(proto.Message): + r"""The response message for discovering supported languages. + + Attributes: + languages (Sequence[~.translation_service.SupportedLanguage]): + A list of supported language responses. This + list contains an entry for each language the + Translation API supports. + """ + + languages = proto.RepeatedField( + proto.MESSAGE, number=1, message="SupportedLanguage", + ) + + +class SupportedLanguage(proto.Message): + r"""A single supported language response corresponds to + information related to one supported language. + + Attributes: + language_code (str): + Supported language code, generally consisting + of its ISO 639-1 identifier, for example, 'en', + 'ja'. In certain cases, BCP-47 codes including + language and region identifiers are returned + (for example, 'zh-TW' and 'zh-CN') + display_name (str): + Human readable name of the language localized + in the display language specified in the + request. + support_source (bool): + Can be used as source language. + support_target (bool): + Can be used as target language. + """ + + language_code = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + support_source = proto.Field(proto.BOOL, number=3) + + support_target = proto.Field(proto.BOOL, number=4) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location for the input content. + + Attributes: + input_uri (str): + Required. Source data URI. For example, + ``gs://my_bucket/my_object``. + """ + + input_uri = proto.Field(proto.STRING, number=1) + + +class InputConfig(proto.Message): + r"""Input configuration for BatchTranslateText request. + + Attributes: + mime_type (str): + Optional. Can be "text/plain" or "text/html". For ``.tsv``, + "text/html" is used if mime_type is missing. For ``.html``, + this field must be "text/html" or empty. For ``.txt``, this + field must be "text/plain" or empty. + gcs_source (~.translation_service.GcsSource): + Required. Google Cloud Storage location for the source + input. This can be a single file (for example, + ``gs://translation-test/input.tsv``) or a wildcard (for + example, ``gs://translation-test/*``). If a file extension + is ``.tsv``, it can contain either one or two columns. The + first column (optional) is the id of the text request. If + the first column is missing, we use the row number (0-based) + from the input file as the ID in the output file. The second + column is the actual text to be translated. We recommend + each row be <= 10K Unicode codepoints, otherwise an error + might be returned. Note that the input tsv must be RFC 4180 + compliant. + + You could use https://github.com/Clever/csvlint to check + potential formatting errors in your tsv file. csvlint + --delimiter='\t' your_input_file.tsv + + The other supported file extensions are ``.txt`` or + ``.html``, which is treated as a single large chunk of text. + """ + + mime_type = proto.Field(proto.STRING, number=1) + + gcs_source = proto.Field( + proto.MESSAGE, number=2, oneof="source", message=GcsSource, + ) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location for the output content. + + Attributes: + output_uri_prefix (str): + Required. There must be no files under 'output_uri_prefix'. + 'output_uri_prefix' must end with "/" and start with + "gs://", otherwise an INVALID_ARGUMENT (400) error is + returned. + """ + + output_uri_prefix = proto.Field(proto.STRING, number=1) + + +class OutputConfig(proto.Message): + r"""Output configuration for BatchTranslateText request. + + Attributes: + gcs_destination (~.translation_service.GcsDestination): + Google Cloud Storage destination for output content. For + every single input file (for example, + gs://a/b/c.[extension]), we generate at most 2 \* n output + files. (n is the # of target_language_codes in the + BatchTranslateTextRequest). + + Output files (tsv) generated are compliant with RFC 4180 + except that record delimiters are '\n' instead of '\r\n'. We + don't provide any way to change record delimiters. + + While the input files are being processed, we write/update + an index file 'index.csv' under 'output_uri_prefix' (for + example, gs://translation-test/index.csv) The index file is + generated/updated as new files are being translated. The + format is: + + input_file,target_language_code,translations_file,errors_file, + glossary_translations_file,glossary_errors_file + + input_file is one file we matched using + gcs_source.input_uri. target_language_code is provided in + the request. translations_file contains the translations. + (details provided below) errors_file contains the errors + during processing of the file. (details below). Both + translations_file and errors_file could be empty strings if + we have no content to output. glossary_translations_file and + glossary_errors_file are always empty strings if the + input_file is tsv. They could also be empty if we have no + content to output. + + Once a row is present in index.csv, the input/output + matching never changes. Callers should also expect all the + content in input_file are processed and ready to be consumed + (that is, no partial output file is written). + + The format of translations_file (for target language code + 'trg') is: + ``gs://translation_test/a_b_c\_'trg'_translations.[extension]`` + + If the input file extension is tsv, the output has the + following columns: Column 1: ID of the request provided in + the input, if it's not provided in the input, then the input + row number is used (0-based). Column 2: source sentence. + Column 3: translation without applying a glossary. Empty + string if there is an error. Column 4 (only present if a + glossary is provided in the request): translation after + applying the glossary. Empty string if there is an error + applying the glossary. Could be same string as column 3 if + there is no glossary applied. + + If input file extension is a txt or html, the translation is + directly written to the output file. If glossary is + requested, a separate glossary_translations_file has format + of + ``gs://translation_test/a_b_c\_'trg'_glossary_translations.[extension]`` + + The format of errors file (for target language code 'trg') + is: ``gs://translation_test/a_b_c\_'trg'_errors.[extension]`` + + If the input file extension is tsv, errors_file contains the + following: Column 1: ID of the request provided in the + input, if it's not provided in the input, then the input row + number is used (0-based). Column 2: source sentence. Column + 3: Error detail for the translation. Could be empty. Column + 4 (only present if a glossary is provided in the request): + Error when applying the glossary. + + If the input file extension is txt or html, + glossary_error_file will be generated that contains error + details. glossary_error_file has format of + ``gs://translation_test/a_b_c\_'trg'_glossary_errors.[extension]`` + """ + + gcs_destination = proto.Field( + proto.MESSAGE, number=1, oneof="destination", message=GcsDestination, + ) + + +class BatchTranslateTextRequest(proto.Message): + r"""The batch translation request. + + Attributes: + parent (str): + Required. Location to make a call. Must refer to a caller's + project. + + Format: + ``projects/{project-number-or-id}/locations/{location-id}``. + + The ``global`` location is not supported for batch + translation. + + Only AutoML Translation models or glossaries within the same + region (have the same location-id) can be used, otherwise an + INVALID_ARGUMENT (400) error is returned. + source_language_code (str): + Required. Source language code. + target_language_codes (Sequence[str]): + Required. Specify up to 10 language codes + here. + models (Sequence[~.translation_service.BatchTranslateTextRequest.ModelsEntry]): + Optional. The models to use for translation. Map's key is + target language code. Map's value is model name. Value can + be a built-in general model, or an AutoML Translation model. + + The value format depends on model type: + + - AutoML Translation models: + ``projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-number-or-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-number-or-id}/locations/{location-id}/models/general/base`` + + If the map is empty or a specific model is not requested for + a language pair, then default google model (nmt) is used. + input_configs (Sequence[~.translation_service.InputConfig]): + Required. Input configurations. + The total number of files matched should be <= + 1000. The total content size should be <= 100M + Unicode codepoints. The files must use UTF-8 + encoding. + output_config (~.translation_service.OutputConfig): + Required. Output configuration. + If 2 input configs match to the same file (that + is, same input path), we don't generate output + for duplicate inputs. + glossaries (Sequence[~.translation_service.BatchTranslateTextRequest.GlossariesEntry]): + Optional. Glossaries to be applied for + translation. It's keyed by target language code. + labels (Sequence[~.translation_service.BatchTranslateTextRequest.LabelsEntry]): + Optional. The labels with user-defined + metadata for the request. + Label keys and values can be no longer than 63 + characters (Unicode codepoints), can only + contain lowercase letters, numeric characters, + underscores and dashes. International characters + are allowed. Label values are optional. Label + keys must start with a letter. + See + https://cloud.google.com/translate/docs/labels + for more information. + """ + + parent = proto.Field(proto.STRING, number=1) + + source_language_code = proto.Field(proto.STRING, number=2) + + target_language_codes = proto.RepeatedField(proto.STRING, number=3) + + models = proto.MapField(proto.STRING, proto.STRING, number=4) + + input_configs = proto.RepeatedField(proto.MESSAGE, number=5, message=InputConfig,) + + output_config = proto.Field(proto.MESSAGE, number=6, message=OutputConfig,) + + glossaries = proto.MapField( + proto.STRING, proto.MESSAGE, number=7, message=TranslateTextGlossaryConfig, + ) + + labels = proto.MapField(proto.STRING, proto.STRING, number=9) + + +class BatchTranslateMetadata(proto.Message): + r"""State metadata for the batch translation operation. + + Attributes: + state (~.translation_service.BatchTranslateMetadata.State): + The state of the operation. + translated_characters (int): + Number of successfully translated characters + so far (Unicode codepoints). + failed_characters (int): + Number of characters that have failed to + process so far (Unicode codepoints). + total_characters (int): + Total number of characters (Unicode + codepoints). This is the total number of + codepoints from input files times the number of + target languages and appears here shortly after + the call is submitted. + submit_time (~.timestamp.Timestamp): + Time when the operation was submitted. + """ + + class State(proto.Enum): + r"""State of the job.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLING = 4 + CANCELLED = 5 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + translated_characters = proto.Field(proto.INT64, number=2) + + failed_characters = proto.Field(proto.INT64, number=3) + + total_characters = proto.Field(proto.INT64, number=4) + + submit_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + +class BatchTranslateResponse(proto.Message): + r"""Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by BatchTranslateText if at least one sentence is + translated successfully. + + Attributes: + total_characters (int): + Total number of characters (Unicode + codepoints). + translated_characters (int): + Number of successfully translated characters + (Unicode codepoints). + failed_characters (int): + Number of characters that have failed to + process (Unicode codepoints). + submit_time (~.timestamp.Timestamp): + Time when the operation was submitted. + end_time (~.timestamp.Timestamp): + The time when the operation is finished and + [google.longrunning.Operation.done][google.longrunning.Operation.done] + is set to true. + """ + + total_characters = proto.Field(proto.INT64, number=1) + + translated_characters = proto.Field(proto.INT64, number=2) + + failed_characters = proto.Field(proto.INT64, number=3) + + submit_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + +class GlossaryInputConfig(proto.Message): + r"""Input configuration for glossaries. + + Attributes: + gcs_source (~.translation_service.GcsSource): + Required. Google Cloud Storage location of glossary data. + File format is determined based on the filename extension. + API returns [google.rpc.Code.INVALID_ARGUMENT] for + unsupported URI-s and file formats. Wildcards are not + allowed. This must be a single file in one of the following + formats: + + For unidirectional glossaries: + + - TSV/CSV (``.tsv``/``.csv``): 2 column file, tab- or + comma-separated. The first column is source text. The + second column is target text. The file must not contain + headers. That is, the first row is data, not column + names. + + - TMX (``.tmx``): TMX file with parallel data defining + source/target term pairs. + + For equivalent term sets glossaries: + + - CSV (``.csv``): Multi-column CSV file defining equivalent + glossary terms in multiple languages. The format is + defined for Google Translation Toolkit and documented in + `Use a + glossary `__. + """ + + gcs_source = proto.Field( + proto.MESSAGE, number=1, oneof="source", message=GcsSource, + ) + + +class Glossary(proto.Message): + r"""Represents a glossary built from user provided data. + + Attributes: + name (str): + Required. The resource name of the glossary. Glossary names + have the form + ``projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}``. + language_pair (~.translation_service.Glossary.LanguageCodePair): + Used with unidirectional glossaries. + language_codes_set (~.translation_service.Glossary.LanguageCodesSet): + Used with equivalent term set glossaries. + input_config (~.translation_service.GlossaryInputConfig): + Required. Provides examples to build the + glossary from. Total glossary must not exceed + 10M Unicode codepoints. + entry_count (int): + Output only. The number of entries defined in + the glossary. + submit_time (~.timestamp.Timestamp): + Output only. When CreateGlossary was called. + end_time (~.timestamp.Timestamp): + Output only. When the glossary creation was + finished. + """ + + class LanguageCodePair(proto.Message): + r"""Used with unidirectional glossaries. + + Attributes: + source_language_code (str): + Required. The BCP-47 language code of the input text, for + example, "en-US". Expected to be an exact match for + GlossaryTerm.language_code. + target_language_code (str): + Required. The BCP-47 language code for translation output, + for example, "zh-CN". Expected to be an exact match for + GlossaryTerm.language_code. + """ + + source_language_code = proto.Field(proto.STRING, number=1) + + target_language_code = proto.Field(proto.STRING, number=2) + + class LanguageCodesSet(proto.Message): + r"""Used with equivalent term set glossaries. + + Attributes: + language_codes (Sequence[str]): + The BCP-47 language code(s) for terms defined in the + glossary. All entries are unique. The list contains at least + two entries. Expected to be an exact match for + GlossaryTerm.language_code. + """ + + language_codes = proto.RepeatedField(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + language_pair = proto.Field( + proto.MESSAGE, number=3, oneof="languages", message=LanguageCodePair, + ) + + language_codes_set = proto.Field( + proto.MESSAGE, number=4, oneof="languages", message=LanguageCodesSet, + ) + + input_config = proto.Field(proto.MESSAGE, number=5, message=GlossaryInputConfig,) + + entry_count = proto.Field(proto.INT32, number=6) + + submit_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) + + +class CreateGlossaryRequest(proto.Message): + r"""Request message for CreateGlossary. + + Attributes: + parent (str): + Required. The project name. + glossary (~.translation_service.Glossary): + Required. The glossary to create. + """ + + parent = proto.Field(proto.STRING, number=1) + + glossary = proto.Field(proto.MESSAGE, number=2, message=Glossary,) + + +class GetGlossaryRequest(proto.Message): + r"""Request message for GetGlossary. + + Attributes: + name (str): + Required. The name of the glossary to + retrieve. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DeleteGlossaryRequest(proto.Message): + r"""Request message for DeleteGlossary. + + Attributes: + name (str): + Required. The name of the glossary to delete. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ListGlossariesRequest(proto.Message): + r"""Request message for ListGlossaries. + + Attributes: + parent (str): + Required. The name of the project from which + to list all of the glossaries. + page_size (int): + Optional. Requested page size. The server may + return fewer glossaries than requested. If + unspecified, the server picks an appropriate + default. + page_token (str): + Optional. A token identifying a page of results the server + should return. Typically, this is the value of + [ListGlossariesResponse.next_page_token] returned from the + previous call to ``ListGlossaries`` method. The first page + is returned if ``page_token``\ is empty or missing. + filter (str): + Optional. Filter specifying constraints of a + list operation. Filtering is not supported yet, + and the parameter currently has no effect. If + missing, no filtering is performed. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=4) + + +class ListGlossariesResponse(proto.Message): + r"""Response message for ListGlossaries. + + Attributes: + glossaries (Sequence[~.translation_service.Glossary]): + The list of glossaries for a project. + next_page_token (str): + A token to retrieve a page of results. Pass this value in + the [ListGlossariesRequest.page_token] field in the + subsequent call to ``ListGlossaries`` method to retrieve the + next page of results. + """ + + @property + def raw_page(self): + return self + + glossaries = proto.RepeatedField(proto.MESSAGE, number=1, message=Glossary,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class CreateGlossaryMetadata(proto.Message): + r"""Stored in the + [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata] + field returned by CreateGlossary. + + Attributes: + name (str): + The name of the glossary that is being + created. + state (~.translation_service.CreateGlossaryMetadata.State): + The current state of the glossary creation + operation. + submit_time (~.timestamp.Timestamp): + The time when the operation was submitted to + the server. + """ + + class State(proto.Enum): + r"""Enumerates the possible states that the creation request can + be in. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLING = 4 + CANCELLED = 5 + + name = proto.Field(proto.STRING, number=1) + + state = proto.Field(proto.ENUM, number=2, enum=State,) + + submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class DeleteGlossaryMetadata(proto.Message): + r"""Stored in the + [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata] + field returned by DeleteGlossary. + + Attributes: + name (str): + The name of the glossary that is being + deleted. + state (~.translation_service.DeleteGlossaryMetadata.State): + The current state of the glossary deletion + operation. + submit_time (~.timestamp.Timestamp): + The time when the operation was submitted to + the server. + """ + + class State(proto.Enum): + r"""Enumerates the possible states that the creation request can + be in. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLING = 4 + CANCELLED = 5 + + name = proto.Field(proto.STRING, number=1) + + state = proto.Field(proto.ENUM, number=2, enum=State,) + + submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class DeleteGlossaryResponse(proto.Message): + r"""Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by DeleteGlossary. + + Attributes: + name (str): + The name of the deleted glossary. + submit_time (~.timestamp.Timestamp): + The time when the operation was submitted to + the server. + end_time (~.timestamp.Timestamp): + The time when the glossary deletion is finished and + [google.longrunning.Operation.done][google.longrunning.Operation.done] + is set to true. + """ + + name = proto.Field(proto.STRING, number=1) + + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/__init__.py index bebafdf306a7..b7cd2fe07916 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/__init__.py +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/__init__.py @@ -1,42 +1,77 @@ # -*- coding: utf-8 -*- -# + # 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 absolute_import -import sys -import warnings - -from google.cloud.translate_v3beta1 import types -from google.cloud.translate_v3beta1.gapic import translation_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class TranslationServiceClient(translation_service_client.TranslationServiceClient): - __doc__ = translation_service_client.TranslationServiceClient.__doc__ +from .services.translation_service import TranslationServiceClient +from .types.translation_service import BatchTranslateMetadata +from .types.translation_service import BatchTranslateResponse +from .types.translation_service import BatchTranslateTextRequest +from .types.translation_service import CreateGlossaryMetadata +from .types.translation_service import CreateGlossaryRequest +from .types.translation_service import DeleteGlossaryMetadata +from .types.translation_service import DeleteGlossaryRequest +from .types.translation_service import DeleteGlossaryResponse +from .types.translation_service import DetectLanguageRequest +from .types.translation_service import DetectLanguageResponse +from .types.translation_service import DetectedLanguage +from .types.translation_service import GcsDestination +from .types.translation_service import GcsSource +from .types.translation_service import GetGlossaryRequest +from .types.translation_service import GetSupportedLanguagesRequest +from .types.translation_service import Glossary +from .types.translation_service import GlossaryInputConfig +from .types.translation_service import InputConfig +from .types.translation_service import ListGlossariesRequest +from .types.translation_service import ListGlossariesResponse +from .types.translation_service import OutputConfig +from .types.translation_service import SupportedLanguage +from .types.translation_service import SupportedLanguages +from .types.translation_service import TranslateTextGlossaryConfig +from .types.translation_service import TranslateTextRequest +from .types.translation_service import TranslateTextResponse +from .types.translation_service import Translation __all__ = ( - "types", + "BatchTranslateMetadata", + "BatchTranslateResponse", + "BatchTranslateTextRequest", + "CreateGlossaryMetadata", + "CreateGlossaryRequest", + "DeleteGlossaryMetadata", + "DeleteGlossaryRequest", + "DeleteGlossaryResponse", + "DetectLanguageRequest", + "DetectLanguageResponse", + "DetectedLanguage", + "GcsDestination", + "GcsSource", + "GetGlossaryRequest", + "GetSupportedLanguagesRequest", + "Glossary", + "GlossaryInputConfig", + "InputConfig", + "ListGlossariesRequest", + "ListGlossariesResponse", + "OutputConfig", + "SupportedLanguage", + "SupportedLanguages", + "TranslateTextGlossaryConfig", + "TranslateTextRequest", + "TranslateTextResponse", + "Translation", "TranslationServiceClient", ) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py deleted file mode 100644 index 15668dfd647f..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/translation_service_client.py +++ /dev/null @@ -1,1096 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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. - -"""Accesses the google.cloud.translation.v3beta1 TranslationService API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import google.api_core.protobuf_helpers -import grpc - -from google.cloud.translate_v3beta1.gapic import translation_service_client_config -from google.cloud.translate_v3beta1.gapic.transports import ( - translation_service_grpc_transport, -) -from google.cloud.translate_v3beta1.proto import translation_service_pb2 -from google.cloud.translate_v3beta1.proto import translation_service_pb2_grpc -from google.longrunning import operations_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-translate", -).version - - -class TranslationServiceClient(object): - """Provides natural language translation operations.""" - - SERVICE_ADDRESS = "translate.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.translation.v3beta1.TranslationService" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - TranslationServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def glossary_path(cls, project, location, glossary): - """Return a fully-qualified glossary string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/glossaries/{glossary}", - project=project, - location=location, - glossary=glossary, - ) - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.TranslationServiceGrpcTransport, - Callable[[~.Credentials, type], ~.TranslationServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = translation_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=translation_service_grpc_transport.TranslationServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = translation_service_grpc_transport.TranslationServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def translate_text( - self, - contents, - target_language_code, - parent, - mime_type=None, - source_language_code=None, - model=None, - glossary_config=None, - labels=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Translates input text and returns translated text. - - Example: - >>> from google.cloud import translate_v3beta1 - >>> - >>> client = translate_v3beta1.TranslationServiceClient() - >>> - >>> # TODO: Initialize `contents`: - >>> contents = [] - >>> - >>> # TODO: Initialize `target_language_code`: - >>> target_language_code = '' - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> response = client.translate_text(contents, target_language_code, parent) - - Args: - contents (list[str]): Required. The content of the input in string format. - We recommend the total content be less than 30k codepoints. - Use BatchTranslateText for larger text. - target_language_code (str): Required. The BCP-47 language code to use for translation of the input - text, set to one of the language codes listed in Language Support. - parent (str): Required. Project or location to make a call. Must refer to a - caller's project. - - Format: ``projects/{project-id}`` or - ``projects/{project-id}/locations/{location-id}``. - - For global calls, use ``projects/{project-id}/locations/global`` or - ``projects/{project-id}``. - - Non-global location is required for requests using AutoML models or - custom glossaries. - - Models and glossaries must be within the same region (have same - location-id), otherwise an INVALID_ARGUMENT (400) error is returned. - mime_type (str): Optional. The format of the source text, for example, "text/html", - "text/plain". If left blank, the MIME type defaults to "text/html". - source_language_code (str): Optional. The BCP-47 language code of the input text if - known, for example, "en-US" or "sr-Latn". Supported language codes are - listed in Language Support. If the source language isn't specified, the API - attempts to identify the source language automatically and returns the - source language within the response. - model (str): Optional. The ``model`` type requested for this translation. - - The format depends on model type: - - - AutoML Translation models: - ``projects/{project-id}/locations/{location-id}/models/{model-id}`` - - - General (built-in) models: - ``projects/{project-id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-id}/locations/{location-id}/models/general/base`` - - For global (non-regionalized) requests, use ``location-id`` ``global``. - For example, - ``projects/{project-id}/locations/global/models/general/nmt``. - - If missing, the system decides which google base model to use. - glossary_config (Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary must be within the - same region (have the same location-id) as the model, otherwise an - INVALID_ARGUMENT (400) error is returned. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig` - labels (dict[str -> str]): Optional. The labels with user-defined metadata for the request. - - Label keys and values can be no longer than 63 characters - (Unicode codepoints), can only contain lowercase letters, numeric - characters, underscores and dashes. International characters are allowed. - Label values are optional. Label keys must start with a letter. - - See https://cloud.google.com/translate/docs/labels for more information. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3beta1.types.TranslateTextResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "translate_text" not in self._inner_api_calls: - self._inner_api_calls[ - "translate_text" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.translate_text, - default_retry=self._method_configs["TranslateText"].retry, - default_timeout=self._method_configs["TranslateText"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.TranslateTextRequest( - contents=contents, - target_language_code=target_language_code, - parent=parent, - mime_type=mime_type, - source_language_code=source_language_code, - model=model, - glossary_config=glossary_config, - labels=labels, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["translate_text"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def detect_language( - self, - parent, - model=None, - content=None, - mime_type=None, - labels=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Detects the language of text within a request. - - Example: - >>> from google.cloud import translate_v3beta1 - >>> - >>> client = translate_v3beta1.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> response = client.detect_language(parent) - - Args: - parent (str): Required. Project or location to make a call. Must refer to a - caller's project. - - Format: ``projects/{project-id}/locations/{location-id}`` or - ``projects/{project-id}``. - - For global calls, use ``projects/{project-id}/locations/global`` or - ``projects/{project-id}``. - - Only models within the same region (has same location-id) can be used. - Otherwise an INVALID_ARGUMENT (400) error is returned. - model (str): Optional. The language detection model to be used. - - Format: - ``projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}`` - - Only one language detection model is currently supported: - ``projects/{project-id}/locations/{location-id}/models/language-detection/default``. - - If not specified, the default model is used. - content (str): The content of the input stored as a string. - mime_type (str): Optional. The format of the source text, for example, "text/html", - "text/plain". If left blank, the MIME type defaults to "text/html". - labels (dict[str -> str]): Optional. The labels with user-defined metadata for the request. - - Label keys and values can be no longer than 63 characters - (Unicode codepoints), can only contain lowercase letters, numeric - characters, underscores and dashes. International characters are allowed. - Label values are optional. Label keys must start with a letter. - - See https://cloud.google.com/translate/docs/labels for more information. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3beta1.types.DetectLanguageResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "detect_language" not in self._inner_api_calls: - self._inner_api_calls[ - "detect_language" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.detect_language, - default_retry=self._method_configs["DetectLanguage"].retry, - default_timeout=self._method_configs["DetectLanguage"].timeout, - client_info=self._client_info, - ) - - # Sanity check: We have some fields which are mutually exclusive; - # raise ValueError if more than one is sent. - google.api_core.protobuf_helpers.check_oneof(content=content,) - - request = translation_service_pb2.DetectLanguageRequest( - parent=parent, - model=model, - content=content, - mime_type=mime_type, - labels=labels, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["detect_language"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_supported_languages( - self, - parent, - display_language_code=None, - model=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns a list of supported languages for translation. - - Example: - >>> from google.cloud import translate_v3beta1 - >>> - >>> client = translate_v3beta1.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> response = client.get_supported_languages(parent) - - Args: - parent (str): Required. Project or location to make a call. Must refer to a - caller's project. - - Format: ``projects/{project-id}`` or - ``projects/{project-id}/locations/{location-id}``. - - For global calls, use ``projects/{project-id}/locations/global`` or - ``projects/{project-id}``. - - Non-global location is required for AutoML models. - - Only models within the same region (have same location-id) can be used, - otherwise an INVALID_ARGUMENT (400) error is returned. - display_language_code (str): Optional. The language to use to return localized, human readable names - of supported languages. If missing, then display names are not returned - in a response. - model (str): Optional. Get supported languages of this model. - - The format depends on model type: - - - AutoML Translation models: - ``projects/{project-id}/locations/{location-id}/models/{model-id}`` - - - General (built-in) models: - ``projects/{project-id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-id}/locations/{location-id}/models/general/base`` - - Returns languages supported by the specified model. If missing, we get - supported languages of Google general base (PBMT) model. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3beta1.types.SupportedLanguages` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_supported_languages" not in self._inner_api_calls: - self._inner_api_calls[ - "get_supported_languages" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_supported_languages, - default_retry=self._method_configs["GetSupportedLanguages"].retry, - default_timeout=self._method_configs["GetSupportedLanguages"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.GetSupportedLanguagesRequest( - parent=parent, display_language_code=display_language_code, model=model, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_supported_languages"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def batch_translate_text( - self, - parent, - source_language_code, - target_language_codes, - input_configs, - output_config, - models=None, - glossaries=None, - labels=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Translates a large volume of text in asynchronous batch mode. - This function provides real-time output as the inputs are being processed. - If caller cancels a request, the partial results (for an input file, it's - all or nothing) may still be available on the specified output location. - - This call returns immediately and you can - use google.longrunning.Operation.name to poll the status of the call. - - Example: - >>> from google.cloud import translate_v3beta1 - >>> - >>> client = translate_v3beta1.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `source_language_code`: - >>> source_language_code = '' - >>> - >>> # TODO: Initialize `target_language_codes`: - >>> target_language_codes = [] - >>> - >>> # TODO: Initialize `input_configs`: - >>> input_configs = [] - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.batch_translate_text(parent, source_language_code, target_language_codes, input_configs, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. Location to make a call. Must refer to a caller's project. - - Format: ``projects/{project-id}/locations/{location-id}``. - - The ``global`` location is not supported for batch translation. - - Only AutoML Translation models or glossaries within the same region - (have the same location-id) can be used, otherwise an INVALID_ARGUMENT - (400) error is returned. - source_language_code (str): Required. Source language code. - target_language_codes (list[str]): Required. Specify up to 10 language codes here. - input_configs (list[Union[dict, ~google.cloud.translate_v3beta1.types.InputConfig]]): Required. Input configurations. - The total number of files matched should be <= 1000. - The total content size should be <= 100M Unicode codepoints. - The files must use UTF-8 encoding. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3beta1.types.InputConfig` - output_config (Union[dict, ~google.cloud.translate_v3beta1.types.OutputConfig]): Required. Output configuration. - If 2 input configs match to the same file (that is, same input path), - we don't generate output for duplicate inputs. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3beta1.types.OutputConfig` - models (dict[str -> str]): Optional. The models to use for translation. Map's key is target - language code. Map's value is model name. Value can be a built-in - general model, or an AutoML Translation model. - - The value format depends on model type: - - - AutoML Translation models: - ``projects/{project-id}/locations/{location-id}/models/{model-id}`` - - - General (built-in) models: - ``projects/{project-id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-id}/locations/{location-id}/models/general/base`` - - If the map is empty or a specific model is not requested for a language - pair, then default google model (nmt) is used. - glossaries (dict[str -> Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]]): Optional. Glossaries to be applied for translation. - It's keyed by target language code. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig` - labels (dict[str -> str]): Optional. The labels with user-defined metadata for the request. - - Label keys and values can be no longer than 63 characters - (Unicode codepoints), can only contain lowercase letters, numeric - characters, underscores and dashes. International characters are allowed. - Label values are optional. Label keys must start with a letter. - - See https://cloud.google.com/translate/docs/labels for more information. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_translate_text" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_translate_text" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_translate_text, - default_retry=self._method_configs["BatchTranslateText"].retry, - default_timeout=self._method_configs["BatchTranslateText"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.BatchTranslateTextRequest( - parent=parent, - source_language_code=source_language_code, - target_language_codes=target_language_codes, - input_configs=input_configs, - output_config=output_config, - models=models, - glossaries=glossaries, - labels=labels, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["batch_translate_text"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - translation_service_pb2.BatchTranslateResponse, - metadata_type=translation_service_pb2.BatchTranslateMetadata, - ) - - def create_glossary( - self, - parent, - glossary, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a glossary and returns the long-running operation. Returns - NOT_FOUND, if the project doesn't exist. - - Example: - >>> from google.cloud import translate_v3beta1 - >>> - >>> client = translate_v3beta1.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `glossary`: - >>> glossary = {} - >>> - >>> response = client.create_glossary(parent, glossary) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The project name. - glossary (Union[dict, ~google.cloud.translate_v3beta1.types.Glossary]): Required. The glossary to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.translate_v3beta1.types.Glossary` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_glossary" not in self._inner_api_calls: - self._inner_api_calls[ - "create_glossary" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_glossary, - default_retry=self._method_configs["CreateGlossary"].retry, - default_timeout=self._method_configs["CreateGlossary"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.CreateGlossaryRequest( - parent=parent, glossary=glossary, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["create_glossary"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - translation_service_pb2.Glossary, - metadata_type=translation_service_pb2.CreateGlossaryMetadata, - ) - - def list_glossaries( - self, - parent, - page_size=None, - filter_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists glossaries in a project. Returns NOT_FOUND, if the project - doesn't exist. - - Example: - >>> from google.cloud import translate_v3beta1 - >>> - >>> client = translate_v3beta1.TranslationServiceClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_glossaries(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_glossaries(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The name of the project from which to list all of the glossaries. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - filter_ (str): Optional. Filter specifying constraints of a list operation. - Filtering is not supported yet, and the parameter currently has no effect. - If missing, no filtering is performed. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.translate_v3beta1.types.Glossary` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_glossaries" not in self._inner_api_calls: - self._inner_api_calls[ - "list_glossaries" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_glossaries, - default_retry=self._method_configs["ListGlossaries"].retry, - default_timeout=self._method_configs["ListGlossaries"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.ListGlossariesRequest( - parent=parent, page_size=page_size, filter=filter_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_glossaries"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="glossaries", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_glossary( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist. - - Example: - >>> from google.cloud import translate_v3beta1 - >>> - >>> client = translate_v3beta1.TranslationServiceClient() - >>> - >>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]') - >>> - >>> response = client.get_glossary(name) - - Args: - name (str): Required. The name of the glossary to retrieve. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3beta1.types.Glossary` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_glossary" not in self._inner_api_calls: - self._inner_api_calls[ - "get_glossary" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_glossary, - default_retry=self._method_configs["GetGlossary"].retry, - default_timeout=self._method_configs["GetGlossary"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.GetGlossaryRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_glossary"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_glossary( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a glossary, or cancels glossary construction if the glossary - isn't created yet. Returns NOT_FOUND, if the glossary doesn't exist. - - Example: - >>> from google.cloud import translate_v3beta1 - >>> - >>> client = translate_v3beta1.TranslationServiceClient() - >>> - >>> name = client.glossary_path('[PROJECT]', '[LOCATION]', '[GLOSSARY]') - >>> - >>> response = client.delete_glossary(name) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - name (str): Required. The name of the glossary to delete. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.translate_v3beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_glossary" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_glossary" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_glossary, - default_retry=self._method_configs["DeleteGlossary"].retry, - default_timeout=self._method_configs["DeleteGlossary"].timeout, - client_info=self._client_info, - ) - - request = translation_service_pb2.DeleteGlossaryRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["delete_glossary"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - translation_service_pb2.DeleteGlossaryResponse, - metadata_type=translation_service_pb2.DeleteGlossaryMetadata, - ) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/translation_service_client_config.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/translation_service_client_config.py deleted file mode 100644 index 228f685cc359..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/translation_service_client_config.py +++ /dev/null @@ -1,82 +0,0 @@ -config = { - "interfaces": { - "google.cloud.translation.v3beta1.TranslationService": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - }, - "methods": { - "TranslateText": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DetectLanguage": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetSupportedLanguages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "BatchTranslateText": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateGlossary": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "ListGlossaries": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetGlossary": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "DeleteGlossary": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/transports/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/transports/translation_service_grpc_transport.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/transports/translation_service_grpc_transport.py deleted file mode 100644 index 34e754aed7ad..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic/transports/translation_service_grpc_transport.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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 google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.translate_v3beta1.proto import translation_service_pb2_grpc - - -class TranslationServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.translation.v3beta1 TranslationService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-translation", - ) - - def __init__( - self, channel=None, credentials=None, address="translate.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "translation_service_stub": translation_service_pb2_grpc.TranslationServiceStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="translate.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def translate_text(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.translate_text`. - - Translates input text and returns translated text. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].TranslateText - - @property - def detect_language(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.detect_language`. - - Detects the language of text within a request. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].DetectLanguage - - @property - def get_supported_languages(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.get_supported_languages`. - - Returns a list of supported languages for translation. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].GetSupportedLanguages - - @property - def batch_translate_text(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.batch_translate_text`. - - Translates a large volume of text in asynchronous batch mode. - This function provides real-time output as the inputs are being processed. - If caller cancels a request, the partial results (for an input file, it's - all or nothing) may still be available on the specified output location. - - This call returns immediately and you can - use google.longrunning.Operation.name to poll the status of the call. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].BatchTranslateText - - @property - def create_glossary(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.create_glossary`. - - Creates a glossary and returns the long-running operation. Returns - NOT_FOUND, if the project doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].CreateGlossary - - @property - def list_glossaries(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.list_glossaries`. - - Lists glossaries in a project. Returns NOT_FOUND, if the project - doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].ListGlossaries - - @property - def get_glossary(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.get_glossary`. - - Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].GetGlossary - - @property - def delete_glossary(self): - """Return the gRPC stub for :meth:`TranslationServiceClient.delete_glossary`. - - Deletes a glossary, or cancels glossary construction if the glossary - isn't created yet. Returns NOT_FOUND, if the glossary doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["translation_service_stub"].DeleteGlossary diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service.proto b/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service.proto deleted file mode 100644 index e62a50883822..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service.proto +++ /dev/null @@ -1,902 +0,0 @@ -// 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. -// - -syntax = "proto3"; - -package google.cloud.translation.v3beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/timestamp.proto"; - -option cc_enable_arenas = true; -option csharp_namespace = "Google.Cloud.Translate.V3Beta1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/translate/v3beta1;translate"; -option java_multiple_files = true; -option java_outer_classname = "TranslationServiceProto"; -option java_package = "com.google.cloud.translate.v3beta1"; -option php_namespace = "Google\\Cloud\\Translate\\V3beta1"; -option ruby_package = "Google::Cloud::Translate::V3beta1"; - -// Proto file for the Cloud Translation API (v3beta1). - -// Provides natural language translation operations. -service TranslationService { - option (google.api.default_host) = "translate.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-translation"; - - // Translates input text and returns translated text. - rpc TranslateText(TranslateTextRequest) returns (TranslateTextResponse) { - option (google.api.http) = { - post: "/v3beta1/{parent=projects/*/locations/*}:translateText" - body: "*" - additional_bindings { - post: "/v3beta1/{parent=projects/*}:translateText" - body: "*" - } - }; - } - - // Detects the language of text within a request. - rpc DetectLanguage(DetectLanguageRequest) returns (DetectLanguageResponse) { - option (google.api.http) = { - post: "/v3beta1/{parent=projects/*/locations/*}:detectLanguage" - body: "*" - additional_bindings { - post: "/v3beta1/{parent=projects/*}:detectLanguage" - body: "*" - } - }; - option (google.api.method_signature) = "parent,model,mime_type"; - } - - // Returns a list of supported languages for translation. - rpc GetSupportedLanguages(GetSupportedLanguagesRequest) returns (SupportedLanguages) { - option (google.api.http) = { - get: "/v3beta1/{parent=projects/*/locations/*}/supportedLanguages" - additional_bindings { - get: "/v3beta1/{parent=projects/*}/supportedLanguages" - } - }; - option (google.api.method_signature) = "parent,display_language_code,model"; - } - - // Translates a large volume of text in asynchronous batch mode. - // This function provides real-time output as the inputs are being processed. - // If caller cancels a request, the partial results (for an input file, it's - // all or nothing) may still be available on the specified output location. - // - // This call returns immediately and you can - // use google.longrunning.Operation.name to poll the status of the call. - rpc BatchTranslateText(BatchTranslateTextRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v3beta1/{parent=projects/*/locations/*}:batchTranslateText" - body: "*" - }; - option (google.longrunning.operation_info) = { - response_type: "BatchTranslateResponse" - metadata_type: "BatchTranslateMetadata" - }; - } - - // Creates a glossary and returns the long-running operation. Returns - // NOT_FOUND, if the project doesn't exist. - rpc CreateGlossary(CreateGlossaryRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v3beta1/{parent=projects/*/locations/*}/glossaries" - body: "glossary" - }; - option (google.api.method_signature) = "parent,glossary"; - option (google.longrunning.operation_info) = { - response_type: "Glossary" - metadata_type: "CreateGlossaryMetadata" - }; - } - - // Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't - // exist. - rpc ListGlossaries(ListGlossariesRequest) returns (ListGlossariesResponse) { - option (google.api.http) = { - get: "/v3beta1/{parent=projects/*/locations/*}/glossaries" - }; - option (google.api.method_signature) = "parent"; - option (google.api.method_signature) = "parent,filter"; - } - - // Gets a glossary. Returns NOT_FOUND, if the glossary doesn't - // exist. - rpc GetGlossary(GetGlossaryRequest) returns (Glossary) { - option (google.api.http) = { - get: "/v3beta1/{name=projects/*/locations/*/glossaries/*}" - }; - option (google.api.method_signature) = "name"; - } - - // Deletes a glossary, or cancels glossary construction - // if the glossary isn't created yet. - // Returns NOT_FOUND, if the glossary doesn't exist. - rpc DeleteGlossary(DeleteGlossaryRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - delete: "/v3beta1/{name=projects/*/locations/*/glossaries/*}" - }; - option (google.api.method_signature) = "name"; - option (google.longrunning.operation_info) = { - response_type: "DeleteGlossaryResponse" - metadata_type: "DeleteGlossaryMetadata" - }; - } -} - -// Configures which glossary should be used for a specific target language, -// and defines options for applying that glossary. -message TranslateTextGlossaryConfig { - // Required. Specifies the glossary used for this translation. Use - // this format: projects/*/locations/*/glossaries/* - string glossary = 1 [(google.api.field_behavior) = REQUIRED]; - - // Optional. Indicates match is case-insensitive. - // Default value is false if missing. - bool ignore_case = 2 [(google.api.field_behavior) = OPTIONAL]; -} - -// The request message for synchronous translation. -message TranslateTextRequest { - // Required. The content of the input in string format. - // We recommend the total content be less than 30k codepoints. - // Use BatchTranslateText for larger text. - repeated string contents = 1 [(google.api.field_behavior) = REQUIRED]; - - // Optional. The format of the source text, for example, "text/html", - // "text/plain". If left blank, the MIME type defaults to "text/html". - string mime_type = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The BCP-47 language code of the input text if - // known, for example, "en-US" or "sr-Latn". Supported language codes are - // listed in Language Support. If the source language isn't specified, the API - // attempts to identify the source language automatically and returns the - // source language within the response. - string source_language_code = 4 [(google.api.field_behavior) = OPTIONAL]; - - // Required. The BCP-47 language code to use for translation of the input - // text, set to one of the language codes listed in Language Support. - string target_language_code = 5 [(google.api.field_behavior) = REQUIRED]; - - // Required. Project or location to make a call. Must refer to a caller's - // project. - // - // Format: `projects/{project-id}` or - // `projects/{project-id}/locations/{location-id}`. - // - // For global calls, use `projects/{project-id}/locations/global` or - // `projects/{project-id}`. - // - // Non-global location is required for requests using AutoML models or - // custom glossaries. - // - // Models and glossaries must be within the same region (have same - // location-id), otherwise an INVALID_ARGUMENT (400) error is returned. - string parent = 8 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Optional. The `model` type requested for this translation. - // - // The format depends on model type: - // - // - AutoML Translation models: - // `projects/{project-id}/locations/{location-id}/models/{model-id}` - // - // - General (built-in) models: - // `projects/{project-id}/locations/{location-id}/models/general/nmt`, - // `projects/{project-id}/locations/{location-id}/models/general/base` - // - // - // For global (non-regionalized) requests, use `location-id` `global`. - // For example, - // `projects/{project-id}/locations/global/models/general/nmt`. - // - // If missing, the system decides which google base model to use. - string model = 6 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Glossary to be applied. The glossary must be - // within the same region (have the same location-id) as the model, otherwise - // an INVALID_ARGUMENT (400) error is returned. - TranslateTextGlossaryConfig glossary_config = 7 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The labels with user-defined metadata for the request. - // - // Label keys and values can be no longer than 63 characters - // (Unicode codepoints), can only contain lowercase letters, numeric - // characters, underscores and dashes. International characters are allowed. - // Label values are optional. Label keys must start with a letter. - // - // See https://cloud.google.com/translate/docs/labels for more information. - map labels = 10 [(google.api.field_behavior) = OPTIONAL]; -} - -message TranslateTextResponse { - // Text translation responses with no glossary applied. - // This field has the same length as - // [`contents`][google.cloud.translation.v3beta1.TranslateTextRequest.contents]. - repeated Translation translations = 1; - - // Text translation responses if a glossary is provided in the request. - // This can be the same as - // [`translations`][google.cloud.translation.v3beta1.TranslateTextResponse.translations] if no terms apply. - // This field has the same length as - // [`contents`][google.cloud.translation.v3beta1.TranslateTextRequest.contents]. - repeated Translation glossary_translations = 3; -} - -// A single translation response. -message Translation { - // Text translated into the target language. - string translated_text = 1; - - // Only present when `model` is present in the request. - // This is same as `model` provided in the request. - string model = 2; - - // The BCP-47 language code of source text in the initial request, detected - // automatically, if no source language was passed within the initial - // request. If the source language was passed, auto-detection of the language - // does not occur and this field is empty. - string detected_language_code = 4; - - // The `glossary_config` used for this translation. - TranslateTextGlossaryConfig glossary_config = 3; -} - -// The request message for language detection. -message DetectLanguageRequest { - // Required. Project or location to make a call. Must refer to a caller's - // project. - // - // Format: `projects/{project-id}/locations/{location-id}` or - // `projects/{project-id}`. - // - // For global calls, use `projects/{project-id}/locations/global` or - // `projects/{project-id}`. - // - // Only models within the same region (has same location-id) can be used. - // Otherwise an INVALID_ARGUMENT (400) error is returned. - string parent = 5 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Optional. The language detection model to be used. - // - // Format: - // `projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}` - // - // Only one language detection model is currently supported: - // `projects/{project-id}/locations/{location-id}/models/language-detection/default`. - // - // If not specified, the default model is used. - string model = 4 [(google.api.field_behavior) = OPTIONAL]; - - // Required. The source of the document from which to detect the language. - oneof source { - // The content of the input stored as a string. - string content = 1; - } - - // Optional. The format of the source text, for example, "text/html", - // "text/plain". If left blank, the MIME type defaults to "text/html". - string mime_type = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The labels with user-defined metadata for the request. - // - // Label keys and values can be no longer than 63 characters - // (Unicode codepoints), can only contain lowercase letters, numeric - // characters, underscores and dashes. International characters are allowed. - // Label values are optional. Label keys must start with a letter. - // - // See https://cloud.google.com/translate/docs/labels for more information. - map labels = 6; -} - -// The response message for language detection. -message DetectedLanguage { - // The BCP-47 language code of source content in the request, detected - // automatically. - string language_code = 1; - - // The confidence of the detection result for this language. - float confidence = 2; -} - -// The response message for language detection. -message DetectLanguageResponse { - // A list of detected languages sorted by detection confidence in descending - // order. The most probable language first. - repeated DetectedLanguage languages = 1; -} - -// The request message for discovering supported languages. -message GetSupportedLanguagesRequest { - // Required. Project or location to make a call. Must refer to a caller's - // project. - // - // Format: `projects/{project-id}` or - // `projects/{project-id}/locations/{location-id}`. - // - // For global calls, use `projects/{project-id}/locations/global` or - // `projects/{project-id}`. - // - // Non-global location is required for AutoML models. - // - // Only models within the same region (have same location-id) can be used, - // otherwise an INVALID_ARGUMENT (400) error is returned. - string parent = 3 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Optional. The language to use to return localized, human readable names - // of supported languages. If missing, then display names are not returned - // in a response. - string display_language_code = 1 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Get supported languages of this model. - // - // The format depends on model type: - // - // - AutoML Translation models: - // `projects/{project-id}/locations/{location-id}/models/{model-id}` - // - // - General (built-in) models: - // `projects/{project-id}/locations/{location-id}/models/general/nmt`, - // `projects/{project-id}/locations/{location-id}/models/general/base` - // - // - // Returns languages supported by the specified model. - // If missing, we get supported languages of Google general base (PBMT) model. - string model = 2 [(google.api.field_behavior) = OPTIONAL]; -} - -// The response message for discovering supported languages. -message SupportedLanguages { - // A list of supported language responses. This list contains an entry - // for each language the Translation API supports. - repeated SupportedLanguage languages = 1; -} - -// A single supported language response corresponds to information related -// to one supported language. -message SupportedLanguage { - // Supported language code, generally consisting of its ISO 639-1 - // identifier, for example, 'en', 'ja'. In certain cases, BCP-47 codes - // including language and region identifiers are returned (for example, - // 'zh-TW' and 'zh-CN') - string language_code = 1; - - // Human readable name of the language localized in the display language - // specified in the request. - string display_name = 2; - - // Can be used as source language. - bool support_source = 3; - - // Can be used as target language. - bool support_target = 4; -} - -// The Google Cloud Storage location for the input content. -message GcsSource { - // Required. Source data URI. For example, `gs://my_bucket/my_object`. - string input_uri = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// Input configuration for BatchTranslateText request. -message InputConfig { - // Optional. Can be "text/plain" or "text/html". - // For `.tsv`, "text/html" is used if mime_type is missing. - // For `.html`, this field must be "text/html" or empty. - // For `.txt`, this field must be "text/plain" or empty. - string mime_type = 1 [(google.api.field_behavior) = OPTIONAL]; - - // Required. Specify the input. - oneof source { - // Required. Google Cloud Storage location for the source input. - // This can be a single file (for example, - // `gs://translation-test/input.tsv`) or a wildcard (for example, - // `gs://translation-test/*`). If a file extension is `.tsv`, it can - // contain either one or two columns. The first column (optional) is the id - // of the text request. If the first column is missing, we use the row - // number (0-based) from the input file as the ID in the output file. The - // second column is the actual text to be - // translated. We recommend each row be <= 10K Unicode codepoints, - // otherwise an error might be returned. - // Note that the input tsv must be RFC 4180 compliant. - // - // You could use https://github.com/Clever/csvlint to check potential - // formatting errors in your tsv file. - // csvlint --delimiter='\t' your_input_file.tsv - // - // The other supported file extensions are `.txt` or `.html`, which is - // treated as a single large chunk of text. - GcsSource gcs_source = 2; - } -} - -// The Google Cloud Storage location for the output content. -message GcsDestination { - // Required. There must be no files under 'output_uri_prefix'. - // 'output_uri_prefix' must end with "/" and start with "gs://", otherwise an - // INVALID_ARGUMENT (400) error is returned. - string output_uri_prefix = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// Output configuration for BatchTranslateText request. -message OutputConfig { - // Required. The destination of output. - oneof destination { - // Google Cloud Storage destination for output content. - // For every single input file (for example, gs://a/b/c.[extension]), we - // generate at most 2 * n output files. (n is the # of target_language_codes - // in the BatchTranslateTextRequest). - // - // Output files (tsv) generated are compliant with RFC 4180 except that - // record delimiters are '\n' instead of '\r\n'. We don't provide any way to - // change record delimiters. - // - // While the input files are being processed, we write/update an index file - // 'index.csv' under 'output_uri_prefix' (for example, - // gs://translation-test/index.csv) The index file is generated/updated as - // new files are being translated. The format is: - // - // input_file,target_language_code,translations_file,errors_file, - // glossary_translations_file,glossary_errors_file - // - // input_file is one file we matched using gcs_source.input_uri. - // target_language_code is provided in the request. - // translations_file contains the translations. (details provided below) - // errors_file contains the errors during processing of the file. (details - // below). Both translations_file and errors_file could be empty - // strings if we have no content to output. - // glossary_translations_file and glossary_errors_file are always empty - // strings if the input_file is tsv. They could also be empty if we have no - // content to output. - // - // Once a row is present in index.csv, the input/output matching never - // changes. Callers should also expect all the content in input_file are - // processed and ready to be consumed (that is, no partial output file is - // written). - // - // The format of translations_file (for target language code 'trg') is: - // gs://translation_test/a_b_c_'trg'_translations.[extension] - // - // If the input file extension is tsv, the output has the following - // columns: - // Column 1: ID of the request provided in the input, if it's not - // provided in the input, then the input row number is used (0-based). - // Column 2: source sentence. - // Column 3: translation without applying a glossary. Empty string if there - // is an error. - // Column 4 (only present if a glossary is provided in the request): - // translation after applying the glossary. Empty string if there is an - // error applying the glossary. Could be same string as column 3 if there is - // no glossary applied. - // - // If input file extension is a txt or html, the translation is directly - // written to the output file. If glossary is requested, a separate - // glossary_translations_file has format of - // gs://translation_test/a_b_c_'trg'_glossary_translations.[extension] - // - // The format of errors file (for target language code 'trg') is: - // gs://translation_test/a_b_c_'trg'_errors.[extension] - // - // If the input file extension is tsv, errors_file contains the following: - // Column 1: ID of the request provided in the input, if it's not - // provided in the input, then the input row number is used (0-based). - // Column 2: source sentence. - // Column 3: Error detail for the translation. Could be empty. - // Column 4 (only present if a glossary is provided in the request): - // Error when applying the glossary. - // - // If the input file extension is txt or html, glossary_error_file will be - // generated that contains error details. glossary_error_file has format of - // gs://translation_test/a_b_c_'trg'_glossary_errors.[extension] - GcsDestination gcs_destination = 1; - } -} - -// The batch translation request. -message BatchTranslateTextRequest { - // Required. Location to make a call. Must refer to a caller's project. - // - // Format: `projects/{project-id}/locations/{location-id}`. - // - // The `global` location is not supported for batch translation. - // - // Only AutoML Translation models or glossaries within the same region (have - // the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) - // error is returned. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. Source language code. - string source_language_code = 2 [(google.api.field_behavior) = REQUIRED]; - - // Required. Specify up to 10 language codes here. - repeated string target_language_codes = 3 [(google.api.field_behavior) = REQUIRED]; - - // Optional. The models to use for translation. Map's key is target language - // code. Map's value is model name. Value can be a built-in general model, - // or an AutoML Translation model. - // - // The value format depends on model type: - // - // - AutoML Translation models: - // `projects/{project-id}/locations/{location-id}/models/{model-id}` - // - // - General (built-in) models: - // `projects/{project-id}/locations/{location-id}/models/general/nmt`, - // `projects/{project-id}/locations/{location-id}/models/general/base` - // - // - // If the map is empty or a specific model is - // not requested for a language pair, then default google model (nmt) is used. - map models = 4 [(google.api.field_behavior) = OPTIONAL]; - - // Required. Input configurations. - // The total number of files matched should be <= 1000. - // The total content size should be <= 100M Unicode codepoints. - // The files must use UTF-8 encoding. - repeated InputConfig input_configs = 5 [(google.api.field_behavior) = REQUIRED]; - - // Required. Output configuration. - // If 2 input configs match to the same file (that is, same input path), - // we don't generate output for duplicate inputs. - OutputConfig output_config = 6 [(google.api.field_behavior) = REQUIRED]; - - // Optional. Glossaries to be applied for translation. - // It's keyed by target language code. - map glossaries = 7 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The labels with user-defined metadata for the request. - // - // Label keys and values can be no longer than 63 characters - // (Unicode codepoints), can only contain lowercase letters, numeric - // characters, underscores and dashes. International characters are allowed. - // Label values are optional. Label keys must start with a letter. - // - // See https://cloud.google.com/translate/docs/labels for more information. - map labels = 9 [(google.api.field_behavior) = OPTIONAL]; -} - -// State metadata for the batch translation operation. -message BatchTranslateMetadata { - // State of the job. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is being processed. - RUNNING = 1; - - // The batch is processed, and at least one item was successfully - // processed. - SUCCEEDED = 2; - - // The batch is done and no item was successfully processed. - FAILED = 3; - - // Request is in the process of being canceled after caller invoked - // longrunning.Operations.CancelOperation on the request id. - CANCELLING = 4; - - // The batch is done after the user has called the - // longrunning.Operations.CancelOperation. Any records processed before the - // cancel command are output as specified in the request. - CANCELLED = 5; - } - - // The state of the operation. - State state = 1; - - // Number of successfully translated characters so far (Unicode codepoints). - int64 translated_characters = 2; - - // Number of characters that have failed to process so far (Unicode - // codepoints). - int64 failed_characters = 3; - - // Total number of characters (Unicode codepoints). - // This is the total number of codepoints from input files times the number of - // target languages and appears here shortly after the call is submitted. - int64 total_characters = 4; - - // Time when the operation was submitted. - google.protobuf.Timestamp submit_time = 5; -} - -// Stored in the [google.longrunning.Operation.response][google.longrunning.Operation.response] field returned by -// BatchTranslateText if at least one sentence is translated successfully. -message BatchTranslateResponse { - // Total number of characters (Unicode codepoints). - int64 total_characters = 1; - - // Number of successfully translated characters (Unicode codepoints). - int64 translated_characters = 2; - - // Number of characters that have failed to process (Unicode codepoints). - int64 failed_characters = 3; - - // Time when the operation was submitted. - google.protobuf.Timestamp submit_time = 4; - - // The time when the operation is finished and - // [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to true. - google.protobuf.Timestamp end_time = 5; -} - -// Input configuration for glossaries. -message GlossaryInputConfig { - // Required. Specify the input. - oneof source { - // Required. Google Cloud Storage location of glossary data. - // File format is determined based on the filename extension. API returns - // [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file - // formats. Wildcards are not allowed. This must be a single file in one of - // the following formats: - // - // For unidirectional glossaries: - // - // - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated. - // The first column is source text. The second column is target text. - // The file must not contain headers. That is, the first row is data, not - // column names. - // - // - TMX (`.tmx`): TMX file with parallel data defining source/target term - // pairs. - // - // For equivalent term sets glossaries: - // - // - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms - // in multiple languages. The format is defined for Google Translation - // Toolkit and documented in [Use a - // glossary](https://support.google.com/translatortoolkit/answer/6306379?hl=en). - GcsSource gcs_source = 1; - } -} - -// Represents a glossary built from user provided data. -message Glossary { - option (google.api.resource) = { - type: "translate.googleapis.com/Glossary" - pattern: "projects/{project}/locations/{location}/glossaries/{glossary}" - }; - - // Used with unidirectional glossaries. - message LanguageCodePair { - // Required. The BCP-47 language code of the input text, for example, - // "en-US". Expected to be an exact match for GlossaryTerm.language_code. - string source_language_code = 1; - - // Required. The BCP-47 language code for translation output, for example, - // "zh-CN". Expected to be an exact match for GlossaryTerm.language_code. - string target_language_code = 2; - } - - // Used with equivalent term set glossaries. - message LanguageCodesSet { - // The BCP-47 language code(s) for terms defined in the glossary. - // All entries are unique. The list contains at least two entries. - // Expected to be an exact match for GlossaryTerm.language_code. - repeated string language_codes = 1; - } - - // Required. The resource name of the glossary. Glossary names have the form - // `projects/{project-id}/locations/{location-id}/glossaries/{glossary-id}`. - string name = 1 [(google.api.field_behavior) = REQUIRED]; - - // Languages supported by the glossary. - oneof languages { - // Used with unidirectional glossaries. - LanguageCodePair language_pair = 3; - - // Used with equivalent term set glossaries. - LanguageCodesSet language_codes_set = 4; - } - - // Required. Provides examples to build the glossary from. - // Total glossary must not exceed 10M Unicode codepoints. - GlossaryInputConfig input_config = 5; - - // Output only. The number of entries defined in the glossary. - int32 entry_count = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; - - // Output only. When CreateGlossary was called. - google.protobuf.Timestamp submit_time = 7 [(google.api.field_behavior) = OUTPUT_ONLY]; - - // Output only. When the glossary creation was finished. - google.protobuf.Timestamp end_time = 8 [(google.api.field_behavior) = OUTPUT_ONLY]; -} - -// Request message for CreateGlossary. -message CreateGlossaryRequest { - // Required. The project name. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The glossary to create. - Glossary glossary = 2 [(google.api.field_behavior) = REQUIRED]; -} - -// Request message for GetGlossary. -message GetGlossaryRequest { - // Required. The name of the glossary to retrieve. - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "translate.googleapis.com/Glossary" - } - ]; -} - -// Request message for DeleteGlossary. -message DeleteGlossaryRequest { - // Required. The name of the glossary to delete. - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "translate.googleapis.com/Glossary" - } - ]; -} - -// Request message for ListGlossaries. -message ListGlossariesRequest { - // Required. The name of the project from which to list all of the glossaries. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Optional. Requested page size. The server may return fewer glossaries than - // requested. If unspecified, the server picks an appropriate default. - int32 page_size = 2 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. A token identifying a page of results the server should return. - // Typically, this is the value of [ListGlossariesResponse.next_page_token] - // returned from the previous call to `ListGlossaries` method. - // The first page is returned if `page_token`is empty or missing. - string page_token = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Filter specifying constraints of a list operation. - // Filtering is not supported yet, and the parameter currently has no effect. - // If missing, no filtering is performed. - string filter = 4 [(google.api.field_behavior) = OPTIONAL]; -} - -// Response message for ListGlossaries. -message ListGlossariesResponse { - // The list of glossaries for a project. - repeated Glossary glossaries = 1; - - // A token to retrieve a page of results. Pass this value in the - // [ListGlossariesRequest.page_token] field in the subsequent call to - // `ListGlossaries` method to retrieve the next page of results. - string next_page_token = 2; -} - -// Stored in the [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata] field returned by -// CreateGlossary. -message CreateGlossaryMetadata { - // Enumerates the possible states that the creation request can be in. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is being processed. - RUNNING = 1; - - // The glossary was successfully created. - SUCCEEDED = 2; - - // Failed to create the glossary. - FAILED = 3; - - // Request is in the process of being canceled after caller invoked - // longrunning.Operations.CancelOperation on the request id. - CANCELLING = 4; - - // The glossary creation request was successfully canceled. - CANCELLED = 5; - } - - // The name of the glossary that is being created. - string name = 1; - - // The current state of the glossary creation operation. - State state = 2; - - // The time when the operation was submitted to the server. - google.protobuf.Timestamp submit_time = 3; -} - -// Stored in the [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata] field returned by -// DeleteGlossary. -message DeleteGlossaryMetadata { - // Enumerates the possible states that the creation request can be in. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is being processed. - RUNNING = 1; - - // The glossary was successfully deleted. - SUCCEEDED = 2; - - // Failed to delete the glossary. - FAILED = 3; - - // Request is in the process of being canceled after caller invoked - // longrunning.Operations.CancelOperation on the request id. - CANCELLING = 4; - - // The glossary deletion request was successfully canceled. - CANCELLED = 5; - } - - // The name of the glossary that is being deleted. - string name = 1; - - // The current state of the glossary deletion operation. - State state = 2; - - // The time when the operation was submitted to the server. - google.protobuf.Timestamp submit_time = 3; -} - -// Stored in the [google.longrunning.Operation.response][google.longrunning.Operation.response] field returned by -// DeleteGlossary. -message DeleteGlossaryResponse { - // The name of the deleted glossary. - string name = 1; - - // The time when the operation was submitted to the server. - google.protobuf.Timestamp submit_time = 2; - - // The time when the glossary deletion is finished and - // [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to true. - google.protobuf.Timestamp end_time = 3; -} diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service_pb2.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service_pb2.py deleted file mode 100644 index 8a3ddc389d93..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service_pb2.py +++ /dev/null @@ -1,4042 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/translate_v3beta1/proto/translation_service.proto - -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/translate_v3beta1/proto/translation_service.proto", - package="google.cloud.translation.v3beta1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.translate.v3beta1B\027TranslationServiceProtoP\001ZGgoogle.golang.org/genproto/googleapis/cloud/translate/v3beta1;translate\370\001\001\252\002\036Google.Cloud.Translate.V3Beta1\312\002\036Google\\Cloud\\Translate\\V3beta1\352\002!Google::Cloud::Translate::V3beta1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n>google/cloud/translate_v3beta1/proto/translation_service.proto\x12 google.cloud.translation.v3beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a#google/longrunning/operations.proto\x1a\x1fgoogle/protobuf/timestamp.proto"N\n\x1bTranslateTextGlossaryConfig\x12\x15\n\x08glossary\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x18\n\x0bignore_case\x18\x02 \x01(\x08\x42\x03\xe0\x41\x01"\xbf\x03\n\x14TranslateTextRequest\x12\x15\n\x08\x63ontents\x18\x01 \x03(\tB\x03\xe0\x41\x02\x12\x16\n\tmime_type\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12!\n\x14source_language_code\x18\x04 \x01(\tB\x03\xe0\x41\x01\x12!\n\x14target_language_code\x18\x05 \x01(\tB\x03\xe0\x41\x02\x12\x39\n\x06parent\x18\x08 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x12\n\x05model\x18\x06 \x01(\tB\x03\xe0\x41\x01\x12[\n\x0fglossary_config\x18\x07 \x01(\x0b\x32=.google.cloud.translation.v3beta1.TranslateTextGlossaryConfigB\x03\xe0\x41\x01\x12W\n\x06labels\x18\n \x03(\x0b\x32\x42.google.cloud.translation.v3beta1.TranslateTextRequest.LabelsEntryB\x03\xe0\x41\x01\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\xaa\x01\n\x15TranslateTextResponse\x12\x43\n\x0ctranslations\x18\x01 \x03(\x0b\x32-.google.cloud.translation.v3beta1.Translation\x12L\n\x15glossary_translations\x18\x03 \x03(\x0b\x32-.google.cloud.translation.v3beta1.Translation"\xad\x01\n\x0bTranslation\x12\x17\n\x0ftranslated_text\x18\x01 \x01(\t\x12\r\n\x05model\x18\x02 \x01(\t\x12\x1e\n\x16\x64\x65tected_language_code\x18\x04 \x01(\t\x12V\n\x0fglossary_config\x18\x03 \x01(\x0b\x32=.google.cloud.translation.v3beta1.TranslateTextGlossaryConfig"\x9f\x02\n\x15\x44\x65tectLanguageRequest\x12\x39\n\x06parent\x18\x05 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x12\n\x05model\x18\x04 \x01(\tB\x03\xe0\x41\x01\x12\x11\n\x07\x63ontent\x18\x01 \x01(\tH\x00\x12\x16\n\tmime_type\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12S\n\x06labels\x18\x06 \x03(\x0b\x32\x43.google.cloud.translation.v3beta1.DetectLanguageRequest.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x08\n\x06source"=\n\x10\x44\x65tectedLanguage\x12\x15\n\rlanguage_code\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02"_\n\x16\x44\x65tectLanguageResponse\x12\x45\n\tlanguages\x18\x01 \x03(\x0b\x32\x32.google.cloud.translation.v3beta1.DetectedLanguage"\x91\x01\n\x1cGetSupportedLanguagesRequest\x12\x39\n\x06parent\x18\x03 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12"\n\x15\x64isplay_language_code\x18\x01 \x01(\tB\x03\xe0\x41\x01\x12\x12\n\x05model\x18\x02 \x01(\tB\x03\xe0\x41\x01"\\\n\x12SupportedLanguages\x12\x46\n\tlanguages\x18\x01 \x03(\x0b\x32\x33.google.cloud.translation.v3beta1.SupportedLanguage"p\n\x11SupportedLanguage\x12\x15\n\rlanguage_code\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x16\n\x0esupport_source\x18\x03 \x01(\x08\x12\x16\n\x0esupport_target\x18\x04 \x01(\x08"#\n\tGcsSource\x12\x16\n\tinput_uri\x18\x01 \x01(\tB\x03\xe0\x41\x02"r\n\x0bInputConfig\x12\x16\n\tmime_type\x18\x01 \x01(\tB\x03\xe0\x41\x01\x12\x41\n\ngcs_source\x18\x02 \x01(\x0b\x32+.google.cloud.translation.v3beta1.GcsSourceH\x00\x42\x08\n\x06source"0\n\x0eGcsDestination\x12\x1e\n\x11output_uri_prefix\x18\x01 \x01(\tB\x03\xe0\x41\x02"j\n\x0cOutputConfig\x12K\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32\x30.google.cloud.translation.v3beta1.GcsDestinationH\x00\x42\r\n\x0b\x64\x65stination"\xa6\x06\n\x19\x42\x61tchTranslateTextRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12!\n\x14source_language_code\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12"\n\x15target_language_codes\x18\x03 \x03(\tB\x03\xe0\x41\x02\x12\\\n\x06models\x18\x04 \x03(\x0b\x32G.google.cloud.translation.v3beta1.BatchTranslateTextRequest.ModelsEntryB\x03\xe0\x41\x01\x12I\n\rinput_configs\x18\x05 \x03(\x0b\x32-.google.cloud.translation.v3beta1.InputConfigB\x03\xe0\x41\x02\x12J\n\routput_config\x18\x06 \x01(\x0b\x32..google.cloud.translation.v3beta1.OutputConfigB\x03\xe0\x41\x02\x12\x64\n\nglossaries\x18\x07 \x03(\x0b\x32K.google.cloud.translation.v3beta1.BatchTranslateTextRequest.GlossariesEntryB\x03\xe0\x41\x01\x12\\\n\x06labels\x18\t \x03(\x0b\x32G.google.cloud.translation.v3beta1.BatchTranslateTextRequest.LabelsEntryB\x03\xe0\x41\x01\x1a-\n\x0bModelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1ap\n\x0fGlossariesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12L\n\x05value\x18\x02 \x01(\x0b\x32=.google.cloud.translation.v3beta1.TranslateTextGlossaryConfig:\x02\x38\x01\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\xd3\x02\n\x16\x42\x61tchTranslateMetadata\x12M\n\x05state\x18\x01 \x01(\x0e\x32>.google.cloud.translation.v3beta1.BatchTranslateMetadata.State\x12\x1d\n\x15translated_characters\x18\x02 \x01(\x03\x12\x19\n\x11\x66\x61iled_characters\x18\x03 \x01(\x03\x12\x18\n\x10total_characters\x18\x04 \x01(\x03\x12/\n\x0bsubmit_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"e\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07RUNNING\x10\x01\x12\r\n\tSUCCEEDED\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\x0e\n\nCANCELLING\x10\x04\x12\r\n\tCANCELLED\x10\x05"\xcb\x01\n\x16\x42\x61tchTranslateResponse\x12\x18\n\x10total_characters\x18\x01 \x01(\x03\x12\x1d\n\x15translated_characters\x18\x02 \x01(\x03\x12\x19\n\x11\x66\x61iled_characters\x18\x03 \x01(\x03\x12/\n\x0bsubmit_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"b\n\x13GlossaryInputConfig\x12\x41\n\ngcs_source\x18\x01 \x01(\x0b\x32+.google.cloud.translation.v3beta1.GcsSourceH\x00\x42\x08\n\x06source"\x8e\x05\n\x08Glossary\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12T\n\rlanguage_pair\x18\x03 \x01(\x0b\x32;.google.cloud.translation.v3beta1.Glossary.LanguageCodePairH\x00\x12Y\n\x12language_codes_set\x18\x04 \x01(\x0b\x32;.google.cloud.translation.v3beta1.Glossary.LanguageCodesSetH\x00\x12K\n\x0cinput_config\x18\x05 \x01(\x0b\x32\x35.google.cloud.translation.v3beta1.GlossaryInputConfig\x12\x18\n\x0b\x65ntry_count\x18\x06 \x01(\x05\x42\x03\xe0\x41\x03\x12\x34\n\x0bsubmit_time\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12\x31\n\x08\x65nd_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x1aN\n\x10LanguageCodePair\x12\x1c\n\x14source_language_code\x18\x01 \x01(\t\x12\x1c\n\x14target_language_code\x18\x02 \x01(\t\x1a*\n\x10LanguageCodesSet\x12\x16\n\x0elanguage_codes\x18\x01 \x03(\t:e\xea\x41\x62\n!translate.googleapis.com/Glossary\x12=projects/{project}/locations/{location}/glossaries/{glossary}B\x0b\n\tlanguages"\x95\x01\n\x15\x43reateGlossaryRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x41\n\x08glossary\x18\x02 \x01(\x0b\x32*.google.cloud.translation.v3beta1.GlossaryB\x03\xe0\x41\x02"M\n\x12GetGlossaryRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!translate.googleapis.com/Glossary"P\n\x15\x44\x65leteGlossaryRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!translate.googleapis.com/Glossary"\x98\x01\n\x15ListGlossariesRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12\x13\n\x06\x66ilter\x18\x04 \x01(\tB\x03\xe0\x41\x01"q\n\x16ListGlossariesResponse\x12>\n\nglossaries\x18\x01 \x03(\x0b\x32*.google.cloud.translation.v3beta1.Glossary\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\x8d\x02\n\x16\x43reateGlossaryMetadata\x12\x0c\n\x04name\x18\x01 \x01(\t\x12M\n\x05state\x18\x02 \x01(\x0e\x32>.google.cloud.translation.v3beta1.CreateGlossaryMetadata.State\x12/\n\x0bsubmit_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"e\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07RUNNING\x10\x01\x12\r\n\tSUCCEEDED\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\x0e\n\nCANCELLING\x10\x04\x12\r\n\tCANCELLED\x10\x05"\x8d\x02\n\x16\x44\x65leteGlossaryMetadata\x12\x0c\n\x04name\x18\x01 \x01(\t\x12M\n\x05state\x18\x02 \x01(\x0e\x32>.google.cloud.translation.v3beta1.DeleteGlossaryMetadata.State\x12/\n\x0bsubmit_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"e\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07RUNNING\x10\x01\x12\r\n\tSUCCEEDED\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\x0e\n\nCANCELLING\x10\x04\x12\r\n\tCANCELLED\x10\x05"\x85\x01\n\x16\x44\x65leteGlossaryResponse\x12\x0c\n\x04name\x18\x01 \x01(\t\x12/\n\x0bsubmit_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\x9a\x10\n\x12TranslationService\x12\xf4\x01\n\rTranslateText\x12\x36.google.cloud.translation.v3beta1.TranslateTextRequest\x1a\x37.google.cloud.translation.v3beta1.TranslateTextResponse"r\x82\xd3\xe4\x93\x02l"6/v3beta1/{parent=projects/*/locations/*}:translateText:\x01*Z/"*/v3beta1/{parent=projects/*}:translateText:\x01*\x12\x93\x02\n\x0e\x44\x65tectLanguage\x12\x37.google.cloud.translation.v3beta1.DetectLanguageRequest\x1a\x38.google.cloud.translation.v3beta1.DetectLanguageResponse"\x8d\x01\x82\xd3\xe4\x93\x02n"7/v3beta1/{parent=projects/*/locations/*}:detectLanguage:\x01*Z0"+/v3beta1/{parent=projects/*}:detectLanguage:\x01*\xda\x41\x16parent,model,mime_type\x12\xab\x02\n\x15GetSupportedLanguages\x12>.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest\x1a\x34.google.cloud.translation.v3beta1.SupportedLanguages"\x9b\x01\x82\xd3\xe4\x93\x02p\x12;/v3beta1/{parent=projects/*/locations/*}/supportedLanguagesZ1\x12//v3beta1/{parent=projects/*}/supportedLanguages\xda\x41"parent,display_language_code,model\x12\xeb\x01\n\x12\x42\x61tchTranslateText\x12;.google.cloud.translation.v3beta1.BatchTranslateTextRequest\x1a\x1d.google.longrunning.Operation"y\x82\xd3\xe4\x93\x02@";/v3beta1/{parent=projects/*/locations/*}:batchTranslateText:\x01*\xca\x41\x30\n\x16\x42\x61tchTranslateResponse\x12\x16\x42\x61tchTranslateMetadata\x12\xe6\x01\n\x0e\x43reateGlossary\x12\x37.google.cloud.translation.v3beta1.CreateGlossaryRequest\x1a\x1d.google.longrunning.Operation"|\x82\xd3\xe4\x93\x02?"3/v3beta1/{parent=projects/*/locations/*}/glossaries:\x08glossary\xda\x41\x0fparent,glossary\xca\x41"\n\x08Glossary\x12\x16\x43reateGlossaryMetadata\x12\xd9\x01\n\x0eListGlossaries\x12\x37.google.cloud.translation.v3beta1.ListGlossariesRequest\x1a\x38.google.cloud.translation.v3beta1.ListGlossariesResponse"T\x82\xd3\xe4\x93\x02\x35\x12\x33/v3beta1/{parent=projects/*/locations/*}/glossaries\xda\x41\x06parent\xda\x41\rparent,filter\x12\xb3\x01\n\x0bGetGlossary\x12\x34.google.cloud.translation.v3beta1.GetGlossaryRequest\x1a*.google.cloud.translation.v3beta1.Glossary"B\x82\xd3\xe4\x93\x02\x35\x12\x33/v3beta1/{name=projects/*/locations/*/glossaries/*}\xda\x41\x04name\x12\xdf\x01\n\x0e\x44\x65leteGlossary\x12\x37.google.cloud.translation.v3beta1.DeleteGlossaryRequest\x1a\x1d.google.longrunning.Operation"u\x82\xd3\xe4\x93\x02\x35*3/v3beta1/{name=projects/*/locations/*/glossaries/*}\xda\x41\x04name\xca\x41\x30\n\x16\x44\x65leteGlossaryResponse\x12\x16\x44\x65leteGlossaryMetadata\x1a~\xca\x41\x18translate.googleapis.com\xd2\x41`https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-translationB\xf1\x01\n"com.google.cloud.translate.v3beta1B\x17TranslationServiceProtoP\x01ZGgoogle.golang.org/genproto/googleapis/cloud/translate/v3beta1;translate\xf8\x01\x01\xaa\x02\x1eGoogle.Cloud.Translate.V3Beta1\xca\x02\x1eGoogle\\Cloud\\Translate\\V3beta1\xea\x02!Google::Cloud::Translate::V3beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_BATCHTRANSLATEMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.translation.v3beta1.BatchTranslateMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCEEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLING", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3329, - serialized_end=3430, -) -_sym_db.RegisterEnumDescriptor(_BATCHTRANSLATEMETADATA_STATE) - -_CREATEGLOSSARYMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.translation.v3beta1.CreateGlossaryMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCEEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLING", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3329, - serialized_end=3430, -) -_sym_db.RegisterEnumDescriptor(_CREATEGLOSSARYMETADATA_STATE) - -_DELETEGLOSSARYMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCEEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLING", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3329, - serialized_end=3430, -) -_sym_db.RegisterEnumDescriptor(_DELETEGLOSSARYMETADATA_STATE) - - -_TRANSLATETEXTGLOSSARYCONFIG = _descriptor.Descriptor( - name="TranslateTextGlossaryConfig", - full_name="google.cloud.translation.v3beta1.TranslateTextGlossaryConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="glossary", - full_name="google.cloud.translation.v3beta1.TranslateTextGlossaryConfig.glossary", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ignore_case", - full_name="google.cloud.translation.v3beta1.TranslateTextGlossaryConfig.ignore_case", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=285, - serialized_end=363, -) - - -_TRANSLATETEXTREQUEST_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=768, - serialized_end=813, -) - -_TRANSLATETEXTREQUEST = _descriptor.Descriptor( - name="TranslateTextRequest", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="contents", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.contents", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.mime_type", - index=1, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_language_code", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.source_language_code", - index=2, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_language_code", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.target_language_code", - index=3, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.parent", - index=4, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.model", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossary_config", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.glossary_config", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.translation.v3beta1.TranslateTextRequest.labels", - index=7, - number=10, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_TRANSLATETEXTREQUEST_LABELSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=366, - serialized_end=813, -) - - -_TRANSLATETEXTRESPONSE = _descriptor.Descriptor( - name="TranslateTextResponse", - full_name="google.cloud.translation.v3beta1.TranslateTextResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="translations", - full_name="google.cloud.translation.v3beta1.TranslateTextResponse.translations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossary_translations", - full_name="google.cloud.translation.v3beta1.TranslateTextResponse.glossary_translations", - index=1, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=816, - serialized_end=986, -) - - -_TRANSLATION = _descriptor.Descriptor( - name="Translation", - full_name="google.cloud.translation.v3beta1.Translation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="translated_text", - full_name="google.cloud.translation.v3beta1.Translation.translated_text", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.translation.v3beta1.Translation.model", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detected_language_code", - full_name="google.cloud.translation.v3beta1.Translation.detected_language_code", - index=2, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossary_config", - full_name="google.cloud.translation.v3beta1.Translation.glossary_config", - index=3, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=989, - serialized_end=1162, -) - - -_DETECTLANGUAGEREQUEST_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=768, - serialized_end=813, -) - -_DETECTLANGUAGEREQUEST = _descriptor.Descriptor( - name="DetectLanguageRequest", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.parent", - index=0, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.model", - index=1, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.content", - index=2, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.mime_type", - index=3, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.labels", - index=4, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_DETECTLANGUAGEREQUEST_LABELSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="source", - full_name="google.cloud.translation.v3beta1.DetectLanguageRequest.source", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1165, - serialized_end=1452, -) - - -_DETECTEDLANGUAGE = _descriptor.Descriptor( - name="DetectedLanguage", - full_name="google.cloud.translation.v3beta1.DetectedLanguage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.translation.v3beta1.DetectedLanguage.language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.translation.v3beta1.DetectedLanguage.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1454, - serialized_end=1515, -) - - -_DETECTLANGUAGERESPONSE = _descriptor.Descriptor( - name="DetectLanguageResponse", - full_name="google.cloud.translation.v3beta1.DetectLanguageResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="languages", - full_name="google.cloud.translation.v3beta1.DetectLanguageResponse.languages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1517, - serialized_end=1612, -) - - -_GETSUPPORTEDLANGUAGESREQUEST = _descriptor.Descriptor( - name="GetSupportedLanguagesRequest", - full_name="google.cloud.translation.v3beta1.GetSupportedLanguagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3beta1.GetSupportedLanguagesRequest.parent", - index=0, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_language_code", - full_name="google.cloud.translation.v3beta1.GetSupportedLanguagesRequest.display_language_code", - index=1, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.translation.v3beta1.GetSupportedLanguagesRequest.model", - index=2, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1615, - serialized_end=1760, -) - - -_SUPPORTEDLANGUAGES = _descriptor.Descriptor( - name="SupportedLanguages", - full_name="google.cloud.translation.v3beta1.SupportedLanguages", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="languages", - full_name="google.cloud.translation.v3beta1.SupportedLanguages.languages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1762, - serialized_end=1854, -) - - -_SUPPORTEDLANGUAGE = _descriptor.Descriptor( - name="SupportedLanguage", - full_name="google.cloud.translation.v3beta1.SupportedLanguage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.translation.v3beta1.SupportedLanguage.language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.translation.v3beta1.SupportedLanguage.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="support_source", - full_name="google.cloud.translation.v3beta1.SupportedLanguage.support_source", - index=2, - number=3, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="support_target", - full_name="google.cloud.translation.v3beta1.SupportedLanguage.support_target", - index=3, - number=4, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1856, - serialized_end=1968, -) - - -_GCSSOURCE = _descriptor.Descriptor( - name="GcsSource", - full_name="google.cloud.translation.v3beta1.GcsSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_uri", - full_name="google.cloud.translation.v3beta1.GcsSource.input_uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1970, - serialized_end=2005, -) - - -_INPUTCONFIG = _descriptor.Descriptor( - name="InputConfig", - full_name="google.cloud.translation.v3beta1.InputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.translation.v3beta1.InputConfig.mime_type", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.translation.v3beta1.InputConfig.gcs_source", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="source", - full_name="google.cloud.translation.v3beta1.InputConfig.source", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=2007, - serialized_end=2121, -) - - -_GCSDESTINATION = _descriptor.Descriptor( - name="GcsDestination", - full_name="google.cloud.translation.v3beta1.GcsDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="output_uri_prefix", - full_name="google.cloud.translation.v3beta1.GcsDestination.output_uri_prefix", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2123, - serialized_end=2171, -) - - -_OUTPUTCONFIG = _descriptor.Descriptor( - name="OutputConfig", - full_name="google.cloud.translation.v3beta1.OutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_destination", - full_name="google.cloud.translation.v3beta1.OutputConfig.gcs_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="destination", - full_name="google.cloud.translation.v3beta1.OutputConfig.destination", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=2173, - serialized_end=2279, -) - - -_BATCHTRANSLATETEXTREQUEST_MODELSENTRY = _descriptor.Descriptor( - name="ModelsEntry", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.ModelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.ModelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.ModelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2882, - serialized_end=2927, -) - -_BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY = _descriptor.Descriptor( - name="GlossariesEntry", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.GlossariesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.GlossariesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.GlossariesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2929, - serialized_end=3041, -) - -_BATCHTRANSLATETEXTREQUEST_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=768, - serialized_end=813, -) - -_BATCHTRANSLATETEXTREQUEST = _descriptor.Descriptor( - name="BatchTranslateTextRequest", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_language_code", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.source_language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_language_codes", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.target_language_codes", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="models", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.models", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="input_configs", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.input_configs", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.output_config", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossaries", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.glossaries", - index=6, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.translation.v3beta1.BatchTranslateTextRequest.labels", - index=7, - number=9, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _BATCHTRANSLATETEXTREQUEST_MODELSENTRY, - _BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY, - _BATCHTRANSLATETEXTREQUEST_LABELSENTRY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2282, - serialized_end=3088, -) - - -_BATCHTRANSLATEMETADATA = _descriptor.Descriptor( - name="BatchTranslateMetadata", - full_name="google.cloud.translation.v3beta1.BatchTranslateMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.translation.v3beta1.BatchTranslateMetadata.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="translated_characters", - full_name="google.cloud.translation.v3beta1.BatchTranslateMetadata.translated_characters", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="failed_characters", - full_name="google.cloud.translation.v3beta1.BatchTranslateMetadata.failed_characters", - index=2, - number=3, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_characters", - full_name="google.cloud.translation.v3beta1.BatchTranslateMetadata.total_characters", - index=3, - number=4, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3beta1.BatchTranslateMetadata.submit_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_BATCHTRANSLATEMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3091, - serialized_end=3430, -) - - -_BATCHTRANSLATERESPONSE = _descriptor.Descriptor( - name="BatchTranslateResponse", - full_name="google.cloud.translation.v3beta1.BatchTranslateResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="total_characters", - full_name="google.cloud.translation.v3beta1.BatchTranslateResponse.total_characters", - index=0, - number=1, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="translated_characters", - full_name="google.cloud.translation.v3beta1.BatchTranslateResponse.translated_characters", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="failed_characters", - full_name="google.cloud.translation.v3beta1.BatchTranslateResponse.failed_characters", - index=2, - number=3, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3beta1.BatchTranslateResponse.submit_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.translation.v3beta1.BatchTranslateResponse.end_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3433, - serialized_end=3636, -) - - -_GLOSSARYINPUTCONFIG = _descriptor.Descriptor( - name="GlossaryInputConfig", - full_name="google.cloud.translation.v3beta1.GlossaryInputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.translation.v3beta1.GlossaryInputConfig.gcs_source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="source", - full_name="google.cloud.translation.v3beta1.GlossaryInputConfig.source", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=3638, - serialized_end=3736, -) - - -_GLOSSARY_LANGUAGECODEPAIR = _descriptor.Descriptor( - name="LanguageCodePair", - full_name="google.cloud.translation.v3beta1.Glossary.LanguageCodePair", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="source_language_code", - full_name="google.cloud.translation.v3beta1.Glossary.LanguageCodePair.source_language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_language_code", - full_name="google.cloud.translation.v3beta1.Glossary.LanguageCodePair.target_language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4155, - serialized_end=4233, -) - -_GLOSSARY_LANGUAGECODESSET = _descriptor.Descriptor( - name="LanguageCodesSet", - full_name="google.cloud.translation.v3beta1.Glossary.LanguageCodesSet", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_codes", - full_name="google.cloud.translation.v3beta1.Glossary.LanguageCodesSet.language_codes", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4235, - serialized_end=4277, -) - -_GLOSSARY = _descriptor.Descriptor( - name="Glossary", - full_name="google.cloud.translation.v3beta1.Glossary", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3beta1.Glossary.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_pair", - full_name="google.cloud.translation.v3beta1.Glossary.language_pair", - index=1, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_codes_set", - full_name="google.cloud.translation.v3beta1.Glossary.language_codes_set", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.translation.v3beta1.Glossary.input_config", - index=3, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="entry_count", - full_name="google.cloud.translation.v3beta1.Glossary.entry_count", - index=4, - number=6, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3beta1.Glossary.submit_time", - index=5, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.translation.v3beta1.Glossary.end_time", - index=6, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_GLOSSARY_LANGUAGECODEPAIR, _GLOSSARY_LANGUAGECODESSET,], - enum_types=[], - serialized_options=b"\352Ab\n!translate.googleapis.com/Glossary\022=projects/{project}/locations/{location}/glossaries/{glossary}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="languages", - full_name="google.cloud.translation.v3beta1.Glossary.languages", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=3739, - serialized_end=4393, -) - - -_CREATEGLOSSARYREQUEST = _descriptor.Descriptor( - name="CreateGlossaryRequest", - full_name="google.cloud.translation.v3beta1.CreateGlossaryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3beta1.CreateGlossaryRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="glossary", - full_name="google.cloud.translation.v3beta1.CreateGlossaryRequest.glossary", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4396, - serialized_end=4545, -) - - -_GETGLOSSARYREQUEST = _descriptor.Descriptor( - name="GetGlossaryRequest", - full_name="google.cloud.translation.v3beta1.GetGlossaryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3beta1.GetGlossaryRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!translate.googleapis.com/Glossary", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4547, - serialized_end=4624, -) - - -_DELETEGLOSSARYREQUEST = _descriptor.Descriptor( - name="DeleteGlossaryRequest", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!translate.googleapis.com/Glossary", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4626, - serialized_end=4706, -) - - -_LISTGLOSSARIESREQUEST = _descriptor.Descriptor( - name="ListGlossariesRequest", - full_name="google.cloud.translation.v3beta1.ListGlossariesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.translation.v3beta1.ListGlossariesRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.translation.v3beta1.ListGlossariesRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.translation.v3beta1.ListGlossariesRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.translation.v3beta1.ListGlossariesRequest.filter", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4709, - serialized_end=4861, -) - - -_LISTGLOSSARIESRESPONSE = _descriptor.Descriptor( - name="ListGlossariesResponse", - full_name="google.cloud.translation.v3beta1.ListGlossariesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="glossaries", - full_name="google.cloud.translation.v3beta1.ListGlossariesResponse.glossaries", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.translation.v3beta1.ListGlossariesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4863, - serialized_end=4976, -) - - -_CREATEGLOSSARYMETADATA = _descriptor.Descriptor( - name="CreateGlossaryMetadata", - full_name="google.cloud.translation.v3beta1.CreateGlossaryMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3beta1.CreateGlossaryMetadata.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.translation.v3beta1.CreateGlossaryMetadata.state", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3beta1.CreateGlossaryMetadata.submit_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_CREATEGLOSSARYMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4979, - serialized_end=5248, -) - - -_DELETEGLOSSARYMETADATA = _descriptor.Descriptor( - name="DeleteGlossaryMetadata", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryMetadata.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryMetadata.state", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryMetadata.submit_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_DELETEGLOSSARYMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5251, - serialized_end=5520, -) - - -_DELETEGLOSSARYRESPONSE = _descriptor.Descriptor( - name="DeleteGlossaryResponse", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryResponse.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryResponse.submit_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.translation.v3beta1.DeleteGlossaryResponse.end_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5523, - serialized_end=5656, -) - -_TRANSLATETEXTREQUEST_LABELSENTRY.containing_type = _TRANSLATETEXTREQUEST -_TRANSLATETEXTREQUEST.fields_by_name[ - "glossary_config" -].message_type = _TRANSLATETEXTGLOSSARYCONFIG -_TRANSLATETEXTREQUEST.fields_by_name[ - "labels" -].message_type = _TRANSLATETEXTREQUEST_LABELSENTRY -_TRANSLATETEXTRESPONSE.fields_by_name["translations"].message_type = _TRANSLATION -_TRANSLATETEXTRESPONSE.fields_by_name[ - "glossary_translations" -].message_type = _TRANSLATION -_TRANSLATION.fields_by_name[ - "glossary_config" -].message_type = _TRANSLATETEXTGLOSSARYCONFIG -_DETECTLANGUAGEREQUEST_LABELSENTRY.containing_type = _DETECTLANGUAGEREQUEST -_DETECTLANGUAGEREQUEST.fields_by_name[ - "labels" -].message_type = _DETECTLANGUAGEREQUEST_LABELSENTRY -_DETECTLANGUAGEREQUEST.oneofs_by_name["source"].fields.append( - _DETECTLANGUAGEREQUEST.fields_by_name["content"] -) -_DETECTLANGUAGEREQUEST.fields_by_name[ - "content" -].containing_oneof = _DETECTLANGUAGEREQUEST.oneofs_by_name["source"] -_DETECTLANGUAGERESPONSE.fields_by_name["languages"].message_type = _DETECTEDLANGUAGE -_SUPPORTEDLANGUAGES.fields_by_name["languages"].message_type = _SUPPORTEDLANGUAGE -_INPUTCONFIG.fields_by_name["gcs_source"].message_type = _GCSSOURCE -_INPUTCONFIG.oneofs_by_name["source"].fields.append( - _INPUTCONFIG.fields_by_name["gcs_source"] -) -_INPUTCONFIG.fields_by_name[ - "gcs_source" -].containing_oneof = _INPUTCONFIG.oneofs_by_name["source"] -_OUTPUTCONFIG.fields_by_name["gcs_destination"].message_type = _GCSDESTINATION -_OUTPUTCONFIG.oneofs_by_name["destination"].fields.append( - _OUTPUTCONFIG.fields_by_name["gcs_destination"] -) -_OUTPUTCONFIG.fields_by_name[ - "gcs_destination" -].containing_oneof = _OUTPUTCONFIG.oneofs_by_name["destination"] -_BATCHTRANSLATETEXTREQUEST_MODELSENTRY.containing_type = _BATCHTRANSLATETEXTREQUEST -_BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY.fields_by_name[ - "value" -].message_type = _TRANSLATETEXTGLOSSARYCONFIG -_BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY.containing_type = _BATCHTRANSLATETEXTREQUEST -_BATCHTRANSLATETEXTREQUEST_LABELSENTRY.containing_type = _BATCHTRANSLATETEXTREQUEST -_BATCHTRANSLATETEXTREQUEST.fields_by_name[ - "models" -].message_type = _BATCHTRANSLATETEXTREQUEST_MODELSENTRY -_BATCHTRANSLATETEXTREQUEST.fields_by_name["input_configs"].message_type = _INPUTCONFIG -_BATCHTRANSLATETEXTREQUEST.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_BATCHTRANSLATETEXTREQUEST.fields_by_name[ - "glossaries" -].message_type = _BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY -_BATCHTRANSLATETEXTREQUEST.fields_by_name[ - "labels" -].message_type = _BATCHTRANSLATETEXTREQUEST_LABELSENTRY -_BATCHTRANSLATEMETADATA.fields_by_name[ - "state" -].enum_type = _BATCHTRANSLATEMETADATA_STATE -_BATCHTRANSLATEMETADATA.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_BATCHTRANSLATEMETADATA_STATE.containing_type = _BATCHTRANSLATEMETADATA -_BATCHTRANSLATERESPONSE.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_BATCHTRANSLATERESPONSE.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GLOSSARYINPUTCONFIG.fields_by_name["gcs_source"].message_type = _GCSSOURCE -_GLOSSARYINPUTCONFIG.oneofs_by_name["source"].fields.append( - _GLOSSARYINPUTCONFIG.fields_by_name["gcs_source"] -) -_GLOSSARYINPUTCONFIG.fields_by_name[ - "gcs_source" -].containing_oneof = _GLOSSARYINPUTCONFIG.oneofs_by_name["source"] -_GLOSSARY_LANGUAGECODEPAIR.containing_type = _GLOSSARY -_GLOSSARY_LANGUAGECODESSET.containing_type = _GLOSSARY -_GLOSSARY.fields_by_name["language_pair"].message_type = _GLOSSARY_LANGUAGECODEPAIR -_GLOSSARY.fields_by_name["language_codes_set"].message_type = _GLOSSARY_LANGUAGECODESSET -_GLOSSARY.fields_by_name["input_config"].message_type = _GLOSSARYINPUTCONFIG -_GLOSSARY.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GLOSSARY.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GLOSSARY.oneofs_by_name["languages"].fields.append( - _GLOSSARY.fields_by_name["language_pair"] -) -_GLOSSARY.fields_by_name["language_pair"].containing_oneof = _GLOSSARY.oneofs_by_name[ - "languages" -] -_GLOSSARY.oneofs_by_name["languages"].fields.append( - _GLOSSARY.fields_by_name["language_codes_set"] -) -_GLOSSARY.fields_by_name[ - "language_codes_set" -].containing_oneof = _GLOSSARY.oneofs_by_name["languages"] -_CREATEGLOSSARYREQUEST.fields_by_name["glossary"].message_type = _GLOSSARY -_LISTGLOSSARIESRESPONSE.fields_by_name["glossaries"].message_type = _GLOSSARY -_CREATEGLOSSARYMETADATA.fields_by_name[ - "state" -].enum_type = _CREATEGLOSSARYMETADATA_STATE -_CREATEGLOSSARYMETADATA.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_CREATEGLOSSARYMETADATA_STATE.containing_type = _CREATEGLOSSARYMETADATA -_DELETEGLOSSARYMETADATA.fields_by_name[ - "state" -].enum_type = _DELETEGLOSSARYMETADATA_STATE -_DELETEGLOSSARYMETADATA.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DELETEGLOSSARYMETADATA_STATE.containing_type = _DELETEGLOSSARYMETADATA -_DELETEGLOSSARYRESPONSE.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_DELETEGLOSSARYRESPONSE.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -DESCRIPTOR.message_types_by_name[ - "TranslateTextGlossaryConfig" -] = _TRANSLATETEXTGLOSSARYCONFIG -DESCRIPTOR.message_types_by_name["TranslateTextRequest"] = _TRANSLATETEXTREQUEST -DESCRIPTOR.message_types_by_name["TranslateTextResponse"] = _TRANSLATETEXTRESPONSE -DESCRIPTOR.message_types_by_name["Translation"] = _TRANSLATION -DESCRIPTOR.message_types_by_name["DetectLanguageRequest"] = _DETECTLANGUAGEREQUEST -DESCRIPTOR.message_types_by_name["DetectedLanguage"] = _DETECTEDLANGUAGE -DESCRIPTOR.message_types_by_name["DetectLanguageResponse"] = _DETECTLANGUAGERESPONSE -DESCRIPTOR.message_types_by_name[ - "GetSupportedLanguagesRequest" -] = _GETSUPPORTEDLANGUAGESREQUEST -DESCRIPTOR.message_types_by_name["SupportedLanguages"] = _SUPPORTEDLANGUAGES -DESCRIPTOR.message_types_by_name["SupportedLanguage"] = _SUPPORTEDLANGUAGE -DESCRIPTOR.message_types_by_name["GcsSource"] = _GCSSOURCE -DESCRIPTOR.message_types_by_name["InputConfig"] = _INPUTCONFIG -DESCRIPTOR.message_types_by_name["GcsDestination"] = _GCSDESTINATION -DESCRIPTOR.message_types_by_name["OutputConfig"] = _OUTPUTCONFIG -DESCRIPTOR.message_types_by_name[ - "BatchTranslateTextRequest" -] = _BATCHTRANSLATETEXTREQUEST -DESCRIPTOR.message_types_by_name["BatchTranslateMetadata"] = _BATCHTRANSLATEMETADATA -DESCRIPTOR.message_types_by_name["BatchTranslateResponse"] = _BATCHTRANSLATERESPONSE -DESCRIPTOR.message_types_by_name["GlossaryInputConfig"] = _GLOSSARYINPUTCONFIG -DESCRIPTOR.message_types_by_name["Glossary"] = _GLOSSARY -DESCRIPTOR.message_types_by_name["CreateGlossaryRequest"] = _CREATEGLOSSARYREQUEST -DESCRIPTOR.message_types_by_name["GetGlossaryRequest"] = _GETGLOSSARYREQUEST -DESCRIPTOR.message_types_by_name["DeleteGlossaryRequest"] = _DELETEGLOSSARYREQUEST -DESCRIPTOR.message_types_by_name["ListGlossariesRequest"] = _LISTGLOSSARIESREQUEST -DESCRIPTOR.message_types_by_name["ListGlossariesResponse"] = _LISTGLOSSARIESRESPONSE -DESCRIPTOR.message_types_by_name["CreateGlossaryMetadata"] = _CREATEGLOSSARYMETADATA -DESCRIPTOR.message_types_by_name["DeleteGlossaryMetadata"] = _DELETEGLOSSARYMETADATA -DESCRIPTOR.message_types_by_name["DeleteGlossaryResponse"] = _DELETEGLOSSARYRESPONSE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TranslateTextGlossaryConfig = _reflection.GeneratedProtocolMessageType( - "TranslateTextGlossaryConfig", - (_message.Message,), - { - "DESCRIPTOR": _TRANSLATETEXTGLOSSARYCONFIG, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Configures which glossary should be used for a specific target - language, and defines options for applying that glossary. - - Attributes: - glossary: - Required. Specifies the glossary used for this translation. - Use this format: projects/\ */locations/*/glossaries/\* - ignore_case: - Optional. Indicates match is case-insensitive. Default value - is false if missing. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.TranslateTextGlossaryConfig) - }, -) -_sym_db.RegisterMessage(TranslateTextGlossaryConfig) - -TranslateTextRequest = _reflection.GeneratedProtocolMessageType( - "TranslateTextRequest", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _TRANSLATETEXTREQUEST_LABELSENTRY, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.TranslateTextRequest.LabelsEntry) - }, - ), - "DESCRIPTOR": _TRANSLATETEXTREQUEST, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The request message for synchronous translation. - - Attributes: - contents: - Required. The content of the input in string format. We - recommend the total content be less than 30k codepoints. Use - BatchTranslateText for larger text. - mime_type: - Optional. The format of the source text, for example, - “text/html”, “text/plain”. If left blank, the MIME type - defaults to “text/html”. - source_language_code: - Optional. The BCP-47 language code of the input text if known, - for example, “en-US” or “sr-Latn”. Supported language codes - are listed in Language Support. If the source language isn’t - specified, the API attempts to identify the source language - automatically and returns the source language within the - response. - target_language_code: - Required. The BCP-47 language code to use for translation of - the input text, set to one of the language codes listed in - Language Support. - parent: - Required. Project or location to make a call. Must refer to a - caller’s project. Format: ``projects/{project-id}`` or - ``projects/{project-id}/locations/{location-id}``. For global - calls, use ``projects/{project-id}/locations/global`` or - ``projects/{project-id}``. Non-global location is required - for requests using AutoML models or custom glossaries. Models - and glossaries must be within the same region (have same - location-id), otherwise an INVALID_ARGUMENT (400) error is - returned. - model: - Optional. The ``model`` type requested for this translation. - The format depends on model type: - AutoML Translation - models: ``projects/{project-id}/locations/{location- - id}/models/{model-id}`` - General (built-in) models: - ``projects/{project-id}/locations/{location- - id}/models/general/nmt``, ``projects/{project- - id}/locations/{location-id}/models/general/base`` For global - (non-regionalized) requests, use ``location-id`` ``global``. - For example, ``projects/{project- - id}/locations/global/models/general/nmt``. If missing, the - system decides which google base model to use. - glossary_config: - Optional. Glossary to be applied. The glossary must be within - the same region (have the same location-id) as the model, - otherwise an INVALID_ARGUMENT (400) error is returned. - labels: - Optional. The labels with user-defined metadata for the - request. Label keys and values can be no longer than 63 - characters (Unicode codepoints), can only contain lowercase - letters, numeric characters, underscores and dashes. - International characters are allowed. Label values are - optional. Label keys must start with a letter. See - https://cloud.google.com/translate/docs/labels for more - information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.TranslateTextRequest) - }, -) -_sym_db.RegisterMessage(TranslateTextRequest) -_sym_db.RegisterMessage(TranslateTextRequest.LabelsEntry) - -TranslateTextResponse = _reflection.GeneratedProtocolMessageType( - "TranslateTextResponse", - (_message.Message,), - { - "DESCRIPTOR": _TRANSLATETEXTRESPONSE, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """ - Attributes: - translations: - Text translation responses with no glossary applied. This - field has the same length as [``contents``][google.cloud.trans - lation.v3beta1.TranslateTextRequest.contents]. - glossary_translations: - Text translation responses if a glossary is provided in the - request. This can be the same as [``translations``][google.clo - ud.translation.v3beta1.TranslateTextResponse.translations] if - no terms apply. This field has the same length as [``contents``][google.cloud.translation.v3beta1.TranslateTextRequest.contents]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.TranslateTextResponse) - }, -) -_sym_db.RegisterMessage(TranslateTextResponse) - -Translation = _reflection.GeneratedProtocolMessageType( - "Translation", - (_message.Message,), - { - "DESCRIPTOR": _TRANSLATION, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """A single translation response. - - Attributes: - translated_text: - Text translated into the target language. - model: - Only present when ``model`` is present in the request. This is - same as ``model`` provided in the request. - detected_language_code: - The BCP-47 language code of source text in the initial - request, detected automatically, if no source language was - passed within the initial request. If the source language was - passed, auto-detection of the language does not occur and this - field is empty. - glossary_config: - The ``glossary_config`` used for this translation. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.Translation) - }, -) -_sym_db.RegisterMessage(Translation) - -DetectLanguageRequest = _reflection.GeneratedProtocolMessageType( - "DetectLanguageRequest", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _DETECTLANGUAGEREQUEST_LABELSENTRY, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.DetectLanguageRequest.LabelsEntry) - }, - ), - "DESCRIPTOR": _DETECTLANGUAGEREQUEST, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The request message for language detection. - - Attributes: - parent: - Required. Project or location to make a call. Must refer to a - caller’s project. Format: ``projects/{project- - id}/locations/{location-id}`` or ``projects/{project-id}``. - For global calls, use ``projects/{project- - id}/locations/global`` or ``projects/{project-id}``. Only - models within the same region (has same location-id) can be - used. Otherwise an INVALID_ARGUMENT (400) error is returned. - model: - Optional. The language detection model to be used. Format: - ``projects/{project-id}/locations/{location- - id}/models/language-detection/{model-id}`` Only one language - detection model is currently supported: ``projects/{project- - id}/locations/{location-id}/models/language- - detection/default``. If not specified, the default model is - used. - source: - Required. The source of the document from which to detect the - language. - content: - The content of the input stored as a string. - mime_type: - Optional. The format of the source text, for example, - “text/html”, “text/plain”. If left blank, the MIME type - defaults to “text/html”. - labels: - Optional. The labels with user-defined metadata for the - request. Label keys and values can be no longer than 63 - characters (Unicode codepoints), can only contain lowercase - letters, numeric characters, underscores and dashes. - International characters are allowed. Label values are - optional. Label keys must start with a letter. See - https://cloud.google.com/translate/docs/labels for more - information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.DetectLanguageRequest) - }, -) -_sym_db.RegisterMessage(DetectLanguageRequest) -_sym_db.RegisterMessage(DetectLanguageRequest.LabelsEntry) - -DetectedLanguage = _reflection.GeneratedProtocolMessageType( - "DetectedLanguage", - (_message.Message,), - { - "DESCRIPTOR": _DETECTEDLANGUAGE, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The response message for language detection. - - Attributes: - language_code: - The BCP-47 language code of source content in the request, - detected automatically. - confidence: - The confidence of the detection result for this language. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.DetectedLanguage) - }, -) -_sym_db.RegisterMessage(DetectedLanguage) - -DetectLanguageResponse = _reflection.GeneratedProtocolMessageType( - "DetectLanguageResponse", - (_message.Message,), - { - "DESCRIPTOR": _DETECTLANGUAGERESPONSE, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The response message for language detection. - - Attributes: - languages: - A list of detected languages sorted by detection confidence in - descending order. The most probable language first. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.DetectLanguageResponse) - }, -) -_sym_db.RegisterMessage(DetectLanguageResponse) - -GetSupportedLanguagesRequest = _reflection.GeneratedProtocolMessageType( - "GetSupportedLanguagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSUPPORTEDLANGUAGESREQUEST, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The request message for discovering supported languages. - - Attributes: - parent: - Required. Project or location to make a call. Must refer to a - caller’s project. Format: ``projects/{project-id}`` or - ``projects/{project-id}/locations/{location-id}``. For global - calls, use ``projects/{project-id}/locations/global`` or - ``projects/{project-id}``. Non-global location is required - for AutoML models. Only models within the same region (have - same location-id) can be used, otherwise an INVALID_ARGUMENT - (400) error is returned. - display_language_code: - Optional. The language to use to return localized, human - readable names of supported languages. If missing, then - display names are not returned in a response. - model: - Optional. Get supported languages of this model. The format - depends on model type: - AutoML Translation models: - ``projects/{project-id}/locations/{location-id}/models/{model- - id}`` - General (built-in) models: ``projects/{project- - id}/locations/{location-id}/models/general/nmt``, - ``projects/{project-id}/locations/{location- - id}/models/general/base`` Returns languages supported by the - specified model. If missing, we get supported languages of - Google general base (PBMT) model. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.GetSupportedLanguagesRequest) - }, -) -_sym_db.RegisterMessage(GetSupportedLanguagesRequest) - -SupportedLanguages = _reflection.GeneratedProtocolMessageType( - "SupportedLanguages", - (_message.Message,), - { - "DESCRIPTOR": _SUPPORTEDLANGUAGES, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The response message for discovering supported languages. - - Attributes: - languages: - A list of supported language responses. This list contains an - entry for each language the Translation API supports. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.SupportedLanguages) - }, -) -_sym_db.RegisterMessage(SupportedLanguages) - -SupportedLanguage = _reflection.GeneratedProtocolMessageType( - "SupportedLanguage", - (_message.Message,), - { - "DESCRIPTOR": _SUPPORTEDLANGUAGE, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """A single supported language response corresponds to information - related to one supported language. - - Attributes: - language_code: - Supported language code, generally consisting of its ISO 639-1 - identifier, for example, ‘en’, ‘ja’. In certain cases, BCP-47 - codes including language and region identifiers are returned - (for example, ‘zh-TW’ and ‘zh-CN’) - display_name: - Human readable name of the language localized in the display - language specified in the request. - support_source: - Can be used as source language. - support_target: - Can be used as target language. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.SupportedLanguage) - }, -) -_sym_db.RegisterMessage(SupportedLanguage) - -GcsSource = _reflection.GeneratedProtocolMessageType( - "GcsSource", - (_message.Message,), - { - "DESCRIPTOR": _GCSSOURCE, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The Google Cloud Storage location for the input content. - - Attributes: - input_uri: - Required. Source data URI. For example, - ``gs://my_bucket/my_object``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.GcsSource) - }, -) -_sym_db.RegisterMessage(GcsSource) - -InputConfig = _reflection.GeneratedProtocolMessageType( - "InputConfig", - (_message.Message,), - { - "DESCRIPTOR": _INPUTCONFIG, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Input configuration for BatchTranslateText request. - - Attributes: - mime_type: - Optional. Can be “text/plain” or “text/html”. For ``.tsv``, - “text/html” is used if mime_type is missing. For ``.html``, - this field must be “text/html” or empty. For ``.txt``, this - field must be “text/plain” or empty. - source: - Required. Specify the input. - gcs_source: - Required. Google Cloud Storage location for the source input. - This can be a single file (for example, ``gs://translation- - test/input.tsv``) or a wildcard (for example, - ``gs://translation-test/*``). If a file extension is ``.tsv``, - it can contain either one or two columns. The first column - (optional) is the id of the text request. If the first column - is missing, we use the row number (0-based) from the input - file as the ID in the output file. The second column is the - actual text to be translated. We recommend each row be <= 10K - Unicode codepoints, otherwise an error might be returned. Note - that the input tsv must be RFC 4180 compliant. You could use - https://github.com/Clever/csvlint to check potential - formatting errors in your tsv file. csvlint –delimiter=‘:raw- - latex:`\t`’ your_input_file.tsv The other supported file - extensions are ``.txt`` or ``.html``, which is treated as a - single large chunk of text. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.InputConfig) - }, -) -_sym_db.RegisterMessage(InputConfig) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The Google Cloud Storage location for the output content. - - Attributes: - output_uri_prefix: - Required. There must be no files under ‘output_uri_prefix’. - ‘output_uri_prefix’ must end with “/” and start with “gs://”, - otherwise an INVALID_ARGUMENT (400) error is returned. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Output configuration for BatchTranslateText request. - - Attributes: - destination: - Required. The destination of output. - gcs_destination: - Google Cloud Storage destination for output content. For every - single input file (for example, gs://a/b/c.[extension]), we - generate at most 2 \* n output files. (n is the # of - target_language_codes in the BatchTranslateTextRequest). - Output files (tsv) generated are compliant with RFC 4180 - except that record delimiters are ``\\\\n`` instead of - ``\\\\r\\\\n``. We don’t provide any way to - change record delimiters. While the input files are being - processed, we write/update an index file ‘index.csv’ under - ‘output_uri_prefix’ (for example, gs://translation- - test/index.csv) The index file is generated/updated as new - files are being translated. The format is: - input_file,target_language_code,translations_file,errors_file, - glossary_translations_file,glossary_errors_file input_file is - one file we matched using gcs_source.input_uri. - target_language_code is provided in the request. - translations_file contains the translations. (details provided - below) errors_file contains the errors during processing of - the file. (details below). Both translations_file and - errors_file could be empty strings if we have no content to - output. glossary_translations_file and glossary_errors_file - are always empty strings if the input_file is tsv. They could - also be empty if we have no content to output. Once a row is - present in index.csv, the input/output matching never changes. - Callers should also expect all the content in input_file are - processed and ready to be consumed (that is, no partial output - file is written). The format of translations_file (for target - language code ‘trg’) is: - gs://translation_test/a_b_c\_‘trg’\_translations.[extension] - If the input file extension is tsv, the output has the - following columns: Column 1: ID of the request provided in the - input, if it’s not provided in the input, then the input row - number is used (0-based). Column 2: source sentence. Column 3: - translation without applying a glossary. Empty string if there - is an error. Column 4 (only present if a glossary is provided - in the request): translation after applying the glossary. - Empty string if there is an error applying the glossary. Could - be same string as column 3 if there is no glossary applied. - If input file extension is a txt or html, the translation is - directly written to the output file. If glossary is requested, - a separate glossary_translations_file has format of gs://trans - lation_test/a_b_c\_‘trg’\_glossary_translations.[extension] - The format of errors file (for target language code ‘trg’) is: - gs://translation_test/a_b_c\_‘trg’\_errors.[extension] If the - input file extension is tsv, errors_file contains the - following: Column 1: ID of the request provided in the input, - if it’s not provided in the input, then the input row number - is used (0-based). Column 2: source sentence. Column 3: Error - detail for the translation. Could be empty. Column 4 (only - present if a glossary is provided in the request): Error when - applying the glossary. If the input file extension is txt or - html, glossary_error_file will be generated that contains - error details. glossary_error_file has format of gs://translat - ion_test/a_b_c\_‘trg’\_glossary_errors.[extension] - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -BatchTranslateTextRequest = _reflection.GeneratedProtocolMessageType( - "BatchTranslateTextRequest", - (_message.Message,), - { - "ModelsEntry": _reflection.GeneratedProtocolMessageType( - "ModelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATETEXTREQUEST_MODELSENTRY, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.BatchTranslateTextRequest.ModelsEntry) - }, - ), - "GlossariesEntry": _reflection.GeneratedProtocolMessageType( - "GlossariesEntry", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.BatchTranslateTextRequest.GlossariesEntry) - }, - ), - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATETEXTREQUEST_LABELSENTRY, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.BatchTranslateTextRequest.LabelsEntry) - }, - ), - "DESCRIPTOR": _BATCHTRANSLATETEXTREQUEST, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """The batch translation request. - - Attributes: - parent: - Required. Location to make a call. Must refer to a caller’s - project. Format: ``projects/{project-id}/locations/{location- - id}``. The ``global`` location is not supported for batch - translation. Only AutoML Translation models or glossaries - within the same region (have the same location-id) can be - used, otherwise an INVALID_ARGUMENT (400) error is returned. - source_language_code: - Required. Source language code. - target_language_codes: - Required. Specify up to 10 language codes here. - models: - Optional. The models to use for translation. Map’s key is - target language code. Map’s value is model name. Value can be - a built-in general model, or an AutoML Translation model. The - value format depends on model type: - AutoML Translation - models: ``projects/{project-id}/locations/{location- - id}/models/{model-id}`` - General (built-in) models: - ``projects/{project-id}/locations/{location- - id}/models/general/nmt``, ``projects/{project- - id}/locations/{location-id}/models/general/base`` If the map - is empty or a specific model is not requested for a language - pair, then default google model (nmt) is used. - input_configs: - Required. Input configurations. The total number of files - matched should be <= 1000. The total content size should be <= - 100M Unicode codepoints. The files must use UTF-8 encoding. - output_config: - Required. Output configuration. If 2 input configs match to - the same file (that is, same input path), we don’t generate - output for duplicate inputs. - glossaries: - Optional. Glossaries to be applied for translation. It’s keyed - by target language code. - labels: - Optional. The labels with user-defined metadata for the - request. Label keys and values can be no longer than 63 - characters (Unicode codepoints), can only contain lowercase - letters, numeric characters, underscores and dashes. - International characters are allowed. Label values are - optional. Label keys must start with a letter. See - https://cloud.google.com/translate/docs/labels for more - information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.BatchTranslateTextRequest) - }, -) -_sym_db.RegisterMessage(BatchTranslateTextRequest) -_sym_db.RegisterMessage(BatchTranslateTextRequest.ModelsEntry) -_sym_db.RegisterMessage(BatchTranslateTextRequest.GlossariesEntry) -_sym_db.RegisterMessage(BatchTranslateTextRequest.LabelsEntry) - -BatchTranslateMetadata = _reflection.GeneratedProtocolMessageType( - "BatchTranslateMetadata", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATEMETADATA, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """State metadata for the batch translation operation. - - Attributes: - state: - The state of the operation. - translated_characters: - Number of successfully translated characters so far (Unicode - codepoints). - failed_characters: - Number of characters that have failed to process so far - (Unicode codepoints). - total_characters: - Total number of characters (Unicode codepoints). This is the - total number of codepoints from input files times the number - of target languages and appears here shortly after the call is - submitted. - submit_time: - Time when the operation was submitted. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.BatchTranslateMetadata) - }, -) -_sym_db.RegisterMessage(BatchTranslateMetadata) - -BatchTranslateResponse = _reflection.GeneratedProtocolMessageType( - "BatchTranslateResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHTRANSLATERESPONSE, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Stored in the [google.longrunning.Operation.response][google.longrunni - ng.Operation.response] field returned by BatchTranslateText if at - least one sentence is translated successfully. - - Attributes: - total_characters: - Total number of characters (Unicode codepoints). - translated_characters: - Number of successfully translated characters (Unicode - codepoints). - failed_characters: - Number of characters that have failed to process (Unicode - codepoints). - submit_time: - Time when the operation was submitted. - end_time: - The time when the operation is finished and [google.longrunnin - g.Operation.done][google.longrunning.Operation.done] is set to - true. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.BatchTranslateResponse) - }, -) -_sym_db.RegisterMessage(BatchTranslateResponse) - -GlossaryInputConfig = _reflection.GeneratedProtocolMessageType( - "GlossaryInputConfig", - (_message.Message,), - { - "DESCRIPTOR": _GLOSSARYINPUTCONFIG, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Input configuration for glossaries. - - Attributes: - source: - Required. Specify the input. - gcs_source: - Required. Google Cloud Storage location of glossary data. File - format is determined based on the filename extension. API - returns [google.rpc.Code.INVALID_ARGUMENT] for unsupported - URI-s and file formats. Wildcards are not allowed. This must - be a single file in one of the following formats: For - unidirectional glossaries: - TSV/CSV (``.tsv``/``.csv``): 2 - column file, tab- or comma-separated. The first column is - source text. The second column is target text. The file - must not contain headers. That is, the first row is data, - not column names. - TMX (``.tmx``): TMX file with parallel - data defining source/target term pairs. For equivalent - term sets glossaries: - CSV (``.csv``): Multi-column CSV - file defining equivalent glossary terms in multiple - languages. The format is defined for Google Translation - Toolkit and documented in `Use a glossary `__. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.GlossaryInputConfig) - }, -) -_sym_db.RegisterMessage(GlossaryInputConfig) - -Glossary = _reflection.GeneratedProtocolMessageType( - "Glossary", - (_message.Message,), - { - "LanguageCodePair": _reflection.GeneratedProtocolMessageType( - "LanguageCodePair", - (_message.Message,), - { - "DESCRIPTOR": _GLOSSARY_LANGUAGECODEPAIR, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Used with unidirectional glossaries. - - Attributes: - source_language_code: - Required. The BCP-47 language code of the input text, for - example, “en-US”. Expected to be an exact match for - GlossaryTerm.language_code. - target_language_code: - Required. The BCP-47 language code for translation output, for - example, “zh-CN”. Expected to be an exact match for - GlossaryTerm.language_code. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.Glossary.LanguageCodePair) - }, - ), - "LanguageCodesSet": _reflection.GeneratedProtocolMessageType( - "LanguageCodesSet", - (_message.Message,), - { - "DESCRIPTOR": _GLOSSARY_LANGUAGECODESSET, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Used with equivalent term set glossaries. - - Attributes: - language_codes: - The BCP-47 language code(s) for terms defined in the glossary. - All entries are unique. The list contains at least two - entries. Expected to be an exact match for - GlossaryTerm.language_code. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.Glossary.LanguageCodesSet) - }, - ), - "DESCRIPTOR": _GLOSSARY, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Represents a glossary built from user provided data. - - Attributes: - name: - Required. The resource name of the glossary. Glossary names - have the form ``projects/{project-id}/locations/{location- - id}/glossaries/{glossary-id}``. - languages: - Languages supported by the glossary. - language_pair: - Used with unidirectional glossaries. - language_codes_set: - Used with equivalent term set glossaries. - input_config: - Required. Provides examples to build the glossary from. Total - glossary must not exceed 10M Unicode codepoints. - entry_count: - Output only. The number of entries defined in the glossary. - submit_time: - Output only. When CreateGlossary was called. - end_time: - Output only. When the glossary creation was finished. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.Glossary) - }, -) -_sym_db.RegisterMessage(Glossary) -_sym_db.RegisterMessage(Glossary.LanguageCodePair) -_sym_db.RegisterMessage(Glossary.LanguageCodesSet) - -CreateGlossaryRequest = _reflection.GeneratedProtocolMessageType( - "CreateGlossaryRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEGLOSSARYREQUEST, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Request message for CreateGlossary. - - Attributes: - parent: - Required. The project name. - glossary: - Required. The glossary to create. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.CreateGlossaryRequest) - }, -) -_sym_db.RegisterMessage(CreateGlossaryRequest) - -GetGlossaryRequest = _reflection.GeneratedProtocolMessageType( - "GetGlossaryRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETGLOSSARYREQUEST, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Request message for GetGlossary. - - Attributes: - name: - Required. The name of the glossary to retrieve. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.GetGlossaryRequest) - }, -) -_sym_db.RegisterMessage(GetGlossaryRequest) - -DeleteGlossaryRequest = _reflection.GeneratedProtocolMessageType( - "DeleteGlossaryRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEGLOSSARYREQUEST, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Request message for DeleteGlossary. - - Attributes: - name: - Required. The name of the glossary to delete. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.DeleteGlossaryRequest) - }, -) -_sym_db.RegisterMessage(DeleteGlossaryRequest) - -ListGlossariesRequest = _reflection.GeneratedProtocolMessageType( - "ListGlossariesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTGLOSSARIESREQUEST, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Request message for ListGlossaries. - - Attributes: - parent: - Required. The name of the project from which to list all of - the glossaries. - page_size: - Optional. Requested page size. The server may return fewer - glossaries than requested. If unspecified, the server picks an - appropriate default. - page_token: - Optional. A token identifying a page of results the server - should return. Typically, this is the value of - [ListGlossariesResponse.next_page_token] returned from the - previous call to ``ListGlossaries`` method. The first page is - returned if ``page_token``\ is empty or missing. - filter: - Optional. Filter specifying constraints of a list operation. - Filtering is not supported yet, and the parameter currently - has no effect. If missing, no filtering is performed. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.ListGlossariesRequest) - }, -) -_sym_db.RegisterMessage(ListGlossariesRequest) - -ListGlossariesResponse = _reflection.GeneratedProtocolMessageType( - "ListGlossariesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTGLOSSARIESRESPONSE, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Response message for ListGlossaries. - - Attributes: - glossaries: - The list of glossaries for a project. - next_page_token: - A token to retrieve a page of results. Pass this value in the - [ListGlossariesRequest.page_token] field in the subsequent - call to ``ListGlossaries`` method to retrieve the next page of - results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.ListGlossariesResponse) - }, -) -_sym_db.RegisterMessage(ListGlossariesResponse) - -CreateGlossaryMetadata = _reflection.GeneratedProtocolMessageType( - "CreateGlossaryMetadata", - (_message.Message,), - { - "DESCRIPTOR": _CREATEGLOSSARYMETADATA, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Stored in the [google.longrunning.Operation.metadata][google.longrunni - ng.Operation.metadata] field returned by CreateGlossary. - - Attributes: - name: - The name of the glossary that is being created. - state: - The current state of the glossary creation operation. - submit_time: - The time when the operation was submitted to the server. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.CreateGlossaryMetadata) - }, -) -_sym_db.RegisterMessage(CreateGlossaryMetadata) - -DeleteGlossaryMetadata = _reflection.GeneratedProtocolMessageType( - "DeleteGlossaryMetadata", - (_message.Message,), - { - "DESCRIPTOR": _DELETEGLOSSARYMETADATA, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Stored in the [google.longrunning.Operation.metadata][google.longrunni - ng.Operation.metadata] field returned by DeleteGlossary. - - Attributes: - name: - The name of the glossary that is being deleted. - state: - The current state of the glossary deletion operation. - submit_time: - The time when the operation was submitted to the server. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.DeleteGlossaryMetadata) - }, -) -_sym_db.RegisterMessage(DeleteGlossaryMetadata) - -DeleteGlossaryResponse = _reflection.GeneratedProtocolMessageType( - "DeleteGlossaryResponse", - (_message.Message,), - { - "DESCRIPTOR": _DELETEGLOSSARYRESPONSE, - "__module__": "google.cloud.translate_v3beta1.proto.translation_service_pb2", - "__doc__": """Stored in the [google.longrunning.Operation.response][google.longrunni - ng.Operation.response] field returned by DeleteGlossary. - - Attributes: - name: - The name of the deleted glossary. - submit_time: - The time when the operation was submitted to the server. - end_time: - The time when the glossary deletion is finished and [google.lo - ngrunning.Operation.done][google.longrunning.Operation.done] - is set to true. - """, - # @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.DeleteGlossaryResponse) - }, -) -_sym_db.RegisterMessage(DeleteGlossaryResponse) - - -DESCRIPTOR._options = None -_TRANSLATETEXTGLOSSARYCONFIG.fields_by_name["glossary"]._options = None -_TRANSLATETEXTGLOSSARYCONFIG.fields_by_name["ignore_case"]._options = None -_TRANSLATETEXTREQUEST_LABELSENTRY._options = None -_TRANSLATETEXTREQUEST.fields_by_name["contents"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["mime_type"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["source_language_code"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["target_language_code"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["parent"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["model"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["glossary_config"]._options = None -_TRANSLATETEXTREQUEST.fields_by_name["labels"]._options = None -_DETECTLANGUAGEREQUEST_LABELSENTRY._options = None -_DETECTLANGUAGEREQUEST.fields_by_name["parent"]._options = None -_DETECTLANGUAGEREQUEST.fields_by_name["model"]._options = None -_DETECTLANGUAGEREQUEST.fields_by_name["mime_type"]._options = None -_GETSUPPORTEDLANGUAGESREQUEST.fields_by_name["parent"]._options = None -_GETSUPPORTEDLANGUAGESREQUEST.fields_by_name["display_language_code"]._options = None -_GETSUPPORTEDLANGUAGESREQUEST.fields_by_name["model"]._options = None -_GCSSOURCE.fields_by_name["input_uri"]._options = None -_INPUTCONFIG.fields_by_name["mime_type"]._options = None -_GCSDESTINATION.fields_by_name["output_uri_prefix"]._options = None -_BATCHTRANSLATETEXTREQUEST_MODELSENTRY._options = None -_BATCHTRANSLATETEXTREQUEST_GLOSSARIESENTRY._options = None -_BATCHTRANSLATETEXTREQUEST_LABELSENTRY._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["parent"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["source_language_code"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["target_language_codes"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["models"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["input_configs"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["output_config"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["glossaries"]._options = None -_BATCHTRANSLATETEXTREQUEST.fields_by_name["labels"]._options = None -_GLOSSARY.fields_by_name["name"]._options = None -_GLOSSARY.fields_by_name["entry_count"]._options = None -_GLOSSARY.fields_by_name["submit_time"]._options = None -_GLOSSARY.fields_by_name["end_time"]._options = None -_GLOSSARY._options = None -_CREATEGLOSSARYREQUEST.fields_by_name["parent"]._options = None -_CREATEGLOSSARYREQUEST.fields_by_name["glossary"]._options = None -_GETGLOSSARYREQUEST.fields_by_name["name"]._options = None -_DELETEGLOSSARYREQUEST.fields_by_name["name"]._options = None -_LISTGLOSSARIESREQUEST.fields_by_name["parent"]._options = None -_LISTGLOSSARIESREQUEST.fields_by_name["page_size"]._options = None -_LISTGLOSSARIESREQUEST.fields_by_name["page_token"]._options = None -_LISTGLOSSARIESREQUEST.fields_by_name["filter"]._options = None - -_TRANSLATIONSERVICE = _descriptor.ServiceDescriptor( - name="TranslationService", - full_name="google.cloud.translation.v3beta1.TranslationService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\030translate.googleapis.com\322A`https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-translation", - create_key=_descriptor._internal_create_key, - serialized_start=5659, - serialized_end=7733, - methods=[ - _descriptor.MethodDescriptor( - name="TranslateText", - full_name="google.cloud.translation.v3beta1.TranslationService.TranslateText", - index=0, - containing_service=None, - input_type=_TRANSLATETEXTREQUEST, - output_type=_TRANSLATETEXTRESPONSE, - serialized_options=b'\202\323\344\223\002l"6/v3beta1/{parent=projects/*/locations/*}:translateText:\001*Z/"*/v3beta1/{parent=projects/*}:translateText:\001*', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DetectLanguage", - full_name="google.cloud.translation.v3beta1.TranslationService.DetectLanguage", - index=1, - containing_service=None, - input_type=_DETECTLANGUAGEREQUEST, - output_type=_DETECTLANGUAGERESPONSE, - serialized_options=b'\202\323\344\223\002n"7/v3beta1/{parent=projects/*/locations/*}:detectLanguage:\001*Z0"+/v3beta1/{parent=projects/*}:detectLanguage:\001*\332A\026parent,model,mime_type', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSupportedLanguages", - full_name="google.cloud.translation.v3beta1.TranslationService.GetSupportedLanguages", - index=2, - containing_service=None, - input_type=_GETSUPPORTEDLANGUAGESREQUEST, - output_type=_SUPPORTEDLANGUAGES, - serialized_options=b'\202\323\344\223\002p\022;/v3beta1/{parent=projects/*/locations/*}/supportedLanguagesZ1\022//v3beta1/{parent=projects/*}/supportedLanguages\332A"parent,display_language_code,model', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="BatchTranslateText", - full_name="google.cloud.translation.v3beta1.TranslationService.BatchTranslateText", - index=3, - containing_service=None, - input_type=_BATCHTRANSLATETEXTREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002@";/v3beta1/{parent=projects/*/locations/*}:batchTranslateText:\001*\312A0\n\026BatchTranslateResponse\022\026BatchTranslateMetadata', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateGlossary", - full_name="google.cloud.translation.v3beta1.TranslationService.CreateGlossary", - index=4, - containing_service=None, - input_type=_CREATEGLOSSARYREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002?"3/v3beta1/{parent=projects/*/locations/*}/glossaries:\010glossary\332A\017parent,glossary\312A"\n\010Glossary\022\026CreateGlossaryMetadata', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListGlossaries", - full_name="google.cloud.translation.v3beta1.TranslationService.ListGlossaries", - index=5, - containing_service=None, - input_type=_LISTGLOSSARIESREQUEST, - output_type=_LISTGLOSSARIESRESPONSE, - serialized_options=b"\202\323\344\223\0025\0223/v3beta1/{parent=projects/*/locations/*}/glossaries\332A\006parent\332A\rparent,filter", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetGlossary", - full_name="google.cloud.translation.v3beta1.TranslationService.GetGlossary", - index=6, - containing_service=None, - input_type=_GETGLOSSARYREQUEST, - output_type=_GLOSSARY, - serialized_options=b"\202\323\344\223\0025\0223/v3beta1/{name=projects/*/locations/*/glossaries/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteGlossary", - full_name="google.cloud.translation.v3beta1.TranslationService.DeleteGlossary", - index=7, - containing_service=None, - input_type=_DELETEGLOSSARYREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b"\202\323\344\223\0025*3/v3beta1/{name=projects/*/locations/*/glossaries/*}\332A\004name\312A0\n\026DeleteGlossaryResponse\022\026DeleteGlossaryMetadata", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_TRANSLATIONSERVICE) - -DESCRIPTOR.services_by_name["TranslationService"] = _TRANSLATIONSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service_pb2_grpc.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service_pb2_grpc.py deleted file mode 100644 index 03a0243786df..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/proto/translation_service_pb2_grpc.py +++ /dev/null @@ -1,411 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.translate_v3beta1.proto import ( - translation_service_pb2 as google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) - - -class TranslationServiceStub(object): - """Proto file for the Cloud Translation API (v3beta1). - - Provides natural language translation operations. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.TranslateText = channel.unary_unary( - "/google.cloud.translation.v3beta1.TranslationService/TranslateText", - request_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.TranslateTextRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.TranslateTextResponse.FromString, - ) - self.DetectLanguage = channel.unary_unary( - "/google.cloud.translation.v3beta1.TranslationService/DetectLanguage", - request_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DetectLanguageRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DetectLanguageResponse.FromString, - ) - self.GetSupportedLanguages = channel.unary_unary( - "/google.cloud.translation.v3beta1.TranslationService/GetSupportedLanguages", - request_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.GetSupportedLanguagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.SupportedLanguages.FromString, - ) - self.BatchTranslateText = channel.unary_unary( - "/google.cloud.translation.v3beta1.TranslationService/BatchTranslateText", - request_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.BatchTranslateTextRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.CreateGlossary = channel.unary_unary( - "/google.cloud.translation.v3beta1.TranslationService/CreateGlossary", - request_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.CreateGlossaryRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.ListGlossaries = channel.unary_unary( - "/google.cloud.translation.v3beta1.TranslationService/ListGlossaries", - request_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.ListGlossariesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.ListGlossariesResponse.FromString, - ) - self.GetGlossary = channel.unary_unary( - "/google.cloud.translation.v3beta1.TranslationService/GetGlossary", - request_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.GetGlossaryRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.Glossary.FromString, - ) - self.DeleteGlossary = channel.unary_unary( - "/google.cloud.translation.v3beta1.TranslationService/DeleteGlossary", - request_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DeleteGlossaryRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - - -class TranslationServiceServicer(object): - """Proto file for the Cloud Translation API (v3beta1). - - Provides natural language translation operations. - """ - - def TranslateText(self, request, context): - """Translates input text and returns translated text. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DetectLanguage(self, request, context): - """Detects the language of text within a request. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSupportedLanguages(self, request, context): - """Returns a list of supported languages for translation. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def BatchTranslateText(self, request, context): - """Translates a large volume of text in asynchronous batch mode. - This function provides real-time output as the inputs are being processed. - If caller cancels a request, the partial results (for an input file, it's - all or nothing) may still be available on the specified output location. - - This call returns immediately and you can - use google.longrunning.Operation.name to poll the status of the call. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateGlossary(self, request, context): - """Creates a glossary and returns the long-running operation. Returns - NOT_FOUND, if the project doesn't exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListGlossaries(self, request, context): - """Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't - exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetGlossary(self, request, context): - """Gets a glossary. Returns NOT_FOUND, if the glossary doesn't - exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteGlossary(self, request, context): - """Deletes a glossary, or cancels glossary construction - if the glossary isn't created yet. - Returns NOT_FOUND, if the glossary doesn't exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_TranslationServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "TranslateText": grpc.unary_unary_rpc_method_handler( - servicer.TranslateText, - request_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.TranslateTextRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.TranslateTextResponse.SerializeToString, - ), - "DetectLanguage": grpc.unary_unary_rpc_method_handler( - servicer.DetectLanguage, - request_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DetectLanguageRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DetectLanguageResponse.SerializeToString, - ), - "GetSupportedLanguages": grpc.unary_unary_rpc_method_handler( - servicer.GetSupportedLanguages, - request_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.GetSupportedLanguagesRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.SupportedLanguages.SerializeToString, - ), - "BatchTranslateText": grpc.unary_unary_rpc_method_handler( - servicer.BatchTranslateText, - request_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.BatchTranslateTextRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "CreateGlossary": grpc.unary_unary_rpc_method_handler( - servicer.CreateGlossary, - request_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.CreateGlossaryRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "ListGlossaries": grpc.unary_unary_rpc_method_handler( - servicer.ListGlossaries, - request_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.ListGlossariesRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.ListGlossariesResponse.SerializeToString, - ), - "GetGlossary": grpc.unary_unary_rpc_method_handler( - servicer.GetGlossary, - request_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.GetGlossaryRequest.FromString, - response_serializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.Glossary.SerializeToString, - ), - "DeleteGlossary": grpc.unary_unary_rpc_method_handler( - servicer.DeleteGlossary, - request_deserializer=google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DeleteGlossaryRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.translation.v3beta1.TranslationService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class TranslationService(object): - """Proto file for the Cloud Translation API (v3beta1). - - Provides natural language translation operations. - """ - - @staticmethod - def TranslateText( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3beta1.TranslationService/TranslateText", - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.TranslateTextRequest.SerializeToString, - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.TranslateTextResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DetectLanguage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3beta1.TranslationService/DetectLanguage", - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DetectLanguageRequest.SerializeToString, - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DetectLanguageResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetSupportedLanguages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3beta1.TranslationService/GetSupportedLanguages", - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.GetSupportedLanguagesRequest.SerializeToString, - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.SupportedLanguages.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def BatchTranslateText( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3beta1.TranslationService/BatchTranslateText", - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.BatchTranslateTextRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateGlossary( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3beta1.TranslationService/CreateGlossary", - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.CreateGlossaryRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListGlossaries( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3beta1.TranslationService/ListGlossaries", - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.ListGlossariesRequest.SerializeToString, - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.ListGlossariesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetGlossary( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3beta1.TranslationService/GetGlossary", - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.GetGlossaryRequest.SerializeToString, - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.Glossary.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteGlossary( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.translation.v3beta1.TranslationService/DeleteGlossary", - google_dot_cloud_dot_translate__v3beta1_dot_proto_dot_translation__service__pb2.DeleteGlossaryRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/py.typed b/packages/google-cloud-translate/google/cloud/translate_v3beta1/py.typed new file mode 100644 index 000000000000..dd819a47cefe --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-translation package uses inline types. diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/__init__.py new file mode 100644 index 000000000000..42ffdf2bc43d --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# 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. +# diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/__init__.py new file mode 100644 index 000000000000..e24427116f9f --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from .client import TranslationServiceClient +from .async_client import TranslationServiceAsyncClient + +__all__ = ( + "TranslationServiceClient", + "TranslationServiceAsyncClient", +) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/async_client.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/async_client.py new file mode 100644 index 000000000000..c7908f2bf5ef --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/async_client.py @@ -0,0 +1,799 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.translate_v3beta1.services.translation_service import pagers +from google.cloud.translate_v3beta1.types import translation_service +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import TranslationServiceTransport +from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport +from .client import TranslationServiceClient + + +class TranslationServiceAsyncClient: + """Provides natural language translation operations.""" + + _client: TranslationServiceClient + + DEFAULT_ENDPOINT = TranslationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TranslationServiceClient.DEFAULT_MTLS_ENDPOINT + + glossary_path = staticmethod(TranslationServiceClient.glossary_path) + + from_service_account_file = TranslationServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(TranslationServiceClient).get_transport_class, + type(TranslationServiceClient), + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, TranslationServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the translation service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TranslationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = TranslationServiceClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def translate_text( + self, + request: translation_service.TranslateTextRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateTextResponse: + r"""Translates input text and returns translated text. + + Args: + request (:class:`~.translation_service.TranslateTextRequest`): + The request object. The request message for synchronous + translation. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.TranslateTextResponse: + + """ + # Create or coerce a protobuf request object. + + request = translation_service.TranslateTextRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.translate_text, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def detect_language( + self, + request: translation_service.DetectLanguageRequest = None, + *, + parent: str = None, + model: str = None, + mime_type: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.DetectLanguageResponse: + r"""Detects the language of text within a request. + + Args: + request (:class:`~.translation_service.DetectLanguageRequest`): + The request object. The request message for language + detection. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: + ``projects/{project-id}/locations/{location-id}`` or + ``projects/{project-id}``. + + For global calls, use + ``projects/{project-id}/locations/global`` or + ``projects/{project-id}``. + + Only models within the same region (has same + location-id) can be used. Otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. The language detection model to be used. + + Format: + ``projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}`` + + Only one language detection model is currently + supported: + ``projects/{project-id}/locations/{location-id}/models/language-detection/default``. + + If not specified, the default model is used. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mime_type (:class:`str`): + Optional. The format of the source + text, for example, "text/html", + "text/plain". If left blank, the MIME + type defaults to "text/html". + This corresponds to the ``mime_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.DetectLanguageResponse: + The response message for language + detection. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, model, mime_type]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.DetectLanguageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if model is not None: + request.model = model + if mime_type is not None: + request.mime_type = mime_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.detect_language, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_supported_languages( + self, + request: translation_service.GetSupportedLanguagesRequest = None, + *, + parent: str = None, + display_language_code: str = None, + model: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.SupportedLanguages: + r"""Returns a list of supported languages for + translation. + + Args: + request (:class:`~.translation_service.GetSupportedLanguagesRequest`): + The request object. The request message for discovering + supported languages. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: ``projects/{project-id}`` or + ``projects/{project-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-id}/locations/global`` or + ``projects/{project-id}``. + + Non-global location is required for AutoML models. + + Only models within the same region (have same + location-id) can be used, otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_language_code (:class:`str`): + Optional. The language to use to + return localized, human readable names + of supported languages. If missing, then + display names are not returned in a + response. + This corresponds to the ``display_language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. Get supported languages of this model. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-id}/locations/{location-id}/models/general/base`` + + Returns languages supported by the specified model. If + missing, we get supported languages of Google general + base (PBMT) model. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.SupportedLanguages: + The response message for discovering + supported languages. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, display_language_code, model]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.GetSupportedLanguagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if display_language_code is not None: + request.display_language_code = display_language_code + if model is not None: + request.model = model + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_supported_languages, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def batch_translate_text( + self, + request: translation_service.BatchTranslateTextRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Translates a large volume of text in asynchronous + batch mode. This function provides real-time output as + the inputs are being processed. If caller cancels a + request, the partial results (for an input file, it's + all or nothing) may still be available on the specified + output location. + This call returns immediately and you can + use google.longrunning.Operation.name to poll the status + of the call. + + Args: + request (:class:`~.translation_service.BatchTranslateTextRequest`): + The request object. The batch translation request. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.BatchTranslateResponse``: + Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by BatchTranslateText if at least one + sentence is translated successfully. + + """ + # Create or coerce a protobuf request object. + + request = translation_service.BatchTranslateTextRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_translate_text, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + translation_service.BatchTranslateResponse, + metadata_type=translation_service.BatchTranslateMetadata, + ) + + # Done; return the response. + return response + + async def create_glossary( + self, + request: translation_service.CreateGlossaryRequest = None, + *, + parent: str = None, + glossary: translation_service.Glossary = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a glossary and returns the long-running operation. + Returns NOT_FOUND, if the project doesn't exist. + + Args: + request (:class:`~.translation_service.CreateGlossaryRequest`): + The request object. Request message for CreateGlossary. + parent (:class:`str`): + Required. The project name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + glossary (:class:`~.translation_service.Glossary`): + Required. The glossary to create. + This corresponds to the ``glossary`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.Glossary``: Represents a + glossary built from user provided data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, glossary]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.CreateGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if glossary is not None: + request.glossary = glossary + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_glossary, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + translation_service.Glossary, + metadata_type=translation_service.CreateGlossaryMetadata, + ) + + # Done; return the response. + return response + + async def list_glossaries( + self, + request: translation_service.ListGlossariesRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGlossariesAsyncPager: + r"""Lists glossaries in a project. Returns NOT_FOUND, if the project + doesn't exist. + + Args: + request (:class:`~.translation_service.ListGlossariesRequest`): + The request object. Request message for ListGlossaries. + parent (:class:`str`): + Required. The name of the project + from which to list all of the + glossaries. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filter specifying + constraints of a list operation. + Filtering is not supported yet, and the + parameter currently has no effect. If + missing, no filtering is performed. + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListGlossariesAsyncPager: + Response message for ListGlossaries. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, filter]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.ListGlossariesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_glossaries, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListGlossariesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_glossary( + self, + request: translation_service.GetGlossaryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.Glossary: + r"""Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + exist. + + Args: + request (:class:`~.translation_service.GetGlossaryRequest`): + The request object. Request message for GetGlossary. + name (:class:`str`): + Required. The name of the glossary to + retrieve. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.Glossary: + Represents a glossary built from user + provided data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.GetGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_glossary, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_glossary( + self, + request: translation_service.DeleteGlossaryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a glossary, or cancels glossary construction if the + glossary isn't created yet. Returns NOT_FOUND, if the glossary + doesn't exist. + + Args: + request (:class:`~.translation_service.DeleteGlossaryRequest`): + The request object. Request message for DeleteGlossary. + name (:class:`str`): + Required. The name of the glossary to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.DeleteGlossaryResponse``: + Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by DeleteGlossary. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = translation_service.DeleteGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_glossary, + default_timeout=None, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + translation_service.DeleteGlossaryResponse, + metadata_type=translation_service.DeleteGlossaryMetadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-translation", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("TranslationServiceAsyncClient",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/client.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/client.py new file mode 100644 index 000000000000..b4efa65994b3 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/client.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from collections import OrderedDict +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.translate_v3beta1.services.translation_service import pagers +from google.cloud.translate_v3beta1.types import translation_service +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import TranslationServiceTransport +from .transports.grpc import TranslationServiceGrpcTransport +from .transports.grpc_asyncio import TranslationServiceGrpcAsyncIOTransport + + +class TranslationServiceClientMeta(type): + """Metaclass for the TranslationService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[TranslationServiceTransport]] + _transport_registry["grpc"] = TranslationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TranslationServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[TranslationServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class TranslationServiceClient(metaclass=TranslationServiceClientMeta): + """Provides natural language translation operations.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "translate.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def glossary_path(project: str, location: str, glossary: str,) -> str: + """Return a fully-qualified glossary string.""" + return "projects/{project}/locations/{location}/glossaries/{glossary}".format( + project=project, location=location, glossary=glossary, + ) + + @staticmethod + def parse_glossary_path(path: str) -> Dict[str, str]: + """Parse a glossary path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/glossaries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, TranslationServiceTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the translation service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TranslationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TranslationServiceTransport): + # transport is a TranslationServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def translate_text( + self, + request: translation_service.TranslateTextRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.TranslateTextResponse: + r"""Translates input text and returns translated text. + + Args: + request (:class:`~.translation_service.TranslateTextRequest`): + The request object. The request message for synchronous + translation. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.TranslateTextResponse: + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.TranslateTextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.TranslateTextRequest): + request = translation_service.TranslateTextRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.translate_text] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def detect_language( + self, + request: translation_service.DetectLanguageRequest = None, + *, + parent: str = None, + model: str = None, + mime_type: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.DetectLanguageResponse: + r"""Detects the language of text within a request. + + Args: + request (:class:`~.translation_service.DetectLanguageRequest`): + The request object. The request message for language + detection. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: + ``projects/{project-id}/locations/{location-id}`` or + ``projects/{project-id}``. + + For global calls, use + ``projects/{project-id}/locations/global`` or + ``projects/{project-id}``. + + Only models within the same region (has same + location-id) can be used. Otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. The language detection model to be used. + + Format: + ``projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}`` + + Only one language detection model is currently + supported: + ``projects/{project-id}/locations/{location-id}/models/language-detection/default``. + + If not specified, the default model is used. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mime_type (:class:`str`): + Optional. The format of the source + text, for example, "text/html", + "text/plain". If left blank, the MIME + type defaults to "text/html". + This corresponds to the ``mime_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.DetectLanguageResponse: + The response message for language + detection. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, model, mime_type]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.DetectLanguageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.DetectLanguageRequest): + request = translation_service.DetectLanguageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if model is not None: + request.model = model + if mime_type is not None: + request.mime_type = mime_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.detect_language] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_supported_languages( + self, + request: translation_service.GetSupportedLanguagesRequest = None, + *, + parent: str = None, + display_language_code: str = None, + model: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.SupportedLanguages: + r"""Returns a list of supported languages for + translation. + + Args: + request (:class:`~.translation_service.GetSupportedLanguagesRequest`): + The request object. The request message for discovering + supported languages. + parent (:class:`str`): + Required. Project or location to make a call. Must refer + to a caller's project. + + Format: ``projects/{project-id}`` or + ``projects/{project-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-id}/locations/global`` or + ``projects/{project-id}``. + + Non-global location is required for AutoML models. + + Only models within the same region (have same + location-id) can be used, otherwise an INVALID_ARGUMENT + (400) error is returned. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_language_code (:class:`str`): + Optional. The language to use to + return localized, human readable names + of supported languages. If missing, then + display names are not returned in a + response. + This corresponds to the ``display_language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + model (:class:`str`): + Optional. Get supported languages of this model. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-id}/locations/{location-id}/models/general/base`` + + Returns languages supported by the specified model. If + missing, we get supported languages of Google general + base (PBMT) model. + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.SupportedLanguages: + The response message for discovering + supported languages. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, display_language_code, model]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.GetSupportedLanguagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.GetSupportedLanguagesRequest): + request = translation_service.GetSupportedLanguagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if display_language_code is not None: + request.display_language_code = display_language_code + if model is not None: + request.model = model + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_supported_languages] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def batch_translate_text( + self, + request: translation_service.BatchTranslateTextRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Translates a large volume of text in asynchronous + batch mode. This function provides real-time output as + the inputs are being processed. If caller cancels a + request, the partial results (for an input file, it's + all or nothing) may still be available on the specified + output location. + This call returns immediately and you can + use google.longrunning.Operation.name to poll the status + of the call. + + Args: + request (:class:`~.translation_service.BatchTranslateTextRequest`): + The request object. The batch translation request. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.BatchTranslateResponse``: + Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by BatchTranslateText if at least one + sentence is translated successfully. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.BatchTranslateTextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.BatchTranslateTextRequest): + request = translation_service.BatchTranslateTextRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_translate_text] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + translation_service.BatchTranslateResponse, + metadata_type=translation_service.BatchTranslateMetadata, + ) + + # Done; return the response. + return response + + def create_glossary( + self, + request: translation_service.CreateGlossaryRequest = None, + *, + parent: str = None, + glossary: translation_service.Glossary = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a glossary and returns the long-running operation. + Returns NOT_FOUND, if the project doesn't exist. + + Args: + request (:class:`~.translation_service.CreateGlossaryRequest`): + The request object. Request message for CreateGlossary. + parent (:class:`str`): + Required. The project name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + glossary (:class:`~.translation_service.Glossary`): + Required. The glossary to create. + This corresponds to the ``glossary`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.Glossary``: Represents a + glossary built from user provided data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, glossary]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.CreateGlossaryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.CreateGlossaryRequest): + request = translation_service.CreateGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if glossary is not None: + request.glossary = glossary + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_glossary] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + translation_service.Glossary, + metadata_type=translation_service.CreateGlossaryMetadata, + ) + + # Done; return the response. + return response + + def list_glossaries( + self, + request: translation_service.ListGlossariesRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGlossariesPager: + r"""Lists glossaries in a project. Returns NOT_FOUND, if the project + doesn't exist. + + Args: + request (:class:`~.translation_service.ListGlossariesRequest`): + The request object. Request message for ListGlossaries. + parent (:class:`str`): + Required. The name of the project + from which to list all of the + glossaries. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filter specifying + constraints of a list operation. + Filtering is not supported yet, and the + parameter currently has no effect. If + missing, no filtering is performed. + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListGlossariesPager: + Response message for ListGlossaries. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.ListGlossariesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.ListGlossariesRequest): + request = translation_service.ListGlossariesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_glossaries] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListGlossariesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_glossary( + self, + request: translation_service.GetGlossaryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> translation_service.Glossary: + r"""Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + exist. + + Args: + request (:class:`~.translation_service.GetGlossaryRequest`): + The request object. Request message for GetGlossary. + name (:class:`str`): + Required. The name of the glossary to + retrieve. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.translation_service.Glossary: + Represents a glossary built from user + provided data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.GetGlossaryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.GetGlossaryRequest): + request = translation_service.GetGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_glossary] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_glossary( + self, + request: translation_service.DeleteGlossaryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a glossary, or cancels glossary construction if the + glossary isn't created yet. Returns NOT_FOUND, if the glossary + doesn't exist. + + Args: + request (:class:`~.translation_service.DeleteGlossaryRequest`): + The request object. Request message for DeleteGlossary. + name (:class:`str`): + Required. The name of the glossary to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.translation_service.DeleteGlossaryResponse``: + Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by DeleteGlossary. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a translation_service.DeleteGlossaryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, translation_service.DeleteGlossaryRequest): + request = translation_service.DeleteGlossaryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_glossary] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + translation_service.DeleteGlossaryResponse, + metadata_type=translation_service.DeleteGlossaryMetadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-translation", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("TranslationServiceClient",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/pagers.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/pagers.py new file mode 100644 index 000000000000..a132a74eabf5 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/pagers.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.translate_v3beta1.types import translation_service + + +class ListGlossariesPager: + """A pager for iterating through ``list_glossaries`` requests. + + This class thinly wraps an initial + :class:`~.translation_service.ListGlossariesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``glossaries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGlossaries`` requests and continue to iterate + through the ``glossaries`` field on the + corresponding responses. + + All the usual :class:`~.translation_service.ListGlossariesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., translation_service.ListGlossariesResponse], + request: translation_service.ListGlossariesRequest, + response: translation_service.ListGlossariesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.translation_service.ListGlossariesRequest`): + The initial request object. + response (:class:`~.translation_service.ListGlossariesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = translation_service.ListGlossariesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[translation_service.ListGlossariesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[translation_service.Glossary]: + for page in self.pages: + yield from page.glossaries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGlossariesAsyncPager: + """A pager for iterating through ``list_glossaries`` requests. + + This class thinly wraps an initial + :class:`~.translation_service.ListGlossariesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``glossaries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGlossaries`` requests and continue to iterate + through the ``glossaries`` field on the + corresponding responses. + + All the usual :class:`~.translation_service.ListGlossariesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[translation_service.ListGlossariesResponse]], + request: translation_service.ListGlossariesRequest, + response: translation_service.ListGlossariesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.translation_service.ListGlossariesRequest`): + The initial request object. + response (:class:`~.translation_service.ListGlossariesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = translation_service.ListGlossariesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[translation_service.ListGlossariesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[translation_service.Glossary]: + async def async_generator(): + async for page in self.pages: + for response in page.glossaries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py new file mode 100644 index 000000000000..b977312dd928 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import TranslationServiceTransport +from .grpc import TranslationServiceGrpcTransport +from .grpc_asyncio import TranslationServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[TranslationServiceTransport]] +_transport_registry["grpc"] = TranslationServiceGrpcTransport +_transport_registry["grpc_asyncio"] = TranslationServiceGrpcAsyncIOTransport + + +__all__ = ( + "TranslationServiceTransport", + "TranslationServiceGrpcTransport", + "TranslationServiceGrpcAsyncIOTransport", +) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/base.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/base.py new file mode 100644 index 000000000000..35c84f1c48ac --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/base.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- + +# 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 abc +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.translate_v3beta1.types import translation_service +from google.longrunning import operations_pb2 as operations # type: ignore + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-translation", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class TranslationServiceTransport(abc.ABC): + """Abstract transport class for TranslationService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ) + + def __init__( + self, + *, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.translate_text: gapic_v1.method.wrap_method( + self.translate_text, default_timeout=None, client_info=_client_info, + ), + self.detect_language: gapic_v1.method.wrap_method( + self.detect_language, default_timeout=None, client_info=_client_info, + ), + self.get_supported_languages: gapic_v1.method.wrap_method( + self.get_supported_languages, + default_timeout=None, + client_info=_client_info, + ), + self.batch_translate_text: gapic_v1.method.wrap_method( + self.batch_translate_text, + default_timeout=None, + client_info=_client_info, + ), + self.create_glossary: gapic_v1.method.wrap_method( + self.create_glossary, default_timeout=None, client_info=_client_info, + ), + self.list_glossaries: gapic_v1.method.wrap_method( + self.list_glossaries, default_timeout=None, client_info=_client_info, + ), + self.get_glossary: gapic_v1.method.wrap_method( + self.get_glossary, default_timeout=None, client_info=_client_info, + ), + self.delete_glossary: gapic_v1.method.wrap_method( + self.delete_glossary, default_timeout=None, client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def translate_text( + self, + ) -> typing.Callable[ + [translation_service.TranslateTextRequest], + typing.Union[ + translation_service.TranslateTextResponse, + typing.Awaitable[translation_service.TranslateTextResponse], + ], + ]: + raise NotImplementedError() + + @property + def detect_language( + self, + ) -> typing.Callable[ + [translation_service.DetectLanguageRequest], + typing.Union[ + translation_service.DetectLanguageResponse, + typing.Awaitable[translation_service.DetectLanguageResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_supported_languages( + self, + ) -> typing.Callable[ + [translation_service.GetSupportedLanguagesRequest], + typing.Union[ + translation_service.SupportedLanguages, + typing.Awaitable[translation_service.SupportedLanguages], + ], + ]: + raise NotImplementedError() + + @property + def batch_translate_text( + self, + ) -> typing.Callable[ + [translation_service.BatchTranslateTextRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def create_glossary( + self, + ) -> typing.Callable[ + [translation_service.CreateGlossaryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def list_glossaries( + self, + ) -> typing.Callable[ + [translation_service.ListGlossariesRequest], + typing.Union[ + translation_service.ListGlossariesResponse, + typing.Awaitable[translation_service.ListGlossariesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_glossary( + self, + ) -> typing.Callable[ + [translation_service.GetGlossaryRequest], + typing.Union[ + translation_service.Glossary, typing.Awaitable[translation_service.Glossary] + ], + ]: + raise NotImplementedError() + + @property + def delete_glossary( + self, + ) -> typing.Callable[ + [translation_service.DeleteGlossaryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("TranslationServiceTransport",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/grpc.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/grpc.py new file mode 100644 index 000000000000..f6dadf281625 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/grpc.py @@ -0,0 +1,463 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.translate_v3beta1.types import translation_service +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import TranslationServiceTransport + + +class TranslationServiceGrpcTransport(TranslationServiceTransport): + """gRPC backend transport for TranslationService. + + Provides natural language translation operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def translate_text( + self, + ) -> Callable[ + [translation_service.TranslateTextRequest], + translation_service.TranslateTextResponse, + ]: + r"""Return a callable for the translate text method over gRPC. + + Translates input text and returns translated text. + + Returns: + Callable[[~.TranslateTextRequest], + ~.TranslateTextResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "translate_text" not in self._stubs: + self._stubs["translate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/TranslateText", + request_serializer=translation_service.TranslateTextRequest.serialize, + response_deserializer=translation_service.TranslateTextResponse.deserialize, + ) + return self._stubs["translate_text"] + + @property + def detect_language( + self, + ) -> Callable[ + [translation_service.DetectLanguageRequest], + translation_service.DetectLanguageResponse, + ]: + r"""Return a callable for the detect language method over gRPC. + + Detects the language of text within a request. + + Returns: + Callable[[~.DetectLanguageRequest], + ~.DetectLanguageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "detect_language" not in self._stubs: + self._stubs["detect_language"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/DetectLanguage", + request_serializer=translation_service.DetectLanguageRequest.serialize, + response_deserializer=translation_service.DetectLanguageResponse.deserialize, + ) + return self._stubs["detect_language"] + + @property + def get_supported_languages( + self, + ) -> Callable[ + [translation_service.GetSupportedLanguagesRequest], + translation_service.SupportedLanguages, + ]: + r"""Return a callable for the get supported languages method over gRPC. + + Returns a list of supported languages for + translation. + + Returns: + Callable[[~.GetSupportedLanguagesRequest], + ~.SupportedLanguages]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_supported_languages" not in self._stubs: + self._stubs["get_supported_languages"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/GetSupportedLanguages", + request_serializer=translation_service.GetSupportedLanguagesRequest.serialize, + response_deserializer=translation_service.SupportedLanguages.deserialize, + ) + return self._stubs["get_supported_languages"] + + @property + def batch_translate_text( + self, + ) -> Callable[ + [translation_service.BatchTranslateTextRequest], operations.Operation + ]: + r"""Return a callable for the batch translate text method over gRPC. + + Translates a large volume of text in asynchronous + batch mode. This function provides real-time output as + the inputs are being processed. If caller cancels a + request, the partial results (for an input file, it's + all or nothing) may still be available on the specified + output location. + This call returns immediately and you can + use google.longrunning.Operation.name to poll the status + of the call. + + Returns: + Callable[[~.BatchTranslateTextRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_translate_text" not in self._stubs: + self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/BatchTranslateText", + request_serializer=translation_service.BatchTranslateTextRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["batch_translate_text"] + + @property + def create_glossary( + self, + ) -> Callable[[translation_service.CreateGlossaryRequest], operations.Operation]: + r"""Return a callable for the create glossary method over gRPC. + + Creates a glossary and returns the long-running operation. + Returns NOT_FOUND, if the project doesn't exist. + + Returns: + Callable[[~.CreateGlossaryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_glossary" not in self._stubs: + self._stubs["create_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/CreateGlossary", + request_serializer=translation_service.CreateGlossaryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["create_glossary"] + + @property + def list_glossaries( + self, + ) -> Callable[ + [translation_service.ListGlossariesRequest], + translation_service.ListGlossariesResponse, + ]: + r"""Return a callable for the list glossaries method over gRPC. + + Lists glossaries in a project. Returns NOT_FOUND, if the project + doesn't exist. + + Returns: + Callable[[~.ListGlossariesRequest], + ~.ListGlossariesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_glossaries" not in self._stubs: + self._stubs["list_glossaries"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/ListGlossaries", + request_serializer=translation_service.ListGlossariesRequest.serialize, + response_deserializer=translation_service.ListGlossariesResponse.deserialize, + ) + return self._stubs["list_glossaries"] + + @property + def get_glossary( + self, + ) -> Callable[ + [translation_service.GetGlossaryRequest], translation_service.Glossary + ]: + r"""Return a callable for the get glossary method over gRPC. + + Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + exist. + + Returns: + Callable[[~.GetGlossaryRequest], + ~.Glossary]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_glossary" not in self._stubs: + self._stubs["get_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/GetGlossary", + request_serializer=translation_service.GetGlossaryRequest.serialize, + response_deserializer=translation_service.Glossary.deserialize, + ) + return self._stubs["get_glossary"] + + @property + def delete_glossary( + self, + ) -> Callable[[translation_service.DeleteGlossaryRequest], operations.Operation]: + r"""Return a callable for the delete glossary method over gRPC. + + Deletes a glossary, or cancels glossary construction if the + glossary isn't created yet. Returns NOT_FOUND, if the glossary + doesn't exist. + + Returns: + Callable[[~.DeleteGlossaryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_glossary" not in self._stubs: + self._stubs["delete_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/DeleteGlossary", + request_serializer=translation_service.DeleteGlossaryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["delete_glossary"] + + +__all__ = ("TranslationServiceGrpcTransport",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/grpc_asyncio.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e7f63e99879d --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/services/translation_service/transports/grpc_asyncio.py @@ -0,0 +1,461 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.translate_v3beta1.types import translation_service +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import TranslationServiceTransport +from .grpc import TranslationServiceGrpcTransport + + +class TranslationServiceGrpcAsyncIOTransport(TranslationServiceTransport): + """gRPC AsyncIO backend transport for TranslationService. + + Provides natural language translation operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "translate.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def translate_text( + self, + ) -> Callable[ + [translation_service.TranslateTextRequest], + Awaitable[translation_service.TranslateTextResponse], + ]: + r"""Return a callable for the translate text method over gRPC. + + Translates input text and returns translated text. + + Returns: + Callable[[~.TranslateTextRequest], + Awaitable[~.TranslateTextResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "translate_text" not in self._stubs: + self._stubs["translate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/TranslateText", + request_serializer=translation_service.TranslateTextRequest.serialize, + response_deserializer=translation_service.TranslateTextResponse.deserialize, + ) + return self._stubs["translate_text"] + + @property + def detect_language( + self, + ) -> Callable[ + [translation_service.DetectLanguageRequest], + Awaitable[translation_service.DetectLanguageResponse], + ]: + r"""Return a callable for the detect language method over gRPC. + + Detects the language of text within a request. + + Returns: + Callable[[~.DetectLanguageRequest], + Awaitable[~.DetectLanguageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "detect_language" not in self._stubs: + self._stubs["detect_language"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/DetectLanguage", + request_serializer=translation_service.DetectLanguageRequest.serialize, + response_deserializer=translation_service.DetectLanguageResponse.deserialize, + ) + return self._stubs["detect_language"] + + @property + def get_supported_languages( + self, + ) -> Callable[ + [translation_service.GetSupportedLanguagesRequest], + Awaitable[translation_service.SupportedLanguages], + ]: + r"""Return a callable for the get supported languages method over gRPC. + + Returns a list of supported languages for + translation. + + Returns: + Callable[[~.GetSupportedLanguagesRequest], + Awaitable[~.SupportedLanguages]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_supported_languages" not in self._stubs: + self._stubs["get_supported_languages"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/GetSupportedLanguages", + request_serializer=translation_service.GetSupportedLanguagesRequest.serialize, + response_deserializer=translation_service.SupportedLanguages.deserialize, + ) + return self._stubs["get_supported_languages"] + + @property + def batch_translate_text( + self, + ) -> Callable[ + [translation_service.BatchTranslateTextRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the batch translate text method over gRPC. + + Translates a large volume of text in asynchronous + batch mode. This function provides real-time output as + the inputs are being processed. If caller cancels a + request, the partial results (for an input file, it's + all or nothing) may still be available on the specified + output location. + This call returns immediately and you can + use google.longrunning.Operation.name to poll the status + of the call. + + Returns: + Callable[[~.BatchTranslateTextRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_translate_text" not in self._stubs: + self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/BatchTranslateText", + request_serializer=translation_service.BatchTranslateTextRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["batch_translate_text"] + + @property + def create_glossary( + self, + ) -> Callable[ + [translation_service.CreateGlossaryRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the create glossary method over gRPC. + + Creates a glossary and returns the long-running operation. + Returns NOT_FOUND, if the project doesn't exist. + + Returns: + Callable[[~.CreateGlossaryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_glossary" not in self._stubs: + self._stubs["create_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/CreateGlossary", + request_serializer=translation_service.CreateGlossaryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["create_glossary"] + + @property + def list_glossaries( + self, + ) -> Callable[ + [translation_service.ListGlossariesRequest], + Awaitable[translation_service.ListGlossariesResponse], + ]: + r"""Return a callable for the list glossaries method over gRPC. + + Lists glossaries in a project. Returns NOT_FOUND, if the project + doesn't exist. + + Returns: + Callable[[~.ListGlossariesRequest], + Awaitable[~.ListGlossariesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_glossaries" not in self._stubs: + self._stubs["list_glossaries"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/ListGlossaries", + request_serializer=translation_service.ListGlossariesRequest.serialize, + response_deserializer=translation_service.ListGlossariesResponse.deserialize, + ) + return self._stubs["list_glossaries"] + + @property + def get_glossary( + self, + ) -> Callable[ + [translation_service.GetGlossaryRequest], + Awaitable[translation_service.Glossary], + ]: + r"""Return a callable for the get glossary method over gRPC. + + Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + exist. + + Returns: + Callable[[~.GetGlossaryRequest], + Awaitable[~.Glossary]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_glossary" not in self._stubs: + self._stubs["get_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/GetGlossary", + request_serializer=translation_service.GetGlossaryRequest.serialize, + response_deserializer=translation_service.Glossary.deserialize, + ) + return self._stubs["get_glossary"] + + @property + def delete_glossary( + self, + ) -> Callable[ + [translation_service.DeleteGlossaryRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the delete glossary method over gRPC. + + Deletes a glossary, or cancels glossary construction if the + glossary isn't created yet. Returns NOT_FOUND, if the glossary + doesn't exist. + + Returns: + Callable[[~.DeleteGlossaryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_glossary" not in self._stubs: + self._stubs["delete_glossary"] = self.grpc_channel.unary_unary( + "/google.cloud.translation.v3beta1.TranslationService/DeleteGlossary", + request_serializer=translation_service.DeleteGlossaryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["delete_glossary"] + + +__all__ = ("TranslationServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/types.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/types.py deleted file mode 100644 index 0512ce19f96d..000000000000 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/types.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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 absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.translate_v3beta1.proto import translation_service_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 - - -_shared_modules = [ - operations_pb2, - any_pb2, - timestamp_pb2, - status_pb2, -] - -_local_modules = [ - translation_service_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.translate_v3beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/types/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/types/__init__.py new file mode 100644 index 000000000000..60c0f41d7ae4 --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/types/__init__.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- + +# 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. +# + +from .translation_service import ( + TranslateTextGlossaryConfig, + TranslateTextRequest, + TranslateTextResponse, + Translation, + DetectLanguageRequest, + DetectedLanguage, + DetectLanguageResponse, + GetSupportedLanguagesRequest, + SupportedLanguages, + SupportedLanguage, + GcsSource, + InputConfig, + GcsDestination, + OutputConfig, + BatchTranslateTextRequest, + BatchTranslateMetadata, + BatchTranslateResponse, + GlossaryInputConfig, + Glossary, + CreateGlossaryRequest, + GetGlossaryRequest, + DeleteGlossaryRequest, + ListGlossariesRequest, + ListGlossariesResponse, + CreateGlossaryMetadata, + DeleteGlossaryMetadata, + DeleteGlossaryResponse, +) + + +__all__ = ( + "TranslateTextGlossaryConfig", + "TranslateTextRequest", + "TranslateTextResponse", + "Translation", + "DetectLanguageRequest", + "DetectedLanguage", + "DetectLanguageResponse", + "GetSupportedLanguagesRequest", + "SupportedLanguages", + "SupportedLanguage", + "GcsSource", + "InputConfig", + "GcsDestination", + "OutputConfig", + "BatchTranslateTextRequest", + "BatchTranslateMetadata", + "BatchTranslateResponse", + "GlossaryInputConfig", + "Glossary", + "CreateGlossaryRequest", + "GetGlossaryRequest", + "DeleteGlossaryRequest", + "ListGlossariesRequest", + "ListGlossariesResponse", + "CreateGlossaryMetadata", + "DeleteGlossaryMetadata", + "DeleteGlossaryResponse", +) diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/types/translation_service.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/types/translation_service.py new file mode 100644 index 000000000000..5ee91b8fb97a --- /dev/null +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/types/translation_service.py @@ -0,0 +1,1020 @@ +# -*- coding: utf-8 -*- + +# 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 proto # type: ignore + + +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.translation.v3beta1", + manifest={ + "TranslateTextGlossaryConfig", + "TranslateTextRequest", + "TranslateTextResponse", + "Translation", + "DetectLanguageRequest", + "DetectedLanguage", + "DetectLanguageResponse", + "GetSupportedLanguagesRequest", + "SupportedLanguages", + "SupportedLanguage", + "GcsSource", + "InputConfig", + "GcsDestination", + "OutputConfig", + "BatchTranslateTextRequest", + "BatchTranslateMetadata", + "BatchTranslateResponse", + "GlossaryInputConfig", + "Glossary", + "CreateGlossaryRequest", + "GetGlossaryRequest", + "DeleteGlossaryRequest", + "ListGlossariesRequest", + "ListGlossariesResponse", + "CreateGlossaryMetadata", + "DeleteGlossaryMetadata", + "DeleteGlossaryResponse", + }, +) + + +class TranslateTextGlossaryConfig(proto.Message): + r"""Configures which glossary should be used for a specific + target language, and defines options for applying that glossary. + + Attributes: + glossary (str): + Required. Specifies the glossary used for this translation. + Use this format: projects/\ */locations/*/glossaries/\* + ignore_case (bool): + Optional. Indicates match is case- + nsensitive. Default value is false if missing. + """ + + glossary = proto.Field(proto.STRING, number=1) + + ignore_case = proto.Field(proto.BOOL, number=2) + + +class TranslateTextRequest(proto.Message): + r"""The request message for synchronous translation. + + Attributes: + contents (Sequence[str]): + Required. The content of the input in string + format. We recommend the total content be less + than 30k codepoints. Use BatchTranslateText for + larger text. + mime_type (str): + Optional. The format of the source text, for + example, "text/html", "text/plain". If left + blank, the MIME type defaults to "text/html". + source_language_code (str): + Optional. The BCP-47 language code of the + input text if known, for example, "en-US" or + "sr-Latn". Supported language codes are listed + in Language Support. If the source language + isn't specified, the API attempts to identify + the source language automatically and returns + the source language within the response. + target_language_code (str): + Required. The BCP-47 language code to use for + translation of the input text, set to one of the + language codes listed in Language Support. + parent (str): + Required. Project or location to make a call. Must refer to + a caller's project. + + Format: ``projects/{project-id}`` or + ``projects/{project-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-id}/locations/global`` or + ``projects/{project-id}``. + + Non-global location is required for requests using AutoML + models or custom glossaries. + + Models and glossaries must be within the same region (have + same location-id), otherwise an INVALID_ARGUMENT (400) error + is returned. + model (str): + Optional. The ``model`` type requested for this translation. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-id}/locations/{location-id}/models/general/base`` + + For global (non-regionalized) requests, use ``location-id`` + ``global``. For example, + ``projects/{project-id}/locations/global/models/general/nmt``. + + If missing, the system decides which google base model to + use. + glossary_config (~.translation_service.TranslateTextGlossaryConfig): + Optional. Glossary to be applied. The glossary must be + within the same region (have the same location-id) as the + model, otherwise an INVALID_ARGUMENT (400) error is + returned. + labels (Sequence[~.translation_service.TranslateTextRequest.LabelsEntry]): + Optional. The labels with user-defined + metadata for the request. + Label keys and values can be no longer than 63 + characters (Unicode codepoints), can only + contain lowercase letters, numeric characters, + underscores and dashes. International characters + are allowed. Label values are optional. Label + keys must start with a letter. + See + https://cloud.google.com/translate/docs/labels + for more information. + """ + + contents = proto.RepeatedField(proto.STRING, number=1) + + mime_type = proto.Field(proto.STRING, number=3) + + source_language_code = proto.Field(proto.STRING, number=4) + + target_language_code = proto.Field(proto.STRING, number=5) + + parent = proto.Field(proto.STRING, number=8) + + model = proto.Field(proto.STRING, number=6) + + glossary_config = proto.Field( + proto.MESSAGE, number=7, message=TranslateTextGlossaryConfig, + ) + + labels = proto.MapField(proto.STRING, proto.STRING, number=10) + + +class TranslateTextResponse(proto.Message): + r""" + + Attributes: + translations (Sequence[~.translation_service.Translation]): + Text translation responses with no glossary applied. This + field has the same length as + [``contents``][google.cloud.translation.v3beta1.TranslateTextRequest.contents]. + glossary_translations (Sequence[~.translation_service.Translation]): + Text translation responses if a glossary is provided in the + request. This can be the same as + [``translations``][google.cloud.translation.v3beta1.TranslateTextResponse.translations] + if no terms apply. This field has the same length as + [``contents``][google.cloud.translation.v3beta1.TranslateTextRequest.contents]. + """ + + translations = proto.RepeatedField(proto.MESSAGE, number=1, message="Translation",) + + glossary_translations = proto.RepeatedField( + proto.MESSAGE, number=3, message="Translation", + ) + + +class Translation(proto.Message): + r"""A single translation response. + + Attributes: + translated_text (str): + Text translated into the target language. + model (str): + Only present when ``model`` is present in the request. This + is same as ``model`` provided in the request. + detected_language_code (str): + The BCP-47 language code of source text in + the initial request, detected automatically, if + no source language was passed within the initial + request. If the source language was passed, + auto-detection of the language does not occur + and this field is empty. + glossary_config (~.translation_service.TranslateTextGlossaryConfig): + The ``glossary_config`` used for this translation. + """ + + translated_text = proto.Field(proto.STRING, number=1) + + model = proto.Field(proto.STRING, number=2) + + detected_language_code = proto.Field(proto.STRING, number=4) + + glossary_config = proto.Field( + proto.MESSAGE, number=3, message=TranslateTextGlossaryConfig, + ) + + +class DetectLanguageRequest(proto.Message): + r"""The request message for language detection. + + Attributes: + parent (str): + Required. Project or location to make a call. Must refer to + a caller's project. + + Format: ``projects/{project-id}/locations/{location-id}`` or + ``projects/{project-id}``. + + For global calls, use + ``projects/{project-id}/locations/global`` or + ``projects/{project-id}``. + + Only models within the same region (has same location-id) + can be used. Otherwise an INVALID_ARGUMENT (400) error is + returned. + model (str): + Optional. The language detection model to be used. + + Format: + ``projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}`` + + Only one language detection model is currently supported: + ``projects/{project-id}/locations/{location-id}/models/language-detection/default``. + + If not specified, the default model is used. + content (str): + The content of the input stored as a string. + mime_type (str): + Optional. The format of the source text, for + example, "text/html", "text/plain". If left + blank, the MIME type defaults to "text/html". + labels (Sequence[~.translation_service.DetectLanguageRequest.LabelsEntry]): + Optional. The labels with user-defined + metadata for the request. + Label keys and values can be no longer than 63 + characters (Unicode codepoints), can only + contain lowercase letters, numeric characters, + underscores and dashes. International characters + are allowed. Label values are optional. Label + keys must start with a letter. + See + https://cloud.google.com/translate/docs/labels + for more information. + """ + + parent = proto.Field(proto.STRING, number=5) + + model = proto.Field(proto.STRING, number=4) + + content = proto.Field(proto.STRING, number=1, oneof="source") + + mime_type = proto.Field(proto.STRING, number=3) + + labels = proto.MapField(proto.STRING, proto.STRING, number=6) + + +class DetectedLanguage(proto.Message): + r"""The response message for language detection. + + Attributes: + language_code (str): + The BCP-47 language code of source content in + the request, detected automatically. + confidence (float): + The confidence of the detection result for + this language. + """ + + language_code = proto.Field(proto.STRING, number=1) + + confidence = proto.Field(proto.FLOAT, number=2) + + +class DetectLanguageResponse(proto.Message): + r"""The response message for language detection. + + Attributes: + languages (Sequence[~.translation_service.DetectedLanguage]): + A list of detected languages sorted by + detection confidence in descending order. The + most probable language first. + """ + + languages = proto.RepeatedField(proto.MESSAGE, number=1, message=DetectedLanguage,) + + +class GetSupportedLanguagesRequest(proto.Message): + r"""The request message for discovering supported languages. + + Attributes: + parent (str): + Required. Project or location to make a call. Must refer to + a caller's project. + + Format: ``projects/{project-id}`` or + ``projects/{project-id}/locations/{location-id}``. + + For global calls, use + ``projects/{project-id}/locations/global`` or + ``projects/{project-id}``. + + Non-global location is required for AutoML models. + + Only models within the same region (have same location-id) + can be used, otherwise an INVALID_ARGUMENT (400) error is + returned. + display_language_code (str): + Optional. The language to use to return + localized, human readable names of supported + languages. If missing, then display names are + not returned in a response. + model (str): + Optional. Get supported languages of this model. + + The format depends on model type: + + - AutoML Translation models: + ``projects/{project-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-id}/locations/{location-id}/models/general/base`` + + Returns languages supported by the specified model. If + missing, we get supported languages of Google general base + (PBMT) model. + """ + + parent = proto.Field(proto.STRING, number=3) + + display_language_code = proto.Field(proto.STRING, number=1) + + model = proto.Field(proto.STRING, number=2) + + +class SupportedLanguages(proto.Message): + r"""The response message for discovering supported languages. + + Attributes: + languages (Sequence[~.translation_service.SupportedLanguage]): + A list of supported language responses. This + list contains an entry for each language the + Translation API supports. + """ + + languages = proto.RepeatedField( + proto.MESSAGE, number=1, message="SupportedLanguage", + ) + + +class SupportedLanguage(proto.Message): + r"""A single supported language response corresponds to + information related to one supported language. + + Attributes: + language_code (str): + Supported language code, generally consisting + of its ISO 639-1 identifier, for example, 'en', + 'ja'. In certain cases, BCP-47 codes including + language and region identifiers are returned + (for example, 'zh-TW' and 'zh-CN') + display_name (str): + Human readable name of the language localized + in the display language specified in the + request. + support_source (bool): + Can be used as source language. + support_target (bool): + Can be used as target language. + """ + + language_code = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + support_source = proto.Field(proto.BOOL, number=3) + + support_target = proto.Field(proto.BOOL, number=4) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location for the input content. + + Attributes: + input_uri (str): + Required. Source data URI. For example, + ``gs://my_bucket/my_object``. + """ + + input_uri = proto.Field(proto.STRING, number=1) + + +class InputConfig(proto.Message): + r"""Input configuration for BatchTranslateText request. + + Attributes: + mime_type (str): + Optional. Can be "text/plain" or "text/html". For ``.tsv``, + "text/html" is used if mime_type is missing. For ``.html``, + this field must be "text/html" or empty. For ``.txt``, this + field must be "text/plain" or empty. + gcs_source (~.translation_service.GcsSource): + Required. Google Cloud Storage location for the source + input. This can be a single file (for example, + ``gs://translation-test/input.tsv``) or a wildcard (for + example, ``gs://translation-test/*``). If a file extension + is ``.tsv``, it can contain either one or two columns. The + first column (optional) is the id of the text request. If + the first column is missing, we use the row number (0-based) + from the input file as the ID in the output file. The second + column is the actual text to be translated. We recommend + each row be <= 10K Unicode codepoints, otherwise an error + might be returned. Note that the input tsv must be RFC 4180 + compliant. + + You could use https://github.com/Clever/csvlint to check + potential formatting errors in your tsv file. csvlint + --delimiter='\t' your_input_file.tsv + + The other supported file extensions are ``.txt`` or + ``.html``, which is treated as a single large chunk of text. + """ + + mime_type = proto.Field(proto.STRING, number=1) + + gcs_source = proto.Field( + proto.MESSAGE, number=2, oneof="source", message=GcsSource, + ) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location for the output content. + + Attributes: + output_uri_prefix (str): + Required. There must be no files under 'output_uri_prefix'. + 'output_uri_prefix' must end with "/" and start with + "gs://", otherwise an INVALID_ARGUMENT (400) error is + returned. + """ + + output_uri_prefix = proto.Field(proto.STRING, number=1) + + +class OutputConfig(proto.Message): + r"""Output configuration for BatchTranslateText request. + + Attributes: + gcs_destination (~.translation_service.GcsDestination): + Google Cloud Storage destination for output content. For + every single input file (for example, + gs://a/b/c.[extension]), we generate at most 2 \* n output + files. (n is the # of target_language_codes in the + BatchTranslateTextRequest). + + Output files (tsv) generated are compliant with RFC 4180 + except that record delimiters are '\n' instead of '\r\n'. We + don't provide any way to change record delimiters. + + While the input files are being processed, we write/update + an index file 'index.csv' under 'output_uri_prefix' (for + example, gs://translation-test/index.csv) The index file is + generated/updated as new files are being translated. The + format is: + + input_file,target_language_code,translations_file,errors_file, + glossary_translations_file,glossary_errors_file + + input_file is one file we matched using + gcs_source.input_uri. target_language_code is provided in + the request. translations_file contains the translations. + (details provided below) errors_file contains the errors + during processing of the file. (details below). Both + translations_file and errors_file could be empty strings if + we have no content to output. glossary_translations_file and + glossary_errors_file are always empty strings if the + input_file is tsv. They could also be empty if we have no + content to output. + + Once a row is present in index.csv, the input/output + matching never changes. Callers should also expect all the + content in input_file are processed and ready to be consumed + (that is, no partial output file is written). + + The format of translations_file (for target language code + 'trg') is: + ``gs://translation_test/a_b_c\_'trg'_translations.[extension]`` + + If the input file extension is tsv, the output has the + following columns: Column 1: ID of the request provided in + the input, if it's not provided in the input, then the input + row number is used (0-based). Column 2: source sentence. + Column 3: translation without applying a glossary. Empty + string if there is an error. Column 4 (only present if a + glossary is provided in the request): translation after + applying the glossary. Empty string if there is an error + applying the glossary. Could be same string as column 3 if + there is no glossary applied. + + If input file extension is a txt or html, the translation is + directly written to the output file. If glossary is + requested, a separate glossary_translations_file has format + of + ``gs://translation_test/a_b_c\_'trg'_glossary_translations.[extension]`` + + The format of errors file (for target language code 'trg') + is: ``gs://translation_test/a_b_c\_'trg'_errors.[extension]`` + + If the input file extension is tsv, errors_file contains the + following: Column 1: ID of the request provided in the + input, if it's not provided in the input, then the input row + number is used (0-based). Column 2: source sentence. Column + 3: Error detail for the translation. Could be empty. Column + 4 (only present if a glossary is provided in the request): + Error when applying the glossary. + + If the input file extension is txt or html, + glossary_error_file will be generated that contains error + details. glossary_error_file has format of + ``gs://translation_test/a_b_c\_'trg'_glossary_errors.[extension]`` + """ + + gcs_destination = proto.Field( + proto.MESSAGE, number=1, oneof="destination", message=GcsDestination, + ) + + +class BatchTranslateTextRequest(proto.Message): + r"""The batch translation request. + + Attributes: + parent (str): + Required. Location to make a call. Must refer to a caller's + project. + + Format: ``projects/{project-id}/locations/{location-id}``. + + The ``global`` location is not supported for batch + translation. + + Only AutoML Translation models or glossaries within the same + region (have the same location-id) can be used, otherwise an + INVALID_ARGUMENT (400) error is returned. + source_language_code (str): + Required. Source language code. + target_language_codes (Sequence[str]): + Required. Specify up to 10 language codes + here. + models (Sequence[~.translation_service.BatchTranslateTextRequest.ModelsEntry]): + Optional. The models to use for translation. Map's key is + target language code. Map's value is model name. Value can + be a built-in general model, or an AutoML Translation model. + + The value format depends on model type: + + - AutoML Translation models: + ``projects/{project-id}/locations/{location-id}/models/{model-id}`` + + - General (built-in) models: + ``projects/{project-id}/locations/{location-id}/models/general/nmt``, + ``projects/{project-id}/locations/{location-id}/models/general/base`` + + If the map is empty or a specific model is not requested for + a language pair, then default google model (nmt) is used. + input_configs (Sequence[~.translation_service.InputConfig]): + Required. Input configurations. + The total number of files matched should be <= + 1000. The total content size should be <= 100M + Unicode codepoints. The files must use UTF-8 + encoding. + output_config (~.translation_service.OutputConfig): + Required. Output configuration. + If 2 input configs match to the same file (that + is, same input path), we don't generate output + for duplicate inputs. + glossaries (Sequence[~.translation_service.BatchTranslateTextRequest.GlossariesEntry]): + Optional. Glossaries to be applied for + translation. It's keyed by target language code. + labels (Sequence[~.translation_service.BatchTranslateTextRequest.LabelsEntry]): + Optional. The labels with user-defined + metadata for the request. + Label keys and values can be no longer than 63 + characters (Unicode codepoints), can only + contain lowercase letters, numeric characters, + underscores and dashes. International characters + are allowed. Label values are optional. Label + keys must start with a letter. + See + https://cloud.google.com/translate/docs/labels + for more information. + """ + + parent = proto.Field(proto.STRING, number=1) + + source_language_code = proto.Field(proto.STRING, number=2) + + target_language_codes = proto.RepeatedField(proto.STRING, number=3) + + models = proto.MapField(proto.STRING, proto.STRING, number=4) + + input_configs = proto.RepeatedField(proto.MESSAGE, number=5, message=InputConfig,) + + output_config = proto.Field(proto.MESSAGE, number=6, message=OutputConfig,) + + glossaries = proto.MapField( + proto.STRING, proto.MESSAGE, number=7, message=TranslateTextGlossaryConfig, + ) + + labels = proto.MapField(proto.STRING, proto.STRING, number=9) + + +class BatchTranslateMetadata(proto.Message): + r"""State metadata for the batch translation operation. + + Attributes: + state (~.translation_service.BatchTranslateMetadata.State): + The state of the operation. + translated_characters (int): + Number of successfully translated characters + so far (Unicode codepoints). + failed_characters (int): + Number of characters that have failed to + process so far (Unicode codepoints). + total_characters (int): + Total number of characters (Unicode + codepoints). This is the total number of + codepoints from input files times the number of + target languages and appears here shortly after + the call is submitted. + submit_time (~.timestamp.Timestamp): + Time when the operation was submitted. + """ + + class State(proto.Enum): + r"""State of the job.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLING = 4 + CANCELLED = 5 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + translated_characters = proto.Field(proto.INT64, number=2) + + failed_characters = proto.Field(proto.INT64, number=3) + + total_characters = proto.Field(proto.INT64, number=4) + + submit_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + +class BatchTranslateResponse(proto.Message): + r"""Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by BatchTranslateText if at least one sentence is + translated successfully. + + Attributes: + total_characters (int): + Total number of characters (Unicode + codepoints). + translated_characters (int): + Number of successfully translated characters + (Unicode codepoints). + failed_characters (int): + Number of characters that have failed to + process (Unicode codepoints). + submit_time (~.timestamp.Timestamp): + Time when the operation was submitted. + end_time (~.timestamp.Timestamp): + The time when the operation is finished and + [google.longrunning.Operation.done][google.longrunning.Operation.done] + is set to true. + """ + + total_characters = proto.Field(proto.INT64, number=1) + + translated_characters = proto.Field(proto.INT64, number=2) + + failed_characters = proto.Field(proto.INT64, number=3) + + submit_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + +class GlossaryInputConfig(proto.Message): + r"""Input configuration for glossaries. + + Attributes: + gcs_source (~.translation_service.GcsSource): + Required. Google Cloud Storage location of glossary data. + File format is determined based on the filename extension. + API returns [google.rpc.Code.INVALID_ARGUMENT] for + unsupported URI-s and file formats. Wildcards are not + allowed. This must be a single file in one of the following + formats: + + For unidirectional glossaries: + + - TSV/CSV (``.tsv``/``.csv``): 2 column file, tab- or + comma-separated. The first column is source text. The + second column is target text. The file must not contain + headers. That is, the first row is data, not column + names. + + - TMX (``.tmx``): TMX file with parallel data defining + source/target term pairs. + + For equivalent term sets glossaries: + + - CSV (``.csv``): Multi-column CSV file defining equivalent + glossary terms in multiple languages. The format is + defined for Google Translation Toolkit and documented in + `Use a + glossary `__. + """ + + gcs_source = proto.Field( + proto.MESSAGE, number=1, oneof="source", message=GcsSource, + ) + + +class Glossary(proto.Message): + r"""Represents a glossary built from user provided data. + + Attributes: + name (str): + Required. The resource name of the glossary. Glossary names + have the form + ``projects/{project-id}/locations/{location-id}/glossaries/{glossary-id}``. + language_pair (~.translation_service.Glossary.LanguageCodePair): + Used with unidirectional glossaries. + language_codes_set (~.translation_service.Glossary.LanguageCodesSet): + Used with equivalent term set glossaries. + input_config (~.translation_service.GlossaryInputConfig): + Required. Provides examples to build the + glossary from. Total glossary must not exceed + 10M Unicode codepoints. + entry_count (int): + Output only. The number of entries defined in + the glossary. + submit_time (~.timestamp.Timestamp): + Output only. When CreateGlossary was called. + end_time (~.timestamp.Timestamp): + Output only. When the glossary creation was + finished. + """ + + class LanguageCodePair(proto.Message): + r"""Used with unidirectional glossaries. + + Attributes: + source_language_code (str): + Required. The BCP-47 language code of the input text, for + example, "en-US". Expected to be an exact match for + GlossaryTerm.language_code. + target_language_code (str): + Required. The BCP-47 language code for translation output, + for example, "zh-CN". Expected to be an exact match for + GlossaryTerm.language_code. + """ + + source_language_code = proto.Field(proto.STRING, number=1) + + target_language_code = proto.Field(proto.STRING, number=2) + + class LanguageCodesSet(proto.Message): + r"""Used with equivalent term set glossaries. + + Attributes: + language_codes (Sequence[str]): + The BCP-47 language code(s) for terms defined in the + glossary. All entries are unique. The list contains at least + two entries. Expected to be an exact match for + GlossaryTerm.language_code. + """ + + language_codes = proto.RepeatedField(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + language_pair = proto.Field( + proto.MESSAGE, number=3, oneof="languages", message=LanguageCodePair, + ) + + language_codes_set = proto.Field( + proto.MESSAGE, number=4, oneof="languages", message=LanguageCodesSet, + ) + + input_config = proto.Field(proto.MESSAGE, number=5, message=GlossaryInputConfig,) + + entry_count = proto.Field(proto.INT32, number=6) + + submit_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) + + +class CreateGlossaryRequest(proto.Message): + r"""Request message for CreateGlossary. + + Attributes: + parent (str): + Required. The project name. + glossary (~.translation_service.Glossary): + Required. The glossary to create. + """ + + parent = proto.Field(proto.STRING, number=1) + + glossary = proto.Field(proto.MESSAGE, number=2, message=Glossary,) + + +class GetGlossaryRequest(proto.Message): + r"""Request message for GetGlossary. + + Attributes: + name (str): + Required. The name of the glossary to + retrieve. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DeleteGlossaryRequest(proto.Message): + r"""Request message for DeleteGlossary. + + Attributes: + name (str): + Required. The name of the glossary to delete. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ListGlossariesRequest(proto.Message): + r"""Request message for ListGlossaries. + + Attributes: + parent (str): + Required. The name of the project from which + to list all of the glossaries. + page_size (int): + Optional. Requested page size. The server may + return fewer glossaries than requested. If + unspecified, the server picks an appropriate + default. + page_token (str): + Optional. A token identifying a page of results the server + should return. Typically, this is the value of + [ListGlossariesResponse.next_page_token] returned from the + previous call to ``ListGlossaries`` method. The first page + is returned if ``page_token``\ is empty or missing. + filter (str): + Optional. Filter specifying constraints of a + list operation. Filtering is not supported yet, + and the parameter currently has no effect. If + missing, no filtering is performed. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=4) + + +class ListGlossariesResponse(proto.Message): + r"""Response message for ListGlossaries. + + Attributes: + glossaries (Sequence[~.translation_service.Glossary]): + The list of glossaries for a project. + next_page_token (str): + A token to retrieve a page of results. Pass this value in + the [ListGlossariesRequest.page_token] field in the + subsequent call to ``ListGlossaries`` method to retrieve the + next page of results. + """ + + @property + def raw_page(self): + return self + + glossaries = proto.RepeatedField(proto.MESSAGE, number=1, message=Glossary,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class CreateGlossaryMetadata(proto.Message): + r"""Stored in the + [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata] + field returned by CreateGlossary. + + Attributes: + name (str): + The name of the glossary that is being + created. + state (~.translation_service.CreateGlossaryMetadata.State): + The current state of the glossary creation + operation. + submit_time (~.timestamp.Timestamp): + The time when the operation was submitted to + the server. + """ + + class State(proto.Enum): + r"""Enumerates the possible states that the creation request can + be in. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLING = 4 + CANCELLED = 5 + + name = proto.Field(proto.STRING, number=1) + + state = proto.Field(proto.ENUM, number=2, enum=State,) + + submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class DeleteGlossaryMetadata(proto.Message): + r"""Stored in the + [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata] + field returned by DeleteGlossary. + + Attributes: + name (str): + The name of the glossary that is being + deleted. + state (~.translation_service.DeleteGlossaryMetadata.State): + The current state of the glossary deletion + operation. + submit_time (~.timestamp.Timestamp): + The time when the operation was submitted to + the server. + """ + + class State(proto.Enum): + r"""Enumerates the possible states that the creation request can + be in. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + CANCELLING = 4 + CANCELLED = 5 + + name = proto.Field(proto.STRING, number=1) + + state = proto.Field(proto.ENUM, number=2, enum=State,) + + submit_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class DeleteGlossaryResponse(proto.Message): + r"""Stored in the + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field returned by DeleteGlossary. + + Attributes: + name (str): + The name of the deleted glossary. + submit_time (~.timestamp.Timestamp): + The time when the operation was submitted to + the server. + end_time (~.timestamp.Timestamp): + The time when the glossary deletion is finished and + [google.longrunning.Operation.done][google.longrunning.Operation.done] + is set to true. + """ + + name = proto.Field(proto.STRING, number=1) + + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-translate/mypy.ini b/packages/google-cloud-translate/mypy.ini new file mode 100644 index 000000000000..4505b485436b --- /dev/null +++ b/packages/google-cloud-translate/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/packages/google-cloud-translate/noxfile.py b/packages/google-cloud-translate/noxfile.py index c8e9c95f9189..86bba293eaa7 100644 --- a/packages/google-cloud-translate/noxfile.py +++ b/packages/google-cloud-translate/noxfile.py @@ -27,8 +27,8 @@ BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -70,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") @@ -77,7 +79,7 @@ def default(session): session.run( "py.test", "--quiet", - "--cov=google.cloud.translation", + "--cov=google.cloud.translate", "--cov=google.cloud", "--cov=tests.unit", "--cov-append", @@ -122,7 +124,6 @@ def system(session): session.install( "mock", "pytest", "google-cloud-testutils", ) - session.install("-e", "test_utils") session.install("-e", ".") # Run py.test against the system tests. @@ -140,7 +141,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=95") + session.run("coverage", "report", "--show-missing", "--fail-under=100") session.run("coverage", "erase") @@ -150,7 +151,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") + session.install("sphinx", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -172,7 +173,7 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark", "sphinx-docfx-yaml") + session.install("sphinx", "alabaster", "recommonmark", "sphinx-docfx-yaml") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/packages/google-cloud-translate/samples/snippets/beta_snippets.py b/packages/google-cloud-translate/samples/snippets/beta_snippets.py index 96b19f5de7e5..10ec2dc6e648 100644 --- a/packages/google-cloud-translate/samples/snippets/beta_snippets.py +++ b/packages/google-cloud-translate/samples/snippets/beta_snippets.py @@ -25,14 +25,17 @@ def translate_text(project_id, text): # text = 'Text you wish to translate' location = 'global' - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" response = client.translate_text( - parent=parent, - contents=[text], - mime_type='text/plain', # mime types: text/plain, text/html - source_language_code='en-US', - target_language_code='sr-Latn') + request={ + "parent": parent, + "contents": [text], + "mime_type": "text/plain", # mime types: text/plain, text/html + "source_language_code": "en-US", + "target_language_code": "sr-Latn" + } + ) for translation in response.translations: print(u'Translated Text: {}'.format(translation)) @@ -49,7 +52,7 @@ def batch_translate_text(project_id, input_uri, output_uri): # output_uri = 'gs://YOUR_BUCKET_ID/path_to_store_results/' location = 'us-central1' - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" gcs_source = translate.types.GcsSource(input_uri=input_uri) @@ -64,11 +67,14 @@ def batch_translate_text(project_id, input_uri, output_uri): gcs_destination=gcs_destination) operation = client.batch_translate_text( - parent=parent, - source_language_code='en-US', - target_language_codes=['sr-Latn'], - input_configs=[input_config], - output_config=output_config) + request={ + "parent": parent, + "source_language_code": "en-US", + "target_language_codes": ["sr-Latn"], + "input_configs": [input_config], + "output_config": output_config + } + ) result = operation.result(timeout=240) @@ -86,12 +92,15 @@ def detect_language(project_id, text): # text = 'Text you wish to translate' location = 'global' - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" response = client.detect_language( - parent=parent, - content=text, - mime_type='text/plain') # mime types: text/plain, text/html + request={ + "parent": parent, + "content": text, + "mime_type": "text/plain" # mime types: text/plain, text/html + } + ) for language in response.languages: print(u'Language Code: {} (Confidence: {})'.format( @@ -108,9 +117,9 @@ def list_languages(project_id): # project_id = YOUR_PROJECT_ID location = 'global' - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" - response = client.get_supported_languages(parent) + response = client.get_supported_languages(parent=parent) print('Supported Languages:') for language in response.languages: @@ -127,7 +136,7 @@ def list_languages_with_target(project_id, display_language_code): # display_language_code = 'is' location = 'global' - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" response = client.get_supported_languages( parent=parent, @@ -168,7 +177,7 @@ def create_glossary(project_id, glossary_id): language_codes_set=language_codes_set, input_config=input_config) - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" operation = client.create_glossary(parent=parent, glossary=glossary) @@ -186,9 +195,9 @@ def list_glossaries(project_id): # project_id = 'YOUR_PROJECT_ID' location = 'us-central1' # The location of the glossary - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" - for glossary in client.list_glossaries(parent): + for glossary in client.list_glossaries(parent=parent): print(u'Name: {}'.format(glossary.name)) print(u'Entry count: {}'.format(glossary.entry_count)) print(u'Input uri: {}'.format( @@ -206,12 +215,12 @@ def get_glossary(project_id, glossary_id): # project_id = 'YOUR_PROJECT_ID' # glossary_id = 'GLOSSARY_ID' - parent = client.glossary_path( + name = client.glossary_path( project_id, 'us-central1', # The location of the glossary glossary_id) - response = client.get_glossary(parent) + response = client.get_glossary(name=name) print(u'Name: {}'.format(response.name)) print(u'Language Pair:') print(u'\tSource Language Code: {}'.format( @@ -231,12 +240,12 @@ def delete_glossary(project_id, glossary_id): # project_id = 'YOUR_PROJECT_ID' # glossary_id = 'GLOSSARY_ID' - parent = client.glossary_path( + name = client.glossary_path( project_id, 'us-central1', # The location of the glossary glossary_id) - operation = client.delete_glossary(parent) + operation = client.delete_glossary(name=name) result = operation.result(timeout=90) print(u'Deleted: {}'.format(result.name)) # [END translate_delete_glossary_beta] @@ -260,15 +269,18 @@ def translate_text_with_glossary(project_id, glossary_id, text): glossary_config = translate.types.TranslateTextGlossaryConfig( glossary=glossary) - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" result = client.translate_text( - parent=parent, - contents=[text], - mime_type='text/plain', # mime types: text/plain, text/html - source_language_code='en', - target_language_code='es', - glossary_config=glossary_config) + request={ + "parent": parent, + "contents": [text], + "mime_type": "text/plain", + "source_language_code": "en", + "target_language_code": "es", + "glossary_config": glossary_config + } + ) for translation in result.glossary_translations: print(translation) @@ -355,4 +367,4 @@ def translate_text_with_glossary(project_id, glossary_id, text): delete_glossary(args.project_id, args.glossary_id) elif args.command == 'translate-with-glossary': translate_text_with_glossary( - args.project_id, args.glossary_id, args.text) + args.project_id, args.glossary_id, args.text) diff --git a/packages/google-cloud-translate/samples/snippets/hybrid_glossaries/README.rst b/packages/google-cloud-translate/samples/snippets/hybrid_glossaries/README.rst index e68b8114ce3c..61fdc27fef72 100644 --- a/packages/google-cloud-translate/samples/snippets/hybrid_glossaries/README.rst +++ b/packages/google-cloud-translate/samples/snippets/hybrid_glossaries/README.rst @@ -1,4 +1,3 @@ - .. This file is automatically generated. Do not edit this file directly. Google Translation API Python Samples @@ -16,11 +15,13 @@ This directory contains samples for Google Translation API. With `Google Transla .. _Google Translation API: https://cloud.google.com/translate/docs + + + Setup ------------------------------------------------------------------------------- - Authentication ++++++++++++++ @@ -31,9 +32,6 @@ credentials for applications. .. _Authentication Getting Started Guide: https://cloud.google.com/docs/authentication/getting-started - - - Install Dependencies ++++++++++++++++++++ @@ -48,7 +46,7 @@ Install Dependencies .. _Python Development Environment Setup Guide: https://cloud.google.com/python/setup -#. Create a virtualenv. Samples are compatible with Python 3.6+. +#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. .. code-block:: bash @@ -64,15 +62,9 @@ Install Dependencies .. _pip: https://pip.pypa.io/ .. _virtualenv: https://virtualenv.pypa.io/ - - - - - Samples ------------------------------------------------------------------------------- - Using glossaries with vision and text-to-speech +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @@ -91,10 +83,6 @@ To run this sample: - - - - The client library ------------------------------------------------------------------------------- @@ -110,5 +98,4 @@ to `browse the source`_ and `report issues`_. https://github.com/GoogleCloudPlatform/google-cloud-python/issues - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ +.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/packages/google-cloud-translate/samples/snippets/hybrid_glossaries/hybrid_tutorial.py b/packages/google-cloud-translate/samples/snippets/hybrid_glossaries/hybrid_tutorial.py index 7d36174b4766..c4a8434502ba 100644 --- a/packages/google-cloud-translate/samples/snippets/hybrid_glossaries/hybrid_tutorial.py +++ b/packages/google-cloud-translate/samples/snippets/hybrid_glossaries/hybrid_tutorial.py @@ -104,7 +104,7 @@ def create_glossary(languages, project_id, glossary_name, glossary_uri): language_codes_set=language_codes_set, input_config=input_config) - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" # Create glossary resource # Handle exception for case in which a glossary @@ -150,15 +150,18 @@ def translate_text(text, source_language_code, target_language_code, glossary_config = translate.types.TranslateTextGlossaryConfig( glossary=glossary) - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" result = client.translate_text( - parent=parent, - contents=[text], - mime_type='text/plain', # mime types: text/plain, text/html - source_language_code=source_language_code, - target_language_code=target_language_code, - glossary_config=glossary_config) + request={ + "parent": parent, + "contents": [text], + "mime_type": "text/plain", # mime types: text/plain, text/html + "source_language_code": source_language_code, + "target_language_code": target_language_code, + "glossary_config": glossary_config + } + ) # Extract translated text from API response return result.glossary_translations[0].translated_text @@ -240,7 +243,7 @@ def main(): # uri of .csv file uploaded to Cloud Storage glossary_uri = 'gs://cloud-samples-data/translation/bistro_glossary.csv' - create_glossary(glossary_langs, PROJECT_ID, glossary_name, glossary_uri) + create_glossary(glossary_langs, PROJECT_ID, glossary_name, glossary_uri) # photo -> detected text text_to_translate = pic_to_text(infile) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_batch_translate_text.py b/packages/google-cloud-translate/samples/snippets/translate_v3_batch_translate_text.py index 4454afb40746..487b0965774d 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_batch_translate_text.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_batch_translate_text.py @@ -36,15 +36,18 @@ def batch_translate_text( } gcs_destination = {"output_uri_prefix": output_uri} output_config = {"gcs_destination": gcs_destination} - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" # Supported language codes: https://cloud.google.com/translate/docs/language operation = client.batch_translate_text( - parent=parent, - source_language_code="en", - target_language_codes=["ja"], # Up to 10 language codes here. - input_configs=[input_configs_element], - output_config=output_config) + request={ + "parent": parent, + "source_language_code": "en", + "target_language_codes": ["ja"], # Up to 10 language codes here. + "input_configs": [input_configs_element], + "output_config": output_config + } + ) print(u"Waiting for operation to complete...") response = operation.result(timeout) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_batch_translate_text_with_glossary.py b/packages/google-cloud-translate/samples/snippets/translate_v3_batch_translate_text_with_glossary.py index 97845e2a8e2b..e9c4a7c26375 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_batch_translate_text_with_glossary.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_batch_translate_text_with_glossary.py @@ -42,7 +42,7 @@ def batch_translate_text_with_glossary( gcs_destination = {"output_uri_prefix": output_uri} output_config = {"gcs_destination": gcs_destination} - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" # glossary is a custom dictionary Translation API uses # to translate the domain-specific terminology. @@ -50,19 +50,21 @@ def batch_translate_text_with_glossary( project_id, "us-central1", glossary_id # The location of the glossary ) - glossary_config = translate.types.TranslateTextGlossaryConfig( + glossary_config = translate.TranslateTextGlossaryConfig( glossary=glossary_path ) glossaries = {"ja": glossary_config} # target lang as key operation = client.batch_translate_text( - parent=parent, - source_language_code="en", - target_language_codes=["ja"], # Up to 10 language codes here. - input_configs=[input_configs_element], - glossaries=glossaries, - output_config=output_config, + request={ + "parent": parent, + "source_language_code": "en", + "target_language_codes": ["ja"], # Up to 10 language codes here. + "input_configs": [input_configs_element], + "glossaries": glossaries, + "output_config": output_config + } ) print(u"Waiting for operation to complete...") diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_create_glossary.py b/packages/google-cloud-translate/samples/snippets/translate_v3_create_glossary.py index 603cb4cc5681..2955acaa3478 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_create_glossary.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_create_glossary.py @@ -47,7 +47,7 @@ def create_glossary( name=name, language_codes_set=language_codes_set, input_config=input_config ) - parent = client.location_path(project_id, location) + parent = f"projects/{project_id}/locations/{location}" # glossary is a custom dictionary Translation API uses # to translate the domain-specific terminology. operation = client.create_glossary(parent=parent, glossary=glossary) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_delete_glossary.py b/packages/google-cloud-translate/samples/snippets/translate_v3_delete_glossary.py index e8acf76c31f4..fb9f86afe59e 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_delete_glossary.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_delete_glossary.py @@ -24,9 +24,9 @@ def delete_glossary( """Delete a specific glossary based on the glossary ID.""" client = translate.TranslationServiceClient() - parent = client.glossary_path(project_id, "us-central1", glossary_id) + name = client.glossary_path(project_id, "us-central1", glossary_id) - operation = client.delete_glossary(parent) + operation = client.delete_glossary(name=name) result = operation.result(timeout) print("Deleted: {}".format(result.name)) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_detect_language.py b/packages/google-cloud-translate/samples/snippets/translate_v3_detect_language.py index 759eb41a4d30..9e92b6079d5d 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_detect_language.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_detect_language.py @@ -21,7 +21,9 @@ def detect_language(project_id="YOUR_PROJECT_ID"): client = translate.TranslationServiceClient() - parent = client.location_path(project_id, "global") + location = "global" + + parent = f"projects/{project_id}/locations/{location}" # Detail on supported types can be found here: # https://cloud.google.com/translate/docs/supported-formats diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_get_glossary.py b/packages/google-cloud-translate/samples/snippets/translate_v3_get_glossary.py index 99753136c5b0..f4c2aaae4602 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_get_glossary.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_get_glossary.py @@ -23,7 +23,7 @@ def get_glossary(project_id="YOUR_PROJECT_ID", glossary_id="YOUR_GLOSSARY_ID"): name = client.glossary_path(project_id, "us-central1", glossary_id) - response = client.get_glossary(name) + response = client.get_glossary(name=name) print(u"Glossary name: {}".format(response.name)) print(u"Entry count: {}".format(response.entry_count)) print(u"Input URI: {}".format(response.input_config.gcs_source.input_uri)) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_get_supported_languages.py b/packages/google-cloud-translate/samples/snippets/translate_v3_get_supported_languages.py index 6e15458d9cca..db7792787241 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_get_supported_languages.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_get_supported_languages.py @@ -21,7 +21,7 @@ def get_supported_languages(project_id="YOUR_PROJECT_ID"): client = translate.TranslationServiceClient() - parent = client.location_path(project_id, "global") + parent = f"projects/{project_id}" # Supported language codes: https://cloud.google.com/translate/docs/languages response = client.get_supported_languages(parent=parent) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_get_supported_languages_with_target.py b/packages/google-cloud-translate/samples/snippets/translate_v3_get_supported_languages_with_target.py index f71138b533e4..3a164dcbd28b 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_get_supported_languages_with_target.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_get_supported_languages_with_target.py @@ -20,7 +20,10 @@ def get_supported_languages_with_target(project_id="YOUR_PROJECT_ID"): """Listing supported languages with target language name.""" client = translate.TranslationServiceClient() - parent = client.location_path(project_id, "global") + + location = "global" + + parent = f"projects/{project_id}/locations/{location}" # Supported language codes: https://cloud.google.com/translate/docs/languages response = client.get_supported_languages( diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_list_glossary.py b/packages/google-cloud-translate/samples/snippets/translate_v3_list_glossary.py index 53e51d85447f..934194b4443f 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_list_glossary.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_list_glossary.py @@ -21,10 +21,12 @@ def list_glossaries(project_id="YOUR_PROJECT_ID"): client = translate.TranslationServiceClient() - parent = client.location_path(project_id, "us-central1") + location = "us-central1" + + parent = f"projects/{project_id}/locations/{location}" # Iterate over all results - for glossary in client.list_glossaries(parent): + for glossary in client.list_glossaries(parent=parent): print("Name: {}".format(glossary.name)) print("Entry count: {}".format(glossary.entry_count)) print("Input uri: {}".format(glossary.input_config.gcs_source.input_uri)) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text.py b/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text.py index 086f775a37fb..78a79b4e1072 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text.py @@ -21,17 +21,22 @@ def translate_text(text="YOUR_TEXT_TO_TRANSLATE", project_id="YOUR_PROJECT_ID"): client = translate.TranslationServiceClient() - parent = client.location_path(project_id, "global") + location = "global" + + parent = f"projects/{project_id}/locations/{location}" # Detail on supported types can be found here: # https://cloud.google.com/translate/docs/supported-formats response = client.translate_text( - parent=parent, - contents=[text], - mime_type="text/plain", # mime types: text/plain, text/html - source_language_code="en-US", - target_language_code="fr", + request={ + "parent": parent, + "contents": [text], + "mime_type": "text/plain", # mime types: text/plain, text/html + "source_language_code": "en-US", + "target_language_code": "fr" + } ) + # Display the translation for each input text provided for translation in response.translations: print(u"Translated text: {}".format(translation.translated_text)) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text_with_glossary.py b/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text_with_glossary.py index ca0eeaccced9..b62d54133b20 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text_with_glossary.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text_with_glossary.py @@ -14,7 +14,7 @@ # [START translate_v3_translate_text_with_glossary] -from google.cloud import translate_v3 +from google.cloud import translate def translate_text_with_glossary( @@ -24,24 +24,28 @@ def translate_text_with_glossary( ): """Translates a given text using a glossary.""" - client = translate_v3.TranslationServiceClient() - parent = client.location_path(project_id, "us-central1") + client = translate.TranslationServiceClient() + location = "us-central1" + parent = f"projects/{project_id}/locations/{location}" glossary = client.glossary_path( project_id, "us-central1", glossary_id # The location of the glossary ) - glossary_config = translate_v3.types.TranslateTextGlossaryConfig( + glossary_config = translate.TranslateTextGlossaryConfig( glossary=glossary) # Supported language codes: https://cloud.google.com/translate/docs/languages response = client.translate_text( - contents=[text], - target_language_code="ja", - source_language_code="en", - parent=parent, - glossary_config=glossary_config, + request={ + "contents": [text], + "target_language_code": "ja", + "source_language_code": "en", + "parent": parent, + "glossary_config": glossary_config + } ) + print("Translated text: \n") for translation in response.glossary_translations: print(u"\t {}".format(translation.translated_text)) diff --git a/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text_with_model.py b/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text_with_model.py index 8a0b0bb7825a..44c92f96b437 100644 --- a/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text_with_model.py +++ b/packages/google-cloud-translate/samples/snippets/translate_v3_translate_text_with_model.py @@ -26,19 +26,21 @@ def translate_text_with_model( client = translate.TranslationServiceClient() - parent = client.location_path(project_id, "us-central1") - model_path = "projects/{}/locations/{}/models/{}".format( - project_id, "us-central1", model_id - ) + location = "us-central1" + parent = f"projects/{project_id}/locations/{location}" + model_path = f"{parent}/models/{model_id}" # Supported language codes: https://cloud.google.com/translate/docs/languages response = client.translate_text( - contents=[text], - target_language_code="ja", - model=model_path, - source_language_code="en", - parent=parent, - mime_type="text/plain", # mime types: text/plain, text/html + request={ + "contents": [text], + "target_language_code": "ja", + "model": model_path, + "source_language_code": "en", + "parent": parent, + "mime_type": "text/plain", # mime types: text/plain, text/html + } + ) # Display the translation for each input text provided for translation in response.translations: diff --git a/packages/google-cloud-translate/scripts/fixup_translation_v3_keywords.py b/packages/google-cloud-translate/scripts/fixup_translation_v3_keywords.py new file mode 100644 index 000000000000..60b6c6d3e5ae --- /dev/null +++ b/packages/google-cloud-translate/scripts/fixup_translation_v3_keywords.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- + +# 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class translationCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_translate_text': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'labels', ), + 'create_glossary': ('parent', 'glossary', ), + 'delete_glossary': ('name', ), + 'detect_language': ('parent', 'model', 'content', 'mime_type', 'labels', ), + 'get_glossary': ('name', ), + 'get_supported_languages': ('parent', 'display_language_code', 'model', ), + 'list_glossaries': ('parent', 'page_size', 'page_token', 'filter', ), + 'translate_text': ('contents', 'target_language_code', 'parent', 'mime_type', 'source_language_code', 'model', 'glossary_config', 'labels', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=translationCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the translation client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-cloud-translate/scripts/fixup_translation_v3beta1_keywords.py b/packages/google-cloud-translate/scripts/fixup_translation_v3beta1_keywords.py new file mode 100644 index 000000000000..60b6c6d3e5ae --- /dev/null +++ b/packages/google-cloud-translate/scripts/fixup_translation_v3beta1_keywords.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- + +# 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class translationCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_translate_text': ('parent', 'source_language_code', 'target_language_codes', 'input_configs', 'output_config', 'models', 'glossaries', 'labels', ), + 'create_glossary': ('parent', 'glossary', ), + 'delete_glossary': ('name', ), + 'detect_language': ('parent', 'model', 'content', 'mime_type', 'labels', ), + 'get_glossary': ('name', ), + 'get_supported_languages': ('parent', 'display_language_code', 'model', ), + 'list_glossaries': ('parent', 'page_size', 'page_token', 'filter', ), + 'translate_text': ('contents', 'target_language_code', 'parent', 'mime_type', 'source_language_code', 'model', 'glossary_config', 'labels', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=translationCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the translation client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-cloud-translate/setup.py b/packages/google-cloud-translate/setup.py index fb2dc075972f..cac8febce55c 100644 --- a/packages/google-cloud-translate/setup.py +++ b/packages/google-cloud-translate/setup.py @@ -29,8 +29,10 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.15.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "google-cloud-core >= 1.1.0, < 2.0dev", + "libcst >= 0.2.5", + "proto-plus >= 0.4.0", ] extras = {} @@ -46,7 +48,9 @@ # Only include packages under the 'google' namespace. Do not include tests, # benchmarks, etc. packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] # Determine which namespaces are needed. @@ -69,21 +73,23 @@ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], platforms="Posix; MacOS X; Windows", packages=packages, + scripts=[ + "scripts/fixup_translation_v3_keywords.py", + "scripts/fixup_translation_v3beta1_keywords.py", + ], namespace_packages=namespaces, install_requires=dependencies, extras_require=extras, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-translate/synth.metadata b/packages/google-cloud-translate/synth.metadata index fa1d2bed0cd8..ae0c1f5516f8 100644 --- a/packages/google-cloud-translate/synth.metadata +++ b/packages/google-cloud-translate/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "db69b46790b55a82ab7cfa473d031da787bc7591", - "internalRef": "320411362" + "sha": "868615a5c1c1059c636bb3d82a555edb1d5a251e", + "internalRef": "324294521" } }, { @@ -37,7 +37,7 @@ "apiName": "translate", "apiVersion": "v3beta1", "language": "python", - "generator": "bazel" + "generator": "gapic-generator-python" } }, { @@ -46,7 +46,7 @@ "apiName": "translate", "apiVersion": "v3", "language": "python", - "generator": "bazel" + "generator": "gapic-generator-python" } } ] diff --git a/packages/google-cloud-translate/synth.py b/packages/google-cloud-translate/synth.py index 6f128fd62efa..df2a8a73f178 100644 --- a/packages/google-cloud-translate/synth.py +++ b/packages/google-cloud-translate/synth.py @@ -18,7 +18,7 @@ from synthtool import gcp from synthtool.languages import python -gapic = gcp.GAPICBazel() +gapic = gcp.GAPICMicrogenerator() common = gcp.CommonTemplates() versions = ["v3beta1", "v3"] @@ -38,68 +38,48 @@ library = gapic.py_library( service="translate", version=version, - bazel_target=f"//google/cloud/translate/{version}:translation-{version}-py", - include_protos=True, + proto_path=f"google/cloud/translate/{version}" ) - # s.move(library / f'google/cloud/translation_{version}', f'google/cloud/translate_{version}', excludes=excludes) - s.move(library / f"google/cloud/translate_{version}", excludes=excludes) - s.move(library / "tests") - s.move(library / f"docs/gapic/{version}") + s.move(library / "google/cloud/translation", "google/cloud/translate") + s.move(library / f"google/cloud/translation_{version}", f"google/cloud/translate_{version}") + s.move(library / f"docs/translation_{version}", f"docs/translate_{version}") + s.move(library / f"tests/unit/gapic/translation_{version}", f"tests/unit/gapic/translate_{version}") + s.move(library / "scripts") - # translation -> translate - s.replace( - "google/**/translation_service_pb2_grpc.py", - f"google.cloud.translation_{version}.proto", - f"google.cloud.translate_{version}.proto", - ) - s.replace( - f"google/cloud/translate_{version}/gapic/translation_service_client.py", - "google-cloud-translation", - "google-cloud-translate", - ) - -# Use the highest version library to generate documentation import alias. -s.move(library / "google/cloud/translate.py") - -s.replace( - "google/cloud/**/translation_service_pb2.py", - r"""record delimiters are ‘:raw-latex:`\\n`’ instead of - ‘:raw-latex:`\\r`:raw-latex:`\\n`’.""", - r"""record delimiters are ``\\\\\\\\n`` instead of - ``\\\\\\\\r\\\\\\\\n``.""", -) - -# Fix docstring issue for classes with no summary line +# google.cloud.translation -> google.cloud.translate s.replace( - "google/cloud/**/proto/*_pb2.py", - ''''__doc__': """Attributes:''', - ''''__doc__': """ - Attributes:''', + ["google/cloud/translate*/**/*.py", "docs/translate_v*/*"], + " google.cloud.translation", + " google.cloud.translate" ) +s.replace("tests/**/*.py", "google.cloud.translation", "google.cloud.translate") -# Fix wrapping for literal string +# TODO(danoscarmike): remove once upstream protos have been fixed +# Escape underscores in gs:\\ URLs s.replace( - "google/cloud/**/translation_service_pb2.py", - r"""This field has the same length as \[``contents` -\s+`\]\[google\.cloud\.translation\.v3beta1\.TranslateTextRequest\.conte -\s+nts\]\.""", - """This field has the same length as [``contents``][google.cloud.translation.v3beta1.TranslateTextRequest.contents].""", + "google/cloud/translate_v3*/types/translation_service.py", + r"""a_b_c_""", + """a_b_c\_""" ) # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -# templated_files = gcp.CommonTemplates().py_library(unit_cov_level=100, cov_level=100) -# Pass dependencies to system tests templated_files = common.py_library( - unit_cov_level=95, cov_level=95, samples=True, - system_test_dependencies=['test_utils'] + samples=True, + microgenerator=True, ) -s.move(templated_files) +s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file -# TODO(busunkim): Use latest sphinx after microgenerator transition -s.replace("noxfile.py", '''["']sphinx["']''', '"sphinx<3.0.0"') +# Correct namespace in noxfile +s.replace("noxfile.py", "google.cloud.translation", "google.cloud.translate") + +# ---------------------------------------------------------------------------- +# Samples templates +# ---------------------------------------------------------------------------- + +python.py_samples() # ---------------------------------------------------------------------------- # Samples templates diff --git a/packages/google-cloud-translate/test_utils/credentials.json.enc b/packages/google-cloud-translate/test_utils/credentials.json.enc deleted file mode 100644 index f073c7e4f774..000000000000 --- a/packages/google-cloud-translate/test_utils/credentials.json.enc +++ /dev/null @@ -1,49 +0,0 @@ -U2FsdGVkX1/vVm/dOEg1DCACYbdOcL+ey6+64A+DZGZVgF8Z/3skK6rpPocu6GOA -UZAqASsBH9QifDf8cKVXQXVYpYq6HSv2O0w7vOmVorZO9GYPo98s9/8XO+4ty/AU -aB6TD68frBAYv4cT/l5m7aYdzfzMTy0EOXoleZT09JYP3B5FV3KCO114FzMXGwrj -HXsR6E5SyUUlUnWPC3eD3aqmovay0gxOKYO3ZwjFK1nlbN/8q6/8nwBCf/Bg6SHV -V93pNxdolRlJev9kgKz4RN1z4jGCy5PAndhSLE82NFIs9LoAiEOU5YeMlN+Ulqus -J92nh+ptUe9a4pJGbAuveUWO7zdS1QyXvTMUcmmSfXCNm/eIQjNuu5+rHtIjWKh8 -Ilwj2w1aTfSptQEhk/kwRgFz/d11vfwJzvwTmCxO6zyOeL0VUWLqdCBGgG5As9He -/RenF8PZ1O0WbTt7fns5oTlTk/MUo+0xJ1xqvu/y45LaqqcBAnEdrWKmtM3dJHWv -ufQku+kD+83F/VwBnQdvgMHu6KZEs6LRrNo58r4QuK6fS7VCACdzxID1RM2cL7kT -6BFRlyGj1aigmjne9g9M9Jx4R+mZDpPU1WDzzG71J4qCUwaX8Dfwutuv4uiFvzwq -NUF0wLJJPtKWmtW+hnZ/fhHQGCRsOpZzFnqp6Zv7J7k6esqxMgIjfal7Djk5Acy8 -j3iVvm6CYmKMVqzL62JHYS9Ye83tzBCaR8hpnJQKgH3FSOFY8HSwrtQSIsl/hSeF -41sgnz0Y+/gkzNeU18qFk+eCZmvljyu+JK0nPYUgpOCJYVBNQpNHz5PUyiAEKhtM -IOSdjPRW1Y+Xf4RroJnLPoF24Ijwrow5LCm9hBRY6TPPMMmnIXCd23xcLJ1rMj6g -x4ZikElans+cwuc9wtbb7w01DcpTwQ1+eIV1qV+KIgpnLjRGLhZD4etobBsrwYu/ -vnIwy2QHCKENPb8sbdgp7x2mF7VSX0/7tf+9+i70EBiMzpOKBkiZhtLzm6hOBkEy -ODaWrx4lTTwbSw8Rmtf58APhPFMsjHoNsjiUoK249Y8Y2Ff4fMfqYsXu6VC1n/At -CuWYHc3EfBwFcLJS+RQB9kFk/4FygFBWq4Kj0MqoRruLbKmoGeJKH9q35W0f0NCD -j+iHt3014kMGiuyJe1UDQ6fvEihFFdHuDivFpPAXDt4PTY/WtpDhaGMx23kb54pK -jkAuxpznAB1lK3u9bGRXDasGeHIrNtIlPvgkrWHXvoBVqM7zry8TGtoxp3E3I42Z -cUfDWfB9GqVdrOwvrTzyZsl2uShRkAJaZFZj5aMyYxiptp4gM8CwWiNtOd2EwtRO -LxZX4M02PQFIqXV3FSDA0q6EwglUrTZdAlYeOEkopaKCtG31dEPOSQG3NGJAEYso -Cxm99H7970dp0OAgpNSgRbcWDbhVbQXnRzvFGqLeH6a9dQ/a8uD3s8Qm9Du/kB6d -XxTRe2OGxzcD0AgI8GClE4rIZHCLbcwuJRp0EYcN+pgY80O4U98fZ5RYpU6OYbU/ -MEiaBYFKtZtGkV6AQD568V7hHJWqc5DDfVHUQ/aeQwnKi2vnU66u+nnV2rZxXxLP -+dqeLRpul+wKa5b/Z5SfQ14Ff8s7aVyxaogGpyggyPL1vyq4KWZ6Or/wEE5hgNO4 -kBh6ht0QT1Hti8XY2JK1M+Jgbjgcg4jkHBGVqegrG1Rvcc2A4TYKwx+QMSBhyxrU -5qhROjS4lTcC42hQslMUkUwc4U/Y91XdFbOOnaAkwzI36NRYL0pmgZnYxGJZeRvr -E5foOhnOEVSFGdOkLfFh+FkWZQf56Lmn8Gg2wHE3dZTxLHibiUYfkgOr1uEosq29 -D1NstvlJURPQ0Q+8QQNWcl9nEZHMAjOmnL1hbx+QfuC6seucp+sXGzdZByMLZbvT -tG8KNL293CmyQowgf9MXToWYnwRkcvqfTaKyor2Ggze3JtoFW4t0j4DI1XPciZFX -XmfApHrzdB/bZadzxyaZ2NE0CuH9zDelwI6rz38xsN5liYnp5qmNKVCZVOHccXa6 -J8x365m5/VaaA2RrtdPqKxn8VaKy7+T690QgMXVGM4PbzQzQxHuSleklocqlP+sB -jSMXCZY+ng/i4UmRO9noiyW3UThYh0hIdMYs12EmmI9cnF/OuYZpl30fmqwV+VNM -td5B2fYvAvvsjiX60SFCn3DATP1GrPMBlZSmhhP3GYS+xrWt3Xxta9qIX2BEF1Gg -twnZZRjoULSRFUYPfJPEOfEH2UQwm84wxx/GezVE+S/RpBlatPOgCiLnNNaLfdTC -mTG9qY9elJv3GGQO8Lqgf4i8blExs05lSPk1BDhzTB6H9TLz+Ge0/l1QxKf3gPXU -aImK1azieXMXHECkdKxrzmehwu1dZ/oYOLc/OFQCETwSRoLPFOFpYUpizwmVVHR6 -uLSfRptte4ZOU3zHfpd/0+J4tkwHwEkGzsmMdqudlm7qME6upuIplyVBH8JiXzUK -n1RIH/OPmVEluAnexWRLZNdk7MrakIO4XACVbICENiYQgAIErP568An6twWEGDbZ -bEN64E3cVDTDRPRAunIhhsEaapcxpFEPWlHorxv36nMUt0R0h0bJlCu5QdzckfcX -ZrRuu1kl76ZfbSE8T0G4/rBb9gsU4Gn3WyvLIO3MgFBuxR68ZwcR8LpEUd8qp38H -NG4cxPmN1nGKo663Z+xI2Gt5up4gpl+fOt4mXqxY386rB7yHaOfElMG5TUYdrS9w -1xbbCVgeJ6zxX+NFlndG33cSAPprhw+C18eUu6ZU63WZcYFo3GfK6rs3lvYtofvE -8DxztdTidQedNVNE+63YCjhxd/cZUI5n/UpgYkr9owp7hNGJiR3tdoNLR2gcoGqL -qWhH928k2aSgF2j97LZ2OqoPCp0tUB7ho4jD2u4Ik3GLVNlCc3dCvWRvpHtDTQDv -tujESMfHUc9I2r4S/PD3bku/ABGwa977Yp1PjzJGr9RajA5is5n6GVpyynwjtKG4 -iyyITpdwpCgr8pueTBLwZnas3slmiMOog/E4PmPgctHzvC+vhQijhUtw5zSsmv0l -bZlw/mVhp5Ta7dTcLBKR8DA3m3vTbaEGkz0xpfQr7GfiSMRbJyvIw88pDK0gyTMD diff --git a/packages/google-cloud-translate/test_utils/scripts/circleci/get_tagged_package.py b/packages/google-cloud-translate/test_utils/scripts/circleci/get_tagged_package.py deleted file mode 100644 index c148b9dc2370..000000000000 --- a/packages/google-cloud-translate/test_utils/scripts/circleci/get_tagged_package.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright 2016 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. - -"""Helper to determine package from tag. -Get the current package directory corresponding to the Circle Tag. -""" - -from __future__ import print_function - -import os -import re -import sys - - -TAG_RE = re.compile(r""" - ^ - (?P - (([a-z]+)[_-])*) # pkg-name-with-hyphens-or-underscores (empty allowed) - ([0-9]+)\.([0-9]+)\.([0-9]+) # Version x.y.z (x, y, z all ints) - $ -""", re.VERBOSE) -TAG_ENV = 'CIRCLE_TAG' -ERROR_MSG = '%s env. var. not set' % (TAG_ENV,) -BAD_TAG_MSG = 'Invalid tag name: %s. Expected pkg-name-x.y.z' -CIRCLE_CI_SCRIPTS_DIR = os.path.dirname(__file__) -ROOT_DIR = os.path.realpath( - os.path.join(CIRCLE_CI_SCRIPTS_DIR, '..', '..', '..')) - - -def main(): - """Get the current package directory. - Prints the package directory out so callers can consume it. - """ - if TAG_ENV not in os.environ: - print(ERROR_MSG, file=sys.stderr) - sys.exit(1) - - tag_name = os.environ[TAG_ENV] - match = TAG_RE.match(tag_name) - if match is None: - print(BAD_TAG_MSG % (tag_name,), file=sys.stderr) - sys.exit(1) - - pkg_name = match.group('pkg') - if pkg_name is None: - print(ROOT_DIR) - else: - pkg_dir = pkg_name.rstrip('-').replace('-', '_') - print(os.path.join(ROOT_DIR, pkg_dir)) - - -if __name__ == '__main__': - main() diff --git a/packages/google-cloud-translate/test_utils/scripts/circleci/twine_upload.sh b/packages/google-cloud-translate/test_utils/scripts/circleci/twine_upload.sh deleted file mode 100755 index 23a4738e90b9..000000000000 --- a/packages/google-cloud-translate/test_utils/scripts/circleci/twine_upload.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash - -# Copyright 2016 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. - -set -ev - -# If this is not a CircleCI tag, no-op. -if [[ -z "$CIRCLE_TAG" ]]; then - echo "This is not a release tag. Doing nothing." - exit 0 -fi - -# H/T: http://stackoverflow.com/a/246128/1068170 -SCRIPT="$(dirname "${BASH_SOURCE[0]}")/get_tagged_package.py" -# Determine the package directory being deploying on this tag. -PKG_DIR="$(python ${SCRIPT})" - -# Ensure that we have the latest versions of Twine, Wheel, and Setuptools. -python3 -m pip install --upgrade twine wheel setuptools - -# Move into the package, build the distribution and upload. -cd ${PKG_DIR} -python3 setup.py sdist bdist_wheel -twine upload dist/* diff --git a/packages/google-cloud-translate/test_utils/scripts/get_target_packages.py b/packages/google-cloud-translate/test_utils/scripts/get_target_packages.py deleted file mode 100644 index 1d51830cc23a..000000000000 --- a/packages/google-cloud-translate/test_utils/scripts/get_target_packages.py +++ /dev/null @@ -1,268 +0,0 @@ -# Copyright 2017 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. - -"""Print a list of packages which require testing.""" - -import os -import re -import subprocess -import warnings - - -CURRENT_DIR = os.path.realpath(os.path.dirname(__file__)) -BASE_DIR = os.path.realpath(os.path.join(CURRENT_DIR, '..', '..')) -GITHUB_REPO = os.environ.get('GITHUB_REPO', 'google-cloud-python') -CI = os.environ.get('CI', '') -CI_BRANCH = os.environ.get('CIRCLE_BRANCH') -CI_PR = os.environ.get('CIRCLE_PR_NUMBER') -CIRCLE_TAG = os.environ.get('CIRCLE_TAG') -head_hash, head_name = subprocess.check_output(['git', 'show-ref', 'HEAD'] -).strip().decode('ascii').split() -rev_parse = subprocess.check_output( - ['git', 'rev-parse', '--abbrev-ref', 'HEAD'] -).strip().decode('ascii') -MAJOR_DIV = '#' * 78 -MINOR_DIV = '#' + '-' * 77 - -# NOTE: This reg-ex is copied from ``get_tagged_packages``. -TAG_RE = re.compile(r""" - ^ - (?P - (([a-z]+)-)*) # pkg-name-with-hyphens- (empty allowed) - ([0-9]+)\.([0-9]+)\.([0-9]+) # Version x.y.z (x, y, z all ints) - $ -""", re.VERBOSE) - -# This is the current set of dependencies by package. -# As of this writing, the only "real" dependency is that of error_reporting -# (on logging), the rest are just system test dependencies. -PKG_DEPENDENCIES = { - 'logging': {'pubsub'}, -} - - -def get_baseline(): - """Return the baseline commit. - - On a pull request, or on a branch, return the common parent revision - with the master branch. - - Locally, return a value pulled from environment variables, or None if - the environment variables are not set. - - On a push to master, return None. This will effectively cause everything - to be considered to be affected. - """ - - # If this is a pull request or branch, return the tip for master. - # We will test only packages which have changed since that point. - ci_non_master = (CI == 'true') and any([CI_BRANCH != 'master', CI_PR]) - - if ci_non_master: - - repo_url = 'git@github.com:GoogleCloudPlatform/{}'.format(GITHUB_REPO) - subprocess.run(['git', 'remote', 'add', 'baseline', repo_url], - stderr=subprocess.DEVNULL) - subprocess.run(['git', 'pull', 'baseline'], stderr=subprocess.DEVNULL) - - if CI_PR is None and CI_BRANCH is not None: - output = subprocess.check_output([ - 'git', 'merge-base', '--fork-point', - 'baseline/master', CI_BRANCH]) - return output.strip().decode('ascii') - - return 'baseline/master' - - # If environment variables are set identifying what the master tip is, - # use that. - if os.environ.get('GOOGLE_CLOUD_TESTING_REMOTE', ''): - remote = os.environ['GOOGLE_CLOUD_TESTING_REMOTE'] - branch = os.environ.get('GOOGLE_CLOUD_TESTING_BRANCH', 'master') - return '%s/%s' % (remote, branch) - - # If we are not in CI and we got this far, issue a warning. - if not CI: - warnings.warn('No baseline could be determined; this means tests ' - 'will run for every package. If this is local ' - 'development, set the $GOOGLE_CLOUD_TESTING_REMOTE ' - 'environment variable.') - - # That is all we can do; return None. - return None - - -def get_changed_files(): - """Return a list of files that have been changed since the baseline. - - If there is no base, return None. - """ - # Get the baseline, and fail quickly if there is no baseline. - baseline = get_baseline() - print('# Baseline commit: {}'.format(baseline)) - if not baseline: - return None - - # Return a list of altered files. - try: - return subprocess.check_output([ - 'git', 'diff', '--name-only', '{}..HEAD'.format(baseline), - ], stderr=subprocess.DEVNULL).decode('utf8').strip().split('\n') - except subprocess.CalledProcessError: - warnings.warn('Unable to perform git diff; falling back to assuming ' - 'all packages have changed.') - return None - - -def reverse_map(dict_of_sets): - """Reverse a map of one-to-many. - - So the map:: - - { - 'A': {'B', 'C'}, - 'B': {'C'}, - } - - becomes - - { - 'B': {'A'}, - 'C': {'A', 'B'}, - } - - Args: - dict_of_sets (dict[set]): A dictionary of sets, mapping - one value to many. - - Returns: - dict[set]: The reversed map. - """ - result = {} - for key, values in dict_of_sets.items(): - for value in values: - result.setdefault(value, set()).add(key) - - return result - -def get_changed_packages(file_list): - """Return a list of changed packages based on the provided file list. - - If the file list is None, then all packages should be considered to be - altered. - """ - # Determine a complete list of packages. - all_packages = set() - for file_ in os.listdir(BASE_DIR): - abs_file = os.path.realpath(os.path.join(BASE_DIR, file_)) - nox_file = os.path.join(abs_file, 'nox.py') - if os.path.isdir(abs_file) and os.path.isfile(nox_file): - all_packages.add(file_) - - # If ther is no file list, send down the full package set. - if file_list is None: - return all_packages - - # Create a set based on the list of changed files. - answer = set() - reverse_deps = reverse_map(PKG_DEPENDENCIES) - for file_ in file_list: - # Ignore root directory changes (setup.py, .gitignore, etc.). - if os.path.sep not in file_: - continue - - # Ignore changes that are not in a package (usually this will be docs). - package = file_.split(os.path.sep, 1)[0] - if package not in all_packages: - continue - - # If there is a change in core, short-circuit now and return - # everything. - if package in ('core',): - return all_packages - - # Add the package, as well as any dependencies this package has. - # NOTE: For now, dependencies only go down one level. - answer.add(package) - answer = answer.union(reverse_deps.get(package, set())) - - # We got this far without being short-circuited; return the final answer. - return answer - - -def get_tagged_package(): - """Return the package corresponding to the current tag. - - If there is not tag, will return :data:`None`. - """ - if CIRCLE_TAG is None: - return - - match = TAG_RE.match(CIRCLE_TAG) - if match is None: - return - - pkg_name = match.group('pkg') - if pkg_name == '': - # NOTE: This corresponds to the "umbrella" tag. - return - - return pkg_name.rstrip('-').replace('-', '_') - - -def get_target_packages(): - """Return a list of target packages to be run in the current build. - - If in a tag build, will run only the package(s) that are tagged, otherwise - will run the packages that have file changes in them (or packages that - depend on those). - """ - tagged_package = get_tagged_package() - if tagged_package is None: - file_list = get_changed_files() - print(MAJOR_DIV) - print('# Changed files:') - print(MINOR_DIV) - for file_ in file_list or (): - print('# {}'.format(file_)) - for package in sorted(get_changed_packages(file_list)): - yield package - else: - yield tagged_package - - -def main(): - print(MAJOR_DIV) - print('# Environment') - print(MINOR_DIV) - print('# CircleCI: {}'.format(CI)) - print('# CircleCI branch: {}'.format(CI_BRANCH)) - print('# CircleCI pr: {}'.format(CI_PR)) - print('# CircleCI tag: {}'.format(CIRCLE_TAG)) - print('# HEAD ref: {}'.format(head_hash)) - print('# {}'.format(head_name)) - print('# Git branch: {}'.format(rev_parse)) - print(MAJOR_DIV) - - packages = list(get_target_packages()) - - print(MAJOR_DIV) - print('# Target packages:') - print(MINOR_DIV) - for package in packages: - print(package) - print(MAJOR_DIV) - - -if __name__ == '__main__': - main() diff --git a/packages/google-cloud-translate/test_utils/scripts/get_target_packages_kokoro.py b/packages/google-cloud-translate/test_utils/scripts/get_target_packages_kokoro.py deleted file mode 100644 index 27d3a0c940ea..000000000000 --- a/packages/google-cloud-translate/test_utils/scripts/get_target_packages_kokoro.py +++ /dev/null @@ -1,98 +0,0 @@ -# Copyright 2017 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. - -"""Print a list of packages which require testing.""" - -import pathlib -import subprocess - -import ci_diff_helper -import requests - - -def print_environment(environment): - print("-> CI environment:") - print('Branch', environment.branch) - print('PR', environment.pr) - print('In PR', environment.in_pr) - print('Repo URL', environment.repo_url) - if environment.in_pr: - print('PR Base', environment.base) - - -def get_base(environment): - if environment.in_pr: - return environment.base - else: - # If we're not in a PR, just calculate the changes between this commit - # and its parent. - return 'HEAD~1' - - -def get_changed_files_from_base(base): - return subprocess.check_output([ - 'git', 'diff', '--name-only', f'{base}..HEAD', - ], stderr=subprocess.DEVNULL).decode('utf8').strip().split('\n') - - -_URL_TEMPLATE = ( - 'https://api.github.com/repos/googleapis/google-cloud-python/pulls/' - '{}/files' -) - - -def get_changed_files_from_pr(pr): - url = _URL_TEMPLATE.format(pr) - while url is not None: - response = requests.get(url) - for info in response.json(): - yield info['filename'] - url = response.links.get('next', {}).get('url') - - -def determine_changed_packages(changed_files): - packages = [ - path.parent for path in pathlib.Path('.').glob('*/noxfile.py') - ] - - changed_packages = set() - for file in changed_files: - file = pathlib.Path(file) - for package in packages: - if package in file.parents: - changed_packages.add(package) - - return changed_packages - - -def main(): - environment = ci_diff_helper.get_config() - print_environment(environment) - base = get_base(environment) - - if environment.in_pr: - changed_files = list(get_changed_files_from_pr(environment.pr)) - else: - changed_files = get_changed_files_from_base(base) - - packages = determine_changed_packages(changed_files) - - print(f"Comparing against {base}.") - print("-> Changed packages:") - - for package in packages: - print(package) - - -main() diff --git a/packages/google-cloud-translate/test_utils/scripts/run_emulator.py b/packages/google-cloud-translate/test_utils/scripts/run_emulator.py deleted file mode 100644 index 287b08640691..000000000000 --- a/packages/google-cloud-translate/test_utils/scripts/run_emulator.py +++ /dev/null @@ -1,199 +0,0 @@ -# Copyright 2016 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. - -"""Run system tests locally with the emulator. - -First makes system calls to spawn the emulator and get the local environment -variable needed for it. Then calls the system tests. -""" - - -import argparse -import os -import subprocess - -import psutil - -from google.cloud.environment_vars import BIGTABLE_EMULATOR -from google.cloud.environment_vars import GCD_DATASET -from google.cloud.environment_vars import GCD_HOST -from google.cloud.environment_vars import PUBSUB_EMULATOR -from run_system_test import run_module_tests - - -BIGTABLE = 'bigtable' -DATASTORE = 'datastore' -PUBSUB = 'pubsub' -PACKAGE_INFO = { - BIGTABLE: (BIGTABLE_EMULATOR,), - DATASTORE: (GCD_DATASET, GCD_HOST), - PUBSUB: (PUBSUB_EMULATOR,), -} -EXTRA = { - DATASTORE: ('--no-legacy',), -} -_DS_READY_LINE = '[datastore] Dev App Server is now running.\n' -_PS_READY_LINE_PREFIX = '[pubsub] INFO: Server started, listening on ' -_BT_READY_LINE_PREFIX = '[bigtable] Cloud Bigtable emulator running on ' - - -def get_parser(): - """Get simple ``argparse`` parser to determine package. - - :rtype: :class:`argparse.ArgumentParser` - :returns: The parser for this script. - """ - parser = argparse.ArgumentParser( - description='Run google-cloud system tests against local emulator.') - parser.add_argument('--package', dest='package', - choices=sorted(PACKAGE_INFO.keys()), - default=DATASTORE, help='Package to be tested.') - return parser - - -def get_start_command(package): - """Get command line arguments for starting emulator. - - :type package: str - :param package: The package to start an emulator for. - - :rtype: tuple - :returns: The arguments to be used, in a tuple. - """ - result = ('gcloud', 'beta', 'emulators', package, 'start') - extra = EXTRA.get(package, ()) - return result + extra - - -def get_env_init_command(package): - """Get command line arguments for getting emulator env. info. - - :type package: str - :param package: The package to get environment info for. - - :rtype: tuple - :returns: The arguments to be used, in a tuple. - """ - result = ('gcloud', 'beta', 'emulators', package, 'env-init') - extra = EXTRA.get(package, ()) - return result + extra - - -def datastore_wait_ready(popen): - """Wait until the datastore emulator is ready to use. - - :type popen: :class:`subprocess.Popen` - :param popen: An open subprocess to interact with. - """ - emulator_ready = False - while not emulator_ready: - emulator_ready = popen.stderr.readline() == _DS_READY_LINE - - -def wait_ready_prefix(popen, prefix): - """Wait until the a process encounters a line with matching prefix. - - :type popen: :class:`subprocess.Popen` - :param popen: An open subprocess to interact with. - - :type prefix: str - :param prefix: The prefix to match - """ - emulator_ready = False - while not emulator_ready: - emulator_ready = popen.stderr.readline().startswith(prefix) - - -def wait_ready(package, popen): - """Wait until the emulator is ready to use. - - :type package: str - :param package: The package to check if ready. - - :type popen: :class:`subprocess.Popen` - :param popen: An open subprocess to interact with. - - :raises: :class:`KeyError` if the ``package`` is not among - ``datastore``, ``pubsub`` or ``bigtable``. - """ - if package == DATASTORE: - datastore_wait_ready(popen) - elif package == PUBSUB: - wait_ready_prefix(popen, _PS_READY_LINE_PREFIX) - elif package == BIGTABLE: - wait_ready_prefix(popen, _BT_READY_LINE_PREFIX) - else: - raise KeyError('Package not supported', package) - - -def cleanup(pid): - """Cleanup a process (including all of its children). - - :type pid: int - :param pid: Process ID. - """ - proc = psutil.Process(pid) - for child_proc in proc.children(recursive=True): - try: - child_proc.kill() - child_proc.terminate() - except psutil.NoSuchProcess: - pass - proc.terminate() - proc.kill() - - -def run_tests_in_emulator(package): - """Spawn an emulator instance and run the system tests. - - :type package: str - :param package: The package to run system tests against. - """ - # Make sure this package has environment vars to replace. - env_vars = PACKAGE_INFO[package] - - start_command = get_start_command(package) - # Ignore stdin and stdout, don't pollute the user's output with them. - proc_start = subprocess.Popen(start_command, stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - try: - wait_ready(package, proc_start) - env_init_command = get_env_init_command(package) - proc_env = subprocess.Popen(env_init_command, stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - env_status = proc_env.wait() - if env_status != 0: - raise RuntimeError(env_status, proc_env.stderr.read()) - env_lines = proc_env.stdout.read().strip().split('\n') - # Set environment variables before running the system tests. - for env_var in env_vars: - line_prefix = 'export ' + env_var + '=' - value, = [line.split(line_prefix, 1)[1] for line in env_lines - if line.startswith(line_prefix)] - os.environ[env_var] = value - run_module_tests(package, - ignore_requirements=True) - finally: - cleanup(proc_start.pid) - - -def main(): - """Main method to run this script.""" - parser = get_parser() - args = parser.parse_args() - run_tests_in_emulator(args.package) - - -if __name__ == '__main__': - main() diff --git a/packages/google-cloud-translate/test_utils/scripts/update_docs.sh b/packages/google-cloud-translate/test_utils/scripts/update_docs.sh deleted file mode 100755 index 8cbab9f0dad0..000000000000 --- a/packages/google-cloud-translate/test_utils/scripts/update_docs.sh +++ /dev/null @@ -1,93 +0,0 @@ -#!/bin/bash - -# Copyright 2016 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. - -set -ev - -GH_OWNER='GoogleCloudPlatform' -GH_PROJECT_NAME='google-cloud-python' - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -# Function to build the docs. -function build_docs { - rm -rf docs/_build/ - rm -f docs/bigquery/generated/*.rst - # -W -> warnings as errors - # -T -> show full traceback on exception - # -N -> no color - sphinx-build \ - -W -T -N \ - -b html \ - -d docs/_build/doctrees \ - docs/ \ - docs/_build/html/ - return $? -} - -# Only update docs if we are on CircleCI. -if [[ "${CIRCLE_BRANCH}" == "master" ]] && [[ -z "${CIRCLE_PR_NUMBER}" ]]; then - echo "Building new docs on a merged commit." -elif [[ "$1" == "kokoro" ]]; then - echo "Building and publishing docs on Kokoro." -elif [[ -n "${CIRCLE_TAG}" ]]; then - echo "Building new docs on a tag (but will not deploy)." - build_docs - exit $? -else - echo "Not on master nor a release tag." - echo "Building new docs for testing purposes, but not deploying." - build_docs - exit $? -fi - -# Adding GitHub pages branch. `git submodule add` checks it -# out at HEAD. -GH_PAGES_DIR='ghpages' -git submodule add -q -b gh-pages \ - "git@github.com:${GH_OWNER}/${GH_PROJECT_NAME}" ${GH_PAGES_DIR} - -# Determine if we are building a new tag or are building docs -# for master. Then build new docs in docs/_build from master. -if [[ -n "${CIRCLE_TAG}" ]]; then - # Sphinx will use the package version by default. - build_docs -else - SPHINX_RELEASE=$(git log -1 --pretty=%h) build_docs -fi - -# Update gh-pages with the created docs. -cd ${GH_PAGES_DIR} -git rm -fr latest/ -cp -R ../docs/_build/html/ latest/ - -# Update the files push to gh-pages. -git add . -git status - -# If there are no changes, just exit cleanly. -if [[ -z "$(git status --porcelain)" ]]; then - echo "Nothing to commit. Exiting without pushing changes." - exit -fi - -# Commit to gh-pages branch to apply changes. -git config --global user.email "dpebot@google.com" -git config --global user.name "dpebot" -git commit -m "Update docs after merge to master." - -# NOTE: This may fail if two docs updates (on merges to master) -# happen in close proximity. -git push -q origin HEAD:gh-pages diff --git a/packages/google-cloud-translate/test_utils/setup.py b/packages/google-cloud-translate/test_utils/setup.py deleted file mode 100644 index 8e9222a7f862..000000000000 --- a/packages/google-cloud-translate/test_utils/setup.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright 2017 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 - -from setuptools import find_packages -from setuptools import setup - - -PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) - - -# NOTE: This is duplicated throughout and we should try to -# consolidate. -SETUP_BASE = { - 'author': 'Google Cloud Platform', - 'author_email': 'googleapis-publisher@google.com', - 'scripts': [], - 'url': 'https://github.com/GoogleCloudPlatform/google-cloud-python', - 'license': 'Apache 2.0', - 'platforms': 'Posix; MacOS X; Windows', - 'include_package_data': True, - 'zip_safe': False, - 'classifiers': [ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Apache Software License', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Topic :: Internet', - ], -} - - -REQUIREMENTS = [ - 'google-auth >= 0.4.0', - 'six', -] - -setup( - name='google-cloud-testutils', - version='0.24.0', - description='System test utilities for google-cloud-python', - packages=find_packages(), - install_requires=REQUIREMENTS, - python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*', - **SETUP_BASE -) diff --git a/packages/google-cloud-translate/test_utils/test_utils/__init__.py b/packages/google-cloud-translate/test_utils/test_utils/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/packages/google-cloud-translate/test_utils/test_utils/imports.py b/packages/google-cloud-translate/test_utils/test_utils/imports.py deleted file mode 100644 index 5991af7fc465..000000000000 --- a/packages/google-cloud-translate/test_utils/test_utils/imports.py +++ /dev/null @@ -1,38 +0,0 @@ -# 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. - -import mock -import six - - -def maybe_fail_import(predicate): - """Create and return a patcher that conditionally makes an import fail. - - Args: - predicate (Callable[[...], bool]): A callable that, if it returns `True`, - triggers an `ImportError`. It must accept the same arguments as the - built-in `__import__` function. - https://docs.python.org/3/library/functions.html#__import__ - - Returns: - A mock patcher object that can be used to enable patched import behavior. - """ - orig_import = six.moves.builtins.__import__ - - def custom_import(name, globals=None, locals=None, fromlist=(), level=0): - if predicate(name, globals, locals, fromlist, level): - raise ImportError - return orig_import(name, globals, locals, fromlist, level) - - return mock.patch.object(six.moves.builtins, "__import__", new=custom_import) diff --git a/packages/google-cloud-translate/test_utils/test_utils/retry.py b/packages/google-cloud-translate/test_utils/test_utils/retry.py deleted file mode 100644 index e61c001a03e1..000000000000 --- a/packages/google-cloud-translate/test_utils/test_utils/retry.py +++ /dev/null @@ -1,207 +0,0 @@ -# Copyright 2016 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 time -from functools import wraps - -import six - -MAX_TRIES = 4 -DELAY = 1 -BACKOFF = 2 - - -def _retry_all(_): - """Retry all caught exceptions.""" - return True - - -class BackoffFailed(Exception): - """Retry w/ backoffs did not complete successfully.""" - - -class RetryBase(object): - """Base for retrying calling a decorated function w/ exponential backoff. - - :type max_tries: int - :param max_tries: Number of times to try (not retry) before giving up. - - :type delay: int - :param delay: Initial delay between retries in seconds. - - :type backoff: int - :param backoff: Backoff multiplier e.g. value of 2 will double the - delay each retry. - - :type logger: logging.Logger instance - :param logger: Logger to use. If None, print. - """ - def __init__(self, max_tries=MAX_TRIES, delay=DELAY, backoff=BACKOFF, - logger=None): - self.max_tries = max_tries - self.delay = delay - self.backoff = backoff - self.logger = logger.warning if logger else six.print_ - - -class RetryErrors(RetryBase): - """Decorator for retrying given exceptions in testing. - - :type exception: Exception or tuple of Exceptions - :param exception: The exception to check or may be a tuple of - exceptions to check. - - :type error_predicate: function, takes caught exception, returns bool - :param error_predicate: Predicate evaluating whether to retry after a - caught exception. - - :type max_tries: int - :param max_tries: Number of times to try (not retry) before giving up. - - :type delay: int - :param delay: Initial delay between retries in seconds. - - :type backoff: int - :param backoff: Backoff multiplier e.g. value of 2 will double the - delay each retry. - - :type logger: logging.Logger instance - :param logger: Logger to use. If None, print. - """ - def __init__(self, exception, error_predicate=_retry_all, - max_tries=MAX_TRIES, delay=DELAY, backoff=BACKOFF, - logger=None): - super(RetryErrors, self).__init__(max_tries, delay, backoff, logger) - self.exception = exception - self.error_predicate = error_predicate - - def __call__(self, to_wrap): - @wraps(to_wrap) - def wrapped_function(*args, **kwargs): - tries = 0 - while tries < self.max_tries: - try: - return to_wrap(*args, **kwargs) - except self.exception as caught_exception: - - if not self.error_predicate(caught_exception): - raise - - delay = self.delay * self.backoff**tries - msg = ("%s, Trying again in %d seconds..." % - (caught_exception, delay)) - self.logger(msg) - - time.sleep(delay) - tries += 1 - return to_wrap(*args, **kwargs) - - return wrapped_function - - -class RetryResult(RetryBase): - """Decorator for retrying based on non-error result. - - :type result_predicate: function, takes result, returns bool - :param result_predicate: Predicate evaluating whether to retry after a - result is returned. - - :type max_tries: int - :param max_tries: Number of times to try (not retry) before giving up. - - :type delay: int - :param delay: Initial delay between retries in seconds. - - :type backoff: int - :param backoff: Backoff multiplier e.g. value of 2 will double the - delay each retry. - - :type logger: logging.Logger instance - :param logger: Logger to use. If None, print. - """ - def __init__(self, result_predicate, - max_tries=MAX_TRIES, delay=DELAY, backoff=BACKOFF, - logger=None): - super(RetryResult, self).__init__(max_tries, delay, backoff, logger) - self.result_predicate = result_predicate - - def __call__(self, to_wrap): - @wraps(to_wrap) - def wrapped_function(*args, **kwargs): - tries = 0 - while tries < self.max_tries: - result = to_wrap(*args, **kwargs) - if self.result_predicate(result): - return result - - delay = self.delay * self.backoff**tries - msg = "%s. Trying again in %d seconds..." % ( - self.result_predicate.__name__, delay,) - self.logger(msg) - - time.sleep(delay) - tries += 1 - raise BackoffFailed() - - return wrapped_function - - -class RetryInstanceState(RetryBase): - """Decorator for retrying based on instance state. - - :type instance_predicate: function, takes instance, returns bool - :param instance_predicate: Predicate evaluating whether to retry after an - API-invoking method is called. - - :type max_tries: int - :param max_tries: Number of times to try (not retry) before giving up. - - :type delay: int - :param delay: Initial delay between retries in seconds. - - :type backoff: int - :param backoff: Backoff multiplier e.g. value of 2 will double the - delay each retry. - - :type logger: logging.Logger instance - :param logger: Logger to use. If None, print. - """ - def __init__(self, instance_predicate, - max_tries=MAX_TRIES, delay=DELAY, backoff=BACKOFF, - logger=None): - super(RetryInstanceState, self).__init__( - max_tries, delay, backoff, logger) - self.instance_predicate = instance_predicate - - def __call__(self, to_wrap): - instance = to_wrap.__self__ # only instance methods allowed - - @wraps(to_wrap) - def wrapped_function(*args, **kwargs): - tries = 0 - while tries < self.max_tries: - result = to_wrap(*args, **kwargs) - if self.instance_predicate(instance): - return result - - delay = self.delay * self.backoff**tries - msg = "%s. Trying again in %d seconds..." % ( - self.instance_predicate.__name__, delay,) - self.logger(msg) - - time.sleep(delay) - tries += 1 - raise BackoffFailed() - - return wrapped_function diff --git a/packages/google-cloud-translate/test_utils/test_utils/system.py b/packages/google-cloud-translate/test_utils/test_utils/system.py deleted file mode 100644 index 590dc62a06e6..000000000000 --- a/packages/google-cloud-translate/test_utils/test_utils/system.py +++ /dev/null @@ -1,81 +0,0 @@ -# Copyright 2014 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 os -import sys -import time - -import google.auth.credentials -from google.auth.environment_vars import CREDENTIALS as TEST_CREDENTIALS - - -# From shell environ. May be None. -CREDENTIALS = os.getenv(TEST_CREDENTIALS) - -ENVIRON_ERROR_MSG = """\ -To run the system tests, you need to set some environment variables. -Please check the CONTRIBUTING guide for instructions. -""" - - -class EmulatorCreds(google.auth.credentials.Credentials): - """A mock credential object. - - Used to avoid unnecessary token refreshing or reliance on the network - while an emulator is running. - """ - - def __init__(self): # pylint: disable=super-init-not-called - self.token = b'seekrit' - self.expiry = None - - @property - def valid(self): - """Would-be validity check of the credentials. - - Always is :data:`True`. - """ - return True - - def refresh(self, unused_request): # pylint: disable=unused-argument - """Off-limits implementation for abstract method.""" - raise RuntimeError('Should never be refreshed.') - - -def check_environ(): - err_msg = None - if CREDENTIALS is None: - err_msg = '\nMissing variables: ' + TEST_CREDENTIALS - elif not os.path.isfile(CREDENTIALS): - err_msg = '\nThe %s path %r is not a file.' % (TEST_CREDENTIALS, - CREDENTIALS) - - if err_msg is not None: - msg = ENVIRON_ERROR_MSG + err_msg - print(msg, file=sys.stderr) - sys.exit(1) - - -def unique_resource_id(delimiter='_'): - """A unique identifier for a resource. - - Intended to help locate resources created in particular - testing environments and at particular times. - """ - build_id = os.getenv('CIRCLE_BUILD_NUM', '') - if build_id == '': - return '%s%d' % (delimiter, 1000 * time.time()) - else: - return '%s%s%s%d' % (delimiter, build_id, delimiter, time.time()) diff --git a/packages/google-cloud-translate/test_utils/test_utils/vpcsc_config.py b/packages/google-cloud-translate/test_utils/test_utils/vpcsc_config.py deleted file mode 100644 index 36b15d6be991..000000000000 --- a/packages/google-cloud-translate/test_utils/test_utils/vpcsc_config.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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 pytest - - -INSIDE_VPCSC_ENVVAR = "GOOGLE_CLOUD_TESTS_IN_VPCSC" -PROJECT_INSIDE_ENVVAR = "PROJECT_ID" -PROJECT_OUTSIDE_ENVVAR = "GOOGLE_CLOUD_TESTS_VPCSC_OUTSIDE_PERIMETER_PROJECT" -BUCKET_OUTSIDE_ENVVAR = "GOOGLE_CLOUD_TESTS_VPCSC_OUTSIDE_PERIMETER_BUCKET" - - -class VPCSCTestConfig(object): - """System test utility for VPCSC detection. - - See: https://cloud.google.com/vpc-service-controls/docs/ - """ - - @property - def inside_vpcsc(self): - """Test whether the test environment is configured to run inside VPCSC. - - Returns: - bool: - true if the environment is configured to run inside VPCSC, - else false. - """ - return INSIDE_VPCSC_ENVVAR in os.environ - - @property - def project_inside(self): - """Project ID for testing outside access. - - Returns: - str: project ID used for testing outside access; None if undefined. - """ - return os.environ.get(PROJECT_INSIDE_ENVVAR, None) - - @property - def project_outside(self): - """Project ID for testing inside access. - - Returns: - str: project ID used for testing inside access; None if undefined. - """ - return os.environ.get(PROJECT_OUTSIDE_ENVVAR, None) - - @property - def bucket_outside(self): - """GCS bucket for testing inside access. - - Returns: - str: bucket ID used for testing inside access; None if undefined. - """ - return os.environ.get(BUCKET_OUTSIDE_ENVVAR, None) - - def skip_if_inside_vpcsc(self, testcase): - """Test decorator: skip if running inside VPCSC.""" - reason = ( - "Running inside VPCSC. " - "Unset the {} environment variable to enable this test." - ).format(INSIDE_VPCSC_ENVVAR) - skip = pytest.mark.skipif(self.inside_vpcsc, reason=reason) - return skip(testcase) - - def skip_unless_inside_vpcsc(self, testcase): - """Test decorator: skip if running outside VPCSC.""" - reason = ( - "Running outside VPCSC. " - "Set the {} environment variable to enable this test." - ).format(INSIDE_VPCSC_ENVVAR) - skip = pytest.mark.skipif(not self.inside_vpcsc, reason=reason) - return skip(testcase) - - def skip_unless_inside_project(self, testcase): - """Test decorator: skip if inside project env var not set.""" - reason = ( - "Project ID for running inside VPCSC not set. " - "Set the {} environment variable to enable this test." - ).format(PROJECT_INSIDE_ENVVAR) - skip = pytest.mark.skipif(self.project_inside is None, reason=reason) - return skip(testcase) - - def skip_unless_outside_project(self, testcase): - """Test decorator: skip if outside project env var not set.""" - reason = ( - "Project ID for running outside VPCSC not set. " - "Set the {} environment variable to enable this test." - ).format(PROJECT_OUTSIDE_ENVVAR) - skip = pytest.mark.skipif(self.project_outside is None, reason=reason) - return skip(testcase) - - def skip_unless_outside_bucket(self, testcase): - """Test decorator: skip if outside bucket env var not set.""" - reason = ( - "Bucket ID for running outside VPCSC not set. " - "Set the {} environment variable to enable this test." - ).format(BUCKET_OUTSIDE_ENVVAR) - skip = pytest.mark.skipif(self.bucket_outside is None, reason=reason) - return skip(testcase) - - -vpcsc_config = VPCSCTestConfig() diff --git a/packages/google-cloud-translate/tests/system.py b/packages/google-cloud-translate/tests/system.py index 975d3a223602..56b16091e63b 100644 --- a/packages/google-cloud-translate/tests/system.py +++ b/packages/google-cloud-translate/tests/system.py @@ -14,9 +14,11 @@ # limitations under the License. +import os import unittest from google.cloud import translate_v2 +from google.cloud import translate class Config(object): @@ -26,16 +28,20 @@ class Config(object): global state. """ - CLIENT = None + CLIENT_V2 = None + CLIENT_V3 = None + location = "global" + project_id = os.environ["PROJECT_ID"] def setUpModule(): - Config.CLIENT = translate_v2.Client() + Config.CLIENT_V2 = translate_v2.Client() + Config.CLIENT_V3 = translate.TranslationServiceClient() class TestTranslate(unittest.TestCase): def test_get_languages(self): - result = Config.CLIENT.get_languages() + result = Config.CLIENT_V2.get_languages() # There are **many** more than 10 languages. self.assertGreater(len(result), 10) @@ -46,8 +52,8 @@ def test_get_languages(self): self.assertEqual(lang_map["zu"], "Zulu") def test_detect_language(self): - values = ["takoy", u"fa\xe7ade", "s'il vous plait"] - detections = Config.CLIENT.detect_language(values) + values = ["takoy", "fa\xe7ade", "s'il vous plait"] + detections = Config.CLIENT_V2.detect_language(values) self.assertEqual(len(values), len(detections)) self.assertEqual(detections[0]["language"], "ru") self.assertEqual(detections[1]["language"], "fr") @@ -55,25 +61,72 @@ def test_detect_language(self): def test_translate(self): values = ["petnaest", "dek kvin", "Me llamo Jeff", "My name is Jeff"] - translations = Config.CLIENT.translate( + translations = Config.CLIENT_V2.translate( values, target_language="de", model="nmt" ) self.assertEqual(len(values), len(translations)) self.assertEqual(translations[0]["detectedSourceLanguage"].lower(), "hr") - self.assertEqual(translations[0]["translatedText"].lower(), u"fünfzehn") + self.assertEqual(translations[0]["translatedText"].lower(), "fünfzehn") self.assertEqual(translations[1]["detectedSourceLanguage"], "eo") - self.assertEqual(translations[1]["translatedText"].lower(), u"fünfzehn") + self.assertEqual(translations[1]["translatedText"].lower(), "fünfzehn") self.assertEqual(translations[2]["detectedSourceLanguage"], "es") es_translation = translations[2]["translatedText"].lower() self.assertTrue( - es_translation == u"ich heiße jeff" - or es_translation == u"mein name ist jeff" + es_translation == "ich heiße jeff" or es_translation == "mein name ist jeff" ) self.assertEqual(translations[3]["detectedSourceLanguage"], "en") self.assertEqual( translations[3]["translatedText"].lower(), "mein name ist jeff" ) + + def test_get_languages_v3(self): + parent = f"projects/{Config.project_id}/locations/{Config.location}" + result = Config.CLIENT_V3.get_supported_languages(parent=parent) + languages = [lang.language_code for lang in result.languages] + self.assertGreater( + len(languages), 10 + ) # There are **many** more than 10 languages. + self.assertIn("zu", languages) # Zulu is supported + self.assertIn("fr", languages) # English is supported + self.assertIn("ga", languages) # Irish is supported + + def test_detect_language_v3(self): + parent = f"projects/{Config.project_id}/locations/{Config.location}" + value = "s'il vous plait" + response = Config.CLIENT_V3.detect_language( + request={"parent": parent, "content": value, "mime_type": "text/plain"} + ) + languages = [detection.language_code for detection in response.languages] + self.assertEqual(languages[0], "fr") + + def test_translate_v3(self): + parent = f"projects/{Config.project_id}/locations/{Config.location}" + values = ["petnaest", "dek kvin", "Me llamo Jeff", "My name is Jeff"] + translations = Config.CLIENT_V3.translate_text( + parent=parent, contents=values, target_language_code="de" + ) + + results_map = { + result.detected_language_code: result.translated_text + for result in translations.translations + } + self.assertEqual(len(values), len(results_map)) + + self.assertIn("hr", results_map.keys()) + self.assertIn("eo", results_map.keys()) + self.assertIn("es", results_map.keys()) + self.assertIn("en", results_map.keys()) + + self.assertEqual(results_map["hr"].lower(), "fünfzehn") + self.assertEqual(results_map["eo"].lower(), "fünfzehn") + + es_translation = results_map["es"].lower() + self.assertTrue( + es_translation == "ich heiße jeff" or es_translation == "mein name ist jeff" + ) + + self.assertEqual(results_map["en"].lower(), "mein name ist jeff") diff --git a/packages/google-cloud-translate/tests/unit/gapic/translate_v3/__init__.py b/packages/google-cloud-translate/tests/unit/gapic/translate_v3/__init__.py new file mode 100644 index 000000000000..8b137891791f --- /dev/null +++ b/packages/google-cloud-translate/tests/unit/gapic/translate_v3/__init__.py @@ -0,0 +1 @@ + diff --git a/packages/google-cloud-translate/tests/unit/gapic/translate_v3/test_translation_service.py b/packages/google-cloud-translate/tests/unit/gapic/translate_v3/test_translation_service.py new file mode 100644 index 000000000000..556a93a2584e --- /dev/null +++ b/packages/google-cloud-translate/tests/unit/gapic/translate_v3/test_translation_service.py @@ -0,0 +1,2543 @@ +# -*- coding: utf-8 -*- + +# 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 mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.translate_v3.services.translation_service import ( + TranslationServiceAsyncClient, +) +from google.cloud.translate_v3.services.translation_service import ( + TranslationServiceClient, +) +from google.cloud.translate_v3.services.translation_service import pagers +from google.cloud.translate_v3.services.translation_service import transports +from google.cloud.translate_v3.types import translation_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert TranslationServiceClient._get_default_mtls_endpoint(None) is None + assert ( + TranslationServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + TranslationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + TranslationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + TranslationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + TranslationServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [TranslationServiceClient, TranslationServiceAsyncClient] +) +def test_translation_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "translate.googleapis.com:443" + + +def test_translation_service_client_get_transport_class(): + transport = TranslationServiceClient.get_transport_class() + assert transport == transports.TranslationServiceGrpcTransport + + transport = TranslationServiceClient.get_transport_class("grpc") + assert transport == transports.TranslationServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TranslationServiceClient, transports.TranslationServiceGrpcTransport, "grpc"), + ( + TranslationServiceAsyncClient, + transports.TranslationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + TranslationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TranslationServiceClient), +) +@mock.patch.object( + TranslationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TranslationServiceAsyncClient), +) +def test_translation_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(TranslationServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(TranslationServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TranslationServiceClient, transports.TranslationServiceGrpcTransport, "grpc"), + ( + TranslationServiceAsyncClient, + transports.TranslationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_translation_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TranslationServiceClient, transports.TranslationServiceGrpcTransport, "grpc"), + ( + TranslationServiceAsyncClient, + transports.TranslationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_translation_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_translation_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.translate_v3.services.translation_service.transports.TranslationServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = TranslationServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_translate_text( + transport: str = "grpc", request_type=translation_service.TranslateTextRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.translate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.TranslateTextResponse() + + response = client.translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.TranslateTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.TranslateTextResponse) + + +def test_translate_text_from_dict(): + test_translate_text(request_type=dict) + + +@pytest.mark.asyncio +async def test_translate_text_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.TranslateTextRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.translate_text), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.TranslateTextResponse() + ) + + response = await client.translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.TranslateTextResponse) + + +def test_translate_text_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.TranslateTextRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.translate_text), "__call__") as call: + call.return_value = translation_service.TranslateTextResponse() + + client.translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_translate_text_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.TranslateTextRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.translate_text), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.TranslateTextResponse() + ) + + await client.translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_translate_text_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.translate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.TranslateTextResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.translate_text( + parent="parent_value", + target_language_code="target_language_code_value", + contents=["contents_value"], + model="model_value", + mime_type="mime_type_value", + source_language_code="source_language_code_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].target_language_code == "target_language_code_value" + + assert args[0].contents == ["contents_value"] + + assert args[0].model == "model_value" + + assert args[0].mime_type == "mime_type_value" + + assert args[0].source_language_code == "source_language_code_value" + + +def test_translate_text_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.translate_text( + translation_service.TranslateTextRequest(), + parent="parent_value", + target_language_code="target_language_code_value", + contents=["contents_value"], + model="model_value", + mime_type="mime_type_value", + source_language_code="source_language_code_value", + ) + + +@pytest.mark.asyncio +async def test_translate_text_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.translate_text), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.TranslateTextResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.TranslateTextResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.translate_text( + parent="parent_value", + target_language_code="target_language_code_value", + contents=["contents_value"], + model="model_value", + mime_type="mime_type_value", + source_language_code="source_language_code_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].target_language_code == "target_language_code_value" + + assert args[0].contents == ["contents_value"] + + assert args[0].model == "model_value" + + assert args[0].mime_type == "mime_type_value" + + assert args[0].source_language_code == "source_language_code_value" + + +@pytest.mark.asyncio +async def test_translate_text_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.translate_text( + translation_service.TranslateTextRequest(), + parent="parent_value", + target_language_code="target_language_code_value", + contents=["contents_value"], + model="model_value", + mime_type="mime_type_value", + source_language_code="source_language_code_value", + ) + + +def test_detect_language( + transport: str = "grpc", request_type=translation_service.DetectLanguageRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.detect_language), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.DetectLanguageResponse() + + response = client.detect_language(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.DetectLanguageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.DetectLanguageResponse) + + +def test_detect_language_from_dict(): + test_detect_language(request_type=dict) + + +@pytest.mark.asyncio +async def test_detect_language_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.DetectLanguageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.detect_language), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.DetectLanguageResponse() + ) + + response = await client.detect_language(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.DetectLanguageResponse) + + +def test_detect_language_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.DetectLanguageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.detect_language), "__call__") as call: + call.return_value = translation_service.DetectLanguageResponse() + + client.detect_language(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_detect_language_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.DetectLanguageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.detect_language), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.DetectLanguageResponse() + ) + + await client.detect_language(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_detect_language_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.detect_language), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.DetectLanguageResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.detect_language( + parent="parent_value", + model="model_value", + mime_type="mime_type_value", + content="content_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].model == "model_value" + + assert args[0].mime_type == "mime_type_value" + + assert args[0].content == "content_value" + + +def test_detect_language_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.detect_language( + translation_service.DetectLanguageRequest(), + parent="parent_value", + model="model_value", + mime_type="mime_type_value", + content="content_value", + ) + + +@pytest.mark.asyncio +async def test_detect_language_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.detect_language), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.DetectLanguageResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.DetectLanguageResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.detect_language( + parent="parent_value", + model="model_value", + mime_type="mime_type_value", + content="content_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].model == "model_value" + + assert args[0].mime_type == "mime_type_value" + + assert args[0].content == "content_value" + + +@pytest.mark.asyncio +async def test_detect_language_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.detect_language( + translation_service.DetectLanguageRequest(), + parent="parent_value", + model="model_value", + mime_type="mime_type_value", + content="content_value", + ) + + +def test_get_supported_languages( + transport: str = "grpc", + request_type=translation_service.GetSupportedLanguagesRequest, +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_supported_languages), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.SupportedLanguages() + + response = client.get_supported_languages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.GetSupportedLanguagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.SupportedLanguages) + + +def test_get_supported_languages_from_dict(): + test_get_supported_languages(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_supported_languages_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.GetSupportedLanguagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_supported_languages), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.SupportedLanguages() + ) + + response = await client.get_supported_languages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.SupportedLanguages) + + +def test_get_supported_languages_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.GetSupportedLanguagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_supported_languages), "__call__" + ) as call: + call.return_value = translation_service.SupportedLanguages() + + client.get_supported_languages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_supported_languages_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.GetSupportedLanguagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_supported_languages), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.SupportedLanguages() + ) + + await client.get_supported_languages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_get_supported_languages_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_supported_languages), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.SupportedLanguages() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_supported_languages( + parent="parent_value", + model="model_value", + display_language_code="display_language_code_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].model == "model_value" + + assert args[0].display_language_code == "display_language_code_value" + + +def test_get_supported_languages_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_supported_languages( + translation_service.GetSupportedLanguagesRequest(), + parent="parent_value", + model="model_value", + display_language_code="display_language_code_value", + ) + + +@pytest.mark.asyncio +async def test_get_supported_languages_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_supported_languages), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.SupportedLanguages() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.SupportedLanguages() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_supported_languages( + parent="parent_value", + model="model_value", + display_language_code="display_language_code_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].model == "model_value" + + assert args[0].display_language_code == "display_language_code_value" + + +@pytest.mark.asyncio +async def test_get_supported_languages_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_supported_languages( + translation_service.GetSupportedLanguagesRequest(), + parent="parent_value", + model="model_value", + display_language_code="display_language_code_value", + ) + + +def test_batch_translate_text( + transport: str = "grpc", request_type=translation_service.BatchTranslateTextRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_translate_text), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.batch_translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.BatchTranslateTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_translate_text_from_dict(): + test_batch_translate_text(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_translate_text_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.BatchTranslateTextRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_translate_text), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.batch_translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_translate_text_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.BatchTranslateTextRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_translate_text), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.batch_translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_translate_text_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.BatchTranslateTextRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_translate_text), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.batch_translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_glossary( + transport: str = "grpc", request_type=translation_service.CreateGlossaryRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.create_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.CreateGlossaryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_glossary_from_dict(): + test_create_glossary(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_glossary_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.CreateGlossaryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.create_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_glossary_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.CreateGlossaryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_glossary), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.create_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_glossary_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.CreateGlossaryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_glossary), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.create_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_glossary_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_glossary( + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].glossary == translation_service.Glossary(name="name_value") + + +def test_create_glossary_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_glossary( + translation_service.CreateGlossaryRequest(), + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_glossary_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_glossary( + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].glossary == translation_service.Glossary(name="name_value") + + +@pytest.mark.asyncio +async def test_create_glossary_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_glossary( + translation_service.CreateGlossaryRequest(), + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + +def test_list_glossaries( + transport: str = "grpc", request_type=translation_service.ListGlossariesRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.ListGlossariesResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_glossaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.ListGlossariesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGlossariesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_glossaries_from_dict(): + test_list_glossaries(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_glossaries_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.ListGlossariesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.ListGlossariesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_glossaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGlossariesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_glossaries_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.ListGlossariesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + call.return_value = translation_service.ListGlossariesResponse() + + client.list_glossaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_glossaries_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.ListGlossariesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.ListGlossariesResponse() + ) + + await client.list_glossaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_glossaries_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.ListGlossariesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_glossaries(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_glossaries_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_glossaries( + translation_service.ListGlossariesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_glossaries_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.ListGlossariesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.ListGlossariesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_glossaries(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_glossaries_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_glossaries( + translation_service.ListGlossariesRequest(), parent="parent_value", + ) + + +def test_list_glossaries_pager(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[translation_service.Glossary(),], next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_glossaries(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, translation_service.Glossary) for i in results) + + +def test_list_glossaries_pages(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[translation_service.Glossary(),], next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + RuntimeError, + ) + pages = list(client.list_glossaries(request={}).pages) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_glossaries_async_pager(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[translation_service.Glossary(),], next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_glossaries(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, translation_service.Glossary) for i in responses) + + +@pytest.mark.asyncio +async def test_list_glossaries_async_pages(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[translation_service.Glossary(),], next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + RuntimeError, + ) + pages = [] + async for page in (await client.list_glossaries(request={})).pages: + pages.append(page) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +def test_get_glossary( + transport: str = "grpc", request_type=translation_service.GetGlossaryRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.Glossary( + name="name_value", + entry_count=1210, + language_pair=translation_service.Glossary.LanguageCodePair( + source_language_code="source_language_code_value" + ), + ) + + response = client.get_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.GetGlossaryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.Glossary) + + assert response.name == "name_value" + + assert response.entry_count == 1210 + + +def test_get_glossary_from_dict(): + test_get_glossary(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_glossary_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.GetGlossaryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.Glossary(name="name_value", entry_count=1210,) + ) + + response = await client.get_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.Glossary) + + assert response.name == "name_value" + + assert response.entry_count == 1210 + + +def test_get_glossary_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.GetGlossaryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_glossary), "__call__") as call: + call.return_value = translation_service.Glossary() + + client.get_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_glossary_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.GetGlossaryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_glossary), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.Glossary() + ) + + await client.get_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_glossary_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.Glossary() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_glossary(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_glossary_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_glossary( + translation_service.GetGlossaryRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_glossary_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.Glossary() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.Glossary() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_glossary(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_glossary_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_glossary( + translation_service.GetGlossaryRequest(), name="name_value", + ) + + +def test_delete_glossary( + transport: str = "grpc", request_type=translation_service.DeleteGlossaryRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.delete_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.DeleteGlossaryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_glossary_from_dict(): + test_delete_glossary(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_glossary_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.DeleteGlossaryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.delete_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_glossary_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.DeleteGlossaryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_glossary), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.delete_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_glossary_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.DeleteGlossaryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_glossary), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.delete_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_glossary_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_glossary(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_glossary_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_glossary( + translation_service.DeleteGlossaryRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_glossary_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_glossary(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_glossary_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_glossary( + translation_service.DeleteGlossaryRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = TranslationServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TranslationServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.TranslationServiceGrpcTransport,) + + +def test_translation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.TranslationServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_translation_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.translate_v3.services.translation_service.transports.TranslationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.TranslationServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "translate_text", + "detect_language", + "get_supported_languages", + "batch_translate_text", + "create_glossary", + "list_glossaries", + "get_glossary", + "delete_glossary", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_translation_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.translate_v3.services.translation_service.transports.TranslationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.TranslationServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id="octopus", + ) + + +def test_translation_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + TranslationServiceClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id=None, + ) + + +def test_translation_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.TranslationServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id="octopus", + ) + + +def test_translation_service_host_no_port(): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="translate.googleapis.com" + ), + ) + assert client._transport._host == "translate.googleapis.com:443" + + +def test_translation_service_host_with_port(): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="translate.googleapis.com:8000" + ), + ) + assert client._transport._host == "translate.googleapis.com:8000" + + +def test_translation_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.TranslationServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_translation_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.TranslationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_translation_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.TranslationServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_translation_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.TranslationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_translation_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.TranslationServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_translation_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.TranslationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_translation_service_grpc_lro_client(): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_translation_service_grpc_lro_async_client(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_glossary_path(): + project = "squid" + location = "clam" + glossary = "whelk" + + expected = "projects/{project}/locations/{location}/glossaries/{glossary}".format( + project=project, location=location, glossary=glossary, + ) + actual = TranslationServiceClient.glossary_path(project, location, glossary) + assert expected == actual + + +def test_parse_glossary_path(): + expected = { + "project": "octopus", + "location": "oyster", + "glossary": "nudibranch", + } + path = TranslationServiceClient.glossary_path(**expected) + + # Check that the path construction is reversible. + actual = TranslationServiceClient.parse_glossary_path(path) + assert expected == actual diff --git a/packages/google-cloud-translate/tests/unit/gapic/translate_v3beta1/__init__.py b/packages/google-cloud-translate/tests/unit/gapic/translate_v3beta1/__init__.py new file mode 100644 index 000000000000..8b137891791f --- /dev/null +++ b/packages/google-cloud-translate/tests/unit/gapic/translate_v3beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/packages/google-cloud-translate/tests/unit/gapic/translate_v3beta1/test_translation_service.py b/packages/google-cloud-translate/tests/unit/gapic/translate_v3beta1/test_translation_service.py new file mode 100644 index 000000000000..1dd49ee11392 --- /dev/null +++ b/packages/google-cloud-translate/tests/unit/gapic/translate_v3beta1/test_translation_service.py @@ -0,0 +1,2424 @@ +# -*- coding: utf-8 -*- + +# 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 mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.translate_v3beta1.services.translation_service import ( + TranslationServiceAsyncClient, +) +from google.cloud.translate_v3beta1.services.translation_service import ( + TranslationServiceClient, +) +from google.cloud.translate_v3beta1.services.translation_service import pagers +from google.cloud.translate_v3beta1.services.translation_service import transports +from google.cloud.translate_v3beta1.types import translation_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert TranslationServiceClient._get_default_mtls_endpoint(None) is None + assert ( + TranslationServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + TranslationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + TranslationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + TranslationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + TranslationServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [TranslationServiceClient, TranslationServiceAsyncClient] +) +def test_translation_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "translate.googleapis.com:443" + + +def test_translation_service_client_get_transport_class(): + transport = TranslationServiceClient.get_transport_class() + assert transport == transports.TranslationServiceGrpcTransport + + transport = TranslationServiceClient.get_transport_class("grpc") + assert transport == transports.TranslationServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TranslationServiceClient, transports.TranslationServiceGrpcTransport, "grpc"), + ( + TranslationServiceAsyncClient, + transports.TranslationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + TranslationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TranslationServiceClient), +) +@mock.patch.object( + TranslationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TranslationServiceAsyncClient), +) +def test_translation_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(TranslationServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(TranslationServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TranslationServiceClient, transports.TranslationServiceGrpcTransport, "grpc"), + ( + TranslationServiceAsyncClient, + transports.TranslationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_translation_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TranslationServiceClient, transports.TranslationServiceGrpcTransport, "grpc"), + ( + TranslationServiceAsyncClient, + transports.TranslationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_translation_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_translation_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = TranslationServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_translate_text( + transport: str = "grpc", request_type=translation_service.TranslateTextRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.translate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.TranslateTextResponse() + + response = client.translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.TranslateTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.TranslateTextResponse) + + +def test_translate_text_from_dict(): + test_translate_text(request_type=dict) + + +@pytest.mark.asyncio +async def test_translate_text_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.TranslateTextRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.translate_text), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.TranslateTextResponse() + ) + + response = await client.translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.TranslateTextResponse) + + +def test_translate_text_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.TranslateTextRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.translate_text), "__call__") as call: + call.return_value = translation_service.TranslateTextResponse() + + client.translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_translate_text_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.TranslateTextRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.translate_text), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.TranslateTextResponse() + ) + + await client.translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_detect_language( + transport: str = "grpc", request_type=translation_service.DetectLanguageRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.detect_language), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.DetectLanguageResponse() + + response = client.detect_language(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.DetectLanguageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.DetectLanguageResponse) + + +def test_detect_language_from_dict(): + test_detect_language(request_type=dict) + + +@pytest.mark.asyncio +async def test_detect_language_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.DetectLanguageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.detect_language), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.DetectLanguageResponse() + ) + + response = await client.detect_language(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.DetectLanguageResponse) + + +def test_detect_language_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.DetectLanguageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.detect_language), "__call__") as call: + call.return_value = translation_service.DetectLanguageResponse() + + client.detect_language(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_detect_language_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.DetectLanguageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.detect_language), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.DetectLanguageResponse() + ) + + await client.detect_language(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_detect_language_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.detect_language), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.DetectLanguageResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.detect_language( + parent="parent_value", model="model_value", mime_type="mime_type_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].model == "model_value" + + assert args[0].mime_type == "mime_type_value" + + +def test_detect_language_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.detect_language( + translation_service.DetectLanguageRequest(), + parent="parent_value", + model="model_value", + mime_type="mime_type_value", + ) + + +@pytest.mark.asyncio +async def test_detect_language_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.detect_language), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.DetectLanguageResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.DetectLanguageResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.detect_language( + parent="parent_value", model="model_value", mime_type="mime_type_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].model == "model_value" + + assert args[0].mime_type == "mime_type_value" + + +@pytest.mark.asyncio +async def test_detect_language_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.detect_language( + translation_service.DetectLanguageRequest(), + parent="parent_value", + model="model_value", + mime_type="mime_type_value", + ) + + +def test_get_supported_languages( + transport: str = "grpc", + request_type=translation_service.GetSupportedLanguagesRequest, +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_supported_languages), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.SupportedLanguages() + + response = client.get_supported_languages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.GetSupportedLanguagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.SupportedLanguages) + + +def test_get_supported_languages_from_dict(): + test_get_supported_languages(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_supported_languages_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.GetSupportedLanguagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_supported_languages), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.SupportedLanguages() + ) + + response = await client.get_supported_languages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.SupportedLanguages) + + +def test_get_supported_languages_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.GetSupportedLanguagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_supported_languages), "__call__" + ) as call: + call.return_value = translation_service.SupportedLanguages() + + client.get_supported_languages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_supported_languages_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.GetSupportedLanguagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_supported_languages), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.SupportedLanguages() + ) + + await client.get_supported_languages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_get_supported_languages_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_supported_languages), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.SupportedLanguages() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_supported_languages( + parent="parent_value", + display_language_code="display_language_code_value", + model="model_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].display_language_code == "display_language_code_value" + + assert args[0].model == "model_value" + + +def test_get_supported_languages_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_supported_languages( + translation_service.GetSupportedLanguagesRequest(), + parent="parent_value", + display_language_code="display_language_code_value", + model="model_value", + ) + + +@pytest.mark.asyncio +async def test_get_supported_languages_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_supported_languages), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.SupportedLanguages() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.SupportedLanguages() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_supported_languages( + parent="parent_value", + display_language_code="display_language_code_value", + model="model_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].display_language_code == "display_language_code_value" + + assert args[0].model == "model_value" + + +@pytest.mark.asyncio +async def test_get_supported_languages_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_supported_languages( + translation_service.GetSupportedLanguagesRequest(), + parent="parent_value", + display_language_code="display_language_code_value", + model="model_value", + ) + + +def test_batch_translate_text( + transport: str = "grpc", request_type=translation_service.BatchTranslateTextRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_translate_text), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.batch_translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.BatchTranslateTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_translate_text_from_dict(): + test_batch_translate_text(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_translate_text_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.BatchTranslateTextRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_translate_text), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.batch_translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_translate_text_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.BatchTranslateTextRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_translate_text), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.batch_translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_translate_text_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.BatchTranslateTextRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_translate_text), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.batch_translate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_glossary( + transport: str = "grpc", request_type=translation_service.CreateGlossaryRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.create_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.CreateGlossaryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_glossary_from_dict(): + test_create_glossary(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_glossary_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.CreateGlossaryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.create_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_glossary_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.CreateGlossaryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_glossary), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.create_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_glossary_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.CreateGlossaryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_glossary), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.create_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_glossary_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_glossary( + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].glossary == translation_service.Glossary(name="name_value") + + +def test_create_glossary_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_glossary( + translation_service.CreateGlossaryRequest(), + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_glossary_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_glossary( + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].glossary == translation_service.Glossary(name="name_value") + + +@pytest.mark.asyncio +async def test_create_glossary_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_glossary( + translation_service.CreateGlossaryRequest(), + parent="parent_value", + glossary=translation_service.Glossary(name="name_value"), + ) + + +def test_list_glossaries( + transport: str = "grpc", request_type=translation_service.ListGlossariesRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.ListGlossariesResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_glossaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.ListGlossariesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGlossariesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_glossaries_from_dict(): + test_list_glossaries(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_glossaries_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.ListGlossariesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.ListGlossariesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_glossaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGlossariesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_glossaries_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.ListGlossariesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + call.return_value = translation_service.ListGlossariesResponse() + + client.list_glossaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_glossaries_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.ListGlossariesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.ListGlossariesResponse() + ) + + await client.list_glossaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_glossaries_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.ListGlossariesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_glossaries( + parent="parent_value", filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].filter == "filter_value" + + +def test_list_glossaries_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_glossaries( + translation_service.ListGlossariesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +@pytest.mark.asyncio +async def test_list_glossaries_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.ListGlossariesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.ListGlossariesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_glossaries( + parent="parent_value", filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].filter == "filter_value" + + +@pytest.mark.asyncio +async def test_list_glossaries_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_glossaries( + translation_service.ListGlossariesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_glossaries_pager(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[translation_service.Glossary(),], next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_glossaries(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, translation_service.Glossary) for i in results) + + +def test_list_glossaries_pages(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_glossaries), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[translation_service.Glossary(),], next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + RuntimeError, + ) + pages = list(client.list_glossaries(request={}).pages) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_glossaries_async_pager(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[translation_service.Glossary(),], next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_glossaries(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, translation_service.Glossary) for i in responses) + + +@pytest.mark.asyncio +async def test_list_glossaries_async_pages(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_glossaries), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + translation_service.Glossary(), + ], + next_page_token="abc", + ), + translation_service.ListGlossariesResponse( + glossaries=[], next_page_token="def", + ), + translation_service.ListGlossariesResponse( + glossaries=[translation_service.Glossary(),], next_page_token="ghi", + ), + translation_service.ListGlossariesResponse( + glossaries=[ + translation_service.Glossary(), + translation_service.Glossary(), + ], + ), + RuntimeError, + ) + pages = [] + async for page in (await client.list_glossaries(request={})).pages: + pages.append(page) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +def test_get_glossary( + transport: str = "grpc", request_type=translation_service.GetGlossaryRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.Glossary( + name="name_value", + entry_count=1210, + language_pair=translation_service.Glossary.LanguageCodePair( + source_language_code="source_language_code_value" + ), + ) + + response = client.get_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.GetGlossaryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.Glossary) + + assert response.name == "name_value" + + assert response.entry_count == 1210 + + +def test_get_glossary_from_dict(): + test_get_glossary(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_glossary_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.GetGlossaryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.Glossary(name="name_value", entry_count=1210,) + ) + + response = await client.get_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, translation_service.Glossary) + + assert response.name == "name_value" + + assert response.entry_count == 1210 + + +def test_get_glossary_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.GetGlossaryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_glossary), "__call__") as call: + call.return_value = translation_service.Glossary() + + client.get_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_glossary_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.GetGlossaryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_glossary), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.Glossary() + ) + + await client.get_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_glossary_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.Glossary() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_glossary(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_glossary_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_glossary( + translation_service.GetGlossaryRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_glossary_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = translation_service.Glossary() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + translation_service.Glossary() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_glossary(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_glossary_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_glossary( + translation_service.GetGlossaryRequest(), name="name_value", + ) + + +def test_delete_glossary( + transport: str = "grpc", request_type=translation_service.DeleteGlossaryRequest +): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.delete_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == translation_service.DeleteGlossaryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_glossary_from_dict(): + test_delete_glossary(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_glossary_async(transport: str = "grpc_asyncio"): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = translation_service.DeleteGlossaryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.delete_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_glossary_field_headers(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.DeleteGlossaryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_glossary), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.delete_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_glossary_field_headers_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = translation_service.DeleteGlossaryRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_glossary), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.delete_glossary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_glossary_flattened(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_glossary), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_glossary(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_glossary_flattened_error(): + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_glossary( + translation_service.DeleteGlossaryRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_glossary_flattened_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_glossary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_glossary(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_glossary_flattened_error_async(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_glossary( + translation_service.DeleteGlossaryRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TranslationServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = TranslationServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TranslationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TranslationServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TranslationServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.TranslationServiceGrpcTransport,) + + +def test_translation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.TranslationServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_translation_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.TranslationServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "translate_text", + "detect_language", + "get_supported_languages", + "batch_translate_text", + "create_glossary", + "list_glossaries", + "get_glossary", + "delete_glossary", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_translation_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.translate_v3beta1.services.translation_service.transports.TranslationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.TranslationServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id="octopus", + ) + + +def test_translation_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + TranslationServiceClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id=None, + ) + + +def test_translation_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.TranslationServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + quota_project_id="octopus", + ) + + +def test_translation_service_host_no_port(): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="translate.googleapis.com" + ), + ) + assert client._transport._host == "translate.googleapis.com:443" + + +def test_translation_service_host_with_port(): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="translate.googleapis.com:8000" + ), + ) + assert client._transport._host == "translate.googleapis.com:8000" + + +def test_translation_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.TranslationServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_translation_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.TranslationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_translation_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.TranslationServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_translation_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.TranslationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_translation_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.TranslationServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_translation_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.TranslationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-translation", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_translation_service_grpc_lro_client(): + client = TranslationServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_translation_service_grpc_lro_async_client(): + client = TranslationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_glossary_path(): + project = "squid" + location = "clam" + glossary = "whelk" + + expected = "projects/{project}/locations/{location}/glossaries/{glossary}".format( + project=project, location=location, glossary=glossary, + ) + actual = TranslationServiceClient.glossary_path(project, location, glossary) + assert expected == actual + + +def test_parse_glossary_path(): + expected = { + "project": "octopus", + "location": "oyster", + "glossary": "nudibranch", + } + path = TranslationServiceClient.glossary_path(**expected) + + # Check that the path construction is reversible. + actual = TranslationServiceClient.parse_glossary_path(path) + assert expected == actual diff --git a/packages/google-cloud-translate/tests/unit/gapic/v3/test_translation_service_client_v3.py b/packages/google-cloud-translate/tests/unit/gapic/v3/test_translation_service_client_v3.py deleted file mode 100644 index 65b0d020f60d..000000000000 --- a/packages/google-cloud-translate/tests/unit/gapic/v3/test_translation_service_client_v3.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import translate_v3 -from google.cloud.translate_v3.proto import translation_service_pb2 -from google.longrunning import operations_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestTranslationServiceClient(object): - def test_translate_text(self): - # Setup Expected Response - expected_response = {} - expected_response = translation_service_pb2.TranslateTextResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - contents = [] - target_language_code = "targetLanguageCode1323228230" - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.translate_text(contents, target_language_code, parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.TranslateTextRequest( - contents=contents, target_language_code=target_language_code, parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_translate_text_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup request - contents = [] - target_language_code = "targetLanguageCode1323228230" - parent = client.location_path("[PROJECT]", "[LOCATION]") - - with pytest.raises(CustomException): - client.translate_text(contents, target_language_code, parent) - - def test_detect_language(self): - # Setup Expected Response - expected_response = {} - expected_response = translation_service_pb2.DetectLanguageResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.detect_language(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.DetectLanguageRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_detect_language_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - with pytest.raises(CustomException): - client.detect_language(parent) - - def test_get_supported_languages(self): - # Setup Expected Response - expected_response = {} - expected_response = translation_service_pb2.SupportedLanguages( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.get_supported_languages(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.GetSupportedLanguagesRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_supported_languages_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - with pytest.raises(CustomException): - client.get_supported_languages(parent) - - def test_batch_translate_text(self): - # Setup Expected Response - total_characters = 1368640955 - translated_characters = 1337326221 - failed_characters = 1723028396 - expected_response = { - "total_characters": total_characters, - "translated_characters": translated_characters, - "failed_characters": failed_characters, - } - expected_response = translation_service_pb2.BatchTranslateResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_batch_translate_text", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - source_language_code = "sourceLanguageCode1687263568" - target_language_codes = [] - input_configs = [] - output_config = {} - - response = client.batch_translate_text( - parent, - source_language_code, - target_language_codes, - input_configs, - output_config, - ) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.BatchTranslateTextRequest( - parent=parent, - source_language_code=source_language_code, - target_language_codes=target_language_codes, - input_configs=input_configs, - output_config=output_config, - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_translate_text_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_batch_translate_text_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - source_language_code = "sourceLanguageCode1687263568" - target_language_codes = [] - input_configs = [] - output_config = {} - - response = client.batch_translate_text( - parent, - source_language_code, - target_language_codes, - input_configs, - output_config, - ) - exception = response.exception() - assert exception.errors[0] == error - - def test_create_glossary(self): - # Setup Expected Response - name = "name3373707" - entry_count = 811131134 - expected_response = {"name": name, "entry_count": entry_count} - expected_response = translation_service_pb2.Glossary(**expected_response) - operation = operations_pb2.Operation( - name="operations/test_create_glossary", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - glossary = {} - - response = client.create_glossary(parent, glossary) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.CreateGlossaryRequest( - parent=parent, glossary=glossary - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_glossary_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_create_glossary_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - glossary = {} - - response = client.create_glossary(parent, glossary) - exception = response.exception() - assert exception.errors[0] == error - - def test_list_glossaries(self): - # Setup Expected Response - next_page_token = "" - glossaries_element = {} - glossaries = [glossaries_element] - expected_response = { - "next_page_token": next_page_token, - "glossaries": glossaries, - } - expected_response = translation_service_pb2.ListGlossariesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_glossaries(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.glossaries[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.ListGlossariesRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_glossaries_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_glossaries(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_glossary(self): - # Setup Expected Response - name_2 = "name2-1052831874" - entry_count = 811131134 - expected_response = {"name": name_2, "entry_count": entry_count} - expected_response = translation_service_pb2.Glossary(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - name = client.glossary_path("[PROJECT]", "[LOCATION]", "[GLOSSARY]") - - response = client.get_glossary(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.GetGlossaryRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_glossary_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup request - name = client.glossary_path("[PROJECT]", "[LOCATION]", "[GLOSSARY]") - - with pytest.raises(CustomException): - client.get_glossary(name) - - def test_delete_glossary(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = translation_service_pb2.DeleteGlossaryResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_delete_glossary", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - name = client.glossary_path("[PROJECT]", "[LOCATION]", "[GLOSSARY]") - - response = client.delete_glossary(name) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.DeleteGlossaryRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_glossary_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_delete_glossary_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3.TranslationServiceClient() - - # Setup Request - name = client.glossary_path("[PROJECT]", "[LOCATION]", "[GLOSSARY]") - - response = client.delete_glossary(name) - exception = response.exception() - assert exception.errors[0] == error diff --git a/packages/google-cloud-translate/tests/unit/gapic/v3beta1/test_translation_service_client_v3beta1.py b/packages/google-cloud-translate/tests/unit/gapic/v3beta1/test_translation_service_client_v3beta1.py deleted file mode 100644 index fa2bccc23c79..000000000000 --- a/packages/google-cloud-translate/tests/unit/gapic/v3beta1/test_translation_service_client_v3beta1.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding: utf-8 -*- -# -# 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 -# -# https://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. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import translate_v3beta1 -from google.cloud.translate_v3beta1.proto import translation_service_pb2 -from google.longrunning import operations_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestTranslationServiceClient(object): - def test_translate_text(self): - # Setup Expected Response - expected_response = {} - expected_response = translation_service_pb2.TranslateTextResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - contents = [] - target_language_code = "targetLanguageCode1323228230" - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.translate_text(contents, target_language_code, parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.TranslateTextRequest( - contents=contents, target_language_code=target_language_code, parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_translate_text_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup request - contents = [] - target_language_code = "targetLanguageCode1323228230" - parent = client.location_path("[PROJECT]", "[LOCATION]") - - with pytest.raises(CustomException): - client.translate_text(contents, target_language_code, parent) - - def test_detect_language(self): - # Setup Expected Response - expected_response = {} - expected_response = translation_service_pb2.DetectLanguageResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.detect_language(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.DetectLanguageRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_detect_language_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - with pytest.raises(CustomException): - client.detect_language(parent) - - def test_get_supported_languages(self): - # Setup Expected Response - expected_response = {} - expected_response = translation_service_pb2.SupportedLanguages( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.get_supported_languages(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.GetSupportedLanguagesRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_supported_languages_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - with pytest.raises(CustomException): - client.get_supported_languages(parent) - - def test_batch_translate_text(self): - # Setup Expected Response - total_characters = 1368640955 - translated_characters = 1337326221 - failed_characters = 1723028396 - expected_response = { - "total_characters": total_characters, - "translated_characters": translated_characters, - "failed_characters": failed_characters, - } - expected_response = translation_service_pb2.BatchTranslateResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_batch_translate_text", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - source_language_code = "sourceLanguageCode1687263568" - target_language_codes = [] - input_configs = [] - output_config = {} - - response = client.batch_translate_text( - parent, - source_language_code, - target_language_codes, - input_configs, - output_config, - ) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.BatchTranslateTextRequest( - parent=parent, - source_language_code=source_language_code, - target_language_codes=target_language_codes, - input_configs=input_configs, - output_config=output_config, - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_translate_text_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_batch_translate_text_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - source_language_code = "sourceLanguageCode1687263568" - target_language_codes = [] - input_configs = [] - output_config = {} - - response = client.batch_translate_text( - parent, - source_language_code, - target_language_codes, - input_configs, - output_config, - ) - exception = response.exception() - assert exception.errors[0] == error - - def test_create_glossary(self): - # Setup Expected Response - name = "name3373707" - entry_count = 811131134 - expected_response = {"name": name, "entry_count": entry_count} - expected_response = translation_service_pb2.Glossary(**expected_response) - operation = operations_pb2.Operation( - name="operations/test_create_glossary", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - glossary = {} - - response = client.create_glossary(parent, glossary) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.CreateGlossaryRequest( - parent=parent, glossary=glossary - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_glossary_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_create_glossary_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - glossary = {} - - response = client.create_glossary(parent, glossary) - exception = response.exception() - assert exception.errors[0] == error - - def test_list_glossaries(self): - # Setup Expected Response - next_page_token = "" - glossaries_element = {} - glossaries = [glossaries_element] - expected_response = { - "next_page_token": next_page_token, - "glossaries": glossaries, - } - expected_response = translation_service_pb2.ListGlossariesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_glossaries(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.glossaries[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.ListGlossariesRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_glossaries_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_glossaries(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_glossary(self): - # Setup Expected Response - name_2 = "name2-1052831874" - entry_count = 811131134 - expected_response = {"name": name_2, "entry_count": entry_count} - expected_response = translation_service_pb2.Glossary(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - name = client.glossary_path("[PROJECT]", "[LOCATION]", "[GLOSSARY]") - - response = client.get_glossary(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.GetGlossaryRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_glossary_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup request - name = client.glossary_path("[PROJECT]", "[LOCATION]", "[GLOSSARY]") - - with pytest.raises(CustomException): - client.get_glossary(name) - - def test_delete_glossary(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = translation_service_pb2.DeleteGlossaryResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_delete_glossary", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - name = client.glossary_path("[PROJECT]", "[LOCATION]", "[GLOSSARY]") - - response = client.delete_glossary(name) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = translation_service_pb2.DeleteGlossaryRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_glossary_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_delete_glossary_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = translate_v3beta1.TranslationServiceClient() - - # Setup Request - name = client.glossary_path("[PROJECT]", "[LOCATION]", "[GLOSSARY]") - - response = client.delete_glossary(name) - exception = response.exception() - assert exception.errors[0] == error