File.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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.Integer, 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",
  37. backref="file",
  38. lazy="dynamic",
  39. passive_deletes=True,
  40. )
  41. serialize_only = NamedBaseModel.serialize_only + (
  42. "uuid",
  43. "extension",
  44. "type",
  45. "size",
  46. "created",
  47. "path",
  48. "frames",
  49. "has_annotations",
  50. "fps",
  51. "project_id",
  52. "collection_id",
  53. )
  54. @property
  55. def filename(self):
  56. """ filename consisting of a name and an extension """
  57. return f"{self.name}{self.extension}"
  58. @property
  59. def has_annotations(self):
  60. """ check if there are any referenced results """
  61. return self.results.count() != 0
  62. @property
  63. def absolute_path(self) -> str:
  64. """ returns an absolute of the file """
  65. path = Path(self.path)
  66. if path.is_absolute():
  67. return str(path)
  68. return str(Path.cwd() / path)
  69. # pylint: disable=arguments-differ
  70. def delete(self, commit: bool = True):
  71. """
  72. after the object is deleted, the according physical file
  73. is also delete if commit was True
  74. """
  75. # pylint: disable=unexpected-keyword-arg
  76. dump = super().delete(commit=commit)
  77. if commit:
  78. os.remove(self.path)
  79. # TODO: remove temp files
  80. warnings.warn("Temporary files may still exist!")
  81. return dump
  82. @commit_on_return
  83. def set_collection(self, collection_id: T.Optional[int]):
  84. """
  85. set this file's collection
  86. :param collection_id: new collection id
  87. :return:
  88. """
  89. self.collection_id = collection_id
  90. @commit_on_return
  91. def set_collection_by_reference(self, collection_reference: T.Optional[str]):
  92. """
  93. set this file's collection
  94. :param collection_reference: collection reference
  95. :return:
  96. """
  97. if self.collection_reference is None:
  98. self.set_collection(None)
  99. collection = Collection.query.filter_by(reference=collection_reference).one()
  100. self.collection_id = collection.id
  101. def _get_another_file(self, *query) -> T.Optional[File]:
  102. """
  103. get the first file matching the query ordered by descending id
  104. :return: another file or None
  105. """
  106. return File.query.filter(File.project_id == self.project_id, *query)
  107. def next(self) -> T.Optional[File]:
  108. """
  109. get the successor of this file
  110. :return: another file or None
  111. """
  112. res = self._get_another_file(File.path > self.path)\
  113. .order_by(File.path)
  114. return res.first()
  115. def previous(self) -> T.Optional[File]:
  116. """
  117. get the predecessor of this file
  118. :return: another file or None
  119. """
  120. # pylint: disable=no-member
  121. res = self._get_another_file(File.path < self.path)\
  122. .order_by(File.path.desc())
  123. return res.first()
  124. def next_in_collection(self) -> T.Optional[File]:
  125. """
  126. get the predecessor of this file
  127. :return: another file or None
  128. """
  129. return self._get_another_file(
  130. File.path > self.path, File.collection_id == self.collection_id)\
  131. .order_by(File.path).first()
  132. def previous_in_collection(self) -> T.Optional[File]:
  133. """
  134. get the predecessor of this file
  135. :return: another file or None
  136. """
  137. # pylint: disable=no-member
  138. return self._get_another_file(
  139. File.path < self.path, File.collection_id == self.collection_id)\
  140. .order_by(File.path.desc()).first()
  141. def result(self, identifier: int) -> T.Optional[Result]:
  142. """
  143. get one of the file's results
  144. :return: result object or None
  145. """
  146. return self.results.get(identifier)
  147. @commit_on_return
  148. def create_result(self,
  149. origin: str,
  150. result_type: str,
  151. label: T.Optional[T.Union[Label, int, str]] = None,
  152. data: T.Optional[dict] = None) -> Result:
  153. """
  154. Creates a result and returns the created object
  155. :return: result object
  156. """
  157. result = Result.new(commit=False,
  158. file_id=self.id,
  159. origin=origin,
  160. type=result_type)
  161. result.data = data
  162. if label is not None:
  163. assert isinstance(label, (int, Label, str)), \
  164. f"Label \"{label}\" has invalid type: {type(label)}"
  165. if isinstance(label, str):
  166. label = Label.query.filter(
  167. Label.project_id == self.project_id,
  168. Label.reference == label).one_or_none()
  169. if isinstance(label, Label):
  170. label = label.id
  171. result.label_id = label
  172. return result
  173. def remove_results(self, origin='pipeline') -> T.List[Result]:
  174. """
  175. Remove assigned results, but return them.
  176. :return: list of result objects
  177. """
  178. results = Result.query.filter(
  179. Result.file_id == self.id,
  180. Result.origin == origin)
  181. _results = [r.serialize() for r in results.all()]
  182. results.delete()
  183. return _results