Walid-Ahmed commited on
Commit
e7039b9
·
verified ·
1 Parent(s): fdf862c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -57
app.py CHANGED
@@ -1,12 +1,36 @@
1
- import gradio as gr
2
  import torch
 
 
 
3
  from diffusers import DiffusionPipeline
4
 
5
- # Path for the LoRA model
6
  color_book_lora_path = "artificialguybr/ColoringBookRedmond-V2"
7
  color_book_trigger = ", ColoringBookAF, Coloring Book"
8
 
9
- # Predefined styles for users to choose from
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  styles = {
11
  "Neonpunk": {
12
  "prompt": "neonpunk style, cyberpunk, vaporwave, neon, vibrant, stunningly beautiful, crisp, "
@@ -31,68 +55,40 @@ styles = {
31
  }
32
  }
33
 
34
- # Cache the pipeline to avoid reloading it multiple times
35
- from functools import lru_cache
36
- @lru_cache(maxsize=1)
37
- def load_pipeline(use_lora: bool):
38
- """Load the diffusion pipeline with or without LoRA weights."""
39
- device = "cuda" if torch.cuda.is_available() else "cpu"
40
-
41
- # Load the base model
42
- pipe = DiffusionPipeline.from_pretrained(
43
- "stabilityai/stable-diffusion-xl-refiner-1.0",
44
- torch_dtype=torch.float16 if device == "cuda" else torch.float32,
45
- use_safetensors=True,
46
- variant="fp16" if device == "cuda" else None
47
- )
48
-
49
- # Apply LoRA weights if selected
50
- if use_lora:
51
- pipe.load_lora_weights(color_book_lora_path)
52
-
53
- return pipe
54
-
55
  def generate_image(prompt: str, style_name: str, use_lora: bool):
56
- """Generates an AI-generated image based on user input and selected style."""
57
- try:
58
- # Load the pre-trained pipeline
59
- pipeline = load_pipeline(use_lora)
 
 
 
60
 
61
- # Retrieve style prompts
62
- style_prompt = styles.get(style_name, {}).get("prompt", "")
63
- negative_prompt = styles.get(style_name, {}).get("negative_prompt", "")
64
 
65
- # Apply LoRA trigger phrase if selected
66
- if use_lora:
67
- prompt += color_book_trigger
68
 
69
- # Generate the image
70
- image = pipeline(
71
- prompt=prompt + " " + style_prompt,
72
- negative_prompt="blurred, ugly, watermark, low resolution, " + negative_prompt,
73
- num_inference_steps=20,
74
- guidance_scale=9.0
75
- ).images[0]
76
 
77
- return image
 
78
 
79
- except Exception as e:
80
- return f"Error generating image: {str(e)}"
81
 
82
- # Gradio UI
83
  interface = gr.Interface(
84
  fn=generate_image,
85
  inputs=[
86
  gr.Textbox(label="Enter Your Prompt", placeholder="A cute lion"),
87
- gr.Dropdown(label="Select a Style", choices=list(styles.keys()), value="None"),
88
- gr.Checkbox(label="Use Coloring Book LoRA", value=False)
89
- ],
90
- outputs=gr.Image(label="Generated Image"),
91
- title="🎨 AI Coloring Book & Style Generator",
92
- description="Generate amazing AI-powered art using Stable Diffusion XL. "
93
- "Choose a style or apply a Coloring Book LoRA for unique results."
94
- )
95
-
96
- # Run the Gradio interface
97
- if __name__ == "__main__":
98
- interface.launch()
 
 
1
  import torch
2
+ import gradio as gr
3
+ import spaces # Import spaces for ZeroGPU support
4
+ from functools import lru_cache
5
  from diffusers import DiffusionPipeline
6
 
7
+ # LoRA model path on Hugging Face Hub
8
  color_book_lora_path = "artificialguybr/ColoringBookRedmond-V2"
9
  color_book_trigger = ", ColoringBookAF, Coloring Book"
10
 
11
+ # Load model on CPU initially
12
+ @lru_cache(maxsize=1)
13
+ def load_pipeline(use_lora: bool):
14
+ """Load Stable Diffusion pipeline and LoRA weights (if selected)."""
15
+
16
+ # Load the base model
17
+ pipe = DiffusionPipeline.from_pretrained(
18
+ "stabilityai/stable-diffusion-xl-refiner-1.0",
19
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
20
+ use_safetensors=True,
21
+ variant="fp16" if torch.cuda.is_available() else None
22
+ )
23
+
24
+ # Keep the model on CPU until GPU is requested
25
+ pipe.to("cpu")
26
+
27
+ # Load LoRA if selected
28
+ if use_lora:
29
+ pipe.load_lora_weights(color_book_lora_path)
30
+
31
+ return pipe
32
+
33
+ # Define styles
34
  styles = {
35
  "Neonpunk": {
36
  "prompt": "neonpunk style, cyberpunk, vaporwave, neon, vibrant, stunningly beautiful, crisp, "
 
55
  }
56
  }
57
 
58
+ @spaces.GPU # ZeroGPU: Allocate GPU only when generating images
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  def generate_image(prompt: str, style_name: str, use_lora: bool):
60
+ """Generate an image using Stable Diffusion with optional LoRA fine-tuning."""
61
+
62
+ # Load the pipeline (cached)
63
+ pipeline = load_pipeline(use_lora)
64
+
65
+ # Move model to GPU only when needed
66
+ pipeline.to("cuda")
67
 
68
+ # Get the selected style details
69
+ style_prompt = styles.get(style_name, {}).get("prompt", "")
70
+ negative_prompt = styles.get(style_name, {}).get("negative_prompt", "")
71
 
72
+ # Apply LoRA trigger phrase if enabled
73
+ if use_lora:
74
+ prompt += color_book_trigger
75
 
76
+ # Generate image
77
+ image = pipeline(
78
+ prompt=prompt + " " + style_prompt,
79
+ negative_prompt="blurred, ugly, watermark, low resolution, " + negative_prompt,
80
+ num_inference_steps=20,
81
+ guidance_scale=9.0
82
+ ).images[0]
83
 
84
+ # Move model back to CPU to free GPU resources
85
+ pipeline.to("cpu")
86
 
87
+ return image
 
88
 
89
+ # Gradio Interface for Hugging Face Spaces (ZeroGPU-compatible)
90
  interface = gr.Interface(
91
  fn=generate_image,
92
  inputs=[
93
  gr.Textbox(label="Enter Your Prompt", placeholder="A cute lion"),
94
+ gr.Dropdown(label="Select a Style", choices=list(styles.keys()