6
0

PredictModel.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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, 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. nm: NotificationManager,
  103. project_id: int, file_filter: List[int], result_filter: dict[int, List[Result]]):
  104. """
  105. load the pipeline and call the execute function
  106. :param database: database object
  107. :param pipelines: pipeline cache
  108. :param notifications: notification object
  109. :param nm: notification manager
  110. :param project_id: project id
  111. :param file_filter: list of file ids
  112. :param result_filter: dict of file id and list of results (bounding boxes) to classify
  113. :return:
  114. """
  115. pipeline = None
  116. # create new database instance
  117. project = Project.query.get(project_id)
  118. model_root = project.model.root_folder
  119. storage = MediaStorage(project_id, notifications)
  120. # create a list of MediaFile
  121. # Also convert dict to the same key type.
  122. length = len(file_filter)
  123. # load pipeline
  124. try:
  125. pipeline = pipelines.load_from_root_folder(project_id, model_root)
  126. # iterate over media files
  127. index = 0
  128. for file_id in file_filter:
  129. file = project.file(file_id)
  130. file = MediaFile(file, notifications)
  131. bounding_boxes = [MediaBoundingBox(result) for result in result_filter[file_id]]
  132. # Perform inference.
  133. bbox_labels = pipeline.pure_inference(storage, file, bounding_boxes)
  134. # Add the labels determined in the inference process.
  135. for i, result in enumerate(result_filter[file_id]):
  136. result.label_id = bbox_labels[i].identifier
  137. result.set_origin('user', commit=True)
  138. notifications.add(nm.edit_result, result)
  139. # yield progress
  140. yield index / length, notifications
  141. index += 1
  142. finally:
  143. if pipeline is not None:
  144. pipelines.free_instance(model_root)
  145. @staticmethod
  146. def progress(progress: float, notifications: NotificationList):
  147. """
  148. fire notifications from the correct thread
  149. :param progress: [0, 1]
  150. :param notifications: Notificationlist
  151. :return: progress
  152. """
  153. notifications.fire()
  154. return progress