o
    rMfp                     @   s0  d dl Zd dlZd dlZd dlmZ d dlmZ d dlmZ d dl	Zd dl
mZ d dlmZ d dlmZ d dlmZmZmZ G d	d
 d
eZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZdS )    N)handler)config)Price)AWSQueryConnection)EC2ResponseError)	ResultSet)QuestionFormExternalQuestionHTMLQuestionc                   @      e Zd ZdZdS )MTurkRequestErrorzError for MTurk RequestsN__name__
__module____qualname____doc__ r   r   W/var/www/html/analyze/labelStudio/lib/python3.10/site-packages/boto/mturk/connection.pyr   #   s    r   c                       s~  e Zd ZdZ						dw fdd	Zdd Zd	d
 Z	dxddZdyddZdyddZ	dyddZ
		dzddZ	d{ddZdddejdddddddejddddddddfddZdd Z		!	d|d#d$Zed%d& Zd'd( Z	!	d}d*d+Zdyd,d-Z		!	d~d/d0Zdyd1d2Zdyd3d4Zdyd5d6Zd7d8 Zdyd9d:Zdyd;d<Zdyd=d>Zd?d@ ZdAdB Z 		d{dCdDZ!ddFdGZ"dHdI Z#dJdK Z$dLdM Z%dNdO Z&							P	ddQdRZ'dSdT Z(dUdV Z)ddXdYZ*								ddZd[Z+d\d] Z,	^	"		dd_d`Z-	 	"	ddadbZ.ddcddZ/	dydedfZ0	ddgdhZ1didj Z2dkdl Z3dydmdnZ4dydodpZ5edqdr Z6edsdt Z7edudv Z8  Z9S )MTurkConnectionz
2014-08-15NTr   c                    s^   |	st ddrt dddkrd}	nd}	|
| _tt| j|||||||||	|
|||d d S )NMTurksandboxTruez$mechanicalturk.sandbox.amazonaws.comzmechanicalturk.amazonaws.com)security_tokenprofile_name)r   
has_optiongetdebugsuperr   __init__)selfaws_access_key_idaws_secret_access_key	is_secureportproxy
proxy_port
proxy_user
proxy_passhostr   https_connection_factoryr   r   	__class__r   r   r   ,   s   
zMTurkConnection.__init__c                 C   s   dgS )Nmturkr   )r   r   r   r   _required_auth_capabilityA   s   z)MTurkConnection._required_auth_capabilityc                 C   s   i }|  d|dtfdtfgS )	
        GetAccountBalanceAvailableBalanceOnHoldBalance)_process_requestr   )r   paramsr   r   r   get_account_balanceD   s   z#MTurkConnection.get_account_balancec           
      C   s   t ||| |d}|t|d |r| ||d< |dur+| |}	|	|d< |dur6||  | d|dtfgS )z
        Register a new HIT Type
        title, description are strings
        reward is a Price object
        duration can be a timedelta, or an object castable to an int
        )TitleDescriptionAssignmentDurationInSecondsRewardKeywordsNAutoApprovalDelayInSecondsRegisterHITType	HITTypeId)	dictduration_as_secondsupdater   get_price_as_priceget_as_paramsget_keywords_as_stringr2   r<   )
r   titledescriptionrewarddurationkeywordsapproval_delayqual_reqr3   dr   r   r   register_hit_typeL   s    
z!MTurkConnection.register_hit_typec                 C      |  |d|d|S )zx
        Performs a SetHITTypeNotification operation to set email
        notification for a specified HIT type
        EmailSetHITTypeNotification_set_notification)r   hit_typeemailevent_typesr   r   r   set_email_notificationh      
z&MTurkConnection.set_email_notificationc                 C   rL   )zw
        Performs a SetHITTypeNotification operation to set REST notification
        for a specified HIT type
        RESTrN   rO   )r   rQ   urlrS   r   r   r   set_rest_notificationp   rU   z%MTurkConnection.set_rest_notificationc                 C   rL   )a   
        Performs a SetHITTypeNotification operation so set SQS notification
        for a specified HIT type. Queue URL is of form:
        https://queue.amazonaws.com/<CUSTOMER_ID>/<QUEUE_NAME> and can be
        found when looking at the details for a Queue in the AWS Console
        SQSrN   rO   )r   rQ   	queue_urlrS   r   r   r   set_sqs_notificationx   s   
