1. Martin Ostrovsky
  2. Repustate Clients

Commits

Maru Newby  committed dac3b2d

Added ruby api wrapper.

  • Participants
  • Parent commits bc4f750
  • Branches default

Comments (0)

Files changed (3)

File ruby/repustate.gif

Added
New image

File ruby/repustate.rb

View file
+#
+# Repustate Ruby API client.
+#
+# Requirements:
+#  - Ruby >= 1.8.7
+#  - json
+#
+# Want to change it / improve it / share it? Go for it.
+#
+# Feedback is appreciated at info@repustate.com
+#
+# More documentation available at http://www.repustate.com/docs
+#
+
+require 'base64'
+require 'cgi'
+require 'net/http'
+require 'rexml/document'
+
+require 'rubygems'
+require 'json'
+
+class Repustate
+
+  def initialize(key, version='v2')
+    @key = key
+    @version = version
+  end
+
+  # Retrieve the sentiment for a single URl or block of text.
+  def sentiment(options={:text => nil, :url => nil}, response_type='json')
+    call_api('score', options, response_type)
+  end
+
+  # Bulk score multiple pieces of text (not urls!).
+  def bulk_sentiment(options={:items => []}, response_type='json')
+    items_to_score = Hash[options[:items].enum_for(:each_with_index).collect {
+                            |val, i| ["text#{i}", val]
+                          }]
+    call_api('bulk-score', items_to_score, response_type)
+  end
+
+  # Clean up a web page. It doesn't work well on home pages - it's
+  # designed for content pages.
+  def clean_html(options={:url => nil}, response_type='json')
+    use_http_get = true
+    call_api('clean-html', options, response_type, use_http_get)
+  end
+
+  def adjectives(options={:cloud => nil, :text => nil, :url => nil},
+                 response_type='json')
+    call_natural_language('adj', options, response_type)
+  end
+
+  def verbs(options={:cloud => nil, :text => nil, :url => nil},
+            response_type='json')
+    call_natural_language('verb', options, response_type)
+  end
+
+  def ngrams(options={
+               :url => nil,
+               :text => nil,
+               :max => nil,
+               :min => nil,
+               :freq => nil,
+               :stopwords => nil,
+             }, response_type='json')
+    use_http_get = (options[:text] == nil or options[:text].empty?)
+    call_api('ngrams', options, response_type, use_http_get)
+  end
+
+  # Convert english date indicators like "today", "tomorrow", "next week"
+  # into date strings like 2011-01-12.
+  def date_extraction(options={:text => nil}, response_type='json')
+    call_api('extract-dates', options, response_type)
+  end
+
+  # Given a list of images and titles, generate a simple powerpoint
+  # presentation.
+  def powerpoint(options={
+                  :title => '',
+                  :author => '',
+                  :images => [],
+                  :titles => [],
+                })
+    args = {
+      :title => options[:report_title],
+      :author => options[:author],
+    }
+
+    images_and_titles = options[:images].zip(options[:titles])
+    images_and_titles.each_with_index do |value, i|
+      filename = value[0]
+      title = value[1]
+      image_data = File.read(filename)
+      encoded_image = Base64.encode64(image_data)
+      args["slide_#{i}_image"] = encoded_image
+      args["slide_#{i}_title"] = title
+    end
+
+    call_api('powerpoint', args)
+  end
+
+  protected
+
+  def url_for_call(api_function, response_type)
+    if api_function == 'powerpoint'
+      return "http://api.repustate.com/#{@version}/#{@key}/powerpoint/"
+    else
+      return "http://api.repustate.com/#{@version}/#{@key}/#{api_function}" +
+          ".#{response_type}"
+    end
+  end
+
+  def get_http_result(url, args, use_http_get)
+    if use_http_get
+      query = args.collect { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&')
+      url = url.concat("?#{query}")
+      result = Net::HTTP.get_response(URI.parse(url))
+    else
+      result = Net::HTTP.post_form(URI.parse(url), args)
+    end
+
+    if result.code != '200'
+      raise "HTTP Error: #{result.code} #{result.body}"
+    end
+
+    result.body
+  end
+
+  def parse_result(result, api_function, response_type)
+    if api_function == 'powerpoint'
+      return result
+    elsif response_type == 'json'
+      return JSON.parse(result)
+    else
+      # Default is XML
+      return REXML::Document.new(result)
+    end
+  end
+
+  def call_api(api_function, args={}, response_type='json', use_http_get=false)
+    if not ['json', 'xml'].include?(response_type)
+      raise ArgumentError, "#{response_type} is not a valid response type"
+    end
+
+    # Avoid sending empty parameters
+    args = args.select { |key, value| value and not value.empty? }
+
+    url = url_for_call(api_function, response_type)
+    result = get_http_result(url, args, use_http_get)
+    parse_result(result, api_function, response_type)
+  end
+
+  def call_natural_language(api_function, args={
+                            :cloud => nil,
+                            :text => nil,
+                            :url => nil,
+                            }, response_type='json')
+    call_api(api_function, args, response_type)
+  end
+
+end

File ruby/tc_repustate.rb

View file
+require "repustate"
+require "test/unit"
+
+class TestRepustate < Test::Unit::TestCase
+
+  KEY = '0c9cf39718d8ce33e5310047617f8020984d8f18'
+
+  TEXT = 'iPad'
+
+  URL = 'http://tcrn.ch/aav9Ty'
+
+  def get_accessor
+    return Repustate.new(KEY)
+  end
+
+  def check_result(result, check_status=true)
+    assert_not_nil(result, 'Invalid result')
+    if check_status
+      status = result['status']
+      assert_equal('OK', status, result)
+    end
+  end
+
+  def check_call(func_name, options={}, check_status=true)
+    result = get_accessor().send(func_name, options)
+    check_result(result, check_status)
+  end
+
+  def test_sentiment_for_text
+    check_call('sentiment', {:text => TEXT})
+  end
+
+  def test_sentiment_for_url
+    check_call('sentiment', {:url => URL})
+  end
+
+  def test_xml_response_type
+    result = get_accessor().send('sentiment', {:text => TEXT}, 'xml')
+    check_result(result)
+  end
+
+  def test_bulk_sentiment
+    check_call('bulk_sentiment', {:items => [URL]})
+  end
+
+  def test_clean_html
+    check_call('clean_html', {:url => URL})
+  end
+
+  def test_adjectives_for_text
+    check_call('adjectives', {:text => TEXT})
+  end
+
+  def test_adjectives_for_url
+    check_call('adjectives', {:url => URL})
+  end
+
+  def test_verbs_for_text
+    check_call('verbs', {:text => TEXT})
+  end
+
+  def test_verbs_for_url
+    check_call('verbs', {:url => URL})
+  end
+
+  def test_ngrams_for_text
+    check_call('ngrams', {:text => TEXT})
+  end
+
+  def test_ngrams_for_url
+    check_call('ngrams', {:url => URL})
+  end
+
+  def test_date_extraction
+    check_call('date_extraction', {:text => TEXT})
+  end
+
+  def test_powerpoint
+    options = {
+      :report_title => 'Test Report',
+      :author => 'Martin Ostrovsky',
+      :images => ['repustate.gif'],
+      :titles => ['A test title'],
+    }
+    check_call('powerpoint', options, check_status=false)
+  end
+
+end