rokmr commited on
Commit
2292ec1
·
1 Parent(s): 1bb3dc0

Adding Flux2.0

Browse files
Files changed (2) hide show
  1. app.py +223 -4
  2. requirements.txt +8 -0
app.py CHANGED
@@ -1,7 +1,226 @@
 
 
 
 
 
 
1
  import gradio as gr
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import Flux2Pipeline, Flux2Transformer2DModel
3
+ from diffusers.utils import load_image
4
+ from huggingface_hub import get_token
5
+ import requests
6
+ import io
7
  import gradio as gr
8
+ from PIL import Image
9
 
10
+ repo_id = "diffusers/FLUX.2-dev-bnb-4bit"
11
+ device = "cuda:0"
12
+ torch_dtype = torch.bfloat16
13
 
14
+ def remote_text_encoder(prompts):
15
+ response = requests.post(
16
+ "https://remote-text-encoder-flux-2.huggingface.co/predict",
17
+ json={"prompt": prompts},
18
+ headers={
19
+ "Authorization": f"Bearer {get_token()}",
20
+ "Content-Type": "application/json"
21
+ }
22
+ )
23
+ prompt_embeds = torch.load(io.BytesIO(response.content))
24
+
25
+ return prompt_embeds.to(device)
26
+
27
+ # Load the pipeline
28
+ print("Loading Flux2 pipeline...")
29
+ pipe = Flux2Pipeline.from_pretrained(
30
+ repo_id, text_encoder=None, torch_dtype=torch_dtype
31
+ ).to(device)
32
+ print("Pipeline loaded successfully!")
33
+
34
+ def generate_image(
35
+ prompt: str,
36
+ input_image: Image.Image = None,
37
+ num_inference_steps: int = 28,
38
+ guidance_scale: float = 4.0,
39
+ seed: int = 42,
40
+ progress=gr.Progress()
41
+ ):
42
+ """
43
+ Generate an image using Flux2 based on text prompt and optional input image.
44
+
45
+ Args:
46
+ prompt: Text description of the desired image
47
+ input_image: Optional input image for image-to-image generation
48
+ num_inference_steps: Number of denoising steps (higher = better quality but slower)
49
+ guidance_scale: How closely to follow the prompt (higher = more strict)
50
+ seed: Random seed for reproducibility (-1 for random)
51
+ """
52
+ if not prompt or prompt.strip() == "":
53
+ raise gr.Error("Please enter a prompt!")
54
+
55
+ progress(0, desc="Encoding prompt...")
56
+
57
+ try:
58
+ # Get prompt embeddings from remote encoder
59
+ prompt_embeds = remote_text_encoder(prompt)
60
+
61
+ progress(0.3, desc="Generating image...")
62
+
63
+ # Set up generator
64
+ if seed == -1:
65
+ generator = torch.Generator(device=device)
66
+ else:
67
+ generator = torch.Generator(device=device).manual_seed(seed)
68
+
69
+ # Prepare pipeline arguments
70
+ pipe_kwargs = {
71
+ "prompt_embeds": prompt_embeds,
72
+ "generator": generator,
73
+ "num_inference_steps": num_inference_steps,
74
+ "guidance_scale": guidance_scale,
75
+ }
76
+
77
+ # Add input image if provided
78
+ if input_image is not None:
79
+ pipe_kwargs["image"] = input_image
80
+ progress(0.4, desc="Processing input image...")
81
+
82
+ # Generate image
83
+ image = pipe(**pipe_kwargs).images[0]
84
+
85
+ progress(1.0, desc="Done!")
86
+
87
+ return image
88
+
89
+ except Exception as e:
90
+ raise gr.Error(f"Error generating image: {str(e)}")
91
+
92
+ # Create Gradio interface
93
+ with gr.Blocks(title="Flux2 Image Generator", theme=gr.themes.Soft()) as demo:
94
+ gr.Markdown(
95
+ """
96
+ # 🎨 Flux2 Image Generator
97
+ Generate stunning images using FLUX.2-dev with 4-bit quantization.
98
+ Supports both **text-to-image** and **image-to-image** generation.
99
+ """
100
+ )
101
+
102
+ with gr.Row():
103
+ with gr.Column(scale=1):
104
+ gr.Markdown("### 📝 Input")
105
+
106
+ prompt_input = gr.Textbox(
107
+ label="Prompt",
108
+ placeholder="Describe the image you want to generate...",
109
+ lines=4,
110
+ value="Realistic macro photograph of a hermit crab using a soda can as its shell, partially emerging from the can, captured with sharp detail and natural colors, on a sunlit beach with soft shadows and a shallow depth of field, with blurred ocean waves in the background."
111
+ )
112
+
113
+ image_input = gr.Image(
114
+ label="Input Image (Optional)",
115
+ type="pil",
116
+ sources=["upload", "clipboard"],
117
+ height=300
118
+ )
119
+
120
+ gr.Markdown("### ⚙️ Parameters")
121
+
122
+ with gr.Row():
123
+ num_steps = gr.Slider(
124
+ minimum=1,
125
+ maximum=100,
126
+ value=28,
127
+ step=1,
128
+ label="Inference Steps",
129
+ info="More steps = better quality but slower"
130
+ )
131
+
132
+ guidance = gr.Slider(
133
+ minimum=1.0,
134
+ maximum=15.0,
135
+ value=4.0,
136
+ step=0.5,
137
+ label="Guidance Scale",
138
+ info="How closely to follow the prompt"
139
+ )
140
+
141
+ seed_input = gr.Number(
142
+ label="Seed",
143
+ value=42,
144
+ precision=0,
145
+ info="Use -1 for random seed"
146
+ )
147
+
148
+ generate_btn = gr.Button(
149
+ "🚀 Generate Image",
150
+ variant="primary",
151
+ size="lg"
152
+ )
153
+
154
+ gr.Markdown(
155
+ """
156
+ ### 💡 Tips
157
+ - **Text-to-Image**: Just enter a prompt and click generate
158
+ - **Image-to-Image**: Upload an image and describe the changes
159
+ - Start with 28 steps for a good balance of quality and speed
160
+ - Higher guidance scale follows your prompt more strictly
161
+ - Use the same seed to reproduce results
162
+ """
163
+ )
164
+
165
+ with gr.Column(scale=1):
166
+ gr.Markdown("### 🖼️ Output")
167
+
168
+ output_image = gr.Image(
169
+ label="Generated Image",
170
+ type="pil",
171
+ height=600
172
+ )
173
+
174
+ gr.Markdown(
175
+ """
176
+ ### 📊 Examples
177
+ Try these prompts for inspiration!
178
+ """
179
+ )
180
+
181
+ # Examples
182
+ gr.Examples(
183
+ examples=[
184
+ [
185
+ "A serene landscape with mountains at sunset, vibrant orange and pink sky, reflected in a calm lake, photorealistic",
186
+ None,
187
+ 28,
188
+ 4.0,
189
+ 42
190
+ ],
191
+ [
192
+ "A futuristic cityscape at night, neon lights, flying cars, cyberpunk style, highly detailed",
193
+ None,
194
+ 28,
195
+ 4.0,
196
+ 123
197
+ ],
198
+ [
199
+ "A cute robot reading a book in a cozy library, warm lighting, digital art style",
200
+ None,
201
+ 28,
202
+ 4.0,
203
+ 456
204
+ ],
205
+ [
206
+ "Macro photography of a dew drop on a leaf, morning light, sharp focus, bokeh background",
207
+ None,
208
+ 28,
209
+ 4.0,
210
+ 789
211
+ ],
212
+ ],
213
+ inputs=[prompt_input, image_input, num_steps, guidance, seed_input],
214
+ outputs=output_image,
215
+ cache_examples=False,
216
+ )
217
+
218
+ # Connect the generate button
219
+ generate_btn.click(
220
+ fn=generate_image,
221
+ inputs=[prompt_input, image_input, num_steps, guidance, seed_input],
222
+ outputs=output_image,
223
+ )
224
+
225
+ if __name__ == "__main__":
226
+ demo.launch(share=False, server_name="0.0.0.0", server_port=7860)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ diffusers
3
+ gradio
4
+ huggingface_hub
5
+ Pillow
6
+ requests
7
+ accelerate
8
+ transformers