config.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env python3
  2. """Checks and sets default values for config.json before starting the container."""
  3. import json
  4. import re
  5. import os.path
  6. import sys
  7. DEFAULT_FILEPATH = '/data/config/auto/config.json'
  8. DEFAULT_OUTDIRS = {
  9. "outdir_samples": "",
  10. "outdir_txt2img_samples": "/output/txt2img",
  11. "outdir_img2img_samples": "/output/img2img",
  12. "outdir_extras_samples": "/output/extras",
  13. "outdir_grids": "",
  14. "outdir_txt2img_grids": "/output/txt2img-grids",
  15. "outdir_img2img_grids": "/output/img2img-grids",
  16. "outdir_save": "/output/saved",
  17. "outdir_init_images": "/output/init-images",
  18. }
  19. RE_VALID_OUTDIR = re.compile(r"(^/output(/\.?[\w\-\_]+)+/?$)|(^\s?$)")
  20. DEFAULT_OTHER = {
  21. "font": "DejaVuSans.ttf",
  22. }
  23. def dict_to_json_file(target_file: str, data: dict):
  24. """Write dictionary to specified json file"""
  25. with open(target_file, 'w') as f:
  26. json.dump(data, f)
  27. def json_file_to_dict(config_file: str) -> dict|None:
  28. """Load json file into a dictionary. Return None if file does not exist."""
  29. if os.path.isfile(config_file):
  30. with open(config_file, 'r') as f:
  31. return json.load(f)
  32. else:
  33. return None
  34. def replace_if_invalid(value: str, replacement: str, pattern: str|re.Pattern[str]) -> str:
  35. """Returns original value if valid, fallback value if invalid"""
  36. if re.match(pattern, value):
  37. return value
  38. else:
  39. return replacement
  40. def check_and_replace_config(config_file: str, target_file: str = None):
  41. """Checks given file for invalid values. Replaces those with fallback values (default: overwrites file)."""
  42. # Get current user config, or empty if file does not exists
  43. data = json_file_to_dict(config_file) or {}
  44. # Check and fix output directories
  45. for k, def_val in DEFAULT_OUTDIRS.items():
  46. if k not in data:
  47. data[k] = def_val
  48. else:
  49. data[k] = replace_if_invalid(value=data[k], replacement=def_val, pattern=RE_VALID_OUTDIR)
  50. # Check and fix other default settings
  51. for k, def_val in DEFAULT_OTHER.items():
  52. if k not in data:
  53. data[k] = def_val
  54. # Write results to file
  55. dict_to_json_file(target_file or config_file, data)
  56. if __name__ == '__main__':
  57. if len(sys.argv) > 1:
  58. check_and_replace_config(*sys.argv[1:])
  59. else:
  60. check_and_replace_config(DEFAULT_FILEPATH)