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