6
0

Result.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import json
  2. import typing as T
  3. from pycs import db
  4. from pycs.database.base import BaseModel
  5. from pycs.database.util import commit_on_return
  6. class Result(BaseModel):
  7. """ DB Model for projects """
  8. file_id = db.Column(
  9. db.Integer,
  10. db.ForeignKey("file.id", ondelete="CASCADE"),
  11. nullable=False)
  12. origin = db.Column(db.String, nullable=False)
  13. origin_user = db.Column(db.String, nullable=True)
  14. type = db.Column(db.String, nullable=False)
  15. label_id = db.Column(
  16. db.Integer,
  17. db.ForeignKey("label.id", ondelete="SET NULL"),
  18. nullable=True)
  19. data_encoded = db.Column(db.String)
  20. serialize_only = BaseModel.serialize_only + (
  21. "file_id",
  22. "origin",
  23. "origin_user",
  24. "type",
  25. "label_id",
  26. "data",
  27. )
  28. def serialize(self):
  29. """ extends the default serialize with the decoded data attribute """
  30. result = super().serialize()
  31. result["data"] = self.data
  32. return result
  33. @property
  34. def data(self) -> T.Optional[dict]:
  35. """ getter for the decoded data attribute """
  36. return None if self.data_encoded is None else json.loads(self.data_encoded)
  37. @data.setter
  38. def data(self, value):
  39. """
  40. setter for the decoded data attribute
  41. The attribute is encoded property before assigned to the object.
  42. """
  43. if isinstance(value, str) or value is None:
  44. self.data_encoded = value
  45. elif isinstance(value, (dict, list)):
  46. self.data_encoded = json.dumps(value)
  47. else:
  48. raise ValueError(f"Not supported type: {type(value)}")
  49. @commit_on_return
  50. def set_origin(self, origin: str, origin_user: str = None):
  51. """
  52. set this results origin
  53. :param origin: either 'user' or 'pipeline'
  54. :param origin_user: None if origin is 'pipeline' else name of the user
  55. :return:
  56. """
  57. if origin == "pipeline" and not origin_user is None:
  58. raise ValueError("If an annotation was made by the pipeline no user"\
  59. "can be specified!")
  60. self.origin = origin
  61. self.origin_user = origin_user
  62. @commit_on_return
  63. def set_label(self, label: int):
  64. """
  65. set this results origin
  66. :param label: label ID
  67. :return:
  68. """
  69. self.label_id = label