Skip to content

Instantly share code, notes, and snippets.

@kozakana
Last active September 6, 2021 13:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kozakana/90b25bf231e84ece48a1c5175c6ac310 to your computer and use it in GitHub Desktop.
Save kozakana/90b25bf231e84ece48a1c5175c6ac310 to your computer and use it in GitHub Desktop.
Using Google cloud vision easily
require 'google/apis/vision_v1'
class GcvApi
def initialize api_key, option={}
default = {
retry: 5,
max_results: 2048,
language_hints: 'ja'
}
@option = default.merge option
@vision = Google::Apis::VisionV1::VisionService.new
@vision.key = api_key
Google::Apis::RequestOptions.default.retries = @option[:retry]
end
def analyzed_data image_path
request = Google::Apis::VisionV1::BatchAnnotateImagesRequest.new(
requests: [{
image: {content: File.read(image_path)},
features: [{
type: 'TEXT_DETECTION',
maxResults: @option[:max_results]
}],
imageContext: {languageHints: @option[:language_hints]}
}]
)
@vision.annotate_image(request)
end
def json image_path
self.analyzed_data(image_path).to_json
end
def text image_path
result = self.analyzed_data(image_path)
result.responses.map do |r|
r.text_annotations.first.description
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment