6
0

WebServer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import typing as T
  2. from glob import glob
  3. from pathlib import Path
  4. import eventlet
  5. import munch
  6. import socketio
  7. from flask import send_from_directory
  8. from pycs.database.LabelProvider import LabelProvider
  9. from pycs.database.Model import Model
  10. from pycs.frontend.endpoints.ListJobs import ListJobs
  11. from pycs.frontend.endpoints.ListLabelProviders import ListLabelProviders
  12. from pycs.frontend.endpoints.ListModels import ListModels
  13. from pycs.frontend.endpoints.ListProjects import ListProjects
  14. from pycs.frontend.endpoints.additional.FolderInformation import FolderInformation
  15. from pycs.frontend.endpoints.data.GetCroppedFile import GetCroppedFile
  16. from pycs.frontend.endpoints.data.GetFile import GetFile
  17. from pycs.frontend.endpoints.data.GetPreviousAndNextFile import GetPreviousAndNextFile
  18. from pycs.frontend.endpoints.data.GetResizedFile import GetResizedFile
  19. from pycs.frontend.endpoints.data.RemoveFile import RemoveFile
  20. from pycs.frontend.endpoints.data.UploadFile import UploadFile
  21. from pycs.frontend.endpoints.jobs.RemoveJob import RemoveJob
  22. from pycs.frontend.endpoints.labels.CreateLabel import CreateLabel
  23. from pycs.frontend.endpoints.labels.EditLabelName import EditLabelName
  24. from pycs.frontend.endpoints.labels.EditLabelParent import EditLabelParent
  25. from pycs.frontend.endpoints.labels.ListLabelTree import ListLabelTree
  26. from pycs.frontend.endpoints.labels.ListLabels import ListLabels
  27. from pycs.frontend.endpoints.labels.RemoveLabel import RemoveLabel
  28. from pycs.frontend.endpoints.pipelines.EstimateBoundingBox import EstimateBoundingBox
  29. from pycs.frontend.endpoints.pipelines.FitModel import FitModel
  30. from pycs.frontend.endpoints.pipelines.PredictBoundingBox import PredictBoundingBox
  31. from pycs.frontend.endpoints.pipelines.PredictFile import PredictFile
  32. from pycs.frontend.endpoints.pipelines.PredictModel import PredictModel
  33. from pycs.frontend.endpoints.projects.CreateProject import CreateProject
  34. from pycs.frontend.endpoints.projects.EditProjectDescription import EditProjectDescription
  35. from pycs.frontend.endpoints.projects.EditProjectName import EditProjectName
  36. from pycs.frontend.endpoints.projects.ExecuteExternalStorage import ExecuteExternalStorage
  37. from pycs.frontend.endpoints.projects.ExecuteLabelProvider import ExecuteLabelProvider
  38. from pycs.frontend.endpoints.projects.GetProjectModel import GetProjectModel
  39. from pycs.frontend.endpoints.projects.ListProjectCollections import ListProjectCollections
  40. from pycs.frontend.endpoints.projects.ListProjectFiles import ListProjectFiles
  41. from pycs.frontend.endpoints.projects.RemoveProject import RemoveProject
  42. from pycs.frontend.endpoints.results.ConfirmResult import ConfirmResult
  43. from pycs.frontend.endpoints.results.CopyResults import CopyResults
  44. from pycs.frontend.endpoints.results.CreateResult import CreateResult
  45. from pycs.frontend.endpoints.results.EditResultData import EditResultData
  46. from pycs.frontend.endpoints.results.EditResultLabel import EditResultLabel
  47. from pycs.frontend.endpoints.results.GetProjectResults import GetProjectResults
  48. from pycs.frontend.endpoints.results.GetResults import GetResults
  49. from pycs.frontend.endpoints.results.RemoveResult import RemoveResult
  50. from pycs.frontend.endpoints.results.ResetResults import ResetResults
  51. from pycs.frontend.notifications.NotificationManager import NotificationManager
  52. from pycs.jobs.JobRunner import JobRunner
  53. from pycs.util.PipelineCache import PipelineCache
  54. class WebServer:
  55. """
  56. wrapper class for flask and socket.io which initializes most networking
  57. """
  58. index: Path = Path.cwd() / 'webui' / 'index.html'
  59. def __init__(self, app, settings: munch.Munch, discovery: bool = True):
  60. self.app = app
  61. # initialize web server
  62. if self.is_production:
  63. app.logger.info('production build')
  64. # overwrite root path to serve index.html
  65. @self.app.route('/', methods=['GET'])
  66. def index():
  67. # pylint: disable=unused-variable
  68. return send_from_directory(str(self.index.parent), self.index.name)
  69. else:
  70. app.logger.info('development build')
  71. # set access control header to allow requests from Vue.js development server
  72. @self.app.after_request
  73. def after_request(response):
  74. # pylint: disable=unused-variable
  75. response.headers['Access-Control-Allow-Origin'] = '*'
  76. return response
  77. # create service objects
  78. self.sio = socketio.Server(**self.sio_kwargs(settings.allowedOrigins))
  79. self.wsgi_app = socketio.WSGIApp(self.sio, app, static_files=self.static_files)
  80. self.host = settings.host
  81. self.port = settings.port
  82. # create notification manager
  83. self.jobs = JobRunner()
  84. self.pipelines = PipelineCache(self.jobs, settings.get("pipeline_cache_time"))
  85. self.notifications = NotificationManager(self.sio)
  86. self.jobs.on_create(self.notifications.create_job)
  87. self.jobs.on_start(self.notifications.edit_job)
  88. self.jobs.on_progress(self.notifications.edit_job)
  89. self.jobs.on_finish(self.notifications.edit_job)
  90. self.jobs.on_remove(self.notifications.remove_job)
  91. self.define_routes()
  92. if discovery:
  93. Model.discover("models/")
  94. LabelProvider.discover("labels/")
  95. def sio_kwargs(self, allowed_origins) -> T.Dict[str, T.Union[str, list]]:
  96. """keyword arguments for the socketio.Server depending on the mode"""
  97. kwargs: T.Dict[str, T.Union[str, list]] = dict(async_mode="eventlet")
  98. if self.is_production:
  99. if isinstance(allowed_origins, list) and len(allowed_origins) > 0:
  100. kwargs["cors_allowed_origins"] = allowed_origins
  101. else:
  102. kwargs["cors_allowed_origins"] = "*"
  103. return kwargs
  104. @property
  105. def is_production(self) -> bool:
  106. """property checking, whether the UI is built (production mode)
  107. or served by npm serve (development mode)"""
  108. return self.index.exists()
  109. @property
  110. def static_files(self) -> T.Optional[T.Dict[str, T.Union[str, dict]]]:
  111. """returns a dictionary of static files (production mode)
  112. or None (development mode)"""
  113. if not self.is_production:
  114. return None
  115. # find static files and folders
  116. static_files: T.Dict[str, T.Union[str, dict]] = {}
  117. for file_path in glob('webui/*'):
  118. file_path = file_path.replace('\\', '/')
  119. static_files[file_path[5:]] = file_path
  120. # separately add svg files and set their correct mime type
  121. for svg_path in glob('webui/img/*.svg'):
  122. svg_path = svg_path.replace('\\', '/')
  123. static_files[svg_path[5:]] = {'content_type': 'image/svg+xml', 'filename': svg_path}
  124. return static_files
  125. def define_routes(self):
  126. """ defines app routes """
  127. # additional
  128. self.app.add_url_rule(
  129. '/folder',
  130. view_func=FolderInformation.as_view('folder_information')
  131. )
  132. # jobs
  133. self.app.add_url_rule(
  134. '/jobs',
  135. view_func=ListJobs.as_view('list_jobs', self.jobs)
  136. )
  137. self.app.add_url_rule(
  138. '/jobs/<job_id>/remove',
  139. view_func=RemoveJob.as_view('remove_job', self.jobs)
  140. )
  141. # models
  142. self.app.add_url_rule(
  143. '/models',
  144. view_func=ListModels.as_view('list_models')
  145. )
  146. self.app.add_url_rule(
  147. '/projects/<int:project_id>/model',
  148. view_func=GetProjectModel.as_view('get_project_model')
  149. )
  150. # labels
  151. self.app.add_url_rule(
  152. '/label_providers',
  153. view_func=ListLabelProviders.as_view('label_providers')
  154. )
  155. self.app.add_url_rule(
  156. '/projects/<int:project_id>/labels',
  157. view_func=ListLabels.as_view('list_labels')
  158. )
  159. self.app.add_url_rule(
  160. '/projects/<int:project_id>/labels/tree',
  161. view_func=ListLabelTree.as_view('list_label_tree')
  162. )
  163. self.app.add_url_rule(
  164. '/projects/<int:project_id>/labels',
  165. view_func=CreateLabel.as_view('create_label', self.notifications)
  166. )
  167. self.app.add_url_rule(
  168. '/projects/<int:project_id>/labels/<int:label_id>/remove',
  169. view_func=RemoveLabel.as_view('remove_label', self.notifications)
  170. )
  171. self.app.add_url_rule(
  172. '/projects/<int:project_id>/labels/<int:label_id>/name',
  173. view_func=EditLabelName.as_view('edit_label_name', self.notifications)
  174. )
  175. self.app.add_url_rule(
  176. '/projects/<int:project_id>/labels/<int:label_id>/parent',
  177. view_func=EditLabelParent.as_view('edit_label_parent', self.notifications)
  178. )
  179. # collections
  180. self.app.add_url_rule(
  181. '/projects/<int:project_id>/collections',
  182. view_func=ListProjectCollections.as_view('list_collections')
  183. )
  184. self.app.add_url_rule(
  185. '/projects/<int:project_id>/data/<int:collection_id>/<int:start>/<int:length>',
  186. view_func=ListProjectFiles.as_view('list_collection_files')
  187. )
  188. # data
  189. self.app.add_url_rule(
  190. '/projects/<int:project_id>/data',
  191. view_func=UploadFile.as_view('upload_file', self.notifications)
  192. )
  193. self.app.add_url_rule(
  194. '/projects/<int:project_id>/data',
  195. view_func=ListProjectFiles.as_view('list_all_files')
  196. )
  197. self.app.add_url_rule(
  198. '/projects/<int:project_id>/data/<int:start>/<int:length>',
  199. view_func=ListProjectFiles.as_view('list_files')
  200. )
  201. self.app.add_url_rule(
  202. '/data/<int:file_id>/remove',
  203. view_func=RemoveFile.as_view('remove_file', self.notifications)
  204. )
  205. self.app.add_url_rule(
  206. '/data/<int:file_id>',
  207. view_func=GetFile.as_view('get_file')
  208. )
  209. self.app.add_url_rule(
  210. '/data/<int:file_id>/<resolution>',
  211. view_func=GetResizedFile.as_view('get_resized_file')
  212. )
  213. self.app.add_url_rule(
  214. '/data/<int:file_id>/<resolution>/<crop_box>',
  215. view_func=GetCroppedFile.as_view('get_cropped_file')
  216. )
  217. self.app.add_url_rule(
  218. '/data/<int:file_id>/previous_next',
  219. view_func=GetPreviousAndNextFile.as_view('get_previous_and_next_file')
  220. )
  221. # results
  222. self.app.add_url_rule(
  223. '/projects/<int:project_id>/results',
  224. view_func=GetProjectResults.as_view('get_project_results')
  225. )
  226. self.app.add_url_rule(
  227. '/data/<int:file_id>/results',
  228. view_func=GetResults.as_view('get_results')
  229. )
  230. self.app.add_url_rule(
  231. '/data/<int:file_id>/results',
  232. view_func=CreateResult.as_view('create_result', self.notifications)
  233. )
  234. self.app.add_url_rule(
  235. '/data/<int:file_id>/copy_results',
  236. view_func=CopyResults.as_view('copy_results', self.notifications)
  237. )
  238. self.app.add_url_rule(
  239. '/data/<int:file_id>/reset',
  240. view_func=ResetResults.as_view('reset_results', self.notifications)
  241. )
  242. self.app.add_url_rule(
  243. '/results/<int:result_id>/remove',
  244. view_func=RemoveResult.as_view('remove_result', self.notifications)
  245. )
  246. self.app.add_url_rule(
  247. '/results/<int:result_id>/confirm',
  248. view_func=ConfirmResult.as_view('confirm_result', self.notifications)
  249. )
  250. self.app.add_url_rule(
  251. '/results/<int:result_id>/label',
  252. view_func=EditResultLabel.as_view('edit_result_label', self.notifications)
  253. )
  254. self.app.add_url_rule(
  255. '/results/<int:result_id>/data',
  256. view_func=EditResultData.as_view('edit_result_data', self.notifications)
  257. )
  258. # projects
  259. self.app.add_url_rule(
  260. '/projects',
  261. view_func=ListProjects.as_view('list_projects')
  262. )
  263. self.app.add_url_rule(
  264. '/projects',
  265. view_func=CreateProject.as_view('create_project', self.notifications, self.jobs)
  266. )
  267. self.app.add_url_rule(
  268. '/projects/<int:project_id>/label_provider',
  269. view_func=ExecuteLabelProvider.as_view('execute_label_provider',
  270. self.notifications, self.jobs)
  271. )
  272. self.app.add_url_rule(
  273. '/projects/<int:project_id>/external_storage',
  274. view_func=ExecuteExternalStorage.as_view('execute_external_storage',
  275. self.notifications, self.jobs)
  276. )
  277. self.app.add_url_rule(
  278. '/projects/<int:project_id>/remove',
  279. view_func=RemoveProject.as_view('remove_project', self.notifications)
  280. )
  281. self.app.add_url_rule(
  282. '/projects/<int:project_id>/name',
  283. view_func=EditProjectName.as_view('edit_project_name', self.notifications)
  284. )
  285. self.app.add_url_rule(
  286. '/projects/<int:project_id>/description',
  287. view_func=EditProjectDescription.as_view('edit_project_description', self.notifications)
  288. )
  289. # pipelines
  290. self.app.add_url_rule(
  291. '/projects/<int:project_id>/pipelines/fit',
  292. view_func=FitModel.as_view('fit_model', self.jobs, self.pipelines)
  293. )
  294. self.app.add_url_rule(
  295. '/projects/<int:project_id>/pipelines/predict',
  296. view_func=PredictModel.as_view('predict_model', self.notifications, self.jobs,
  297. self.pipelines)
  298. )
  299. self.app.add_url_rule(
  300. '/data/<int:file_id>/predict',
  301. view_func=PredictFile.as_view('predict_file', self.notifications,
  302. self.jobs, self.pipelines)
  303. )
  304. self.app.add_url_rule(
  305. '/data/<int:file_id>/<int:bbox_id>/predict_bounding_box',
  306. view_func=PredictBoundingBox.as_view('predict_bounding_box', self.notifications,
  307. self.jobs, self.pipelines)
  308. )
  309. self.app.add_url_rule(
  310. '/data/<int:file_id>/estimate',
  311. view_func=EstimateBoundingBox.as_view('estimate_result', self.notifications,
  312. self.jobs)
  313. )
  314. def run(self):
  315. """ start web server """
  316. self.pipelines.start()
  317. eventlet.wsgi.server(eventlet.listen((self.host, self.port)), self.wsgi_app)