pradeep6kumar2024 commited on
Commit
be16ca0
·
1 Parent(s): f9270e9
Files changed (1) hide show
  1. app.py +86 -12
app.py CHANGED
@@ -5,6 +5,7 @@ from huggingface_hub import hf_hub_download
5
  import numpy as np
6
  from PIL import Image
7
  import os
 
8
 
9
  # Suppress symlink warnings
10
  os.environ['HF_HUB_DISABLE_SYMLINKS_WARNING'] = "1"
@@ -38,15 +39,26 @@ styles = {
38
  }
39
  }
40
 
 
 
 
 
 
 
 
41
  def load_pipeline():
42
  """Load and prepare the pipeline with all style embeddings"""
43
  # Check if CUDA is available
44
  device = "cuda" if torch.cuda.is_available() else "cpu"
45
  dtype = torch.float16 if device == "cuda" else torch.float32
46
 
 
 
 
47
  pipe = StableDiffusionPipeline.from_pretrained(
48
- "CompVis/stable-diffusion-v1-4",
49
- torch_dtype=dtype
 
50
  ).to(device)
51
 
52
  # Load all embeddings
@@ -69,6 +81,28 @@ def apply_purple_guidance(image, strength=0.5):
69
 
70
  def generate_image(prompt, style, seed, apply_guidance, guidance_strength=0.5):
71
  """Generate an image with selected style and optional purple guidance"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  if style not in styles:
73
  return None
74
 
@@ -82,20 +116,39 @@ def generate_image(prompt, style, seed, apply_guidance, guidance_strength=0.5):
82
  # Create styled prompt
83
  styled_prompt = f"{prompt} {style_info['token']}"
84
 
85
- # Generate image
86
- image = pipe(
87
- styled_prompt,
88
- generator=generator,
89
- guidance_scale=7.5,
90
- num_inference_steps=20
91
- ).images[0]
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  # Apply purple guidance if requested
94
  if apply_guidance:
95
  image = apply_purple_guidance(image, guidance_strength)
96
 
 
 
 
 
 
97
  return image
98
 
 
 
 
99
  # Initialize the pipeline globally
100
  print("Loading pipeline and embeddings...")
101
  pipe = load_pipeline()
@@ -113,14 +166,35 @@ demo = gr.Interface(
113
  outputs=gr.Image(label="Generated Image"),
114
  title="Style-Guided Image Generation with Purple Enhancement",
115
  description="""Generate images in different styles with optional purple color guidance.
