Example #1
0
def score_from_csv(assign_id, rows, kind='total', invalid=None, message=None):
    """
    Job for uploading Scores.

    @param ``rows`` should be a list of records (mappings),
        with labels `email` and `score`
    """
    log = jobs.get_job_logger()
    current_user = jobs.get_current_job().user
    assign = Assignment.query.get(assign_id)

    message = message or '{} score for {}'.format(kind.title(), assign.display_name)

    def log_err(msg):
        log.info('\t!  {}'.format(msg))

    log.info("Uploading scores for {}:\n".format(assign.display_name))

    if invalid:
        log_err('skipping {} invalid entries on lines:'.format(len(invalid)))
        for line in invalid:
            log_err('\t{}'.format(line))
        log.info('')

    success, total = 0, len(rows)
    for i, row in enumerate(rows, start=1):
        try:
            email, score = row['email'], row['score']
            user = User.query.filter_by(email=email).one()

            backup = Backup.query.filter_by(assignment=assign, submitter=user, submit=True).first()
            if not backup:
                backup = Backup.create(submitter=user, assignment=assign, submit=True)

            uploaded_score = Score(grader=current_user, assignment=assign,
                    backup=backup, user=user, score=score, kind=kind, message=message)

            db.session.add(uploaded_score)
            uploaded_score.archive_duplicates()

        except SQLAlchemyError:
            print_exc()
            log_err('error: user with email `{}` does not exist'.format(email))
        else:
            success += 1
        if i % 100 == 0:
            log.info('\nUploaded {}/{} Scores\n'.format(i, total))
    db.session.commit()

    log.info('\nSuccessfully uploaded {} "{}" scores (with {} errors)'.format(success, kind, total - success))

    return '/admin/course/{cid}/assignments/{aid}/scores'.format(
                cid=jobs.get_current_job().course_id, aid=assign_id)
Example #2
0
def assign_scores(assign_id, score, kind, message, deadline,
                     include_backups=True):
    logger = jobs.get_job_logger()
    current_user = jobs.get_current_job().user

    assignment = Assignment.query.get(assign_id)
    students = [e.user_id for e in assignment.course.get_students()]
    submission_time = server_time_obj(deadline, assignment.course)

    # Find all submissions (or backups) before the deadline
    backups = Backup.query.filter(
        Backup.assignment_id == assign_id,
        or_(Backup.created <= deadline, Backup.custom_submission_time <= deadline)
    ).order_by(Backup.created.desc()).group_by(Backup.submitter_id)

    if not include_backups:
        backups = backups.filter(Backup.submit == True)

    all_backups =  backups.all()

    if not all_backups:
        logger.info("No submissions were found with a deadline of {}."
                    .format(deadline))
        return "No Scores Created"

    total_count = len(all_backups)
    logger.info("Found {} eligible submissions...".format(total_count))

    score_counter, seen = 0, set()

    for back in all_backups:
        if back.creator in seen:
            score_counter += 1
            continue
        new_score = Score(score=score, kind=kind, message=message,
                          user_id=back.submitter_id,
                          assignment=assignment, backup=back,
                          grader=current_user)
        db.session.add(new_score)
        new_score.archive_duplicates()
        db.session.commit()

        score_counter += 1
        if score_counter % 5 == 0:
            logger.info("Scored {} of {}".format(score_counter, total_count))
        seen |= back.owners()

    result = "Left {} '{}' scores of {}".format(score_counter, kind.title(), score)
    logger.info(result)
    return result
