mohamedsobhi777 commited on
Commit
cf2be89
·
verified ·
1 Parent(s): 4b51f52

Uploaded app.py file

Browse files
Files changed (1) hide show
  1. app.py +203 -0
app.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import sys
4
+ from typing import Sequence, Mapping, Any, Union, Tuple
5
+ import torch
6
+ from PIL import Image
7
+ import spaces
8
+ import gradio as gr
9
+ from huggingface_hub import hf_hub_download
10
+ from comfy import model_management
11
+
12
+ # Download required models from huggingface
13
+ hf_token = os.environ.get("HF_TOKEN")
14
+ hf_hub_download(
15
+ repo_id="Comfy-Org/stable-diffusion-v1-5-archive",
16
+ filename="v1-5-pruned-emaonly-fp16.safetensors",
17
+ local_dir="models/checkpoints",
18
+ token=hf_token,
19
+ )
20
+
21
+
22
+ def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
23
+ try:
24
+ return obj[index]
25
+ except KeyError:
26
+ return obj["result"][index]
27
+
28
+
29
+ def find_path(name: str, path: str = None) -> str:
30
+ """
31
+ Recursively looks at parent folders starting from the given path until it finds the given name.
32
+ Returns the path as a Path object if found, or None otherwise.
33
+ """
34
+ # If no path is given, use the current working directory
35
+ if path is None:
36
+ path = os.getcwd()
37
+
38
+ # Check if the current directory contains the name
39
+ if name in os.listdir(path):
40
+ path_name = os.path.join(path, name)
41
+ print(f"{name} found: {path_name}")
42
+ return path_name
43
+
44
+ # Get the parent directory
45
+ parent_directory = os.path.dirname(path)
46
+
47
+ # If the parent directory is the same as the current directory, we've reached the root and stop the search
48
+ if parent_directory == path:
49
+ return None
50
+
51
+ # Recursively call the function with the parent directory
52
+ return find_path(name, parent_directory)
53
+
54
+
55
+ def add_comfyui_directory_to_sys_path() -> None:
56
+ """
57
+ Add 'ComfyUI' to the sys.path
58
+ """
59
+ comfyui_path = find_path("ComfyUI")
60
+ if comfyui_path is not None and os.path.isdir(comfyui_path):
61
+ sys.path.append(comfyui_path)
62
+ print(f"'{comfyui_path}' added to sys.path")
63
+
64
+
65
+ def add_extra_model_paths() -> None:
66
+ try:
67
+ from main import load_extra_path_config
68
+ except ImportError:
69
+ print(
70
+ "Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
71
+ )
72
+ from utils.extra_config import load_extra_path_config
73
+
74
+ extra_model_paths = find_path("extra_model_paths.yaml")
75
+
76
+ if extra_model_paths is not None:
77
+ load_extra_path_config(extra_model_paths)
78
+ else:
79
+ print("Could not find the extra_model_paths config file.")
80
+
81
+
82
+ add_comfyui_directory_to_sys_path()
83
+ add_extra_model_paths()
84
+
85
+
86
+ def import_custom_nodes() -> None:
87
+ import asyncio
88
+ import execution
89
+ from nodes import init_extra_nodes
90
+ import server
91
+
92
+ # Creating a new event loop and setting it as the default loop
93
+ loop = asyncio.new_event_loop()
94
+ asyncio.set_event_loop(loop)
95
+
96
+ # Creating an instance of PromptServer with the loop
97
+ server_instance = server.PromptServer(loop)
98
+ execution.PromptQueue(server_instance)
99
+
100
+ # Initializing custom nodes
101
+ init_extra_nodes()
102
+
103
+
104
+ from nodes import NODE_CLASS_MAPPINGS
105
+
106
+ import_custom_nodes()
107
+
108
+
109
+ checkpointloadersimple = NODE_CLASS_MAPPINGS["CheckpointLoaderSimple"]()
110
+ cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
111
+ vaeencode = NODE_CLASS_MAPPINGS["VAEEncode"]()
112
+ ksampler = NODE_CLASS_MAPPINGS["KSampler"]()
113
+ vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()
114
+ framercomfysaveimagenode = NODE_CLASS_MAPPINGS["FramerComfySaveImageNode"]()
115
+
116
+
117
+ checkpointloadersimple_14 = checkpointloadersimple.load_checkpoint(
118
+ ckpt_name="v1-5-pruned-emaonly-fp16.safetensors"
119
+ )
120
+
121
+
122
+ model_loaders = [checkpointloadersimple_14]
123
+
124
+ model_management.load_models_gpu(
125
+ [
126
+ loader[0].patcher if hasattr(loader[0], "patcher") else loader[0]
127
+ for loader in model_loaders
128
+ ]
129
+ )
130
+
131
+
132
+ @spaces.GPU
133
+ def run_workflow(prompt, negative_prompt, image_input) -> Tuple[Any, ...]:
134
+ with torch.inference_mode():
135
+ cliptextencode_6 = cliptextencode.encode(
136
+ text=prompt, clip=get_value_at_index(checkpointloadersimple_14, 1)
137
+ )
138
+
139
+ cliptextencode_7 = cliptextencode.encode(
140
+ text=negative_prompt, clip=get_value_at_index(checkpointloadersimple_14, 1)
141
+ )
142
+
143
+ vaeencode_12 = vaeencode.encode(
144
+ pixels=image_input, vae=get_value_at_index(checkpointloadersimple_14, 2)
145
+ )
146
+
147
+ ksampler_3 = ksampler.sample(
148
+ seed=random.randint(1, 2**64),
149
+ steps=20,
150
+ cfg=8,
151
+ sampler_name="dpmpp_2m",
152
+ scheduler="normal",
153
+ denoise=0.8700000000000001,
154
+ model=get_value_at_index(checkpointloadersimple_14, 0),
155
+ positive=get_value_at_index(cliptextencode_6, 0),
156
+ negative=get_value_at_index(cliptextencode_7, 0),
157
+ latent_image=get_value_at_index(vaeencode_12, 0),
158
+ )
159
+
160
+ vaedecode_8 = vaedecode.decode(
161
+ samples=get_value_at_index(ksampler_3, 0),
162
+ vae=get_value_at_index(checkpointloadersimple_14, 2),
163
+ )
164
+
165
+ framercomfysaveimagenode_18 = framercomfysaveimagenode.save_images(
166
+ filename_prefix="ComfyUI",
167
+ output_name="result_image",
168
+ images=get_value_at_index(vaedecode_8, 0),
169
+ )
170
+
171
+ framercomfysaveimagenode_18_path = (
172
+ "output/" + framercomfysaveimagenode_18["ui"]["images"][0]["filename"]
173
+ )
174
+ return framercomfysaveimagenode_18_path
175
+
176
+
177
+ # Create Gradio interface
178
+ image18_output = gr.Image(label="Generated Image18")
179
+
180
+ with gr.Blocks() as app:
181
+ with gr.Row():
182
+ with gr.Column():
183
+ prompt_input = gr.Textbox(
184
+ label="Prompt",
185
+ value="None" if "None" else None,
186
+ placeholder=f"Enter prompt here...",
187
+ )
188
+ negative_prompt_input = gr.Textbox(
189
+ label="Negative_Prompt",
190
+ value="None" if "None" else None,
191
+ placeholder=f"Enter negative_prompt here...",
192
+ )
193
+ generate_btn = gr.Button("Generate")
194
+ with gr.Column():
195
+ image18_output.render()
196
+ generate_btn.click(
197
+ fn=run_workflow,
198
+ inputs=[prompt_input, negative_prompt_input],
199
+ outputs=[image18_output],
200
+ )
201
+
202
+ if __name__ == "__main__":
203
+ app.launch(share=True)