File size: 6,159 Bytes
cf2be89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import os
import random
import sys
from typing import Sequence, Mapping, Any, Union, Tuple
import torch
from PIL import Image
import spaces
import gradio as gr
from huggingface_hub import hf_hub_download
from comfy import model_management

# Download required models from huggingface
hf_token = os.environ.get("HF_TOKEN")
hf_hub_download(
    repo_id="Comfy-Org/stable-diffusion-v1-5-archive",
    filename="v1-5-pruned-emaonly-fp16.safetensors",
    local_dir="models/checkpoints",
    token=hf_token,
)


def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
    try:
        return obj[index]
    except KeyError:
        return obj["result"][index]


def find_path(name: str, path: str = None) -> str:
    """
    Recursively looks at parent folders starting from the given path until it finds the given name.
    Returns the path as a Path object if found, or None otherwise.
    """
    # If no path is given, use the current working directory
    if path is None:
        path = os.getcwd()

    # Check if the current directory contains the name
    if name in os.listdir(path):
        path_name = os.path.join(path, name)
        print(f"{name} found: {path_name}")
        return path_name

    # Get the parent directory
    parent_directory = os.path.dirname(path)

    # If the parent directory is the same as the current directory, we've reached the root and stop the search
    if parent_directory == path:
        return None

    # Recursively call the function with the parent directory
    return find_path(name, parent_directory)


def add_comfyui_directory_to_sys_path() -> None:
    """
    Add 'ComfyUI' to the sys.path
    """
    comfyui_path = find_path("ComfyUI")
    if comfyui_path is not None and os.path.isdir(comfyui_path):
        sys.path.append(comfyui_path)
        print(f"'{comfyui_path}' added to sys.path")


def add_extra_model_paths() -> None:
    try:
        from main import load_extra_path_config
    except ImportError:
        print(
            "Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
        )
        from utils.extra_config import load_extra_path_config

    extra_model_paths = find_path("extra_model_paths.yaml")

    if extra_model_paths is not None:
        load_extra_path_config(extra_model_paths)
    else:
        print("Could not find the extra_model_paths config file.")


add_comfyui_directory_to_sys_path()
add_extra_model_paths()


def import_custom_nodes() -> None:
    import asyncio
    import execution
    from nodes import init_extra_nodes
    import server

    # Creating a new event loop and setting it as the default loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    # Creating an instance of PromptServer with the loop
    server_instance = server.PromptServer(loop)
    execution.PromptQueue(server_instance)

    # Initializing custom nodes
    init_extra_nodes()


from nodes import NODE_CLASS_MAPPINGS

import_custom_nodes()


checkpointloadersimple = NODE_CLASS_MAPPINGS["CheckpointLoaderSimple"]()
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
vaeencode = NODE_CLASS_MAPPINGS["VAEEncode"]()
ksampler = NODE_CLASS_MAPPINGS["KSampler"]()
vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()
framercomfysaveimagenode = NODE_CLASS_MAPPINGS["FramerComfySaveImageNode"]()


checkpointloadersimple_14 = checkpointloadersimple.load_checkpoint(
    ckpt_name="v1-5-pruned-emaonly-fp16.safetensors"
)


model_loaders = [checkpointloadersimple_14]

model_management.load_models_gpu(
    [
        loader[0].patcher if hasattr(loader[0], "patcher") else loader[0]
        for loader in model_loaders
    ]
)


@spaces.GPU
def run_workflow(prompt, negative_prompt, image_input) -> Tuple[Any, ...]:
    with torch.inference_mode():
        cliptextencode_6 = cliptextencode.encode(
            text=prompt, clip=get_value_at_index(checkpointloadersimple_14, 1)
        )

        cliptextencode_7 = cliptextencode.encode(
            text=negative_prompt, clip=get_value_at_index(checkpointloadersimple_14, 1)
        )

        vaeencode_12 = vaeencode.encode(
            pixels=image_input, vae=get_value_at_index(checkpointloadersimple_14, 2)
        )

        ksampler_3 = ksampler.sample(
            seed=random.randint(1, 2**64),
            steps=20,
            cfg=8,
            sampler_name="dpmpp_2m",
            scheduler="normal",
            denoise=0.8700000000000001,
            model=get_value_at_index(checkpointloadersimple_14, 0),
            positive=get_value_at_index(cliptextencode_6, 0),
            negative=get_value_at_index(cliptextencode_7, 0),
            latent_image=get_value_at_index(vaeencode_12, 0),
        )

        vaedecode_8 = vaedecode.decode(
            samples=get_value_at_index(ksampler_3, 0),
            vae=get_value_at_index(checkpointloadersimple_14, 2),
        )

        framercomfysaveimagenode_18 = framercomfysaveimagenode.save_images(
            filename_prefix="ComfyUI",
            output_name="result_image",
            images=get_value_at_index(vaedecode_8, 0),
        )

    framercomfysaveimagenode_18_path = (
        "output/" + framercomfysaveimagenode_18["ui"]["images"][0]["filename"]
    )
    return framercomfysaveimagenode_18_path


# Create Gradio interface
image18_output = gr.Image(label="Generated Image18")

with gr.Blocks() as app:
    with gr.Row():
        with gr.Column():
            prompt_input = gr.Textbox(
                label="Prompt",
                value="None" if "None" else None,
                placeholder=f"Enter prompt here...",
            )
            negative_prompt_input = gr.Textbox(
                label="Negative_Prompt",
                value="None" if "None" else None,
                placeholder=f"Enter negative_prompt here...",
            )
            generate_btn = gr.Button("Generate")
        with gr.Column():
            image18_output.render()
    generate_btn.click(
        fn=run_workflow,
        inputs=[prompt_input, negative_prompt_input],
        outputs=[image18_output],
    )

if __name__ == "__main__":
    app.launch(share=True)