FitModel.py 2.1 KB

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