Database.py 11 KB

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