ar08 commited on
Commit
20dc4d8
·
verified ·
1 Parent(s): f01a187

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -74
app.py CHANGED
@@ -1,11 +1,10 @@
1
  import gradio as gr
2
  import torch
 
3
  from diffusers import StableDiffusionImg2ImgPipeline
4
  from PIL import Image
5
- import numpy as np
6
  from typing import Generator, List
7
 
8
- # Set up device and model
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
  model_id = "nitrosocke/Ghibli-Diffusion"
11
 
@@ -17,98 +16,129 @@ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
17
  pipe = pipe.to(device)
18
  pipe.enable_attention_slicing()
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def generate_ghibli_style(
21
  input_image: Image.Image,
22
  steps: int = 25,
23
  strength: float = 0.6,
24
- guidance_scale: float = 7.0,
25
- progress: gr.Progress = gr.Progress()
26
- ) -> Generator[List[Image.Image], None, None]:
27
- """
28
- Generate Ghibli-style images in real-time with intermediate steps
29
- """
30
- prompt = "ghibli style, high quality, detailed portrait"
31
- negative_prompt = "low quality, blurry, bad anatomy"
32
-
33
- intermediate_images = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- def callback(step: int, timestep: int, latents: torch.Tensor):
 
 
 
36
  with torch.no_grad():
37
- # Decode the latents to image
38
- image = pipe.decode_latents(latents)
39
- image = pipe.numpy_to_pil(image)[0]
40
- intermediate_images.append(image)
41
-
42
- # Update progress and yield the current images
43
- progress(step / steps, desc="Generating...")
44
- yield intermediate_images
45
-
46
- # Run the pipeline
47
- with torch.inference_mode():
48
- # Create a generator that will yield the images
49
- generator = pipe(
50
- prompt=prompt,
51
- image=input_image,
52
- negative_prompt=negative_prompt,
53
- strength=strength,
54
- guidance_scale=guidance_scale,
55
- num_inference_steps=steps,
56
- callback=callback,
57
- callback_steps=1 # Call after every step
58
- )
59
-
60
- # Yield the final result
61
- final_image = generator.images[0]
62
- intermediate_images.append(final_image)
63
- yield intermediate_images
64
-
65
- # Custom CSS for better appearance
66
- css = """
67
- .gallery {
68
- min-height: 500px;
69
- }
70
- .gallery img {
71
- max-height: 400px;
72
- object-fit: contain;
73
- }
74
- """
75
 
76
  # Gradio interface
77
- with gr.Blocks(css=css) as demo:
78
- gr.Markdown("# ✨ Studio Ghibli Portrait Generator ✨")
79
- gr.Markdown("Upload a photo and watch it transform into a Ghibli-style portrait in real-time!")
80
 
81
  with gr.Row():
82
  with gr.Column():
83
- input_image = gr.Image(label="Upload Photo", type="pil")
84
- steps_slider = gr.Slider(10, 50, value=25, step=1, label="Inference Steps")
85
- strength_slider = gr.Slider(0.1, 0.9, value=0.6, step=0.05, label="Transformation Strength")
86
- generate_btn = gr.Button("Generate", variant="primary")
87
 
88
  with gr.Column():
89
  gallery = gr.Gallery(
90
  label="Generation Progress",
91
  show_label=True,
92
- elem_id="gallery",
93
- preview=True
 
 
94
  )
95
-
96
- # Example images
97
- gr.Examples(
98
- examples=[
99
- ["examples/portrait1.jpg", 25, 0.6],
100
- ["examples/portrait2.jpg", 30, 0.5],
101
- ],
102
- inputs=[input_image, steps_slider, strength_slider],
103
- label="Try these examples!"
104
- )
105
-
106
  generate_btn.click(
107
  fn=generate_ghibli_style,
108
  inputs=[input_image, steps_slider, strength_slider],
109
- outputs=gallery
 
 
 
 
 
 
 
 
 
110
  )
111
 
112
- # Launch the app
113
  if __name__ == "__main__":
114
- demo.queue(concurrency_count=1).launch(share=True)
 
 
1
  import gradio as gr
2
  import torch
3
+ import numpy as np
4
  from diffusers import StableDiffusionImg2ImgPipeline
5
  from PIL import Image
 
6
  from typing import Generator, List
7
 
 
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
9
  model_id = "nitrosocke/Ghibli-Diffusion"
10
 
 
16
  pipe = pipe.to(device)
17
  pipe.enable_attention_slicing()
18
 
