Permalink
Browse files

Initial commit

  • Loading branch information...
0 parents commit 71931b31ea6f9549dd02772cb249556cd28c5fab @laurynas laurynas committed Aug 11, 2012
@@ -0,0 +1,18 @@
+*.gem
+*.rbc
+.bundle
+.config
+.yardoc
+.idea
+Gemfile.lock
+InstalledFiles
+_yardoc
+coverage
+doc/
+lib/bundler/man
+pkg
+rdoc
+spec/reports
+test/tmp
+test/version_tmp
+tmp
2 .rspec
@@ -0,0 +1,2 @@
+--color
+--format progress
@@ -0,0 +1,7 @@
+rvm:
+ - 1.9.3
+ - 1.9.2
+ - jruby
+ - rbx
+script: "bundle exec rake spec"
+
10 Gemfile
@@ -0,0 +1,10 @@
+source 'https://rubygems.org'
+
+gemspec
+
+gem 'rake'
+gem 'json'
+
+group :test do
+ gem "rspec"
+end
22 LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) 2012 Laurynas Butkus
+
+MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,51 @@
+Detect Language API Client [![Build Status](https://secure.travis-ci.org/detectlanguage/detect_language.png)](http://travis-ci.org/detectlanguage/detect_language)
+========
+
+Detects language of given text. Returns detected language codes and scores.
+
+## Installation
+
+Add this line to your application's Gemfile:
+
+ gem 'detect_language'
+
+Or install it yourself as:
+
+ $ gem install detect_language
+
+### Configuration
+
+Before using Detect Language API client you setup your personal API key.
+You can get it by signing up at http://detectlanguage.com
+
+If you are using Rails, create initializer `config/initializers/detect_language.rb` and add following code there.
+Otherwise just integrate following code into your apps configuration.
+
+ DetectLanguage.configure do |config|
+ config.api_key = "YOUR API KEY"
+ end
+
+## Usage
+
+### Language detection
+
+ DetectLanguage.detect("Buenos dias señor")
+
+#### Result
+
+ [ {"language"=>"es", "isReliable"=>false, "confidence"=>0.3271028037383178},
+ {"language"=>"pt", "isReliable"=>false, "confidence"=>0.08356545961002786} ]
+
+### Simple language detection
+
+If you need just a language code you can use `simple_detect`. It returns just the language code.
+
+ DetectLanguage.simple_detect("Buenos dias señor")
+
+#### Result
+
+ "es"
+
+## License
+
+Detect Language API Client is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.
@@ -0,0 +1,7 @@
+#!/usr/bin/env rake
+require "bundler/gem_tasks"
+require 'rspec/core/rake_task'
+
+RSpec::Core::RakeTask.new
+
+task :default => :spec
@@ -0,0 +1,17 @@
+# -*- encoding: utf-8 -*-
+require File.expand_path('../lib/detect_language/version', __FILE__)
+
+Gem::Specification.new do |gem|
+ gem.authors = ["Laurynas Butkus"]
+ gem.email = ["laurynas.butkus@gmail.com"]
+ gem.description = %q{Language Detection API Client}
+ gem.summary = %q{Detects language of given text. Returns detected language codes and scores.}
+ gem.homepage = "https://github.com/detectlanguage/detect_language"
+
+ gem.files = `git ls-files`.split($\)
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
+ gem.name = "detect_language"
+ gem.require_paths = ["lib"]
+ gem.version = DetectLanguage::VERSION
+end
@@ -0,0 +1,39 @@
+require "detect_language/version"
+require "detect_language/exception"
+require "detect_language/configuration"
+require "detect_language/client"
+
+module DetectLanguage
+ class << self
+ attr_writer :configuration
+
+ def configure
+ yield(configuration)
+ end
+
+ # The configuration object.
+ # @see DetectLanguage.configure
+ def configuration
+ @configuration ||= Configuration.new
+ end
+
+ def client
+ @client ||= Client.new(configuration)
+ end
+
+ def detect(text)
+ result = client.execute(:detect, :q => text)
+ result['data']['detections']
+ end
+
+ def simple_detect(text)
+ detections = detect(text)
+
+ if detections.empty?
+ nil
+ else
+ detections[0]['language']
+ end
+ end
+ end
+end
@@ -0,0 +1,66 @@
+require 'net/http'
+require 'json'
+
+module DetectLanguage
+ class Client
+ attr_reader :configuration
+
+ def initialize(configuration)
+ @configuration = configuration
+ end
+
+ def execute(method, params)
+ http = setup_http_connection
+
+ request_params = params.merge(:key => configuration.api_key)
+
+ request = Net::HTTP::Post.new(request_uri(method))
+ request.set_form_data(request_params)
+ request.add_field('User-Agent', configuration.user_agent)
+
+ response = http.request(request)
+
+ case response
+ when Net::HTTPSuccess then
+ parse_response(response.body)
+ else
+ raise "Failure: #{response.class}"
+ end
+ end
+
+ private
+
+ def parse_response(response_body)
+ response = JSON.parse(response_body)
+
+ if response["error"].nil?
+ response
+ else
+ raise Exception.new(response["error"]["message"])
+ end
+ end
+
+ def request_uri(method)
+ "/#{configuration.api_version}/#{method}"
+ end
+
+ def setup_http_connection
+ http =
+ Net::HTTP::Proxy(configuration.proxy_host, configuration.proxy_port, configuration.proxy_user,
+ configuration.proxy_pass).
+ new(configuration.host, configuration.port)
+
+ http.read_timeout = configuration.http_read_timeout
+ http.open_timeout = configuration.http_open_timeout
+
+ if configuration.secure?
+ http.use_ssl = true
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
+ else
+ http.use_ssl = false
+ end
+
+ http
+ end
+ end
+end
@@ -0,0 +1,83 @@
+module DetectLanguage
+ class Configuration
+ # The API key for your project, found on your homepage after you login into detectlanguage.com website
+ # Defaults to 'demo', which has a limited number of requests.
+ attr_accessor :api_key
+
+ # The API version you are using (defaults to 0.2).
+ attr_accessor :api_version
+
+ # HTTP request user agent (defaults to 'Detect Language API ruby gem').
+ attr_accessor :user_agent
+
+ # The host to connect to (defaults to ws.detectlanguage.com).
+ attr_accessor :host
+
+ # The port on which your DetectLanguage server runs (defaults to 443 for secure
+ # connections, 80 for insecure connections).
+ attr_accessor :port
+
+ # +true+ for https connections, +false+ for http connections.
+ attr_accessor :secure
+
+ # The HTTP open timeout in seconds.
+ attr_accessor :http_open_timeout
+
+ # The HTTP read timeout in seconds.
+ attr_accessor :http_read_timeout
+
+ # The hostname of your proxy server (if using a proxy).
+ attr_accessor :proxy_host
+
+ # The port of your proxy server (if using a proxy).
+ attr_accessor :proxy_port
+
+ # The username to use when logging into your proxy server (if using a proxy).
+ attr_accessor :proxy_user
+
+ # The password to use when logging into your proxy server (if using a proxy).
+ attr_accessor :proxy_pass
+
+ alias_method :secure?, :secure
+
+ def initialize
+ @api_key = "demo"
+ @api_version = "0.2"
+ @host = "ws.detectlanguage.com"
+ @user_agent = "Detect Language API ruby gem"
+ end
+
+ def protocol
+ if secure?
+ 'https'
+ else
+ 'http'
+ end
+ end
+
+ def port
+ @port || default_port
+ end
+
+ # Allows config options to be read like a hash
+ #
+ # @param [Symbol] option Key for a given attribute
+ def [](option)
+ send(option)
+ end
+
+ private
+
+ # Determines what port should we use for sending requests.
+ # @return [Fixnum] Returns 443 if you've set secure to true in your
+ # configuration, and 80 otherwise.
+ def default_port
+ if secure?
+ 443
+ else
+ 80
+ end
+ end
+
+ end
+end
@@ -0,0 +1,5 @@
+module DetectLanguage
+ class Exception < ::Exception
+
+ end
+end
@@ -0,0 +1,3 @@
+module DetectLanguage
+ VERSION = "1.0.0"
+end
Oops, something went wrong.

0 comments on commit 71931b3

Please sign in to comment.