aexyb commited on
Commit
722ceac
Β·
verified Β·
1 Parent(s): 6f8f51d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -319
app.py CHANGED
@@ -1,80 +1,15 @@
1
- #!/bin/bash
2
- set -e
3
-
4
- echo "=========================================="
5
- echo "πŸ“₯ DOWNLOADING MODELS (Build Phase)"
6
- echo "=========================================="
7
-
8
- mkdir -p models
9
-
10
- echo ""
11
- echo "Model: FLUX.2-klein-4B Q8_0"
12
- echo "Repo: unsloth/FLUX.2-klein-4B-GGUF"
13
- echo ""
14
-
15
- # Try possible filenames (HF repos sometimes rename files)
16
- POSSIBLE_NAMES=(
17
- "flux.2-klein-4b-Q8_0.gguf"
18
- "flux.2-klein-4b-Q8_0.gguf"
19
- "flux.2.klein.4b.Q8_0.gguf"
20
- "flux_2_klein_4b_Q8_0.gguf"
21
- "Flux.2-klein-4b-Q8_0.gguf"
22
- )
23
-
24
- DOWNLOADED=false
25
-
26
- for FILENAME in "${POSSIBLE_NAMES[@]}"; do
27
- echo "Trying: $FILENAME"
28
-
29
- URL="https://huggingface.co/unsloth/FLUX.2-klein-4B-GGUF/resolve/main/${FILENAME}"
30
-
31
- # Check if URL exists (HTTP 200)
32
- HTTP_CODE=$(curl -sI "$URL" | head -n 1 | cut -d' ' -f2)
33
-
34
- if [ "$HTTP_CODE" = "200" ]; then
35
- echo "βœ… Found! Downloading..."
36
- wget -O "models/${FILENAME}" "$URL" --progress=bar:force:noscroll
37
-
38
- # Verify download
39
- if [ -f "models/${FILENAME}" ] && [ $(stat -c%s "models/${FILENAME}") -gt 1000000 ]; then
40
- SIZE=$(du -h "models/${FILENAME}" | cut -f1)
41
- echo "βœ… Downloaded: ${FILENAME} (${SIZE})"
42
- DOWNLOADED=true
43
- break
44
- fi
45
- else
46
- echo "❌ Not found (HTTP $HTTP_CODE)"
47
- fi
48
- done
49
-
50
- if [ "$DOWNLOADED" = false ]; then
51
- echo ""
52
- echo "⚠️ AUTO-DOWNLOAD FAILED"
53
- echo ""
54
- echo "Manual steps:"
55
- echo "1. Visit: https://huggingface.co/unsloth/FLUX.2-klein-4B-GGUF/tree/main"
56
- echo "2. Find the Q8_0 .gguf file"
57
- echo "3. Note the EXACT filename"
58
- echo "4. Upload it to ./models/ folder in your Space"
59
- echo ""
60
- exit 1
61
- fi
62
-
63
- echo ""
64
- echo "=========================================="
65
- echo "βœ… MODEL DOWNLOAD COMPLETE"
66
- echo "=========================================="
67
- ls -lh models/
68
  """
69
- FLUX.2-klein-4B Q8_0 Generator v5.0
70
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
71
- βœ… Models downloaded at BUILD TIME (not runtime)
 
 
72
  βœ… Gradio 6.0 compatible
73
- βœ… CPU Optimized for 18GB RAM
74
  """
75
 
76
  import os
77
  import sys
 
78
  from pathlib import Path
79
  from datetime import datetime
80
 
@@ -86,12 +21,22 @@ BASE = Path.cwd()
86
  MODELS = BASE / "models"
87
  OUTPUTS = BASE / "outputs"
88
 
89
- # Model configuration
90
- MODEL_FILE = None # Will auto-detect
 
 
 
 
 
91
  MODEL_PATH = None
92
 
93
- def find_model_file():
94
- """Find the GGUF model file in ./models/"""
 
 
 
 
 
95
  global MODEL_FILE, MODEL_PATH
96
 
97
  MODELS.mkdir(exist_ok=True)
@@ -100,28 +45,57 @@ def find_model_file():
100
  gguf_files = list(MODELS.glob("*.gguf"))
101
 
102
  if gguf_files:
