google-cloud-translate-v2 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,180 @@
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ require "google/cloud/translate/v2/api"
17
+ require "google/cloud/translate/v2/version"
18
+ require "google/cloud" unless defined? Google::Cloud.new
19
+ require "google/cloud/env"
20
+
21
+ module Google
22
+ module Cloud
23
+ module Translate
24
+ ##
25
+ # # Google Cloud Translation API
26
+ #
27
+ # [Google Cloud Translation API](https://cloud.google.com/translation/)
28
+ # provides a simple, programmatic interface for translating an arbitrary
29
+ # string into any supported language. It is highly responsive, so websites
30
+ # and applications can integrate with Translation API for fast, dynamic
31
+ # translation of source text. Language detection is also available in cases
32
+ # where the source language is unknown.
33
+ #
34
+ # Translation API supports more than one hundred different languages, from
35
+ # Afrikaans to Zulu. Used in combination, this enables translation between
36
+ # thousands of language pairs. Also, you can send in HTML and receive HTML
37
+ # with translated text back. You don't need to extract your source text or
38
+ # reassemble the translated content.
39
+ #
40
+ module V2
41
+ ##
42
+ # Creates a new object for connecting to Cloud Translation API. Each call creates a new connection.
43
+ #
44
+ # Like other Cloud Platform services, Google Cloud Translation API supports authentication using a project ID
45
+ # and OAuth 2.0 credentials. In addition, it supports authentication using a public API access key. (If both the
46
+ # API key and the project and OAuth 2.0 credentials are provided, the API key will be used.) Instructions and
47
+ # configuration options are covered in the {file:AUTHENTICATION.md Authentication Guide}.
48
+ #
49
+ # @param [String] project_id Project identifier for the Cloud Translation service you are connecting to. If not
50
+ # present, the default project for the credentials is used.
51
+ # @param [String, Hash, Google::Auth::Credentials] credentials The path to the keyfile as a String, the contents
52
+ # of the keyfile as a Hash, or a Google::Auth::Credentials object. (See {Translate::V2::Credentials})
53
+ # @param [String] key a public API access key (not an OAuth 2.0 token)
54
+ # @param [String, Array<String>] scope The OAuth 2.0 scopes controlling the set of resources and operations that
55
+ # the connection can access. See [Using OAuth 2.0 to Access Google
56
+ # APIs](https://developers.google.com/identity/protocols/OAuth2).
57
+ #
58
+ # The default scope is:
59
+ #
60
+ # * `https://www.googleapis.com/auth/cloud-platform`
61
+ # @param [Integer] retries Number of times to retry requests on server error. The default value is `3`.
62
+ # Optional.
63
+ # @param [Integer] timeout Default timeout to use in requests. Optional.
64
+ # @param [String] endpoint Override of the endpoint host name. Optional. If the param is nil, uses the default
65
+ # endpoint.
66
+ #
67
+ # @return [Google::Cloud::Translate::V2::Api]
68
+ #
69
+ # @example
70
+ # require "google/cloud/translate/v2"
71
+ #
72
+ # translate = Google::Cloud::Translate::V2.new(
73
+ # version: :v2,
74
+ # project_id: "my-todo-project",
75
+ # credentials: "/path/to/keyfile.json"
76
+ # )
77
+ #
78
+ # translation = translate.translate "Hello world!", to: "la"
79
+ # translation.text #=> "Salve mundi!"
80
+ #
81
+ # @example Using API Key.
82
+ # require "google/cloud/translate/v2"
83
+ #
84
+ # translate = Google::Cloud::Translate::V2.new(
85
+ # key: "api-key-abc123XYZ789"
86
+ # )
87
+ #
88
+ # translation = translate.translate "Hello world!", to: "la"
89
+ # translation.text #=> "Salve mundi!"
90
+ #
91
+ # @example Using API Key from the environment variable.
92
+ # require "google/cloud/translate/v2"
93
+ #
94
+ # ENV["TRANSLATE_KEY"] = "api-key-abc123XYZ789"
95
+ #
96
+ # translate = Google::Cloud::Translate::V2.new
97
+ #
98
+ # translation = translate.translate "Hello world!", to: "la"
99
+ # translation.text #=> "Salve mundi!"
100
+ #
101
+ def self.new project_id: nil, credentials: nil, key: nil, scope: nil, retries: nil, timeout: nil, endpoint: nil
102
+ project_id ||= default_project_id
103
+
104
+ configuration = translation_config
105
+ key ||= configuration&.key || ENV["TRANSLATE_KEY"] || ENV["GOOGLE_CLOUD_KEY"]
106
+ retries ||= configuration&.retries
107
+ timeout ||= configuration&.timeout
108
+ endpoint ||= configuration&.endpoint
109
+
110
+ if key
111
+ return Google::Cloud::Translate::V2::Api.new(
112
+ Google::Cloud::Translate::V2::Service.new(
113
+ project_id.to_s, nil, retries: retries, timeout: timeout, key: key, host: endpoint
114
+ )
115
+ )
116
+ end
117
+
118
+ scope ||= configuration&.scope
119
+ credentials ||= default_credentials scope: scope
120
+
121
+ unless credentials.is_a? Google::Auth::Credentials
122
+ credentials = Google::Cloud::Translate::V2::Credentials.new credentials, scope: scope
123
+ end
124
+
125
+ project_id = resolve_project_id project_id, credentials
126
+ raise ArgumentError, "project_id is missing" if project_id.empty?
127
+
128
+ Google::Cloud::Translate::V2::Api.new(
129
+ Google::Cloud::Translate::V2::Service.new(
130
+ project_id, credentials, retries: retries, timeout: timeout, host: endpoint
131
+ )
132
+ )
133
+ end
134
+
135
+ ##
136
+ # @private Default project.
137
+ def self.default_project_id
138
+ translation_config&.project_id ||
139
+ ENV["TRANSLATE_PROJECT"] ||
140
+ Google::Cloud.configure.project_id ||
141
+ Google::Cloud.env.project_id
142
+ end
143
+
144
+ ##
145
+ # @private Default credentials.
146
+ def self.default_credentials scope: nil
147
+ translation_config&.credentials ||
148
+ Google::Cloud::Config.credentials_from_env(
149
+ "TRANSLATE_CREDENTIALS", "TRANSLATE_CREDENTIALS_JSON", "TRANSLATE_KEYFILE", "TRANSLATE_KEYFILE_JSON"
150
+ ) ||
151
+ Google::Cloud.configure.credentials ||
152
+ Google::Cloud::Translate::V2::Credentials.default(scope: scope)
153
+ end
154
+
155
+ ##
156
+ # @private Default configuration.
157
+ def self.default_config
158
+ Google::Cloud.configure
159
+ end
160
+
161
+ ##
162
+ # @private Resolve project.
163
+ def self.resolve_project_id project_id, credentials
164
+ # Always cast to a string
165
+ return project_id.to_s unless credentials.respond_to? :project_id
166
+
167
+ # Always cast to a string
168
+ project_id || credentials.project_id.to_s
169
+ end
170
+
171
+ ##
172
+ # @private The global config from google-cloud-translate, or nil if not available
173
+ def self.translation_config
174
+ return nil unless Google::Cloud.configure.subconfig? :translate
175
+ Google::Cloud.configure.translate
176
+ end
177
+ end
178
+ end
179
+ end
180
+ end
@@ -0,0 +1,254 @@
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ require "google/cloud/translate/v2/service"
17
+ require "google/cloud/translate/v2/translation"
18
+ require "google/cloud/translate/v2/detection"
19
+ require "google/cloud/translate/v2/language"
20
+
21
+ module Google
22
+ module Cloud
23
+ module Translate
24
+ module V2
25
+ ##
26
+ # # Api
27
+ #
28
+ # Represents top-level access to the Google Cloud Translation API. Translation API supports more than one
29
+ # hundred different languages, from Afrikaans to Zulu. Used in combination, this enables translation between
30
+ # thousands of language pairs. Also, you can send in HTML and receive HTML with translated text back. You don't
31
+ # need to extract your source text or reassemble the translated content.
32
+ #
33
+ # @see https://cloud.google.com/translation/docs/getting-started Cloud Translation API Quickstart
34
+ #
35
+ # @example
36
+ # require "google/cloud/translate/v2"
37
+ #
38
+ # translate = Google::Cloud::Translate::V2.new
39
+ #
40
+ # translation = translate.translate "Hello world!", to: "la"
41
+ #
42
+ # translation.to_s #=> "Salve mundi!"
43
+ #
44
+ # translation.from #=> "en"
45
+ # translation.origin #=> "Hello world!"
46
+ # translation.to #=> "la"
47
+ # translation.text #=> "Salve mundi!"
48
+ #
49
+ class Api
50
+ ##
51
+ # @private The Service object.
52
+ attr_accessor :service
53
+
54
+ ##
55
+ # @private Creates a new Api instance.
56
+ #
57
+ # See {Google::Cloud.translate}
58
+ def initialize service
59
+ @service = service
60
+ end
61
+
62
+ ##
63
+ # The Cloud Translation API project connected to.
64
+ #
65
+ # @example
66
+ # require "google/cloud/translate/v2"
67
+ #
68
+ # translate = Google::Cloud::Translate::V2.new(
69
+ # project_id: "my-todo-project",
70
+ # credentials: "/path/to/keyfile.json"
71
+ # )
72
+ #
73
+ # translate.project_id #=> "my-todo-project"
74
+ #
75
+ def project_id
76
+ service.project_id
77
+ end
78
+ alias project project_id
79
+
80
+ ##
81
+ # Returns text translations from one language to another.
82
+ #
83
+ # @see https://cloud.google.com/translation/docs/translating-text#Translate Translating Text
84
+ #
85
+ # @param [String] text The text or texts to translate.
86
+ # @param [String] to The target language into which the text should be translated. This is required. The value
87
+ # must be an [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code.
88
+ # @param [String] from The source language of the text or texts. This is an [ISO
89
+ # 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code. This is optional.
90
+ # @param [String] format The format of the text. Possible values include `:text` and `:html`. This is
91
+ # optional. The Translation API default is `:html`.
92
+ # @param [String] model The model used by the service to perform the translation. Can be either `base` to use
93
+ # the Phrase-Based Machine Translation (PBMT) model, or `nmt` to use the Neural Machine Translation (NMT)
94
+ # model. The default is `nmt`.
95
+ #
96
+ # If the model is `nmt`, and the requested language translation pair is not supported for the NMT model,
97
+ # then the request is translated using the PBMT model.
98
+ #
99
+ # @param [String] cid The customization id for translate. This is optional.
100
+ #
101
+ # @return [Translation, Array<Translation>] A single {Translation} object if just one text was given, or an
102
+ # array of {Translation} objects if multiple texts were given.
103
+ #
104
+ # @example
105
+ # require "google/cloud/translate/v2"
106
+ #
107
+ # translate = Google::Cloud::Translate::V2.new
108
+ #
109
+ # translation = translate.translate "Hello world!", to: "la"
110
+ #
111
+ # translation.to_s #=> "Salve mundi!"
112
+ #
113
+ # translation.detected? #=> true
114
+ # translation.from #=> "en"
115
+ # translation.origin #=> "Hello world!"
116
+ # translation.to #=> "la"
117
+ # translation.text #=> "Salve mundi!"
118
+ # translation.model #=> "base"
119
+ #
120
+ # @example Using the neural machine translation model:
121
+ # require "google/cloud/translate/v2"
122
+ #
123
+ # translate = Google::Cloud::Translate::V2.new
124
+ #
125
+ # translation = translate.translate "Hello world!",
126
+ # to: "la", model: "nmt"
127
+ #
128
+ # translation.to_s #=> "Salve mundi!"
129
+ # translation.model #=> "nmt"
130
+ #
131
+ # @example Setting the `from` language.
132
+ # require "google/cloud/translate/v2"
133
+ #
134
+ # translate = Google::Cloud::Translate::V2.new
135
+ #
136
+ # translation = translate.translate "Hello world!",
137
+ # from: :en, to: :la
138
+ # translation.detected? #=> false
139
+ # translation.text #=> "Salve mundi!"
140
+ #
141
+ # @example Retrieving multiple translations.
142
+ # require "google/cloud/translate/v2"
143
+ #
144
+ # translate = Google::Cloud::Translate::V2.new
145
+ #
146
+ # translations = translate.translate "Hello my friend.",
147
+ # "See you soon.",
148
+ # from: "en", to: "la"
149
+ # translations.count #=> 2
150
+ # translations[0].text #=> "Salve amice."
151
+ # translations[1].text #=> "Vide te mox."
152
+ #
153
+ # @example Preserving HTML tags.
154
+ # require "google/cloud/translate/v2"
155
+ #
156
+ # translate = Google::Cloud::Translate::V2.new
157
+ #
158
+ # translation = translate.translate "<strong>Hello</strong> world!",
159
+ # to: :la
160
+ # translation.text #=> "<strong>Salve</strong> mundi!"
161
+ #
162
+ def translate *text, to: nil, from: nil, format: nil, model: nil, cid: nil
163
+ return nil if text.empty?
164
+ raise ArgumentError, "to is required" if to.nil?
165
+ to = to.to_s
166
+ from = from.to_s if from
167
+ format = format.to_s if format
168
+ text = Array(text).flatten
169
+ gapi = service.translate text, to: to, from: from, format: format, model: model, cid: cid
170
+ Translation.from_gapi_list gapi, text, to, from
171
+ end
172
+
173
+ ##
174
+ # Detect the most likely language or languages of a text or multiple texts.
175
+ #
176
+ # @see https://cloud.google.com/translation/docs/detecting-language Detecting Language
177
+ #
178
+ # @param [String] text The text or texts upon which language detection should be performed.
179
+ #
180
+ # @return [Detection, Array<Detection>] A single {Detection} object if just one text was given, or an array
181
+ # of {Detection} objects if multiple texts were given.
182
+ #
183
+ # @example
184
+ # require "google/cloud/translate/v2"
185
+ #
186
+ # translate = Google::Cloud::Translate::V2.new
187
+ #
188
+ # detection = translate.detect "Hello world!"
189
+ # detection.language #=> "en"
190
+ # detection.confidence #=> 0.7100697
191
+ #
192
+ # @example Detecting multiple texts.
193
+ # require "google/cloud/translate/v2"
194
+ #
195
+ # translate = Google::Cloud::Translate::V2.new
196
+ #
197
+ # detections = translate.detect "Hello world!",
198
+ # "Bonjour le monde!"
199
+ # detections.count #=> 2
200
+ # detections.first.language #=> "en"
201
+ # detections.first.confidence #=> 0.7100697
202
+ # detections.last.language #=> "fr"
203
+ # detections.last.confidence #=> 0.40440267
204
+ #
205
+ def detect *text
206
+ return nil if text.empty?
207
+ text = Array(text).flatten
208
+ gapi = service.detect text
209
+ Detection.from_gapi gapi, text
210
+ end
211
+
212
+ ##
213
+ # List the languages supported by the API. These are the languages to and from which text can be translated.
214
+ #
215
+ # @see https://cloud.google.com/translation/docs/discovering-supported-languages
216
+ # Discovering Supported Languages
217
+ #
218
+ # @param [String] language The language and collation in which the names of the languages are returned. If
219
+ # this is `nil` then no names are returned.
220
+ #
221
+ # @return [Array<Language>] An array of {Language} objects supported by the API.
222
+ #
223
+ # @example
224
+ # require "google/cloud/translate/v2"
225
+ #
226
+ # translate = Google::Cloud::Translate::V2.new
227
+ #
228
+ # languages = translate.languages
229
+ # languages.count #=> 104
230
+ #
231
+ # english = languages.detect { |l| l.code == "en" }
232
+ # english.name #=> nil
233
+ #
234
+ # @example Get all languages with their names in French.
235
+ # require "google/cloud/translate/v2"
236
+ #
237
+ # translate = Google::Cloud::Translate::V2.new
238
+ #
239
+ # languages = translate.languages "fr"
240
+ # languages.count #=> 104
241
+ #
242
+ # english = languages.detect { |l| l.code == "en" }
243
+ # english.name #=> "Anglais"
244
+ #
245
+ def languages language = nil
246
+ language = language.to_s if language
247
+ gapi = service.languages language
248
+ Array(gapi["languages"]).map { |g| Language.from_gapi g }
249
+ end
250
+ end
251
+ end
252
+ end
253
+ end
254
+ end
@@ -0,0 +1,58 @@
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ require "googleauth"
17
+
18
+ module Google
19
+ module Cloud
20
+ module Translate
21
+ module V2
22
+ ##
23
+ # # Credentials
24
+ #
25
+ # Represents the authentication and authorization used to connect to the Cloud Translation API.
26
+ #
27
+ # @example
28
+ # require "google/cloud/translate/v2"
29
+ #
30
+ # keyfile = "/path/to/keyfile.json"
31
+ # creds = Google::Cloud::Translate::V2::Credentials.new keyfile
32
+ #
33
+ # translate = Google::Cloud::Translate.new(
34
+ # version: :v2,
35
+ # project_id: "my-todo-project",
36
+ # credentials: creds
37
+ # )
38
+ #
39
+ # translate.project_id #=> "my-todo-project"
40
+ #
41
+ class Credentials < Google::Auth::Credentials
42
+ SCOPE = ["https://www.googleapis.com/auth/cloud-platform"].freeze
43
+ PATH_ENV_VARS = ["TRANSLATE_CREDENTIALS",
44
+ "TRANSLATE_KEYFILE",
45
+ "GOOGLE_CLOUD_CREDENTIALS",
46
+ "GOOGLE_CLOUD_KEYFILE",
47
+ "GCLOUD_KEYFILE"].freeze
48
+ JSON_ENV_VARS = ["TRANSLATE_CREDENTIALS_JSON",
49
+ "TRANSLATE_KEYFILE_JSON",
50
+ "GOOGLE_CLOUD_CREDENTIALS_JSON",
51
+ "GOOGLE_CLOUD_KEYFILE_JSON",
52
+ "GCLOUD_KEYFILE_JSON"].freeze
53
+ DEFAULT_PATHS = ["~/.config/gcloud/application_default_credentials.json"].freeze
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end