z$MTurkConnection.set_sqs_notificationPingc                 C   s   |  |d|d||S )zx
        Performs a SendTestEventNotification operation with REST notification
        for a specified HIT type
        rV   SendTestEventNotificationrO   )r   rQ   rW   rS   test_event_typer   r   r   send_test_event_notification   s   
z,MTurkConnection.send_test_event_notificationc                 C   s~   d|i}||t jjjjdd}|r| ||d i }	d}
|D ]}|| |	d|
|f < q||	 |r9|d|i | ||S )zy
        Common operation to set notification or send a test event
        notification for a specified HIT type
        r<   T)Destination	TransportVersionActive	EventType   zNotification.%d.%sTestEventType)botor,   notificationNotificationMessageNOTIFICATION_VERSIONbuild_list_paramsr?   r2   )r   rQ   	transportdestinationrequest_typerS   r^   r3   notification_paramsnotification_rest_paramsnumkeyr   r   r   rP      s$   

z!MTurkConnection._set_notification   )daysre   c                 C   sx  |  ||d}|du o|du }|du rK|duo|du}|s |r$td|r)|g}t|}t|tr5|}nt|tr=|}nt|trD|}| |d< n|sQtd||d< |r^||  |re||d< n1t	
|}t	|	}|  |
}t||||d}||d	 |dur|  |}||d
< || |dur||d< |dur||  |r| ||d | d|dtfgS )z
        Creates a new HIT.
        Returns a ResultSet
        See: http://docs.amazonwebservices.com/AWSMechTurk/2012-03-25/AWSMturkAPI/ApiReference_CreateHITOperation.html
        )LifetimeInSecondsMaxAssignmentsNzkMust specify question (single Question instance) or questions (list or QuestionForm instance), but not bothQuestionz|Must not specify question (single Question instance) or questions (list or QuestionForm instance) when specifying hit_layoutHITLayoutIdr<   )r5   r6   r9   r7   r8   r:   RequesterAnnotationResponseGroup	CreateHITHIT)r>   
ValueErrorr   
isinstancer	   r
   
get_as_xmlr?   rA   r   rB   r@   r=   rk   r2   r|   )r   rQ   question
hit_layoutlifetimemax_assignmentsrC   rD   rG   rE   rF   rH   
annotation	questionsqualificationslayout_paramsresponse_groupsr3   neitherbothquestion_paramfinal_keywordsfinal_pricefinal_durationadditional_paramsrJ   r   r   r   
create_hit   s\   








zMTurkConnection.create_hitc                 C      ||d}|  d|S )a  
        Change the HIT type of an existing HIT. Note that the reward associated
        with the new HIT type must match the reward of the current HIT type in
        order for the operation to be valid.

        :type hit_id: str
        :type hit_type: str
        )HITIdr<   ChangeHITTypeOfHITr2   )r   hit_idrQ   r3   r   r   r   change_hit_type_of_hit  s   	z&MTurkConnection.change_hit_type_of_hit
Reviewable
Expiration	Ascending
   c                 C   s:   |||||d}|dur| d|i | d|dtfgS )z
        Retrieve the HITs that have a status of Reviewable, or HITs that
        have a status of Reviewing, and that belong to the Requester
        calling the operation.
        )StatusSortPropertySortDirectionPageSize
PageNumberNr<   GetReviewableHITsr|   )r?   r2   r|   )r   rQ   statussort_bysort_direction	page_sizepage_numberr3   r   r   r   get_reviewable_hits  s   z#MTurkConnection.get_reviewable_hitsc                 C   s&   ||  t ||   }ttd|d S )z
        Given a page size (records per page) and a total number of
        records, return the page numbers to be retrieved.
        re   )boollistrange)r   total_recordspagesr   r   r   
