FrankFacundo commited on
Commit
46af7ed
·
1 Parent(s): b3445fb
Files changed (2) hide show
  1. app.py +160 -119
  2. requirements.txt +2 -1
app.py CHANGED
@@ -1,153 +1,194 @@
1
- import gradio as gr
2
  import numpy as np
 
 
 
3
  import random
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
 
16
 
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
 
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
 
22
 
23
 
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
  def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
  ):
 
 
 
36
  if randomize_seed:
37
  seed = random.randint(0, MAX_SEED)
38
 
39
- generator = torch.Generator().manual_seed(seed)
 
40
 
41
- image = pipe(
42
  prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
 
 
 
45
  num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
  ).images[0]
50
 
51
- return image, seed
 
52
 
53
 
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
 
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
 
 
 
 
 
 
 
 
78
  )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
-
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
  )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
  )
 
 
 
99
 
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
-
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
  fn=infer,
140
  inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
  ],
150
- outputs=[result, seed],
151
  )
152
 
153
  if __name__ == "__main__":
 
 
1
  import numpy as np
2
+ import gradio as gr
3
+ import spaces
4
+ import os
5
  import random
6
 
 
 
7
  import torch
8
+ from PIL import Image
9
+ import cv2
10
+ from huggingface_hub import login
11
+ from diffusers import FluxControlNetPipeline, FluxControlNetModel
12
+ from diffusers.models import FluxMultiControlNetModel
13
+
14
+ """
15
+ FLUX‑1 ControlNet demo
16
+ ----------------------
17
+ This script rebuilds the Gradio interface shown in your screenshot with **one** control‑image upload
18
+ slot and integrates the FLUX.1‑dev‑ControlNet‑Union‑Pro model.
19
+
20
+ Key points
21
+ ~~~~~~~~~~
22
+ * Single *control image* input (left).
23
+ * *Result* and *Pre‑processed Cond* previews side‑by‑side (center & right).
24
+ * *Prompt* textbox plus a dedicated **ControlNet** panel for choosing the mode and strength.
25
+ * Seed handling with optional randomisation.
26
+ * Advanced sliders for *Guidance scale* and *Inference steps*.
27
+ * Works on CUDA (bfloat16) or CPU (float32).
28
+ * Minimal Canny preview implementation when the *canny* mode is selected (extend as you like for the
29
+ other modes).
30
+
31
+ Before running, set the `HUGGINGFACE_TOKEN` environment variable **or** call
32
+ `login("<YOUR_HF_TOKEN>")` explicitly.
33
+ """
34
+
35
+ # --------------------------------------------------
36
+ # Model & pipeline setup
37
+ # --------------------------------------------------
38
+ HF_TOKEN = os.getenv("HF_TOKEN_NEW")
39
+ login(HF_TOKEN)
40
+ # If you prefer to hard‑code the token, uncomment:
41
+ # login("hf_your_token_here")
42
+
43
+ BASE_MODEL = "black-forest-labs/FLUX.1-dev"
44
+ CONTROLNET_MODEL = "Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro"
45
 
46
  device = "cuda" if torch.cuda.is_available() else "cpu"
47
+ dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
48
+
49
+ controlnet_single = FluxControlNetModel.from_pretrained(
50
+ CONTROLNET_MODEL, torch_dtype=dtype
51
+ )
52
+ controlnet = FluxMultiControlNetModel([controlnet_single])
53
+
54
+ pipe = FluxControlNetPipeline.from_pretrained(
55
+ BASE_MODEL, controlnet=controlnet, torch_dtype=dtype
56
+ ).to(device)
57
+ pipe.set_progress_bar_config(disable=True)
58
+
59
+ # --------------------------------------------------
60
+ # UI ‑> model value mapping
61
+ # --------------------------------------------------
62
+ MODE_MAPPING = {
63
+ "canny": 0,
64
+ "depth": 1,
65
+ "openpose": 2,
66
+ "gray": 3,
67
+ "blur": 4,
68
+ "tile": 5,
69
+ "low quality": 6,
70
+ }
71
+
72
+ MAX_SEED = 100
73
+
74
+ # --------------------------------------------------
75
+ # Helper: quick‑n‑dirty Canny preview (only for UI display)
76
+ # --------------------------------------------------
77
+
78
+
79
+ def _preview_canny(pil_img: Image.Image) -> Image.Image:
80
+ arr = np.array(pil_img.convert("RGB"))
81
+ edges = cv2.Canny(arr, 100, 200)
82
+ edges_rgb = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
83
+ return Image.fromarray(edges_rgb)
84
+
85
 
