Created
June 11, 2013 02:31
-
-
Save avivo/5754128 to your computer and use it in GitHub Desktop.
A simple (only slightly hacky) ruby wrapper for some of the mobileworks.com crowdsourcing api.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
# LOGIN = 'username:password' | |
# Calls curl with the given (string) arguments and returns the resulting parsed json as a ruby object. | |
def curl_json(args) | |
# TODO: add error checking | |
call = "curl #{args}" | |
puts call | |
response = `#{call}` | |
puts response | |
response | |
JSON.parse(response) | |
end | |
# 'method' is either :task, or :project | |
# 'data' is the ruby object | |
# posts the task and return the json response as hash with some extra fields (like the :method and :id of the created object) | |
# set `data[:paid] = true` to send to real workers and not the sandbox | |
def post(method, data) | |
workers = if data[:paid] then 'work' else 'sandbox' end | |
data.delete(:paid) | |
json_data = data.to_json | |
response = curl_json("--data '#{json_data}' https://#{workers}.mobileworks.com/api/v2/#{method.to_s}/ -u #{LOGIN}") | |
response[:method] = method | |
response[:paid] = data[:paid] | |
response[:id] = response["Location"].match(/\/([^\/]*)\/$/)[1].to_i | |
response | |
end | |
# Given a response from post, gets the current results from workers | |
def get_results(response) | |
method = response[:method] | |
id = response[:id] | |
workers = if response[:paid] then 'work' else 'sandbox' end | |
curl_json("https://#{workers}.mobileworks.com/api/v2/#{method}/#{id}/ -u #{LOGIN}") | |
end | |
# Makes a map {resource -> answer} from finished tasks of a project | |
def answers_from_project_results(results) | |
Hash[results["tasks"].select {|t| t["status"] == "done" }.map {|t| [t["resource"], t["answer"]] }] | |
end | |
# Given answers from a partially completed project, add those tasks as tests (with answers) to the project, removing them from tasks. | |
def add_answers_as_tests(project, answers) | |
tests, tasks = project[:tasks].partition{|t| answers[t[:resource]]}; | |
tests.map{|t| | |
answer = answers[t[:resource]]; | |
t[:fields].map{|f| | |
ans = answer.detect{|ans| ans.keys.first == f.keys.first}; | |
f[:answers] = ans.values | |
} | |
} | |
project[:tasks] = tasks | |
project[:tests] = tests | |
end | |
# # Example task | |
# example_task = { | |
# instructions: 'What is _____?', | |
# fields: [{ '_____' => 't' }], | |
# resource: 'https://www.google.com/search?q=_____', | |
# resourcetype: 'l', | |
# redundancy: 1 | |
# } | |
# response = post(:task, example_task) | |
# results = get_results(response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment