fantos commited on
Commit
06d2a79
ยท
verified ยท
1 Parent(s): d32dc63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -146
app.py CHANGED
@@ -1,26 +1,19 @@
1
  import spaces
 
2
  import os
3
  import time
4
  from os import path
5
- import gradio as gr
6
- import torch
7
 
8
- # Set cache paths before importing transformers/diffusers
9
  cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
10
- os.environ["HF_HOME"] = cache_path
11
  os.environ["TRANSFORMERS_CACHE"] = cache_path
12
  os.environ["HF_HUB_CACHE"] = cache_path
 
13
 
14
- # Import with proper error handling
15
- try:
16
- from diffusers import DiffusionPipeline, FluxPipeline
17
- from diffusers.models import FluxTransformer2DModel
18
- from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
19
- from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
20
- except ImportError as e:
21
- print(f"Import error: {e}")
22
- # Fallback to DiffusionPipeline if specific components are not available
23
- from diffusers import DiffusionPipeline
24
 
25
  torch.backends.cuda.matmul.allow_tf32 = True
26
 
@@ -37,146 +30,211 @@ class timer:
37
  if not path.exists(cache_path):
38
  os.makedirs(cache_path, exist_ok=True)
39
 
40
- # Load pipeline with robust error handling
41
- try:
42
- # First attempt: Try to load as FluxPipeline
43
- from diffusers import FluxPipeline
44
- pipe = FluxPipeline.from_pretrained(
45
- "black-forest-labs/FLUX.1-dev",
46
- torch_dtype=torch.bfloat16,
47
- use_safetensors=True
48
- )
49
- print("Successfully loaded FluxPipeline")
50
- except Exception as e:
51
- print(f"Error loading FluxPipeline: {e}")
52
- # Fallback: Use DiffusionPipeline with simpler configuration
53
- try:
54
- pipe = DiffusionPipeline.from_pretrained(
55
- "black-forest-labs/FLUX.1-dev",
56
- torch_dtype=torch.bfloat16,
57
- use_safetensors=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  )
59
- print("Successfully loaded DiffusionPipeline with bfloat16")
60
- except Exception as e2:
61
- print(f"Error with bfloat16: {e2}")
62
- # Final fallback: Use float16 without safety checker
63
- pipe = DiffusionPipeline.from_pretrained(
64
- "black-forest-labs/FLUX.1-dev",
65
- torch_dtype=torch.float16,
66
- safety_checker=None,
67
- requires_safety_checker=False
 
 
 
 
68
  )
69
- print("Successfully loaded DiffusionPipeline with float16")
70
-
71
- # Try to load LoRA weights with error handling
72
- try:
73
- from huggingface_hub import hf_hub_download
74
- lora_path = hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors")
75
- pipe.load_lora_weights(lora_path)
76
- pipe.fuse_lora(lora_scale=0.125)
77
- print("Successfully loaded and fused LoRA weights")
78
- except Exception as e:
79
- print(f"Warning: Could not load LoRA weights: {e}")
80
- print("Continuing without LoRA acceleration...")
81
-
82
- # Move to GPU with error handling
83
- try:
84
- pipe.to(device="cuda", dtype=torch.bfloat16)
85
- except Exception as e:
86
- print(f"Error moving to bfloat16: {e}")
87
- pipe.to(device="cuda", dtype=torch.float16)
88
-
89
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
90
- gr.Markdown(
91
- """
92
- <div style="text-align: center; max-width: 650px; margin: 0 auto;">
93
- <h1 style="font-size: 2.5rem; font-weight: 700; margin-bottom: 1rem; display: contents;">Hyper-FLUX-8steps-LoRA</h1>
94
- <p style="font-size: 1rem; margin-bottom: 1.5rem;">AutoML team from ByteDance</p>
95
- </div>
96
- """
97
- )
98
 
99
- with gr.Row():
100
- with gr.Column(scale=3):
101
- with gr.Group():
102
- prompt = gr.Textbox(
103
- label="Your Image Description",
104
- placeholder="E.g., A serene landscape with mountains and a lake at sunset",
105
- lines=3
106
- )
107
-
108
- with gr.Accordion("Advanced Settings", open=False):
109
- with gr.Group():
110
- with gr.Row():
111
- height = gr.Slider(label="Height", minimum=256, maximum=1152, step=64, value=1024)
112
- width = gr.Slider(label="Width", minimum=256, maximum=1152, step=64, value=1024)
113
-
114
- with gr.Row():
115
- steps = gr.Slider(label="Inference Steps", minimum=6, maximum=25, step=1, value=8)
116
- scales = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=5.0, step=0.1, value=3.5)
117
-
118
- seed = gr.Number(label="Seed (for reproducibility)", value=3413, precision=0)
119
-
120
- generate_btn = gr.Button("Generate Image", variant="primary", scale=1)
121
-
122
- with gr.Column(scale=4):
123
- output = gr.Image(label="Your Generated Image")
124
-
125
- gr.Markdown(
126
- """
127
- <div style="max-width: 650px; margin: 2rem auto; padding: 1rem; border-radius: 10px; background-color: #f0f0f0;">
128
- <h2 style="font-size: 1.5rem; margin-bottom: 1rem;">How to Use</h2>
129
- <ol style="padding-left: 1.5rem;">
130
- <li>Enter a detailed description of the image you want to create.</li>
131
- <li>Adjust advanced settings if desired (tap to expand).</li>
132
- <li>Tap "Generate Image" and wait for your creation!</li>
133
- </ol>
134
- <p style="margin-top: 1rem; font-style: italic;">Tip: Be specific in your description for best results!</p>
135
- </div>
136
- """
137
- )
 
 
138
 