19
+ def resize_and_crop(image: Image.Image, target_size: int = 512) -> Image.Image:
20
+ """Resize and crop the image to the target size while maintaining aspect ratio."""
21
+ width, height = image.size
22
+ if width > height:
23
+ left = (width - height) // 2
24
+ right = left + height
25
+ image = image.crop((left, 0, right, height))
26
+ elif height > width:
27
+ top = (height - width) // 2
28
+ bottom = top + width
29
+ image = image.crop((0, top, width, bottom))
30
+ return image.resize((target_size, target_size))
31
+
32
  def generate_ghibli_style(
33
  input_image: Image.Image,
34
  steps: int = 25,
35
  strength: float = 0.6,
36
+ guidance_scale: float = 7.5
37
+ ) -> Generator[Image.Image, None, None]:
38
+ """Generator that yields intermediate images at each diffusion step."""
39
+ prompt = "ghibli style, detailed anime portrait, studio ghibli, anime artwork"
40
+ negative_prompt = "blurry, low quality, sketch, cartoon, 3d, deformed, disfigured"
41
+
42
+ # Preprocess image
43
+ input_image = resize_and_crop(input_image)
44
+ init_image = input_image.convert("RGB")
45
+
46
+ # Prepare latent variables
47
+ init_image = pipe.image_processor.preprocess(init_image)
48
+ init_latents = pipe.vae.encode(init_image.to(device)).latent_dist.sample()
49
+ init_latents = pipe.vae.config.scaling_factor * init_latents
50
+
51
+ # Prepare scheduler
52
+ pipe.scheduler.set_timesteps(steps, device=device)
53
+ timesteps = pipe.scheduler.timesteps[int(steps * strength):]
54
+ noise = torch.randn_like(init_latents)
55
+ latents = pipe.scheduler.add_noise(init_latents, noise, timesteps[:1])
56
+
57
+ # Prepare text embeddings
58
+ text_inputs = pipe.tokenizer(
59
+ prompt,
60
+ padding="max_length",
61
+ max_length=pipe.tokenizer.model_max_length,
62
+ return_tensors="pt"
63
+ )
64
+ text_embeddings = pipe.text_encoder(text_inputs.input_ids.to(device))[0]
65
+
66
+ # Unconditional embedding
67
+ uncond_input = pipe.tokenizer(
68
+ [negative_prompt] * init_image.shape[0],
69
+ padding="max_length",
70
+ max_length=text_embeddings.shape[1],
71
+ return_tensors="pt"
72
+ )
73
+ uncond_embeddings = pipe.text_encoder(uncond_input.input_ids.to(device))[0]
74
+
75
+ # Classifier-free guidance
76
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
77
+
78
+ # Diffusion process
79
+ for i, t in enumerate(gr.Progress().tqdm(timesteps, desc="Generating")):
80
+ # Expand latents for classifier-free guidance
81
+ latent_model_input = torch.cat([latents] * 2)
82
+ latent_model_input = pipe.scheduler.scale_model_input(latent_model_input, t)
83
+
84
+ # Predict noise
85
+ noise_pred = pipe.unet(
86
+ latent_model_input,
87
+ t,
88
+ encoder_hidden_states=text_embeddings
89
+ ).sample
90
+
91
+ # Perform guidance
92
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
93
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
94
 
95
+ # Compute previous step
96
+ latents = pipe.scheduler.step(noise_pred, t, latents).prev_sample
97
+
98
+ # Decode and yield image
99
  with torch.no_grad():
100
+ image = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict=False)[0]
101
+ image = pipe.image_processor.postprocess(image, output_type="pil")[0]
102
+
103
+ yield image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  # Gradio interface
106
+ with gr.Blocks() as demo:
107
+ gr.Markdown("# ✨ Studio Ghibli Style Transformer ✨")
108
+ gr.Markdown("Upload a portrait photo to transform it into a Studio Ghibli-style artwork!")
109
 
110
  with gr.Row():
111
  with gr.Column():
112
+ input_image = gr.Image(label="Input Image", type="pil")
113
+ steps_slider = gr.Slider(10, 50, value=25, label="Number of Steps")
114
+ strength_slider = gr.Slider(0.1, 0.9, value=0.6, label="Transformation Strength")
115
+ generate_btn = gr.Button("✨ Transform!", variant="primary")
116
 
117
  with gr.Column():
118
  gallery = gr.Gallery(
119
  label="Generation Progress",
120
  show_label=True,
121
+ columns=5,
122
+ preview=True,
123
+ object_fit="contain",
124
+ height=600
125
  )
126
+
 
 
 
 
 
 
 
 
 
 
127
  generate_btn.click(
128
  fn=generate_ghibli_style,
129
  inputs=[input_image, steps_slider, strength_slider],
130
+ outputs=gallery,
131
+ concurrency_limit=1
132
+ )
133
+
134
+ gr.Examples(
135
+ examples=["example1.jpg", "example2.jpg"],
136
+ inputs=input_image,
137
+ outputs=gallery,
138
+ fn=generate_ghibli_style,
139
+ cache_examples=True
140
  )
141
 
 
142
  if __name__ == "__main__":
143
+
144
+ demo.launch()