WebServer.py 16 KB

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