1
1

FitModel.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. project = Project.get_or_404(project_id)
  22. # extract request data
  23. data = request.get_json(force=True)
  24. if not data.get('fit', False):
  25. abort(400, "fit flag is missing")
  26. # create job
  27. try:
  28. self.jobs.run(project,
  29. 'Model Interaction',
  30. f'{project.name} (fit model with new data)',
  31. f'{project.name}/model-interaction',
  32. FitModel.load_and_fit,
  33. self.pipelines,
  34. project.id)
  35. except JobGroupBusyException:
  36. return abort(400, "Model fitting already running")
  37. return make_response()
  38. @staticmethod
  39. def load_and_fit(pipelines: PipelineCache, project_id: int):
  40. """
  41. load the pipeline and call the fit function
  42. :param pipelines: pipeline cache
  43. :param project_id: project id
  44. """
  45. pipeline = None
  46. # create new database instance
  47. project = Project.query.get(project_id)
  48. model = project.model
  49. storage = MediaStorage(project_id)
  50. # load pipeline
  51. try:
  52. pipeline = pipelines.load_from_root_folder(project_id, model.root_folder)
  53. yield from pipeline.fit(storage)
  54. except TypeError:
  55. pass
  56. finally:
  57. if pipeline is not None:
  58. pipelines.free_instance(model.root_folder)