FitModel.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from flask import make_response, request, abort
  2. from flask.views import View
  3. from pycs.database.Project import Project
  4. from pycs.interfaces.MediaStorage import MediaStorage
  5. from pycs.jobs.JobGroupBusyException import JobGroupBusyException
  6. from pycs.jobs.JobRunner import JobRunner
  7. from pycs.util.PipelineCache import PipelineCache
  8. class FitModel(View):
  9. """
  10. use annotated data to fit a model
  11. """
  12. # pylint: disable=arguments-differ
  13. methods = ['POST']
  14. def __init__(self, pipelines: PipelineCache):
  15. # pylint: disable=invalid-name
  16. self.pipelines = pipelines
  17. def dispatch_request(self, project_id):
  18. # extract request data
  19. data = request.get_json(force=True)
  20. if not data.get('fit', False):
  21. return abort(400)
  22. # find project
  23. project = Project.query.get(project_id)
  24. if project is None:
  25. return abort(404)
  26. # create job
  27. try:
  28. JobRunner.Run(project,
  29. 'Model Interaction',
  30. f'{project.name} (fit model with new data)',
  31. f'{project.name}/model-interaction',
  32. self.load_and_fit, self.pipelines, project.id)
  33. except JobGroupBusyException:
  34. return abort(400)
  35. return make_response()
  36. @staticmethod
  37. def load_and_fit(pipelines: PipelineCache, project_id: int):
  38. """
  39. load the pipeline and call the fit function
  40. :param pipelines: pipeline cache
  41. :param project_id: project id
  42. """
  43. pipeline = None
  44. project = Project.query.get(project_id)
  45. storage = MediaStorage(project_id)
  46. # load pipeline
  47. try:
  48. pipeline = pipelines.load_from_root_folder(project)
  49. yield from pipeline.fit(storage)
  50. except TypeError:
  51. pass
  52. finally:
  53. if pipeline is not None:
  54. pipelines.free_instance(project)