fantos commited on
Commit
d32dc63
·
verified ·
1 Parent(s): 210bfc3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -149
app.py CHANGED
@@ -8,16 +8,18 @@ import torch
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
 
12
  # Import with proper error handling
13
  try:
14
- from diffusers import DiffusionPipeline
15
  from diffusers.models import FluxTransformer2DModel
16
  from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
17
  from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
18
  except ImportError as e:
19
  print(f"Import error: {e}")
20
- # Fallback to DiffusionPipeline if FluxPipeline is not available
21
  from diffusers import DiffusionPipeline
22
 
23
  torch.backends.cuda.matmul.allow_tf32 = True
@@ -35,23 +37,36 @@ class timer:
35
  if not path.exists(cache_path):
36
  os.makedirs(cache_path, exist_ok=True)
37
 
38
- # Use DiffusionPipeline as a more stable alternative
39
  try:
40
- # Try to load as FluxPipeline first
41
- pipe = DiffusionPipeline.from_pretrained(
 
42
  "black-forest-labs/FLUX.1-dev",
43
  torch_dtype=torch.bfloat16,
44
  use_safetensors=True
45
  )
 
46
  except Exception as e:
47
- print(f"Error loading FLUX pipeline: {e}")
48
- # Fallback to a simpler configuration
49
- pipe = DiffusionPipeline.from_pretrained(
50
- "black-forest-labs/FLUX.1-dev",
51
- torch_dtype=torch.float16,
52
- safety_checker=None,
53
- requires_safety_checker=False
54
- )
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  # Try to load LoRA weights with error handling
57
  try:
@@ -59,161 +74,64 @@ try:
59
  lora_path = hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors")
60
  pipe.load_lora_weights(lora_path)
61
  pipe.fuse_lora(lora_scale=0.125)
 
62
  except Exception as e:
63
  print(f"Warning: Could not load LoRA weights: {e}")
64
  print("Continuing without LoRA acceleration...")
65
 
66
- pipe.to(device="cuda", dtype=torch.bfloat16)
67
-
68
- # Define example prompts
69
- example_prompts = [
70
- "A cyberpunk cityscape at night with neon lights reflecting in puddles, towering skyscrapers and flying cars",
71
- "An ethereal fairy with translucent iridescent wings standing in an enchanted forest with glowing mushrooms and floating light particles",
72
- "A majestic dragon soaring through stormy clouds above jagged mountain peaks as lightning strikes in the background",
73
- "A futuristic space station orbiting a vibrant nebula with multiple colorful ringed planets visible through a massive observation window",
74
- "An underwater scene of an ancient lost city with ornate temples and statues covered in bioluminescent coral and swimming sea creatures"
75
- ]
76
-
77
- # Custom CSS for neon theme
78
- css = """
79
- .neon-container {
80
- background: linear-gradient(to right, #000428, #004e92);
81
- border-radius: 16px;
82
- box-shadow: 0 0 15px #00f3ff, 0 0 25px #00f3ff;
83
- }
84
- .neon-title {
85
- text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 15px #0073e6, 0 0 20px #0073e6, 0 0 25px #0073e6;
86
- color: #ffffff;
87
- font-weight: bold !important;
88
- }
89
- .neon-text {
90
- color: #00ff9d;
91
- text-shadow: 0 0 5px #00ff9d;
92
- }
93
- .neon-button {
94
- box-shadow: 0 0 5px #ff00dd, 0 0 10px #ff00dd !important;
95
- background: linear-gradient(90deg, #ff00dd, #8b00ff) !important;
96
- border: none !important;
97
- color: white !important;
98
- font-weight: bold !important;
99
- }
100
- .neon-button:hover {
101
- box-shadow: 0 0 10px #ff00dd, 0 0 20px #ff00dd !important;
102
- }
103
- .neon-input {
104
- border: 1px solid #00f3ff !important;
105
- box-shadow: 0 0 5px #00f3ff !important;
106
- }
107
- .neon-slider > div {
108
- background: linear-gradient(90deg, #00ff9d, #00f3ff) !important;
109
- }
110
- .neon-slider > div > div {
111
- background: #ff00dd !important;
112
- box-shadow: 0 0 5px #ff00dd !important;
113
- }
114
- .neon-card {
115
- background-color: rgba(0, 0, 0, 0.7) !important;
116
- border: 1px solid #00f3ff !important;
117
- box-shadow: 0 0 10px #00f3ff !important;
118
- padding: 16px !important;
119
- border-radius: 8px !important;
120
- }
121
- .neon-example {
122
- background: rgba(0, 0, 0, 0.5) !important;
123
- border: 1px solid #00ff9d !important;
124
- border-radius: 8px !important;
125
- padding: 8px !important;
126
- color: #00ff9d !important;
127
- box-shadow: 0 0 5px #00ff9d !important;
128
- margin: 4px !important;
129
- cursor: pointer !important;
130
- }
131
- .neon-example:hover {
132
- box-shadow: 0 0 10px #00ff9d, 0 0 15px #00ff9d !important;
133
- background: rgba(0, 255, 157, 0.2) !important;
134
- }
135
- """
136
 
