Spaces:
Running
on
Zero
Running
on
Zero
File size: 22,115 Bytes
ee8573c b226a7a ee8573c a2a7c32 ee8573c a2a7c32 ee8573c a2a7c32 a46f87e a2a7c32 a46f87e 351b6ed ee8573c a2a7c32 03990e9 c8ebd5b 03990e9 c8ebd5b a2a7c32 03990e9 5153322 a2a7c32 5153322 03990e9 c8ebd5b 5153322 c8ebd5b 03990e9 c8ebd5b 03990e9 c8ebd5b 03990e9 16a7de0 03990e9 4e87cdd 8ed7188 03990e9 8ed7188 03990e9 6d80425 03990e9 5d67b89 a2a7c32 03990e9 a2a7c32 03990e9 a2a7c32 03990e9 4e87cdd 03990e9 351b6ed 03990e9 5153322 03990e9 5153322 5d67b89 0f7efec 5153322 5566586 03990e9 5153322 a2a7c32 5153322 03990e9 c8ebd5b 5153322 a2a7c32 5153322 03990e9 5153322 a2a7c32 5153322 03990e9 5153322 03990e9 5153322 03990e9 5153322 03990e9 5153322 03990e9 5153322 03990e9 5153322 03990e9 a2a7c32 5153322 03990e9 5153322 03990e9 5153322 03990e9 b4e548c 03990e9 c7ee98c 5b0c1dc 03990e9 9770fc5 5153322 9770fc5 5153322 03990e9 5153322 03990e9 a2a7c32 03990e9 a2a7c32 03990e9 5153322 03990e9 5153322 03990e9 a2a7c32 5153322 a2a7c32 c8ebd5b 03990e9 5153322 a2a7c32 03990e9 a2a7c32 03990e9 a2a7c32 03990e9 a2a7c32 03990e9 a2a7c32 03990e9 a2a7c32 03990e9 a2a7c32 03990e9 5153322 03990e9 5153322 99924e1 5153322 a2a7c32 5153322 5d67b89 03990e9 5d67b89 03990e9 a2a7c32 03990e9 974f017 c8ebd5b 03990e9 |
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 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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
import subprocess
import os
# ํ์ ํจํค์ง ์ค์น (์ด๋ฏธ ์ค์น๋์ด ์๋ค๋ฉด ๋ฌด์๋ฉ๋๋ค)
subprocess.run(
"pip install flash-attn --no-build-isolation",
env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
shell=True,
)
subprocess.run("pip install huggingface_hub==0.25.0", shell=True)
subprocess.run("pip install numpy==1.26.4 sentencepiece sacremoses transformers gradio safetensors torchvision diffusers", shell=True)
# ์ฒดํฌํฌ์ธํธ ํด๋ ์์ฑ ๋ฐ ๋ชจ๋ธ ์ค๋
์ท ๋ค์ด๋ก๋
os.makedirs("/home/user/app/checkpoints", exist_ok=True)
from huggingface_hub import snapshot_download
snapshot_download(repo_id="Alpha-VLLM/Lumina-Image-2.0", local_dir="/home/user/app/checkpoints")
hf_token = os.environ["HF_TOKEN"]
# โ
์ค์: CUDA ์ด๊ธฐํ ์ ์ spaces ํจํค์ง๋ฅผ ์ํฌํธํฉ๋๋ค.
import spaces
# ์ด์ CUDA์ ๊ด๋ จ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ ์ํฌํธํฉ๋๋ค.
import argparse
import builtins
import json
import math
import multiprocessing as mp
import random
import socket
import traceback
import torch
import gradio as gr
import numpy as np
from safetensors.torch import load_file
from torchvision.transforms.functional import to_pil_image
# ๋ฒ์ญ ํ์ดํ๋ผ์ธ (ํ๊ธ ํ๋กฌํํธ๋ฅผ ์์ด๋ก ๋ฒ์ญ)
from transformers import pipeline
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
from imgproc import generate_crop_size_list
import models
from transport import Sampler, create_transport
from multiprocessing import Process, Queue, set_start_method, get_context
class ModelFailure:
pass
# Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt
def encode_prompt(prompt_batch, text_encoder, tokenizer, proportion_empty_prompts, is_train=True):
captions = []
for caption in prompt_batch:
if random.random() < proportion_empty_prompts:
captions.append("")
elif isinstance(caption, str):
captions.append(caption)
elif isinstance(caption, (list, np.ndarray)):
captions.append(random.choice(caption) if is_train else caption[0])
with torch.no_grad():
text_inputs = tokenizer(
captions,
padding=True,
pad_to_multiple_of=8,
max_length=256,
truncation=True,
return_tensors="pt",
)
print(f"Text Encoder Device: {text_encoder.device}")
text_input_ids = text_inputs.input_ids.cuda()
prompt_masks = text_inputs.attention_mask.cuda()
print(f"Text Input Ids Device: {text_input_ids.device}")
print(f"Prompt Masks Device: {prompt_masks.device}")
prompt_embeds = text_encoder(
input_ids=text_input_ids,
attention_mask=prompt_masks,
output_hidden_states=True,
).hidden_states[-2]
text_encoder.cpu()
return prompt_embeds, prompt_masks
@torch.no_grad()
def model_main(args, master_port, rank):
# diffusers, transformers ๋ฑ์ ๋ด๋ถ ์ํฌํธ๋ฅผ ์ํด ํจ์ ๋ด๋ถ์์ ์ํฌํธํฉ๋๋ค.
from diffusers.models import AutoencoderKL
from transformers import AutoModel, AutoTokenizer
# ๊ธฐ๋ณธ print ํจ์๋ฅผ ์ค๋ฒ๋ผ์ด๋ํ์ฌ ์ถ๋ ฅ ์ง์ฐ์ ์ต์ํํฉ๋๋ค.
original_print = builtins.print
def print(*args, **kwargs):
kwargs.setdefault("flush", True)
original_print(*args, **kwargs)
builtins.print = print
train_args = torch.load(os.path.join(args.ckpt, "model_args.pth"))
print("Loaded model arguments:", json.dumps(train_args.__dict__, indent=2))
print(f"Creating lm: Gemma-2-2B")
dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[args.precision]
text_encoder = AutoModel.from_pretrained("google/gemma-2-2b", torch_dtype=dtype, token=hf_token).eval().to("cuda")
cap_feat_dim = text_encoder.config.hidden_size
if args.num_gpus > 1:
raise NotImplementedError("Inference with >1 GPUs not yet supported")
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b", token=hf_token)
tokenizer.padding_side = "right"
vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", token=hf_token).cuda()
print(f"Creating DiT: {train_args.model}")
model = models.__dict__[train_args.model](
in_channels=16,
qk_norm=train_args.qk_norm,
cap_feat_dim=cap_feat_dim,
)
model.eval().to("cuda", dtype=dtype)
assert train_args.model_parallel_size == args.num_gpus
if args.ema:
print("Loading EMA model.")
print('Loading model weights...')
ckpt_path = os.path.join(
args.ckpt,
f"consolidated{'_ema' if args.ema else ''}.{rank:02d}-of-{args.num_gpus:02d}.safetensors",
)
if os.path.exists(ckpt_path):
ckpt = load_file(ckpt_path)
else:
ckpt_path = os.path.join(
args.ckpt,
f"consolidated{'_ema' if args.ema else ''}.{rank:02d}-of-{args.num_gpus:02d}.pth",
)
assert os.path.exists(ckpt_path)
ckpt = torch.load(ckpt_path, map_location="cuda")
model.load_state_dict(ckpt, strict=True)
print('Model weights loaded.')
return text_encoder, tokenizer, vae, model
@torch.no_grad()
def inference(args, infer_args, text_encoder, tokenizer, vae, model):
dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[args.precision]
train_args = torch.load(os.path.join(args.ckpt, "model_args.pth"))
torch.cuda.set_device(0)
with torch.autocast("cuda", dtype):
(
cap,
neg_cap,
system_type,
resolution,
num_sampling_steps,
cfg_scale,
cfg_trunc,
renorm_cfg,
solver,
t_shift,
seed,
scaling_method,
scaling_watershed,
proportional_attn,
) = infer_args
system_prompt = system_type
cap = system_prompt + cap
if neg_cap != "":
neg_cap = system_prompt + neg_cap
metadata = dict(
real_cap=cap,
real_neg_cap=neg_cap,
system_type=system_type,
resolution=resolution,
num_sampling_steps=num_sampling_steps,
cfg_scale=cfg_scale,
cfg_trunc=cfg_trunc,
renorm_cfg=renorm_cfg,
solver=solver,
t_shift=t_shift,
seed=seed,
scaling_method=scaling_method,
scaling_watershed=scaling_watershed,
proportional_attn=proportional_attn,
)
print("> Parameters:", json.dumps(metadata, indent=2))
try:
# ์ํ๋ฌ ์ค์
if solver == "dpm":
transport = create_transport("Linear", "velocity")
sampler = Sampler(transport)
sample_fn = sampler.sample_dpm(
model.forward_with_cfg,
model_kwargs=model_kwargs,
)
else:
transport = create_transport(
args.path_type,
args.prediction,
args.loss_weight,
args.train_eps,
args.sample_eps,
)
sampler = Sampler(transport)
sample_fn = sampler.sample_ode(
sampling_method=solver,
num_steps=num_sampling_steps,
atol=args.atol,
rtol=args.rtol,
reverse=args.reverse,
time_shifting_factor=t_shift,
)
# ํด์๋ ๋ฐ latent ๊ณต๊ฐ ํฌ๊ธฐ ๊ณ์ฐ
resolution = resolution.split(" ")[-1]
w, h = resolution.split("x")
w, h = int(w), int(h)
latent_w, latent_h = w // 8, h // 8
if int(seed) != 0:
torch.random.manual_seed(int(seed))
z = torch.randn([1, 16, latent_h, latent_w], device="cuda").to(dtype)
z = z.repeat(2, 1, 1, 1)
with torch.no_grad():
if neg_cap != "":
cap_feats, cap_mask = encode_prompt([cap] + [neg_cap], text_encoder, tokenizer, 0.0)
else:
cap_feats, cap_mask = encode_prompt([cap] + [""], text_encoder, tokenizer, 0.0)
cap_mask = cap_mask.to(cap_feats.device)
model_kwargs = dict(
cap_feats=cap_feats,
cap_mask=cap_mask,
cfg_scale=cfg_scale,
cfg_trunc=1 - cfg_trunc,
renorm_cfg=renorm_cfg,
)
print(f"> Caption: {cap}")
print(f"> Number of sampling steps: {num_sampling_steps}")
print(f"> CFG scale: {cfg_scale}")
print("> Starting sampling...")
if solver == "dpm":
samples = sample_fn(z, steps=num_sampling_steps, order=2, skip_type="time_uniform_flow", method="multistep", flow_shift=t_shift)
else:
samples = sample_fn(z, model.forward_with_cfg, **model_kwargs)[-1]
samples = samples[:1]
print("Sample dtype:", samples.dtype)
vae_scale = {
"sdxl": 0.13025,
"sd3": 1.5305,
"ema": 0.18215,
"mse": 0.18215,
"cogvideox": 1.15258426,
"flux": 0.3611,
}["flux"]
vae_shift = {
"sdxl": 0.0,
"sd3": 0.0609,
"ema": 0.0,
"mse": 0.0,
"cogvideox": 0.0,
"flux": 0.1159,
}["flux"]
print(f"> VAE scale: {vae_scale}, shift: {vae_shift}")
print("Samples shape:", samples.shape)
samples = vae.decode(samples / vae_scale + vae_shift).sample
samples = (samples + 1.0) / 2.0
samples.clamp_(0.0, 1.0)
img = to_pil_image(samples[0].float())
print("> Generated image successfully.")
return img, metadata
except Exception:
print(traceback.format_exc())
return ModelFailure()
def none_or_str(value):
if value == "None":
return None
return value
def parse_transport_args(parser):
group = parser.add_argument_group("Transport arguments")
group.add_argument(
"--path-type",
type=str,
default="Linear",
choices=["Linear", "GVP", "VP"],
help="Type of path for transport: 'Linear', 'GVP' (Geodesic Vector Pursuit), or 'VP' (Vector Pursuit).",
)
group.add_argument(
"--prediction",
type=str,
default="velocity",
choices=["velocity", "score", "noise"],
help="Prediction model for the transport dynamics.",
)
group.add_argument(
"--loss-weight",
type=none_or_str,
default=None,
choices=[None, "velocity", "likelihood"],
help="Weighting of different loss components: 'velocity', 'likelihood', or None.",
)
group.add_argument("--sample-eps", type=float, help="Sampling parameter in the transport model.")
group.add_argument("--train-eps", type=float, help="Training epsilon to stabilize learning.")
def parse_ode_args(parser):
group = parser.add_argument_group("ODE arguments")
group.add_argument(
"--atol",
type=float,
default=1e-6,
help="Absolute tolerance for the ODE solver.",
)
group.add_argument(
"--rtol",
type=float,
default=1e-3,
help="Relative tolerance for the ODE solver.",
)
group.add_argument("--reverse", action="store_true", help="Run the ODE solver in reverse.")
group.add_argument(
"--likelihood",
action="store_true",
help="Enable likelihood calculation during the ODE solving process.",
)
def find_free_port() -> int:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 0))
port = sock.getsockname()[1]
sock.close()
return port
# ํ๊ธ ํ๋กฌํํธ๊ฐ ๊ฐ์ง๋๋ฉด ์์ด๋ก ๋ฒ์ญํ๋ ํจ์
def translate_if_korean(text: str) -> str:
import re
if re.search(r"[ใฑ-ใ
ใ
-ใ
ฃ๊ฐ-ํฃ]", text):
print("Translating Korean prompt to English...")
translation = translator(text)
return translation[0]["translation_text"]
return text
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--num_gpus", type=int, default=1)
parser.add_argument("--ckpt", type=str, default='/home/user/app/checkpoints', required=False)
parser.add_argument("--ema", action="store_true")
parser.add_argument("--precision", default="bf16", choices=["bf16", "fp32"])
parser.add_argument("--hf_token", type=str, default=None, help="Hugging Face read token for accessing gated repo.")
parser.add_argument("--res", type=int, default=1024, choices=[256, 512, 1024])
parser.add_argument("--port", type=int, default=12123)
parse_transport_args(parser)
parse_ode_args(parser)
args = parser.parse_known_args()[0]
if args.num_gpus != 1:
raise NotImplementedError("Multi-GPU Inference is not yet supported")
master_port = find_free_port()
text_encoder, tokenizer, vae, model = model_main(args, master_port, 0)
description = "Lumina-Image 2.0 ([Github](https://github.com/Alpha-VLLM/Lumina-Image-2.0/tree/main))"
# ์ปค์คํ
CSS: ๋ฉ๋ด ์ปจํ
์ด๋์ ๋๋น๋ฅผ ์ค์ด๊ณ , ๋ฐฐ๊ฒฝ์ด ์ ๋ณด์ด๋๋ก ๋ฐํฌ๋ช
๋ฐฐ๊ฒฝ์ ์ ์ฉํฉ๋๋ค.
custom_css = """
body {
background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
font-family: 'Helvetica', sans-serif;
color: #333;
}
.gradio-container {
background: rgba(255, 255, 255, 0.85); /* ๋ฐํฌ๋ช
๋ฐฐ๊ฒฝ */
max-width: 800px; /* ์ปจํ
์ด๋ ์ต๋ ๋๋น ์กฐ์ */
margin: 20px auto; /* ์ค์ ์ ๋ ฌ */
border-radius: 15px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.25);
padding: 20px;
}
.gradio-title {
font-weight: bold;
font-size: 1.5em;
text-align: center;
margin-bottom: 10px;
}
"""
with gr.Blocks(css=custom_css) as demo:
with gr.Row():
gr.Markdown(f"<div class='gradio-title'>{description}</div>")
with gr.Row():
with gr.Column():
cap = gr.Textbox(
lines=2,
label="Caption",
interactive=True,
value="Majestic landscape photograph of snow-capped mountains under a dramatic sky at sunset. The mountains dominate the lower half of the image, with rugged peaks and deep crevasses visible. A glacier flows down the right side, partially illuminated by the warm light. The sky is filled with fiery orange and golden clouds, contrasting with the cool tones of the snow. The central peak is partially obscured by clouds, adding a sense of mystery. The foreground features dark, shadowed forested areas, enhancing the depth. High contrast, natural lighting, warm color palette, photorealistic, expansive, awe-inspiring, serene, visually balanced, dynamic composition.",
placeholder="Enter a caption."
)
neg_cap = gr.Textbox(
lines=2,
label="Negative Caption",
interactive=True,
value="",
placeholder="Enter a negative caption."
)
default_value = "You are an assistant designed to generate high-quality images with the highest degree of image-text alignment based on textual prompts."
system_type = gr.Dropdown(
value=default_value,
choices=[
"You are an assistant designed to generate high-quality images with the highest degree of image-text alignment based on textual prompts.",
"You are an assistant designed to generate superior images with the superior degree of image-text alignment based on textual prompts or user prompts.",
""
],
label="System Type"
)
with gr.Row():
res_choices = [f"{w}x{h}" for w, h in generate_crop_size_list((args.res // 64) ** 2, 64)]
default_value = "1024x1024"
resolution = gr.Dropdown(value=default_value, choices=res_choices, label="Resolution")
with gr.Row():
num_sampling_steps = gr.Slider(minimum=1, maximum=70, value=40, step=1, interactive=True, label="Sampling Steps")
seed = gr.Slider(minimum=0, maximum=int(1e5), value=0, step=1, interactive=True, label="Seed (0 for random)")
cfg_trunc = gr.Slider(minimum=0, maximum=1, value=0, step=0.01, interactive=True, label="CFG Truncation")
with gr.Row():
solver = gr.Dropdown(value="euler", choices=["euler", "midpoint", "rk4"], label="Solver")
t_shift = gr.Slider(minimum=1, maximum=20, value=6, step=1, interactive=True, label="Time Shift")
cfg_scale = gr.Slider(minimum=1.0, maximum=20.0, value=4.0, interactive=True, label="CFG Scale")
with gr.Row():
renorm_cfg = gr.Dropdown(value=True, choices=[True, False, 2.0], label="CFG Renorm")
with gr.Accordion("Advanced Settings for Resolution Extrapolation", open=False):
with gr.Row():
scaling_method = gr.Dropdown(value="Time-aware", choices=["Time-aware", "None"], label="RoPE Scaling Method")
scaling_watershed = gr.Slider(minimum=0.0, maximum=1.0, value=0.3, interactive=True, label="Linear/NTK Watershed")
with gr.Row():
proportional_attn = gr.Checkbox(value=True, interactive=True, label="Proportional Attention")
with gr.Row():
submit_btn = gr.Button("Submit", variant="primary")
with gr.Column():
output_img = gr.Image(label="Generated Image", interactive=False)
with gr.Accordion(label="Generation Parameters", open=True):
gr_metadata = gr.JSON(label="Metadata", show_label=False)
with gr.Row():
prompts = [
"Close-up portrait of a young woman with light brown hair, looking to the right, illuminated by warm, golden sunlight. Her hair is gently tousled, catching the light and creating a halo effect around her head. She wears a white garment with a V-neck, visible in the lower left of the frame. The background is dark and out of focus, enhancing the contrast between her illuminated face and the shadows. Soft, ethereal lighting, high contrast, warm color palette, shallow depth of field, natural backlighting, serene and contemplative mood, cinematic quality, intimate and visually striking composition.",
"ํ๋์ ๋๋ ์ฉ, ์ ๋น๋ก์ด ๋ถ์๊ธฐ, ๊ตฌ๋ฆ ์๋ฅผ ๋ ๋ฉฐ ๋น๋๋ ๋น๋์ ๊ฐ์ง, ์ ์ค ์์ ์กด์ฌ, ๊ฐ๋ ฌํ ์์ฑ์ ๋ํ
์ผํ ๋ฌ์ฌ.",
"Aesthetic photograph of a bouquet of pink and white ranunculus flowers in a clear glass vase, centrally positioned on a wooden surface. The flowers are in full bloom, displaying intricate layers of petals with a soft gradient from pale pink to white. The vase is filled with water, visible through the clear glass, and the stems are submerged. In the background, a blurred vase with green stems is partially visible, adding depth to the composition. The lighting is warm and natural, casting soft shadows and highlighting the delicate textures of the petals. The scene is serene and intimate, with a focus on the organic beauty of the flowers. Photorealistic, shallow depth of field, soft natural lighting, warm color palette, high contrast, glossy texture, tranquil, visually balanced.",
"ํๅชไผ้
็็ฝ็ซ็ฉฟ็ไธไปถ็ดซ่ฒ็ๆ่ข๏ผๆ่ขไธ็ปฃๆ็ฒพ่ด็็กไธน่ฑๅพๆก๏ผๆพๅพ้ซ่ดตๅ
ธ้
ใๅฎๅคดไธๆด็ไธๆต้่ฒ็ๅ้ฅฐ๏ผๅด้ๅผ็ไธๆ น่ฑกๅพๅฅฝ่ฟ็็บข่ฒไธๅธฆใๅจๅด็ฏ็ป็่ฎธๅค้ฃๅจ็็บธ้นคๅ้่ฒ็ๅ
็น๏ผ่ฅ้ ๅบไธ็ง็ฅฅ็ๅๆขฆๅนป็ๆฐๅดใ่ถ
ๅๅฎ้ฃๆ ผใ"
]
prompts = [[p] for p in prompts]
gr.Examples(prompts, [cap], label="Examples")
@spaces.GPU(duration=200)
def on_submit(cap, neg_cap, system_type, resolution, num_sampling_steps, cfg_scale, cfg_trunc, renorm_cfg, solver, t_shift, seed, scaling_method, scaling_watershed, proportional_attn, progress=gr.Progress(track_tqdm=True)):
# ํ๊ธ ํ๋กฌํํธ๊ฐ ๊ฐ์ง๋๋ฉด ์์ด๋ก ๋ฒ์ญ
cap = translate_if_korean(cap)
if neg_cap and neg_cap.strip():
neg_cap = translate_if_korean(neg_cap)
infer_args = (cap, neg_cap, system_type, resolution, num_sampling_steps, cfg_scale, cfg_trunc, renorm_cfg, solver, t_shift, seed, scaling_method, scaling_watershed, proportional_attn)
result = inference(args, infer_args, text_encoder, tokenizer, vae, model)
if isinstance(result, ModelFailure):
raise RuntimeError("Model failed to generate the image.")
return result
submit_btn.click(
on_submit,
[cap, neg_cap, system_type, resolution, num_sampling_steps, cfg_scale, cfg_trunc, renorm_cfg, solver, t_shift, seed, scaling_method, scaling_watershed, proportional_attn],
[output_img, gr_metadata],
)
def show_scaling_watershed(scaling_m):
return gr.update(visible=scaling_m == "Time-aware")
scaling_method.change(show_scaling_watershed, scaling_method, scaling_watershed)
demo.queue().launch(server_name="0.0.0.0")
if __name__ == "__main__":
main()
|