Skip to content

parse_settings

Abstract away and store project settings for ease of use.

ComfyCommittedSettings

Contains a committed pair of Local settings and chosen config.

This object is for holding state but may not be changed once set. Use of this can be omitted by interfacing with

settings = ComfyLocalSettings("project_name")
settings.commit("profile name")
# ... later, maybe in another thread
settings, profile = ComfyLocalSettings.pull_committed_settings()
Source code in client/ayon_comfyui/settings_util/parse_settings.py
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
class ComfyCommittedSettings:
    """Contains a committed pair of Local settings and chosen config.

    This object is for holding state but may not be changed once set.
    Use of this can be omitted by interfacing with
    ```
    settings = ComfyLocalSettings("project_name")
    settings.commit("profile name")
    # ... later, maybe in another thread
    settings, profile = ComfyLocalSettings.pull_committed_settings()
    ```
    """

    _settings: ClassVar[ComfyLocalSettings | ComfyRemoteSettings] = None
    _config: ClassVar[
        ComfyLocalSettings.ComfyLocalProfile
        | ComfyRemoteSettings.ComfyRemoteProfile
    ] = None

    @classmethod
    def commit(
        cls,
        settings: ComfyLocalSettings | ComfyRemoteSettings,
        config: ComfyLocalSettings.ComfyLocalProfile
        | ComfyRemoteSettings.ComfyRemoteProfile,
    ) -> None:
        """Commit settings and configuration to memory."""
        if cls._settings is not None or cls._config is not None:
            # Maybe raise an error but I am not a fan...
            return
        if isinstance(
            settings, (ComfyLocalSettings, ComfyRemoteSettings)
        ) and isinstance(
            config,
            (
                ComfyLocalSettings.ComfyLocalProfile,
                ComfyRemoteSettings.ComfyRemoteProfile,
            ),
        ):
            cls._settings = settings
            cls._config = config

    @classmethod
    def pull(
        cls,
    ) -> (
        tuple[ComfyLocalSettings, ComfyLocalSettings.ComfyLocalProfile]
        | tuple[ComfyRemoteSettings, ComfyRemoteSettings.ComfyRemoteProfile]
    ):
        """Returns class level stored settings and configuration.

        ```
        settings, profile = LocalComfyCommittedSettings.pull()
        ```
        """
        if cls._settings is not None and cls._config is not None:
            return (cls._settings, cls._config)
        return None

commit(settings, config) classmethod

Commit settings and configuration to memory.

Source code in client/ayon_comfyui/settings_util/parse_settings.py
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
@classmethod
def commit(
    cls,
    settings: ComfyLocalSettings | ComfyRemoteSettings,
    config: ComfyLocalSettings.ComfyLocalProfile
    | ComfyRemoteSettings.ComfyRemoteProfile,
) -> None:
    """Commit settings and configuration to memory."""
    if cls._settings is not None or cls._config is not None:
        # Maybe raise an error but I am not a fan...
        return
    if isinstance(
        settings, (ComfyLocalSettings, ComfyRemoteSettings)
    ) and isinstance(
        config,
        (
            ComfyLocalSettings.ComfyLocalProfile,
            ComfyRemoteSettings.ComfyRemoteProfile,
        ),
    ):
        cls._settings = settings
        cls._config = config

pull() classmethod

Returns class level stored settings and configuration.

settings, profile = LocalComfyCommittedSettings.pull()
Source code in client/ayon_comfyui/settings_util/parse_settings.py
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
@classmethod
def pull(
    cls,
) -> (
    tuple[ComfyLocalSettings, ComfyLocalSettings.ComfyLocalProfile]
    | tuple[ComfyRemoteSettings, ComfyRemoteSettings.ComfyRemoteProfile]
):
    """Returns class level stored settings and configuration.

    ```
    settings, profile = LocalComfyCommittedSettings.pull()
    ```
    """
    if cls._settings is not None and cls._config is not None:
        return (cls._settings, cls._config)
    return None

