-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmturk_client.py
207 lines (179 loc) · 6.35 KB
/
mturk_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import boto3
from config import Config
import logging
import json
from urllib import parse
from botocore.config import Config as BotoConfig
from typing import Optional
from enums.qualification_types import QualificationType
class Client:
__instance = None
@staticmethod
def get():
logging.debug(f'Creating a new BOTO3 MTurk client')
if Client.__instance != None:
return Client.__instance
else:
Client.__instance = boto3.client(
'mturk',
endpoint_url=Config.get('endpoint_url'),
region_name=Config.get('region_name'),
aws_access_key_id=Config.get('aws_access_key_id'),
aws_secret_access_key=Config.get('aws_secret_access_key'),
config=BotoConfig(
retries = {
'max_attempts': 15,
'mode': 'adaptive'
}
)
)
return Client.__instance
def create_hit_type (
title: str,
keywords: str,
description: str,
reward: str,
duration_sec: int,
auto_approval_delay_sec: int
) -> str:
response = Client.get().create_hit_type(
AutoApprovalDelayInSeconds=auto_approval_delay_sec,
AssignmentDurationInSeconds=duration_sec,
Reward=reward,
Title=title,
Keywords=keywords,
Description=description
)
logging.debug(f'mturk create_hit_type response: {response}')
if (response['ResponseMetadata']['HTTPStatusCode'] == 200):
return response['HITTypeId']
else:
raise Exception('Could not create HIT type: ' + str(response))
def create_hit(
hit_type: dict,
image_url: str,
comment: Optional[str] = None,
max_assignments: int = int(Config.get('max_assignments')),
qualification_requirements: list = []
):
external_url = Config.get('external_url')
fullUrl = f'{external_url}?image={image_url}'
if comment:
fullUrl += f'&comment={parse.quote_plus(comment)}'
question_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
<ExternalQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd">
<ExternalURL>{fullUrl}</ExternalURL>
<FrameHeight>0</FrameHeight>
</ExternalQuestion>
'''
arguments = {
'Title': hit_type['title'],
'Keywords': hit_type['keywords'],
'Description': hit_type['description'],
'Reward': hit_type['reward'],
'AssignmentDurationInSeconds': hit_type['duration_sec'],
'AutoApprovalDelayInSeconds': hit_type['auto_approval_delay_sec'],
'MaxAssignments': max_assignments,
'LifetimeInSeconds': int(Config.get('lifetime_sec')),
'Question': question_xml
}
if qualification_requirements:
arguments['QualificationRequirements'] = qualification_requirements
response = Client.get().create_hit(
**arguments
)
return response
def create_hit_with_hit_type(
type_id: str,
image_url: str,
comment: Optional[str] = None,
max_assignments: int = int(Config.get('max_assignments')),
):
external_url = Config.get('external_url')
fullUrl = f'{external_url}?image={image_url}'
if comment:
fullUrl += f'&comment={parse.quote_plus(comment)}'
question_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
<ExternalQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd">
<ExternalURL>{fullUrl}</ExternalURL>
<FrameHeight>0</FrameHeight>
</ExternalQuestion>
'''
arguments = {
'HITTypeId': type_id,
'MaxAssignments': max_assignments,
'LifetimeInSeconds': int(Config.get('lifetime_sec')),
'Question': question_xml
}
response = Client.get().create_hit_with_hit_type(
**arguments
)
return response
def get_HIT_status(id: str):
response = Client.get().get_hit(
HITId=id
)
logging.debug(f'HIT status: {response}')
return response
def get_HIT_results(hit_id: str)-> dict:
response = Client.get().list_assignments_for_hit(HITId=hit_id)
return response
def list_hits():
response = Client.get().list_hits()
logging.debug(f'List hits response: {json.dumps(response)}')
return response
def create_qual_type(qual: QualificationType) -> dict:
"""
Creates a new qualification type and returns the contents of the QualificationType response key.
"""
response = Client.get().create_qualification_type(**qual.value)
logging.debug(f'Created Qualification Type with name {qual.value["Name"]}')
return response['QualificationType']
def assign_qualification_to_worker(
qual_id: str,
worker_id: str,
integer_value: Optional[int] = None,
send_notification: bool = False
):
args = {
'QualificationTypeId': qual_id,
'WorkerId':worker_id,
'SendNotification': send_notification
}
if integer_value is not None:
args['IntegerValue'] = integer_value
logging.debug(f'Calliing associate_qualification with following args: {args}')
response = Client.get().associate_qualification_with_worker(**args)
return response
def approve_assignment(
assignment_id: str,
requester_feedback: str= Config.get('approve_assignment_feedback'),
):
logging.debug(f'Approving assignment {assignment_id} with feedback: "{requester_feedback}"')
Client.get().approve_assignment(
AssignmentId=assignment_id,
RequesterFeedback=requester_feedback,
OverrideRejection=True
)
def reject_assignment(
assignment_id: str,
requester_feedback: str= Config.get('reject_assignment_feedback'),
):
logging.debug(f'Rejecting assignment {assignment_id} with feedback: "{requester_feedback}"')
Client.get().reject_assignment(
AssignmentId=assignment_id,
RequesterFeedback=requester_feedback
)
def notify_workers(
subject: str,
message_text: str,
worker_ids: list[str]
):
if(len(worker_ids)) and subject and message_text:
logging.info(f'Notifying {len(worker_ids)} worker(s) with subject "{subject}"')
response = Client.get().notify_workers(
Subject=subject,
MessageText=message_text,
WorkerIds=worker_ids
)
logging.debug(f'notify_workers response: {response}')