CreateResult.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.frontend.notifications.NotificationManager import NotificationManager
  6. class CreateResult(View):
  7. """
  8. create a result for a file
  9. """
  10. # pylint: disable=arguments-differ
  11. methods = ['POST']
  12. def __init__(self, nm: NotificationManager):
  13. # pylint: disable=invalid-name
  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 request_data.get('type') not in ['labeled-image', 'bounding-box']:
  19. return abort(400)
  20. rtype = request_data['type']
  21. if 'label' in request_data and request_data['label']:
  22. label = request_data['label']
  23. elif request_data['type'] == 'labeled-image':
  24. return abort(400, "label missing for the labeled-image annotation")
  25. else:
  26. label = None
  27. if request_data.get('data'):
  28. data = request_data['data']
  29. elif request_data['type'] == 'bounding-box':
  30. return abort(400, "data missing for the bounding box annotation")
  31. else:
  32. data = {}
  33. # find file
  34. file = File.query.get(file_id)
  35. if file is None:
  36. return abort(404)
  37. removed = []
  38. # start transaction
  39. with db.session.begin_nested():
  40. # find full-image labels and remove them
  41. for result in file.results.all():
  42. if result.type == 'labeled-image':
  43. removed.append(result.serialize())
  44. result.remove(commit=True)
  45. # insert into database
  46. new_result = file.create_result('user', rtype, label, data,
  47. commit=False)
  48. for result in removed:
  49. self.nm.remove_result(result.serialize())
  50. self.nm.create_result(new_result.id)
  51. return jsonify(new_result)