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"
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/" \
"aaa03c23b3724a16a56b629203edc62c/outputs".freeze
attr_reader :tags
def initialize(image_path)
@image_path = image_path
end
def predict!
headers = {
"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))
def tags
@tags ||= extract_tags(JSON.parse(post_image.body))
end
private
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"]
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

View File

@ -3,37 +3,30 @@ ENV["CLARIFAI_API_KEY"] = "1234"
require "clarifai"
describe Clarifai do
describe ".predict" do
describe ".tags" 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": [
{
"data": {
"concepts": [
{
"id": "ai_PpTcwbdQ",
"name": "computer",
"value": 0.96887743,
},
{
"id": "ai_62K34TR4",
"name": "technology",
"value": 0.96544206,
},
{ "name": "computer", "value": 0.96887743 },
{ "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