LabelProviderDiscovery.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import re
  2. from contextlib import closing
  3. from glob import glob
  4. from json import load
  5. from os import path, listdir
  6. def __find_files():
  7. # list folders in labels/
  8. for folder in glob('labels/*'):
  9. # list files
  10. for filename in listdir(folder):
  11. file_path = path.join(folder, filename)
  12. # filter configuration files
  13. if not path.isfile(file_path):
  14. continue
  15. if not re.match(r'^configuration(\d+)?\.json$', filename):
  16. continue
  17. # yield element
  18. yield folder, filename, file_path
  19. def discover(database):
  20. """
  21. find label providers in the corresponding folder and add them to the database
  22. :param database:
  23. :return:
  24. """
  25. with closing(database.cursor()) as cursor:
  26. for folder, configuration_file, configuration_path in __find_files():
  27. # load configuration file
  28. with open(configuration_path, 'r') as file:
  29. label = load(file)
  30. # extract data
  31. name = label['name']
  32. description = label['description'] if 'description' in label else None
  33. # save to database
  34. cursor.execute('''
  35. INSERT INTO label_providers (name, description, root_folder, configuration_file)
  36. VALUES (?, ?, ?, ?)
  37. ON CONFLICT (root_folder, configuration_file)
  38. DO UPDATE SET name = ?, description = ?
  39. ''', (name, description, folder, configuration_file, name, description))