File.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. from __future__ import annotations
  2. import os
  3. import typing as T
  4. import warnings
  5. from datetime import datetime
  6. from pathlib import Path
  7. from pycs import db
  8. from pycs.database.Collection import Collection
  9. from pycs.database.Result import Result
  10. from pycs.database.base import NamedBaseModel
  11. from pycs.database.util import commit_on_return
  12. class File(NamedBaseModel):
  13. # table columns
  14. uuid = db.Column(db.String, nullable=False)
  15. extension = db.Column(db.String, nullable=False)
  16. type = db.Column(db.String, nullable=False)
  17. size = db.Column(db.String, nullable=False)
  18. created = db.Column(db.DateTime, default=datetime.utcnow,
  19. index=True, nullable=False)
  20. path = db.Column(db.String, nullable=False)
  21. frames = db.Column(db.Integer)
  22. fps = db.Column(db.Float)
  23. project_id = db.Column(
  24. db.Integer,
  25. db.ForeignKey("project.id", ondelete="CASCADE"),
  26. nullable=False)
  27. collection_id = db.Column(
  28. db.Integer,
  29. db.ForeignKey("collection.id", ondelete="SET NULL"))
  30. # contraints
  31. __table_args__ = (
  32. db.UniqueConstraint('project_id', 'path'),
  33. )
  34. results = db.relationship("Result", backref="file",
  35. lazy="dynamic", passive_deletes=True)
  36. serialize_only = NamedBaseModel.serialize_only + (
  37. "uuid",
  38. "extension",
  39. "type",
  40. "size",
  41. "created",
  42. "path",
  43. "frames",
  44. "fps",
  45. "project_id",
  46. "collection_id",
  47. )
  48. @property
  49. def filename(self):
  50. return f"{self.name}{self.extension}"
  51. @property
  52. def absolute_path(self) -> str:
  53. path = Path(self.path)
  54. if path.is_absolute():
  55. return str(path)
  56. return str(Path.cwd() / path)
  57. def delete(self, commit: bool = True):
  58. super().delete(commit=commit)
  59. # remove file from folder
  60. os.remove(self.path)
  61. # TODO: remove temp files
  62. warnings.warn("Temporary files may still exist!")
  63. @commit_on_return
  64. def set_collection(self, collection_id: T.Optional[int]):
  65. """
  66. set this file's collection
  67. :param collection_id: new collection id
  68. :return:
  69. """
  70. self.collection_id = collection_id
  71. @commit_on_return
  72. def set_collection_by_reference(self, collection_reference: T.Optional[str]):
  73. """
  74. set this file's collection
  75. :param collection_reference: collection reference
  76. :return:
  77. """
  78. if self.collection_reference is None:
  79. self.set_collection(None)
  80. collection = Collection.query.filter_by(reference=collection_reference).one()
  81. self.collection_id = collection.id
  82. def _get_another_file(self, *query) -> T.Optional[File]:
  83. """
  84. get the first file matching the query ordered by descending id
  85. :return: another file or None
  86. """
  87. return File.query.filter(File.project_id == self.project_id, *query)
  88. def next(self) -> T.Optional[File]:
  89. """
  90. get the successor of this file
  91. :return: another file or None
  92. """
  93. return self._get_another_file(File.id > self.id)\
  94. .order_by(File.id).first()
  95. def previous(self) -> T.Optional[File]:
  96. """
  97. get the predecessor of this file
  98. :return: another file or None
  99. """
  100. return self._get_another_file(File.id < self.id)\
  101. .order_by(File.id.desc()).first()
  102. def next_in_collection(self) -> T.Optional[File]:
  103. """
  104. get the predecessor of this file
  105. :return: another file or None
  106. """
  107. return self._get_another_file(
  108. File.id > self.id, File.collection_id == self.collection_id)\
  109. .order_by(File.id).first()
  110. def previous_in_collection(self) -> T.Optional[File]:
  111. """
  112. get the predecessor of this file
  113. :return: another file or None
  114. """
  115. return self._get_another_file(
  116. File.id < self.id, File.collection_id == self.collection_id)\
  117. .order_by(File.id.desc()).first()
  118. def result(self, id: int) -> T.Optional[Result]:
  119. return self.results.get(id)
  120. @commit_on_return
  121. def create_result(self,
  122. origin: str,
  123. result_type: str,
  124. label: T.Optional[T.Union[Label, int]] = None,
  125. data: T.Optional[dict] = None) -> Result:
  126. result = Result.new(commit=False,
  127. file_id=self.id,
  128. origin=origin,
  129. type=result_type)
  130. result.data = data
  131. if label is not None:
  132. assert isinstance(label, (int, Label)), f"Wrong label type: {type(label)}"
  133. if isinstance(label, Label):
  134. label = label.id
  135. result.label_id = label
  136. return result
  137. def remove_results(self, origin='pipeline') -> T.List[Result]:
  138. results = Result.query.filter(
  139. Result.file_id == self.id,
  140. Result.origin == origin)
  141. _results = results.all()
  142. results.delete()
  143. return _results