PageRenderTime 50ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/boto-2.5.2/boto/mturk/connection.py

#
Python | 920 lines | 765 code | 50 blank | 105 comment | 28 complexity | e2099f4b275b2b556a8adaf6e3bbf63d MD5 | raw file
  1. # Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a
  4. # copy of this software and associated documentation files (the
  5. # "Software"), to deal in the Software without restriction, including
  6. # without limitation the rights to use, copy, modify, merge, publish, dis-
  7. # tribute, sublicense, and/or sell copies of the Software, and to permit
  8. # persons to whom the Software is furnished to do so, subject to the fol-
  9. # lowing conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included
  12. # in all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  16. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  17. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  18. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. # IN THE SOFTWARE.
  21. import xml.sax
  22. import datetime
  23. import itertools
  24. from boto import handler
  25. from boto import config
  26. from boto.mturk.price import Price
  27. import boto.mturk.notification
  28. from boto.connection import AWSQueryConnection
  29. from boto.exception import EC2ResponseError
  30. from boto.resultset import ResultSet
  31. from boto.mturk.question import QuestionForm, ExternalQuestion
  32. class MTurkRequestError(EC2ResponseError):
  33. "Error for MTurk Requests"
  34. # todo: subclass from an abstract parent of EC2ResponseError
  35. class MTurkConnection(AWSQueryConnection):
  36. APIVersion = '2008-08-02'
  37. def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
  38. is_secure=True, port=None, proxy=None, proxy_port=None,
  39. proxy_user=None, proxy_pass=None,
  40. host=None, debug=0,
  41. https_connection_factory=None):
  42. if not host:
  43. if config.has_option('MTurk', 'sandbox') and config.get('MTurk', 'sandbox') == 'True':
  44. host = 'mechanicalturk.sandbox.amazonaws.com'
  45. else:
  46. host = 'mechanicalturk.amazonaws.com'
  47. AWSQueryConnection.__init__(self, aws_access_key_id,
  48. aws_secret_access_key,
  49. is_secure, port, proxy, proxy_port,
  50. proxy_user, proxy_pass, host, debug,
  51. https_connection_factory)
  52. def _required_auth_capability(self):
  53. return ['mturk']
  54. def get_account_balance(self):
  55. """
  56. """
  57. params = {}
  58. return self._process_request('GetAccountBalance', params,
  59. [('AvailableBalance', Price),
  60. ('OnHoldBalance', Price)])
  61. def register_hit_type(self, title, description, reward, duration,
  62. keywords=None, approval_delay=None, qual_req=None):
  63. """
  64. Register a new HIT Type
  65. title, description are strings
  66. reward is a Price object
  67. duration can be a timedelta, or an object castable to an int
  68. """
  69. params = dict(
  70. Title=title,
  71. Description=description,
  72. AssignmentDurationInSeconds=
  73. self.duration_as_seconds(duration),
  74. )
  75. params.update(MTurkConnection.get_price_as_price(reward).get_as_params('Reward'))
  76. if keywords:
  77. params['Keywords'] = self.get_keywords_as_string(keywords)
  78. if approval_delay is not None:
  79. d = self.duration_as_seconds(approval_delay)
  80. params['AutoApprovalDelayInSeconds'] = d
  81. if qual_req is not None:
  82. params.update(qual_req.get_as_params())
  83. return self._process_request('RegisterHITType', params, [('HITTypeId', HITTypeId)])
  84. def set_email_notification(self, hit_type, email, event_types=None):
  85. """
  86. Performs a SetHITTypeNotification operation to set email
  87. notification for a specified HIT type
  88. """
  89. return self._set_notification(hit_type, 'Email', email, event_types)
  90. def set_rest_notification(self, hit_type, url, event_types=None):
  91. """
  92. Performs a SetHITTypeNotification operation to set REST notification
  93. for a specified HIT type
  94. """
  95. return self._set_notification(hit_type, 'REST', url, event_types)
  96. def _set_notification(self, hit_type, transport, destination, event_types=None):
  97. """
  98. Common SetHITTypeNotification operation to set notification for a
  99. specified HIT type
  100. """
  101. assert isinstance(hit_type, str), "hit_type argument should be a string."
  102. params = {'HITTypeId': hit_type}
  103. # from the Developer Guide:
  104. # The 'Active' parameter is optional. If omitted, the active status of
  105. # the HIT type's notification specification is unchanged. All HIT types
  106. # begin with their notification specifications in the "inactive" status.
  107. notification_params = {'Destination': destination,
  108. 'Transport': transport,
  109. 'Version': boto.mturk.notification.NotificationMessage.NOTIFICATION_VERSION,
  110. 'Active': True,
  111. }
  112. # add specific event types if required
  113. if event_types:
  114. self.build_list_params(notification_params, event_types, 'EventType')
  115. # Set up dict of 'Notification.1.Transport' etc. values
  116. notification_rest_params = {}
  117. num = 1
  118. for key in notification_params:
  119. notification_rest_params['Notification.%d.%s' % (num, key)] = notification_params[key]
  120. # Update main params dict
  121. params.update(notification_rest_params)
  122. # Execute operation
  123. return self._process_request('SetHITTypeNotification', params)
  124. def create_hit(self, hit_type=None, question=None,
  125. lifetime=datetime.timedelta(days=7),
  126. max_assignments=1,
  127. title=None, description=None, keywords=None,
  128. reward=None, duration=datetime.timedelta(days=7),
  129. approval_delay=None, annotation=None,
  130. questions=None, qualifications=None,
  131. response_groups=None):
  132. """
  133. Creates a new HIT.
  134. Returns a ResultSet
  135. See: http://docs.amazonwebservices.com/AWSMechanicalTurkRequester/2006-10-31/ApiReference_CreateHITOperation.html
  136. """
  137. # handle single or multiple questions
  138. neither = question is None and questions is None
  139. both = question is not None and questions is not None
  140. if neither or both:
  141. raise ValueError("Must specify either question (single Question instance) or questions (list or QuestionForm instance), but not both")
  142. if question:
  143. questions = [question]
  144. question_param = QuestionForm(questions)
  145. if isinstance(question, QuestionForm):
  146. question_param = question
  147. elif isinstance(question, ExternalQuestion):
  148. question_param = question
  149. # Handle basic required arguments and set up params dict
  150. params = {'Question': question_param.get_as_xml(),
  151. 'LifetimeInSeconds':
  152. self.duration_as_seconds(lifetime),
  153. 'MaxAssignments': max_assignments,
  154. }
  155. # if hit type specified then add it
  156. # else add the additional required parameters
  157. if hit_type:
  158. params['HITTypeId'] = hit_type
  159. else:
  160. # Handle keywords
  161. final_keywords = MTurkConnection.get_keywords_as_string(keywords)
  162. # Handle price argument
  163. final_price = MTurkConnection.get_price_as_price(reward)
  164. final_duration = self.duration_as_seconds(duration)
  165. additional_params = dict(
  166. Title=title,
  167. Description=description,
  168. Keywords=final_keywords,
  169. AssignmentDurationInSeconds=final_duration,
  170. )
  171. additional_params.update(final_price.get_as_params('Reward'))
  172. if approval_delay is not None:
  173. d = self.duration_as_seconds(approval_delay)
  174. additional_params['AutoApprovalDelayInSeconds'] = d
  175. # add these params to the others
  176. params.update(additional_params)
  177. # add the annotation if specified
  178. if annotation is not None:
  179. params['RequesterAnnotation'] = annotation
  180. # Add the Qualifications if specified
  181. if qualifications is not None:
  182. params.update(qualifications.get_as_params())
  183. # Handle optional response groups argument
  184. if response_groups:
  185. self.build_list_params(params, response_groups, 'ResponseGroup')
  186. # Submit
  187. return self._process_request('CreateHIT', params, [('HIT', HIT),])
  188. def change_hit_type_of_hit(self, hit_id, hit_type):
  189. """
  190. Change the HIT type of an existing HIT. Note that the reward associated
  191. with the new HIT type must match the reward of the current HIT type in
  192. order for the operation to be valid.
  193. :type hit_id: str
  194. :type hit_type: str
  195. """
  196. params = {'HITId' : hit_id,
  197. 'HITTypeId': hit_type}
  198. return self._process_request('ChangeHITTypeOfHIT', params)
  199. def get_reviewable_hits(self, hit_type=None, status='Reviewable',
  200. sort_by='Expiration', sort_direction='Ascending',
  201. page_size=10, page_number=1):
  202. """
  203. Retrieve the HITs that have a status of Reviewable, or HITs that
  204. have a status of Reviewing, and that belong to the Requester
  205. calling the operation.
  206. """
  207. params = {'Status' : status,
  208. 'SortProperty' : sort_by,
  209. 'SortDirection' : sort_direction,
  210. 'PageSize' : page_size,
  211. 'PageNumber' : page_number}
  212. # Handle optional hit_type argument
  213. if hit_type is not None:
  214. params.update({'HITTypeId': hit_type})
  215. return self._process_request('GetReviewableHITs', params, [('HIT', HIT),])
  216. @staticmethod
  217. def _get_pages(page_size, total_records):
  218. """
  219. Given a page size (records per page) and a total number of
  220. records, return the page numbers to be retrieved.
  221. """
  222. pages = total_records/page_size+bool(total_records%page_size)
  223. return range(1, pages+1)
  224. def get_all_hits(self):
  225. """
  226. Return all of a Requester's HITs
  227. Despite what search_hits says, it does not return all hits, but
  228. instead returns a page of hits. This method will pull the hits
  229. from the server 100 at a time, but will yield the results
  230. iteratively, so subsequent requests are made on demand.
  231. """
  232. page_size = 100
  233. search_rs = self.search_hits(page_size=page_size)
  234. total_records = int(search_rs.TotalNumResults)
  235. get_page_hits = lambda page: self.search_hits(page_size=page_size, page_number=page)
  236. page_nums = self._get_pages(page_size, total_records)
  237. hit_sets = itertools.imap(get_page_hits, page_nums)
  238. return itertools.chain.from_iterable(hit_sets)
  239. def search_hits(self, sort_by='CreationTime', sort_direction='Ascending',
  240. page_size=10, page_number=1, response_groups=None):
  241. """
  242. Return a page of a Requester's HITs, on behalf of the Requester.
  243. The operation returns HITs of any status, except for HITs that
  244. have been disposed with the DisposeHIT operation.
  245. Note:
  246. The SearchHITs operation does not accept any search parameters
  247. that filter the results.
  248. """
  249. params = {'SortProperty' : sort_by,
  250. 'SortDirection' : sort_direction,
  251. 'PageSize' : page_size,
  252. 'PageNumber' : page_number}
  253. # Handle optional response groups argument
  254. if response_groups:
  255. self.build_list_params(params, response_groups, 'ResponseGroup')
  256. return self._process_request('SearchHITs', params, [('HIT', HIT),])
  257. def get_assignments(self, hit_id, status=None,
  258. sort_by='SubmitTime', sort_direction='Ascending',
  259. page_size=10, page_number=1, response_groups=None):
  260. """
  261. Retrieves completed assignments for a HIT.
  262. Use this operation to retrieve the results for a HIT.
  263. The returned ResultSet will have the following attributes:
  264. NumResults
  265. The number of assignments on the page in the filtered results
  266. list, equivalent to the number of assignments being returned
  267. by this call.
  268. A non-negative integer
  269. PageNumber
  270. The number of the page in the filtered results list being
  271. returned.
  272. A positive integer
  273. TotalNumResults
  274. The total number of HITs in the filtered results list based
  275. on this call.
  276. A non-negative integer
  277. The ResultSet will contain zero or more Assignment objects
  278. """
  279. params = {'HITId' : hit_id,
  280. 'SortProperty' : sort_by,
  281. 'SortDirection' : sort_direction,
  282. 'PageSize' : page_size,
  283. 'PageNumber' : page_number}
  284. if status is not None:
  285. params['AssignmentStatus'] = status
  286. # Handle optional response groups argument
  287. if response_groups:
  288. self.build_list_params(params, response_groups, 'ResponseGroup')
  289. return self._process_request('GetAssignmentsForHIT', params,
  290. [('Assignment', Assignment),])
  291. def approve_assignment(self, assignment_id, feedback=None):
  292. """
  293. """
  294. params = {'AssignmentId': assignment_id,}
  295. if feedback:
  296. params['RequesterFeedback'] = feedback
  297. return self._process_request('ApproveAssignment', params)
  298. def reject_assignment(self, assignment_id, feedback=None):
  299. """
  300. """
  301. params = {'AssignmentId': assignment_id,}
  302. if feedback:
  303. params['RequesterFeedback'] = feedback
  304. return self._process_request('RejectAssignment', params)
  305. def get_hit(self, hit_id, response_groups=None):
  306. """
  307. """
  308. params = {'HITId': hit_id,}
  309. # Handle optional response groups argument
  310. if response_groups:
  311. self.build_list_params(params, response_groups, 'ResponseGroup')
  312. return self._process_request('GetHIT', params, [('HIT', HIT),])
  313. def set_reviewing(self, hit_id, revert=None):
  314. """
  315. Update a HIT with a status of Reviewable to have a status of Reviewing,
  316. or reverts a Reviewing HIT back to the Reviewable status.
  317. Only HITs with a status of Reviewable can be updated with a status of
  318. Reviewing. Similarly, only Reviewing HITs can be reverted back to a
  319. status of Reviewable.
  320. """
  321. params = {'HITId': hit_id,}
  322. if revert:
  323. params['Revert'] = revert
  324. return self._process_request('SetHITAsReviewing', params)
  325. def disable_hit(self, hit_id, response_groups=None):
  326. """
  327. Remove a HIT from the Mechanical Turk marketplace, approves all
  328. submitted assignments that have not already been approved or rejected,
  329. and disposes of the HIT and all assignment data.
  330. Assignments for the HIT that have already been submitted, but not yet
  331. approved or rejected, will be automatically approved. Assignments in
  332. progress at the time of the call to DisableHIT will be approved once
  333. the assignments are submitted. You will be charged for approval of
  334. these assignments. DisableHIT completely disposes of the HIT and
  335. all submitted assignment data. Assignment results data cannot be
  336. retrieved for a HIT that has been disposed.
  337. It is not possible to re-enable a HIT once it has been disabled.
  338. To make the work from a disabled HIT available again, create a new HIT.
  339. """
  340. params = {'HITId': hit_id,}
  341. # Handle optional response groups argument
  342. if response_groups:
  343. self.build_list_params(params, response_groups, 'ResponseGroup')
  344. return self._process_request('DisableHIT', params)
  345. def dispose_hit(self, hit_id):
  346. """
  347. Dispose of a HIT that is no longer needed.
  348. Only HITs in the "reviewable" state, with all submitted
  349. assignments approved or rejected, can be disposed. A Requester
  350. can call GetReviewableHITs to determine which HITs are
  351. reviewable, then call GetAssignmentsForHIT to retrieve the
  352. assignments. Disposing of a HIT removes the HIT from the
  353. results of a call to GetReviewableHITs. """
  354. params = {'HITId': hit_id,}
  355. return self._process_request('DisposeHIT', params)
  356. def expire_hit(self, hit_id):
  357. """
  358. Expire a HIT that is no longer needed.
  359. The effect is identical to the HIT expiring on its own. The
  360. HIT no longer appears on the Mechanical Turk web site, and no
  361. new Workers are allowed to accept the HIT. Workers who have
  362. accepted the HIT prior to expiration are allowed to complete
  363. it or return it, or allow the assignment duration to elapse
  364. (abandon the HIT). Once all remaining assignments have been
  365. submitted, the expired HIT becomes"reviewable", and will be
  366. returned by a call to GetReviewableHITs.
  367. """
  368. params = {'HITId': hit_id,}
  369. return self._process_request('ForceExpireHIT', params)
  370. def extend_hit(self, hit_id, assignments_increment=None, expiration_increment=None):
  371. """
  372. Increase the maximum number of assignments, or extend the
  373. expiration date, of an existing HIT.
  374. NOTE: If a HIT has a status of Reviewable and the HIT is
  375. extended to make it Available, the HIT will not be returned by
  376. GetReviewableHITs, and its submitted assignments will not be
  377. returned by GetAssignmentsForHIT, until the HIT is Reviewable
  378. again. Assignment auto-approval will still happen on its
  379. original schedule, even if the HIT has been extended. Be sure
  380. to retrieve and approve (or reject) submitted assignments
  381. before extending the HIT, if so desired.
  382. """
  383. # must provide assignment *or* expiration increment
  384. if (assignments_increment is None and expiration_increment is None) or \
  385. (assignments_increment is not None and expiration_increment is not None):
  386. raise ValueError("Must specify either assignments_increment or expiration_increment, but not both")
  387. params = {'HITId': hit_id,}
  388. if assignments_increment:
  389. params['MaxAssignmentsIncrement'] = assignments_increment
  390. if expiration_increment:
  391. params['ExpirationIncrementInSeconds'] = expiration_increment
  392. return self._process_request('ExtendHIT', params)
  393. def get_help(self, about, help_type='Operation'):
  394. """
  395. Return information about the Mechanical Turk Service
  396. operations and response group NOTE - this is basically useless
  397. as it just returns the URL of the documentation
  398. help_type: either 'Operation' or 'ResponseGroup'
  399. """
  400. params = {'About': about, 'HelpType': help_type,}
  401. return self._process_request('Help', params)
  402. def grant_bonus(self, worker_id, assignment_id, bonus_price, reason):
  403. """
  404. Issues a payment of money from your account to a Worker. To
  405. be eligible for a bonus, the Worker must have submitted
  406. results for one of your HITs, and have had those results
  407. approved or rejected. This payment happens separately from the
  408. reward you pay to the Worker when you approve the Worker's
  409. assignment. The Bonus must be passed in as an instance of the
  410. Price object.
  411. """
  412. params = bonus_price.get_as_params('BonusAmount', 1)
  413. params['WorkerId'] = worker_id
  414. params['AssignmentId'] = assignment_id
  415. params['Reason'] = reason
  416. return self._process_request('GrantBonus', params)
  417. def block_worker(self, worker_id, reason):
  418. """
  419. Block a worker from working on my tasks.
  420. """
  421. params = {'WorkerId': worker_id, 'Reason': reason}
  422. return self._process_request('BlockWorker', params)
  423. def unblock_worker(self, worker_id, reason):
  424. """
  425. Unblock a worker from working on my tasks.
  426. """
  427. params = {'WorkerId': worker_id, 'Reason': reason}
  428. return self._process_request('UnblockWorker', params)
  429. def notify_workers(self, worker_ids, subject, message_text):
  430. """
  431. Send a text message to workers.
  432. """
  433. params = {'Subject' : subject,
  434. 'MessageText': message_text}
  435. self.build_list_params(params, worker_ids, 'WorkerId')
  436. return self._process_request('NotifyWorkers', params)
  437. def create_qualification_type(self,
  438. name,
  439. description,
  440. status,
  441. keywords=None,
  442. retry_delay=None,
  443. test=None,
  444. answer_key=None,
  445. answer_key_xml=None,
  446. test_duration=None,
  447. auto_granted=False,
  448. auto_granted_value=1):
  449. """
  450. Create a new Qualification Type.
  451. name: This will be visible to workers and must be unique for a
  452. given requester.
  453. description: description shown to workers. Max 2000 characters.
  454. status: 'Active' or 'Inactive'
  455. keywords: list of keyword strings or comma separated string.
  456. Max length of 1000 characters when concatenated with commas.
  457. retry_delay: number of seconds after requesting a
  458. qualification the worker must wait before they can ask again.
  459. If not specified, workers can only request this qualification
  460. once.
  461. test: a QuestionForm
  462. answer_key: an XML string of your answer key, for automatically
  463. scored qualification tests.
  464. (Consider implementing an AnswerKey class for this to support.)
  465. test_duration: the number of seconds a worker has to complete the test.
  466. auto_granted: if True, requests for the Qualification are granted
  467. immediately. Can't coexist with a test.
  468. auto_granted_value: auto_granted qualifications are given this value.
  469. """
  470. params = {'Name': name,
  471. 'Description': description,
  472. 'QualificationTypeStatus': status,
  473. }
  474. if retry_delay is not None:
  475. params['RetryDelayInSeconds'] = retry_delay
  476. if test is not None:
  477. assert(isinstance(test, QuestionForm))
  478. assert(test_duration is not None)
  479. params['Test'] = test.get_as_xml()
  480. if test_duration is not None:
  481. params['TestDurationInSeconds'] = test_duration
  482. if answer_key is not None:
  483. if isinstance(answer_key, basestring):
  484. params['AnswerKey'] = answer_key # xml
  485. else:
  486. raise TypeError
  487. # Eventually someone will write an AnswerKey class.
  488. if auto_granted:
  489. assert(test is None)
  490. params['AutoGranted'] = True
  491. params['AutoGrantedValue'] = auto_granted_value
  492. if keywords:
  493. params['Keywords'] = self.get_keywords_as_string(keywords)
  494. return self._process_request('CreateQualificationType', params,
  495. [('QualificationType', QualificationType),])
  496. def get_qualification_type(self, qualification_type_id):
  497. params = {'QualificationTypeId' : qualification_type_id }
  498. return self._process_request('GetQualificationType', params,
  499. [('QualificationType', QualificationType),])
  500. def get_qualifications_for_qualification_type(self, qualification_type_id):
  501. params = {'QualificationTypeId' : qualification_type_id }
  502. return self._process_request('GetQualificationsForQualificationType', params,
  503. [('QualificationType', QualificationType),])
  504. def update_qualification_type(self, qualification_type_id,
  505. description=None,
  506. status=None,
  507. retry_delay=None,
  508. test=None,
  509. answer_key=None,
  510. test_duration=None,
  511. auto_granted=None,
  512. auto_granted_value=None):
  513. params = {'QualificationTypeId' : qualification_type_id }
  514. if description is not None:
  515. params['Description'] = description
  516. if status is not None:
  517. params['QualificationTypeStatus'] = status
  518. if retry_delay is not None:
  519. params['RetryDelayInSeconds'] = retry_delay
  520. if test is not None:
  521. assert(isinstance(test, QuestionForm))
  522. params['Test'] = test.get_as_xml()
  523. if test_duration is not None:
  524. params['TestDurationInSeconds'] = test_duration
  525. if answer_key is not None:
  526. if isinstance(answer_key, basestring):
  527. params['AnswerKey'] = answer_key # xml
  528. else:
  529. raise TypeError
  530. # Eventually someone will write an AnswerKey class.
  531. if auto_granted is not None:
  532. params['AutoGranted'] = auto_granted
  533. if auto_granted_value is not None:
  534. params['AutoGrantedValue'] = auto_granted_value
  535. return self._process_request('UpdateQualificationType', params,
  536. [('QualificationType', QualificationType),])
  537. def dispose_qualification_type(self, qualification_type_id):
  538. """TODO: Document."""
  539. params = {'QualificationTypeId' : qualification_type_id}
  540. return self._process_request('DisposeQualificationType', params)
  541. def search_qualification_types(self, query=None, sort_by='Name',
  542. sort_direction='Ascending', page_size=10,
  543. page_number=1, must_be_requestable=True,
  544. must_be_owned_by_caller=True):
  545. """TODO: Document."""
  546. params = {'Query' : query,
  547. 'SortProperty' : sort_by,
  548. 'SortDirection' : sort_direction,
  549. 'PageSize' : page_size,
  550. 'PageNumber' : page_number,
  551. 'MustBeRequestable' : must_be_requestable,
  552. 'MustBeOwnedByCaller' : must_be_owned_by_caller}
  553. return self._process_request('SearchQualificationTypes', params,
  554. [('QualificationType', QualificationType),])
  555. def get_qualification_requests(self, qualification_type_id,
  556. sort_by='Expiration',
  557. sort_direction='Ascending', page_size=10,
  558. page_number=1):
  559. """TODO: Document."""
  560. params = {'QualificationTypeId' : qualification_type_id,
  561. 'SortProperty' : sort_by,
  562. 'SortDirection' : sort_direction,
  563. 'PageSize' : page_size,
  564. 'PageNumber' : page_number}
  565. return self._process_request('GetQualificationRequests', params,
  566. [('QualificationRequest', QualificationRequest),])
  567. def grant_qualification(self, qualification_request_id, integer_value=1):
  568. """TODO: Document."""
  569. params = {'QualificationRequestId' : qualification_request_id,
  570. 'IntegerValue' : integer_value}
  571. return self._process_request('GrantQualification', params)
  572. def revoke_qualification(self, subject_id, qualification_type_id,
  573. reason=None):
  574. """TODO: Document."""
  575. params = {'SubjectId' : subject_id,
  576. 'QualificationTypeId' : qualification_type_id,
  577. 'Reason' : reason}
  578. return self._process_request('RevokeQualification', params)
  579. def assign_qualification(self, qualification_type_id, worker_id,
  580. value=1, send_notification=True):
  581. params = {'QualificationTypeId' : qualification_type_id,
  582. 'WorkerId' : worker_id,
  583. 'IntegerValue' : value,
  584. 'SendNotification' : send_notification}
  585. return self._process_request('AssignQualification', params)
  586. def get_qualification_score(self, qualification_type_id, worker_id):
  587. """TODO: Document."""
  588. params = {'QualificationTypeId' : qualification_type_id,
  589. 'SubjectId' : worker_id}
  590. return self._process_request('GetQualificationScore', params,
  591. [('Qualification', Qualification),])
  592. def update_qualification_score(self, qualification_type_id, worker_id,
  593. value):
  594. """TODO: Document."""
  595. params = {'QualificationTypeId' : qualification_type_id,
  596. 'SubjectId' : worker_id,
  597. 'IntegerValue' : value}
  598. return self._process_request('UpdateQualificationScore', params)
  599. def _process_request(self, request_type, params, marker_elems=None):
  600. """
  601. Helper to process the xml response from AWS
  602. """
  603. response = self.make_request(request_type, params, verb='POST')
  604. return self._process_response(response, marker_elems)
  605. def _process_response(self, response, marker_elems=None):
  606. """
  607. Helper to process the xml response from AWS
  608. """
  609. body = response.read()
  610. #print body
  611. if '<Errors>' not in body:
  612. rs = ResultSet(marker_elems)
  613. h = handler.XmlHandler(rs, self)
  614. xml.sax.parseString(body, h)
  615. return rs
  616. else:
  617. raise MTurkRequestError(response.status, response.reason, body)
  618. @staticmethod
  619. def get_keywords_as_string(keywords):
  620. """
  621. Returns a comma+space-separated string of keywords from either
  622. a list or a string
  623. """
  624. if isinstance(keywords, list):
  625. keywords = ', '.join(keywords)
  626. if isinstance(keywords, str):
  627. final_keywords = keywords
  628. elif isinstance(keywords, unicode):
  629. final_keywords = keywords.encode('utf-8')
  630. elif keywords is None:
  631. final_keywords = ""
  632. else:
  633. raise TypeError("keywords argument must be a string or a list of strings; got a %s" % type(keywords))
  634. return final_keywords
  635. @staticmethod
  636. def get_price_as_price(reward):
  637. """
  638. Returns a Price data structure from either a float or a Price
  639. """
  640. if isinstance(reward, Price):
  641. final_price = reward
  642. else:
  643. final_price = Price(reward)
  644. return final_price
  645. @staticmethod
  646. def duration_as_seconds(duration):
  647. if isinstance(duration, datetime.timedelta):
  648. duration = duration.days*86400 + duration.seconds
  649. try:
  650. duration = int(duration)
  651. except TypeError:
  652. raise TypeError("Duration must be a timedelta or int-castable, got %s" % type(duration))
  653. return duration
  654. class BaseAutoResultElement:
  655. """
  656. Base class to automatically add attributes when parsing XML
  657. """
  658. def __init__(self, connection):
  659. pass
  660. def startElement(self, name, attrs, connection):
  661. return None
  662. def endElement(self, name, value, connection):
  663. setattr(self, name, value)
  664. class HIT(BaseAutoResultElement):
  665. """
  666. Class to extract a HIT structure from a response (used in ResultSet)
  667. Will have attributes named as per the Developer Guide,
  668. e.g. HITId, HITTypeId, CreationTime
  669. """
  670. # property helper to determine if HIT has expired
  671. def _has_expired(self):
  672. """ Has this HIT expired yet? """
  673. expired = False
  674. if hasattr(self, 'Expiration'):
  675. now = datetime.datetime.utcnow()
  676. expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
  677. expired = (now >= expiration)
  678. else:
  679. raise ValueError("ERROR: Request for expired property, but no Expiration in HIT!")
  680. return expired
  681. # are we there yet?
  682. expired = property(_has_expired)
  683. class HITTypeId(BaseAutoResultElement):
  684. """
  685. Class to extract an HITTypeId structure from a response
  686. """
  687. pass
  688. class Qualification(BaseAutoResultElement):
  689. """
  690. Class to extract an Qualification structure from a response (used in
  691. ResultSet)
  692. Will have attributes named as per the Developer Guide such as
  693. QualificationTypeId, IntegerValue. Does not seem to contain GrantTime.
  694. """
  695. pass
  696. class QualificationType(BaseAutoResultElement):
  697. """
  698. Class to extract an QualificationType structure from a response (used in
  699. ResultSet)
  700. Will have attributes named as per the Developer Guide,
  701. e.g. QualificationTypeId, CreationTime, Name, etc
  702. """
  703. pass
  704. class QualificationRequest(BaseAutoResultElement):
  705. """
  706. Class to extract an QualificationRequest structure from a response (used in
  707. ResultSet)
  708. Will have attributes named as per the Developer Guide,
  709. e.g. QualificationRequestId, QualificationTypeId, SubjectId, etc
  710. TODO: Ensure that Test and Answer attribute are treated properly if the
  711. qualification requires a test. These attributes are XML-encoded.
  712. """
  713. pass
  714. class Assignment(BaseAutoResultElement):
  715. """
  716. Class to extract an Assignment structure from a response (used in
  717. ResultSet)
  718. Will have attributes named as per the Developer Guide,
  719. e.g. AssignmentId, WorkerId, HITId, Answer, etc
  720. """
  721. def __init__(self, connection):
  722. BaseAutoResultElement.__init__(self, connection)
  723. self.answers = []
  724. def endElement(self, name, value, connection):
  725. # the answer consists of embedded XML, so it needs to be parsed independantly
  726. if name == 'Answer':
  727. answer_rs = ResultSet([('Answer', QuestionFormAnswer),])
  728. h = handler.XmlHandler(answer_rs, connection)
  729. value = connection.get_utf8_value(value)
  730. xml.sax.parseString(value, h)
  731. self.answers.append(answer_rs)
  732. else:
  733. BaseAutoResultElement.endElement(self, name, value, connection)
  734. class QuestionFormAnswer(BaseAutoResultElement):
  735. """
  736. Class to extract Answers from inside the embedded XML
  737. QuestionFormAnswers element inside the Answer element which is
  738. part of the Assignment structure
  739. A QuestionFormAnswers element contains an Answer element for each
  740. question in the HIT or Qualification test for which the Worker
  741. provided an answer. Each Answer contains a QuestionIdentifier
  742. element whose value corresponds to the QuestionIdentifier of a
  743. Question in the QuestionForm. See the QuestionForm data structure
  744. for more information about questions and answer specifications.
  745. If the question expects a free-text answer, the Answer element
  746. contains a FreeText element. This element contains the Worker's
  747. answer
  748. *NOTE* - currently really only supports free-text and selection answers
  749. """
  750. def __init__(self, connection):
  751. BaseAutoResultElement.__init__(self, connection)
  752. self.fields = []
  753. self.qid = None
  754. def endElement(self, name, value, connection):
  755. if name == 'QuestionIdentifier':
  756. self.qid = value
  757. elif name in ['FreeText', 'SelectionIdentifier', 'OtherSelectionText'] and self.qid:
  758. self.fields.append( value )