ComfyLocalSettings

Contains local settings.

Source code in client/ayon_comfyui/settings_util/parse_settings.py
 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
class ComfyLocalSettings:
    """Contains local settings."""

    class ComfyLocalProfile:
        """Parses a single config to then pass on.

        Automatically takes platform into account.
        """

        def __init__(self, profile_dict: dict[str, str]) -> None:
            """Initialize config helper class."""
            self._name = profile_dict.get("name")
            os_map = {"win32": "win", "linux": "lin", "darwin": "osx"}
            self._os = os_map.get(sys.platform, "lin")

            self._profile_dict: dict[str, str] = profile_dict

            custom_dir_list: list[dict] = (
                self._get_launch_profile_bare_setting("extra_dirs")
            )

            self._custom_directories = [
                ComfyUICustomDirectories(dir_dict, self._os)
                for dir_dict in custom_dir_list
            ]

            # filter for enabled entries
            self._custom_directories = [
                dir_ for dir_ in self._custom_directories if dir_.is_enabled
            ]

            if not self.omit_packaged_plugin:
                self._custom_directories.append(
                    ComfyUICustomDirectories.create_default_customnodes_profile()
                )

        def _get_platform_profile_setting(
            self, base_key: str
        ) -> str | dict | None:
            """Used in properties to fetch the right value for current OS.

            Returns:
            Value expected from key
            """
            return self._profile_dict.get(f"{base_key}_{self._os}")

        def _get_platform_profile_setting_path(
            self, base_key: str
        ) -> str | None:
            """Used in properties to fetch the right value for current OS.

            Returns:
            Value expected from key, as a normalized path.
            """
            value = self._get_platform_profile_setting(base_key)
            if not isinstance(value, str):
                return None
            if self._os == "win":
                value = value.replace("\\", "/")
            return value

        def _get_launch_profile_setting(
            self, base_key: str
        ) -> str | dict | None:
            """Used in properties to fetch the right value for current OS.

            Returns:
            Value expected from key
            """
            launch_profile: dict[str, str] = self._profile_dict.get(
                "launch_profile"
            )
            return launch_profile.get(f"{base_key}_{self._os}")

        def _get_launch_profile_bare_setting(
            self, base_key: str
        ) -> str | dict | list | None:
            """Used in properties to fetch the right value.

            Returns:
            Value expected from key
            """
            launch_profile: dict[str, str] = self._profile_dict.get(
                "launch_profile"
            )
            return launch_profile.get(base_key)

        def _get_launch_profile_setting_path(
            self, base_key: str
        ) -> str | None:
            """Used in properties to fetch the right value for current OS.

            Returns:
            Value expected from key, as a normalized path.
            """
            value = self._get_launch_profile_setting(base_key)
            if not isinstance(value, (str, list)):
                return None
            if self._os == "win":
                if isinstance(value, list):
                    value = [val.replace("\\", "/") for val in value]
                elif isinstance(value, str):
                    value = value.replace("\\", "/")
            return value

        def _get_launch_profile_args(self) -> list[str]:
            """Concatenate launch args.

            Takes care of windows standalone build flag based on settings.

            Returns:
                Launch arguments as a list.
            """
            args = []
            for arg in self._get_launch_profile_setting("launch_args"):
                args.extend([arg.get("key"), arg.get("value")])
            launch_args = [arg for arg in args if arg]
            if self._os in {"lin", "osx"} or not self.is_windows_portable:
                launch_args = [
                    arg
                    for arg in launch_args
                    if arg != "--windows-standalone-build"
                ]
            elif self._os == "win" and self.is_windows_portable:
                launch_args = [
                    arg
                    for arg in launch_args
                    if arg != "--windows-standalone-build"
                ]
                # make sure that --windows-standalone-build is always first
                launch_args.insert(0, "--windows-standalone-build")
            return launch_args

        @property
        def name(self) -> str:
            """Returns configuration name."""
            return self._name

        @property
        @template_wrap
        def base_folder(self) -> str:
            """Gets base folder where ComfyUI is stored."""
            return self._get_platform_profile_setting_path("comfy_base_folder")

        @property
        def comfy_port(self) -> str:
            """Gets port where comfyui is supposed to run."""
            return self._profile_dict.get("comfy_launch_port")

        @property
        def comfy_local_url(self) -> str:
            """Gets complete HTTP address ComfyUI runs on."""
            return f"http://127.0.0.1:{self.comfy_port}"

        @property
        def using_custom_python(self) -> bool:
            """Return whether custom python path is used."""
            return self._profile_dict.get("python_path_use_custom")

        @property
        def using_managed_venv(self) -> bool:
            """Return whether to use managed venv with python."""
            return self._profile_dict.get("python_use_managed_venv")

        @property
        @template_wrap
        def custom_python_path(self) -> str | None:
            """Return path to python if a custom."""
            if self.using_custom_python:
                return self._get_platform_profile_setting_path("python_path")
            return None

        @property
        def get_customfolders_yaml(self) -> str:
            """Return indented YAML component of custom folders."""
            return ComfyUICustomDirectories.generate_yaml(
                self._custom_directories
            )

        @property
        @template_wrap
        def launch_args(self) -> list[str]:
            """Return launch arguments for profile.

            Filters out windows portable flag for inappropriate platforms
            """
            return self._get_launch_profile_args()

        @property
        def is_windows_portable(self) -> bool:
            """Return if profile for windows is a windows portable build."""
            launch_kwargs: dict[str, Any] = self._profile_dict.get(
                "launch_profile"
            )
            return launch_kwargs.get("comfy_is_windows_portable")

        @property
        def omit_packaged_plugin(self) -> bool:
            """Return if profile should omit the packaged Comfyui plugin.

            This means that a valid ayon comfyui plugin location
            has to exist in the launch args.
            """
            launch_kwargs: dict[str, Any] = self._profile_dict.get(
                "launch_profile"
            )
            return launch_kwargs.get("dev_omit_packaged_ayon_comfyui_plugin")

        def _validate_profile_for_os(
            self, os_name: str
        ) -> dict[str, list[str]]:
            """Validate this profile and report back.

            Specify os_name to spoof perceived OS for setting retrieval.

            Returns:
                A dict with errors and logs:
                {
                    "errors" : [...],
                    "logs"   : [...],
                }
            """
            # conform
            if os_name in {"win", "win32"}:
                os_name = "win"
            elif os_name in {"lin", "linux"}:
                os_name = "lin"
            elif os_name in {"osx", "darwin"}:
                os_name = "osx"

            old_os = self._os
            self._os = os_name

            profiles_os = [
                ComfyUICustomDirectories(
                    custom_dir._directory_settings,  # noqa : SLF001
                    os_name,
                )
                for custom_dir in self._custom_directories
            ]
            profiles_dict = ComfyUICustomDirectories.collect_as_dict(
                profiles_os
            )

            # Run tests
            errors = []
            logs = []
            if not self.name:
                errors.append(
                    f"{self.name} | {os_name}: ill formed name for profile"
                    " (must have contents)"
                )
            if not self.base_folder:
                errors.append(
                    f"{self.name} | {os_name}: is missing base folder"
                )
            if not self.custom_python_path and self.using_custom_python:
                errors.append(
                    f"{self.name} | {os_name}: is missing custom "
                    "python path with 'use custom python' specified"
                )
            if (
                profiles_dict.get("custom_nodes") is None
                and self.omit_packaged_plugin
            ):
                logs.append(
                    f"{self.name} | {os_name}: is missing extra node"
                    " directory in dev mode. Ayon plugin may be missing."
                )
            if not self.launch_args:
                logs.append(f"{self.name} | {os_name}: no launch arguments.")

            # restore old os
            self._os = old_os

            return {"errors": errors, "logs": logs}

        def validate_profile(self) -> dict[str, list[str]]:
            """Validate this profile and report back.

            Returns:
                A dict with errors and (benign) logs:
                {
                    "errors" : [...],
                    "logs"   : [...],
                }
            """
            return self._validate_profile_for_os(self._os)

        @property
        def is_valid(self) -> bool:
            """Returns whether profile is bad for current OS."""
            return not bool(self.validate_profile().get("errors"))

        @staticmethod
        def _map_internal_os_name(_os: str) -> str:
            os_name_map = {"win": "Windows", "lin": "Linux", "osx": "MacOSX"}
            return os_name_map.get(_os)

        @property
        def current_os(self) -> str:
            """Return profile OS.

            Possible results:
            Windows, Linux, MacOSX
            """
            return self._map_internal_os_name(self._os)

    def __init__(self, project_name: str | None = None):
        """Initialize settings for local launch."""
        self._settings = {}
        self._profiles: dict[str, ComfyLocalSettings.ComfyLocalProfile] = {}
        if project_name and project_name is not None:
            self._settings = (
                get_project_settings(project_name)
                .get("comfyui")
                .get("local_settings")
            )
        else:
            self._settings = (
                get_studio_settings().get("comfyui").get("local_settings")
            )

        self._port_server: int = self._settings["server_pulse_port"]
        self._port_web: int = self._settings["frontend_port"]
        self._port_http_static: int = self._settings["http_server_port"]
        self._parse_settings()

    def _parse_settings(self) -> None:
        """Parse out settings into objects."""
        for setting in self._settings.get("local_setting_list"):
            profile = ComfyLocalSettings.ComfyLocalProfile(setting)
            self._profiles[profile.name] = profile

    @property
    def port_webui(self) -> int:
        """Return webui connection port."""
        return self._port_web

    @property
    def port_backend(self) -> int:
        """Return backend connection port."""
        return self._port_server

    @property
    def port_static_frontend(self) -> int:
        """Return static frontend port (hosts <iframe> with ComfyUI)."""
        return self._port_http_static

    @property
    def address_frontend(self) -> str:
        """Return static frontend adress."""
        return f"http://localhost:{self.port_static_frontend}"

    @property
    def profiles(self) -> list[str]:
        """Return a list of profile names."""
        return list(self._profiles.keys())

    def __getitem__(self, key: str) -> ComfyLocalProfile | None:
        """Return a profile associated with a name."""
        return self._profiles.get(key)

    def get(
        self, key: str, default: DEFAULT_T | None = None
    ) -> ComfyLocalProfile | DEFAULT_T | None:
        """Return a profile associated with a name, else default.

        Default is None by default.
        """
        return self._profiles.get(key, default)

    def commit(
        self,
        config: ComfyLocalSettings.ComfyLocalProfile | str,
    ) -> None:
        """Commit this & config to ComfyCommittedSettings.

        ```
        settings = ComfyLocalSettings("project_name")
        settings.commit("profile name")
        # ... later, maybe in another thread
        settings, profile = ComfyLocalSettings.pull_committed_settings()
        ```
        """
        if isinstance(config, str):
            config = self.get(config)

        ComfyCommittedSettings.commit(self, config)

    @classmethod
    def pull_committed_settings(
        cls,
    ) -> tuple[ComfyLocalSettings, ComfyLocalSettings.ComfyLocalProfile]:
        """Return committed settings.

        ```
        settings = ComfyLocalSettings("project_name")
        settings.commit("profile name")
        # ... later, maybe in another thread
        settings, profile = ComfyLocalSettings.pull_committed_settings()
        ```
        """
        return ComfyCommittedSettings.pull()

address_frontend property

Return static frontend adress.

port_backend property

Return backend connection port.

port_static_frontend property

Return static frontend port (hosts