Example #3
0
def grade(bid):
    """ Used as a form submission endpoint. """
    backup = Backup.query.options(db.joinedload('assignment')).get(bid)
    if not backup:
        abort(404)
    if not Backup.can(backup, current_user, 'grade'):
        flash("You do not have permission to score this assignment.", "warning")
        abort(401)

    form = forms.GradeForm()
    score_kind = form.kind.data.strip().lower()
    is_composition = (score_kind == "composition")
    # TODO: Form should include redirect url instead of guessing based off tag

    if is_composition:
        form = forms.CompositionScoreForm()

    if not form.validate_on_submit():
        return grading_view(backup, form=form)

    score = Score(backup=backup, grader=current_user,
                  assignment_id=backup.assignment_id)
    form.populate_obj(score)
    db.session.add(score)
    db.session.commit()

    # Archive old scores of the same kind
    score.archive_duplicates()

    next_page = None
    flash_msg = "Added a {0} {1} score.".format(score.score, score_kind)

    # Find GradingTasks applicable to this score
    tasks = backup.grading_tasks
    for task in tasks:
        task.score = score
        cache.delete_memoized(User.num_grading_tasks, task.grader)

    db.session.commit()

    if len(tasks) == 1:
        # Go to next task for the current task queue if possible.
        task = tasks[0]
        next_task = task.get_next_task()
        next_route = '.composition' if is_composition else '.grading'
        # Handle case when the task is on the users queue
        if next_task:
            flash_msg += (" There are {0} tasks left. Here's the next submission:"
                          .format(task.remaining))
            next_page = url_for(next_route, bid=next_task.backup_id)
        else:
            flash_msg += " All done with grading for {}".format(backup.assignment.name)
            next_page = url_for('.grading_tasks')
    else:
        # TODO: Send task id or redirect_url in the grading form
        # For now, default to grading tasks
        next_page = url_for('.grading_tasks')

    flash(flash_msg, 'success')

    if not next_page:
        next_page = url_for('.assignment_queues', aid=backup.assignment_id,
                            cid=backup.assignment.course_id)
    return redirect(next_page)
Example #4
0
File: admin.py Project: gratimax/ok
def grade(bid):
    """ Used as a form submission endpoint. """
    backup = Backup.query.options(db.joinedload('assignment')).get(bid)
    if not backup:
        abort(404)
    if not Backup.can(backup, current_user, 'grade'):
        flash("You do not have permission to score this assignment.", "warning")
        abort(401)

    form = forms.GradeForm()
    score_kind = form.kind.data.strip().lower()
    is_composition = (score_kind == "composition")
    # TODO: Form should include redirect url instead of guessing based off tag

    if is_composition:
        form = forms.CompositionScoreForm()

    if not form.validate_on_submit():
        return grading_view(backup, form=form)

    score = Score(backup=backup, grader=current_user,
                  assignment_id=backup.assignment_id)
    form.populate_obj(score)
    db.session.add(score)
    db.session.commit()

    # Archive old scores of the same kind
    score.archive_duplicates()

    next_page = None
    flash_msg = "Added a {0} {1} score.".format(score.score, score_kind)

    # Find GradingTasks applicable to this score
    tasks = backup.grading_tasks
    for task in tasks:
        task.score = score
        cache.delete_memoized(User.num_grading_tasks, task.grader)

    db.session.commit()

    if len(tasks) == 1:
        # Go to next task for the current task queue if possible.
        task = tasks[0]
        next_task = task.get_next_task()
        next_route = '.composition' if is_composition else '.grading'
        # Handle case when the task is on the users queue
        if next_task:
            flash_msg += (" There are {0} tasks left. Here's the next submission:"
                          .format(task.remaining))
            next_page = url_for(next_route, bid=next_task.backup_id)
        else:
            flash_msg += " All done with grading for {}".format(backup.assignment.name)
            next_page = url_for('.grading_tasks')
    else:
        # TODO: Send task id or redirect_url in the grading form
        # For now, default to grading tasks
        next_page = url_for('.grading_tasks')

    flash(flash_msg, 'success')

    if not next_page:
        next_page = url_for('.assignment_queues', aid=backup.assignment_id,
                            cid=backup.assignment.course_id)
    return redirect(next_page)
