watson-api-client 0.0.5 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 80d9217a623965243bfff5dc95daf624318a0460
4
- data.tar.gz: eb67925572e32a0e57740abbb181cc51df8b1ed4
3
+ metadata.gz: e5e285ac79001c2c4aef924bba1340704bdda499
4
+ data.tar.gz: 3d88b4815e9e59be39c56b3630696ecdedf2341c
5
5
  SHA512:
6
- metadata.gz: 0ec54a0d0c8a1e9a3f9f9707e6b04d73e6169c44d530e0cbfa5f4822d7d7b9b7a1458a391b9211677b3a6bc194aa68260cd0f2c4a06c773f743b750ed563d828
7
- data.tar.gz: 56946b3c2b36ce78a83e553a4a66c8483d64dfdf313b9d42fef734965a2fdc73e5e6eb77f5af63694e1965a07b8e26fabdb37ae6334ba93c2f100a435236cbd3
6
+ metadata.gz: 26a89836acaa337531ff177e4a7fc80a9c3c39f382d136f930493a032d300f47f1deace4a4d048934cf4c40977145e7fbcf6ce2bf3e2f8bb101bd244a397e63d
7
+ data.tar.gz: 7161b31c3ff8f87ce4a11b07b2be6505c012e21f83692fb436cfc9f1fcb2f83db89813b330c7301fa285f190ddfe5fa254db98105b4b98e10f5b81007a81eee3
@@ -1,6 +1,6 @@
1
- language: ruby
2
- rvm:
3
- - 2.2.0
4
- - 2.1
5
- - 2.0
6
- script: "ruby lib/watson-api-client.rb"
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.0
4
+ - 2.1
5
+ - 2.0
6
+ script: "ruby lib/watson-api-client.rb"
data/Gemfile CHANGED
@@ -1,3 +1,3 @@
1
- source 'https://rubygems.org'
2
-
3
- gem 'rest-client'
1
+ source 'https://rubygems.org'
2
+
3
+ gem 'rest-client'
data/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2015 Takashi SUGA <suchowan@box.email.ne.jp>.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Takashi SUGA <suchowan@box.email.ne.jp>.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md CHANGED
@@ -1,143 +1,163 @@
1
- watson-api-client - An IBM Watson™ API client
2
- ================================================================
3
-
4
- [![Gem Version](https://badge.fury.io/rb/watson-api-client.svg)](http://badge.fury.io/rb/watson-api-client)
5
- [![Build Status](https://travis-ci.org/blueboxjesse/watson-api-client.svg?branch=master)](https://travis-ci.org/blueboxjesse/watson-api-client)
6
-
7
- The [watson-api-client](http://rubygems.org/gems/watson-api-client) is a gem to use REST API on the IBM Watson™ Developer Cloud.
8
-
9
- It wraps the [rest-client](https://rubygems.org/gems/rest-client) REST API using [Swagger](http://swagger.io/) documents retrievable from the [Watson API Reference](https://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/).
10
-
11
-
12
- Installation
13
- ------------
14
-
15
- The watson-api-client gem can be installed by running:
16
-
17
- gem install watson-api-client
18
-
19
- Since watson-api-client is dependent on the rest-client, when the rest-client is not installed, the rest-client is also installed automatically.
20
-
21
-
22
- Documentation
23
- -------------
24
-
25
- The simple API documentation for the watson-api-client is available on [RubyDoc.info](http://rubydoc.info/gems/watson-api-client).
26
-
27
- However, most of the classes and methods of this gem are not described in the above document because they are dynamically defined.
28
- Instead, you can output to the standard output the actual those list of classes and methods when you run the lib/watson-api-client.rb directly, or
29
- you can also use the following method to view a list of known APIs:
30
-
31
- ```
32
- require 'watson-api-client'
33
-
34
- puts WatsonAPIClient::AvailableAPIs
35
- ```
36
-
37
- Source Code
38
- -----------
39
-
40
- The source code for the watson-api-client is available on [GitHub](https://github.com/suchowan/watson-api-client).
41
-
42
-
43
- Example Usage
44
- -------------
45
-
46
- ###Preparation
47
-
48
- The watson-api-client is a gem to use REST API on the IBM Watson™ Developer Cloud.
49
- To enable these API, you have to do the user registration to the IBM Bluemix™ beforehand, make the services effective, and be relating them to your application.
50
- For more information, refer to 'Getting Started' in '[Table of Contents for Services Documentation](http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/)'.
51
-
52
- ###Relationship Extraction example
53
-
54
- Let's use the 'Relationship Extraction' service.
55
-
56
- require 'watson-api-client'
57
- service = WatsonAPIClient::RelationshipExtraction.new(:user=>"xxxxxx",
58
- :password=>"yyyyy",
59
- :verify_ssl=>OpenSSL::SSL::VERIFY_NONE)
60
- result = service.extract('rt' => 'json',
61
- 'sid' => 'ie-en-news',
62
- 'txt' => 'John Smith lives in New York, and he has been living there since 2001.')
63
- p JSON.parse(result.body)
64
-
65
- ####Generation of the RelationshipExtraction service object
66
- First of all, the instance of the RelationshipExtraction class has to be generated.
67
- The constructor argument is passed to the constructor of [RestClient::Resource](http://www.rubydoc.info/gems/rest-client/RestClient/Resource) class.
68
- Please refer to the document of the rest-client for the details of this hash argument.
69
-
70
- Class name called RelationshipExtraction is the camel case-ized service name of [Watson API Reference](http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/).
71
- :user and :password are the 'username' and the 'password' picked out from environment variable VCAP_SERVICES.
72
- Please refer to '[Viewing Bluemix environment variables](http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/getting_started/gs-bluemix.shtml#vcapViewing)' for the details of VCAP_SERVICES.
73
-
74
- However, when no server application associated with the service exists, 'Show Credentials' link does not appear on the console window.
75
- Therefore, it is necessary to start up a server application even if it is a dummy.
76
-
77
- If the server application is a Ruby on Rails application that require 'watson-api-client', and if it is deployed on the Cloud Foundry, the watson-api-client can read environment variable VCAP_SERVICES directly.
78
- In this case, the specification of :user and :password is omissible.
79
-
80
- ####Extraction of relationship in an example sentence using RelationshipExtraction#extract
81
- Next, by the 'extract' method of the RelationshipExtraction class, we try to extract relationship in an example sentence.
82
- How to set the argument can be seen by clicking on the 'Expand Operations' link of the Watson API Reference 'Relationship Extraction'.
83
- The method name called 'extract' is the nickname corresponding to 'POST /v1/sire/0'.
84
- This can be seen by opening the JSON code of Swagger by clicking on the '[Raw](http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/listings/relationship-extraction)' link of the 'Relationship Extraction' of API Reference window.
85
-
86
- The list of the method of the RelationshipExtraction class can be seen even by using the following script.
87
-
88
- p WatsonAPIClient::RelationshipExtraction::API['digest']
89
-
90
- Since 'json' is specified as Return type ('rt') in this example, the JSON string is stored in the body of the 'extract' method response.
91
- When converting this JSON string to a hash object using JSON.parse method, the result of Relationship Extraction can be used variously by your client programs.
92
-
93
- ###Personality Insights example
94
-
95
- Next, let's use 'Personality Insights'.
96
-
97
- service = WatsonAPIClient::PersonalityInsights.new(:user=>"xxxxxx",
98
- :password=>"yyyyy",
99
- :verify_ssl=>OpenSSL::SSL::VERIFY_NONE)
100
- result = service.profile(
101
- 'Content-Type' => "text/plain",
102
- 'Accept' => "application/json",
103
- 'Accept-Language' => "en",
104
- 'Content-Language' => "en",
105
- 'body' => open('https://raw.githubusercontent.com/suchowan/watson-api-client/master/LICENSE',
106
- :ssl_verify_mode=>OpenSSL::SSL::VERIFY_NONE))
107
- p JSON.parse(result.body)
108
-
109
- The class name, the method name, and the argument setting rules are the same as that of the case of 'Relationship Extraction' almost.
110
- The rest-client and the watson-api-client judge which of path, query, header, body each argument is used for automatically.
111
-
112
- Additional note at the release of the version 0.0.3
113
- -------
114
- The documents which 'watson-api-client' referred to have changed in [February 2016](https://github.com/suchowan/watson-api-client/issues/1).
115
-
116
-
117
- (1) The JSON file which held the list of APIs emptied.
118
-
119
- (2) The version of Swagger which describes API specifications went up from 1.2 to 2.0.
120
-
121
-
122
- They may be linked to the release of the IBM Watson for Japanese language.
123
-
124
- The new version 0.0.3 corresponding to them was released provisionally.
125
- Concerning about (1) in the version 0.0.3, the locations of JSON files which describe API specification are acquired from contents of web pages for human using regular expressions.
126
-
127
- Essentially, as well as former versions, the location of the API documents should be readable with JSON file.
128
- I will request to the IBM to revive the JSON file which held the list of APIs.
129
-
130
- At present this gem is an alpha version and only the normal behavior of RelationshipExtraction and PersonalityInsights are confirmed.
131
- It is welcome when you can cooperate with the confirmation of other various functions.
132
-
133
-
134
- Credits
135
- -------
136
- Copyright (c) 2015-2016 [Takashi SUGA](http://hosi.org/TakashiSuga.ttl)
137
-
138
-
139
- Legal
140
- -------
141
- The watson-api-client is released under the MIT license, see [LICENSE](https://github.com/suchowan/watson-api-client/blob/master/LICENSE) for details.
142
-
143
- IBM Watson™ and IBM Bluemix™ are trade marks of the IBM corporation.
1
+ watson-api-client - An IBM Watson™ API client
2
+ ================================================================
3
+
4
+ [![Gem Version](https://badge.fury.io/rb/watson-api-client.svg)](http://badge.fury.io/rb/watson-api-client)
5
+ [![Build Status](https://travis-ci.org/blueboxjesse/watson-api-client.svg?branch=master)](https://travis-ci.org/blueboxjesse/watson-api-client)
6
+
7
+ The [watson-api-client](http://rubygems.org/gems/watson-api-client) is a gem to use REST API on the IBM Watson™ Developer Cloud.
8
+
9
+ It wraps the [rest-client](https://rubygems.org/gems/rest-client) REST API using [Swagger](http://swagger.io/) documents retrievable from the [Watson API Reference](https://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/).
10
+
11
+
12
+ Installation
13
+ ------------
14
+
15
+ The watson-api-client gem can be installed by running:
16
+
17
+ gem install watson-api-client
18
+
19
+ Since watson-api-client is dependent on the rest-client, when the rest-client is not installed, the rest-client is also installed automatically.
20
+
21
+
22
+ Documentation
23
+ -------------
24
+
25
+ The simple API documentation for the watson-api-client is available on [RubyDoc.info](http://rubydoc.info/gems/watson-api-client).
26
+
27
+ However, most of the classes and methods of this gem are not described in the above document because they are dynamically defined.
28
+ Instead, you can output to the standard output the actual those list of classes and methods when you run the lib/watson-api-client.rb directly, or
29
+ you can also use the following method to view a list of known APIs:
30
+
31
+ ```
32
+ require 'watson-api-client'
33
+
34
+ puts WatsonAPIClient::AvailableAPIs
35
+ ```
36
+
37
+ Source Code
38
+ -----------
39
+
40
+ The source code for the watson-api-client is available on [GitHub](https://github.com/suchowan/watson-api-client).
41
+
42
+
43
+ Example Usage
44
+ -------------
45
+
46
+ ###Preparation
47
+
48
+ The watson-api-client is a gem to use REST API on the IBM Watson™ Developer Cloud.
49
+ To enable these API, you have to do the user registration to the IBM Bluemix™ beforehand, make the services effective, and be relating them to your application.
50
+ For more information, refer to 'Getting Started' in '[Table of Contents for Services Documentation](http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/)'.
51
+
52
+ ###Relationship Extraction example
53
+
54
+ The Watson Relationship Extraction Beta was deprecated on July 27th, 2016, and Relationship Extraction functionality has been merged into AlchemyLanguage.
55
+
56
+ Let's use the [Relationship Extraction functionality in 'AlchemyLanguage'](https://www.ibm.com/watson/developercloud/doc/alchemylanguage/migration.shtml) service.
57
+
58
+ require 'watson-api-client'
59
+ service = WatsonAPIClient::AlchemyLanguage.new(:apikey=>"......",
60
+ :verify_ssl=>OpenSSL::SSL::VERIFY_NONE)
61
+ result = service.URLGetTypedRelations('model' => 'en-news', # model: 'en-news',
62
+ 'url' => 'www.cnn.com', # url: 'www.cnn.com',
63
+ 'outputMode' => 'json') # outputMode: 'json')
64
+ p JSON.parse(result.body)
65
+
66
+ ####Generation of the AlchemyLanguage service object
67
+ First of all, the instance of the AlchemyLanguage class has to be generated.
68
+ The constructor argument is passed to the constructor of [RestClient::Resource](http://www.rubydoc.info/gems/rest-client/RestClient/Resource) class.
69
+ Please refer to the document of the rest-client for the details of this hash argument.
70
+
71
+ Class name called AlchemyLanguage is the camel case-ized service name of [Watson API Reference](http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/).
72
+ :apikey is the 'apikey' picked out from environment variable VCAP_SERVICES.
73
+ Please refer to '[Viewing Bluemix environment variables](http://www.ibm.com/watson/developercloud/doc/getting_started/gs-variables.shtml#vcapServices)' for the details of VCAP_SERVICES.
74
+
75
+ If the server application is a Ruby on Rails application that require 'watson-api-client', and if it is deployed on the Cloud Foundry, the watson-api-client can read environment variable VCAP_SERVICES directly.
76
+ In this case, the specification of :apikey is omissible.
77
+
78
+ ####Extraction of relationship in an example site using AlchemyLanguage#URLGetTypedRelations
79
+ Next, by the 'URLGetTypedRelations' method of the AlchemyLanguage class, we try to extract relationship in an example site.
80
+ How to set the arguments can be seen at Alchemy's [API Reference](https://www.ibm.com/watson/developercloud/alchemy-language/api/v1/#relations).
81
+
82
+ This can be seen by opening the [JSON code of Swagger](https://watson-api-explorer.mybluemix.net/listings/alchemy-language-v1.json).
83
+
84
+ The list of the method of the AlchemyLanguage class can be seen even by using the following script.
85
+
86
+ p WatsonAPIClient::AlchemyLanguage::API['digest']
87
+
88
+ Since 'json' is specified as output mode type ('outputMode') in this example, the JSON string is stored in the body of the 'URLGetTypedRelations' method response.
89
+ When converting this JSON string to a hash object using JSON.parse method, the result of URLGetTypedRelations can be used variously by your client programs.
90
+
91
+ ###Personality Insights example
92
+
93
+ Next, let's use 'Personality Insights'.
94
+
95
+ service = WatsonAPIClient::PersonalityInsights.new(:user=>"xxxxxx",
96
+ :password=>"yyyyy",
97
+ :verify_ssl=>OpenSSL::SSL::VERIFY_NONE)
98
+ result = service.profile(
99
+ 'Content-Type' => "text/plain",
100
+ 'Accept' => "application/json",
101
+ 'Accept-Language' => "en",
102
+ 'Content-Language' => "en",
103
+ 'body' => open('https://raw.githubusercontent.com/suchowan/watson-api-client/master/LICENSE',
104
+ :ssl_verify_mode=>OpenSSL::SSL::VERIFY_NONE))
105
+ p JSON.parse(result.body)
106
+
107
+ The class name, the method name, and the argument setting rules are the same as that of the case of 'AlchemyLanguage' almost.
108
+ The rest-client and the watson-api-client judge which of path, query, header, body each argument is used for automatically.
109
+
110
+ ###Visual Recognition example
111
+
112
+ Last, let's use 'Visual Recognition'.
113
+
114
+ service = WatsonAPIClient::VisualRecognition.new(:api_key=>"...", :version=>'2016-05-20')
115
+ [
116
+ service.detect_faces('url'=>'https://example.com/example.jpg'),
117
+ service.detect_faces('url'=>'https://example.com/example.jpg', :access=>'get'),
118
+ service.detect_faces_get('url'=>'https://example.com/example.jpg'),
119
+ service.detect_faces('images_file' => open('face.png','rb')),
120
+ service.detect_faces('images_file' => open('face.png','rb'), :access=>'post'),
121
+ service.detect_faces_post('images_file' => open('face.png','rb'))
122
+ ].each do |result|
123
+ pp JSON.parse(result.body)
124
+ end
125
+
126
+ Please be careful about the difference in the spellings of :apikey and :api_key.
127
+
128
+ The 'detect_faces' method comes to work in both 'get' access and 'post' access.
129
+ When being ambiguous, it's judged by the kind of designated parameters automatically.
130
+
131
+
132
+ Additional note at the release of the version 0.0.3
133
+ -------
134
+ The documents which 'watson-api-client' referred to have changed in [February 2016](https://github.com/suchowan/watson-api-client/issues/1).
135
+
136
+
137
+ (1) The JSON file which held the list of APIs emptied.
138
+
139
+ (2) The version of Swagger which describes API specifications went up from 1.2 to 2.0.
140
+
141
+
142
+ They may be linked to the release of the IBM Watson for Japanese language.
143
+
144
+ The new version 0.0.3 corresponding to them was released provisionally.
145
+ Concerning about (1) in the version 0.0.3, the locations of JSON files which describe API specification are acquired from contents of web pages for human using regular expressions.
146
+
147
+ Essentially, as well as former versions, the location of the API documents should be readable with JSON file.
148
+ I will request to the IBM to revive the JSON file which held the list of APIs.
149
+
150
+ At present this gem is an alpha version and only the normal behavior of RelationshipExtraction(functionality), PersonalityInsights, and VisualRecognition are confirmed.
151
+ It is welcome when you can cooperate with the confirmation of other various functions.
152
+
153
+
154
+ Credits
155
+ -------
156
+ Copyright (c) 2015-2016 [Takashi SUGA](http://hosi.org/TakashiSuga.ttl)
157
+
158
+
159
+ Legal
160
+ -------
161
+ The watson-api-client is released under the MIT license, see [LICENSE](https://github.com/suchowan/watson-api-client/blob/master/LICENSE) for details.
162
+
163
+ IBM Watson™ and IBM Bluemix™ are trade marks of the IBM corporation.
data/Rakefile CHANGED
@@ -1 +1 @@
1
- require "bundler/gem_tasks"
1
+ require "bundler/gem_tasks"
@@ -6,7 +6,9 @@ require 'pp' if __FILE__ == $PROGRAM_NAME
6
6
 
7
7
  class WatsonAPIClient
8
8
 
9
- VERSION = '0.0.5'
9
+ VERSION = '0.0.6'
10
+
11
+ class Alchemy < self; end
10
12
 
11
13
  class << self
12
14
 
@@ -27,24 +29,12 @@ class WatsonAPIClient
27
29
  rescue OpenURI::HTTPError
28
30
  end
29
31
  end
30
-
32
+
31
33
  # Watson Developercloud
32
34
  host2 = doc_urls[:doc_base2][/^https?:\/\/[^\/]+/]
33
35
  open(doc_urls[:doc_base2], Options, &:read).scan(/<li>\s*<img.+data-src=.+?>\s*<h2><a href="(.+?)".*?>\s*(.+?)\s*<\/a><\/h2>\s*<p>(.+?)<\/p>\s*<\/li>/) do
34
36
  api = {'path'=>$1, 'title'=>$2, 'description'=>$3}
35
- next if api['path'] =~ /\.\./
36
- if apis.key?(api['title'])
37
- apis[api['title']]['description'] = api['description']
38
- else
39
- # Only for Relationship Extraction
40
- open(doc_urls[:doc_base2] + api['path'], Options, &:read).scan(/<li><a href="(.+?)".*?>API\s+explorer<\/a><\/li>/i) do
41
- ref = host2 + $1
42
- open(ref, Options, &:read).scan(/getAbsoluteUrl\("(.+?)"\)/) do
43
- api['path'] = ref.split('/')[0..-2].join('/') + '/' + $1
44
- end
45
- end
46
- apis[api['title']] = api
47
- end
37
+ apis[api['title']]['description'] = api['description'] if api['path'] !~ /\.\./ && apis.key?(api['title'])
48
38
  end
49
39
 
50
40
  apis
@@ -52,23 +42,33 @@ class WatsonAPIClient
52
42
 
53
43
  # for Swagger 2.0
54
44
  def listings(apis)
55
- methods = {}
56
- digest = {}
45
+ methods = Hash.new {|h,k| h[k] = {}}
46
+ digest = Hash.new {|h,k| h[k] = {}}
57
47
  apis['paths'].each_pair do |path, operations|
58
- operations.each_pair do |method, operation|
59
- body = nil
60
- (operation['parameters']||[]).each do |parameter|
61
- next unless parameter['in'] == 'body'
62
- body = parameter['name']
63
- break
48
+ operations.each_pair do |access, operation|
49
+ if operation['parameters']
50
+ (0...operation['parameters'].size).to_a.reverse.each do |index|
51
+ parameter = operation['parameters'][index]
52
+ operation['parameters'][index..index] = apis['parameters'][parameter[parameter.keys.first].split('/').last] if parameter.keys.first == '$ref'
53
+ end
54
+ body = nil
55
+ query = []
56
+ min = []
57
+ max = []
58
+ operation['parameters'].each do |parameter|
59
+ param = parameter['name']
60
+ body ||= param if parameter['in'] == 'body'
61
+ query << param if parameter['in'] == 'query'
62
+ min << param if parameter['required']
63
+ max << param
64
+ end
64
65
  end
65
- if operation['operationId'].nil?
66
- nickname = path
67
- else
68
- nickname = operation['operationId'].sub(/(.)/) {$1.downcase}
66
+ access = access.downcase
67
+ nickname = (operation['operationId'] || path.gsub(/\/\{.+?\}/,'').split('/').last) #.sub(/(.)/) {$1.downcase}
68
+ [nickname, nickname+'_'+access].each do |name|
69
+ methods[name][access] = {'path'=>path, 'operation'=>operation, 'body'=>body, 'query'=>query, 'min'=>min, 'max'=>max}
69
70
  end
70
- methods[nickname] = {'method'=>method, 'path'=>path, 'operation'=>operation, 'body'=>body}
71
- digest[nickname] = {'method'=>method, 'path'=>path, 'summary'=>operation['summary']}
71
+ digest[nickname][access] = {'path'=>path, 'summary'=>operation['summary']}
72
72
  end
73
73
  end
74
74
  {'apis'=>apis, 'methods'=>methods, 'digest'=>digest}
@@ -77,6 +77,7 @@ class WatsonAPIClient
77
77
 
78
78
  api_docs = {
79
79
  :gateway => 'https://gateway.watsonplatform.net',
80
+ :gateway_a => 'https://gateway-a.watsonplatform.net',
80
81
  :doc_base1 => 'https://watson-api-explorer.mybluemix.net/',
81
82
  :doc_base2 => 'http://www.ibm.com/watson/developercloud/doc/',
82
83
  :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE
@@ -88,17 +89,26 @@ class WatsonAPIClient
88
89
  :doc_base1 => api_docs.delete(:doc_base1),
89
90
  :doc_base2 => api_docs.delete(:doc_base2)
90
91
  }
91
-
92
- Gateway = api_docs.delete(:gateway)
92
+ Gateways = {
93
+ :gateway => api_docs.delete(:gateway),
94
+ :gateway_a => api_docs.delete(:gateway_a)
95
+ }
93
96
  Options = api_docs
94
97
  Services = JSON.parse(ENV['VCAP_SERVICES'] || '{}')
98
+ DefaultParams = {:user=>'username', :password=>'password'}
95
99
  AvailableAPIs = []
96
100
 
97
101
  retrieve_doc(doc_urls).each_value do |list|
98
102
  AvailableAPIs << list['title'].gsub(/\s+(.)/) {$1.upcase}
103
+ klass, env =
104
+ case list['title']
105
+ when /^Alchemy/; ['Alchemy', 'alchemy_api' ]
106
+ when /^Visual/ ; ['Alchemy', 'watson_vision_combined' ]
107
+ else ; ['WatsonAPIClient', list['title'].sub(/\s+/,'_').downcase]
108
+ end
99
109
  module_eval %Q{
100
- class #{list['title'].gsub(/\s+(.)/) {$1.upcase}} < self
101
- Service = superclass::Services['#{list['title'].sub(/\s+/,'_').downcase}']
110
+ class #{list['title'].gsub(/\s+(.)/) {$1.upcase}} < #{klass}
111
+ Service = WatsonAPIClient::Services['#{env}']
102
112
  RawDoc = "#{list['path']}"
103
113
 
104
114
  class << self
@@ -106,7 +116,7 @@ class WatsonAPIClient
106
116
 
107
117
  def const_missing(constant)
108
118
  if constant == :API
109
- const_set(:API, listings(JSON.parse(open(RawDoc, superclass::Options, &:read))))
119
+ const_set(:API, listings(JSON.parse(open(RawDoc, WatsonAPIClient::Options, &:read))))
110
120
  else
111
121
  _const_missing(constant)
112
122
  end
@@ -120,52 +130,122 @@ class WatsonAPIClient
120
130
  # All subclass constructors use following hash parameter -
121
131
  #
122
132
  # @param [Hash] options See following..
123
- # @option options [String] :url API URL (default: the url described in listings or VCAP_SERVICES)
124
- # @option options [String] :user USER ID (default: the username described in VCAP_SERVICES)
125
- # @option options [String] :password USER Password (default: the password described in VCAP_SERVICES)
126
- # @option options [Object] other_options Other options are passed to RestClient::Resource.new[http://www.rubydoc.info/gems/rest-client/RestClient/Resource] as it is.
133
+ # @option options [String] :url API URL (default: the url described in listings or VCAP_SERVICES)
134
+ # @option options [String] :user USER ID (default: the username described in VCAP_SERVICES)
135
+ # @option options [String] :password USER Password (default: the password described in VCAP_SERVICES)
136
+ # @option options [String] :apikey or :api_key API key for the Alchemy API (default: the apikey or api_key described in VCAP_SERVICES)
137
+ # @option options [String] :version The release date of the version of the Alchemy API.
138
+ # @option options [Object] other_options Other options are passed to RestClient::Resource.new[http://www.rubydoc.info/gems/rest-client/RestClient/Resource] as it is.
127
139
  #
128
- # @note VCAP_SERVICES[http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/getting_started/gs-bluemix.shtml#vcapViewing] is IBM Bluemix™ environment variable.
140
+ # @note VCAP_SERVICES[http://www.ibm.com/watson/developercloud/doc/getting_started/gs-variables.shtml#vcapServices] is IBM Bluemix™ environment variable.
129
141
  #
130
142
  def initialize(options={})
143
+ define_api_methods
144
+ set_variables(options)
145
+ @url ||= Gateways[:gateway] + self.class::API['apis']['basePath']
146
+ @options = {}
147
+ self.class.superclass::DefaultParams.each_pair do |sym, key|
148
+ @options[sym] = @credential[key] if @credential.key?(key)
149
+ end
150
+ @options.update(options)
151
+ @service = RestClient::Resource.new(@url, @options)
152
+ end
153
+
154
+ private
155
+
156
+ def define_api_methods
131
157
  self.class::API['methods'].each_pair do |method, definition|
132
158
  self.class.module_eval %Q{define_method("#{method}",
133
- Proc.new {|options={}| rest_access_#{definition['body'] ? 'with' : 'without'}_body("#{method}", options)}
159
+ Proc.new {|options={}| rest_access_#{definition.keys.size > 1 ? 'auto_detect' :
160
+ definition[definition.keys.first]['body'] ? 'with_body' :
161
+ 'without_body' }("#{method}", options.dup)}
134
162
  )} unless respond_to?(method)
135
163
  end
136
- credential = self.class::Service ? self.class::Service.first['credentials'] : {}
137
- if options[:url]
138
- @url = options.delete(:url)
139
- elsif credential['url']
140
- @url = credential['url']
141
- else
142
- @url = Gateway + self.class::API['apis']['basePath']
164
+ end
165
+
166
+ def set_variables(options)
167
+ @credential = self.class::Service ? self.class::Service.first['credentials'] : {}
168
+ if options.key?(:url)
169
+ @url = options.delete(:url)
170
+ elsif @credential.key?('url')
171
+ @url = @credential['url']
143
172
  end
144
- @options = {:user=>credential['username'], :password=>credential['password']}.merge(options)
145
- @service = RestClient::Resource.new(@url, @options)
146
173
  end
147
174
 
148
- private
175
+ def rest_access_auto_detect(method, options={})
176
+ definition = self.class::API['methods'][method.to_s]
177
+ options[:access] ||= select_access(definition, options)
178
+ definition[options[:access]]['body'] ?
179
+ rest_access_with_body(method, options) :
180
+ rest_access_without_body(method, options)
181
+ end
149
182
 
150
183
  def rest_access_without_body(method, options={})
151
184
  path, access = swagger_info(method, options)
152
- options = { :params => options } if access.downcase == 'get'
185
+ options = {:params => options} if access == 'get'
153
186
  @service[path].send(access, options)
154
187
  end
155
188
 
156
189
  def rest_access_with_body(method, options={})
157
- path, access = swagger_info(method, options)
158
- body = options.delete(self.class::API['methods'][method.to_s]['body'])
190
+ path, access, spec = swagger_info(method, options)
191
+ body = options.delete(spec['body'])
159
192
  @service[path].send(access, body, options)
160
193
  end
161
194
 
195
+ def select_access(definition, options={})
196
+ definition.keys.reverse.each do |access|
197
+ spec = definition[access]
198
+ keys = options.keys.map {|key| key.to_s}
199
+ return access if (keys - spec['max']).empty? && (spec['min'] - keys).empty?
200
+ end
201
+ raise ArgumentError, "Cannot select the suitable access method from '#{definition.keys.join(', ')}', see #{self.class::RawDoc}."
202
+ end
203
+
162
204
  def swagger_info(method, options)
163
- spec = self.class::API['methods'][method.to_s]
164
- lacked = []
165
- spec['operation']['parameters'].each do |parameter|
166
- lacked << parameter['name'] if parameter['required'] && !options[parameter['name']]
205
+ definition = self.class::API['methods'][method.to_s]
206
+ access = (options.delete(:access) || definition.keys.first).downcase
207
+ spec = definition[access]
208
+ options.keys.each do |key|
209
+ options[key.to_s] = options.delete(key) if key.kind_of?(Symbol)
210
+ end
211
+ lacked = spec['min'] - options.keys
212
+ extra = options.keys - spec['max']
213
+ raise ArgumentError, "Lacked parameter(s) : '#{lacked.join(', ')}', see #{self.class::RawDoc}." unless lacked.empty?
214
+ raise ArgumentError, "Extra parameter(s) : '#{extra.join(', ')}', see #{self.class::RawDoc}." unless extra.empty?
215
+ query = {}
216
+ spec['query'].each do |param|
217
+ query[param] = options.delete(param) if options.key?(param)
218
+ end
219
+ path = spec['path'].gsub(/\{(.+?)\}/) {options.delete($1)}
220
+ path += '?' + URI.encode_www_form(query) unless query.empty?
221
+ [path, access, spec]
222
+ end
223
+
224
+ #
225
+ # for Alchemy APIs
226
+ #
227
+ class Alchemy < self
228
+
229
+ DefaultParams = %w(apikey api_key version)
230
+
231
+ def initialize(options={})
232
+ define_api_methods
233
+ set_variables(options)
234
+ @url ||= (Gateways[:gateway_a] + self.class::API['apis']['basePath']).sub('/alchemy-api','')
235
+ @apikey = {}
236
+ self.class.superclass::DefaultParams.each do |key|
237
+ @apikey[key] = @credential[key] if @credential.key?(key)
238
+ @apikey[key] = options.delete(key.to_sym) if options.key?(key.to_sym)
239
+ end
240
+ @options = options
241
+ @service = RestClient::Resource.new(@url, @options)
242
+ end
243
+
244
+ private
245
+
246
+ def swagger_info(method, options)
247
+ options.update(@apikey)
248
+ super(method, options)
167
249
  end
168
- raise ArgumentError, "Parameter(s) '#{lacked.join(', ')}' required, see #{self.class::RawDoc}." unless lacked.empty?
169
- [spec['path'].gsub(/\{(.+?)\}/) {options.delete($1)}, spec['method']]
170
250
  end
171
251
  end
@@ -1,24 +1,24 @@
1
- # -*- encoding: utf-8 -*-
2
- $:.push File.expand_path('../lib', __FILE__)
3
- require 'watson-api-client'
4
-
5
- Gem::Specification.new do |s|
6
- s.name = 'watson-api-client'
7
- s.version = WatsonAPIClient::VERSION
8
- s.authors = ['Takashi SUGA']
9
- s.email = ['suchowan@box.email.ne.jp']
10
- s.homepage = 'https://github.com/suchowan/watson-api-client'
11
- s.license = 'MIT'
12
- s.summary = %q{An IBM Watson™ API client}
13
- s.description = %q{The watson-api-client is a gem to use REST API on the IBM Watson™ Developer Cloud. It wraps the rest-client REST API using Swagger documents retrievable from the Watson API Reference.}
14
-
15
- s.files = `git ls-files`.split("\n")
16
- s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
17
- s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
18
- s.require_paths = ['lib']
19
- s.required_ruby_version = '>= 1.9.3'
20
-
21
- # specify any dependencies here; for example:
22
- # s.add_development_dependency 'rspec'
23
- s.add_runtime_dependency 'rest-client'
24
- end
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path('../lib', __FILE__)
3
+ require 'watson-api-client'
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = 'watson-api-client'
7
+ s.version = WatsonAPIClient::VERSION
8
+ s.authors = ['Takashi SUGA']
9
+ s.email = ['suchowan@box.email.ne.jp']
10
+ s.homepage = 'https://github.com/suchowan/watson-api-client'
11
+ s.license = 'MIT'
12
+ s.summary = %q{An IBM Watson™ API client}
13
+ s.description = %q{The watson-api-client is a gem to use REST API on the IBM Watson™ Developer Cloud. It wraps the rest-client REST API using Swagger documents retrievable from the Watson API Reference.}
14
+
15
+ s.files = `git ls-files`.split("\n")
16
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
17
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
18
+ s.require_paths = ['lib']
19
+ s.required_ruby_version = '>= 1.9.3'
20
+
21
+ # specify any dependencies here; for example:
22
+ # s.add_development_dependency 'rspec'
23
+ s.add_runtime_dependency 'rest-client'
24
+ end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: watson-api-client
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.5
4
+ version: 0.0.6
5
5
  platform: ruby
6
6
  authors:
7
7
  - Takashi SUGA
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2016-07-29 00:00:00.000000000 Z
11
+ date: 2016-09-02 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rest-client