139
  @spaces.GPU
140
  def process_image(height, width, steps, scales, prompt, seed):
141
  global pipe
142
  with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16), timer("inference"):
143
- try:
144
- # Try the standard call with list prompt
145
- result = pipe(
146
- prompt=[prompt],
147
- generator=torch.Generator().manual_seed(int(seed)),
148
- num_inference_steps=int(steps),
149
- guidance_scale=float(scales),
150
- height=int(height),
151
- width=int(width),
152
- max_sequence_length=256
153
- )
154
- return result.images[0]
155
- except TypeError as e:
156
- print(f"TypeError with list prompt: {e}")
157
- # Fallback for different pipeline signatures (string prompt)
158
- try:
159
- result = pipe(
160
- prompt=prompt,
161
- generator=torch.Generator().manual_seed(int(seed)),
162
- num_inference_steps=int(steps),
163
- guidance_scale=float(scales),
164
- height=int(height),
165
- width=int(width)
166
- )
167
- return result.images[0]
168
- except Exception as e2:
169
- print(f"Error in fallback: {e2}")
170
- # Final fallback without max_sequence_length
171
- result = pipe(
172
- prompt=prompt,
173
- generator=torch.Generator("cuda").manual_seed(int(seed)),
174
- num_inference_steps=int(steps),
175
- guidance_scale=float(scales),
176
- height=int(height),
177
- width=int(width)
178
- )
179
- return result.images[0]
180
 
