pax_global_header00006660000000000000000000000064135055624330014520gustar00rootroot0000000000000052 comment=edbd3b1bb1643edb4f0fccbaa0bef7cb6d1108f6 ruby-google-cloud-translate-1.3.0/000077500000000000000000000000001350556243300170535ustar00rootroot00000000000000ruby-google-cloud-translate-1.3.0/.yardopts000066400000000000000000000003551350556243300207240ustar00rootroot00000000000000--no-private --title=Google Cloud Translation API --markup markdown --markup-provider redcarpet --main OVERVIEW.md ./lib/**/*.rb - OVERVIEW.md AUTHENTICATION.md CONTRIBUTING.md TROUBLESHOOTING.md CHANGELOG.md CODE_OF_CONDUCT.md LICENSE ruby-google-cloud-translate-1.3.0/AUTHENTICATION.md000066400000000000000000000163021350556243300215160ustar00rootroot00000000000000# Authentication In general, the google-cloud-translate library uses [Service Account](https://cloud.google.com/iam/docs/creating-managing-service-accounts) credentials to connect to Google Cloud services. When running on Compute Engine the credentials will be discovered automatically. When running on other environments, the Service Account credentials can be specified by providing the path to the [JSON keyfile](https://cloud.google.com/iam/docs/managing-service-account-keys) for the account (or the JSON itself) in environment variables. Additionally, Cloud SDK credentials can also be discovered automatically, but this is only recommended during development. ## Project and Credential Lookup The google-cloud-translate library aims to make authentication as simple as possible, and provides several mechanisms to configure your system without providing **Project ID** and **Service Account Credentials** directly in code. **Project ID** is discovered in the following order: 1. Specify project ID in method arguments 2. Specify project ID in configuration 3. Discover project ID in environment variables 4. Discover GCE project ID **Credentials** are discovered in the following order: 1. Specify credentials in method arguments 2. Specify credentials in configuration 3. Discover credentials path in environment variables 4. Discover credentials JSON in environment variables 5. Discover credentials file in the Cloud SDK's path 6. Discover GCE credentials ### Google Cloud Platform environments While running on Google Cloud Platform environments such as Google Compute Engine, Google App Engine and Google Kubernetes Engine, no extra work is needed. The **Project ID** and **Credentials** and are discovered automatically. Code should be written as if already authenticated. Just be sure when you [set up the GCE instance][gce-how-to], you add the correct scopes for the APIs you want to access. For example: * **All APIs** * `https://www.googleapis.com/auth/cloud-platform` * `https://www.googleapis.com/auth/cloud-platform.read-only` * **BigQuery** * `https://www.googleapis.com/auth/bigquery` * `https://www.googleapis.com/auth/bigquery.insertdata` * **Compute Engine** * `https://www.googleapis.com/auth/compute` * **Datastore** * `https://www.googleapis.com/auth/datastore` * `https://www.googleapis.com/auth/userinfo.email` * **DNS** * `https://www.googleapis.com/auth/ndev.clouddns.readwrite` * **Pub/Sub** * `https://www.googleapis.com/auth/pubsub` * **Storage** * `https://www.googleapis.com/auth/devstorage.full_control` * `https://www.googleapis.com/auth/devstorage.read_only` * `https://www.googleapis.com/auth/devstorage.read_write` ### Environment Variables The **Project ID** and **Credentials JSON** can be placed in environment variables instead of declaring them directly in code. Each service has its own environment variable, allowing for different service accounts to be used for different services. (See the READMEs for the individual service gems for details.) The path to the **Credentials JSON** file can be stored in the environment variable, or the **Credentials JSON** itself can be stored for environments such as Docker containers where writing files is difficult or not encouraged. The environment variables that Translation checks for project ID are: 1. `TRANSLATE_PROJECT` 2. `GOOGLE_CLOUD_PROJECT` The environment variables that Translation checks for credentials are configured on {Google::Cloud::Translate::Credentials}: 1. `TRANSLATE_CREDENTIALS` - Path to JSON file, or JSON contents 2. `TRANSLATE_KEYFILE` - Path to JSON file, or JSON contents 3. `GOOGLE_CLOUD_CREDENTIALS` - Path to JSON file, or JSON contents 4. `GOOGLE_CLOUD_KEYFILE` - Path to JSON file, or JSON contents 5. `GOOGLE_APPLICATION_CREDENTIALS` - Path to JSON file ```ruby require "google/cloud/translate" ENV["TRANSLATE_PROJECT"] = "my-project-id" ENV["TRANSLATE_CREDENTIALS"] = "path/to/keyfile.json" translate = Google::Cloud::Translate.new ``` ### Configuration The **Project ID** and **Credentials JSON** can be configured instead of placing them in environment variables or providing them as arguments. ```ruby require "google/cloud/translate" Google::Cloud::Translate.configure do |config| config.project_id = "my-project-id" config.credentials = "path/to/keyfile.json" end translate = Google::Cloud::Translate.new ``` ### Cloud SDK This option allows for an easy way to authenticate during development. If credentials are not provided in code or in environment variables, then Cloud SDK credentials are discovered. To configure your system for this, simply: 1. [Download and install the Cloud SDK](https://cloud.google.com/sdk) 2. Authenticate using OAuth 2.0 `$ gcloud auth login` 3. Write code as if already authenticated. **NOTE:** This is _not_ recommended for running in production. The Cloud SDK *should* only be used during development. [gce-how-to]: https://cloud.google.com/compute/docs/authentication#using [dev-console]: https://console.cloud.google.com/project [enable-apis]: https://raw.githubusercontent.com/GoogleCloudPlatform/gcloud-common/master/authentication/enable-apis.png [create-new-service-account]: https://raw.githubusercontent.com/GoogleCloudPlatform/gcloud-common/master/authentication/create-new-service-account.png [create-new-service-account-existing-keys]: https://raw.githubusercontent.com/GoogleCloudPlatform/gcloud-common/master/authentication/create-new-service-account-existing-keys.png [reuse-service-account]: https://raw.githubusercontent.com/GoogleCloudPlatform/gcloud-common/master/authentication/reuse-service-account.png ## Creating a Service Account Google Cloud requires a **Project ID** and **Service Account Credentials** to connect to the APIs. You will use the **Project ID** and **JSON key file** to connect to most services with google-cloud-translate. If you are not running this client on Google Compute Engine, you need a Google Developers service account. 1. Visit the [Google Developers Console][dev-console]. 1. Create a new project or click on an existing project. 1. Activate the slide-out navigation tray and select **API Manager**. From here, you will enable the APIs that your application requires. ![Enable the APIs that your application requires][enable-apis] *Note: You may need to enable billing in order to use these services.* 1. Select **Credentials** from the side navigation. You should see a screen like one of the following. ![Create a new service account][create-new-service-account] ![Create a new service account With Existing Keys][create-new-service-account-existing-keys] Find the "Add credentials" drop down and select "Service account" to be guided through downloading a new JSON key file. If you want to re-use an existing service account, you can easily generate a new key file. Just select the account you wish to re-use, and click "Generate new JSON key": ![Re-use an existing service account][reuse-service-account] The key file you download will be used by this library to authenticate API requests and should be stored in a secure location. ## Troubleshooting If you're having trouble authenticating you can ask for help by following the {file:TROUBLESHOOTING.md Troubleshooting Guide}. ruby-google-cloud-translate-1.3.0/CHANGELOG.md000066400000000000000000000041711350556243300206670ustar00rootroot00000000000000# Release History ### 1.3.0 / 2019-02-01 * Make use of Credentials#project_id * Use Credentials#project_id If a project_id is not provided, use the value on the Credentials object. This value was added in googleauth 0.7.0. * Loosen googleauth dependency Allow for new releases up to 0.10. The googleauth devs have committed to maintanining the current API and will not make backwards compatible changes before 0.10. ### 1.2.4 / 2018-09-20 * Update documentation. * Change documentation URL to googleapis GitHub org. * Fix circular require warning. ### 1.2.3 / 2018-09-12 * Add missing documentation files to package. ### 1.2.2 / 2018-09-10 * Update documentation. ### 1.2.1 / 2018-08-21 * Update documentation. ### 1.2.0 / 2018-02-27 * Support Shared Configuration. ### 1.1.0 / 2017-11-14 * Add `Google::Cloud::Translate::Credentials` class. * Rename constructor arguments to `project_id` and `credentials`. (The previous arguments `project` and `keyfile` are still supported.) * Document `Google::Auth::Credentials` as `credentials` value. * Updated `faraday`, `googleauth` dependencies. ### 1.0.1 / 2017-07-11 * Remove mention of discontinued Premium Edition billing from documentation. ### 1.0.0 / 2017-06-28 * Release 1.0 ### 0.23.1 / 2017-05-23 * Fix error handling (adrian-gomez) ### 0.23.0 / 2017-03-31 * No changes ### 0.22.2 / 2016-12-22 * Change product name to Google Cloud Translation API in docs. ### 0.22.1 / 2016-11-16 * Add missing googleauth dependency (frankyn) ### 0.22.0 / 2016-11-14 * Support authentication with service accounts * Add `model` parameter to translate method * Add `model` attribute to Translation objects ### 0.21.0 / 2016-10-20 * New service constructor Google::Cloud::Translate.new ### 0.20.1 / 2016-09-02 * Fix for timeout on uploads. ### 0.20.0 / 2016-08-26 This gem contains the Google Cloud Translate service implementation for the `google-cloud` gem. The `google-cloud` gem replaces the old `gcloud` gem. Legacy code can continue to use the `gcloud` gem. * Namespace is now `Google::Cloud` * The `google-cloud` gem is now an umbrella package for individual gems ruby-google-cloud-translate-1.3.0/CODE_OF_CONDUCT.md000066400000000000000000000036771350556243300216670ustar00rootroot00000000000000# Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) ruby-google-cloud-translate-1.3.0/CONTRIBUTING.md000066400000000000000000000141031350556243300213030ustar00rootroot00000000000000# Contributing to Google Cloud Translation 1. **Sign one of the contributor license agreements below.** 2. Fork the repo, develop and test your code changes. 3. Send a pull request. ## Contributor License Agreements Before we can accept your pull requests you'll need to sign a Contributor License Agreement (CLA): - **If you are an individual writing original source code** and **you own the intellectual property**, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). - **If you work for a company that wants to allow you to contribute your work**, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). You can sign these electronically (just scroll to the bottom). After that, we'll be able to accept your pull requests. ## Setup In order to use the google-cloud-translate console and run the project's tests, there is a small amount of setup: 1. Install Ruby. google-cloud-translate requires Ruby 2.3+. You may choose to manage your Ruby and gem installations with [RVM](https://rvm.io/), [rbenv](https://github.com/rbenv/rbenv), or [chruby](https://github.com/postmodern/chruby). 2. Install [Bundler](http://bundler.io/). ```sh $ gem install bundler ``` 3. Install the top-level project dependencies. ```sh $ bundle install ``` 4. Install the Translation dependencies. ```sh $ cd google-cloud-translate/ $ bundle exec rake bundleupdate ``` ## Console In order to run code interactively, you can automatically load google-cloud-translate and its dependencies in IRB. This requires that your developer environment has already been configured by following the steps described in the {file:AUTHENTICATION.md Authentication Guide}. An IRB console can be created with: ```sh $ cd google-cloud-translate/ $ bundle exec rake console ``` ## Translation Tests Tests are very important part of google-cloud-translate. All contributions should include tests that ensure the contributed code behaves as expected. To run the unit tests, documentation tests, and code style checks together for a package: ``` sh $ cd google-cloud-translate/ $ bundle exec rake ci ``` To run the command above, plus all acceptance tests, use `rake ci:acceptance` or its handy alias, `rake ci:a`. ### Translation Unit Tests The project uses the [minitest](https://github.com/seattlerb/minitest) library, including [specs](https://github.com/seattlerb/minitest#specs), [mocks](https://github.com/seattlerb/minitest#mocks) and [minitest-autotest](https://github.com/seattlerb/minitest-autotest). To run the Translation unit tests: ``` sh $ cd google-cloud-translate/ $ bundle exec rake test ``` ### Translation Documentation Tests The project tests the code examples in the gem's [YARD](https://github.com/lsegal/yard)-based documentation. The example testing functions in a way that is very similar to unit testing, and in fact the library providing it, [yard-doctest](https://github.com/p0deje/yard-doctest), is based on the project's unit test library, [minitest](https://github.com/seattlerb/minitest). To run the Translation documentation tests: ``` sh $ cd google-cloud-translate/ $ bundle exec rake doctest ``` If you add, remove or modify documentation examples when working on a pull request, you may need to update the setup for the tests. The stubs and mocks required to run the tests are located in `support/doctest_helper.rb`. Please note that much of the setup is matched by the title of the [`@example`](http://www.rubydoc.info/gems/yard/file/docs/Tags.md#example) tag. If you alter an example's title, you may encounter breaking tests. ### Translation Acceptance Tests The Translation acceptance tests interact with the live service API. Follow the instructions in the {file:AUTHENTICATION.md Authentication guide} for enabling the Translation API. Occasionally, some API features may not yet be generally available, making it difficult for some contributors to successfully run the entire acceptance test suite. However, please ensure that you do successfully run acceptance tests for any code areas covered by your pull request. To run the acceptance tests, first create and configure a project in the Google Developers Console, as described in the {file:AUTHENTICATION.md Authentication guide}. Be sure to download the JSON KEY file. Make note of the PROJECT_ID and the KEYFILE location on your system. Before you can run the Translation acceptance tests, you must first create indexes used in the tests. #### Running the Translation acceptance tests To run the Translation acceptance tests: ``` sh $ cd google-cloud-translate/ $ bundle exec rake acceptance[\\{my-project-id},\\{/path/to/keyfile.json}] ``` Or, if you prefer you can store the values in the `GCLOUD_TEST_PROJECT` and `GCLOUD_TEST_KEYFILE` environment variables: ``` sh $ cd google-cloud-translate/ $ export GCLOUD_TEST_PROJECT=\\{my-project-id} $ export GCLOUD_TEST_KEYFILE=\\{/path/to/keyfile.json} $ bundle exec rake acceptance ``` If you want to use a different project and credentials for acceptance tests, you can use the more specific `TRANSLATE_TEST_PROJECT` and `TRANSLATE_TEST_KEYFILE` environment variables: ``` sh $ cd google-cloud-translate/ $ export TRANSLATE_TEST_PROJECT=\\{my-project-id} $ export TRANSLATE_TEST_KEYFILE=\\{/path/to/keyfile.json} $ bundle exec rake acceptance ``` ## Coding Style Please follow the established coding style in the library. The style is is largely based on [The Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) with a few exceptions based on seattle-style: * Avoid parenthesis when possible, including in method definitions. * Always use double quotes strings. ([Option B](https://github.com/bbatsov/ruby-style-guide#strings)) You can check your code against these rules by running Rubocop like so: ```sh $ cd google-cloud-translate/ $ bundle exec rake rubocop ``` ## Code of Conduct Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See {file:CODE_OF_CONDUCT.md Code of Conduct} for more information. ruby-google-cloud-translate-1.3.0/LICENSE000066400000000000000000000261371350556243300200710ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ruby-google-cloud-translate-1.3.0/OVERVIEW.md000066400000000000000000000125341350556243300206500ustar00rootroot00000000000000# Google Cloud Translation API [Google Cloud Translation API](https://cloud.google.com/translation/) provides a simple, programmatic interface for translating an arbitrary string into any supported language. It is highly responsive, so websites and applications can integrate with Translation API for fast, dynamic translation of source text. Language detection is also available in cases where the source language is unknown. Translation API supports more than one hundred different languages, from Afrikaans to Zulu. Used in combination, this enables translation between thousands of language pairs. Also, you can send in HTML and receive HTML with translated text back. You don't need to extract your source text or reassemble the translated content. ## Authenticating Like other Cloud Platform services, Google Cloud Translation API supports authentication using a project ID and OAuth 2.0 credentials. In addition, it supports authentication using a public API access key. (If both the API key and the project and OAuth 2.0 credentials are provided, the API key will be used.) Instructions and configuration options are covered in the {file:AUTHENTICATION.md Authentication Guide}. ## Translating texts Translating text from one language to another is easy (and extremely fast.) The only required arguments to {Google::Cloud::Translate::Api#translate} are a string and the [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) code of the language to which you wish to translate. ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new translation = translate.translate "Hello world!", to: "la" puts translation #=> Salve mundi! translation.from #=> "en" translation.origin #=> "Hello world!" translation.to #=> "la" translation.text #=> "Salve mundi!" ``` You may want to use the `from` option to specify the language of the source text, as the following example illustrates. (Single words do not give Translation API much to work with.) ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new translation = translate.translate "chat", to: "en" translation.detected? #=> true translation.from #=> "en" translation.text #=> "chat" translation = translate.translate "chat", from: "fr", to: "en" translation.detected? #=> false translation.from #=> "fr" translation.text #=> "cat" ``` You can pass multiple texts to {Google::Cloud::Translate::Api#translate}. ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new translations = translate.translate "chien", "chat", from: "fr", to: "en" translations.size #=> 2 translations[0].origin #=> "chien" translations[0].text #=> "dog" translations[1].origin #=> "chat" translations[1].text #=> "cat" ``` By default, any HTML in your source text will be preserved. ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new translation = translate.translate "Hello world!", to: :la translation.text #=> "Salve mundi!" ``` ## Detecting languages You can use {Google::Cloud::Translate::Api#detect} to see which language the Translation API ranks as the most likely source language for a text. The `confidence` score is a float value between `0` and `1`. ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new detection = translate.detect "chat" detection.text #=> "chat" detection.language #=> "en" detection.confidence #=> 0.59922177 ``` You can pass multiple texts to {Google::Cloud::Translate::Api#detect}. ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new detections = translate.detect "chien", "chat" detections.size #=> 2 detections[0].text #=> "chien" detections[0].language #=> "fr" detections[0].confidence #=> 0.7109375 detections[1].text #=> "chat" detections[1].language #=> "en" detections[1].confidence #=> 0.59922177 ``` ## Listing supported languages Translation API adds new languages frequently. You can use {Google::Cloud::Translate::Api#languages} to query the list of supported languages. ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new languages = translate.languages languages.size #=> 104 languages[0].code #=> "af" languages[0].name #=> nil ``` To receive the names of the supported languages, as well as their [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) codes, provide the code for the language in which you wish to receive the names. ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new languages = translate.languages "en" languages.size #=> 104 languages[0].code #=> "af" languages[0].name #=> "Afrikaans" ``` ## Configuring retries and timeout You can configure how many times API requests may be automatically retried. When an API request fails, the response will be inspected to see if the request meets criteria indicating that it may succeed on retry, such as `500` and `503` status codes or a specific internal error code such as `rateLimitExceeded`. If it meets the criteria, the request will be retried after a delay. If another error occurs, the delay will be increased before a subsequent attempt, until the `retries` limit is reached. You can also set the request `timeout` value in seconds. ```ruby require "google/cloud/translate" translate = Google::Cloud::Translate.new retries: 10, timeout: 120 ``` ruby-google-cloud-translate-1.3.0/TROUBLESHOOTING.md000066400000000000000000000024121350556243300216630ustar00rootroot00000000000000# Troubleshooting ## Where can I get more help? ### Ask the Community If you have a question about how to use a Google Cloud client library in your project or are stuck in the Developer's console and don't know where to turn, it's possible your questions have already been addressed by the community. First, check out the appropriate tags on StackOverflow: - [`google-cloud-platform+ruby+translate`][so-ruby] Next, try searching through the issues on GitHub: - [`api:translate` issues][gh-search-ruby] Still nothing? ### Ask the Developers If you're experiencing a bug with the code, or have an idea for how it can be improved, *please* create a new issue on GitHub so we can talk about it. - [New issue][gh-ruby] Or, you can ask questions on the [Google Cloud Platform Slack][slack-ruby]. You can use the "ruby" channel for general Ruby questions, or use the "google-cloud-ruby" channel if you have questions about this gem in particular. [so-ruby]: http://stackoverflow.com/questions/tagged/google-cloud-platform+ruby+translate [gh-search-ruby]: https://github.com/googlecloudplatform/google-cloud-ruby/issues?q=label%3A%22api%3A+translate%22 [gh-ruby]: https://github.com/googlecloudplatform/google-cloud-ruby/issues/new [slack-ruby]: https://gcp-slack.appspot.com/ ruby-google-cloud-translate-1.3.0/google-cloud-translate.gemspec000066400000000000000000000104241350556243300247740ustar00rootroot00000000000000######################################################### # This file has been automatically generated by gem2tgz # ######################################################### # -*- encoding: utf-8 -*- # stub: google-cloud-translate 1.3.0 ruby lib Gem::Specification.new do |s| s.name = "google-cloud-translate".freeze s.version = "1.3.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Mike Moore".freeze, "Chris Smith".freeze] s.date = "2019-02-04" s.description = "google-cloud-translate is the official library for Google Cloud Translation API.".freeze s.email = ["mike@blowmage.com".freeze, "quartzmo@gmail.com".freeze] s.files = [".yardopts".freeze, "AUTHENTICATION.md".freeze, "CHANGELOG.md".freeze, "CODE_OF_CONDUCT.md".freeze, "CONTRIBUTING.md".freeze, "LICENSE".freeze, "OVERVIEW.md".freeze, "TROUBLESHOOTING.md".freeze, "lib/google-cloud-translate.rb".freeze, "lib/google/cloud/translate.rb".freeze, "lib/google/cloud/translate/api.rb".freeze, "lib/google/cloud/translate/credentials.rb".freeze, "lib/google/cloud/translate/detection.rb".freeze, "lib/google/cloud/translate/language.rb".freeze, "lib/google/cloud/translate/service.rb".freeze, "lib/google/cloud/translate/translation.rb".freeze, "lib/google/cloud/translate/version.rb".freeze] s.homepage = "https://github.com/googleapis/google-cloud-ruby/tree/master/google-cloud-translate".freeze s.licenses = ["Apache-2.0".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.0.0".freeze) s.rubygems_version = "2.7.6.2".freeze s.summary = "API Client library for Google Cloud Translation API".freeze if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q.freeze, ["~> 1.1"]) s.add_runtime_dependency(%q.freeze, ["~> 0.13"]) s.add_runtime_dependency(%q.freeze, ["~> 1.2"]) s.add_runtime_dependency(%q.freeze, ["< 0.10.0", ">= 0.6.2"]) s.add_development_dependency(%q.freeze, ["~> 5.10"]) s.add_development_dependency(%q.freeze, ["~> 1.0"]) s.add_development_dependency(%q.freeze, ["~> 1.1"]) s.add_development_dependency(%q.freeze, ["~> 5.2"]) s.add_development_dependency(%q.freeze, ["~> 3.0"]) s.add_development_dependency(%q.freeze, ["~> 0.61.0"]) s.add_development_dependency(%q.freeze, ["~> 0.9"]) s.add_development_dependency(%q.freeze, ["~> 0.9"]) s.add_development_dependency(%q.freeze, ["~> 0.1.13"]) else s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, ["~> 0.13"]) s.add_dependency(%q.freeze, ["~> 1.2"]) s.add_dependency(%q.freeze, ["< 0.10.0", ">= 0.6.2"]) s.add_dependency(%q.freeze, ["~> 5.10"]) s.add_dependency(%q.freeze, ["~> 1.0"]) s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, ["~> 5.2"]) s.add_dependency(%q.freeze, ["~> 3.0"]) s.add_dependency(%q.freeze, ["~> 0.61.0"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.1.13"]) end else s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, ["~> 0.13"]) s.add_dependency(%q.freeze, ["~> 1.2"]) s.add_dependency(%q.freeze, ["< 0.10.0", ">= 0.6.2"]) s.add_dependency(%q.freeze, ["~> 5.10"]) s.add_dependency(%q.freeze, ["~> 1.0"]) s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, ["~> 5.2"]) s.add_dependency(%q.freeze, ["~> 3.0"]) s.add_dependency(%q.freeze, ["~> 0.61.0"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.1.13"]) end end ruby-google-cloud-translate-1.3.0/lib/000077500000000000000000000000001350556243300176215ustar00rootroot00000000000000ruby-google-cloud-translate-1.3.0/lib/google-cloud-translate.rb000066400000000000000000000161511350556243300245250ustar00rootroot00000000000000# 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 # # 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. ## # This file is here to be autorequired by bundler, so that the # Google::Cloud.translate and Google::Cloud#translate methods can be available, # but the library and all dependencies won't be loaded until required and used. gem "google-cloud-core" require "google/cloud" unless defined? Google::Cloud.new require "google/cloud/config" require "googleauth" module Google module Cloud ## # Creates a new object for connecting to the Cloud Translation API. Each # call creates a new connection. # # Like other Cloud Platform services, Google Cloud Translation API supports # authentication using a project ID and OAuth 2.0 credentials. In addition, # it supports authentication using a public API access key. (If both the API # key and the project and OAuth 2.0 credentials are provided, the API key # will be used.) Instructions and configuration options are covered in the # {file:AUTHENTICATION.md Authentication Guide}. # # @param [String] key a public API access key (not an OAuth 2.0 token) # @param [String, Array] scope The OAuth 2.0 scopes controlling the # set of resources and operations that the connection can access. See # [Using OAuth 2.0 to Access Google # APIs](https://developers.google.com/identity/protocols/OAuth2). # # The default scope is: # # * `https://www.googleapis.com/auth/cloud-platform` # @param [Integer] retries Number of times to retry requests on server # error. The default value is `3`. Optional. # @param [Integer] timeout Default timeout to use in requests. Optional. # # @return [Google::Cloud::Translate::Api] # # @example # require "google/cloud" # # gcloud = Google::Cloud.new # translate = gcloud.translate "api-key-abc123XYZ789" # # translation = translate.translate "Hello world!", to: "la" # translation.text #=> "Salve mundi!" # # @example Using API Key from the environment variable. # require "google/cloud" # # ENV["TRANSLATE_KEY"] = "api-key-abc123XYZ789" # # gcloud = Google::Cloud.new # translate = gcloud.translate # # translation = translate.translate "Hello world!", to: "la" # translation.text #=> "Salve mundi!" # def translate key = nil, scope: nil, retries: nil, timeout: nil Google::Cloud.translate key, project_id: @project, credentials: @keyfile, scope: scope, retries: (retries || @retries), timeout: (timeout || @timeout) end ## # Creates a new object for connecting to the Cloud Translation API. Each # call creates a new connection. # # Like other Cloud Platform services, Google Cloud Translation API supports # authentication using a project ID and OAuth 2.0 credentials. In addition, # it supports authentication using a public API access key. (If both the API # key and the project and OAuth 2.0 credentials are provided, the API key # will be used.) Instructions and configuration options are covered in the # {file:AUTHENTICATION.md Authentication Guide}. # # @param [String] key a public API access key (not an OAuth 2.0 token) # @param [String] project_id Project identifier for the Cloud Translation # service you are connecting to. If not present, the default project for # the credentials is used. # @param [String, Hash, Google::Auth::Credentials] credentials The path to # the keyfile as a String, the contents of the keyfile as a Hash, or a # Google::Auth::Credentials object. (See {Translate::Credentials}) # @param [String, Array] scope The OAuth 2.0 scopes controlling the # set of resources and operations that the connection can access. See # [Using OAuth 2.0 to Access Google # APIs](https://developers.google.com/identity/protocols/OAuth2). # # The default scope is: # # * `https://www.googleapis.com/auth/cloud-platform` # @param [Integer] retries Number of times to retry requests on server # error. The default value is `3`. Optional. # @param [Integer] timeout Default timeout to use in requests. Optional. # @param [String] project Alias for the `project_id` argument. Deprecated. # @param [String] keyfile Alias for the `credentials` argument. # Deprecated. # # @return [Google::Cloud::Translate::Api] # # @example # require "google/cloud" # # translate = Google::Cloud.translate "api-key-abc123XYZ789" # # translation = translate.translate "Hello world!", to: "la" # translation.text #=> "Salve mundi!" # # @example Using API Key from the environment variable. # require "google/cloud" # # ENV["TRANSLATE_KEY"] = "api-key-abc123XYZ789" # # translate = Google::Cloud.translate # # translation = translate.translate "Hello world!", to: "la" # translation.text #=> "Salve mundi!" # def self.translate key = nil, project_id: nil, credentials: nil, scope: nil, retries: nil, timeout: nil, project: nil, keyfile: nil require "google/cloud/translate" Google::Cloud::Translate.new key: key, project_id: project_id, credentials: credentials, scope: scope, retries: retries, timeout: timeout, project: project, keyfile: keyfile end end end # Set the default translate configuration Google::Cloud.configure.add_config! :translate do |config| default_project = Google::Cloud::Config.deferred do ENV["TRANSLATE_PROJECT"] end default_creds = Google::Cloud::Config.deferred do Google::Cloud::Config.credentials_from_env( "TRANSLATE_CREDENTIALS", "TRANSLATE_CREDENTIALS_JSON", "TRANSLATE_KEYFILE", "TRANSLATE_KEYFILE_JSON" ) end default_key = Google::Cloud::Config.deferred do ENV["TRANSLATE_KEY"] || ENV["GOOGLE_CLOUD_KEY"] end config.add_field! :project_id, default_project, match: String, allow_nil: true config.add_alias! :project, :project_id config.add_field! :credentials, default_creds, match: [String, Hash, Google::Auth::Credentials], allow_nil: true config.add_alias! :keyfile, :credentials config.add_field! :key, default_key, match: String, allow_nil: true config.add_field! :scope, nil, match: [String, Array] config.add_field! :retries, nil, match: Integer config.add_field! :timeout, nil, match: Integer end ruby-google-cloud-translate-1.3.0/lib/google/000077500000000000000000000000001350556243300210755ustar00rootroot00000000000000ruby-google-cloud-translate-1.3.0/lib/google/cloud/000077500000000000000000000000001350556243300222035ustar00rootroot00000000000000ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate.rb000066400000000000000000000170041350556243300245270ustar00rootroot00000000000000# 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 # # 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. require "google-cloud-translate" require "google/cloud/translate/api" require "google/cloud/config" require "google/cloud/env" module Google module Cloud ## # # Google Cloud Translation API # # [Google Cloud Translation API](https://cloud.google.com/translation/) # provides a simple, programmatic interface for translating an arbitrary # string into any supported language. It is highly responsive, so websites # and applications can integrate with Translation API for fast, dynamic # translation of source text. Language detection is also available in cases # where the source language is unknown. # # Translation API supports more than one hundred different languages, from # Afrikaans to Zulu. Used in combination, this enables translation between # thousands of language pairs. Also, you can send in HTML and receive HTML # with translated text back. You don't need to extract your source text or # reassemble the translated content. # # See {file:OVERVIEW.md Translation Overview}. # module Translate # rubocop:disable Metrics/AbcSize ## # Creates a new object for connecting to Cloud Translation API. Each call # creates a new connection. # # Like other Cloud Platform services, Google Cloud Translation API # supports authentication using a project ID and OAuth 2.0 credentials. In # addition, it supports authentication using a public API access key. (If # both the API key and the project and OAuth 2.0 credentials are provided, # the API key will be used.) Instructions and configuration options are # covered in the {file:AUTHENTICATION.md Authentication Guide}. # # @param [String] project_id Project identifier for the Cloud Translation # service you are connecting to. If not present, the default project for # the credentials is used. # @param [String, Hash, Google::Auth::Credentials] credentials The path to # the keyfile as a String, the contents of the keyfile as a Hash, or a # Google::Auth::Credentials object. (See {Translate::Credentials}) # @param [String] key a public API access key (not an OAuth 2.0 token) # @param [String, Array] scope The OAuth 2.0 scopes controlling # the set of resources and operations that the connection can access. # See [Using OAuth 2.0 to Access Google # APIs](https://developers.google.com/identity/protocols/OAuth2). # # The default scope is: # # * `https://www.googleapis.com/auth/cloud-platform` # @param [Integer] retries Number of times to retry requests on server # error. The default value is `3`. Optional. # @param [Integer] timeout Default timeout to use in requests. Optional. # @param [String] project Alias for the `project_id` argument. Deprecated. # @param [String] keyfile Alias for the `credentials` argument. # Deprecated. # # @return [Google::Cloud::Translate::Api] # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new( # project_id: "my-todo-project", # credentials: "/path/to/keyfile.json" # ) # # translation = translate.translate "Hello world!", to: "la" # translation.text #=> "Salve mundi!" # # @example Using API Key. # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new( # key: "api-key-abc123XYZ789" # ) # # translation = translate.translate "Hello world!", to: "la" # translation.text #=> "Salve mundi!" # # @example Using API Key from the environment variable. # require "google/cloud/translate" # # ENV["TRANSLATE_KEY"] = "api-key-abc123XYZ789" # # translate = Google::Cloud::Translate.new # # translation = translate.translate "Hello world!", to: "la" # translation.text #=> "Salve mundi!" # def self.new project_id: nil, credentials: nil, key: nil, scope: nil, retries: nil, timeout: nil, project: nil, keyfile: nil project_id ||= (project || default_project_id) key ||= configure.key if key return Google::Cloud::Translate::Api.new( Google::Cloud::Translate::Service.new( project_id.to_s, nil, retries: retries, timeout: timeout, key: key ) ) end scope ||= configure.scope retries ||= configure.retries timeout ||= configure.timeout credentials ||= keyfile || default_credentials(scope: scope) unless credentials.is_a? Google::Auth::Credentials credentials = Translate::Credentials.new credentials, scope: scope end if credentials.respond_to? :project_id project_id ||= credentials.project_id end project_id = project_id.to_s # Always cast to a string raise ArgumentError, "project_id is missing" if project_id.empty? Translate::Api.new( Translate::Service.new( project_id, credentials, retries: retries, timeout: timeout ) ) end # rubocop:enable Metrics/AbcSize ## # Configure the Google Cloud Translate library. # # The following Translate configuration parameters are supported: # # * `project_id` - (String) Identifier for a Translate project. (The # parameter `project` is considered deprecated, but may also be used.) # * `credentials` - (String, Hash, Google::Auth::Credentials) The path to # the keyfile as a String, the contents of the keyfile as a Hash, or a # Google::Auth::Credentials object. (See {Translate::Credentials}) (The # parameter `keyfile` is considered deprecated, but may also be used.) # * `scope` - (String, Array) The OAuth 2.0 scopes controlling # the set of resources and operations that the connection can access. # * `retries` - (Integer) Number of times to retry requests on server # error. # * `timeout` - (Integer) Default timeout to use in requests. # # @return [Google::Cloud::Config] The configuration object the # Google::Cloud::Translate library uses. # def self.configure yield Google::Cloud.configure.translate if block_given? Google::Cloud.configure.translate end ## # @private Default project. def self.default_project_id Google::Cloud.configure.translate.project_id || Google::Cloud.configure.project_id || Google::Cloud.env.project_id end ## # @private Default credentials. def self.default_credentials scope: nil Google::Cloud.configure.translate.credentials || Google::Cloud.configure.credentials || Translate::Credentials.default(scope: scope) end end end end ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate/000077500000000000000000000000001350556243300242005ustar00rootroot00000000000000ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate/api.rb000066400000000000000000000240111350556243300252740ustar00rootroot00000000000000# 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 # # 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. require "google/cloud/translate/service" require "google/cloud/translate/translation" require "google/cloud/translate/detection" require "google/cloud/translate/language" module Google module Cloud module Translate ## # # Api # # Represents top-level access to the Google Cloud Translation API. # Translation API supports more than one hundred different languages, from # Afrikaans to Zulu. Used in combination, this enables translation between # thousands of language pairs. Also, you can send in HTML and receive HTML # with translated text back. You don't need to extract your source text or # reassemble the translated content. # # @see https://cloud.google.com/translation/docs/getting-started # Cloud Translation API Quickstart # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # translation = translate.translate "Hello world!", to: "la" # # translation.to_s #=> "Salve mundi!" # # translation.from #=> "en" # translation.origin #=> "Hello world!" # translation.to #=> "la" # translation.text #=> "Salve mundi!" # class Api ## # @private The Service object. attr_accessor :service ## # @private Creates a new Api instance. # # See {Google::Cloud.translate} def initialize service @service = service end ## # The Cloud Translation API project connected to. # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new( # project_id: "my-todo-project", # credentials: "/path/to/keyfile.json" # ) # # translate.project_id #=> "my-todo-project" # def project_id service.project end alias project project_id ## # Returns text translations from one language to another. # # @see https://cloud.google.com/translation/docs/translating-text#Translate # Translating Text # # @param [String] text The text or texts to translate. # @param [String] to The target language into which the text should be # translated. This is required. The value must be an [ISO # 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) # language code. # @param [String] from The source language of the text or texts. This is # an [ISO # 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) # language code. This is optional. # @param [String] format The format of the text. Possible values include # `:text` and `:html`. This is optional. The Translation API default # is `:html`. # @param [String] model The model used by the service to perform the # translation. Can be either `base` to use the Phrase-Based Machine # Translation (PBMT) model, or `nmt` to use the Neural Machine # Translation (NMT) model. The default is `nmt`. # # If the model is `nmt`, and the requested language translation pair # is not supported for the NMT model, then the request is translated # using the PBMT model. # # @param [String] cid The customization id for translate. This is # optional. # # @return [Translation, Array] A single {Translation} # object if just one text was given, or an array of {Translation} # objects if multiple texts were given. # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # translation = translate.translate "Hello world!", to: "la" # # translation.to_s #=> "Salve mundi!" # # translation.detected? #=> true # translation.from #=> "en" # translation.origin #=> "Hello world!" # translation.to #=> "la" # translation.text #=> "Salve mundi!" # translation.model #=> "base" # # @example Using the neural machine translation model: # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # translation = translate.translate "Hello world!", # to: "la", model: "nmt" # # translation.to_s #=> "Salve mundi!" # translation.model #=> "nmt" # # @example Setting the `from` language. # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # translation = translate.translate "Hello world!", # from: :en, to: :la # translation.detected? #=> false # translation.text #=> "Salve mundi!" # # @example Retrieving multiple translations. # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # translations = translate.translate "Hello my friend.", # "See you soon.", # from: "en", to: "la" # translations.count #=> 2 # translations[0].text #=> "Salve amice." # translations[1].text #=> "Vide te mox." # # @example Preserving HTML tags. # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # translation = translate.translate "Hello world!", # to: :la # translation.text #=> "Salve mundi!" # def translate *text, to: nil, from: nil, format: nil, model: nil, cid: nil return nil if text.empty? raise ArgumentError, "to is required" if to.nil? to = to.to_s from = from.to_s if from format = format.to_s if format text = Array(text).flatten gapi = service.translate text, to: to, from: from, format: format, model: model, cid: cid Translation.from_gapi_list gapi, text, to, from end ## # Detect the most likely language or languages of a text or multiple # texts. # # @see https://cloud.google.com/translation/docs/detecting-language # Detecting Language # # @param [String] text The text or texts upon which language detection # should be performed. # # @return [Detection, Array] A single {Detection} object if # just one text was given, or an array of {Detection} objects if # multiple texts were given. # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # detection = translate.detect "Hello world!" # detection.language #=> "en" # detection.confidence #=> 0.7100697 # # @example Detecting multiple texts. # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # detections = translate.detect "Hello world!", # "Bonjour le monde!" # detections.count #=> 2 # detections.first.language #=> "en" # detections.first.confidence #=> 0.7100697 # detections.last.language #=> "fr" # detections.last.confidence #=> 0.40440267 # def detect *text return nil if text.empty? text = Array(text).flatten gapi = service.detect(text) Detection.from_gapi gapi, text end ## # List the languages supported by the API. These are the languages to # and from which text can be translated. # # @see https://cloud.google.com/translation/docs/discovering-supported-languages # Discovering Supported Languages # # @param [String] language The language and collation in which the names # of the languages are returned. If this is `nil` then no names are # returned. # # @return [Array] An array of {Language} objects supported by # the API. # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # languages = translate.languages # languages.count #=> 104 # # english = languages.detect { |l| l.code == "en" } # english.name #=> nil # # @example Get all languages with their names in French. # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # languages = translate.languages "fr" # languages.count #=> 104 # # english = languages.detect { |l| l.code == "en" } # english.name #=> "Anglais" # def languages language = nil language = language.to_s if language gapi = service.languages language Array(gapi["languages"]).map { |g| Language.from_gapi g } end end end end end ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate/credentials.rb000066400000000000000000000036611350556243300270300ustar00rootroot00000000000000# 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 # # 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. require "googleauth" module Google module Cloud module Translate ## # # Credentials # # Represents the authentication and authorization used to connect to the # Cloud Translation API. # # @example # require "google/cloud/translate" # # keyfile = "/path/to/keyfile.json" # creds = Google::Cloud::Translate::Credentials.new keyfile # # translate = Google::Cloud::Translate.new( # project_id: "my-todo-project", # credentials: creds # ) # # translate.project_id #=> "my-todo-project" # class Credentials < Google::Auth::Credentials SCOPE = ["https://www.googleapis.com/auth/cloud-platform"].freeze PATH_ENV_VARS = %w[TRANSLATE_CREDENTIALS TRANSLATE_KEYFILE GOOGLE_CLOUD_CREDENTIALS GOOGLE_CLOUD_KEYFILE GCLOUD_KEYFILE].freeze JSON_ENV_VARS = %w[TRANSLATE_CREDENTIALS_JSON TRANSLATE_KEYFILE_JSON GOOGLE_CLOUD_CREDENTIALS_JSON GOOGLE_CLOUD_KEYFILE_JSON GCLOUD_KEYFILE_JSON].freeze DEFAULT_PATHS = \ ["~/.config/gcloud/application_default_credentials.json"].freeze end end end end ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate/detection.rb000066400000000000000000000103301350556243300265000ustar00rootroot00000000000000# 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 # # 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. module Google module Cloud module Translate ## # # Detection # # Represents a detect language query result. Returned by # {Google::Cloud::Translate::Api#detect}. # # @see https://cloud.google.com/translation/docs/detecting-language # Detecting Language # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # detections = translate.detect "chien", "chat" # # detections.size #=> 2 # detections[0].text #=> "chien" # detections[0].language #=> "fr" # detections[0].confidence #=> 0.7109375 # detections[1].text #=> "chat" # detections[1].language #=> "en" # detections[1].confidence #=> 0.59922177 # class Detection ## # The text upon which the language detection was performed. # # @return [String] attr_reader :text ## # The list of detection results for the given text. The most likely # language is listed first, and its attributes can be accessed through # {#language} and {#confidence}. # # @return [Array] attr_reader :results ## # @private Create a new object. def initialize text, results @text = text @results = results end ## # The confidence that the language detection result is correct. The # closer this value is to 1, the higher the confidence in language # detection. # # @return [Float] a value between 0 and 1 def confidence return nil if results.empty? results.first.confidence end ## # The most likely language that was detected. This is an [ISO # 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language # code. # # @return [String] the language code def language return nil if results.empty? results.first.language end ## # @private New Detection from a ListDetectionsResponse object as # defined by the Google API Client object. def self.from_gapi gapi, text res = text.zip(Array(gapi["detections"])).map do |txt, detections| results = detections.map { |g| Result.from_gapi g } new txt, results end return res.first if res.size == 1 res end ## # # Result # # Represents an individual result in a # {Google::Cloud::Translate::Detection} result. # class Result ## # The confidence that the language detection result is correct. The # closer this value is to 1, the higher the confidence in language # detection. # # @return [Float] a value between 0 and 1 attr_reader :confidence ## # The language detected. This is an [ISO # 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) # language code. # # @return [String] the language code attr_reader :language ## # @private Create a new object. def initialize confidence, language @confidence = confidence @language = language end ## # @private New Detection::Result from a DetectionsResource object as # defined by the Google API Client object. def self.from_gapi gapi new gapi["confidence"], gapi["language"] end end end end end end ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate/language.rb000066400000000000000000000037111350556243300263120ustar00rootroot00000000000000# 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 # # 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. module Google module Cloud module Translate ## # # Language # # Represents a supported languages query result. Returned by # {Google::Cloud::Translate::Api#languages}. # # @see https://cloud.google.com/translation/docs/discovering-supported-languages # Discovering Supported Languages # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # languages = translate.languages "en" # # languages.size #=> 104 # languages[0].code #=> "af" # languages[0].name #=> "Afrikaans" # class Language ## # The language code. This is an [ISO # 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language # code. # # @return [String] attr_reader :code ## # The localized name of the language, if available. # # @return [String] attr_reader :name ## # @private Create a new object. def initialize code, name @code = code @name = name end ## # @private New Language from a LanguagesResource object as defined by # the Google API Client object. def self.from_gapi gapi new gapi["language"], gapi["name"] end end end end end ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate/service.rb000066400000000000000000000144101350556243300261650ustar00rootroot00000000000000# 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 # # 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. require "google/cloud/errors" require "google/cloud/translate/credentials" require "google/cloud/translate/version" require "faraday" module Google module Cloud module Translate ## # @private # Represents the Translation API REST service, exposing the API calls. class Service #:nodoc: API_VERSION = "v2".freeze API_URL = "https://translation.googleapis.com".freeze # @private attr_accessor :project, :credentials, :retries, :timeout, :key ## # Creates a new Service instance. def initialize project, credentials, retries: nil, timeout: nil, key: nil @project = project @credentials = credentials @retries = retries @timeout = timeout @key = key end ## # Returns Hash of ListTranslationsResponse JSON def translate text, to: nil, from: nil, format: nil, model: nil, cid: nil body = { q: Array(text), target: to, source: from, format: format, model: model, cid: cid }.delete_if { |_k, v| v.nil? }.to_json post "/language/translate/v2", body end ## # Returns API::ListDetectionsResponse def detect text body = { q: Array(text) }.to_json post "language/translate/v2/detect", body end ## # Returns API::ListLanguagesResponse def languages language = nil body = { target: language }.to_json post "language/translate/v2/languages", body end def inspect self.class.to_s end protected def post path, body = nil response = execute do http.post path do |req| req.headers.merge! default_http_headers req.body = body unless body.nil? if @key req.params = { key: @key } else sign_http_request! req end end end return JSON.parse(response.body)["data"] if response.success? raise Google::Cloud::Error.gapi_error_class_for(response.status) rescue Faraday::ConnectionFailed raise Google::Cloud::ResourceExhaustedError end ## # The HTTP object that makes calls to API. # This must be a Faraday object. def http @http ||= Faraday.new url: API_URL, request: { open_timeout: @timeout, timeout: @timeout }.delete_if { |_k, v| v.nil? } end ## # The default HTTP headers to be sent on all API calls. def default_http_headers @default_http_headers ||= { "User-Agent" => "gcloud-ruby/#{Google::Cloud::Translate::VERSION}", "google-cloud-resource-prefix" => "projects/#{@project}", "Content-Type" => "application/json", "x-goog-api-client" => "gl-ruby/#{RUBY_VERSION} " \ "gccl/#{Google::Cloud::Translate::VERSION}" } end ## # Make a request and apply incremental backoff def execute backoff = Backoff.new retries: retries backoff.execute do yield end rescue Faraday::ConnectionFailed raise Google::Cloud::ResourceExhaustedError end ## # Sign Oauth2 API calls. def sign_http_request! request client = credentials.client return if client.nil? client.fetch_access_token! if client.expires_within? 30 client.generate_authenticated_request request: request request end ## # @private Backoff class Backoff class << self attr_accessor :retries attr_accessor :http_codes attr_accessor :reasons attr_accessor :backoff # :nodoc: end # Set the default values self.retries = 3 self.http_codes = [500, 503] self.reasons = %w[rateLimitExceeded userRateLimitExceeded] self.backoff = ->(retries) { sleep retries.to_i } def initialize options = {} #:nodoc: @max_retries = (options[:retries] || Backoff.retries).to_i @http_codes = (options[:http_codes] || Backoff.http_codes).to_a @reasons = (options[:reasons] || Backoff.reasons).to_a @backoff = options[:backoff] || Backoff.backoff end def execute #:nodoc: current_retries = 0 loop do response = yield # Expecting Faraday::Response return response if response.success? break response unless retry? response, current_retries current_retries += 1 @backoff.call current_retries end end protected def retry? result, current_retries #:nodoc: if current_retries < @max_retries return true if retry_http_code? result return true if retry_error_reason? result end false end def retry_http_code? response #:nodoc: @http_codes.include? response.status end def retry_error_reason? response #:nodoc: result = JSON.parse(response.body) if result && result["error"] && result["error"]["errors"] Array(result["error"]["errors"]).each do |error| if error["reason"] && @reasons.include?(error["reason"]) return true end end end false end end end end end end ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate/translation.rb000066400000000000000000000073701350556243300270720ustar00rootroot00000000000000# 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 # # 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. module Google module Cloud module Translate ## # # Translation # # Represents a translation query result. Returned by # {Google::Cloud::Translate::Api#translate}. # # @see https://cloud.google.com/translation/docs/translating-text#Translate # Translating Text # # @example # require "google/cloud/translate" # # translate = Google::Cloud::Translate.new # # translation = translate.translate "Hello world!", to: "la" # # translation.to_s #=> "Salve mundi!" # # translation.from #=> "en" # translation.origin #=> "Hello world!" # translation.to #=> "la" # translation.text #=> "Salve mundi!" # class Translation ## # The translated result. # # @return [String] attr_reader :text alias to_s text alias to_str text ## # The original query text that was translated. # # @return [String] attr_reader :origin ## # The target language into which the text was translated. # # @return [String] attr_reader :to alias language to alias target to ## # The source language from which the text was translated. # # @return [String] attr_reader :from alias source from ## # The translation model. Can be either `base` for the Phrase-Based # Machine Translation (PBMT) model, or `nmt` for the Neural Machine # Translation (NMT) model. If you did not include a model parameter with # your request, then this field is not included in the response. # # @return [String] attr_reader :model ## # @private Create a new object. def initialize text, to, origin, from, model, detected @text = text @to = to @origin = origin @from = from @model = model @detected = detected end ## # Determines if the source language was detected by the Google Cloud # Cloud Translation API. # # @return [Boolean] `true` if the source language was detected by the # Cloud Translation API, `false` if the source language was provided # in the request def detected? @detected end ## # @private New Translation from a TranslationsListResponse object as # defined by the Google API Client object. def self.from_gapi_list gapi, text, to, from res = text.zip(Array(gapi["translations"])).map do |origin, g| from_gapi g, to, origin, from end return res.first if res.size == 1 res end ## # @private New Translation from a TranslationsResource object as defined # by the Google API Client object. def self.from_gapi gapi, to, origin, from from ||= gapi["detectedSourceLanguage"] detected = !gapi["detectedSourceLanguage"].nil? new gapi["translatedText"], to, origin, from, gapi["model"], detected end end end end end ruby-google-cloud-translate-1.3.0/lib/google/cloud/translate/version.rb000066400000000000000000000012441350556243300262130ustar00rootroot00000000000000# 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 # # 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. module Google module Cloud module Translate VERSION = "1.3.0".freeze end end end