Example #5
0
def assign_scores(assign_id,
                  score,
                  kind,
                  message,
                  deadline,
                  include_backups=True,
                  grade_backups=False):
    logger = jobs.get_job_logger()
    current_user = jobs.get_current_job().user

    assignment = Assignment.query.get(assign_id)
    students = [e.user_id for e in assignment.course.get_students()]
    submission_time = server_time_obj(deadline, assignment.course)

    # Find all submissions (or backups) before the deadline
    backups = Backup.query.filter(
        Backup.assignment_id == assign_id,
        or_(Backup.created <= deadline,
            Backup.custom_submission_time <= deadline)).group_by(
                Backup.submitter_id).order_by(Backup.created.desc())

    if not include_backups:
        backups = backups.filter(Backup.submit == True)

    all_backups = backups.all()

    if not all_backups:
        logger.info("No submissions were found with a deadline of {}.".format(
            deadline))
        return "No Scores Created"

    score_counter, seen = 0, set()

    unique_backups = []

    for back in all_backups:
        if back.creator not in seen:
            unique_backups.append(back)
            seen |= back.owners()

    total_count = len(unique_backups)
    logger.info(
        "Found {} unique and eligible submissions...".format(total_count))

    if grade_backups:
        logger.info('\nAutograding {} backups'.format(total_count))
        backup_ids = [back.id for back in unique_backups]
        try:
            autograde_backups(assignment, current_user.id, backup_ids, logger)
        except ValueError:
            logger.info(
                'Could not autograde backups - Please add an autograding key.')
    else:
        for back in unique_backups:
            new_score = Score(score=score,
                              kind=kind,
                              message=message,
                              user_id=back.submitter_id,
                              assignment=assignment,
                              backup=back,
                              grader=current_user)

            db.session.add(new_score)
            new_score.archive_duplicates()

            score_counter += 1
            if score_counter % 100 == 0:
                logger.info("Scored {} of {}".format(score_counter,
                                                     total_count))

        # only commit if all scores were successfully added
        db.session.commit()

    logger.info("Left {} '{}' scores of {}".format(score_counter, kind.title(),
                                                   score))
    return '/admin/course/{cid}/assignments/{aid}/scores'.format(
        cid=jobs.get_current_job().course_id, aid=assignment.id)
Example #6
0
def assign_scores(assign_id, score, kind, message, deadline,
                     include_backups=True, grade_backups=False):
    logger = jobs.get_job_logger()
    current_user = jobs.get_current_job().user

    assignment = Assignment.query.get(assign_id)
    students = [e.user_id for e in assignment.course.get_students()]
    submission_time = server_time_obj(deadline, assignment.course)

    # Find all submissions (or backups) before the deadline
    backups = Backup.query.filter(
        Backup.assignment_id == assign_id,
        or_(Backup.created <= deadline, Backup.custom_submission_time <= deadline)
    ).group_by(Backup.submitter_id).order_by(Backup.created.desc())

    if not include_backups:
        backups = backups.filter(Backup.submit == True)

    all_backups =  backups.all()

    if not all_backups:
        logger.info("No submissions were found with a deadline of {}."
                    .format(deadline))
        return "No Scores Created"

    score_counter, seen = 0, set()

    unique_backups = []

    for back in all_backups:
        if back.creator not in seen:
            unique_backups.append(back)
            seen |= back.owners()

    total_count = len(unique_backups)
    logger.info("Found {} unique and eligible submissions...".format(total_count))

    if grade_backups:
        logger.info('\nAutograding {} backups'.format(total_count))
        backup_ids = [back.id for back in unique_backups]
        try:
            autograde_backups(assignment, current_user.id, backup_ids, logger)
        except ValueError:
            logger.info('Could not autograde backups - Please add an autograding key.')
    else:
        for back in unique_backups:
            new_score = Score(score=score, kind=kind, message=message,
                              user_id=back.submitter_id,
                              assignment=assignment, backup=back,
                              grader=current_user)

            db.session.add(new_score)
            new_score.archive_duplicates()

            score_counter += 1
            if score_counter % 100 == 0:
                logger.info("Scored {} of {}".format(score_counter, total_count))

        # only commit if all scores were successfully added
        db.session.commit()

    logger.info("Left {} '{}' scores of {}".format(score_counter, kind.title(), score))
    return '/admin/course/{cid}/assignments/{aid}/scores'.format(
                cid=jobs.get_current_job().course_id, aid=assignment.id)