_get_pages.  s   zMTurkConnection._get_pagesc                    sL   d j  d}t|j} fdd} |}t||}tj|S )aD  
        Return all of a Requester's HITs

        Despite what search_hits says, it does not return all hits, but
        instead returns a page of hits. This method will pull the hits
        from the server 100 at a time, but will yield the results
        iteratively, so subsequent requests are made on demand.
        d   )r   c                    s   j  | dS )N)r   r   )search_hitspager   r   r   r   <lambda>C  s    z.MTurkConnection.get_all_hits.<locals>.<lambda>)r   intTotalNumResultsr   	itertoolsimapchainfrom_iterable)r   	search_rsr   get_page_hits	page_numshit_setsr   r   r   get_all_hits7  s   	
zMTurkConnection.get_all_hitsCreationTimec                 C   s4   ||||d}|r|  ||d | d|dtfgS )aI  
        Return a page of a Requester's HITs, on behalf of the Requester.
        The operation returns HITs of any status, except for HITs that
        have been disposed with the DisposeHIT operation.
        Note:
        The SearchHITs operation does not accept any search parameters
        that filter the results.
        )r   r   r   r   rz   
SearchHITsr|   rk   r2   r|   )r   r   r   r   r   r   r3   r   r   r   r   H  s   
zMTurkConnection.search_hitsc                 C   s4   d|i}|r|  ||d | d|dtfdtfgS )a_  
        Retrieves an assignment using the assignment's ID. Requesters can only
        retrieve their own assignments, and only assignments whose related HIT
        has not been disposed.

        The returned ResultSet will have the following attributes:

        Request
                This element is present only if the Request ResponseGroup
                is specified.
        Assignment
                The assignment. The response includes one Assignment object.
        HIT
                The HIT associated with this assignment. The response
                includes one HIT object.

        AssignmentIdrz   GetAssignment
Assignmentr|   )rk   r2   r   r|   )r   assignment_idr   r3   r   r   r   get_assignment\  s   zMTurkConnection.get_assignment
SubmitTimec           	      C   sF   |||||d}|dur||d< |r|  ||d | d|dtfgS )ad  
        Retrieves completed assignments for a HIT.
        Use this operation to retrieve the results for a HIT.

        The returned ResultSet will have the following attributes:

        NumResults
                The number of assignments on the page in the filtered results
                list, equivalent to the number of assignments being returned
                by this call.
                A non-negative integer, as a string.
        PageNumber
                The number of the page in the filtered results list being
                returned.
                A positive integer, as a string.
        TotalNumResults
                The total number of HITs in the filtered results list based
                on this call.
                A non-negative integer, as a string.

        The ResultSet will contain zero or more Assignment objects

        )r   r   r   r   r   NAssignmentStatusrz   GetAssignmentsForHITr   )rk   r2   r   )	r   r   r   r   r   r   r   r   r3   r   r   r   get_assignmentsy  s   zMTurkConnection.get_assignmentsc                 C       d|i}|r
||d< |  d|S )r.   r   RequesterFeedbackApproveAssignmentr   r   r   feedbackr3   r   r   r   approve_assignment     z"MTurkConnection.approve_assignmentc                 C   r   )r.   r   r   RejectAssignmentr   r   r   r   r   reject_assignment  r   z!MTurkConnection.reject_assignmentc                 C   r   )r.   r   r   ApproveRejectedAssignmentr   r   r   r   r   approve_rejected_assignment  r   z+MTurkConnection.approve_rejected_assignmentc                 C      ||d}|  d|dtfgS )a  
        Generates and returns a temporary URL to an uploaded file. The
        temporary URL is used to retrieve the file as an answer to a
        FileUploadAnswer question, it is valid for 60 seconds.

        Will have a FileUploadURL attribute as per the API Reference.
        )r   QuestionIdentifierGetFileUploadURLFileUploadURL)r2   r   )r   r   question_identifierr3   r   r   r   get_file_upload_url  s   	z#MTurkConnection.get_file_upload_urlc                 C   s.   d|i}|r|  ||d | d|dtfgS )r.   r   rz   GetHITr|   r   r   r   r   r3   r   r   r   get_hit  s   zMTurkConnection.get_hitc                 C   r   )aU  
        Update a HIT with a status of Reviewable to have a status of Reviewing,
        or reverts a Reviewing HIT back to the Reviewable status.

        Only HITs with a status of Reviewable can be updated with a status of
        Reviewing.  Similarly, only Reviewing HITs can be reverted back to a
        status of Reviewable.
        r   RevertSetHITAsReviewingr   )r   r   revertr3   r   r   r   set_reviewing  s   	zMTurkConnection.set_reviewingc                 C   s&   d|i}|r|  ||d | d|S )an  
        Remove a HIT from the Mechanical Turk marketplace, approves all
        submitted assignments that have not already been approved or rejected,
        and disposes of the HIT and all assignment data.

        Assignments for the HIT that have already been submitted, but not yet
        approved or rejected, will be automatically approved. Assignments in
        progress at the time of the call to DisableHIT will be approved once
        the assignments are submitted. You will be charged for approval of
        these assignments.  DisableHIT completely disposes of the HIT and
        all submitted assignment data. Assignment results data cannot be
        retrieved for a HIT that has been disposed.

        It is not possible to re-enable a HIT once it has been disabled.
        To make the work from a disabled HIT available again, create a new HIT.
        r   rz   
