mygengo-ruby 1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,37 @@
1
+ myGengo Ruby Library (for the [myGengo API](http://mygengo.com/))
2
+ ========================================================================================================
3
+ Translating your tools and products helps people all over the world access them; this is, of course, a
4
+ somewhat tricky problem to solve. **[myGengo](http://mygengo.com/)** is a service that offers human-translation
5
+ (which is often a higher quality than machine translation), and an API to manage sending in work and watching
6
+ jobs. This is a ruby interface to make using the API simpler (some would say incredibly easy).
7
+
8
+
9
+ Installation & Requirements
10
+ -------------------------------------------------------------------------------------------------------
11
+ Installing myGengo is fairly simple:
12
+
13
+ gem install mygengo
14
+
15
+
16
+ Tests - Running Them, etc
17
+ ------------------------------------------------------------------------------------------------------
18
+ myGengo has a full suite of Unit Tests. To run them, grab the source, head into the mygengo directory,
19
+ and rake the tests:
20
+
21
+ rake test
22
+
23
+
24
+ Question, Comments, Complaints, Praise?
25
+ ------------------------------------------------------------------------------------------------------
26
+ If you have questions or comments and would like to reach us directly, please feel free to do
27
+ so at the following outlets. We love hearing from developers!
28
+
29
+ Email: ryan [at] mygengo dot com
30
+ Twitter: **[@mygengo_dev](http://twitter.com/mygengo_dev)**
31
+
32
+ If you come across any issues, please file them on the **[Github project issue tracker](https://github.com/myGengo/mygengo-ruby/issues)**. Thanks!
33
+
34
+
35
+ Documentation
36
+ ------------------------------------------------------------------------------------------------------
37
+ Coming shortly. :)
@@ -0,0 +1,10 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+
4
+ task :default => :test
5
+
6
+ Rake::TestRake.new do |t|
7
+ t.libs << "test"
8
+ t.test_files = FileList['test/*test.rb']
9
+ t.verbose = true
10
+ end
@@ -0,0 +1,294 @@
1
+ # Encoding: UTF-8
2
+
3
+ require 'rubygems'
4
+ require 'net/http'
5
+ require 'uri'
6
+ require 'cgi'
7
+ require 'json'
8
+ require 'hmac-sha1'
9
+ require 'time'
10
+ require 'pp'
11
+
12
+ module MyGengo
13
+
14
+ # The only real class that ever needs to be instantiated.
15
+ class API
16
+ attr_accessor :api_host
17
+ attr_accessor :debug
18
+ attr_accessor :client_info
19
+
20
+ # Creates a new API handler to shuttle calls/jobs/etc over to the myGengo translation API.
21
+ #
22
+ # Options:
23
+ # <tt>opts</tt> - A hash containing the api key, the api secret key, the API version (defaults to 1), whether to use
24
+ # the sandbox API, and an optional custom user agent to send.
25
+ def initialize(opts)
26
+ # Consider this an example of the object you need to pass.
27
+ @opts = {
28
+ :public_key => '',
29
+ :private_key => '',
30
+ :api_version => '1',
31
+ :sandbox => false,
32
+ :user_agent => "myGengo Ruby Library v#{MyGengo::Config::VERSION}",
33
+ :debug => false,
34
+ }.merge(opts)
35
+
36
+ # Let's go ahead and separate these out, for clarity...
37
+ @debug = @opts[:debug]
38
+ @api_host = (@opts[:sandbox] == true ? MyGengo::Config::SANDBOX_API_HOST : MyGengo::Config::API_HOST) + "v#{@opts[:api_version]}/"
39
+
40
+ # More of a public "check this" kind of object.
41
+ @client_info = {"VERSION" => MyGengo::Config::VERSION}
42
+ end
43
+
44
+ # Creates an HMAC::SHA1 signature, signing the request with the private key.
45
+ def signature_of(params)
46
+ if Hash === params
47
+ sorted_keys = params.keys.sort
48
+ params = sorted_keys.zip(params.values_at(*sorted_keys)).map do |k, v|
49
+ "#{k}=#{CGI::escape(v)}"
50
+ end * '&'
51
+ end
52
+
53
+ # This will be faster, but is more work for an end user to maintain. :(
54
+ #OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), @opts[:private_key], params)
55
+ HMAC::SHA1.hexdigest @opts[:private_key], params
56
+ end
57
+
58
+ # The "GET" method; handles requesting basic data sets from myGengo and converting
59
+ # the response to a Ruby hash/object.
60
+ #
61
+ # Options:
62
+ # <tt>endpoint</tt> - String/URL to request data from.
63
+ # <tt>params</tt> - Data necessary for request (keys, etc). Generally taken care of by the requesting instance.
64
+ def get_from_mygengo(endpoint, params = {})
65
+ # The first part of the object we're going to encode and use in our request to myGengo. The signing process
66
+ # is a little annoying at the moment, so bear with us...
67
+ query = {}
68
+ query["api_key"] = @opts[:public_key]
69
+ query["data"] = params.to_json if !params.empty?
70
+ query["ts"] = Time.now.gmtime.to_i.to_s
71
+
72
+ query.merge!("api_sig" => signature_of(query))
73
+
74
+ endpoint << '?' + query.map { |k, v| "#{k}=#{CGI::escape(v)}" }.join('&')
75
+ api_url = URI.parse(@api_host + endpoint);
76
+
77
+ resp = Net::HTTP.start(api_url.host, api_url.port) do |http|
78
+ puts api_url.request_uri
79
+ http.request(Net::HTTP::Get.new(api_url.request_uri, {
80
+ 'Accept' => 'application/json',
81
+ 'User-Agent' => @opts[:user_agent]
82
+ }))
83
+ end
84
+
85
+ json = JSON.parse(resp.body)
86
+
87
+ if json['opstat'] != 'ok'
88
+ raise MyGengo::Exception.new(json['opstat'], json['err']['code'].to_i, json['err']['msg'])
89
+ end
90
+
91
+ # Return it if there are no problems, nice...
92
+ json
93
+ end
94
+
95
+ # The "POST" method; handles shuttling up encoded job data to myGengo
96
+ # for translation and such. Somewhat similar to the above methods, but depending on the scenario
97
+ # can get some strange exceptions, so we're gonna keep them fairly separate for the time being. Consider
98
+ # for a merger down the road...
99
+ #
100
+ # Options:
101
+ # <tt>endpoint</tt> - String/URL to post data to.
102
+ # <tt>params</tt> - Data necessary for request (keys, etc). Generally taken care of by the requesting instance.
103
+ def send_to_mygengo(endpoint, params = {})
104
+ data = {}
105
+
106
+ # ...strip out job data as we need it.
107
+ if !params[:job].nil?
108
+ data[:job] = {:job => params[:job]}
109
+ elsif !params[:jobs].nil?
110
+ data[:jobs] = {:jobs => params[:jobs]}
111
+ data[:process] = params[:process] if !params[:process].nil?
112
+ data[:as_group] = params[:as_group] if !params[:as_group].nil?
113
+ elsif !params[:comment].nil?
114
+ data[:comment] = params[:comment]
115
+ elsif !params[:update].nil?
116
+ # Less confusing for people. ;P
117
+ data[:update] = params[:action]
118
+ end
119
+
120
+ # The first part of the object we're going to encode and use in our request to myGengo. The signing process
121
+ # is a little annoying at the moment, so bear with us...
122
+ query = {
123
+ "api_key" => @opts[:public_key],
124
+ "ts" => Time.now.gmtime.to_i.to_s
125
+ }
126
+ query["data"] = data if !data.empty?
127
+ query.merge!('api_sig' => signature_of(query.to_json))
128
+
129
+ api_url = URI.parse(@api_host + endpoint);
130
+
131
+ resp = Net::HTTP.start(api_url.host, api_url.port) do |http|
132
+ req = Net::HTTP::Post.new(api_url.request_uri, {
133
+ 'Accept' => 'application/json',
134
+ 'User-Agent' => @opts[:user_agent]
135
+ })
136
+ req.set_form_data query
137
+ http.request(req)
138
+ end
139
+
140
+ json = JSON.parse(resp.body)
141
+
142
+ if json['opstat'] != 'ok'
143
+ raise MyGengo::Exception.new(json['opstat'], json['err']['code'].to_i, json['err']['msg'])
144
+ end
145
+
146
+ # Return it if there are no problems, nice...
147
+ json
148
+ end
149
+
150
+ # Returns a Ruby-hash of the stats for the current account. No arguments required!
151
+ #
152
+ # Options:
153
+ # <tt>None</tt> - N/A
154
+ def getAccountStats(params = {})
155
+ self.get_from_mygengo('account/stats', params)
156
+ end
157
+
158
+ # Returns a Ruby-hash of the balance for the authenticated account. No args required!
159
+ #
160
+ # Options:
161
+ # <tt>None</tt> - N/A
162
+ def getAccountBalance(params = {})
163
+ self.get_from_mygengo('account/balance', params)
164
+ end
165
+
166
+ # Posts a translation job over to myGengo, returns a response indicating whether the submission was
167
+ # successful or not. Param list is quite expansive here, pay attention...
168
+ #
169
+ # Options:
170
+ # <tt>job</tt> - A job is a hash of data describing what you want translated. See the examples included for
171
+ # more information on what this should be. (type/slug/body_src/lc_src/lc_tgt/tier/auto_approve/comment/callback_url/custom_data)
172
+ def postTranslationJob(params = {})
173
+ self.send_to_mygengo('translate/job', params)
174
+ end
175
+
176
+ # Much like the above, but takes a hash titled "jobs" that is multiple jobs, each with their own unique key.
177
+ #
178
+ # Options:
179
+ # <tt>jobs</tt> - "Jobs" is a hash containing further hashes; each further hash is a job. This is best seen in the example code.
180
+ def postTranslationJobs(params = {})
181
+ self.send_to_mygengo('translate/jobs', params)
182
+ end
183
+
184
+ # Updates an already submitted job.
185
+ #
186
+ # Options:
187
+ # <tt>id</tt> - The ID of a job to update.
188
+ # <tt>action</tt> - A hash describing the update to this job. See the examples for further documentation.
189
+ def updateTranslationJob(params = {})
190
+ self.send_to_mygengo('translate/job/:id'.gsub(':id', params.delete(:id)), params)
191
+ end
192
+
193
+ # Given an ID, pulls down information concerning that job from myGengo.
194
+ #
195
+ # <tt>id</tt> - The ID of a job to check.
196
+ # <tt>pre_mt</tt> - Optional, get a machine translation if the human translation is not done.
197
+ def getTranslationJob(params = {})
198
+ self.get_from_mygengo('translate/job/:id'.gsub(':id', params.delete(:id)), params)
199
+ end
200
+
201
+ # Pulls down a list of recently submitted jobs, allows some filters.
202
+ #
203
+ # <tt>status</tt> - Optional. "unpaid", "available", "pending", "reviewable", "approved", "rejected", or "canceled".
204
+ # <tt>timestamp_after</tt> - Optional. Epoch timestamp from which to filter submitted jobs.
205
+ # <tt>count</tt> - Optional. Defaults to 10.
206
+ def getTranslationJobs(params = {})
207
+ self.get_from_mygengo('translate/jobs', params)
208
+ end
209
+
210
+ # Pulls a group of jobs that were previously submitted together.
211
+ #
212
+ # <tt>id</tt> - Required, the ID of a job that you want the batch/group of.
213
+ def getTranslationJobBatch(params = {})
214
+ self.get_from_mygengo('translate/jobs/:id'.gsub(':id', params.delete(:id)), params)
215
+ end
216
+
217
+ # Mirrors the bulk Translation call, but just returns an estimated cost.
218
+ def determineTranslationCost(params = {})
219
+ self.send_to_mygengo('translate/service/quote', params)
220
+ end
221
+
222
+ # Post a comment for a translator or myGengo on a job.
223
+ #
224
+ # Options:
225
+ # <tt>id</tt> - The ID of the job you're commenting on.
226
+ # <tt>comment</tt> - The comment to put on the job.
227
+ def postTranslationJobComment(params = {})
228
+ self.send_to_mygengo('translate/job/:id/comment'.gsub(':id', params.delete(:id)), params)
229
+ end
230
+
231
+ # Get all comments (the history) from a given job.
232
+ #
233
+ # Options:
234
+ # <tt>id</tt> - The ID of the job to get comments for.
235
+ def getTranslationJobComments(params = {})
236
+ self.get_from_mygengo('translate/job/:id/comments'.gsub(':id', params.delete(:id)), params)
237
+ end
238
+
239
+ # Returns the feedback you've submitted for a given job.
240
+ #
241
+ # Options:
242
+ # <tt>id</tt> - The ID of the translation job you're retrieving comments from.
243
+ def getTranslationJobFeedback(params = {})
244
+ self.get_from_mygengo('translate/job/:id/feedback'.gsub(':id', params.delete(:id)), params)
245
+ end
246
+
247
+ # Gets a list of the revision resources for a job. Revisions are created each time a translator updates the text.
248
+ #
249
+ # Options:
250
+ # <tt>id</tt> - The ID of the translation job you're getting revisions from.
251
+ def getTranslationJobRevisions(params = {})
252
+ self.get_from_mygengo('translate/job/:id/revisions'.gsub(':id', params.delete(:id)), params)
253
+ end
254
+
255
+ # Get a specific revision to a job.
256
+ #
257
+ # Options:
258
+ # <tt>id</tt> - The ID of the translation job you're getting revisions from.
259
+ # <tt>rev_id</tt> - The ID of the revision you're looking up.
260
+ def getTranslationJobRevision(params = {})
261
+ self.get_from_mygengo('translate/job/:id/revisions/:revision_id'.gsub(':id', params.delete(:id)).gsub(':rev_id', params.delete(:rev_id)), params)
262
+ end
263
+
264
+ # Returns a preview image for a job.
265
+ #
266
+ # Options:
267
+ # <tt>id</tt> - The ID of the job you want a preview image of.
268
+ def getTranslationJobPreviewImage(params = {})
269
+ self.get_from_mygengo('translate/job/:id/preview'.gsub(':id', params.delete(:id)), params)
270
+ end
271
+
272
+ # Deletes a job.
273
+ #
274
+ # Options:
275
+ # <tt>id</tt> - The ID of the job you want to delete.
276
+ def deleteTranslationJob(params = {})
277
+ self.send_to_mygengo('translate/job/:id'.gsub(':id', params.delete(:id)), params)
278
+ end
279
+
280
+ # Gets information about currently supported language pairs.
281
+ #
282
+ # Options:
283
+ # <tt>lc_src</tt> - Optional language code to filter on.
284
+ def getServiceLanguagePairs(params = {})
285
+ self.get_from_mygengo('translate/service/language_pairs', params)
286
+ end
287
+
288
+ # Pulls down currently supported languages.
289
+ def getServiceLanguages(params = {})
290
+ self.get_from_mygengo('translate/service/languages', params)
291
+ end
292
+ end
293
+
294
+ end
@@ -0,0 +1,15 @@
1
+ module MyGengo
2
+ # Base Exception class and such.
3
+ class MyGengo::Exception < ::StandardError
4
+ attr_accessor :opstat, :code, :msg
5
+
6
+ # Pretty self explanatory stuff here...
7
+ def initialize(opstat, code, msg)
8
+ @opstat = opstat
9
+ @code = code
10
+ @msg = msg
11
+
12
+ puts msg
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ require 'mygengo-ruby/api_handler'
2
+ require 'mygengo-ruby/mygengo_exception'
3
+
4
+ module MyGengo
5
+ # Store global config objects here - e.g, urls, etc.
6
+ module Config
7
+ # API url endpoints; replace the version at function call time to
8
+ # allow for function-by-function differences in versioning.
9
+ API_HOST = 'http://api.mygengo.com/'
10
+ SANDBOX_API_HOST = 'http://api.sandbox.mygengo.com/'
11
+
12
+ # Pretty self explanatory.
13
+ VERSION = 1.0
14
+ end
15
+ end
@@ -0,0 +1,18 @@
1
+ All code provided from the http://mygengo.com site, such as API example code and libraries, is provided under the New BSD license unless otherwise noted. Details are below.
2
+
3
+ New BSD License
4
+ Copyright (c) 2009-2011, myGengo, Inc.
5
+ All rights reserved.
6
+
7
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
8
+
9
+ Redistributions of source code must retain the above copyright notice,
10
+ this list of conditions and the following disclaimer.
11
+ Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+ Neither the name of myGengo, Inc. nor the names of its contributors may
15
+ be used to endorse or promote products derived from this software
16
+ without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
metadata ADDED
@@ -0,0 +1,73 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mygengo-ruby
3
+ version: !ruby/object:Gem::Version
4
+ hash: 15
5
+ prerelease: false
6
+ segments:
7
+ - 1
8
+ - 0
9
+ version: "1.0"
10
+ platform: ruby
11
+ authors:
12
+ - Ryan McGrath <ryan@mygengo.com>
13
+ - Matthew Romaine <matt@mygengo.com>
14
+ - Kim Ahlstrom
15
+ autorequire:
16
+ bindir: bin
17
+ cert_chain: []
18
+
19
+ date: 2011-05-10 00:00:00 +09:00
20
+ default_executable:
21
+ dependencies: []
22
+
23
+ description: myGengo is a service that offers various translation API, both machine and high quality human-sourced translation based. ruby-mygengo lets you interface with the myGengo REST API (http://mygengo.com/services/api/dev-docs/).
24
+ email: ryan@mygengo.com
25
+ executables: []
26
+
27
+ extensions: []
28
+
29
+ extra_rdoc_files: []
30
+
31
+ files:
32
+ - lib/mygengo-ruby/api_handler.rb
33
+ - lib/mygengo-ruby/mygengo_exception.rb
34
+ - lib/mygengo.rb
35
+ - licenses/LICENSE.txt
36
+ - Rakefile
37
+ - README.md
38
+ has_rdoc: true
39
+ homepage: https://github.com/myGengo/mygengo-ruby
40
+ licenses: []
41
+
42
+ post_install_message:
43
+ rdoc_options: []
44
+
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ none: false
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ hash: 3
53
+ segments:
54
+ - 0
55
+ version: "0"
56
+ required_rubygems_version: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ hash: 3
62
+ segments:
63
+ - 0
64
+ version: "0"
65
+ requirements: []
66
+
67
+ rubyforge_project:
68
+ rubygems_version: 1.3.7
69
+ signing_key:
70
+ specification_version: 3
71
+ summary: A library for interfacing with the myGengo API.
72
+ test_files: []
73
+