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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
)
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
| 22 |
)
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
parser = HfArgumentParser([AppArgs])
|
| 25 |
args_tuple = parser.parse_args_into_dataclasses()
|
| 26 |
args = args_tuple[0]
|
| 27 |
|
| 28 |
-
# Set model_name based on local_model flag
|
| 29 |
-
if args.local_model:
|
| 30 |
-
args.model_name = "ghibli-fine-tuned-sd-2.1"
|
| 31 |
-
|
| 32 |
demo = create_demo(args.model_name, args.device)
|
| 33 |
-
demo.launch(server_port=args.port, share=args.share)
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import numpy as np
|
| 9 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 10 |
+
from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
from transformers import HfArgumentParser
|
| 13 |
|
| 14 |
+
def get_examples(examples_dir: str = "assets/examples") -> list:
|
| 15 |
+
"""
|
| 16 |
+
Load example data from the assets/examples directory.
|
| 17 |
+
Each example is a subdirectory containing a config.json and an image file.
|
| 18 |
+
Returns a list of [prompt, height, width, num_inference_steps, guidance_scale, seed, image_path].
|
| 19 |
+
"""
|
| 20 |
+
examples = Path(examples_dir)
|
| 21 |
+
ans = []
|
| 22 |
+
for example in examples.iterdir():
|
| 23 |
+
if not example.is_dir():
|
| 24 |
+
continue
|
| 25 |
+
with open(example / "config.json") as f:
|
| 26 |
+
example_dict = json.load(f)
|
| 27 |
+
|
| 28 |
+
required_keys = ["prompt", "height", "width", "num_inference_steps", "guidance_scale", "seed", "image"]
|
| 29 |
+
if not all(key in example_dict for key in required_keys):
|
| 30 |
+
continue
|
| 31 |
+
|
| 32 |
+
example_list = [
|
| 33 |
+
example_dict["prompt"],
|
| 34 |
+
example_dict["height"],
|
| 35 |
+
example_dict["width"],
|
| 36 |
+
example_dict["num_inference_steps"],
|
| 37 |
+
example_dict["guidance_scale"],
|
| 38 |
+
example_dict["seed"],
|
| 39 |
+
str(example / example_dict["image"]) # Path to the image file
|
| 40 |
+
]
|
| 41 |
+
ans.append(example_list)
|
| 42 |
+
|
| 43 |
+
if not ans:
|
| 44 |
+
ans = [
|
| 45 |
+
["a serene landscape in Ghibli style", 64, 64, 50, 3.5, 42, None]
|
| 46 |
+
]
|
| 47 |
+
return ans
|
| 48 |
+
|
| 49 |
+
def create_demo(
|
| 50 |
+
model_name: str = "danhtran2mind/ghibli-fine-tuned-sd-2.1",
|
| 51 |
+
device: str = "cuda" if torch.cuda.is_available() else "cpu",
|
| 52 |
+
):
|
| 53 |
+
# Convert device string to torch.device
|
| 54 |
+
device = torch.device(device)
|
| 55 |
+
dtype = torch.float16 if device.type == "cuda" else torch.float32
|
| 56 |
+
|
| 57 |
+
# Load models with consistent dtype
|
| 58 |
+
vae = AutoencoderKL.from_pretrained(model_name, subfolder="vae", torch_dtype=dtype).to(device)
|
| 59 |
+
tokenizer = CLIPTokenizer.from_pretrained(model_name, subfolder="tokenizer")
|
| 60 |
+
text_encoder = CLIPTextModel.from_pretrained(model_name, subfolder="text_encoder", torch_dtype=dtype).to(device)
|
| 61 |
+
unet = UNet2DConditionModel.from_pretrained(model_name, subfolder="unet", torch_dtype=dtype).to(device)
|
| 62 |
+
scheduler = PNDMScheduler.from_pretrained(model_name, subfolder="scheduler")
|
| 63 |
+
|
| 64 |
+
def generate_image(prompt, height, width, num_inference_steps, guidance_scale, seed, random_seed):
|
| 65 |
+
if not prompt:
|
| 66 |
+
return None, "Prompt cannot be empty."
|
| 67 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 68 |
+
return None, "Height and width must be divisible by 8 (e.g., 256, 512, 1024)."
|
| 69 |
+
if num_inference_steps < 1 or num_inference_steps > 100:
|
| 70 |
+
return None, "Number of inference steps must be between 1 and 100."
|
| 71 |
+
if guidance_scale < 1.0 or guidance_scale > 20.0:
|
| 72 |
+
return None, "Guidance scale must be between 1.0 and 20.0."
|
| 73 |
+
if seed < 0 or seed > 4294967295:
|
| 74 |
+
return None, "Seed must be between 0 and 4294967295."
|
| 75 |
+
|
| 76 |
+
batch_size = 1
|
| 77 |
+
if random_seed:
|
| 78 |
+
seed = torch.randint(0, 4294967295, (1,)).item()
|
| 79 |
+
generator = torch.Generator(device=device).manual_seed(int(seed))
|
| 80 |
+
|
| 81 |
+
text_input = tokenizer(
|
| 82 |
+
[prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt"
|
| 83 |
)
|
| 84 |
+
with torch.no_grad():
|
| 85 |
+
text_embeddings = text_encoder(text_input.input_ids.to(device))[0].to(dtype=dtype)
|
| 86 |
+
|
| 87 |
+
max_length = text_input.input_ids.shape[-1]
|
| 88 |
+
uncond_input = tokenizer(
|
| 89 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
| 90 |
)
|
| 91 |
+
with torch.no_grad():
|
| 92 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0].to(dtype=dtype)
|
| 93 |
+
|
| 94 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
| 95 |
+
|
| 96 |
+
latents = torch.randn(
|
| 97 |
+
(batch_size, unet.config.in_channels, height // 8, width // 8),
|
| 98 |
+
generator=generator,
|
| 99 |
+
dtype=dtype,
|
| 100 |
+
device=device
|
| 101 |
)
|
| 102 |
+
|
| 103 |
+
scheduler.set_timesteps(num_inference_steps)
|
| 104 |
+
latents = latents * scheduler.init_noise_sigma
|
| 105 |
+
|
| 106 |
+
for t in tqdm(scheduler.timesteps, desc="Generating image"):
|
| 107 |
+
latent_model_input = torch.cat([latents] * 2)
|
| 108 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
| 109 |
+
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
if device.type == "cuda":
|
| 112 |
+
with torch.autocast(device_type="cuda", dtype=torch.float16):
|
| 113 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
|
| 114 |
+
else:
|
| 115 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
|
| 116 |
+
|
| 117 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 118 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 119 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
| 120 |
+
|
| 121 |
+
with torch.no_grad():
|
| 122 |
+
latents = latents / vae.config.scaling_factor
|
| 123 |
+
image = vae.decode(latents).sample
|
| 124 |
+
|
| 125 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 126 |
+
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
|
| 127 |
+
image = (image * 255).round().astype("uint8")
|
| 128 |
+
pil_image = Image.fromarray(image[0])
|
| 129 |
+
|
| 130 |
+
return pil_image, f"Image generated successfully! Seed used: {seed}"
|
| 131 |
+
|
| 132 |
+
def load_example_image(prompt, height, width, num_inference_steps, guidance_scale, seed, image_path):
|
| 133 |
+
"""
|
| 134 |
+
Load the image for the selected example and update input fields.
|
| 135 |
+
"""
|
| 136 |
+
if image_path and Path(image_path).exists():
|
| 137 |
+
try:
|
| 138 |
+
image = Image.open(image_path)
|
| 139 |
+
return prompt, height, width, num_inference_steps, guidance_scale, seed, image, f"Loaded image: {image_path}"
|
| 140 |
+
except Exception as e:
|
| 141 |
+
return prompt, height, width, num_inference_steps, guidance_scale, seed, None, f"Error loading image: {e}"
|
| 142 |
+
return prompt, height, width, num_inference_steps, guidance_scale, seed, None, "No image available"
|
| 143 |
+
|
| 144 |
+
badges_text = r"""
|
| 145 |
+
<div style="text-align: center; display: flex; justify-content: left; gap: 5px;">
|
| 146 |
+
<a href="https://huggingface.co/spaces/danhtran2mind/ghibli-fine-tuned-sd-2.1"><img src="https://img.shields.io/static/v1?label=%F0%9F%A4%97%20Hugging%20Face&message=Space&color=orange"></a>
|
| 147 |
+
</div>
|
| 148 |
+
""".strip()
|
| 149 |
+
|
| 150 |
+
with gr.Blocks() as demo:
|
| 151 |
+
gr.Markdown("# Ghibli-Style Image Generator")
|
| 152 |
+
gr.Markdown(badges_text)
|
| 153 |
+
gr.Markdown("Generate images in Ghibli style using a fine-tuned Stable Diffusion model. Select an example below to load a pre-generated image or enter a prompt to generate a new one.")
|
| 154 |
+
gr.Markdown("""**Note:** For CPU inference, execution time is long (e.g., for resolution 512 × 512) with 50 inference steps, time is approximately 1700 seconds).""")
|
| 155 |
+
|
| 156 |
+
with gr.Row():
|
| 157 |
+
with gr.Column():
|
| 158 |
+
prompt = gr.Textbox(label="Prompt", placeholder="e.g., 'a serene landscape in Ghibli style'")
|
| 159 |
+
with gr.Row():
|
| 160 |
+
width = gr.Slider(32, 4096, 512, step=8, label="Generation Width")
|
| 161 |
+
height = gr.Slider(32, 4096, 512, step=8, label="Generation Height")
|
| 162 |
+
with gr.Accordion("Advanced Options", open=False):
|
| 163 |
+
num_inference_steps = gr.Slider(1, 100, 50, step=1, label="Number of Inference Steps")
|
| 164 |
+
guidance_scale = gr.Slider(1.0, 20.0, 3.5, step=0.5, label="Guidance Scale")
|
| 165 |
+
seed = gr.Number(42, label="Seed (0 to 4294967295)")
|
| 166 |
+
random_seed = gr.Checkbox(label="Use Random Seed", value=False)
|
| 167 |
+
generate_btn = gr.Button("Generate Image")
|
| 168 |
+
|
| 169 |
+
with gr.Column():
|
| 170 |
+
output_image = gr.Image(label="Generated Image")
|
| 171 |
+
output_text = gr.Textbox(label="Status")
|
| 172 |
+
|
| 173 |
+
examples = get_examples("assets/examples")
|
| 174 |
+
gr.Examples(
|
| 175 |
+
examples=examples,
|
| 176 |
+
inputs=[prompt, height, width, num_inference_steps, guidance_scale, seed, output_image],
|
| 177 |
+
outputs=[prompt, height, width, num_inference_steps, guidance_scale, seed, output_image, output_text],
|
| 178 |
+
fn=load_example_image,
|
| 179 |
+
cache_examples=False
|
| 180 |
)
|
| 181 |
+
|
| 182 |
+
generate_btn.click(
|
| 183 |
+
fn=generate_image,
|
| 184 |
+
inputs=[prompt, height, width, num_inference_steps, guidance_scale, seed, random_seed],
|
| 185 |
+
outputs=[output_image, output_text]
|
| 186 |
)
|
| 187 |
|
| 188 |
+
return demo
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
|
| 192 |
+
@dataclasses.dataclass
|
| 193 |
+
class AppArgs:
|
| 194 |
+
if local_model == True:
|
| 195 |
+
model_name: str = "ghibli-fine-tuned-sd-2.1"
|
| 196 |
+
else:
|
| 197 |
+
model_name: str = "danhtran2mind/ghibli-fine-tuned-sd-2.1"
|
| 198 |
+
device: str = "cuda" if torch.cuda.is_available() else "cpu"
|
| 199 |
+
port: int = 7860
|
| 200 |
+
share: bool = False # Set to True for public sharing (Hugging Face Spaces)
|
| 201 |
+
|
| 202 |
parser = HfArgumentParser([AppArgs])
|
| 203 |
args_tuple = parser.parse_args_into_dataclasses()
|
| 204 |
args = args_tuple[0]
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
demo = create_demo(args.model_name, args.device)
|
| 207 |
+
demo.launch(server_port=args.port, share=args.share)
|
| 208 |
+
|
| 209 |
+
<<add option choose local_model when run app.py>>
|