103
- # Pick the largest one (likely the main model)
104
  gguf_files.sort(key=lambda x: x.stat().st_size, reverse=True)
105
  MODEL_FILE = gguf_files[0].name
106
  MODEL_PATH = str(gguf_files[0])
107
 
108
  size_mb = gguf_files[0].stat().st_size / (1024*1024)
109
- print(f"βœ… Found model: {MODEL_FILE} ({size_mb:.1f} MB)")
110
  return True
111
- else:
112
- print("❌ No .gguf model files found in ./models/")
113
- print(f" Contents of {MODELS}: {list(MODELS.iterdir())}")
114
- return False
115
-
116
 
117
- def log(msg):
118
- """Timestamped logging"""
119
- print(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}")
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
- # ══════════════════════════════════════════════
123
- # GENERATION FUNCTION
124
- # ══════════════════════════════════════════════
125
 
126
  def generate_image(
127
  prompt: str,
@@ -133,66 +107,48 @@ def generate_image(
133
  seed: int = -1,
134
  progress=None
135
  ):
136
- """
137
- Generate image using Flux GGUF model
138
- """
139
 
140
- # Validate inputs
141
  if not prompt or not prompt.strip():
142
- return None, "❌ Please enter a text prompt!"
143
 
144
- prompt = prompt.strip()
145
-
146
- # Check model exists
147
  if not MODEL_PATH or not Path(MODEL_PATH).exists():
148
- return None, f"""❌ Model file not found!
149
 
150
- Expected location: {MODEL_PATH}
151
 
152
- SOLUTION:
153
- 1. Ensure download_models.sh ran successfully during build
154
- 2. Or manually upload a .gguf file to ./models/
155
  3. Restart Space"""
156
 
157
  try:
158
- # Import ML libraries (lazy load)
159
  import torch
160
  from diffusers import FluxPipeline
161
 
162
  if progress:
163
- progress(0.05, desc="Loading pipeline...")
164
 
165
- log("🎨 Loading FLUX pipeline...")
166
- log(f" Model: {MODEL_FILE}")
167
- log(f" Prompt: {prompt[:80]}...")
168
 
169
- # Load pipeline
170
  pipe = FluxPipeline.from_single_file(
171
  MODEL_PATH,
172
  torch_dtype=torch.bfloat16
173
  )
174
-
175
- # Enable CPU offloading for low memory
176
  pipe.enable_model_cpu_offload()
177
 
178
  if progress:
179
- progress(0.25, desc="Pipeline loaded, generating...")
180
 
181
- log(f" Parameters: {width}x{height}, {steps} steps, CFG={cfg}")
182
-
183
- # Set seed
184
  generator = None
185
  if seed > 0:
186
  generator = torch.Generator(device="cpu").manual_seed(seed)
187
- log(f" Seed: {seed}")
188
  else:
189
  import random
190
  seed = random.randint(0, 2**32)
191
- log(f" Seed: {seed} (random)")
192
 
193
- # Generate image
194
  result = pipe(
195
- prompt=prompt,
196
  negative_prompt=neg_prompt.strip() or None,
197
  height=int(height),
198
  width=int(width),
@@ -202,83 +158,58 @@ SOLUTION:
202
  )
203
 
204
  if progress:
205
- progress(0.9, desc="Saving output...")
206
 
207
- # Save image
208
  OUTPUTS.mkdir(exist_ok=True)
209
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
210
- output_filename = f"flux_{timestamp}.png"
211
- output_path = str(OUTPUTS_DIR / output_filename)
212
 
213
  result.images[0].save(output_path)
214
-
215
  file_size = Path(output_path).stat().st_size / (1024*1024)
216
 
217
  if progress:
218
- progress(1.0, desc="Complete!")
219
 
220
- status = f"""βœ… Image Generated Successfully!
221
 
222
- πŸ“Š Details:
223
- β”œβ”€ File: {output_filename}
224
- β”œβ”€ Size: {file_size:.2f} MB
225
- β”œβ”€ Resolution: {width} Γ— {height}
226
- β”œβ”€ Steps: {steps}
227
- β”œβ”€ CFG Scale: {cfg}
228
- └─ Seed: {seed}
229
 
230
- πŸ’‘ Model: {MODEL_FILE}
231
- ⏱️ Generation completed!"""
232
-
233
- log(f"βœ… Saved: {output_path} ({file_size:.1f} MB)")
234
 
 
235
  return output_path, status
236
 
237
  except ImportError as e:
238
- missing_pkg = str(e).split("'")[1] if "'" in str(e) else str(e)
239
- return None, f"""❌ Missing Python Package!
240
-
241
- Package: {missing_pkg}
242
 
243
- Fix: Add to requirements.txt and restart:
244
- diffusers>=0.30.0
245
- transformers>=4.44.0
246
- accelerate>=0.33.0
247
- safetensors>=0.4.5
248
- sentencepiece>=0.2.0"""
249
 
250
  except Exception as e:
251
  error_type = type(e).__name__
252
- error_msg = str(e)[:800]
253
 
254
  log(f"❌ ERROR: {error_type}: {error_msg}")
255
 
256
- # Provide helpful suggestions
257
- if "out of memory" in error_msg.lower():
258
  suggestion = """
259
  πŸ”΄ OUT OF MEMORY!
 
260
 
261
- Your 18GB RAM is full. Solutions:
 
262
  β€’ Reduce resolution to 512Γ—512
263
- β€’ Reduce steps to 10-15
264
- β€’ Close other applications
265
- β€’ Use smaller model (Q4_K_M instead of Q8_0)"""
266
- elif "CUDA" in error_msg.upper():
267
- suggestion = """
268
- ⚠️ GPU/CUDA Error
269
-
270
- This Space is CPU-only. The pipeline should use CPU offloading.
271
- If this persists, try restarting the Space."""
272
  else:
273
- suggestion = f"""
274
- Error Details:
275
- Type: {error_type}
276
- Message: {error_msg}
277
-
278
- Check logs above for full traceback."""
279
 
280
- return None, f"""❌ Generation Failed!
281
- {suggestion}"""
282
 
283
 
284
  # ══════════════════════════════════════════════
@@ -286,211 +217,113 @@ Check logs above for full traceback."""
286
  # ══════════════════════════════════════════════
287
 
288
  print("\n" + "="*60)
289
- print("🎨 FLUX.2-klein-4B Generator")
290
  print("="*60 + "\n")
291
 
292
- # Find model file (should already exist from build)
293
- model_found = find_model_file()
294
-
295
- if not model_found:
296
- print("""
297
- ⚠️ WARNING: No model file detected!
298
-
299
- This means either:
300
- 1. download_models.sh failed during build
301
- 2. Models weren't uploaded yet
302
-
303
- TO FIX:
304
- Option A: Upload .gguf file to ./models/ via Space UI
305
- Option B: Rebuild Space after fixing download script
 
 
 
 
 
306
  """)
307
 
308
  # ══════════════════════════════════════════════
309
- # GRADIO INTERFACE (Gradio 6.0 Compatible!)
310
  # ══════════════════════════════════════════════
311
 
312
  import gradio as gr
313
 
314
- # Create interface WITHOUT theme in constructor (Gradio 6.0 fix)
315
- with gr.Blocks(title="FLUX.2-klein-4B Q8_0 Generator") as demo:
316
 
317
  gr.Markdown("""
318
- # 🎨 FLUX.2-klein-4B (Q8_0) Text-to-Image
319
 
320
- ### ⚑ CPU-Powered β€’ Diffusers Backend β€’ No GPU Required
 
321
 
322
  ---
323
  """)
324
 
325
- # Status indicator
326
- status_text = f"""
327
- **System Status:** {'βœ… Ready' if model_found else '⚠️ No Model Found'}
328
 
329
- **Model:** `{MODEL_FILE or 'Not detected'}`
330
 
331
- **Mode:** CPU Inference (18GB RAM optimized)
332
  """
333
 
334
- gr.Markdown(status_text)
335
 
336
  with gr.Row():
337
  with gr.Column(scale=2):
338
  prompt_input = gr.Textbox(
339
  label="✍️ Prompt",
340
- placeholder="A red fox in snow, detailed, 8k quality...",
341
  lines=4,
342
  value="a red fox in snow, detailed, 8k"
343
  )
344
-
345
  neg_input = gr.Textbox(
346
- label="🚫 Negative Prompt (optional)",
347
- placeholder="blurry, low quality, deformed, ugly...",
348
- lines=2,
349
- value=""
350
  )
351
 
352
  with gr.Column(scale=1):
353
- width_slider = gr.Slider(
354
- minimum=256,
355
- maximum=1024,
356
- value=1024,
357
- step=64,
358
- label="↔️ Width (px)",
359
- info="Lower = faster"
360
- )
361
-
362
- height_slider = gr.Slider(
363
- minimum=256,
364
- maximum=1024,
365
- value=1024,
366
- step=64,
367
- label="↕️ Height (px)",
368
- info="Lower = faster"
369
- )
370
-
371
- steps_slider = gr.Slider(
372
- minimum=1,
373
- maximum=50,
374
- value=20,
375
- step=1,
376
- label="πŸ”„ Inference Steps",
377
- info="20 recommended"
378
- )
379
-
380
- cfg_slider = gr.Slider(
381
- minimum=1.0,
382
- maximum=20.0,
383
- value=7.0,
384
- step=0.5,
385
- label="βš™οΈ CFG Scale",
386
- info="7.0 good for Flux"
387
- )
388
-
389
- seed_input = gr.Number(
390
- value=-1,
391
- label="🎲 Seed",
392
- info="-1 = random",
393
- precision=0
394
- )
395
 
396
  with gr.Row():
397
- gen_btn = gr.Button(
398
- "πŸš€ Generate Image",
399
- variant="primary",
400
- size="lg"
401
- )
402
- clear_btn = gr.Button(
403
- "πŸ—‘οΈ Clear All",
404
- size="lg"
405
- )
406
 
407
  with gr.Row():
408
- with gr.Column():
409
- output_image = gr.Image(
410
- label="πŸ–ΌοΈ Generated Output",
411
- height=500,
412
- type="filepath"
413
- )
414
-
415
- with gr.Column():
416
- status_output = gr.Textbox(
417
- label="πŸ“Š Status & Information",
418
- lines=14,
419
- max_lines=25,
420
- interactive=False
421
- )
422
 
423
- # Event handlers
424
  gen_btn.click(
425
  fn=generate_image,
426
- inputs=[
427
- prompt_input,
428
- neg_input,
429
- width_slider,
430
- height_slider,
431
- steps_slider,
432
- cfg_slider,
433
- seed_input
434
- ],
435
  outputs=[output_image, status_output],
436
  show_progress=True
437
  )
438
 
439
  clear_btn.click(
440
- fn=lambda: (
441
- "a red fox in snow, detailed, 8k", # Reset prompt
442
- "", # Clear negative
443
- 1024, # Default width
444
- 1024, # Default height
445
- 20, # Default steps
446
- 7.0, # Default CFG
447
- -1, # Random seed
448
- None, # Clear image
449
- "" # Clear status
450
- ),
451
- outputs=[
452
- prompt_input,
453
- neg_input,
454
- width_slider,
455
- height_slider,
456
- steps_slider,
457
- cfg_slider,
458
- seed_input,
459
- output_image,
460
- status_output
461
- ]
462
  )
463
 
464
- # Footer help text
465
  gr.Markdown("""
466
  ---
467
- ### πŸ’‘ Performance Tips (CPU Mode)
468
-
469
- | Setting | Fast (Quick Preview) | Quality (Best Results) |
470
- |---------|---------------------|----------------------|
471
- | **Resolution** | 512 Γ— 512 | 1024 Γ— 1024 |
472
- | **Steps** | 10-15 | 25-30 |
473
- | **CFG Scale** | 5.0-7.0 | 7.0-12.0 |
474
-
475
- ⏱️ **First generation**: ~3-5 minutes (model loading)
476
-
477
- ⏱️ **Subsequent generations**: ~1-3 minutes each
478
-
479
- πŸ”΄ **Memory**: Keep total under 12GB usage on 18GB system
480
  """)
481
 
482
 
483
  # ══════════════════════════════════════════════
484
- # LAUNCH (Gradio 6.0 Compatible!)
485
  # ══════════════════════════════════════════════
486
 
487
  if __name__ == "__main__":
488
- log("πŸš€ Launching web interface...")
489
-
490
- # FIXED: Move theme to launch() for Gradio 6.0+
491
- demo.launch(
492
- server_name="0.0.0.0",
493
- server_port=7860,
494
- share=False,
495
- # theme=gr.themes.Soft() # Uncomment if you want custom theme
496
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ FLUX.2-klein-4B Generator v6.0 - FINAL VERSION
3
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4
+ βœ… Correct model filename (with hyphens!)
5
+ βœ… Auto-downloads if missing (backup to build script)
6
+ βœ… Uses Q4_K_M by default (fits 18GB RAM better)
7
  βœ… Gradio 6.0 compatible
 
8
  """
9
 
10
  import os
11
  import sys
12
+ import urllib.request
13
  from pathlib import Path
14
  from datetime import datetime
15
 
 
21
  MODELS = BASE / "models"
22
  OUTPUTS = BASE / "outputs"
23
 
24
+ # CORRECT filenames (from HF repo)
25
+ POSSIBLE_MODELS = [
26
+ "flux-2-klein-4b-Q4_K_M.gguf", # 2.6 GB - RECOMMENDED for 18GB RAM
27
+ "flux-2-klein-4b-Q8_0.gguf", # 4.3 GB - High quality (may OOM)
28
+ ]
29
+
30
+ MODEL_FILE = None
31
  MODEL_PATH = None
32
 
33
+
34
+ def log(msg):
35
+ print(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}")
36
+
37
+
38
+ def find_model():
39
+ """Find existing model file"""
40
  global MODEL_FILE, MODEL_PATH
41
 
42
  MODELS.mkdir(exist_ok=True)
 
45
  gguf_files = list(MODELS.glob("*.gguf"))
46
 
47
  if gguf_files:
48
+ # Pick largest one
49
  gguf_files.sort(key=lambda x: x.stat().st_size, reverse=True)
50
  MODEL_FILE = gguf_files[0].name
51
  MODEL_PATH = str(gguf_files[0])
52
 
53
  size_mb = gguf_files[0].stat().st_size / (1024*1024)
54
+ log(f"βœ… Found model: {MODEL_FILE} ({size_mb:.1f} MB)")
55
  return True
56
+
57
+ return False
 
 
 
58
 
 
 
 
59
 
60
+ def download_model():
61
+ """Download model as fallback"""
62
+ global MODEL_FILE, MODEL_PATH
63
+
64
+ log("⬇️ No model found - attempting download...")
65
+
66
+ for model_name in POSSIBLE_MODELS:
67
+ url = f"https://huggingface.co/unsloth/FLUX.2-klein-4B-GGUF/resolve/main/{model_name}"
68
+ dest = MODELS / model_name
69
+
70
+ log(f"Trying: {model_name}")
71
+
72
+ try:
73
+ def progress(count, block_size, total_size):
74
+ if total_size > 0:
75
+ percent = count * block_size * 100 // total_size
76
+ mb = count * block_size / (1024*1024)
77
+ total_mb = total_size / (1024*1024)
78
+ print(f"\r {percent}% ({mb:.1f}/{total_mb:.1f} MB)", end="", flush=True)
79
+
80
+ urllib.request.urlretrieve(url, dest, progress)
81
+ print("") # New line after progress
82
+
83
+ if dest.exists() and dest.stat().st_size > 1000000: # > 1MB
84
+ size_mb = dest.stat().st_size / (1024*1024)
85
+ log(f"βœ… Downloaded: {model_name} ({size_mb:.1f} MB)")
86
+
87
+ MODEL_FILE = model_name
88
+ MODEL_PATH = str(dest)
89
+ return True
90
+
91
+ except Exception as e:
92
+ log(f"❌ Failed: {e}")
93
+ if dest.exists():
94
+ dest.unlink()
95
+
96
+ log("❌ All download attempts failed")
97
+ return False
98
 
 
 
 
99
 
100
  def generate_image(
101
  prompt: str,
 
107
  seed: int = -1,
108
  progress=None
109
  ):
110
+ """Generate image with Flux GGUF model"""
 
 
111
 
 
112
  if not prompt or not prompt.strip():
113
+ return None, "❌ Please enter a prompt!"
114
 
 
 
 
115
  if not MODEL_PATH or not Path(MODEL_PATH).exists():
116
+ return None, f"""❌ Model missing!
117
 
118
+ Expected: {MODEL_PATH or 'No model set'}
119
 
120
+ QUICK FIX:
121
+ 1. Wait for auto-download (should happen at startup)
122
+ 2. Or upload flux-2-klein-4b-Q4_K_M.gguf to ./models/
123
  3. Restart Space"""
124
 
125
  try:
 
126
  import torch
127
  from diffusers import FluxPipeline
128
 
129
  if progress:
130
+ progress(0.05, desc="Loading pipeline (first run ~2 min)...")
131
 
132
+ log(f"🎨 Loading: {MODEL_FILE}")
 
 
133
 
 
134
  pipe = FluxPipeline.from_single_file(
135
  MODEL_PATH,
136
  torch_dtype=torch.bfloat16
137
  )
 
 
138
  pipe.enable_model_cpu_offload()
139
 
140
  if progress:
141
+ progress(0.25, desc="Generating...")
142
 
 
 
 
143
  generator = None
144
  if seed > 0:
145
  generator = torch.Generator(device="cpu").manual_seed(seed)
 
146
  else:
147
  import random
148
  seed = random.randint(0, 2**32)
 
149
 
 
150
  result = pipe(
151
+ prompt=prompt.strip(),
152
  negative_prompt=neg_prompt.strip() or None,
153
  height=int(height),
154
  width=int(width),
 
158
  )
159
 
160
  if progress:
161
+ progress(0.9, desc="Saving...")
162
 
 
163
  OUTPUTS.mkdir(exist_ok=True)
164
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
165
+ output_path = str(OUTPUTS_DIR / f"flux_{timestamp}.png")
 
166
 
167
  result.images[0].save(output_path)
 
168
  file_size = Path(output_path).stat().st_size / (1024*1024)
169
 
170
  if progress:
171
+ progress(1.0, desc="Done!")
172
 
173
+ status = f"""βœ… Generated Successfully!
174
 
175
+ πŸ“Š Stats:
176
+ β€’ File: flux_{timestamp}.png ({file_size:.1f} MB)
177
+ β€’ Size: {width}Γ—{height}
178
+ β€’ Steps: {steps}
179
+ β€’ CFG: {cfg}
180
+ β€’ Seed: {seed}
 
181
 
182
+ πŸ’‘ Model: {MODEL_FILE}"""
 
 
 
183
 
184
+ log(f"βœ… Saved: {output_path}")
185
  return output_path, status
186
 
187
  except ImportError as e:
188
+ pkg = str(e).split("'")[1] if "'" in str(e) else str(e)
189
+ return None, f"""❌ Missing package: {pkg}
 
 
190
 
191
+ Install with:
192
+ pip install diffusers transformers accelerate safetensors sentencepiece torch"""
 
 
 
 
193
 
194
  except Exception as e:
195
  error_type = type(e).__name__
196
+ error_msg = str(e)[:500]
197
 
198
  log(f"❌ ERROR: {error_type}: {error_msg}")
199
 
200
+ if "memory" in error_msg.lower() or "ram" in error_msg.lower():
 
201
  suggestion = """
202
  πŸ”΄ OUT OF MEMORY!
203
+ Your 18GB RAM is full.
204
 
205
+ Solutions:
206
+ β€’ Use Q4_K_M model (2.6GB) instead of Q8_0 (4.3GB)
207
  β€’ Reduce resolution to 512Γ—512
208
+ β€’ Reduce steps to 10-15"""
 
 
 
 
 
 
 
 
209
  else:
210
+ suggestion = f"\nError: {error_type}\n{error_msg}"
 
 
 
 
 
211
 
212
+ return None, f"""❌ Generation Failed!{suggestion}"""
 
213
 
214
 
215
  # ══════════════════════════════════════════════
 
217
  # ══════════════════════════════════════════════
218
 
219
  print("\n" + "="*60)
220
+ print("🎨 FLUX.2-klein-4B Generator v6.0")
221
  print("="*60 + "\n")
222
 
223
+ # Try to find existing model
224
+ if not find_model():
225
+ # If not found, try downloading
226
+ if not download_model():
227
+ print("""
228
+ ⚠️ WARNING: Could not find or download model!
229
+
230
+ MANUAL UPLOAD INSTRUCTIONS:
231
+
232
+ Option A (Recommended - Smaller/Faster):
233
+ 1. Go to: https://huggingface.co/unsloth/FLUX.2-klein-4B-GGUF/blob/main/flux-2-klein-4b-Q4_K_M.gguf
234
+ 2. Click "Download"
235
+ 3. Upload to your Space's ./models/ folder
236
+ 4. Restart Space
237
+
238
+ Option B (Higher Quality - Larger):
239
+ 1. Download: flux-2-klein-4b-Q8_0.gguf (4.3GB) from same repo
240
+ 2. Upload to ./models/
241
+ 3. Restart Space
242
  """)
243
 
244
  # ══════════════════════════════════════════════
245
+ # GRADIO INTERFACE
246
  # ══════════════════════════════════════════════
247
 
248
  import gradio as gr
249
 
250
+ with gr.Blocks(title="FLUX.2-klein-4B Generator") as demo:
 
251
 
252
  gr.Markdown("""
253
+ # 🎨 FLUX.2-klein-4B Text-to-Image Generator
254
 
255
+ ### Model: `unsloth/FLUX.2-klein-4B-GGUF`
256
+ ### Backend: Diffusers (CPU Optimized)
257
 
258
  ---
259
  """)
260
 
261
+ status_md = f"""
262
+ **Status:** {'βœ… Ready' if MODEL_FILE else '⚠️ Waiting for Model'}
 
263
 
264
+ **Model File:** `{MODEL_FILE or 'Not loaded'}`
265
 
266
+ **Mode:** CPU Inference (18GB RAM)
267
  """
268
 
269
+ gr.Markdown(status_md)
270
 
271
  with gr.Row():
272
  with gr.Column(scale=2):
273
  prompt_input = gr.Textbox(
274
  label="✍️ Prompt",
275
+ placeholder="A red fox in snow, detailed, 8k...",
276
  lines=4,
277
  value="a red fox in snow, detailed, 8k"
278
  )
 
279
  neg_input = gr.Textbox(
280
+ label="🚫 Negative Prompt",
281
+ placeholder="blurry, low quality...",
282
+ lines=2
 
283
  )
284
 
285
  with gr.Column(scale=1):
286
+ width_slider = gr.Slider(256, 1024, 1024, 64, label="Width")
287
+ height_slider = gr.Slider(256, 1024, 1024, 64, label="Height")
288
+ steps_slider = gr.Slider(1, 50, 20, 1, label="Steps")
289
+ cfg_slider = gr.Slider(1.0, 20.0, 7.0, 0.5, label="CFG Scale")
290
+ seed_input = gr.Number(-1, label="Seed (-1=random)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
 
292
  with gr.Row():
293
+ gen_btn = gr.Button("πŸš€ Generate", variant="primary", size="lg")
294
+ clear_btn = gr.Button("πŸ—‘οΈ Clear", size="lg")
 
 
 
 
 
 
 
295
 
296
  with gr.Row():
297
+ output_image = gr.Image(label="Output", height=500, type="filepath")
298
+ status_output = gr.Textbox(label="Status", lines=12, interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
299
 
 
300
  gen_btn.click(
301
  fn=generate_image,
302
+ inputs=[prompt_input, neg_input, width_slider, height_slider,
303
+ steps_slider, cfg_slider, seed_input],
 
 
 
 
 
 
 
304
  outputs=[output_image, status_output],
305
  show_progress=True
306
  )
307
 
308
  clear_btn.click(
309
+ fn=lambda: ("a red fox in snow, detailed, 8k", "", 1024, 1024, 20, 7.0, -1, None, ""),
310
+ outputs=[prompt_input, neg_input, width_slider, height_slider,
311
+ steps_slider, cfg_slider, seed_input, output_image, status_output]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  )
313
 
 
314
  gr.Markdown("""
315
  ---
316
+ ### πŸ’‘ Tips
317
+ - **First run**: Slow (~3-5 min) while loading model
318
+ - **Subsequent runs**: Faster (~1-3 min each)
319
+ - **Memory**: Using Q4_K_M (2.6GB) to fit 18GB RAM safely
 
 
 
 
 
 
 
 
 
320
  """)
321
 
322
 
323
  # ══════════════════════════════════════════════
324
+ # LAUNCH
325
  # ══════════════════════════════════════════════
326
 
327
  if __name__ == "__main__":
328
+ log("πŸš€ Launching Gradio...")
329
+ demo.launch(server_name="0.0.0.0", server_port=7860)