181
  generate_btn.click(
182
  process_image,
 
1
  import spaces
2
+ import argparse
3
  import os
4
  import time
5
  from os import path
6
+ from safetensors.torch import load_file
7
+ from huggingface_hub import hf_hub_download
8
 
 
9
  cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
 
10
  os.environ["TRANSFORMERS_CACHE"] = cache_path
11
  os.environ["HF_HUB_CACHE"] = cache_path
12
+ os.environ["HF_HOME"] = cache_path
13
 
14
+ import gradio as gr
15
+ import torch
16
+ from diffusers import FluxPipeline
 
 
 
 
 
 
 
17
 
18
  torch.backends.cuda.matmul.allow_tf32 = True
19
 
 
30
  if not path.exists(cache_path):
31
  os.makedirs(cache_path, exist_ok=True)
32
 
33
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
34
+ pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"))
35
+ pipe.fuse_lora(lora_scale=0.125)
36
+ pipe.to(device="cuda", dtype=torch.bfloat16)
37
+
38
+ # Custom CSS for gradient effects and visual enhancements
39
+ custom_css = """
40
+ .container {
41
+ max-width: 1200px;
42
+ margin: 0 auto;
43
+ padding: 20px;
44
+ }
45
+
46
+ .gradio-container {
47
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
48
+ min-height: 100vh;
49
+ }
50
+
51
+ .main-content {
52
+ background: rgba(255, 255, 255, 0.95);
53
+ border-radius: 20px;
54
+ padding: 30px;
55
+ box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
56
+ backdrop-filter: blur(10px);
57
+ }
58
+
59
+ h1 {
60
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
61
+ -webkit-background-clip: text;
62
+ -webkit-text-fill-color: transparent;
63
+ background-clip: text;
64
+ text-align: center;
65
+ font-size: 3rem !important;
66
+ font-weight: 800 !important;
67
+ margin-bottom: 1rem !important;
68
+ text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
69
+ }
70
+
71
+ .subtitle {
72
+ text-align: center;
73
+ color: #666;
74
+ font-size: 1.2rem;
75
+ margin-bottom: 2rem;
76
+ }
77
+
78
+ .gr-button-primary {
79
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
80
+ border: none !important;
81
+ color: white !important;
82
+ font-weight: bold !important;
83
+ font-size: 1.1rem !important;
84
+ padding: 12px 30px !important;
85
+ border-radius: 10px !important;
86
+ transition: all 0.3s ease !important;
87
+ box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important;
88
+ }
89
+
90
+ .gr-button-primary:hover {
91
+ transform: translateY(-2px) !important;
92
+ box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
93
+ }
94
+
95
+ .gr-input, .gr-box {
96
+ border-radius: 10px !important;
97
+ border: 2px solid #e0e0e0 !important;
98
+ transition: all 0.3s ease !important;
99
+ }
100
+
101
+ .gr-input:focus {
102
+ border-color: #667eea !important;
103
+ box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1) !important;
104
+ }
105
+
106
+ .gr-form {
107
+ background: white !important;
108
+ border-radius: 15px !important;
109
+ padding: 20px !important;
110
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05) !important;
111
+ }
112
+
113
+ .gr-padded {
114
+ padding: 15px !important;
115
+ }
116
+
117
+ .badge-container {
118
+ display: flex;
119
+ justify-content: center;
120
+ gap: 12px;
121
+ margin: 20px 0;
122
+ }
123
+
124
+ .how-to-use {
125
+ background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
126
+ border-radius: 15px;
127
+ padding: 25px;
128
+ margin-top: 30px;
129
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
130
+ }
131
+
132
+ .how-to-use h2 {
133
+ color: #667eea;
134
+ font-size: 1.8rem;
135
+ margin-bottom: 1rem;
136
+ }
137
+
138
+ .how-to-use ol {
139
+ color: #555;
140
+ line-height: 1.8;
141
+ }
142
+
143
+ .how-to-use li {
144
+ margin-bottom: 10px;
145
+ }
146
+
147
+ .tip {
148
+ background: rgba(102, 126, 234, 0.1);
149
+ border-left: 4px solid #667eea;
150
+ padding: 15px;
151
+ margin-top: 20px;
152
+ border-radius: 5px;
153
+ color: #555;
154
+ font-style: italic;
155
+ }
156
+ """
157
+
158
+ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
159
+ with gr.Column(elem_classes="main-content"):
160
+ gr.HTML(
161
+ """
162
+ <div style="text-align: center; max-width: 800px; margin: 0 auto;">
163
+ <h1>FLUX Fast & Furious</h1>
164
+ <p class="subtitle">Lightning-fast image generation powered by Hyper-FLUX LoRA</p>
165
+ </div>
166
+ """
167
  )
168
+
169
+ gr.HTML(
170
+ """
171
+ <div class='badge-container'>
172
+ <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
173
+ <img src="https://img.shields.io/static/v1?label=OpenFree&message=BEST%20AI%20Services&color=%230000ff&labelColor=%23000080&logo=huggingface&logoColor=%23ffa500&style=for-the-badge" alt="OpenFree badge">
174
+ </a>
175
+
176
+ <a href="https://discord.gg/openfreeai" target="_blank">
177
+ <img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge" alt="Discord badge">
178
+ </a>
179
+ </div>
180
+ """
181
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
+ with gr.Row():
184
+ with gr.Column(scale=3):
185
+ with gr.Group():
186
+ prompt = gr.Textbox(
187
+ label="โœจ Your Image Description",
188
+ placeholder="E.g., A serene landscape with mountains and a lake at sunset",
189
+ lines=3
190
+ )
191
+
192
+ with gr.Accordion("๐ŸŽจ Advanced Settings", open=False):
193
+ with gr.Group():
194
+ with gr.Row():
195
+ height = gr.Slider(label="Height", minimum=256, maximum=1152, step=64, value=1024)
196
+ width = gr.Slider(label="Width", minimum=256, maximum=1152, step=64, value=1024)
197
+
198
+ with gr.Row():
199
+ steps = gr.Slider(label="Inference Steps", minimum=6, maximum=25, step=1, value=8)
200
+ scales = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=5.0, step=0.1, value=3.5)
201
+
202
+ seed = gr.Number(label="Seed (for reproducibility)", value=3413, precision=0)
203
+
204
+ generate_btn = gr.Button("๐Ÿš€ Generate Image", variant="primary", scale=1)
205
+
206
+ with gr.Column(scale=4):
207
+ output = gr.Image(label="๐ŸŽจ Your Generated Image")
208
+
209
+ gr.HTML(
210
+ """
211
+ <div class="how-to-use">
212
+ <h2>๐Ÿ“– How to Use</h2>
213
+ <ol>
214
+ <li>โœ๏ธ Enter a detailed description of the image you want to create</li>
215
+ <li>โš™๏ธ Adjust advanced settings if desired (tap to expand)</li>
216
+ <li>๐ŸŽฏ Tap "Generate Image" and watch the magic happen!</li>
217
+ </ol>
218
+ <div class="tip">
219
+ ๐Ÿ’ก <strong>Pro Tip:</strong> Be specific in your description for best results! Include details about style, mood, colors, and composition.
220
+ </div>
221
+ </div>
222
+ """
223
+ )
224
 
225
  @spaces.GPU
226
  def process_image(height, width, steps, scales, prompt, seed):
227
  global pipe
228
  with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16), timer("inference"):
229
+ return pipe(
230
+ prompt=[prompt],
231
+ generator=torch.Generator().manual_seed(int(seed)),
232
+ num_inference_steps=int(steps),
233
+ guidance_scale=float(scales),
234
+ height=int(height),
235
+ width=int(width),
236
+ max_sequence_length=256
237
+ ).images[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
 
239
  generate_btn.click(
240
  process_image,