preset.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import os
  2. import json
  3. from typing import Tuple, List, Dict
  4. from pathlib import Path
  5. from modules.images import sanitize_filename_part
  6. PresetDict = Dict[str, Dict[str, any]]
  7. class Preset:
  8. base_dir: Path
  9. default_filename: str
  10. default_values: PresetDict
  11. components: List[object]
  12. def __init__(
  13. self,
  14. base_dir: os.PathLike,
  15. default_filename='default.json'
  16. ) -> None:
  17. self.base_dir = Path(base_dir)
  18. self.default_filename = default_filename
  19. self.default_values = self.load(default_filename)[1]
  20. self.components = []
  21. def component(self, component_class: object, **kwargs) -> object:
  22. # find all the top components from the Gradio context and create a path
  23. from gradio.context import Context
  24. parent = Context.block
  25. paths = [kwargs['label']]
  26. while parent is not None:
  27. if hasattr(parent, 'label'):
  28. paths.insert(0, parent.label)
  29. parent = parent.parent
  30. path = '/'.join(paths)
  31. component = component_class(**{
  32. **kwargs,
  33. **self.default_values.get(path, {})
  34. })
  35. setattr(component, 'path', path)
  36. self.components.append(component)
  37. return component
  38. def load(self, filename: str) -> Tuple[str, PresetDict]:
  39. if not filename.endswith('.json'):
  40. filename += '.json'
  41. path = self.base_dir.joinpath(sanitize_filename_part(filename))
  42. configs = {}
  43. if path.is_file():
  44. configs = json.loads(path.read_text())
  45. return path, configs
  46. def save(self, filename: str, *values) -> Tuple:
  47. path, configs = self.load(filename)
  48. for index, component in enumerate(self.components):
  49. config = configs.get(component.path, {})
  50. config['value'] = values[index]
  51. for attr in ['visible', 'min', 'max', 'step']:
  52. if hasattr(component, attr):
  53. config[attr] = config.get(attr, getattr(component, attr))
  54. configs[component.path] = config
  55. self.base_dir.mkdir(0o777, True, True)
  56. path.write_text(
  57. json.dumps(configs, indent=4)
  58. )
  59. return 'successfully saved the preset'
  60. def apply(self, filename: str) -> Tuple:
  61. values = self.load(filename)[1]
  62. outputs = []
  63. for component in self.components:
  64. config = values.get(component.path, {})
  65. if 'value' in config and hasattr(component, 'choices'):
  66. if config['value'] not in component.choices:
  67. config['value'] = None
  68. outputs.append(component.update(**config))
  69. return (*outputs, 'successfully loaded the preset')
  70. def list(self) -> List[str]:
  71. presets = [
  72. p.name
  73. for p in self.base_dir.glob('*.json')
  74. if p.is_file()
  75. ]
  76. if len(presets) < 1:
  77. presets.append(self.default_filename)
  78. return presets