Spaces:
Paused
Paused
File size: 6,860 Bytes
9e17d8f 7d125a7 f85986b 9e17d8f f85986b 9e17d8f f85986b 9e17d8f f85986b 9e17d8f f85986b 7d125a7 9e17d8f f85986b 9e17d8f f85986b 9e17d8f f85986b 7d125a7 f85986b 9e17d8f f85986b 7d125a7 f85986b 7d125a7 010ba30 f85986b 9e17d8f f85986b 7d125a7 f85986b 7d125a7 f85986b 7d125a7 9e17d8f f85986b 7d125a7 f85986b 7d125a7 f85986b 7d125a7 f85986b 7d125a7 f85986b 7d125a7 f85986b 9e17d8f f85986b 010ba30 |
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 time
import gradio as gr
from gradio_imageslider import ImageSlider
from comfydeploy import ComfyDeploy
from PIL import Image
import requests
from io import BytesIO
import base64
import glob
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.environ.get("COMFY_DEPLOY_API_KEY")
DEPLOYMENT_ID = os.environ.get("COMFY_DEPLOYMENT_ID")
if not API_KEY or not DEPLOYMENT_ID:
raise ValueError(
"Please set COMFY_DEPLOY_API_KEY and COMFY_DEPLOYMENT_ID in your environment variables"
)
client = ComfyDeploy(bearer_auth=API_KEY)
def get_base64_from_image(image: Image.Image) -> str:
buffered = BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode("utf-8")
def get_profile(profile) -> dict:
return {
"username": profile.username,
"profile": profile.profile,
"name": profile.name,
}
async def process(
image: Image.Image | None = None,
profile: gr.OAuthProfile | None = None,
progress: gr.Progress = gr.Progress(),
) -> tuple[Image.Image, Image.Image] | None:
if not image:
gr.Info("Please upload an image ")
return None
if profile is None:
gr.Info("Please log in to process the image.")
return None
user_data = get_profile(profile)
print("--------- RUN ----------")
print(user_data)
progress(0, desc="Preparing inputs...")
image_base64 = get_base64_from_image(image)
inputs = {
"image": f"data:image/png;base64,{image_base64}",
**{k: str(v) for k, v in params.items()},
}
output = await process_image(inputs, progress)
progress(100, desc="Processing completed")
return image, output
async def process_image(inputs: dict, progress: gr.Progress) -> Image.Image | None:
try:
result = client.run.create(
request={"deployment_id": DEPLOYMENT_ID, "inputs": inputs}
)
if result and result.object:
run_id: str = result.object.run_id
progress(0, desc="Starting processing...")
while True:
run_result = client.run.get(run_id=run_id)
if not run_result.object:
continue
progress_value = run_result.object.progress or 0
status = run_result.object.live_status or "Cold starting..."
progress(progress_value, desc=f"Status: {status}")
if run_result.object.status == "success":
for output in run_result.object.outputs or []:
if output.data and output.data.images:
image_url: str = output.data.images[0].url
response = requests.get(image_url)
processed_image = Image.open(BytesIO(response.content))
return processed_image
elif run_result.object.status == "failed":
print("Processing failed")
return None
time.sleep(1) # Wait for 1 second before checking the status again
except Exception as e:
print(f"Error: {e}")
return None
def load_preset_images():
image_files = glob.glob("images/inputs/*")
return [
{"name": img, "image": Image.open(img)}
for img in image_files
if Image.open(img).format.lower()
in ["png", "jpg", "jpeg", "gif", "bmp", "webp"]
]
def build_example(input_image_path):
output_image_path = input_image_path.replace("inputs", "outputs")
return [
input_image_path,
0.4,
10,
1024,
1,
4,
0,
1,
0.7,
(input_image_path, output_image_path),
]
def serialize_params(params: dict) -> dict:
return {
key: {"value": param.value, "label": param.label}
for key, param in params.items()
}
with gr.Blocks() as demo:
gr.HTML("""
<div style="display: flex; justify-content: center; text-align:center; flex-direction: column;">
<h1 style="color: #333;">๐ Creative Image Upscaler</h1>
<div style="max-width: 800px; margin: 0 auto;">
<p style="font-size: 16px;">Upload an image and adjust the parameters to enhance your image.</p>
<p style="font-size: 16px;">Click on the <b>"Run"</b> button to process the image and compare the original and processed images using the slider.</p>
<p style="font-size: 16px;">โ ๏ธ Note that the images are compressed to reduce the workloads of the demo.</p>
</div>
</div>
""")
with gr.Row(equal_height=False):
with gr.Column():
# The image overflow, fix
input_image = gr.Image(type="pil", label="Input Image", interactive=True)
with gr.Accordion("Avanced parameters", open=False):
params = {
"denoise": gr.Slider(0, 1, value=0.4, label="Denoise"),
"steps": gr.Slider(1, 25, value=10, label="Steps"),
"tile_size": gr.Slider(256, 2048, value=1024, label="Tile Size"),
"downscale": gr.Slider(1, 4, value=1, label="Downscale"),
"upscale": gr.Slider(1, 4, value=4, label="Upscale"),
"color_match": gr.Slider(0, 1, value=0, label="Color Match"),
"controlnet_tile_end": gr.Slider(
0, 1, value=1, label="ControlNet Tile End"
),
"controlnet_tile_strength": gr.Slider(
0, 1, value=0.7, label="ControlNet Tile Strength"
),
}
with gr.Column():
image_slider = ImageSlider(
label="Compare Original and Processed", interactive=False
)
login_button = gr.LoginButton(scale=8)
process_btn = gr.Button("Run", variant="primary", size="lg")
process_btn.click(
fn=lambda _: gr.update(interactive=False, value="Processing..."),
inputs=[],
outputs=[process_btn],
api_name=False,
).then(
fn=process,
inputs=[
input_image,
],
outputs=[image_slider],
api_name=False,
).then(
fn=lambda _: gr.update(interactive=True, value="Run"),
inputs=[],
outputs=[process_btn],
api_name=False,
)
examples = [build_example(img) for img in glob.glob("images/inputs/*")]
gr.Examples(examples=examples, inputs=[input_image, *params.values(), image_slider])
if __name__ == "__main__":
demo.queue().launch(debug=True, share=True)
|