Ammar Vohra commited on
Commit
1226bd0
·
1 Parent(s): c9468bc

seamless texture from flux space

Browse files
Files changed (3) hide show
  1. app.py +69 -170
  2. live_preview_helpers.py +166 -0
  3. requirements.txt +1 -0
app.py CHANGED
@@ -1,148 +1,66 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
- import io
5
- from PIL import Image
6
- import tempfile
7
  import spaces
8
- from diffusers import DiffusionPipeline
9
  import torch
10
- from scipy.ndimage import sobel # For normal map generation
 
 
11
 
 
12
  device = "cuda" if torch.cuda.is_available() else "cpu"
13
- model_repo_id = "black-forest-labs/FLUX.1-dev"
14
 
15
- if torch.cuda.is_available():
16
- torch_dtype = torch.bfloat16
17
- else:
18
- torch_dtype = torch.float32
19
-
20
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
21
- pipe = pipe.to(device)
22
 
23
  MAX_SEED = np.iinfo(np.int32).max
24
- MAX_IMAGE_SIZE = 1024
25
-
26
- def generate_normal_map_from_image(image: Image.Image, strength: float = 1.0) -> Image.Image:
27
- """
28
- Generates a normal map from a PIL Image using Sobel filters.
29
- This is a simplified approach, not using an AI model for normal map generation.
30
- It approximates normals from the intensity changes in the image.
31
-
32
- Args:
33
- image (PIL.Image.Image): The input image (e.g., the generated texture).
34
- strength (float): Controls the intensity/depth of the normal map effect.
35
- Higher values make the bumps more pronounced.
36
-
37
- Returns:
38
- PIL.Image.Image: The generated normal map.
39
- """
40
- # Convert to grayscale
41
- gray_image = image.convert("L")
42
- pixels = np.array(gray_image, dtype=np.float32)
43
-
44
- # Calculate gradients using Sobel filter
45
- # dx (horizontal gradient)
46
- dx = sobel(pixels, axis=1)
47
- # dy (vertical gradient)
48
- dy = sobel(pixels, axis=0)
49
-
50
- # Create the normal vector components
51
- # The Z component determines how "flat" or "bumpy" the surface appears.
52
- # A higher strength means the Z component is relatively smaller, making the surface look bumpier.
53
- # A lower strength means the Z component is relatively larger, making the surface look flatter.
54
- # We scale dx and dy by strength, and keep Z as 1.0 (or a constant that will be normalized).
55
- # Then normalize the vector (dx_scaled, dy_scaled, 1.0)
56
-
57
- # Scale gradients by strength
58
- normal_x = -dx * strength
59
- normal_y = -dy * strength
60
- normal_z = np.ones_like(pixels) * 255.0 # A large constant for Z before normalization
61
-
62
- # Normalize the vectors (x, y, z)
63
- magnitude = np.sqrt(normal_x**2 + normal_y**2 + normal_z**2)
64
- # Avoid division by zero
65
- magnitude[magnitude == 0] = 1e-6 # Small epsilon to prevent division by zero
66
-
67
- normal_x_norm = normal_x / magnitude
68
- normal_y_norm = normal_y / magnitude
69
- normal_z_norm = normal_z / magnitude
70
-
71
- # Map normalized components (-1 to 1) to 0-255 for RGB channels
72
- # R: (normal_x_norm + 1) / 2 * 255
73
- # G: (normal_y_norm + 1) / 2 * 255
74
- # B: (normal_z_norm + 1) / 2 * 255
75
 
76
- # Common convention for normal maps: R=X, G=Y, B=Z.
77
- # Some engines (e.g., OpenGL) might require Y to be inverted.
78
- # For general purpose, let's keep it standard.
79
- r_channel = ((normal_x_norm + 1) / 2 * 255).astype(np.uint8)
80
- g_channel = ((normal_y_norm + 1) / 2 * 255).astype(np.uint8)
81
- b_channel = ((normal_z_norm + 1) / 2 * 255).astype(np.uint8)
82
 
