File.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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.Label import Label
  11. from pycs.database.base import NamedBaseModel
  12. from pycs.database.util import commit_on_return
  13. class File(NamedBaseModel):
  14. """ DB Model for files """
  15. # table columns
  16. uuid = db.Column(db.String, nullable=False)
  17. extension = db.Column(db.String, nullable=False)
  18. type = db.Column(db.String, nullable=False)
  19. size = db.Column(db.String, nullable=False)
  20. created = db.Column(db.DateTime, default=datetime.utcnow,
  21. index=True, nullable=False)
  22. path = db.Column(db.String, nullable=False)
  23. frames = db.Column(db.Integer)
  24. fps = db.Column(db.Float)
  25. project_id = db.Column(
  26. db.Integer,
  27. db.ForeignKey("project.id", ondelete="CASCADE"),
  28. nullable=False)
  29. collection_id = db.Column(
  30. db.Integer,
  31. db.ForeignKey("collection.id", ondelete="SET NULL"))
  32. # contraints
  33. __table_args__ = (
  34. db.UniqueConstraint('project_id', 'path'),
  35. )
  36. results = db.relationship("Result", backref="file",
  37. lazy="dynamic", passive_deletes=True)
  38. serialize_only = NamedBaseModel.serialize_only + (
  39. "uuid",
  40. "extension",
  41. "type",
  42. "size",
  43. "created",
  44. "path",
  45. "frames",
  46. "fps",
  47. "project_id",
  48. "collection_id",
  49. )
  50. @property
  51. def filename(self):
  52. """ filename consisting of a name and an extension """
  53. return f"{self.name}{self.extension}"
  54. @property
  55. def absolute_path(self) -> str:
  56. """ returns an absolute of the file """
  57. path = Path(self.path)
  58. if path.is_absolute():
  59. return str(path)
  60. return str(Path.cwd() / path)
  61. # pylint: disable=arguments-differ
  62. def delete(self, commit: bool = True):
  63. """
  64. after the object is deleted, the according physical file
  65. is also delete if commit was True
  66. """
  67. # pylint: disable=unexpected-keyword-arg
  68. super().delete(commit=commit)
  69. if commit:
  70. os.remove(self.path)
  71. # TODO: remove temp files
  72. warnings.warn("Temporary files may still exist!")
  73. @commit_on_return
  74. def set_collection(self, collection_id: T.Optional[int]):
  75. """
  76. set this file's collection
  77. :param collection_id: new collection id
  78. :return:
  79. """
  80. self.collection_id = collection_id
  81. @commit_on_return
  82. def set_collection_by_reference(self, collection_reference: T.Optional[str]):
  83. """
  84. set this file's collection
  85. :param collection_reference: collection reference
  86. :return:
  87. """
  88. if self.collection_reference is None:
  89. self.set_collection(None)
  90. collection = Collection.query.filter_by(reference=collection_reference).one()
  91. self.collection_id = collection.id
  92. def _get_another_file(self, *query) -> T.Optional[File]:
  93. """
  94. get the first file matching the query ordered by descending id
  95. :return: another file or None
  96. """
  97. return File.query.filter(File.project_id == self.project_id, *query)
  98. def next(self) -> T.Optional[File]:
  99. """
  100. get the successor of this file
  101. :return: another file or None
  102. """
  103. return self._get_another_file(File.id > self.id)\
  104. .order_by(File.id).first()
  105. def previous(self) -> T.Optional[File]:
  106. """
  107. get the predecessor of this file
  108. :return: another file or None
  109. """
  110. # pylint: disable=no-member
  111. return self._get_another_file(File.id < self.id)\
  112. .order_by(File.id.desc()).first()
  113. def next_in_collection(self) -> T.Optional[File]:
  114. """
  115. get the predecessor of this file
  116. :return: another file or None
  117. """
  118. return self._get_another_file(
  119. File.id > self.id, File.collection_id == self.collection_id)\
  120. .order_by(File.id).first()
  121. def previous_in_collection(self) -> T.Optional[File]:
  122. """
  123. get the predecessor of this file
  124. :return: another file or None
  125. """
  126. # pylint: disable=no-member
  127. return self._get_another_file(
  128. File.id < self.id, File.collection_id == self.collection_id)\
  129. .order_by(File.id.desc()).first()
  130. def result(self, identifier: int) -> T.Optional[Result]:
  131. """
  132. get one of the file's results
  133. :return: result object or None
  134. """
  135. return self.results.get(identifier)
  136. @commit_on_return
  137. def create_result(self,
  138. origin: str,
  139. result_type: str,
  140. label: T.Optional[T.Union[Label, int]] = None,
  141. data: T.Optional[dict] = None) -> Result:
  142. """
  143. Creates a result and returns the created object
  144. :return: result object
  145. """
  146. result = Result.new(commit=False,
  147. file_id=self.id,
  148. origin=origin,
  149. type=result_type)
  150. result.data = data
  151. if label is not None:
  152. assert isinstance(label, (int, Label)), f"Wrong label type: {type(label)}"
  153. if isinstance(label, Label):
  154. label = label.id
  155. result.label_id = label
  156. return result
  157. def remove_results(self, origin='pipeline') -> T.List[Result]:
  158. """
  159. Remove assigned results, but return them.
  160. :return: list of result objects
  161. """
  162. results = Result.query.filter(
  163. Result.file_id == self.id,
  164. Result.origin == origin)
  165. _results = results.all()
  166. results.delete()
  167. return _results