WebServer.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import eventlet
  2. import os
  3. import socketio
  4. from glob import glob
  5. from os import getcwd
  6. from os import path
  7. from os.path import exists
  8. from flask import Flask
  9. from flask import send_from_directory
  10. from pycs import app
  11. from pycs.database.Model import Model
  12. from pycs.database.LabelProvider import LabelProvider
  13. from pycs.frontend.endpoints.ListJobs import ListJobs
  14. from pycs.frontend.endpoints.ListLabelProviders import ListLabelProviders
  15. from pycs.frontend.endpoints.ListModels import ListModels
  16. from pycs.frontend.endpoints.ListProjects import ListProjects
  17. from pycs.frontend.endpoints.additional.FolderInformation import FolderInformation
  18. from pycs.frontend.endpoints.data.GetCroppedFile import GetCroppedFile
  19. from pycs.frontend.endpoints.data.GetFile import GetFile
  20. from pycs.frontend.endpoints.data.GetPreviousAndNextFile import GetPreviousAndNextFile
  21. from pycs.frontend.endpoints.data.GetResizedFile import GetResizedFile
  22. from pycs.frontend.endpoints.data.RemoveFile import RemoveFile
  23. from pycs.frontend.endpoints.data.UploadFile import UploadFile
  24. from pycs.frontend.endpoints.jobs.RemoveJob import RemoveJob
  25. from pycs.frontend.endpoints.labels.CreateLabel import CreateLabel
  26. from pycs.frontend.endpoints.labels.EditLabelName import EditLabelName
  27. from pycs.frontend.endpoints.labels.EditLabelParent import EditLabelParent
  28. from pycs.frontend.endpoints.labels.ListLabelTree import ListLabelTree
  29. from pycs.frontend.endpoints.labels.ListLabels import ListLabels
  30. from pycs.frontend.endpoints.labels.RemoveLabel import RemoveLabel
  31. from pycs.frontend.endpoints.pipelines.FitModel import FitModel
  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. def __init__(self, app, settings: dict, discovery: bool = True):
  60. PRODUCTION = os.path.exists('webui/index.html')
  61. # initialize web server
  62. if PRODUCTION:
  63. print('production build')
  64. # find static files and folders
  65. static_files = {}
  66. for file_path in glob('webui/*'):
  67. file_path = file_path.replace('\\', '/')
  68. static_files[file_path[5:]] = file_path
  69. # separately add svg files and set their correct mime type
  70. for svg_path in glob('webui/img/*.svg'):
  71. svg_path = svg_path.replace('\\', '/')
  72. static_files[svg_path[5:]] = {'content_type': 'image/svg+xml', 'filename': svg_path}
  73. # create service objects
  74. if len(settings['allowedOrigins']) > 0:
  75. origins = settings['allowedOrigins']
  76. self.__sio = socketio.Server(cors_allowed_origins=origins, async_mode='eventlet')
  77. else:
  78. self.__sio = socketio.Server(async_mode='eventlet')
  79. self.__app = socketio.WSGIApp(self.__sio, app, static_files=static_files)
  80. # overwrite root path to serve index.html
  81. @app.route('/', methods=['GET'])
  82. def index():
  83. # pylint: disable=unused-variable
  84. return send_from_directory(path.join(getcwd(), 'webui'), 'index.html')
  85. else:
  86. print('development build')
  87. # create service objects
  88. self.__sio = socketio.Server(cors_allowed_origins='*', async_mode='eventlet')
  89. self.app = app
  90. self.wsgi_app = socketio.WSGIApp(self.__sio, app)
  91. # set access control header to allow requests from Vue.js development server
  92. @self.app.after_request
  93. def after_request(response):
  94. # pylint: disable=unused-variable
  95. response.headers['Access-Control-Allow-Origin'] = '*'
  96. return response
  97. # set json encoder so database objects are serialized correctly
  98. self.app.json_encoder = JSONEncoder
  99. self.host = settings.host
  100. self.port = settings.port
  101. # create notification manager
  102. jobs = JobRunner()
  103. pipelines = PipelineCache(jobs)
  104. notifications = NotificationManager(self.__sio)
  105. jobs.on_create(notifications.create_job)
  106. jobs.on_start(notifications.edit_job)
  107. jobs.on_progress(notifications.edit_job)
  108. jobs.on_finish(notifications.edit_job)
  109. jobs.on_remove(notifications.remove_job)
  110. self.define_routes(jobs, notifications, pipelines)
  111. if discovery:
  112. Model.discover("models/")
  113. LabelProvider.discover("labels/")
  114. def define_routes(self, jobs, notifications, pipelines):
  115. # additional
  116. self.app.add_url_rule(
  117. '/folder',
  118. view_func=FolderInformation.as_view('folder_information')
  119. )
  120. # jobs
  121. self.app.add_url_rule(
  122. '/jobs',
  123. view_func=ListJobs.as_view('list_jobs', jobs)
  124. )
  125. self.app.add_url_rule(
  126. '/jobs/<int:job_id>/remove',
  127. view_func=RemoveJob.as_view('remove_job', jobs)
  128. )
  129. # models
  130. self.app.add_url_rule(
  131. '/models',
  132. view_func=ListModels.as_view('list_models')
  133. )
  134. self.app.add_url_rule(
  135. '/projects/<int:project_id>/model',
  136. view_func=GetProjectModel.as_view('get_project_model')
  137. )
  138. # labels
  139. self.app.add_url_rule(
  140. '/label_providers',
  141. view_func=ListLabelProviders.as_view('label_providers')
  142. )
  143. self.app.add_url_rule(
  144. '/projects/<int:project_id>/labels',
  145. view_func=ListLabels.as_view('list_labels')
  146. )
  147. self.app.add_url_rule(
  148. '/projects/<int:project_id>/labels/tree',
  149. view_func=ListLabelTree.as_view('list_label_tree')
  150. )
  151. self.app.add_url_rule(
  152. '/projects/<int:project_id>/labels',
  153. view_func=CreateLabel.as_view('create_label', notifications)
  154. )
  155. self.app.add_url_rule(
  156. '/projects/<int:project_id>/labels/<int:label_id>/remove',
  157. view_func=RemoveLabel.as_view('remove_label', notifications)
  158. )
  159. self.app.add_url_rule(
  160. '/projects/<int:project_id>/labels/<int:label_id>/name',
  161. view_func=EditLabelName.as_view('edit_label_name', notifications)
  162. )
  163. self.app.add_url_rule(
  164. '/projects/<int:project_id>/labels/<int:label_id>/parent',
  165. view_func=EditLabelParent.as_view('edit_label_parent', notifications)
  166. )
  167. # collections
  168. self.app.add_url_rule(
  169. '/projects/<int:project_id>/collections',
  170. view_func=ListProjectCollections.as_view('list_collections')
  171. )
  172. self.app.add_url_rule(
  173. '/projects/<int:project_id>/data/<int:collection_id>/<int:start>/<int:length>',
  174. view_func=ListProjectFiles.as_view('list_collection_files')
  175. )
  176. # data
  177. self.app.add_url_rule(
  178. '/projects/<int:project_id>/data',
  179. view_func=UploadFile.as_view('upload_file', notifications)
  180. )
  181. self.app.add_url_rule(
  182. '/projects/<int:project_id>/data/<int:start>/<int:length>',
  183. view_func=ListProjectFiles.as_view('list_files')
  184. )
  185. self.app.add_url_rule(
  186. '/data/<int:file_id>/remove',
  187. view_func=RemoveFile.as_view('remove_file', notifications)
  188. )
  189. self.app.add_url_rule(
  190. '/data/<int:file_id>',
  191. view_func=GetFile.as_view('get_file')
  192. )
  193. self.app.add_url_rule(
  194. '/data/<int:file_id>/<resolution>',
  195. view_func=GetResizedFile.as_view('get_resized_file')
  196. )
  197. self.app.add_url_rule(
  198. '/data/<int:file_id>/<resolution>/<crop_box>',
  199. view_func=GetCroppedFile.as_view('crop_result', database)
  200. )
  201. self.app.add_url_rule(
  202. '/data/<int:file_id>/previous_next',
  203. view_func=GetPreviousAndNextFile.as_view('get_previous_and_next_file')
  204. )
  205. # results
  206. self.app.add_url_rule(
  207. '/projects/<int:project_id>/results',
  208. view_func=GetProjectResults.as_view('get_project_results')
  209. )
  210. self.app.add_url_rule(
  211. '/data/<int:file_id>/results',
  212. view_func=GetResults.as_view('get_results')
  213. )
  214. self.app.add_url_rule(
  215. '/data/<int:file_id>/results',
  216. view_func=CreateResult.as_view('create_result', notifications)
  217. )
  218. self.app.add_url_rule(
  219. '/data/<int:file_id>/reset',
  220. view_func=ResetResults.as_view('reset_results', notifications)
  221. )
  222. self.app.add_url_rule(
  223. '/results/<int:result_id>/remove',
  224. view_func=RemoveResult.as_view('remove_result', notifications)
  225. )
  226. self.app.add_url_rule(
  227. '/results/<int:result_id>/confirm',
  228. view_func=ConfirmResult.as_view('confirm_result', notifications)
  229. )
  230. self.app.add_url_rule(
  231. '/results/<int:result_id>/crop',
  232. view_func=ResultAsCrop.as_view('crop_result')
  233. )
  234. self.app.add_url_rule(
  235. '/results/<int:result_id>/crop/<int:max_width>',
  236. view_func=ResultAsCrop.as_view('crop_result_resized_by_width')
  237. )
  238. self.app.add_url_rule(
  239. '/results/<int:result_id>/crop/<int:max_width>x<int:max_height>',
  240. view_func=ResultAsCrop.as_view('crop_result_resized')
  241. )
  242. self.app.add_url_rule(
  243. '/results/<int:result_id>/label',
  244. view_func=EditResultLabel.as_view('edit_result_label', notifications)
  245. )
  246. self.app.add_url_rule(
  247. '/results/<int:result_id>/data',
  248. view_func=EditResultData.as_view('edit_result_data', notifications)
  249. )
  250. # projects
  251. self.app.add_url_rule(
  252. '/projects',
  253. view_func=ListProjects.as_view('list_projects')
  254. )
  255. self.app.add_url_rule(
  256. '/projects',
  257. view_func=CreateProject.as_view('create_project', notifications, jobs)
  258. )
  259. self.app.add_url_rule(
  260. '/projects/<int:project_id>/label_provider',
  261. view_func=ExecuteLabelProvider.as_view('execute_label_provider', notifications, jobs)
  262. )
  263. self.app.add_url_rule(
  264. '/projects/<int:project_id>/external_storage',
  265. view_func=ExecuteExternalStorage.as_view('execute_external_storage', notifications, jobs)
  266. )
  267. self.app.add_url_rule(
  268. '/projects/<int:project_id>/remove',
  269. view_func=RemoveProject.as_view('remove_project', notifications)
  270. )
  271. self.app.add_url_rule(
  272. '/projects/<int:project_id>/name',
  273. view_func=EditProjectName.as_view('edit_project_name', notifications)
  274. )
  275. self.app.add_url_rule(
  276. '/projects/<int:project_id>/description',
  277. view_func=EditProjectDescription.as_view('edit_project_description', notifications)
  278. )
  279. # pipelines
  280. self.app.add_url_rule(
  281. '/projects/<int:project_id>/pipelines/fit',
  282. view_func=FitModel.as_view('fit_model', jobs, pipelines)
  283. )
  284. self.app.add_url_rule(
  285. '/projects/<int:project_id>/pipelines/predict',
  286. view_func=PredictModel.as_view('predict_model', notifications, jobs,
  287. pipelines)
  288. )
  289. self.app.add_url_rule(
  290. '/data/<int:file_id>/predict',
  291. view_func=PredictFile.as_view('predict_file', notifications, jobs, pipelines)
  292. )
  293. def run(self):
  294. # finally start web server
  295. eventlet.wsgi.server(eventlet.listen((self.host, self.port)), self.wsgi_app)