83
- normal_map_array = np.stack([r_channel, g_channel, b_channel], axis=-1)
84
-
85
- return Image.fromarray(normal_map_array, 'RGB')
86
-
87
- @spaces.GPU(duration=65)
88
- def infer(
89
- prompt,
90
- negative_prompt="",
91
- seed=42,
92
- randomize_seed=False,
93
- width=1024,
94
- height=1024,
95
- guidance_scale=4.5,
96
- num_inference_steps=40,
97
- normal_map_strength=1.0,
98
- progress=gr.Progress(track_tqdm=True),
99
- ):
100
  if randomize_seed:
101
  seed = random.randint(0, MAX_SEED)
102
-
103
  generator = torch.Generator().manual_seed(seed)
104
-
105
- image = pipe(
106
- prompt=f"smlstxtr, {prompt}, seamless texture",
107
- negative_prompt=negative_prompt,
108
- guidance_scale=guidance_scale,
109
- num_inference_steps=num_inference_steps,
110
- width=width,
111
- height=height,
112
- generator=generator,
113
- ).images[0]
114
-
115
- # Generate the normal map from the created image
116
- normal_map_image = generate_normal_map_from_image(image, strength=normal_map_strength)
117
 
118
- # Create temporary files with proper cleanup
119
- with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as normal_tmp_file:
120
- normal_map_image.save(normal_tmp_file.name, format="JPEG")
121
- normal_map_path = normal_tmp_file.name
122
-
123
- with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_file:
124
- image.save(tmp_file.name, format="JPEG")
125
- image_path = tmp_file.name
126
-
127
- return image_path, normal_map_path
128
-
129
-
130
  examples = [
131
- "A seamless grassy ground texture, 4k, realistic, for game environment",
132
- "Rough concrete wall texture, weathered, high detail",
133
- "Smooth metallic surface with subtle scratches, sci-fi style",
134
  ]
135
 
136
- css = """
137
  #col-container {
138
  margin: 0 auto;
139
- max-width: 640px;
140
  }
141
  """
142
 
143
  with gr.Blocks(css=css) as demo:
 
144
  with gr.Column(elem_id="col-container"):
 
 
 
 
 
145
  with gr.Row():
 
146
  prompt = gr.Text(
147
  label="Prompt",
148
  show_label=False,
@@ -150,21 +68,13 @@ with gr.Blocks(css=css) as demo:
150
  placeholder="Enter your prompt",
151
  container=False,
152
  )
153
-
154
- run_button = gr.Button("Run", scale=0, variant="primary")
155
-
156
- with gr.Row():
157
- result_image = gr.Image(label="Generated Texture", type="filepath")
158
- normal_map_result = gr.Image(label="Normal Map", type="filepath")
159
-
160
  with gr.Accordion("Advanced Settings", open=False):
161
- negative_prompt = gr.Text(
162
- label="Negative prompt",
163
- max_lines=1,
164
- placeholder="Enter a negative prompt",
165
- visible=False,
166
- )
167
-
168
  seed = gr.Slider(
169
  label="Seed",
170
  minimum=0,
@@ -172,69 +82,58 @@ with gr.Blocks(css=css) as demo:
172
  step=1,
173
  value=0,
174
  )
175
-
176
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
177
-
178
  with gr.Row():
 
179
  width = gr.Slider(
180
  label="Width",
181
- minimum=512,
182
  maximum=MAX_IMAGE_SIZE,
183
  step=32,
184
- value=1024,
185
  )
186
-
187
  height = gr.Slider(
188
  label="Height",
189
- minimum=512,
190
  maximum=MAX_IMAGE_SIZE,
191
  step=32,
192
  value=1024,
193
  )
194
-
195
  with gr.Row():
 
196
  guidance_scale = gr.Slider(
197
- label="Guidance scale",
198
- minimum=0.0,
199
- maximum=7.5,
200
  step=0.1,
201
- value=4.5,
202
  )
