Skip to content

Instantly share code, notes, and snippets.

@leviwilson
Created September 24, 2015 13:19
Show Gist options
  • Save leviwilson/d51dd70312a026a805ab to your computer and use it in GitHub Desktop.
Save leviwilson/d51dd70312a026a805ab to your computer and use it in GitHub Desktop.
require 'faraday'
require 'dotenv'
require 'json'
module MeaningCloud
def self.topics(options)
request :topics, options, lang: 'en', tt: 'ecr'
end
def self.sentiment(options)
request :sentiment, options, model: 'auto'
end
def self.text_classification(options)
request :class, options, model: 'IPTC_en'
end
def self.lang(options)
request :lang, options
end
class << self
attr_accessor :api_key
def request(what, arguments, defaults={})
payload = {
key: api_key,
of: :json
}.merge(defaults).merge(arguments)
version = current_version_for(what)
response = Response.new JSON.parse api.post("#{what}-#{version}", payload).body
end
def api
@api ||= Faraday.new 'https://api.meaningcloud.com'
end
def current_version_for(what)
{
topics: '1.2',
sentiment: '2.0',
class: '1.1',
lang: '1.1'
}[what] || '2.0'
end
end
private_class_method :request, :api, :current_version_for
class Response
attr_reader :status, :message, :body, :credits, :remaining_credits
def initialize(json)
status = json.delete 'status'
@status = status['code']
@message = status['msg']
@body = json
@credits, @remaining_credits = status['credits'].to_i, status['remaining_credits'].to_i
raise ApiError, message unless success?
end
def success?
status === '0'
end
end
class ApiError < Exception
end
end
require_relative 'meaning_cloud'
MeaningCloud.api_key = ENV['MC_KEY']
MeaningCloud.sentiment(txt: 'I would like to see if the sentiments extracted are happy or sad.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment