from celery import task
import logging
from celery.task import periodic_task
from freeform_data.models import Problem, Essay
from datetime import timedelta
from django.conf import settings
from ml_grading.ml_model_creation import handle_single_problem, MIN_ESSAYS_TO_TRAIN_WITH
from ml_grading.ml_grader import handle_single_essay
from django.db.models import Q, Count
from django.db import transaction

log=logging.getLogger(__name__)

@periodic_task(run_every=timedelta(seconds=settings.TIME_BETWEEN_ML_CREATOR_CHECKS))
def create_ml_models():
    transaction.commit_unless_managed()
    problems = Problem.objects.all()
    for problem in problems:
        create_ml_models_single_problem(problem)

@task()
def create_ml_models_single_problem(problem):
    transaction.commit_unless_managed()
    handle_single_problem(problem)

@periodic_task(run_every=timedelta(seconds=settings.TIME_BETWEEN_ML_GRADER_CHECKS))
def grade_ml():
    transaction.commit_unless_managed()
    problems = Problem.objects.filter(essay__has_been_ml_graded=True).annotate(essay_count=Count('essay')).filter(essay_count__gt=MIN_ESSAYS_TO_TRAIN_WITH)
    essays = Essay.objects.filter(problem__in=problems, has_been_ml_graded=False)
    for essay in essays:
        grade_ml_single_essay(essay)

@task()
def grade_ml_single_essay(essay):
    transaction.commit_unless_managed()
    handle_single_essay(essay)
@@ -1095,16 +1095,17 @@
 unt__gt=
+(
 MIN_ESSA
@@ -1120,16 +1120,19 @@
 AIN_WITH
+-1)
 )%0A    es

Fix ML grading to recognize the minimum