203
-
204
  num_inference_steps = gr.Slider(
205
  label="Number of inference steps",
206
  minimum=1,
207
  maximum=50,
208
  step=1,
209
- value=40,
210
  )
211
- # New slider for normal map strength
212
- normal_map_strength = gr.Slider(
213
- label="Normal Map Strength",
214
- minimum=0.1,
215
- maximum=5.0,
216
- step=0.1,
217
- value=1.0,
218
- info="Adjusts the perceived depth/bumpiness of the normal map."
219
- )
220
 
221
- gr.Examples(examples=examples, inputs=[prompt], outputs=[result_image, normal_map_result], fn=infer, cache_examples=True, cache_mode="lazy")
222
  gr.on(
223
  triggers=[run_button.click, prompt.submit],
224
- fn=infer,
225
- inputs=[
226
- prompt,
227
- negative_prompt,
228
- seed,
229
- randomize_seed,
230
- width,
231
- height,
232
- guidance_scale,
233
- num_inference_steps,
234
- normal_map_strength,
235
- ],
236
- outputs=[result_image, normal_map_result],
237
  )
238
 
239
- if __name__ == "__main__":
240
- demo.launch()
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
 
 
4
  import spaces
 
5
  import torch
6
+ from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler, AutoencoderTiny, AutoencoderKL
7
+ from transformers import CLIPTextModel, CLIPTokenizer,T5EncoderModel, T5TokenizerFast
8
+ from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
9
 
10
+ dtype = torch.bfloat16
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
12
 
13
+ taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
14
+ good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=dtype).to(device)
15
+ pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=dtype, vae=taef1).to(device)
16
+ torch.cuda.empty_cache()
 
 
 
17
 
18
  MAX_SEED = np.iinfo(np.int32).max
19
+ MAX_IMAGE_SIZE = 2048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
 
 
 
 
 
22
 
23
+ @spaces.GPU(duration=75)
24
+ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=3.5, num_inference_steps=28, progress=gr.Progress(track_tqdm=True)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  if randomize_seed:
26
  seed = random.randint(0, MAX_SEED)
 
27
  generator = torch.Generator().manual_seed(seed)
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
30
+ prompt= f"smlstxtr, {prompt} , seamless texture",
31
+ guidance_scale=guidance_scale,
32
+ num_inference_steps=num_inference_steps,
33
+ width=width,
34
+ height=height,
35
+ generator=generator,
36
+ output_type="pil",
37
+ good_vae=good_vae,
38
+ ):
39
+ yield img
40
+
41
  examples = [
42
+ "A rusty metal surface with peeling paint and corrosion spots",
43
+ " A dense cluster of white snowflakes on dark blue background",
44
+ "A collection of colorful beach pebbles packed tightly together",
45
  ]
46
 
47
+ css="""
48
  #col-container {
49
  margin: 0 auto;
50
+ max-width: 520px;
51
  }
52
  """
53
 
54
  with gr.Blocks(css=css) as demo:
55
+
56
  with gr.Column(elem_id="col-container"):
57
+ gr.Markdown(f"""# FLUX.1 [dev]
58
+ 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/)
59
+ [[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-dev)]
60
+ """)
61
+
62
  with gr.Row():
63
+
64
  prompt = gr.Text(
65
  label="Prompt",
66
  show_label=False,
 
68
  placeholder="Enter your prompt",
69
  container=False,
70
  )
71
+
72
+ run_button = gr.Button("Run", scale=0)
73
+
74
+ result = gr.Image(label="Result", show_label=False)
75
+
 
 
76
  with gr.Accordion("Advanced Settings", open=False):
77
+
 
 
 
 
 
 
78
  seed = gr.Slider(
79
  label="Seed",
80
  minimum=0,
 
82
  step=1,
83
  value=0,
84
  )
85
+
86
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
87
+
88
  with gr.Row():
89
+
90
  width = gr.Slider(
91
  label="Width",
92
+ minimum=256,
93
  maximum=MAX_IMAGE_SIZE,
94
  step=32,
95
+ value=1024,
96
  )
