Ejemplo n.º 1
0
def extend_mturk_hit(hit_id, assignments, duration_hours, sandbox):
    """Add assignments, and optionally time, to an existing MTurk HIT."""
    out = Output()
    config = get_config()
    config.load()
    mode = "sandbox" if sandbox else "live"
    assignments_presented = "assignments" if assignments > 1 else "assignment"
    duration_presented = duration_hours or 0.0

    with config.override({"mode": mode}):
        if not click.confirm(
                "\n\nYou are about to add {:.1f} hours and {} {} to {} HIT {}.\n"
                "Continue?".format(duration_presented, assignments,
                                   assignments_presented, mode, hit_id)):
            out.log("Aborting...")
            return

        service = _mturk_service_from_config(sandbox)
        try:
            hit_info = service.extend_hit(hit_id=hit_id,
                                          number=assignments,
                                          duration_hours=duration_hours)
        except MTurkServiceException as ex:
            out.error(
                "HIT extension failed with the following error:\n{}".format(
                    ex), )
            return

    out.log("Updated HIT Details")
    out.log(tabulate.tabulate(hit_info.items()), chevrons=False)
Ejemplo n.º 2
0
def expire(hit_id, app, sandbox, exit=True):
    """Expire (set to "Reviewable") an MTurk HIT by specifying a HIT ID, or by
    specifying a Dallinger experiment ID, in which case HITs with the experiment
    ID in their ``annotation`` field will be expired.
    """
    if (hit_id and app) or not (hit_id or app):
        raise click.BadParameter("Must specify --hit_id or --app, but not both.")
    if app is not None:
        verify_id(None, "--app", app)
    service = _mturk_service_from_config(sandbox)

    # Assemble the list of HITs to expire
    if hit_id:
        targets = [hit_id]
    else:  # Find HITs based on --app value
        targets = [
            h["id"]
            for h in service.get_hits(hit_filter=lambda h: h.get("annotation") == app)
        ]

    success = []
    failures = []
    for hit_id in targets:
        try:
            service.expire_hit(hit_id=hit_id)
            success.append(hit_id)
        except MTurkServiceException:
            failures.append(hit_id)
    out = Output()
    if success:
        out.log(
            "Expired {} hit[s] (which may have already been expired): {}".format(
                len(success), ", ".join(success)
            )
        )
    if failures:
        out.log(
            "Could not expire {} hit[s]: {}".format(len(failures), ", ".join(failures))
        )
    if not success and not failures:
        out.error("Failed to find any matching HITs on MTurk.")
        if not sandbox:
            out.log(
                "If this experiment was run in the MTurk sandbox, use:\n"
                "  `dallinger expire --sandbox --app {}`".format(app),
                chevrons=False,
            )
        out.log("You can run `dallinger hits` to help troubleshoot.", chevrons=False)
    if exit and not success:
        sys.exit(1)
Ejemplo n.º 3
0
def email_test():
    """Test email configuration and send a test email."""
    out = Output()
    config = get_config()
    config.load()
    settings = EmailConfig(config)
    out.log("Email Config")
    out.log(tabulate.tabulate(settings.as_dict().items()), chevrons=False)
    problems = settings.validate()
    if problems:
        out.error(
            "✗ There are mail configuration problems. Fix these first:\n{}".
            format(problems))
        return

    else:
        out.log("✓ email config looks good!")
    mailer = SMTPMailer(
        config.get("smtp_host"),
        config.get("smtp_username"),
        config.get("smtp_password"),
    )
    msg = {
        "subject": "Test message from Dallinger",
        "sender": config.get("dallinger_email_address"),
        "recipients": [config.get("contact_email_on_error")],
        "body": "This has been a test...",
    }
    out.log(
        "Sending a test email from {sender} to {recipients[0]}".format(**msg))
    try:
        mailer.send(**msg)
    except MessengerError:
        out.error("✗ Message sending failed...")
        raise
    else:
        out.log("✓ Test email sent successfully to {}!".format(
            msg["recipients"][0]))
Ejemplo n.º 4
0
def compensate(recruiter, worker_id, email, dollars, sandbox):
    """Credit a specific worker by ID through their recruiter"""
    out = Output()
    config = get_config()
    config.load()
    mode = "sandbox" if sandbox else "live"
    do_notify = email is not None
    no_email_str = "" if email else " NOT"

    with config.override({"mode": mode}):
        rec = by_name(recruiter)
        if not click.confirm(
            '\n\nYou are about to pay worker "{}" ${:.2f} in "{}" mode using the "{}" recruiter.\n'
            "The worker will{} be notified by email. "
            "Continue?".format(worker_id, dollars, mode, recruiter, no_email_str)
        ):
            out.log("Aborting...")
            return

        try:
            result = rec.compensate_worker(
                worker_id=worker_id, email=email, dollars=dollars, notify=do_notify
            )
        except Exception as ex:
            out.error(
                "Compensation failed. The recruiter reports the following error:\n{}".format(
                    ex
                ),
            )
            return

    out.log("HIT Details")
    out.log(tabulate.tabulate(result["hit"].items()), chevrons=False)
    out.log("Qualification Details")
    out.log(tabulate.tabulate(result["qualification"].items()), chevrons=False)
    out.log("Worker Notification")
    out.log(tabulate.tabulate(result["email"].items()), chevrons=False)