yeshog50 commited on
Commit
033fe26
·
verified ·
1 Parent(s): 2235066

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -124
app.py CHANGED
@@ -2,42 +2,58 @@ import os
2
  import random
3
  import gradio as gr
4
  import torch
5
- from diffusers import StableDiffusionPipeline, LCMScheduler
6
- from huggingface_hub import hf_hub_download
7
 
8
- # Configuration
9
- MODEL_ID = "segmind/SSD-1B"
10
- LORA_ID = "latent-consistency/lcm-lora-ssd-1b"
11
  MODEL_CACHE = "model_cache"
12
  os.makedirs(MODEL_CACHE, exist_ok=True)
13
 
14
- # Initialize the pipeline with optimizations
15
  def get_pipeline():
16
- # Load base model
17
- pipe = StableDiffusionPipeline.from_pretrained(
18
  MODEL_ID,
19
- torch_dtype=torch.float32,
20
  cache_dir=MODEL_CACHE,
21
- safety_checker=None,
22
- use_safetensors=True
 
 
 
 
 
23
  )
24
 
25
- # Apply LCM-LoRA for 4-8x faster generation
26
- lcm_lora_path = hf_hub_download(
27
- LORA_ID,
28
- "lora_layers.safetensors",
29
  cache_dir=MODEL_CACHE
30
  )
31
- pipe.load_lora_weights(lcm_lora_path)
32
- pipe.fuse_lora()
33
 
34
- # Configure scheduler
35
- pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  # CPU optimizations
38
  pipe = pipe.to("cpu")
39
  pipe.enable_attention_slicing()
40
- pipe.enable_model_cpu_offload()
41
 
42
  return pipe
43
 
@@ -50,15 +66,13 @@ def generate_image(
50
  width: int = 768,
51
  height: int = 768,
52
  seed: int = -1,
53
- guidance_scale: float = 2.0, # Lower for LCM
54
- num_inference_steps: int = 8 # Only 4-8 steps needed
55
  ):
56
- # Handle seed
57
  if seed == -1:
58
  seed = random.randint(0, 2147483647)
59
  generator = torch.Generator(device="cpu").manual_seed(seed)
60
 
61
- # Generate image
62
  with torch.no_grad():
63
  image = pipeline(
64
  prompt=prompt,
@@ -67,118 +81,36 @@ def generate_image(
67
  height=height,
68
  guidance_scale=guidance_scale,
69
  num_inference_steps=num_inference_steps,
70
- generator=generator,
71
- output_type="pil"
72
  ).images[0]
73
 
74
  return image, seed
75
 
76
- # Professional enhancement presets
77
- ENHANCEMENTS = {
78
- "Ultra Realistic": "masterpiece, best quality, ultra detailed, 8k",
79
- "Cinematic": "cinematic lighting, film grain, depth of field",
80
- "Digital Art": "concept art, digital painting, sharp focus",
81
- "Photorealistic": "photorealistic, DSLR, f/1.8, natural lighting"
82
- }
83
-
84
- def apply_enhancement(prompt, enhancement):
85
- return f"{ENHANCEMENTS[enhancement]}, {prompt}"
86
-
87
- # Create professional interface
88
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="teal")) as demo:
89
- gr.Markdown("""
90
- # 🚀 FLUX Pro Image Generator
91
- **Professional Quality Images · Lightning Fast on CPU**
92
- *Powered by SSD-1B with LCM-LoRA technology*
93
- """)
94
 
95
  with gr.Row():
96
- with gr.Column(scale=3):
97
- with gr.Group():
98
- prompt = gr.Textbox(
99
- label="Prompt",
100
- placeholder="Describe the image you want to create...",
101
- lines=3,
102
- elem_id="prompt-box"
103
- )
104
- enhancement = gr.Dropdown(
105
- label="Quality Enhancement",
106
- choices=list(ENHANCEMENTS.keys()),
107
- value="Ultra Realistic"
108
- )
109
- negative_prompt = gr.Textbox(
110
- label="Negative Prompt",
111
- placeholder="What to exclude from the image...",
112
- value="low quality, blurry, cartoon, drawing, sketch"
113
- )
114
-
115
- generate_btn = gr.Button("Generate Image", variant="primary", size="lg")
116
 
117
- with gr.Accordion("Advanced Settings", open=False):
118
- with gr.Row():
119
- width = gr.Slider(512, 1024, value=768, step=64, label="Width")
120
- height = gr.Slider(512, 1024, value=768, step=64, label="Height")
121
- with gr.Row():
122
- guidance = gr.Slider(1.0, 5.0, value=2.0, step=0.1, label="Guidance Scale")
123
- steps = gr.Slider(4, 12, value=8, step=1, label="Generation Steps")
124
  seed = gr.Number(label="Seed", value=-1)
125
 
126
- with gr.Column(scale=2):
127
- output_image = gr.Image(
128
- label="Generated Image",
129
- type="pil",
130
- elem_id="output-image",
131
- height=500
132
- )
133
- with gr.Group():
134
- used_seed = gr.Textbox(label="Used Seed", interactive=False)
135
- gr.Markdown("**Tip:** For best results, use detailed descriptive prompts")
136
-
137
- # Enhancement application
138
- enhancement.change(
139
- fn=apply_enhancement,
140
- inputs=[prompt, enhancement],
141
- outputs=prompt
142
- )
143
-
144
- # Generation handler
145
  generate_btn.click(
146
- fn=generate_image,
147
  inputs=[prompt, negative_prompt, width, height, seed, guidance, steps],
148
  outputs=[output_image, used_seed]
149
  )
