WebServer.py 16 KB

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