PredictModel.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. from typing import List
  2. from typing import Union
  3. from flask import abort
  4. from flask import make_response
  5. from flask import request
  6. from flask.views import View
  7. from pycs import db
  8. from pycs.database.Project import Project
  9. from pycs.database.Result import Result
  10. from pycs.frontend.notifications.NotificationList import NotificationList
  11. from pycs.frontend.notifications.NotificationManager import NotificationManager
  12. from pycs.interfaces.MediaFile import MediaFile
  13. from pycs.interfaces.MediaBoundingBox import MediaBoundingBox
  14. from pycs.interfaces.MediaStorage import MediaStorage
  15. from pycs.jobs.JobGroupBusyException import JobGroupBusyException
  16. from pycs.jobs.JobRunner import JobRunner
  17. from pycs.util.PipelineCache import PipelineCache
  18. class PredictModel(View):
  19. """
  20. load a model and create predictions
  21. """
  22. # pylint: disable=arguments-differ
  23. methods = ['POST']
  24. def __init__(self, nm: NotificationManager, jobs: JobRunner, pipelines: PipelineCache):
  25. # pylint: disable=invalid-name
  26. self.nm = nm
  27. self.jobs = jobs
  28. self.pipelines = pipelines
  29. def dispatch_request(self, user: str, project_id):
  30. project = Project.get_or_404(project_id)
  31. # extract request data
  32. data = request.get_json(force=True)
  33. predict = data.get('predict')
  34. if predict is None:
  35. abort(400, "predict argument is missing")
  36. if predict not in ['all', 'new']:
  37. abort(400, "predict must be either 'all' or 'new'")
  38. # create job
  39. try:
  40. notifications = NotificationList(self.nm)
  41. self.jobs.run(project,
  42. 'Model Interaction',
  43. f'{project.name} (create predictions)',
  44. f'{project.id}/model-interaction',
  45. PredictModel.load_and_predict,
  46. self.pipelines, notifications,
  47. project.id, predict,
  48. progress=self.progress)
  49. except JobGroupBusyException:
  50. abort(400, "Model prediction is already running")
  51. return make_response()
  52. @staticmethod
  53. def load_and_predict(pipelines: PipelineCache,
  54. notifications: NotificationList,
  55. project_id: int, file_filter: Union[str, List[int]]):
  56. """
  57. load the pipeline and call the execute function
  58. :param database: database object
  59. :param pipelines: pipeline cache
  60. :param notifications: notification object
  61. :param project_id: project id
  62. :param file_filter: list of file ids or 'new' / 'all'
  63. :return:
  64. """
  65. pipeline = None
  66. # create new database instance
  67. project = Project.query.get(project_id)
  68. model_root = project.model.root_folder
  69. storage = MediaStorage(project_id, notifications)
  70. # create a list of MediaFile
  71. if isinstance(file_filter, str):
  72. if file_filter == 'new':
  73. files = project.files_without_results()
  74. length = project.count_files_without_results()
  75. else:
  76. files = project.files.all()
  77. length = project.files.count()
  78. else:
  79. files = [project.file(identifier) for identifier in file_filter]
  80. length = len(files)
  81. media_files = map(lambda f: MediaFile(f, notifications), files)
  82. # load pipeline
  83. try:
  84. pipeline = pipelines.load_from_root_folder(project_id, model_root)
  85. # iterate over media files
  86. index = 0
  87. for file in media_files:
  88. # remove old predictions
  89. file.remove_predictions()
  90. # create new predictions
  91. pipeline.execute(storage, file)
  92. # commit changes and yield progress
  93. db.session.commit()
  94. yield index / length, notifications
  95. index += 1
  96. finally:
  97. if pipeline is not None:
  98. pipelines.free_instance(model_root)
  99. @staticmethod
  100. def load_and_pure_inference(pipelines: PipelineCache,
  101. notifications: NotificationList,
  102. notification_manager: NotificationManager,
  103. project_id: int, file_filter: List[int],
  104. result_filter: dict[int, List[Result]]):
  105. """
  106. load the pipeline and call the execute function
  107. :param database: database object
  108. :param pipelines: pipeline cache
  109. :param notifications: notification object
  110. :param notification_manager: notification manager
  111. :param project_id: project id
  112. :param file_filter: list of file ids
  113. :param result_filter: dict of file id and list of results to classify
  114. :return:
  115. """
  116. pipeline = None
  117. # create new database instance
  118. project = Project.query.get(project_id)
  119. model_root = project.model.root_folder
  120. storage = MediaStorage(project_id, notifications)
  121. # create a list of MediaFile
  122. # Also convert dict to the same key type.
  123. length = len(file_filter)
  124. # load pipeline
  125. try:
  126. pipeline = pipelines.load_from_root_folder(project_id, model_root)
  127. # iterate over media files
  128. index = 0
  129. for file_id in file_filter:
  130. file = project.file(file_id)
  131. file = MediaFile(file, notifications)
  132. bounding_boxes = [MediaBoundingBox(result) for result in result_filter[file_id]]
  133. # Perform inference.
  134. bbox_labels = pipeline.pure_inference(storage, file, bounding_boxes)
  135. # Add the labels determined in the inference process.
  136. for i, result in enumerate(result_filter[file_id]):
  137. result.label_id = bbox_labels[i].identifier
  138. result.set_origin('user', origin_user=None, commit=True)
  139. notifications.add(notification_manager.edit_result, result)
  140. # yield progress
  141. yield index / length, notifications
  142. index += 1
  143. finally:
  144. if pipeline is not None:
  145. pipelines.free_instance(model_root)
  146. @staticmethod
  147. def progress(progress: float, notifications: NotificationList):
  148. """
  149. fire notifications from the correct thread
  150. :param progress: [0, 1]
  151. :param notifications: Notificationlist
  152. :return: progress
  153. """
  154. notifications.fire()
  155. return progress