150
-
151
- # Professional examples
152
- gr.Examples(
153
- examples=[
154
- [
155
- "A futuristic cityscape at twilight, towering skyscrapers with neon lights reflecting on wet streets",
156
- "Ultra Realistic",
157
- "low quality, cartoon, drawing, blurry",
158
- 768,
159
- 768
160
- ],
161
- [
162
- "Portrait of a cyberpunk samurai warrior, intricate armor with glowing circuits, detailed face",
163
- "Cinematic",
164
- "anime, cartoon, sketch, simple background",
165
- 768,
166
- 1024
167
- ],
168
- [
169
- "Majestic fantasy castle floating in the clouds, golden sunlight, hyperdetailed",
170
- "Digital Art",
171
- "photograph, realistic, photo",
172
- 1024,
173
- 768
174
- ]
175
- ],
176
- inputs=[prompt, enhancement, negative_prompt, width, height],
177
- label="Professional Examples"
178
- )
179
 
180
- # Launch the app
181
  if __name__ == "__main__":
182
- demo.queue(max_size=10).launch(
183
- server_name="0.0.0.0",
184
- server_port=int(os.getenv("PORT", 7860))
 
2
  import random
3
  import gradio as gr
4
  import torch
5
+ from diffusers import DiffusionPipeline, UNet2DConditionModel
6
+ from transformers import CLIPTextModel, CLIPTokenizer
7
 
8
+ # Configuration - Using Flux Model
9
+ MODEL_ID = "CompVis/Flux-Pro"
10
+ LORA_ID = "flux/lora-weights"
11
  MODEL_CACHE = "model_cache"
12
  os.makedirs(MODEL_CACHE, exist_ok=True)
13
 
 
14
  def get_pipeline():
15
+ # Load Flux components
16
+ unet = UNet2DConditionModel.from_pretrained(
17
  MODEL_ID,
18
+ subfolder="unet",
19
  cache_dir=MODEL_CACHE,
20
+ torch_dtype=torch.float32
21
+ )
22
+
23
+ text_encoder = CLIPTextModel.from_pretrained(
24
+ MODEL_ID,
25
+ subfolder="text_encoder",
26
+ cache_dir=MODEL_CACHE
27
  )
28
 
29
+ tokenizer = CLIPTokenizer.from_pretrained(
30
+ MODEL_ID,
31
+ subfolder="tokenizer",
 
32
  cache_dir=MODEL_CACHE
33
  )
 
 
34
 
35
+ # Create pipeline
36
+ pipe = DiffusionPipeline.from_pretrained(
37
+ MODEL_ID,
38
+ unet=unet,
39
+ text_encoder=text_encoder,
40
+ tokenizer=tokenizer,
41
+ cache_dir=MODEL_CACHE,
42
+ torch_dtype=torch.float32,
43
+ safety_checker=None
44
+ )
45
+
46
+ # Load LoRA weights
47
+ lora_path = hf_hub_download(
48
+ LORA_ID,
49
+ "flux_lora.safetensors",
50
+ cache_dir=MODEL_CACHE
51
+ )
52
+ pipe.unet.load_attn_procs(lora_path)
53
 
54
  # CPU optimizations
55
  pipe = pipe.to("cpu")
56
  pipe.enable_attention_slicing()
 
57
 
58
  return pipe
59
 
 
66
  width: int = 768,
67
  height: int = 768,
68
  seed: int = -1,
69
+ guidance_scale: float = 7.5,
70
+ num_inference_steps: int = 25
71
  ):
 
72
  if seed == -1:
73
  seed = random.randint(0, 2147483647)
74
  generator = torch.Generator(device="cpu").manual_seed(seed)
75
 
 
76
  with torch.no_grad():
77
  image = pipeline(
78
  prompt=prompt,
 
81
  height=height,
82
  guidance_scale=guidance_scale,
83
  num_inference_steps=num_inference_steps,
84
+ generator=generator
 
85
  ).images[0]
86
 
87
  return image, seed
88
 
89
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
90
+ gr.Markdown("# 🌀 FLUX-Pro Image Generator")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  with gr.Row():
93
+ with gr.Column():
94
+ prompt = gr.Textbox(label="Prompt", lines=3)
95
+ negative_prompt = gr.Textbox(label="Negative Prompt", value="blurry, low quality")
96
+ generate_btn = gr.Button("Generate", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
+ with gr.Accordion("Advanced", open=False):
99
+ width = gr.Slider(512, 1024, value=768, step=64, label="Width")
100
+ height = gr.Slider(512, 1024, value=768, step=64, label="Height")
101
+ guidance = gr.Slider(1.0, 15.0, value=7.5, step=0.5, label="Guidance")
102
+ steps = gr.Slider(15, 50, value=25, step=1, label="Steps")
 
 
103
  seed = gr.Number(label="Seed", value=-1)
104
 
105
+ with gr.Column():
106
+ output_image = gr.Image(label="Result", type="pil")
107
+ used_seed = gr.Textbox(label="Used Seed")
108
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  generate_btn.click(
110
+ generate_image,
111
  inputs=[prompt, negative_prompt, width, height, seed, guidance, steps],
112
  outputs=[output_image, used_seed]
113
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
 
115
  if __name__ == "__main__":
116
+ demo.launch()