DisableHITrk   r2   r   r   r   r   disable_hit  s   zMTurkConnection.disable_hitc                 C      d|i}|  d|S )a  
        Dispose of a HIT that is no longer needed.

        Only HITs in the "reviewable" state, with all submitted
        assignments approved or rejected, can be disposed. A Requester
        can call GetReviewableHITs to determine which HITs are
        reviewable, then call GetAssignmentsForHIT to retrieve the
        assignments.  Disposing of a HIT removes the HIT from the
        results of a call to GetReviewableHITs.  r   
DisposeHITr   r   r   r3   r   r   r   dispose_hit  s   
zMTurkConnection.dispose_hitc                 C   r   )aI  
        Expire a HIT that is no longer needed.

        The effect is identical to the HIT expiring on its own. The
        HIT no longer appears on the Mechanical Turk web site, and no
        new Workers are allowed to accept the HIT. Workers who have
        accepted the HIT prior to expiration are allowed to complete
        it or return it, or allow the assignment duration to elapse
        (abandon the HIT). Once all remaining assignments have been
        submitted, the expired HIT becomes"reviewable", and will be
        returned by a call to GetReviewableHITs.
        r   ForceExpireHITr   r   r   r   r   
expire_hit  s   zMTurkConnection.expire_hitc                 C   sT   |du r|du s|dur|durt dd|i}|r||d< |r$||d< | d|S )a  
        Increase the maximum number of assignments, or extend the
        expiration date, of an existing HIT.

        NOTE: If a HIT has a status of Reviewable and the HIT is
        extended to make it Available, the HIT will not be returned by
        GetReviewableHITs, and its submitted assignments will not be
        returned by GetAssignmentsForHIT, until the HIT is Reviewable
        again.  Assignment auto-approval will still happen on its
        original schedule, even if the HIT has been extended. Be sure
        to retrieve and approve (or reject) submitted assignments
        before extending the HIT, if so desired.
        NzOMust specify either assignments_increment or expiration_increment, but not bothr   MaxAssignmentsIncrementExpirationIncrementInSeconds	ExtendHIT)r}   r2   )r   r   assignments_incrementexpiration_incrementr3   r   r   r   
extend_hit  s   zMTurkConnection.extend_hit	Operationc                 C   r   )z
        Return information about the Mechanical Turk Service
        operations and response group NOTE - this is basically useless
        as it just returns the URL of the documentation

        help_type: either 'Operation' or 'ResponseGroup'
        )AboutHelpTypeHelpr   )r   about	help_typer3   r   r   r   get_help4  s   
zMTurkConnection.get_helpc                 C   s0   | dd}||d< ||d< ||d< | d|S )a  
        Issues a payment of money from your account to a Worker.  To
        be eligible for a bonus, the Worker must have submitted
        results for one of your HITs, and have had those results
        approved or rejected. This payment happens separately from the
        reward you pay to the Worker when you approve the Worker's
        assignment.  The Bonus must be passed in as an instance of the
        Price object.
        BonusAmountre   WorkerIdr   Reason
GrantBonus)rA   r2   )r   	worker_idr   bonus_pricereasonr3   r   r   r   grant_bonus?  s
   
zMTurkConnection.grant_bonusc                 C   r   )z:
        Block a worker from working on my tasks.
        r   r   BlockWorkerr   r   r   r   r3   r   r   r   block_workerP     
