CreateResult.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from flask import request, abort, jsonify
  2. from flask.views import View
  3. from pycs.database.Database import Database
  4. from pycs.frontend.notifications.NotificationManager import NotificationManager
  5. class CreateResult(View):
  6. """
  7. create a result for a file
  8. """
  9. # pylint: disable=arguments-differ
  10. methods = ['POST']
  11. def __init__(self, db: Database, nm: NotificationManager):
  12. # pylint: disable=invalid-name
  13. self.db = db
  14. self.nm = nm
  15. def dispatch_request(self, file_id: int):
  16. # extract request data
  17. request_data = request.get_json(force=True)
  18. if 'type' not in request_data:
  19. return abort(400)
  20. if request_data['type'] not in ['labeled-image', 'bounding-box']:
  21. return abort(400)
  22. rtype = request_data['type']
  23. if 'label' in request_data and request_data['label']:
  24. label = request_data['label']
  25. elif request_data['type'] == 'labeled-image':
  26. return abort(400, "label missing for the labeled-image annotation")
  27. else:
  28. label = None
  29. if 'data' in request_data and request_data['data']:
  30. data = request_data['data']
  31. elif request_data['type'] == 'bounding-box':
  32. return abort(400, "data missing for the bounding box annotation")
  33. else:
  34. data = {}
  35. # find file
  36. file = self.db.file(file_id)
  37. if file is None:
  38. return abort(404)
  39. # start transaction
  40. with self.db:
  41. # find full-image labels and remove them
  42. for result in file.results.all():
  43. if result.type == 'labeled-image':
  44. result.remove()
  45. self.nm.remove_result(result.serialize())
  46. # insert into database
  47. result = file.create_result('user', rtype, label, data)
  48. self.nm.create_result(result.id)
  49. return jsonify(result)