97
+
98
  height = gr.Slider(
99
  label="Height",
100
+ minimum=256,
101
  maximum=MAX_IMAGE_SIZE,
102
  step=32,
103
  value=1024,
104
  )
105
+
106
  with gr.Row():
107
+
108
  guidance_scale = gr.Slider(
109
+ label="Guidance Scale",
110
+ minimum=1,
111
+ maximum=15,
112
  step=0.1,
113
+ value=3.5,
114
  )
115
+
116
  num_inference_steps = gr.Slider(
117
  label="Number of inference steps",
118
  minimum=1,
119
  maximum=50,
120
  step=1,
121
+ value=28,
122
  )
123
+
124
+ gr.Examples(
125
+ examples = examples,
126
+ fn = infer,
127
+ inputs = [prompt],
128
+ outputs = [result],
129
+ cache_examples="lazy"
130
+ )
 
131
 
 
132
  gr.on(
133
  triggers=[run_button.click, prompt.submit],
134
+ fn = infer,
135
+ inputs = [prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
136
+ outputs = [result]
 
 
 
 
 
 
 
 
 
 
137
  )
138
 
139
+ demo.launch()
 
live_preview_helpers.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from diffusers import FluxPipeline, AutoencoderTiny, FlowMatchEulerDiscreteScheduler
4
+ from typing import Any, Dict, List, Optional, Union
5
+
6
+ # Helper functions
7
+ def calculate_shift(
8
+ image_seq_len,
9
+ base_seq_len: int = 256,
10
+ max_seq_len: int = 4096,
11
+ base_shift: float = 0.5,
12
+ max_shift: float = 1.16,
13
+ ):
14
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
15
+ b = base_shift - m * base_seq_len
16
+ mu = image_seq_len * m + b
17
+ return mu
18
+
19
+ def retrieve_timesteps(
20
+ scheduler,
21
+ num_inference_steps: Optional[int] = None,
22
+ device: Optional[Union[str, torch.device]] = None,
23
+ timesteps: Optional[List[int]] = None,
24
+ sigmas: Optional[List[float]] = None,
25
+ **kwargs,
26
+ ):
27
+ if timesteps is not None and sigmas is not None:
28
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
29
+ if timesteps is not None:
30
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
31
+ timesteps = scheduler.timesteps
32
+ num_inference_steps = len(timesteps)
33
+ elif sigmas is not None:
34
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
35
+ timesteps = scheduler.timesteps
36
+ num_inference_steps = len(timesteps)
37
+ else:
38
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
39
+ timesteps = scheduler.timesteps
40
+ return timesteps, num_inference_steps
41
+
42
+ # FLUX pipeline function
43
+ @torch.inference_mode()
44
+ def flux_pipe_call_that_returns_an_iterable_of_images(
45
+ self,
46
+ prompt: Union[str, List[str]] = None,
47
+ prompt_2: Optional[Union[str, List[str]]] = None,
48
+ height: Optional[int] = None,
49
+ width: Optional[int] = None,
50
+ num_inference_steps: int = 28,
51
+ timesteps: List[int] = None,
52
+ guidance_scale: float = 3.5,
53
+ num_images_per_prompt: Optional[int] = 1,
54
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
55
+ latents: Optional[torch.FloatTensor] = None,
56
+ prompt_embeds: Optional[torch.FloatTensor] = None,
57
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
58
+ output_type: Optional[str] = "pil",
59
+ return_dict: bool = True,
60
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
61
+ max_sequence_length: int = 512,
62
+ good_vae: Optional[Any] = None,
63
+ ):
64
+ height = height or self.default_sample_size * self.vae_scale_factor
65
+ width = width or self.default_sample_size * self.vae_scale_factor
66
+
67
+ # 1. Check inputs
68
+ self.check_inputs(
69
+ prompt,
70
+ prompt_2,
71
+ height,
72
+ width,
73
+ prompt_embeds=prompt_embeds,
74
+ pooled_prompt_embeds=pooled_prompt_embeds,
75
+ max_sequence_length=max_sequence_length,
76
+ )
77
+
78
+ self._guidance_scale = guidance_scale
79
+ self._joint_attention_kwargs = joint_attention_kwargs
80
+ self._interrupt = False
81
+
82
+ # 2. Define call parameters
83
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
84
+ device = self._execution_device
85
+
86
+ # 3. Encode prompt
87
+ lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None
88
+ prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
89
+ prompt=prompt,
90
+ prompt_2=prompt_2,
91
+ prompt_embeds=prompt_embeds,
92
+ pooled_prompt_embeds=pooled_prompt_embeds,
93
+ device=device,
94
+ num_images_per_prompt=num_images_per_prompt,
95
+ max_sequence_length=max_sequence_length,
96
+ lora_scale=lora_scale,
97
+ )
98
+ # 4. Prepare latent variables
99
+ num_channels_latents = self.transformer.config.in_channels // 4
100
+ latents, latent_image_ids = self.prepare_latents(
101
+ batch_size * num_images_per_prompt,
102
+ num_channels_latents,
103
+ height,
104
+ width,
105
+ prompt_embeds.dtype,
106
+ device,
107
+ generator,
108
+ latents,
109
+ )
110
+ # 5. Prepare timesteps
111
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
112
+ image_seq_len = latents.shape[1]
113
+ mu = calculate_shift(
114
+ image_seq_len,
115
+ self.scheduler.config.base_image_seq_len,
116
+ self.scheduler.config.max_image_seq_len,
117
+ self.scheduler.config.base_shift,
118
+ self.scheduler.config.max_shift,
119
+ )
120
+ timesteps, num_inference_steps = retrieve_timesteps(
121
+ self.scheduler,
122
+ num_inference_steps,
123
+ device,
124
+ timesteps,
125
+ sigmas,
126
+ mu=mu,
127
+ )
128
+ self._num_timesteps = len(timesteps)
129
+
130
+ # Handle guidance
131
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
132
+
133
+ # 6. Denoising loop
134
+ for i, t in enumerate(timesteps):
135
+ if self.interrupt:
136
+ continue
137
+
138
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
139
+
140
+ noise_pred = self.transformer(
141
+ hidden_states=latents,
142
+ timestep=timestep / 1000,
143
+ guidance=guidance,
144
+ pooled_projections=pooled_prompt_embeds,
145
+ encoder_hidden_states=prompt_embeds,
146
+ txt_ids=text_ids,
147
+ img_ids=latent_image_ids,
148
+ joint_attention_kwargs=self.joint_attention_kwargs,
149
+ return_dict=False,
150
+ )[0]
151
+ # Yield intermediate result
152
+ latents_for_image = self._unpack_latents(latents, height, width, self.vae_scale_factor)
153
+ latents_for_image = (latents_for_image / self.vae.config.scaling_factor) + self.vae.config.shift_factor
154
+ image = self.vae.decode(latents_for_image, return_dict=False)[0]
155
+ yield self.image_processor.postprocess(image, output_type=output_type)[0]
156
+
157
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
158
+ torch.cuda.empty_cache()
159
+
160
+ # Final image using good_vae
161
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
162
+ latents = (latents / good_vae.config.scaling_factor) + good_vae.config.shift_factor
163
+ image = good_vae.decode(latents, return_dict=False)[0]
164
+ self.maybe_free_model_hooks()
165
+ torch.cuda.empty_cache()
166
+ yield self.image_processor.postprocess(image, output_type=output_type)[0]
requirements.txt CHANGED
@@ -4,6 +4,7 @@ diffusers
4
  torch
5
  numpy
6
  transformers
 
7
  git+https://github.com/huggingface/diffusers.git
8
  sentencepiece
9
  scipy
 
4
  torch
5
  numpy
6
  transformers
7
+ xformers
8
  git+https://github.com/huggingface/diffusers.git
9
  sentencepiece
10
  scipy