zMTurkConnection.block_workerc                 C   r   )z<
        Unblock a worker from working on my tasks.
        r   UnblockWorkerr   r  r   r   r   unblock_workerX  r  zMTurkConnection.unblock_workerc                 C   s$   ||d}|  ||d | d|S )z1
        Send a text message to workers.
        )SubjectMessageTextr   NotifyWorkersr   )r   
worker_idssubjectmessage_textr3   r   r   r   notify_workers`  s
   zMTurkConnection.notify_workersFc                 C   s   |||d}|dur||d< |dur%t |tsJ |	dusJ | |d< |	dur-|	|d< |dur=t |tr;||d< nt|
rM|du sEJ d|d< ||d	< |rV| ||d
< | d|dtfgS )am  
        Create a new Qualification Type.

        name: This will be visible to workers and must be unique for a
           given requester.

        description: description shown to workers.  Max 2000 characters.

        status: 'Active' or 'Inactive'

        keywords: list of keyword strings or comma separated string.
           Max length of 1000 characters when concatenated with commas.

        retry_delay: number of seconds after requesting a
           qualification the worker must wait before they can ask again.
           If not specified, workers can only request this qualification
           once.

        test: a QuestionForm

        answer_key: an XML string of your answer key, for automatically
           scored qualification tests.
           (Consider implementing an AnswerKey class for this to support.)

        test_duration: the number of seconds a worker has to complete the test.

        auto_granted: if True, requests for the Qualification are granted
           immediately.  Can't coexist with a test.

        auto_granted_value: auto_granted qualifications are given this value.

        )Namer6   QualificationTypeStatusNRetryDelayInSecondsTestTestDurationInSeconds	AnswerKeyTAutoGrantedAutoGrantedValuer9   CreateQualificationTypeQualificationType)r~   r   r   
basestring	TypeErrorrB   r2   r  )r   namerD   r   rG   retry_delaytest
answer_keyanswer_key_xmltest_durationauto_grantedauto_granted_valuer3   r   r   r   create_qualification_typej  s6   -

z)MTurkConnection.create_qualification_typec                 C   s   d|i}|  d|dtfgS )NQualificationTypeIdGetQualificationTyper  r2   r  r   qualification_type_idr3   r   r   r   get_qualification_type  s   z&MTurkConnection.get_qualification_typec                    sL   d  }t|j} fdd} |}t||}tj|S )Nr   c                    s   j  | dS )N)r'  r   r   ))get_qualifications_for_qualification_typer   r   r'  r   r   r   r     s    zFMTurkConnection.get_all_qualifications_for_qual_type.<locals>.<lambda>)r)  r   r   r   r   r   r   r   )r   r'  search_qualr   get_page_qualsr   	qual_setsr   r*  r   $get_all_qualifications_for_qual_type  s   

z4MTurkConnection.get_all_qualifications_for_qual_typer   c                 C   s    |||d}|  d|dtfgS )N)r#  r   r   %GetQualificationsForQualificationTypeQualificationr2   r0  )r   r'  r   r   r3   r   r   r   r)    s   z9MTurkConnection.get_qualifications_for_qualification_typec
                 C   s   d|i}
|d ur||
d< |d ur||
d< |d ur||
d< |d ur-t |ts'J | |
d< |d ur5||
d< |d urEt |trC||
d< nt|d urM||
d< |	d urU|	|
d	< | d
|
dtfgS )Nr#  r6   r  r  r  r  r  r  r  UpdateQualificationTyper  )r~   r   r   r  r  r2   r  )r   r'  rD   r   r  r  r  r  r   r!  r3   r   r   r   update_qualification_type  s.   


z)MTurkConnection.update_qualification_typec                 C   r   )TODO: Document.r#  DisposeQualificationTyper   r&  r   r   r   dispose_qualification_type  s   z*MTurkConnection.dispose_qualification_typer  c           	      C   s(   |||||||d}|  d|dtfgS )r4  )Queryr   r   r   r   MustBeRequestableMustBeOwnedByCallerSearchQualificationTypesr  r%  )	r   queryr   r   r   r   must_be_requestablemust_be_owned_by_callerr3   r   r   r   search_qualification_types  s   z*MTurkConnection.search_qualification_typesc                 C   s$   |||||d}|  d|dtfgS )r4  )r#  r   r   r   r   GetQualificationRequestsQualificationRequest)r2   r@  )r   r'  r   r   r   r   r3   r   r   r   get_qualification_requests  s   z*MTurkConnection.get_qualification_requestsc                 C   r   )r4  )QualificationRequestIdIntegerValueGrantQualificationr   )r   qualification_request_idinteger_valuer3   r   r   r   grant_qualification  s   z#MTurkConnection.grant_qualificationc                 C      |||d}|  d|S )r4  )	SubjectIdr#  r   RevokeQualificationr   )r   
subject_idr'  r   r3   r   r   r   revoke_qualification!  
   z$MTurkConnection.revoke_qualificationc                 C   s   ||||d}|  d|S )N)r#  r   rC  SendNotificationAssignQualificationr   )r   r'  r   valuesend_notificationr3   r   r   r   assign_qualification)  s   z$MTurkConnection.assign_qualificationc                 C   r   )r4  )r#  rI  GetQualificationScorer0  r1  )r   r'  r   r3   r   r   r   get_qualification_score1  s   z'MTurkConnection.get_qualification_scorec                 C   rH  )r4  )r#  rI  rC  UpdateQualificationScorer   )r   r'  r   rP  r3   r   r   r   update_qualification_score8  rM  z*MTurkConnection.update_qualification_scorec                 C   s$   ||d< | j d|dd}| ||S )=
        Helper to process the xml response from AWS
        r   NPOST)verb)make_request_process_response)r   rn   r3   marker_elemsresponser   r   r   r2   @  s   z MTurkConnection._process_requestc                 C   s^   |  }| jdkrt| d|dvr't|}t|| }tj	|| |S t
|j|j|)rW     z<Errors>utf-8)readr   printdecoder   r   
XmlHandlerxmlsaxparseStringr   r   r   )r   r]  r\  bodyrshr   r   r   r[  H  s   
z!MTurkConnection._process_responsec                 C   s^   t | tr
d| } t | tr| }|S t | tr| d}|S | du r'd}|S tdt|  )zk
        Returns a comma+space-separated string of keywords from either
        a list or a string
        z, r_  N zAkeywords argument must be a string or a list of strings; got a %s)r~   r   joinstrunicodeencoder  type)rG   r   r   r   r   rB   W  s   




z&MTurkConnection.get_keywords_as_stringc                 C   s   t | tr	| }|S t| }|S )zO
        Returns a Price data structure from either a float or a Price
        )r~   r   )rE   r   r   r   r   r@   i  s
   
z"MTurkConnection.get_price_as_pricec                 C   sJ   t | tjr| jd | j } zt| } W | S  ty$   tdt|  w )NiQ z4Duration must be a timedelta or int-castable, got %s)r~   datetime	timedeltart   secondsr   r  ro  )rF   r   r   r   r>   t  s   
z#MTurkConnection.duration_as_seconds)NNTNNNNNNr   NNN)NNNN)Nr\   )NN)Nr   r   r   r   re   )r   r   r   re   N)Nr   r   r   re   N)r   )NNNNNNFre   )r   re   )NNNNNNNN)Nr  r   r   re   TT)r   r   r   re   )re   )re   T):r   r   r   
APIVersionr   r-   r4   rK   rT   rX   r[   r_   rP   rp  rq  r   r   r   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r"  r(  r.  r)  r3  r6  r>  rA  rG  rL  rR  rT  rV  r2   r[  rB   r@   r>   __classcell__r   r   r*   r   r   (   s    	





(

V





*








O
	
,



	





r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	BaseAutoResultElementzE
    Base class to automatically add attributes when parsing XML
    c                 C      d S rs  r   r   
connectionr   r   r   r        zBaseAutoResultElement.__init__c                 C   rx  rs  r   )r   r  attrsrz  r   r   r   startElement  r{  z"BaseAutoResultElement.startElementc                 C   s   t | || d S rs  )setattrr   r  rP  rz  r   r   r   
endElement  s   z BaseAutoResultElement.endElementN)r   r   r   r   r   r}  r  r   r   r   r   rw    s
    rw  c                   @   s    e Zd ZdZdd ZeeZdS )r|   z
    Class to extract a HIT structure from a response (used in ResultSet)

    Will have attributes named as per the Developer Guide,
    e.g. HITId, HITTypeId, CreationTime
    c                 C   s<   d}t | drtj }tj| jd}||k}|S td)z Has this HIT expired yet? Fr   z%Y-%m-%dT%H:%M:%SZz>ERROR: Request for expired property, but no Expiration in HIT!)hasattrrp  utcnowstrptimer   r}   )r   expirednow
expirationr   r   r   _has_expired  s   

zHIT._has_expiredN)r   r   r   r   r  propertyr  r   r   r   r   r|     s    r|   c                   @   r   )r   zE
    Class to extract an FileUploadURL structure from a response
    Nr   r   r   r   r   r         r   c                   @   r   )r<   zA
    Class to extract an HITTypeId structure from a response
    Nr   r   r   r   r   r<     r  r<   c                   @   r   )r0  z
    Class to extract an Qualification structure from a response (used in
    ResultSet)

    Will have attributes named as per the Developer Guide such as
    QualificationTypeId, IntegerValue. Does not seem to contain GrantTime.
    Nr   r   r   r   r   r0        r0  c                   @   r   )r  z
    Class to extract an QualificationType structure from a response (used in
    ResultSet)

    Will have attributes named as per the Developer Guide,
    e.g. QualificationTypeId, CreationTime, Name, etc
    Nr   r   r   r   r   r    r  r  c                       ,   e Zd ZdZ fddZ fddZ  ZS )r@  z
    Class to extract an QualificationRequest structure from a response (used in
    ResultSet)

    Will have attributes named as per the Developer Guide,
    e.g. QualificationRequestId, QualificationTypeId, SubjectId, etc
    c                       t t| | g | _d S rs  )r   r@  r   answersry  r*   r   r   r        
zQualificationRequest.__init__c                    b   |dkr%t dtfg}t||}||}tj|| | j	| d S t
t| ||| d S NAnswer)r   QuestionFormAnswerr   rc  get_utf8_valuerd  re  rf  r  appendr   r@  r  r   r  rP  rz  	answer_rsri  r*   r   r   r       
zQualificationRequest.endElementr   r   r   r   r   r  rv  r   r   r*   r   r@        r@  c                       r  )r   z
    Class to extract an Assignment structure from a response (used in
    ResultSet)

    Will have attributes named as per the Developer Guide,
    e.g. AssignmentId, WorkerId, HITId, Answer, etc
    c                    r  rs  )r   r   r   r  ry  r*   r   r   r     r  zAssignment.__init__c                    r  r  )r   r  r   rc  r  rd  re  rf  r  r  r   r   r  r  r*   r   r   r    r  zAssignment.endElementr  r   r   r*   r   r     r  r   c                       s(   e Zd ZdZ fddZdd Z  ZS )r  a:  
    Class to extract Answers from inside the embedded XML
    QuestionFormAnswers element inside the Answer element which is
    part of the Assignment and QualificationRequest structures

    A QuestionFormAnswers element contains an Answer element for each
    question in the HIT or Qualification test for which the Worker
    provided an answer. Each Answer contains a QuestionIdentifier
    element whose value corresponds to the QuestionIdentifier of a
    Question in the QuestionForm. See the QuestionForm data structure
    for more information about questions and answer specifications.

    If the question expects a free-text answer, the Answer element
    contains a FreeText element. This element contains the Worker's
    answer

    *NOTE* - currently really only supports free-text and selection answers
    c                    s    t t| | g | _d | _d S rs  )r   r  r   fieldsqidry  r*   r   r   r     s   
zQuestionFormAnswer.__init__c                 C   s8   |dkr	|| _ d S |dv r| j r| j| d S d S d S )Nr   )FreeTextSelectionIdentifierOtherSelectionText)r  r  r  r  r   r   r   r    s
   
zQuestionFormAnswer.endElementr  r   r   r*   r   r    s    r  ) xml.saxrd  rp  r   rg   r   r   boto.mturk.pricer   boto.mturk.notificationboto.connectionr   boto.exceptionr   boto.resultsetr   boto.mturk.questionr   r	   r
   r   r   objectrw  r|   r   r<   r0  r  r@  r   r  r   r   r   r   <module>   s8         ]