116
- Choose a style, enter a prompt, and optionally apply purple color enhancement.""",
 
117
  examples=[
118
  ["A serene mountain landscape with a lake at sunset", "glitch", 42, True, 0.5],
119
  ["A magical forest at twilight", "anime80s", 789, True, 0.7],
120
  ["A cyberpunk city at night", "night", 456, False, 0.5],
121
  ],
122
- cache_examples=True
 
123
  )
124
 
125
  if __name__ == "__main__":
126
- demo.launch(share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import numpy as np
6
  from PIL import Image
7
  import os
8
+ import gc
9
 
10
  # Suppress symlink warnings
11
  os.environ['HF_HUB_DISABLE_SYMLINKS_WARNING'] = "1"
 
39
  }
40
  }
41
 
42
+ # Pre-generate example images
43
+ example_images = {
44
+ "glitch": "examples/glitch_example.jpg",
45
+ "anime80s": "examples/anime80s_example.jpg",
46
+ "night": "examples/night_example.jpg"
47
+ }
48
+
49
  def load_pipeline():
50
  """Load and prepare the pipeline with all style embeddings"""
51
  # Check if CUDA is available
52
  device = "cuda" if torch.cuda.is_available() else "cpu"
53
  dtype = torch.float16 if device == "cuda" else torch.float32
54
 
55
+ # Use smaller model for CPU
56
+ model_id = "runwayml/stable-diffusion-v1-5" if device == "cuda" else "CompVis/stable-diffusion-v1-4"
57
+
58
  pipe = StableDiffusionPipeline.from_pretrained(
59
+ model_id,
60
+ torch_dtype=dtype,
61
+ low_cpu_mem_usage=True
62
  ).to(device)
63
 
64
  # Load all embeddings
 
81
 
82
  def generate_image(prompt, style, seed, apply_guidance, guidance_strength=0.5):
83
  """Generate an image with selected style and optional purple guidance"""
84
+ # Check if this is one of our examples with pre-generated images
85
+ if prompt == "A serene mountain landscape with a lake at sunset" and style == "glitch" and seed == 42:
86
+ if os.path.exists(example_images["glitch"]):
87
+ image = Image.open(example_images["glitch"])
88
+ if apply_guidance:
89
+ image = apply_purple_guidance(image, guidance_strength)
90
+ return image
91
+
92
+ if prompt == "A magical forest at twilight" and style == "anime80s" and seed == 789:
93
+ if os.path.exists(example_images["anime80s"]):
94
+ image = Image.open(example_images["anime80s"])
95
+ if apply_guidance:
96
+ image = apply_purple_guidance(image, guidance_strength)
97
+ return image
98
+
99
+ if prompt == "A cyberpunk city at night" and style == "night" and seed == 456:
100
+ if os.path.exists(example_images["night"]):
101
+ image = Image.open(example_images["night"])
102
+ if apply_guidance:
103
+ image = apply_purple_guidance(image, guidance_strength)
104
+ return image
105
+
106
  if style not in styles:
107
  return None
108
 
 
116
  # Create styled prompt
117
  styled_prompt = f"{prompt} {style_info['token']}"
118
 
119
+ # Generate image with reduced settings for CPU
120
+ if device == "cpu":
121
+ # Use much smaller image size and fewer steps on CPU
122
+ image = pipe(
123
+ styled_prompt,
124
+ generator=generator,
125
+ guidance_scale=7.5,
126
+ num_inference_steps=10, # Reduced steps
127
+ height=256, # Smaller height
128
+ width=256 # Smaller width
129
+ ).images[0]
130
+ else:
131
+ image = pipe(
132
+ styled_prompt,
133
+ generator=generator,
134
+ guidance_scale=7.5,
135
+ num_inference_steps=20
136
+ ).images[0]
137
 
138
  # Apply purple guidance if requested
139
  if apply_guidance:
140
  image = apply_purple_guidance(image, guidance_strength)
141
 
142
+ # Clean up memory
143
+ gc.collect()
144
+ if device == "cuda":
145
+ torch.cuda.empty_cache()
146
+
147
  return image
148
 
149
+ # Create examples directory
150
+ os.makedirs("examples", exist_ok=True)
151
+
152
  # Initialize the pipeline globally
153
  print("Loading pipeline and embeddings...")
154
  pipe = load_pipeline()
 
166
  outputs=gr.Image(label="Generated Image"),
167
  title="Style-Guided Image Generation with Purple Enhancement",
168
  description="""Generate images in different styles with optional purple color guidance.
169
+ Choose a style, enter a prompt, and optionally apply purple color enhancement.
170
+ Note: Generation may take a few minutes on CPU.""",
171
  examples=[
172
  ["A serene mountain landscape with a lake at sunset", "glitch", 42, True, 0.5],
173
  ["A magical forest at twilight", "anime80s", 789, True, 0.7],
174
  ["A cyberpunk city at night", "night", 456, False, 0.5],
175
  ],
176
+ cache_examples=True,
177
+ allow_flagging="never" # Disable flagging to reduce overhead
178
  )
179
 
180
  if __name__ == "__main__":
181
+ # Generate and save example images if they don't exist
182
+ if not all(os.path.exists(path) for path in example_images.values()):
183
+ print("Pre-generating example images...")
184
+ # Example 1
185
+ if not os.path.exists(example_images["glitch"]):
186
+ img = generate_image("A serene mountain landscape with a lake at sunset", "glitch", 42, False, 0.5)
187
+ img.save(example_images["glitch"])
188
+
189
+ # Example 2
190
+ if not os.path.exists(example_images["anime80s"]):
191
+ img = generate_image("A magical forest at twilight", "anime80s", 789, False, 0.7)
192
+ img.save(example_images["anime80s"])
193
+
194
+ # Example 3
195
+ if not os.path.exists(example_images["night"]):
196
+ img = generate_image("A cyberpunk city at night", "night", 456, False, 0.5)
197
+ img.save(example_images["night"])
198
+
199
+ # Launch the app
200
+ demo.launch(share=False, show_error=True)