Database.py 9.9 KB

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