Database.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import sqlite3
  2. from contextlib import closing
  3. from time import time
  4. from typing import Optional, Iterator
  5. from pycs.database.Collection import Collection
  6. from pycs.database.File import File
  7. from pycs.database.LabelProvider import LabelProvider
  8. from pycs.database.Model import Model
  9. from pycs.database.Project import Project
  10. from pycs.database.Result import Result
  11. from pycs.database.discovery.LabelProviderDiscovery import discover as discover_label_providers
  12. from pycs.database.discovery.ModelDiscovery import discover as discover_models
  13. class Database:
  14. """
  15. opens an sqlite database and allows to access several objects
  16. """
  17. def __init__(self, path: str = ':memory:', initialization=True, discovery=True):
  18. """
  19. opens or creates a given sqlite database and creates all required tables
  20. :param path: path to sqlite database
  21. """
  22. # save properties
  23. self.path = path
  24. # initialize database connection
  25. self.con = sqlite3.connect(path)
  26. self.con.execute("PRAGMA foreign_keys = ON")
  27. if initialization:
  28. # create tables
  29. with self:
  30. with closing(self.con.cursor()) as cursor:
  31. cursor.execute('''
  32. CREATE TABLE IF NOT EXISTS models (
  33. id INTEGER PRIMARY KEY,
  34. name TEXT NOT NULL,
  35. description TEXT,
  36. root_folder TEXT NOT NULL UNIQUE,
  37. supports TEXT NOT NULL
  38. )
  39. ''')
  40. cursor.execute('''
  41. CREATE TABLE IF NOT EXISTS label_providers (
  42. id INTEGER PRIMARY KEY,
  43. name TEXT NOT NULL,
  44. description TEXT,
  45. root_folder TEXT NOT NULL,
  46. configuration_file TEXT NOT NULL,
  47. UNIQUE(root_folder, configuration_file)
  48. )
  49. ''')
  50. cursor.execute('''
  51. CREATE TABLE IF NOT EXISTS projects (
  52. id INTEGER PRIMARY KEY,
  53. name TEXT NOT NULL,
  54. description TEXT,
  55. created INTEGER NOT NULL,
  56. model INTEGER,
  57. label_provider INTEGER,
  58. root_folder TEXT NOT NULL UNIQUE,
  59. external_data BOOL NOT NULL,
  60. data_folder TEXT NOT NULL,
  61. FOREIGN KEY (model) REFERENCES models(id)
  62. ON UPDATE CASCADE ON DELETE SET NULL,
  63. FOREIGN KEY (label_provider) REFERENCES label_providers(id)
  64. ON UPDATE CASCADE ON DELETE SET NULL
  65. )
  66. ''')
  67. cursor.execute('''
  68. CREATE TABLE IF NOT EXISTS labels (
  69. id INTEGER PRIMARY KEY,
  70. project INTEGER NOT NULL,
  71. parent INTEGER,
  72. created INTEGER NOT NULL,
  73. reference TEXT,
  74. name TEXT NOT NULL,
  75. hierarchy_level TEXT,
  76. FOREIGN KEY (project) REFERENCES projects(id)
  77. ON UPDATE CASCADE ON DELETE CASCADE,
  78. FOREIGN KEY (parent) REFERENCES labels(id)
  79. ON UPDATE CASCADE ON DELETE SET NULL,
  80. UNIQUE(project, reference)
  81. )
  82. ''')
  83. cursor.execute('''
  84. CREATE TABLE IF NOT EXISTS collections (
  85. id INTEGER PRIMARY KEY,
  86. project INTEGER NOT NULL,
  87. reference TEXT NOT NULL,
  88. name TEXT NOT NULL,
  89. description TEXT,
  90. position INTEGER NOT NULL,
  91. autoselect INTEGER NOT NULL,
  92. FOREIGN KEY (project) REFERENCES projects(id)
  93. ON UPDATE CASCADE ON DELETE CASCADE,
  94. UNIQUE(project, reference)
  95. )
  96. ''')
  97. cursor.execute('''
  98. CREATE TABLE IF NOT EXISTS files (
  99. id INTEGER PRIMARY KEY,
  100. uuid TEXT NOT NULL,
  101. project INTEGER NOT NULL,
  102. collection INTEGER,
  103. type TEXT NOT NULL,
  104. name TEXT NOT NULL,
  105. extension TEXT NOT NULL,
  106. size INTEGER NOT NULL,
  107. created INTEGER NOT NULL,
  108. path TEXT NOT NULL,
  109. frames INTEGER,
  110. fps FLOAT,
  111. FOREIGN KEY (project) REFERENCES projects(id)
  112. ON UPDATE CASCADE ON DELETE CASCADE,
  113. FOREIGN KEY (collection) REFERENCES collections(id)
  114. ON UPDATE CASCADE ON DELETE SET NULL,
  115. UNIQUE(project, path)
  116. )
  117. ''')
  118. cursor.execute('''
  119. CREATE TABLE IF NOT EXISTS results (
  120. id INTEGER PRIMARY KEY,
  121. file INTEGER NOT NULL,
  122. origin TEXT NOT NULL,
  123. type TEXT NOT NULL,
  124. label INTEGER,
  125. data TEXT,
  126. FOREIGN KEY (file) REFERENCES files(id)
  127. ON UPDATE CASCADE ON DELETE CASCADE
  128. )
  129. ''')
  130. if discovery:
  131. # run discovery modules
  132. with self:
  133. discover_models(self.con)
  134. discover_label_providers(self.con)
  135. def close(self):
  136. """
  137. close database file
  138. """
  139. self.con.close()
  140. def copy(self):
  141. """
  142. Create a copy of this database object. This can be used to access the database
  143. from another thread. Table initialization and model and label provider discovery is
  144. disabled to speedup this function.
  145. :return: Database
  146. """
  147. return Database(self.path, initialization=False, discovery=False)
  148. def commit(self):
  149. """
  150. commit changes
  151. """
  152. self.con.commit()
  153. def __enter__(self):
  154. self.con.__enter__()
  155. return self
  156. def __exit__(self, exc_type, exc_val, exc_tb):
  157. self.con.__exit__(exc_type, exc_val, exc_tb)
  158. def models(self) -> Iterator[Model]:
  159. """
  160. get a list of all available models
  161. :return: iterator of models
  162. """
  163. with closing(self.con.cursor()) as cursor:
  164. cursor.execute('SELECT * FROM models')
  165. for row in cursor:
  166. yield Model(self, row)
  167. def model(self, identifier: int) -> Optional[Model]:
  168. """
  169. get a model using its unique identifier
  170. :param identifier: unique identifier
  171. :return: model
  172. """
  173. with closing(self.con.cursor()) as cursor:
  174. cursor.execute('SELECT * FROM models WHERE id = ?', [identifier])
  175. row = cursor.fetchone()
  176. if row is not None:
  177. return Model(self, row)
  178. return None
  179. def label_providers(self) -> Iterator[LabelProvider]:
  180. """
  181. get a list of all available label providers
  182. :return: iterator over label providers
  183. """
  184. with closing(self.con.cursor()) as cursor:
  185. cursor.execute('SELECT * FROM label_providers')
  186. for row in cursor:
  187. yield LabelProvider(self, row)
  188. def label_provider(self, identifier: int) -> Optional[LabelProvider]:
  189. """
  190. get a label provider using its unique identifier
  191. :param identifier: unique identifier
  192. :return: label provider
  193. """
  194. with closing(self.con.cursor()) as cursor:
  195. cursor.execute('SELECT * FROM label_providers WHERE id = ?', [identifier])
  196. row = cursor.fetchone()
  197. if row is not None:
  198. return LabelProvider(self, row)
  199. return None
  200. def projects(self) -> Iterator[Project]:
  201. """
  202. get a list of all available projects
  203. :return: iterator over projects
  204. """
  205. with closing(self.con.cursor()) as cursor:
  206. cursor.execute('SELECT * FROM projects')
  207. for row in cursor:
  208. yield Project(self, row)
  209. def project(self, identifier: int) -> Optional[Project]:
  210. """
  211. get a project using its unique identifier
  212. :param identifier: unique identifier
  213. :return: project
  214. """
  215. with closing(self.con.cursor()) as cursor:
  216. cursor.execute('SELECT * FROM projects WHERE id = ?', [identifier])
  217. row = cursor.fetchone()
  218. if row is not None:
  219. return Project(self, row)
  220. return None
  221. def create_project(self,
  222. name: str,
  223. description: str,
  224. model: Model,
  225. label_provider: Optional[LabelProvider],
  226. root_folder: str,
  227. external_data: bool,
  228. data_folder: str):
  229. """
  230. insert a project into the database
  231. :param name: project name
  232. :param description: project description
  233. :param model: used model
  234. :param label_provider: used label provider (optional)
  235. :param root_folder: path to project folder
  236. :param external_data: whether an external data directory is used
  237. :param data_folder: path to data folder
  238. :return: created project
  239. """
  240. # prepare some values
  241. created = int(time())
  242. label_provider_id = label_provider.identifier if label_provider is not None else None
  243. # insert statement
  244. with closing(self.con.cursor()) as cursor:
  245. cursor.execute('''
  246. INSERT INTO projects (
  247. name, description, created, model, label_provider, root_folder, external_data,
  248. data_folder
  249. )
  250. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  251. ''', (name, description, created, model.identifier, label_provider_id, root_folder,
  252. external_data, data_folder))
  253. return self.project(cursor.lastrowid)
  254. def collection(self, identifier: int) -> Optional[Collection]:
  255. """
  256. get a collection using its unique identifier
  257. :param identifier: unique identifier
  258. :return: collection
  259. """
  260. with closing(self.con.cursor()) as cursor:
  261. cursor.execute('SELECT * FROM collections WHERE id = ?', [identifier])
  262. row = cursor.fetchone()
  263. if row is not None:
  264. return Collection(self, row)
  265. return None
  266. def file(self, identifier) -> Optional[File]:
  267. """
  268. get a file using its unique identifier
  269. :param identifier: unique identifier
  270. :return: file
  271. """
  272. with closing(self.con.cursor()) as cursor:
  273. cursor.execute('SELECT * FROM files WHERE id = ?', [identifier])
  274. row = cursor.fetchone()
  275. if row is not None:
  276. return File(self, row)
  277. return None
  278. def result(self, identifier) -> Optional[Result]:
  279. """
  280. get a result using its unique identifier
  281. :param identifier: unique identifier
  282. :return: result
  283. """
  284. with closing(self.con.cursor()) as cursor:
  285. cursor.execute('SELECT * FROM results WHERE id = ?', [identifier])
  286. row = cursor.fetchone()
  287. if row is not None:
  288. return Result(self, row)
  289. return None