CreateResult.py 1.9 KB

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