Database.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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:', discovery=True):
  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. if discovery:
  109. with self:
  110. discover_models(self.con)
  111. discover_label_providers(self.con)
  112. def close(self):
  113. self.con.close()
  114. def __enter__(self):
  115. self.con.__enter__()
  116. def __exit__(self, exc_type, exc_val, exc_tb):
  117. self.con.__exit__(exc_type, exc_val, exc_tb)
  118. def models(self) -> List[Model]:
  119. """
  120. get a list of all available models
  121. :return: list of all available models
  122. """
  123. with closing(self.con.cursor()) as cursor:
  124. cursor.execute('SELECT * FROM models')
  125. return list(map(
  126. lambda row: Model(self, row),
  127. cursor.fetchall()
  128. ))
  129. def model(self, identifier: int) -> Optional[Model]:
  130. """
  131. get a model using its unique identifier
  132. :param identifier: unique identifier
  133. :return: model
  134. """
  135. with closing(self.con.cursor()) as cursor:
  136. cursor.execute('SELECT * FROM models WHERE id = ?', [identifier])
  137. row = cursor.fetchone()
  138. if row is not None:
  139. return Model(self, row)
  140. return None
  141. def label_providers(self) -> List[LabelProvider]:
  142. """
  143. get a list of all available label providers
  144. :return: list of all available label providers
  145. """
  146. with closing(self.con.cursor()) as cursor:
  147. cursor.execute('SELECT * FROM label_providers')
  148. return list(map(
  149. lambda row: LabelProvider(self, row),
  150. cursor.fetchall()
  151. ))
  152. def label_provider(self, identifier: int) -> Optional[LabelProvider]:
  153. """
  154. get a label provider using its unique identifier
  155. :param identifier: unique identifier
  156. :return: label provider
  157. """
  158. with closing(self.con.cursor()) as cursor:
  159. cursor.execute('SELECT * FROM label_providers WHERE id = ?', [identifier])
  160. row = cursor.fetchone()
  161. if row is not None:
  162. return LabelProvider(self, row)
  163. return None
  164. def projects(self) -> List[Project]:
  165. """
  166. get a list of all available projects
  167. :return: list of all available projects
  168. """
  169. with closing(self.con.cursor()) as cursor:
  170. cursor.execute('SELECT * FROM projects')
  171. return list(map(
  172. lambda row: Project(self, row),
  173. cursor.fetchall()
  174. ))
  175. def project(self, identifier: int) -> Optional[Project]:
  176. """
  177. get a project using its unique identifier
  178. :param identifier: unique identifier
  179. :return: project
  180. """
  181. with closing(self.con.cursor()) as cursor:
  182. cursor.execute('SELECT * FROM projects WHERE id = ?', [identifier])
  183. row = cursor.fetchone()
  184. if row is not None:
  185. return Project(self, row)
  186. return None
  187. def create_project(self,
  188. name: str,
  189. description: str,
  190. model: Model,
  191. label_provider: Optional[LabelProvider],
  192. root_folder: str,
  193. external_data: bool,
  194. data_folder: str):
  195. """
  196. insert a project into the database
  197. :param name: project name
  198. :param description: project description
  199. :param model: used model
  200. :param label_provider: used label provider (optional)
  201. :param root_folder: path to project folder
  202. :param external_data: whether an external data directory is used
  203. :param data_folder: path to data folder
  204. :return: created project
  205. """
  206. # prepare some values
  207. created = int(time())
  208. label_provider_id = label_provider.identifier if label_provider is not None else None
  209. # insert statement
  210. with closing(self.con.cursor()) as cursor:
  211. cursor.execute('''
  212. INSERT INTO projects (
  213. name, description, created, model, label_provider, root_folder, external_data,
  214. data_folder
  215. )
  216. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  217. ''', (name, description, created, model.identifier, label_provider_id, root_folder,
  218. external_data, data_folder))
  219. return self.project(cursor.lastrowid)
  220. def file(self, identifier) -> Optional[File]:
  221. """
  222. get a file using its unique identifier
  223. :param identifier: unique identifier
  224. :return: file
  225. """
  226. with closing(self.con.cursor()) as cursor:
  227. cursor.execute('SELECT * FROM files WHERE id = ?', [identifier])
  228. row = cursor.fetchone()
  229. if row is not None:
  230. return File(self, row)
  231. return None
  232. def result(self, identifier) -> Optional[Result]:
  233. """
  234. get a result using its unique identifier
  235. :param identifier: unique identifier
  236. :return: result
  237. """
  238. with closing(self.con.cursor()) as cursor:
  239. cursor.execute('SELECT * FROM results WHERE id = ?', [identifier])
  240. row = cursor.fetchone()
  241. if row is not None:
  242. return Result(self, row)
  243. return None