scnnr 0.1.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 7d5ce96021afa8ae437e4a7b23cdb7018bfc0202
4
+ data.tar.gz: e06b41c303d7f2949b8ac542454e6e40ffa77ed3
5
+ SHA512:
6
+ metadata.gz: ea14db49ec5b7f1e671444ef7715015030133c4b4e2eaa533bb8bb6c66539db2beb20280725e47f3948178c6ff24094e430558edece68868a432de258fdac124
7
+ data.tar.gz: 005662bd30ebb39ad6065b2208b24c7c8301cd04123cf17b3175e7cd4bc1dee0501dd88250244e788073c4e561bc8af5e5cea71863176fbfbe91a54c27852242
@@ -0,0 +1,46 @@
1
+ # Ruby CircleCI 2.0 configuration file
2
+ #
3
+ # Check https://circleci.com/docs/2.0/language-ruby/ for more details
4
+ #
5
+ version: 2
6
+ jobs:
7
+ build: &build
8
+ docker:
9
+ - image: ruby
10
+ working_directory: ~/repo
11
+ steps:
12
+ - checkout
13
+ - run:
14
+ name: install dependencies
15
+ command: |
16
+ bundle install --jobs=4 --retry=3 --path vendor/bundle
17
+ # run tests!
18
+ - run:
19
+ name: run tests
20
+ command: |
21
+ mkdir /tmp/test-results
22
+ bundle exec rubocop --format progress -r $(bundle show rubocop-junit-formatter)/lib/rubocop/formatter/junit_formatter.rb --format RuboCop::Formatter::JUnitFormatter --out /tmp/test-results/rubocop.xml
23
+ bundle exec rspec --format progress \
24
+ --format RspecJunitFormatter \
25
+ --out /tmp/test-results/rspec.xml \
26
+ --format progress
27
+ # collect reports
28
+ - store_test_results:
29
+ path: /tmp/test-results
30
+ - store_artifacts:
31
+ path: /tmp/test-results
32
+ destination: test-results
33
+ ruby-2.3.5:
34
+ <<: *build
35
+ docker:
36
+ - image: circleci/ruby:2.3.5-node-browsers
37
+ ruby-2.4.1:
38
+ <<: *build
39
+ docker:
40
+ - image: circleci/ruby:2.4.1-node-browsers
41
+ workflows:
42
+ version: 2
43
+ ruby-multi-build:
44
+ jobs:
45
+ - ruby-2.3.5
46
+ - ruby-2.4.1
data/.gitignore ADDED
@@ -0,0 +1,51 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /spec/examples.txt
9
+ /test/tmp/
10
+ /test/version_tmp/
11
+ /tmp/
12
+ .rspec_status
13
+
14
+ # Used by dotenv library to load environment variables.
15
+ # .env
16
+
17
+ ## Specific to RubyMotion:
18
+ .dat*
19
+ .repl_history
20
+ build/
21
+ *.bridgesupport
22
+ build-iPhoneOS/
23
+ build-iPhoneSimulator/
24
+
25
+ ## Specific to RubyMotion (use of CocoaPods):
26
+ #
27
+ # We recommend against adding the Pods directory to your .gitignore. However
28
+ # you should judge for yourself, the pros and cons are mentioned at:
29
+ # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
30
+ #
31
+ # vendor/Pods/
32
+
33
+ ## Documentation cache and generated files:
34
+ /.yardoc/
35
+ /_yardoc/
36
+ /doc/
37
+ /rdoc/
38
+
39
+ ## Environment normalization:
40
+ /.bundle/
41
+ /vendor/bundle
42
+ /lib/bundler/man/
43
+
44
+ # for a library or gem, you might want to ignore these files since the code is
45
+ # intended to run in multiple environments; otherwise, check them in:
46
+ Gemfile.lock
47
+ .ruby-version
48
+ .ruby-gemset
49
+
50
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
51
+ .rvmrc
data/.rubocop.yml ADDED
@@ -0,0 +1,67 @@
1
+ require:
2
+ - rubocop-rspec
3
+
4
+ AllCops:
5
+ TargetRubyVersion: 2.4
6
+
7
+ Metrics/LineLength:
8
+ Max: 120
9
+
10
+ Metrics/ClassLength:
11
+ Max: 300
12
+
13
+ Metrics/BlockLength:
14
+ Max: 25
15
+ Exclude:
16
+ - 'Rakefile'
17
+ - '**/*.rake'
18
+ - 'spec/**/*.rb'
19
+ - 'scnnr.gemspec'
20
+
21
+ Style/MethodDefParentheses:
22
+ EnforcedStyle: require_parentheses
23
+
24
+ Style/CollectionMethods:
25
+ Enabled: true
26
+ PreferredMethods:
27
+ reduce: inject
28
+
29
+ Style/TrailingCommaInArguments:
30
+ EnforcedStyleForMultiline: no_comma
31
+
32
+ Style/TrailingCommaInLiteral:
33
+ EnforcedStyleForMultiline: comma
34
+
35
+ Style/Documentation:
36
+ Enabled: false
37
+
38
+ Style/RedundantSelf:
39
+ Enabled: false
40
+
41
+ Layout/MultilineMethodCallIndentation:
42
+ EnforcedStyle: indented
43
+
44
+ Layout/IndentHash:
45
+ EnforcedStyle: consistent
46
+
47
+ Style/BracesAroundHashParameters:
48
+ Enabled: false
49
+
50
+ RSpec/NestedGroups:
51
+ Max: 5
52
+
53
+ RSpec/NamedSubject:
54
+ Enabled: false
55
+
56
+ RSpec/MultipleExpectations:
57
+ Enabled: false
58
+
59
+ RSpec/ExampleLength:
60
+ Enabled: false
61
+
62
+ RSpec/MessageSpies:
63
+ EnforcedStyle: receive
64
+
65
+ RSpec/AnyInstance:
66
+ Exclude:
67
+ - 'spec/scnnr/connection_spec.rb'
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at support@newrope.biz. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ gem 'rake', '~> 10.0'
8
+
9
+ group :development do
10
+ gem 'pry', '~> 0.10'
11
+ end
12
+
13
+ group :test do
14
+ gem 'rspec', '~> 3.5'
15
+ gem 'rspec_junit_formatter', '~> 0.3'
16
+ gem 'rubocop', '~> 0.49.0'
17
+ gem 'rubocop-junit-formatter', '~> 0.1'
18
+ gem 'rubocop-rspec', '~> 1.15.0'
19
+ gem 'webmock', '~> 3.0'
20
+ end
21
+
22
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 NEWROPE Co. Ltd.
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 ADDED
@@ -0,0 +1,129 @@
1
+ # Official #CBK scnnr client library for Ruby.
2
+
3
+ ## Installation
4
+ ### Bundler
5
+ ```
6
+ gem 'scnnr'
7
+ ```
8
+
9
+ ### Manual
10
+ ```
11
+ gem install scnnr
12
+ ```
13
+
14
+ ## Configuration
15
+ You can pass configuration options as a block to `Scnnr::Client.new`.
16
+
17
+ ```
18
+ client = Scnnr::Client.new do |config|
19
+ config.api_key = 'YOUR API KEY'
20
+ config.api_version = 'v1'
21
+ config.timeout = 0 # sec
22
+ config.logger = Logger.new(STDOUT) # You can specify an alternative logger.
23
+ config.logger.level = :info # You can change the default log level.
24
+ end
25
+ ```
26
+
27
+ ## Examples
28
+ ### Basic usage
29
+ Request image recognition by an image URL.
30
+
31
+ ```
32
+ url = 'https://example.com/dummy.jpg'
33
+ recognition = client.recognize_url(url)
34
+
35
+ # you can override config.timeout.
36
+ recognition = client.recognize_url(url, timeout: 10)
37
+ ```
38
+
39
+ Request image recognition by a binary image.
40
+
41
+ ```
42
+ img = File.open('dummy_image_file', 'rb')
43
+ recognition = client.recognize_image(img)
44
+ ```
45
+
46
+ `Recognition` class represents the image recognition result from API.
47
+ If the recognition processing is completed, you will get `Recognition` instance whose state is `finished`.
48
+
49
+ ```
50
+ recognition.finished?
51
+ => true
52
+
53
+ recognition.to_h
54
+ => {"id"=>"20170829/ed4c674c-7970-4e9c-9b26-1b6076b36b49",
55
+ "objects"=>
56
+ [{"bounding_box"=>{"bottom"=>0.2696995, "left"=>0.3842466, "right"=>0.57190025, "top"=>0.14457992},
57
+ "category"=>"hat",
58
+ "labels"=>
59
+ [{"name"=>"ハット", "score"=>0.9985399},
60
+ {"name"=>"中折れ", "score"=>0.99334323},
61
+ {"name"=>"ストローハット", "score"=>0.95629793},
62
+ {"name"=>"ベージュ", "score"=>0.9062561},
63
+ {"name"=>"つば広ハット", "score"=>0.7737022},
64
+ {"name"=>"ホワイト", "score"=>0.5695046}]},
65
+ {"bounding_box"=>{"bottom"=>0.95560884, "left"=>0.41641566, "right"=>0.5212327, "top"=>0.8452401},
66
+ "category"=>"shoe",
67
+ "labels"=>
68
+ [{"name"=>"サンダル", "score"=>0.93934095},
69
+ {"name"=>"ホワイト", "score"=>0.74320596},
70
+ {"name"=>"パンプス", "score"=>0.70763165},
71
+ {"name"=>"サボ", "score"=>0.69153166},
72
+ {"name"=>"ストラップ", "score"=>0.66519636},
73
+ {"name"=>"ウェッジソール", "score"=>0.6325865},
74
+ {"name"=>"オープントゥ", "score"=>0.61965847},
75
+ {"name"=>"アンクルストラップ", "score"=>0.576824},
76
+ {"name"=>"厚底", "score"=>0.53842664}]},
77
+ {"bounding_box"=>{"bottom"=>0.7018228, "left"=>0.35182703, "right"=>0.6113004, "top"=>0.25296396},
78
+ "category"=>"dress",
79
+ "labels"=>[{"name"=>"グリーン", "score"=>0.9765959}, {"name"=>"ワンピース", "score"=>0.94697183}, {"name"=>"カーキ", "score"=>0.8136864}, {"name"=>"無地", "score"=>0.54719794}, {"name"=>"フレア", "score"=>0.51572186}]}],
80
+ "state"=>"finished"}
81
+ ```
82
+
83
+ If the timeout value is zero or `nil`, you will get `Recognition` instance whose state is `queued`.
84
+
85
+ Then you can fetch the recognition result using `Scnnr::Client#fetch`.
86
+
87
+ ```
88
+ recognition.queued?
89
+ => true
90
+
91
+ recognition.to_h
92
+ => {"id"=>"20170829/ed4c674c-7970-4e9c-9b26-1b6076b36b49", "state"=>"queued"}
93
+
94
+ recognition = client.fetch(recognition.id)
95
+ recognition.finished?
96
+ => true
97
+ ```
98
+
99
+ ### Error handling
100
+
101
+ If the recognition processing is not completed within the timeout time or the recognition failed,
102
+ you will get an error with `Recognition` instance.
103
+
104
+ ```
105
+ begin
106
+ url = 'https://example.com/dummy.jpg'
107
+ recognition = client.recognize_url(url, timeout: 10)
108
+ rescue Scnnr::TimeoutError => e
109
+ # You can fetch the result just like when the timeout value is zero or nil.
110
+ recognition = client.fetch(e.recognition.id, timeout: 10)
111
+ recognition.finished? # => true or false
112
+ rescue Scnnr::RecognitionFailed => e
113
+ # Failed to recognize the image you requested.
114
+ recognition = e.recognition
115
+ recognition.error? # => true
116
+ STDERR.puts "[ERROR] #{e.title}: #{e.detail} (e.type)"
117
+ rescue Scnnr::RequestFailed => e
118
+ # Failed to reserve the recognition.
119
+ # This kind of errors have no `#recognition` field.
120
+ STDERR.puts "[ERROR] #{e.title}: #{e.detail} (e.type)"
121
+ rescue Scnnr::RecognitionNotFound => e
122
+ # Failed to find the recognition with the specified ID.
123
+ # This kind of errors have no `#recognition` field.
124
+ STDERR.puts "[ERROR] #{e.title}: #{e.detail} (e.type)"
125
+ rescue => e
126
+ # Unexpected error.
127
+ raise
128
+ end
129
+ ```
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'scnnr'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ require 'pry'
12
+ Pry.start
13
+
14
+ # require 'irb'
15
+ # IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lib/scnnr.rb ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'scnnr/configuration'
4
+ require 'scnnr/errors'
5
+ require 'scnnr/recognition'
6
+ require 'scnnr/recognition/object'
7
+ require 'scnnr/recognition/object/bounding_box'
8
+ require 'scnnr/recognition/object/label'
9
+ require 'scnnr/client'
10
+ require 'scnnr/connection'
11
+ require 'scnnr/polling_manager'
12
+ require 'scnnr/response'
13
+ require 'scnnr/version'
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class Client
5
+ require 'net/http'
6
+ require 'json'
7
+
8
+ ENDPOINT_BASE = 'https://api.scnnr.cubki.jp'
9
+
10
+ def initialize
11
+ yield(self.config) if block_given?
12
+ end
13
+
14
+ def config
15
+ @config ||= Configuration.new
16
+ end
17
+
18
+ def recognize_image(image, options = {})
19
+ options = merge_options(options)
20
+ uri = construct_uri('recognitions', options)
21
+ # TODO: Use PollingManager to be accepted timeout > 25
22
+ response = post_connection(uri, options).send_stream(image)
23
+ handle_response(response, options)
24
+ end
25
+
26
+ def recognize_url(url, options = {})
27
+ options = merge_options(options)
28
+ uri = construct_uri('remote/recognitions', options)
29
+ # TODO: Use PollingManager to be accepted timeout > 25
30
+ response = post_connection(uri, options).send_json({ url: url })
31
+ handle_response(response, options)
32
+ end
33
+
34
+ def fetch(recognition_id, options = {})
35
+ return request(recognition_id, options) if options.delete(:polling) == false
36
+ options = merge_options(options)
37
+ PollingManager.new(options.delete(:timeout)).polling(self, recognition_id, options)
38
+ end
39
+
40
+ private
41
+
42
+ def merge_options(options = {})
43
+ self.config.to_h.merge(options)
44
+ end
45
+
46
+ def construct_uri(path, options = {})
47
+ options = merge_options(options)
48
+ URI.parse("#{ENDPOINT_BASE}/#{options[:api_version]}/#{path}?timeout=#{options[:timeout]}")
49
+ end
50
+
51
+ def get_connection(uri, options = {})
52
+ Connection.new(uri, :get, nil, options[:logger])
53
+ end
54
+
55
+ def post_connection(uri, options = {})
56
+ Connection.new(uri, :post, options[:api_key], options[:logger])
57
+ end
58
+
59
+ def request(recognition_id, options = {})
60
+ options = merge_options(options)
61
+ uri = construct_uri("recognitions/#{recognition_id}", options)
62
+ response = get_connection(uri, options).send_request
63
+ handle_response(response, options)
64
+ end
65
+
66
+ def handle_response(response, options = {})
67
+ response = Response.new(response, options[:timeout].positive?)
68
+ response.build_recognition
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ Configuration = Struct.new(:api_key, :api_version, :timeout, :logger) do
5
+ require 'logger'
6
+
7
+ DEFAULT_LOGGER = Logger.new(STDOUT, level: :info)
8
+
9
+ def initialize
10
+ super(nil, 'v1', 0, DEFAULT_LOGGER)
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class Connection
5
+ require 'net/http'
6
+ require 'json'
7
+
8
+ def initialize(uri, method, api_key, logger)
9
+ @uri = uri
10
+ @method = method
11
+ @api_key = api_key
12
+ @logger = logger
13
+ end
14
+
15
+ def send_stream(stream)
16
+ send_request do |req|
17
+ req['Content-Type'] = 'application/octet-stream'
18
+ req['Transfer-Encoding'] = 'chunked'
19
+ req.body_stream = stream
20
+ end
21
+ end
22
+
23
+ def send_json(data)
24
+ data = data.to_json if data.is_a?(Hash)
25
+ send_request do |req|
26
+ req['Content-Type'] = 'application/json'
27
+ req.body = data
28
+ end
29
+ end
30
+
31
+ def send_request
32
+ block = block_given? ? Proc.new : nil
33
+ request = build_request(&block)
34
+ run_request(request)
35
+ end
36
+
37
+ private
38
+
39
+ def run_request(request)
40
+ Net::HTTP.start(@uri.host, @uri.port, use_ssl: use_ssl?) do |http|
41
+ @logger&.info("Started #{@method.upcase} #{@uri}")
42
+ http.request(request)
43
+ end
44
+ end
45
+
46
+ def use_ssl?
47
+ @uri.scheme == 'https'
48
+ end
49
+
50
+ def build_request
51
+ request =
52
+ case @method&.intern
53
+ when :get then Net::HTTP::Get.new(@uri.request_uri)
54
+ when :post then Net::HTTP::Post.new(@uri.request_uri)
55
+ else raise NotImplementedError
56
+ end
57
+ yield(request) if block_given?
58
+ request['x-api-key'] = @api_key if @api_key
59
+ request
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class Error < StandardError
5
+ attr_accessor :detail, :title, :type
6
+
7
+ def initialize(message, attrs)
8
+ super(message)
9
+ @detail = attrs['detail']
10
+ @title = attrs['title']
11
+ @type = attrs['type']
12
+ end
13
+ end
14
+
15
+ class RequestFailed < Error; end
16
+
17
+ class RecognitionNotFound < Error; end
18
+
19
+ class RecognitionFailed < Error
20
+ attr_accessor :recognition
21
+
22
+ def initialize(message, recognition)
23
+ super(message, recognition.error)
24
+ @recognition = recognition
25
+ end
26
+ end
27
+
28
+ class TimeoutError < StandardError
29
+ attr_accessor :recognition
30
+
31
+ def initialize(message, recognition)
32
+ super(message)
33
+ @recognition = recognition
34
+ end
35
+ end
36
+
37
+ class UnsupportedError < StandardError
38
+ attr_accessor :response
39
+
40
+ def initialize(response)
41
+ super(response.body)
42
+ @response = response
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class PollingManager
5
+ MAX_TIMEOUT = 25
6
+
7
+ attr_accessor :timeout
8
+
9
+ def initialize(timeout)
10
+ case timeout
11
+ when Integer, Float::INFINITY then @timeout = timeout
12
+ else
13
+ raise ArgumentError, "timeout must be Integer or Float::INFINITY, but given: #{timeout}"
14
+ end
15
+ end
16
+
17
+ def remain_timeout?
18
+ self.timeout.positive?
19
+ end
20
+
21
+ def polling(client, recognition_id, options = {})
22
+ loop do
23
+ timeout = [self.timeout, MAX_TIMEOUT].min
24
+ self.timeout -= timeout
25
+ recognition = client.fetch(recognition_id, options.merge(timeout: timeout, polling: false))
26
+ break recognition if recognition.finished? || !self.remain_timeout?
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class Recognition
5
+ attr_reader :id, :objects, :state, :error
6
+
7
+ def initialize(attrs = {})
8
+ @id = attrs['id']
9
+ @objects = (attrs['objects'] || []).map { |obj| Object.new(obj) }
10
+ @state = attrs['state']&.intern
11
+ @error = attrs['error']
12
+ end
13
+
14
+ def queued?
15
+ self.state == :queued
16
+ end
17
+
18
+ def finished?
19
+ self.state == :finished
20
+ end
21
+
22
+ def error?
23
+ self.state == :error
24
+ end
25
+
26
+ def to_h
27
+ { 'id' => self.id, 'objects' => self.objects.map(&:to_h), 'state' => self.state.to_s }
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class Recognition
5
+ class Object
6
+ attr_reader :bounding_box, :category, :labels
7
+
8
+ def initialize(attrs = {})
9
+ @bounding_box = BoundingBox.new(attrs['bounding_box'])
10
+ @category = attrs['category']
11
+ @labels = (attrs['labels'] || []).map { |label| Label.new(label) }
12
+ end
13
+
14
+ def to_h
15
+ { 'bounding_box' => self.bounding_box.to_h, 'category' => self.category, 'labels' => self.labels.map(&:to_h) }
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class Recognition
5
+ class Object
6
+ class BoundingBox
7
+ attr_reader :bottom, :left, :right, :top
8
+
9
+ def initialize(attrs = {})
10
+ @bottom = attrs['bottom']
11
+ @left = attrs['left']
12
+ @right = attrs['right']
13
+ @top = attrs['top']
14
+ end
15
+
16
+ def to_h
17
+ { 'bottom' => self.bottom, 'left' => self.left, 'right' => self.right, 'top' => self.top }
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class Recognition
5
+ class Object
6
+ class Label
7
+ attr_reader :name, :score
8
+
9
+ def initialize(attrs = {})
10
+ @name = attrs['name']
11
+ @score = attrs['score']
12
+ end
13
+
14
+ def to_h
15
+ { 'name' => self.name, 'score' => self.score }
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ class Response
5
+ SUPPORTED_CONTENT_TYPE = 'application/jp.cubki.scnnr.v1+json'
6
+
7
+ def initialize(response, async)
8
+ raise UnsupportedError, response if response.content_type != SUPPORTED_CONTENT_TYPE
9
+ @response = response
10
+ @async = async
11
+ end
12
+
13
+ def body
14
+ @body ||= @response.body
15
+ end
16
+
17
+ def parsed_body
18
+ @parsed_body ||= JSON.parse(self.body)
19
+ end
20
+
21
+ def async?
22
+ @async == true
23
+ end
24
+
25
+ def build_recognition
26
+ case @response
27
+ when Net::HTTPSuccess
28
+ recognition = Recognition.new(self.parsed_body)
29
+ handle_recognition(recognition)
30
+ else
31
+ handle_error
32
+ end
33
+ end
34
+
35
+ private
36
+
37
+ def handle_recognition(recognition)
38
+ raise TimeoutError.new('recognition timed out', recognition) if recognition.queued? && async?
39
+ raise RecognitionFailed.new('recognition failed', recognition) if recognition.error?
40
+ recognition
41
+ end
42
+
43
+ def handle_error
44
+ case @response
45
+ when Net::HTTPNotFound
46
+ raise RecognitionNotFound.new('recognition not found', self.parsed_body)
47
+ when Net::HTTPUnprocessableEntity
48
+ raise RequestFailed.new('failed to reserve the recognition', self.parsed_body)
49
+ else raise UnsupportedError, @response
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scnnr
4
+ VERSION = '0.1.0'
5
+ end
data/scnnr.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ # frozen_string_literal: true
3
+
4
+ lib = File.expand_path('../lib', __FILE__)
5
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
6
+ require 'scnnr/version'
7
+
8
+ Gem::Specification.new do |spec|
9
+ spec.name = 'scnnr'
10
+ spec.version = Scnnr::VERSION
11
+ spec.authors = ['NEWROPE Co. Ltd.']
12
+ spec.email = ['support@newrope.biz']
13
+
14
+ spec.summary = spec.description
15
+ spec.description = 'Official #CBK scnnr client library for Ruby.'
16
+ spec.homepage = 'https://github.com/NEWROPE/scnnr-ruby'
17
+ spec.license = 'MIT'
18
+
19
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
20
+ f.match(%r{^(test|spec|features)/})
21
+ end
22
+ spec.bindir = 'bin'
23
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
24
+ spec.require_paths = ['lib']
25
+
26
+ spec.add_development_dependency 'bundler', '~> 1.15'
27
+ end
metadata ADDED
@@ -0,0 +1,83 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: scnnr
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - NEWROPE Co. Ltd.
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2017-09-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.15'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.15'
27
+ description: 'Official #CBK scnnr client library for Ruby.'
28
+ email:
29
+ - support@newrope.biz
30
+ executables:
31
+ - console
32
+ - setup
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - ".circleci/config.yml"
37
+ - ".gitignore"
38
+ - ".rubocop.yml"
39
+ - CODE_OF_CONDUCT.md
40
+ - Gemfile
41
+ - LICENSE
42
+ - README.md
43
+ - Rakefile
44
+ - bin/console
45
+ - bin/setup
46
+ - lib/scnnr.rb
47
+ - lib/scnnr/client.rb
48
+ - lib/scnnr/configuration.rb
49
+ - lib/scnnr/connection.rb
50
+ - lib/scnnr/errors.rb
51
+ - lib/scnnr/polling_manager.rb
52
+ - lib/scnnr/recognition.rb
53
+ - lib/scnnr/recognition/object.rb
54
+ - lib/scnnr/recognition/object/bounding_box.rb
55
+ - lib/scnnr/recognition/object/label.rb
56
+ - lib/scnnr/response.rb
57
+ - lib/scnnr/version.rb
58
+ - scnnr.gemspec
59
+ homepage: https://github.com/NEWROPE/scnnr-ruby
60
+ licenses:
61
+ - MIT
62
+ metadata: {}
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubyforge_project:
79
+ rubygems_version: 2.6.13
80
+ signing_key:
81
+ specification_version: 4
82
+ summary: ''
83
+ test_files: []