Spaces:
Paused

aexyb commited on
Commit
f527486
Β·
verified Β·
1 Parent(s): 1fe3966

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -0
app.py CHANGED
@@ -1,3 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import os
3
  import subprocess
 
1
+ """
2
+ Flux Text-to-Image Generator (CPU Only)
3
+ Auto-setup included - downloads models on first run
4
+ """
5
+
6
+ # ============================================================
7
+ # PART 1: AUTO SETUP - Download models if missing
8
+ # ============================================================
9
+ import os
10
+ import sys
11
+ import urllib.request
12
+ from pathlib import Path
13
+
14
+ def auto_setup():
15
+ """Ensure all required files exist"""
16
+ print("\n" + "="*60)
17
+ print("πŸ”§ RUNNING AUTO-SETUP...")
18
+ print("="*60 + "\n")
19
+
20
+ # Create directories
21
+ Path("models").mkdir(exist_ok=True)
22
+ Path("outputs").mkdir(exist_ok=True)
23
+ print("βœ… Created directories: models/, outputs/")
24
+
25
+ # Define models
26
+ models = {
27
+ "bonsai-flux2-klein-ternary-q2_k.gguf":
28
+ "https://huggingface.co/bonsai-models/flux.1-klein-gguf/resolve/main/bonsai-flux2-klein-ternary-q2_k.gguf",
29
+ "flux2-vae.safetensors":
30
+ "https://huggingface.co/black-forest-labs/FLUX.1-dev/resolve/main/ae.safetensors",
31
+ "qwen_3_4b.gguf":
32
+ "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q2_k.gguf",
33
+ }
34
+
35
+ # Download missing models
36
+ for filename, url in models.items():
37
+ filepath = Path("models") / filename
38
+
39
+ if filepath.exists():
40
+ size_mb = filepath.stat().st_size / (1024*1024)
41
+ print(f"βœ… Found: {filename} ({size_mb:.1f} MB)")
42
+ else:
43
+ print(f"πŸ“₯ Downloading: {filename}")
44
+ try:
45
+ urllib.request.urlretrieve(url, filepath)
46
+ size_mb = filepath.stat().st_size / (1024*1024)
47
+ print(f" βœ… Saved ({size_mb:.1f} MB)")
48
+ except Exception as e:
49
+ print(f" ❌ Error: {e}")
50
+ print(f" ⚠️ Manual download needed from:")
51
+ print(f" {url}")
52
+
53
+ print("\n" + "="*60)
54
+ print("βœ… SETUP COMPLETE")
55
+ print("="*60 + "\n")
56
+
57
+ # Run setup
58
+ auto_setup()
59
+
60
+ # ============================================================
61
+ # PART 2: IMPORTS & CONFIGURATION
62
+ # ============================================================
63
+ import gradio as gr
64
+ import subprocess
65
+ from datetime import datetime
66
+
67
+ # Paths
68
+ MODELS_DIR = "./models"
69
+ OUTPUTS_DIR = "./outputs"
70
+
71
+ DIFFUSION_MODEL = os.path.join(MODELS_DIR, "bonsai-flux2-klein-ternary-q2_k.gguf")
72
+ VAE_MODEL = os.path.join(MODELS_DIR, "flux2-vae.safetensors")
73
+ LLM_MODEL = os.path.join(MODELS_DIR, "qwen_3_4b.gguf")
74
+
75
+ SD_CLI = "./stable-diffusion.cpp/bin/sd-cli" # Adjust if needed
76
+
77
+
78
+ # ============================================================
79
+ # PART 3: IMAGE GENERATION FUNCTION
80
+ # ============================================================
81
+ def generate_image(
82
+ prompt: str,
83
+ negative_prompt: str = "",
84
+ cfg_scale: float = 1.0,
85
+ steps: int = 4,
86
+ width: int = 1024,
87
+ height: int = 1024,
88
+ seed: int = -1,
89
+ progress=gr.Progress()
90
+ ):
91
+ """Generate image using stable diffusion.cpp"""
92
+
93
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
94
+ output_filename = f"generated_{timestamp}.png"
95
+ output_path = os.path.join(OUTPUTS_DIR, output_filename)
96
+
97
+ cmd = [
98
+ SD_CLI,
99
+ "--diffusion-model", DIFFUSION_MODEL,
100
+ "--vae", VAE_MODEL,
101
+ "--llm", LLM_MODEL,
102
+ "-p", prompt,
103
+ "--cfg-scale", str(cfg_scale),
104
+ "--steps", str(steps),
105
+ "-W", str(width),
106
+ "-H", str(height),
107
+ "-o", output_path,
108
+ "--offload-to-cpu",
109
+ "--diffusion-fa",
110
+ "--vae-tiling",
111
+ ]
112
+
113
+ if seed > 0:
114
+ cmd.extend(["--seed", str(seed)])
115
+ if negative_prompt:
116
+ cmd.extend(["-n", negative_prompt])
117
+
118
+ progress(0.1, desc="Starting generation...")
119
+
120
+ try:
121
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
122
+ progress(0.9, desc="Processing output...")
123
+
124
+ if result.returncode != 0:
125
+ return None, f"Error: {result.stderr}"
126
+
127
+ if os.path.exists(output_path):
128
+ progress(1.0, desc="Complete!")
129
+ return output_path, "βœ… Image generated successfully!"
130
+ else:
131
+ return None, "Output file not found"
132
+
133
+ except subprocess.TimeoutExpired:
134
+ return None, "⏰ Generation timed out (5 min limit)"
135
+ except Exception as e:
136
+ return None, f"❌ Error: {str(e)}"
137
+
138
+
139
+ # ============================================================
140
+ # PART 4: GRADIO INTERFACE
141
+ # ============================================================
142
+ with gr.Blocks(title="Flux Text-to-Image (CPU)", theme=gr.themes.Soft()) as demo:
143
+
144
+ gr.Markdown("""
145
+ # 🎨 Flux Text-to-Image Generator
146
+ ### CPU-Powered | stable diffusion.cpp | No GPU Required ⚑
147
+ """)
148
+
149
+ with gr.Row():
150
+ with gr.Column(scale=2):
151
+ prompt_input = gr.Textbox(
152
+ label="✍️ Prompt",
153
+ placeholder="A red fox in snow, detailed, 8k...",
154
+ lines=3,
155
+ value="a red fox in snow, detailed, 8k"
156
+ )
157
+
158
+ neg_prompt = gr.Textbox(
159
+ label="🚫 Negative Prompt (optional)",
160
+ placeholder="blurry, low quality...",
161
+ lines=2
162
+ )
163
+
164
+ with gr.Column(scale=1):
165
+ cfg_slider = gr.Slider(1.0, 7.0, value=1.0, step=0.5, label="βš™οΈ CFG Scale")
166
+ steps_slider = gr.Slider(1, 20, value=4, step=1, label="πŸ”„ Steps")
167
+ seed_input = gr.Number(label="🎲 Seed (-1=random)", value=-1, precision=0)
168
+
169
+ with gr.Row():
170
+ gen_btn = gr.Button("πŸš€ Generate Image", variant="primary", size="lg")
171
+ clear_btn = gr.Button("πŸ—‘οΈ Clear", size="lg")
172
+
173
+ with gr.Row():
174
+ output_image = gr.Image(label="πŸ–ΌοΈ Generated Image", type="filepath", height=400)
175
+ status_output = gr.Textbox(label="πŸ“Š Status", interactive=False)
176
+
177
+ gen_btn.click(
178
+ fn=generate_image,
179
+ inputs=[prompt_input, neg_prompt, cfg_slider, steps_slider, seed_input],
180
+ outputs=[output_image, status_output]
181
+ )
182
+
183
+ clear_btn.click(
184
+ fn=lambda: (None, "", "", 1.0, 4, -1, None, ""),
185
+ outputs=[prompt_input, neg_prompt, cfg_slider, steps_slider, seed_input,
186
+ output_image, status_output]
187
+ )
188
+
189
+
190
+ # ============================================================
191
+ # PART 5: LAUNCH
192
+ # ============================================================
193
+ if __name__ == "__main__":
194
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
195
  import gradio as gr
196
  import os
197
  import subprocess