mohamedsobhi777's picture
Uploaded app.py file
cf2be89 verified
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)