137
- with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
138
- with gr.Blocks(elem_classes=["neon-container"]):
139
- gr.Markdown(
140
- """
141
- <div style="text-align: center; max-width: 650px; margin: 0 auto;">
142
- <h1 style="font-size: 3rem; font-weight: 700; margin-bottom: 1rem; display: contents;" class="neon-title">FLUX: Fast & Furious</h1>
143
- <p style="font-size: 1.2rem; margin-bottom: 1.5rem;" class="neon-text">AutoML team from ByteDance</p>
144
- </div>
145
- """
146
- )
147
-
148
- gr.HTML(
149
  """
150
- <div class='container' style='display:flex; justify-content:center; gap:12px;'>
151
- <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
152
- <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">
153
- </a>
154
-
155
- <a href="https://discord.gg/openfreeai" target="_blank">
156
- <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">
157
- </a>
158
  </div>
159
  """
160
  )
161
-
162
  with gr.Row():
163
- with gr.Column(scale=3, elem_classes=["neon-card"]):
164
  with gr.Group():
165
  prompt = gr.Textbox(
166
  label="Your Image Description",
167
  placeholder="E.g., A serene landscape with mountains and a lake at sunset",
168
- lines=3,
169
- elem_classes=["neon-input"]
170
  )
171
 
172
- # Examples section
173
- gr.Markdown('<p class="neon-text">Click on any example to use it:</p>')
174
- with gr.Row():
175
- example_boxes = [gr.Button(ex[:40] + "...", elem_classes=["neon-example"]) for ex in example_prompts]
176
-
177
- # Connect example buttons to the prompt textbox
178
- for i, example_btn in enumerate(example_boxes):
179
- example_btn.click(
180
- fn=lambda x=example_prompts[i]: x,
181
- outputs=prompt
182
- )
183
-
184
  with gr.Accordion("Advanced Settings", open=False):
185
  with gr.Group():
186
  with gr.Row():
187
- height = gr.Slider(label="Height", minimum=256, maximum=1152, step=64, value=1024,
188
- elem_classes=["neon-slider"])
189
- width = gr.Slider(label="Width", minimum=256, maximum=1152, step=64, value=1024,
190
- elem_classes=["neon-slider"])
191
 
192
  with gr.Row():
193
- steps = gr.Slider(label="Inference Steps", minimum=6, maximum=25, step=1, value=8,
194
- elem_classes=["neon-slider"])
195
- scales = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=5.0, step=0.1, value=3.5,
196
- elem_classes=["neon-slider"])
197
 
198
- seed = gr.Number(label="Seed (for reproducibility)", value=3413, precision=0,
199
- elem_classes=["neon-input"])
200
 
201
- generate_btn = gr.Button("Generate Image", variant="primary", scale=1, elem_classes=["neon-button"])
202
 
203
- with gr.Column(scale=4, elem_classes=["neon-card"]):
204
  output = gr.Image(label="Your Generated Image")
205
 
206
  gr.Markdown(
207
  """
208
- <div style="max-width: 650px; margin: 2rem auto; padding: 1rem; border-radius: 10px;" class="neon-card">
209
- <h2 style="font-size: 1.5rem; margin-bottom: 1rem;" class="neon-text">How to Use</h2>
210
- <ol style="padding-left: 1.5rem; color: #00f3ff;">
211
  <li>Enter a detailed description of the image you want to create.</li>
212
- <li>Or click one of our exciting example prompts above!</li>
213
  <li>Adjust advanced settings if desired (tap to expand).</li>
214
  <li>Tap "Generate Image" and wait for your creation!</li>
215
  </ol>
216
- <p style="margin-top: 1rem; font-style: italic; color: #ff00dd;">Tip: Be specific in your description for best results!</p>
217
  </div>
218
  """
219
  )
@@ -223,7 +141,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
223
  global pipe
224
  with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16), timer("inference"):
225
  try:
226
- # Try the standard call
227
  result = pipe(
228
  prompt=[prompt],
229
  generator=torch.Generator().manual_seed(int(seed)),
@@ -233,18 +151,32 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
233
  width=int(width),
234
  max_sequence_length=256
235
  )
236
- except TypeError:
237
- # Fallback for different pipeline signatures
238
- result = pipe(
239
- prompt=prompt,
240
- generator=torch.Generator().manual_seed(int(seed)),
241
- num_inference_steps=int(steps),
242
- guidance_scale=float(scales),
243
- height=int(height),
244
- width=int(width)
245
- )
246
-
247
- return result.images[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
249
  generate_btn.click(
250
  process_image,
 
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
 
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:
 
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
  )
 
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)),
 
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,