Skip to content

Instantly share code, notes, and snippets.

@ianhenrysmith
Last active May 1, 2018 22:01
Show Gist options
  • Select an option

  • Save ianhenrysmith/0cec016eb08a9387b538a030af9cd892 to your computer and use it in GitHub Desktop.

Select an option

Save ianhenrysmith/0cec016eb08a9387b538a030af9cd892 to your computer and use it in GitHub Desktop.
require "faraday"
require "byebug"
require "json"
require "nokogiri"
require "open-uri"
class ImagePopulator
# class to wrap the API for Match Reverse Image Search
# https://github.com/cleargraphinc/match
def initialize(
search_url: "http://0.0.0.0:8888",
random_image_source: "https://commons.wikimedia.org/wiki/Special:Random/File",
connection: Faraday.new(search_url) do |conn|
conn.request :url_encoded
conn.adapter :net_http
end
)
self.random_image_source = random_image_source
self.connection = connection
end
# populate Match with images
def create(count = 1)
count.times do |index|
image_url = random_image_src_url
current = index + 1
puts "creating image #{current} of #{count}: #{image_url}"
create_arbitrary(image_url)
rescue NoMethodError, Faraday::ConnectionFailed # ruby ^2.5.0 required for this
puts " * ERROR; SKIPPING *"
next
end
end
def create_arbitrary(image_url)
connection.post("/add", { url: image_url, filepath: image_url })
end
# get images matching url
def search(image_url)
response = connection.post("/search", { url: image_url })
JSON.parse(response.body)
end
def compare(image_url_1, image_url_2)
response = connection.post("/compare", { url_1: image_url_1, url_2: image_url_2 })
JSON.parse(response.body)
end
def list(offset = 0, limit = 20)
response = connection.get("/list", { offset: offset, limit: limit })
JSON.parse(response.body)
end
def count
response = connection.get("/count")
JSON.parse(response.body)
end
def delete(filepath)
# not working for some reason. used postman to do this manually
# maybe look at: https://gist.github.com/narath/9e74cb7dd17050c76936fded2861f2d1
# request.body = URI.encode({ filepath: filepath })?
connection.delete("/delete?filepath=#{filepath}")
end
private
attr_accessor :search_url, :random_image_source, :connection
def random_image_src_url
page = random_image_page
# get src of image from wikipedia random file page
page.css("#file").css("img").first.attribute("src").value
end
def random_image_page
Nokogiri::HTML(open(random_image_page_url))
end
def random_image_page_url
response = Faraday.get(random_image_source) # get random file page
image_url = response.headers["location"] # redirect url from 302 response
puts " random page url: #{image_url}"
image_url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment