freebase-api 0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,4 @@
1
+ /coverage/
2
+ /.env
3
+ /pkg/
4
+ /doc/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --colour
2
+ --format documentation
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gem 'rake', '~> 10.0'
4
+
5
+ group :test do
6
+ gem 'coveralls', :require => false
7
+ gem 'rspec', '~> 2.12'
8
+ gem 'yard', '~> 0.8'
9
+ gem 'rspec', '~> 2.12'
10
+ gem 'simplecov', '~> 0.7', :require => false
11
+ gem 'redcarpet', '~> 2.2'
12
+ end
13
+
14
+ # Specify your gem's dependencies in freebase-api.gemspec
15
+ gemspec
@@ -0,0 +1,53 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ freebase-api (0.1)
5
+ httparty (~> 0.10)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ colorize (0.5.8)
11
+ coveralls (0.6.2)
12
+ colorize
13
+ multi_json (~> 1.3)
14
+ rest-client
15
+ simplecov (>= 0.7)
16
+ thor
17
+ diff-lcs (1.2.1)
18
+ httparty (0.10.0)
19
+ multi_json (~> 1.0)
20
+ multi_xml
21
+ mime-types (1.21)
22
+ multi_json (1.6.1)
23
+ multi_xml (0.5.2)
24
+ rake (10.0.3)
25
+ redcarpet (2.2.2)
26
+ rest-client (1.6.7)
27
+ mime-types (>= 1.16)
28
+ rspec (2.13.0)
29
+ rspec-core (~> 2.13.0)
30
+ rspec-expectations (~> 2.13.0)
31
+ rspec-mocks (~> 2.13.0)
32
+ rspec-core (2.13.0)
33
+ rspec-expectations (2.13.0)
34
+ diff-lcs (>= 1.1.3, < 2.0)
35
+ rspec-mocks (2.13.0)
36
+ simplecov (0.7.1)
37
+ multi_json (~> 1.0)
38
+ simplecov-html (~> 0.7.1)
39
+ simplecov-html (0.7.1)
40
+ thor (0.17.0)
41
+ yard (0.8.5.2)
42
+
43
+ PLATFORMS
44
+ ruby
45
+
46
+ DEPENDENCIES
47
+ coveralls
48
+ freebase-api!
49
+ rake (~> 10.0)
50
+ redcarpet (~> 2.2)
51
+ rspec (~> 2.12)
52
+ simplecov (~> 0.7)
53
+ yard (~> 0.8)
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2013 Perfect Memory
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,204 @@
1
+ # freebase-api [![Build Status](https://travis-ci.org/PerfectMemory/freebase-api.png?branch=master)](http://travis-ci.org/mongoid/mongoid) [![Coverage Status](https://coveralls.io/repos/PerfectMemory/freebase-api/badge.png?branch=master)](https://coveralls.io/r/PerfectMemory/freebase-api) [![Code Climate](https://codeclimate.com/github/PerfectMemory/freebase-api.png)](https://codeclimate.com/github/PerfectMemory/freebase-api) [![Dependency Status](https://gemnasium.com/PerfectMemory/freebase-api.png)](https://gemnasium.com/PerfectMemory/freebase-api)
2
+
3
+ freebase-api provides access to both a raw-access and an abstract-layer to the [Freebase API](http://wiki.freebase.com/wiki/Freebase_API).
4
+
5
+ Currently supported APIs are :
6
+
7
+ - Search ([doc](https://developers.google.com/freebase/v1/search))
8
+ - MQL Read ([doc](https://developers.google.com/freebase/v1/mqlread))
9
+ - Topic ([doc](https://developers.google.com/freebase/v1/topic))
10
+ - Image support
11
+
12
+ ## Installation
13
+
14
+ Add this line to your application's Gemfile:
15
+
16
+ gem 'freebase-api'
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself with:
23
+
24
+ $ gem install freebase-api
25
+
26
+ ## Session
27
+
28
+ If you have a [Google API key](https://code.google.com/apis/console), you can set the environment variable `GOOGLE_API_KEY`, the default session will load it automatically.
29
+
30
+ You can override the default session by providing some options, like the language or the environment.
31
+
32
+ ```ruby
33
+ FreebaseAPI.session = FreebaseAPI::Session.new(key: 'GOOGLE_API_KEY', env: => :stable)
34
+ ```
35
+
36
+ Options are :
37
+
38
+ * `:key` : your Google API key
39
+ * `:env` : the environment (sandbox or stable) (default is :stable)
40
+ * `:query_options` : some options that will be used in each query
41
+ * `:limit` : the number of items returned (default is 10)
42
+ * `:lang` : the language you would like the content in (default is 'en')
43
+
44
+ ## Fetch resources
45
+
46
+ The DSL of `freebase-api` is based on 3 main models :
47
+
48
+ * **Topic** (used to store topics, types, CVTs)
49
+ * **Attribute** (used to store value typed properties such as string, number, date)
50
+ * **Image** (used to store image data)
51
+
52
+ To access a specific resource on Freebase, you can use the `Topic` model which provides some useful methods. The `get` method is based on the `Topic API`.
53
+
54
+ ```ruby
55
+ resource = FreebaseAPI::Topic.get('/en/github') # => #<FreebaseAPI::Topic:0x000000021a10d8>
56
+ ```
57
+
58
+ Once the resource is fetched, you can access its properties :
59
+
60
+ ```ruby
61
+ # id
62
+ resource.id # => "/m/04g0kcw"
63
+
64
+ # Name
65
+ resource.name # => "GitHub"
66
+
67
+ # Description
68
+ resource.description # => "GitHub is a web-based hosting service for software dev..."
69
+
70
+ # Types
71
+ resource.types # => ["/common/topic", "/internet/website", "/base/technologyofdoing/proposal_agent"]
72
+
73
+ # Properties
74
+ resource.properties.size # => 18
75
+
76
+ # Access a specific Property
77
+ attribute = resource.property('/common/topic/official_website').first # => #<FreebaseAPI::Attribute:0x00000002008500>
78
+ attribute.value # => "http://github.com/"
79
+
80
+ types = resource.property('/type/object/type') # => #<FreebaseAPI::Topic:0x00000002009888>
81
+ types.map(&:id) # => equivalent to resource.types
82
+
83
+ types[1].name # => "Website"
84
+ types[1].sync # fetch all the properties of this topic
85
+ types[1].description # => "Website or (Web site) is a collection of web pages, typically common..."
86
+
87
+ # Image
88
+ image = property.image(maxwidth: 150, maxheight: 150) # => #<FreebaseAPI::Image:0x00000001fcd4c8>
89
+ image.store('/path/to/filename') # record the image
90
+ ```
91
+
92
+ ## Search resources
93
+
94
+ To search topics using a query, you can use `FreebaseAPI::Topic.search` that returns a Hash ordered by scores (keys). This method supports
95
+ all the parameters of the official API.
96
+
97
+ ```
98
+ results = FreebaseAPI::Topic.search('jackson') # => [100.55349=>#<FreebaseAPI::Topic:0x000000021e91d0>, 73.209366=>#<FreebaseAPI::Topic:0x000000021f01d8> ...]
99
+ best_match = results.values.first # => #<FreebaseAPI::Topic:0x000000021e91d0>
100
+ best_match.name # => "Michael Jackson"
101
+ best_match.sync
102
+ best_match.description # => "Michael Joseph Jackson (August 29, 1958 – June 25, 2009) was an American recording artist..."
103
+ ```
104
+
105
+ ```ruby
106
+ FreebaseAPI::Topic.search('Cee Lo Green', filter: '(all type:/music/artist created:"The Lady Killer")')
107
+ # => {868.82666=>#<FreebaseAPI::Topic:0x000000029ca250}
108
+ ```
109
+
110
+ ## Freebase API Raw access
111
+
112
+ To get a raw access to the API, use `FreebaseAPI.session`. You can use any option or parameter documented in the Freebase API with the following methods.
113
+
114
+ ### Search
115
+
116
+ The `search` method provides access to Freebase data given a free text query. Please consult the [Search Overview](https://developers.google.com/freebase/v1/search-overview) and the [Search Cookbook](https://developers.google.com/freebase/v1/search-cookbook) for more information on how to construct detailed search queries. All the parameters are supported.
117
+
118
+ ```ruby
119
+ FreebaseAPI.session.search('Cee Lo Green', filter: '(all type:/music/artist created:"The Lady Killer")')
120
+ ```
121
+
122
+ The method returns an Array containing all the results.
123
+
124
+ ```json
125
+ [{"mid"=>"/m/01w5jwb",
126
+ "id"=>"/en/cee_lo_1974",
127
+ "name"=>"Cee Lo Green",
128
+ "notable"=>{"name"=>"Singer-songwriter", "id"=>"/m/016z4k"},
129
+ "lang"=>"en",
130
+ "score"=>868.82666}]
131
+ ```
132
+
133
+ ### Topic
134
+
135
+ The `topic` method calls a web service that will return all known facts for a given topic including images and text blurbs. You can apply filters to the Topic API so that it only returns the property values that you're interested in. This is ideal for building topic pages and short summaries of an entity. You can consult the API reference [here](https://developers.google.com/freebase/v1/topic).
136
+
137
+ ```ruby
138
+ FreebaseAPI.session.topic('/en/cee_lo_1974', filter: '/people/person/profession')
139
+ ```
140
+
141
+ The method returns a Hash containing all the properties.
142
+
143
+ ```json
144
+ { "id"=>"/m/01w5jwb",
145
+ "property"=>{
146
+ "/people/person/profession"=>{"valuetype"=>"object", "values"=>[
147
+ {"text"=>"Record producer", "lang"=>"en", "id"=>"/m/0dz3r", "creator"=>"/user/mw_template_bot", "timestamp"=>"2008-10-09T08:34:08.000Z"},
148
+ {"text"=>"Singer-songwriter", "lang"=>"en", "id"=>"/m/016z4k", "creator"=>"/user/mw_template_bot", "timestamp"=>"2008-10-09T08:34:08.000Z"},
149
+ {"text"=>"Actor", "lang"=>"en", "id"=>"/m/02hrh1q", "creator"=>"/user/netflixbot", "timestamp"=>"2011-04-09T04:01:36.001Z"},
150
+ {"text"=>"Rapper", "lang"=>"en", "id"=>"/m/0hpcdn2", "creator"=>"/user/lycel", "timestamp"=>"2011-12-28T07:40:42.002Z"}
151
+ ], "count"=>4.0}
152
+ }
153
+ }
154
+ ```
155
+
156
+ ### MQL Read
157
+
158
+ The `mqlread` method provides access to the Freebase database using the [Metaweb query language (MQL)](https://developers.google.com/freebase/v1/mql-overview). You can consult the API reference [here](https://developers.google.com/freebase/v1/mqlread).
159
+
160
+ ```ruby
161
+ FreebaseAPI.session.mqlread({
162
+ :type => '/internet/website',
163
+ :id => '/en/github',
164
+ :'/common/topic/official_website' => nil}
165
+ )
166
+ ```
167
+
168
+ The method returns a Hash containing the MQL response.
169
+
170
+ ```json
171
+ {"/common/topic/official_website"=>"http://github.com/",
172
+ "id"=>"/en/github",
173
+ "type"=>"/internet/website"}
174
+ ```
175
+
176
+ ### Image
177
+
178
+ The `image` method retrieves image data for a given Topic.
179
+
180
+ ```ruby
181
+ FreebaseAPI.session.image('/en/github', maxwidth: 150, maxheight: 150)
182
+ ```
183
+
184
+ The method returns data bytes.
185
+
186
+ ```
187
+ \x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x0...
188
+ ```
189
+
190
+ ## Contributing to freebase-api
191
+
192
+ * Check the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
193
+ * Check the issue tracker to make sure someone already hasn't requested it and/or contributed it
194
+ * Fork the project
195
+ * Start a feature/bugfix branch
196
+ * Commit and push until you are happy with your contribution
197
+ * Make sure to add tests for it. This is important so I don't unintentionally break it in a future version.
198
+ * Please try not to mess with the Rakefile, version, or history. If you want, or really need, to have your own version, that is fine, but please isolate it in its own commit so I can cherry-pick around it.
199
+
200
+ ## Copyright
201
+
202
+ Copyright (c) 2013 Perfect Memory. See LICENSE.txt for
203
+ further details.
204
+
@@ -0,0 +1,8 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+ require 'yard'
4
+
5
+ YARD::Rake::YardocTask.new
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task :default => :spec
@@ -0,0 +1,19 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/freebase_api/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Aymeric Brisse"]
6
+ gem.email = ["aymeric.brisse@mperfect-memory.com"]
7
+ gem.description = %q{A library to use the Freebase API}
8
+ gem.summary = %q{Provides access to both a raw-access and an abstract-layer to the Freebase API}
9
+ gem.homepage = "https://github.com/PerfectMemory/freebase-api"
10
+
11
+ gem.files = `git ls-files`.split($\)
12
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
13
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
14
+ gem.name = "freebase-api"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = FreebaseAPI::VERSION
17
+
18
+ gem.add_dependency('httparty', '~> 0.10')
19
+ end
@@ -0,0 +1,32 @@
1
+ require 'logger'
2
+
3
+ require 'freebase_api/session'
4
+ require 'freebase_api/image'
5
+ require 'freebase_api/version'
6
+ require 'freebase_api/topic'
7
+ require 'freebase_api/attribute'
8
+ require 'freebase_api/exceptions'
9
+ require 'freebase_api/ext/hash'
10
+
11
+ # FreebaseAPI is a library to use the Freebase API
12
+ #
13
+ # It provides :
14
+ # - a Data mapper
15
+ # - a low level class to use directly the Freebase API (Topic, Search, MQLRead)
16
+ #
17
+ # @see http://wiki.freebase.com/wiki/Freebase_API
18
+ module FreebaseAPI
19
+ class << self
20
+ attr_accessor :logger, :session
21
+
22
+ def init_logger
23
+ logger = Logger.new(STDERR)
24
+ logger.level = Logger::WARN
25
+ logger.progname = "FreebaseAPI"
26
+ self.logger = logger
27
+ end
28
+ end
29
+ end
30
+
31
+ FreebaseAPI.init_logger
32
+ FreebaseAPI.session = FreebaseAPI::Session.new
@@ -0,0 +1,29 @@
1
+ module FreebaseAPI
2
+ # Attribute can be any Freebase data type
3
+ class Attribute
4
+
5
+ attr_accessor :type
6
+
7
+ def initialize(data, options={})
8
+ @data = data
9
+ @type = options[:type]
10
+ end
11
+
12
+ def value
13
+ @data['value']
14
+ end
15
+
16
+ def text
17
+ @data['text']
18
+ end
19
+
20
+ def lang
21
+ @data['lang']
22
+ end
23
+
24
+ def type
25
+ @type
26
+ end
27
+
28
+ end
29
+ end
@@ -0,0 +1,25 @@
1
+ module FreebaseAPI
2
+ # A class for returning errors from the Freebase API
3
+ class Error < StandardError
4
+ attr_accessor :code, :message, :errors
5
+
6
+ def initialize(params)
7
+ FreebaseAPI.logger.error("#{params['message']} (#{params['code']})")
8
+ self.code = params['code']
9
+ self.message = params['message']
10
+ end
11
+
12
+ def to_s
13
+ "#{self.message} (#{self.code})"
14
+ end
15
+ end
16
+
17
+ class ServiceError < Error
18
+ def initialize(params)
19
+ super
20
+ self.errors = params['errors']
21
+ end
22
+ end
23
+
24
+ class NetError < Error ;; end
25
+ end
@@ -0,0 +1,15 @@
1
+ class Hash
2
+
3
+ def deep_merge(other_hash)
4
+ dup.deep_merge!(other_hash)
5
+ end
6
+
7
+ def deep_merge!(other_hash)
8
+ other_hash.each_pair do |k,v|
9
+ tv = self[k]
10
+ self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v
11
+ end
12
+ self
13
+ end
14
+
15
+ end
@@ -0,0 +1,44 @@
1
+ module FreebaseAPI
2
+ class Image
3
+
4
+ attr_reader :id
5
+
6
+ class << self
7
+ def get(id, options={})
8
+ image = Image.new(id, options)
9
+ image.retrieve
10
+ image
11
+ end
12
+ end
13
+
14
+ def initialize(id, options={})
15
+ @data = nil
16
+ @options = options
17
+ @id = id
18
+ end
19
+
20
+ def retrieve
21
+ @data = FreebaseAPI.session.image(self.id, @options)
22
+ end
23
+
24
+ def store(filename)
25
+ File.open(filename, 'wb') do |f|
26
+ f.write data
27
+ end
28
+ end
29
+
30
+ def size
31
+ data.size
32
+ end
33
+
34
+ def inspect
35
+ self.to_s
36
+ end
37
+
38
+ private
39
+
40
+ def data
41
+ @data || retrieve
42
+ end
43
+ end
44
+ end