old_contents: 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-1))
      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)
new_contents: 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.all().annotate(essay_count=Count('essay')).filter(essay_count__gt=(MIN_ESSAYS_TO_TRAIN_WITH-1))
      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)
subject: Fix tasks to grade ml properly