6
0

Database.py 12 KB

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