1
0
mirror of https://github.com/danbee/my-images synced 2025-03-04 08:49:05 +00:00

Refactor Clarifai class

This commit is contained in:
Daniel Barber 2018-08-24 22:56:52 -04:00
parent 5bf0727fd0
commit f27285b419
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
2 changed files with 46 additions and 48 deletions

View File

@ -2,43 +2,48 @@ require "base64"
require "http" require "http"
class Clarifai class Clarifai
KEY = ENV.fetch("CLARIFAI_API_KEY").freeze API_KEY = ENV.fetch("CLARIFAI_API_KEY").freeze
API_URL = "https://api.clarifai.com/v2/models/" \ API_URL = "https://api.clarifai.com/v2/models/" \
"aaa03c23b3724a16a56b629203edc62c/outputs".freeze "aaa03c23b3724a16a56b629203edc62c/outputs".freeze
attr_reader :tags
def initialize(image_path) def initialize(image_path)
@image_path = image_path @image_path = image_path
end end
def predict! def tags
headers = { @tags ||= extract_tags(JSON.parse(post_image.body))
"Authorization": "Key #{KEY}",
"Content-Type": "application/json",
}
params = {
"inputs": [
{
"data": {
"image": {
"base64": Base64.encode64(File.read(@image_path)),
},
},
},
],
}
resp = HTTP.
headers(headers).
post(API_URL, json: params)
extract_tags(JSON.parse(resp.body))
end end
private
def extract_tags(response_hash) def extract_tags(response_hash)
@tags = response_hash["outputs"][0]["data"]["concepts"].map do |concept| response_hash["outputs"][0]["data"]["concepts"].map do |concept|
concept["name"] concept["name"]
end end
end end
def post_image
HTTP.
headers(headers).
post(API_URL, json: payload)
end
def headers
{
"Authorization": "Key #{API_KEY}",
"Content-Type": "application/json",
}
end
def payload
{ "inputs": [{ "data": { "image": { "base64": image_base64 } } }] }
end
def image_base64
Base64.encode64(image_file)
end
def image_file
File.read(@image_path)
end
end end

View File

@ -3,37 +3,30 @@ ENV["CLARIFAI_API_KEY"] = "1234"
require "clarifai" require "clarifai"
describe Clarifai do describe Clarifai do
describe ".predict" do describe ".tags" do
it "predicts tags for our image" do it "predicts tags for our image" do
stub_body = { WebMock.
stub_request(:post, Clarifai::API_URL).
to_return(status: 200, body: stub_body.to_json)
clarifai_image = Clarifai.new("spec/fixtures/spectrum.jpg")
expect(clarifai_image.tags).to eq(["computer", "technology"])
end
def stub_body
{
"outputs": [ "outputs": [
{ {
"data": { "data": {
"concepts": [ "concepts": [
{ { "name": "computer", "value": 0.96887743 },
"id": "ai_PpTcwbdQ", { "name": "technology", "value": 0.96544206 },
"name": "computer",
"value": 0.96887743,
},
{
"id": "ai_62K34TR4",
"name": "technology",
"value": 0.96544206,
},
], ],
}, },
}, },
], ],
}.to_json }
WebMock.
stub_request(:post, Clarifai::API_URL).
to_return(status: 200, body: stub_body)
clarifai_image = Clarifai.new("spec/fixtures/spectrum.jpg")
clarifai_image.predict!
expect(clarifai_image.tags).to eq(["computer", "technology"])
end end
end end
end end