86
+ def _make_preview(control_image: Image.Image, mode: str) -> Image.Image:
87
+ if mode == "canny":
88
+ return _preview_canny(control_image)
89
+ # For other modes you can plug in your own visualiser later
90
+ return control_image
91
 
 
 
92
 
93
+ # --------------------------------------------------
94
+ # Inference function
95
+ # --------------------------------------------------
96
 
97
 
98
+ @spaces.GPU
99
  def infer(
100
+ control_image: Image.Image,
101
+ prompt: str,
102
+ mode: str,
103
+ control_strength: float,
104
+ seed: int,
105
+ randomize_seed: bool,
106
+ guidance_scale: float,
107
+ num_inference_steps: int,
 
108
  ):
109
+ if control_image is None:
110
+ raise gr.Error("Please upload a control image first.")
111
+
112
  if randomize_seed:
113
  seed = random.randint(0, MAX_SEED)
114
 
115
+ gen = torch.Generator(device).manual_seed(seed)
116
+ w, h = control_image.size
117
 
118
+ result = pipe(
119
  prompt=prompt,
120
+ control_image=[control_image],
121
+ control_mode=[MODE_MAPPING[mode]],
122
+ width=w,
123
+ height=h,
124
+ controlnet_conditioning_scale=[control_strength],
125
  num_inference_steps=num_inference_steps,
126
+ guidance_scale=guidance_scale,
127
+ generator=gen,
 
128
  ).images[0]
129
 
130
+ preview = _make_preview(control_image, mode)
131
+ return result, seed, preview
132
 
133
 
134
+ # --------------------------------------------------
135
+ # Gradio UI
136
+ # --------------------------------------------------
137
+ css = """#wrapper {max-width: 960px; margin: 0 auto;}"""
138
+ with gr.Blocks(css=css, elem_id="wrapper") as demo:
139
+ gr.Markdown("## FLUX.1‑dev‑ControlNet‑Union‑Pro")
140
+ gr.Markdown(
141
+ "A unified ControlNet for **FLUX.1‑dev** from the InstantX team and Shakker Labs. "
142
+ + "Recommended strengths: *canny 0.65*, *tile 0.45*, *depth 0.55*, *blur 0.45*, "
143
+ + "*openpose 0.55*, *gray 0.45*, *low quality 0.40*. Long prompts usually help."
144
+ )
 
145
 
146
+ # ------------ Image panel row ------------
147
+ with gr.Row():
148
+ control_image = gr.Image(
149
+ label="Upload a processed control image",
150
+ type="pil",
151
+ height=512,
152
+ )
153
+ result_image = gr.Image(label="Result", height=512)
154
+ preview_image = gr.Image(label="Pre‑processed Cond", height=512)
155
+
156
+ # ------------ Prompt ------------
157
+ prompt_txt = gr.Textbox(label="Prompt", value="best quality", lines=1)
158
+
159
+ # ------------ ControlNet settings ------------
160
+ with gr.Row():
161
+ with gr.Column():
162
+ gr.Markdown("### ControlNet")
163
+ mode_radio = gr.Radio(
164
+ choices=list(MODE_MAPPING.keys()), value="gray", label="Mode"
165
  )
166
+ strength_slider = gr.Slider(
167
+ 0.0, 1.0, value=0.5, step=0.01, label="control strength"
 
 
 
 
 
 
 
 
 
168
  )
169
+ with gr.Column():
170
+ seed_slider = gr.Slider(0, MAX_SEED, step=1, value=42, label="Seed")
171
+ randomize_chk = gr.Checkbox(label="Randomize seed", value=True)
172
+ guidance_slider = gr.Slider(
173
+ 0.0, 10.0, step=0.1, value=3.5, label="Guidance scale"
 
 
174
  )
175
+ steps_slider = gr.Slider(1, 50, step=1, value=24, label="Inference steps")
176
+
177
+ submit_btn = gr.Button("Submit")
178
 
179
+ submit_btn.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  fn=infer,
181
  inputs=[
182
+ control_image,
183
+ prompt_txt,
184
+ mode_radio,
185
+ strength_slider,
186
+ seed_slider,
187
+ randomize_chk,
188
+ guidance_slider,
189
+ steps_slider,
190
  ],
191
+ outputs=[result_image, seed_slider, preview_image],
192
  )
193
 
194
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -3,4 +3,5 @@ diffusers
3
  invisible_watermark
4
  torch
5
  transformers
6
- xformers
 
 
3
  invisible_watermark
4
  torch
5
  transformers
6
+ xformers
7
+ sentencepiece==0.2.0