vilarin commited on
Commit
0dec378
1 Parent(s): 12ed65b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -174
app.py CHANGED
@@ -1,175 +1,195 @@
1
- import os
2
- import gradio as gr
3
- import torch
4
- import numpy as np
5
- import random
6
- from diffusers import FluxPipeline
7
- import spaces
8
- from optimum.quanto import freeze, qfloat8, quantize
9
- from translatepy import Translator
10
-
11
-
12
- os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
13
- translator = Translator()
14
- HF_TOKEN = os.environ.get("HF_TOKEN", None)
15
- # Constants
16
- model = "black-forest-labs/FLUX.1-dev"
17
- MAX_SEED = np.iinfo(np.int32).max
18
-
19
- CSS = """
20
- footer {
21
- visibility: hidden;
22
- }
23
- """
24
-
25
- JS = """function () {
26
- gradioURL = window.location.href
27
- if (!gradioURL.endsWith('?__theme=dark')) {
28
- window.location.replace(gradioURL + '?__theme=dark');
29
- }
30
- }"""
31
-
32
- pipe = FluxPipeline.from_pretrained(
33
- model,
34
- torch_dtype=torch.bfloat16).to("cuda")
35
-
36
- quantize(pipe.transformer, weights=qfloat8)
37
- freeze(pipe.transformer)
38
-
39
- quantize(pipe.text_encoder_2, weights=qfloat8)
40
- freeze(pipe.text_encoder_2)
41
-
42
- pipe.enable_model_cpu_offload()
43
- pipe.to("cuda")
44
-
45
- # Function
46
- @spaces.GPU()
47
- def generate_image(
48
- prompt,
49
- width=1024,
50
- height=1024,
51
- scales=5,
52
- steps=30,
53
- seed: int =-1,
54
- nums=1,
55
- progress=gr.Progress(track_tqdm=True)):
56
-
57
- if seed == -1:
58
- seed = random.randint(0, MAX_SEED)
59
- seed = int(seed)
60
- print(f'prompt:{prompt}')
61
-
62
- text = str(translator.translate(prompt, 'English'))
63
-
64
- generator = torch.Generator().manual_seed(seed)
65
-
66
-
67
- image = pipe(
68
- prompt=text,
69
- height=height,
70
- width=width,
71
- guidance_scale=scales,
72
- output_type="pil",
73
- num_inference_steps=steps,
74
- max_sequence_length=512,
75
- num_images_per_prompt=nums,
76
- generator=generator,
77
- ).images
78
-
79
- print(image)
80
- print(seed)
81
- return image, seed
82
-
83
-
84
- examples = [
85
- "a female character with long, flowing hair that appears to be made of ethereal, swirling patterns resembling the Northern Lights or Aurora Borealis. The background is dominated by deep blues and purples, creating a mysterious and dramatic atmosphere. The character's face is serene, with pale skin and striking features. She wears a dark-colored outfit with subtle patterns. The overall style of the artwork is reminiscent of fantasy or supernatural genres",
86
- "Digital art, portrait of an anthropomorphic roaring Tiger warrior with full armor, close up in the middle of a battle, behind him there is a banner with the text \"Open Source\".",
87
- "photo of a dog and a cat both standing on a red box, with a blue ball in the middle with a parrot standing on top of the ball. The box has the text \"FLUX\"",
88
- "selfie photo of a wizard with long beard and purple robes, he is apparently in the middle of Tokyo. Probably taken from a phone.",
89
- "A vibrant street wall covered in colorful graffiti, the centerpiece spells \"FLUX\", in a storm of colors",
90
- "photo of a young woman with long, wavy brown hair tied in a bun and glasses. She has a fair complexion and is wearing subtle makeup, emphasizing her eyes and lips. She is dressed in a black top. The background appears to be an urban setting with a building facade, and the sunlight casts a warm glow on her face.",
91
- "anime art of a steampunk inventor in their workshop, surrounded by gears, gadgets, and steam. He is holding a blue potion and a red potion, one in each hand",
92
- "photo of picturesque scene of a road surrounded by lush green trees and shrubs. The road is wide and smooth, leading into the distance. On the right side of the road, there's a blue sports car parked with the license plate spelling \"FLUX\". The sky above is partly cloudy, suggesting a pleasant day. The trees have a mix of green and brown foliage. There are no people visible in the image. The overall composition is balanced, with the car serving as a focal point.",
93
- "photo of young man in a black suit, white shirt, and black tie. He has a neatly styled haircut and is looking directly at the camera with a neutral expression. The background consists of a textured wall with horizontal lines. The photograph is in black and white, emphasizing contrasts and shadows. The man appears to be in his late twenties or early thirties, with fair skin and short, dark hair.",
94
- "photo of a woman on the beach, shot from above. She is facing the sea, while wearing a white dress. She has long blonde hair"
95
- ]
96
-
97
-
98
-
99
- # Gradio Interface
100
-
101
- with gr.Blocks(css=CSS, js=JS, theme="soft") as demo:
102
- gr.HTML("<h1><center>Flux Dev Quanto</center></h1>")
103
- gr.HTML("<p><center><a href='https://huggingface.co/black-forest-labs/FLUX.1-dev'>FLUX.1 DEV</a> with <a href='https://huggingface.co/blog/quanto-diffusers'>Quanto</a></center></p>")
104
- with gr.Row():
105
- with gr.Column(scale=4):
106
- img = gr.Gallery(label='flux Generated Image', columns = 1, preview=True, height=600)
107
- with gr.Row():
108
- prompt = gr.Textbox(label='Enter Your Prompt (Multi-Languages)', placeholder="Enter prompt...", scale=6)
109
- sendBtn = gr.Button(scale=1, variant='primary')
110
- with gr.Accordion("Advanced Options", open=True):
111
- with gr.Column(scale=1):
112
- width = gr.Slider(
113
- label="Width",
114
- minimum=512,
115
- maximum=1280,
116
- step=8,
117
- value=1024,
118
- )
119
- height = gr.Slider(
120
- label="Height",
121
- minimum=512,
122
- maximum=1280,
123
- step=8,
124
- value=1024,
125
- )
126
- scales = gr.Slider(
127
- label="Guidance",
128
- minimum=3.5,
129
- maximum=7,
130
- step=0.1,
131
- value=3.5,
132
- )
133
- steps = gr.Slider(
134
- label="Steps",
135
- minimum=1,
136
- maximum=100,
137
- step=1,
138
- value=30,
139
- )
140
- seed = gr.Slider(
141
- label="Seeds",
142
- minimum=-1,
143
- maximum=MAX_SEED,
144
- step=1,
145
- value=-1,
146
- scale=2,
147
- )
148
- nums = gr.Slider(
149
- label="Image Numbers",
150
- minimum=1,
151
- maximum=4,
152
- step=1,
153
- value=1,
154
- scale=1,
155
- )
156
- gr.Examples(
157
- examples=examples,
158
- inputs=prompt,
159
- outputs=[img, seed],
160
- fn=generate_image,
161
- cache_examples="lazy",
162
- examples_per_page=4,
163
- )
164
-
165
- sendBtn.click(fn=generate_image,
166
- inputs=[prompt, width, height, scales, steps, seed, nums],
167
- outputs=[img, seed],
168
- )
169
- prompt.submit(fn=generate_image,
170
- inputs=[prompt, width, height, scales, steps, seed, nums],
171
- outputs=[img, seed],
172
- )
173
-
174
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  demo.queue().launch()
 
1
+ import os
2
+ import gradio as gr
3
+ import torch
4
+ import numpy as np
5
+ import random
6
+ from diffusers import FluxPipeline, FluxTransformer2DModel
7
+ import spaces
8
+ from transformers import T5EncoderModel
9
+ from optimum.quanto import QuantizedDiffusersModel
10
+ from translatepy import Translator
11
+ from huggingface_hub import hf_hub_download
12
+
13
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
14
+ translator = Translator()
15
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
16
+ # Constants
17
+ r_model = "black-forest-labs/FLUX.1-dev"
18
+ model = "./model/"
19
+ MAX_SEED = np.iinfo(np.int32).max
20
+
21
+ CSS = """
22
+ footer {
23
+ visibility: hidden;
24
+ }
25
+ """
26
+
27
+ JS = """function () {
28
+ gradioURL = window.location.href
29
+ if (!gradioURL.endsWith('?__theme=dark')) {
30
+ window.location.replace(gradioURL + '?__theme=dark');
31
+ }
32
+ }"""
33
+
34
+ filenames = [
35
+ "flux1-dev-fp8.safetensors",
36
+ "t5xxl_fp8_e4m3fn.safetensors",
37
+ ]
38
+
39
+ for filename in filenames:
40
+ downloaded_model_path = hf_hub_download(
41
+ repo_id="camenduru/FLUX.1-dev",
42
+ filename=filename,
43
+ local_dir="model"
44
+ )
45
+
46
+ class QuantizedFluxTransformer2DModel(QuantizedDiffusersModel):
47
+ base_class = FluxTransformer2DModel
48
+
49
+ transformer = QuantizedFluxTransformer2DModel.from_pretrained(model)
50
+ transformer.to(device="cuda", dtype=torch.float16)
51
+
52
+ text_encoder_2 = T5EncoderModel.from_pretrained(
53
+ model,
54
+ torch_dtype=torch.float16)
55
+
56
+
57
+ pipe = FluxPipeline.from_pretrained(
58
+ r_model,
59
+ transformer=None,
60
+ text_encoder_2=text_encoder_2,
61
+ torch_dtype=torch.float16,).to("cuda")
62
+
63
+ pipe.transformer = transformer
64
+
65
+ # Function
66
+ @spaces.GPU()
67
+ def generate_image(
68
+ prompt,
69
+ width=1024,
70
+ height=1024,
71
+ scales=5,
72
+ steps=30,
73
+ seed: int =-1,
74
+ nums=1,
75
+ progress=gr.Progress(track_tqdm=True)):
76
+
77
+ if seed == -1:
78
+ seed = random.randint(0, MAX_SEED)
79
+ seed = int(seed)
80
+ print(f'prompt:{prompt}')
81
+
82
+ text = str(translator.translate(prompt, 'English'))
83
+
84
+ generator = torch.Generator().manual_seed(seed)
85
+
86
+
87
+ image = pipe(
88
+ prompt=text,
89
+ height=height,
90
+ width=width,
91
+ guidance_scale=scales,
92
+ output_type="pil",
93
+ num_inference_steps=steps,
94
+ max_sequence_length=512,
95
+ num_images_per_prompt=nums,
96
+ generator=generator,
97
+ ).images
98
+
99
+ print(image)
100
+ print(seed)
101
+ return image, seed
102
+
103
+
104
+ examples = [
105
+ "a female character with long, flowing hair that appears to be made of ethereal, swirling patterns resembling the Northern Lights or Aurora Borealis. The background is dominated by deep blues and purples, creating a mysterious and dramatic atmosphere. The character's face is serene, with pale skin and striking features. She wears a dark-colored outfit with subtle patterns. The overall style of the artwork is reminiscent of fantasy or supernatural genres",
106
+ "Digital art, portrait of an anthropomorphic roaring Tiger warrior with full armor, close up in the middle of a battle, behind him there is a banner with the text \"Open Source\".",
107
+ "photo of a dog and a cat both standing on a red box, with a blue ball in the middle with a parrot standing on top of the ball. The box has the text \"FLUX\"",
108
+ "selfie photo of a wizard with long beard and purple robes, he is apparently in the middle of Tokyo. Probably taken from a phone.",
109
+ "A vibrant street wall covered in colorful graffiti, the centerpiece spells \"FLUX\", in a storm of colors",
110
+ "photo of a young woman with long, wavy brown hair tied in a bun and glasses. She has a fair complexion and is wearing subtle makeup, emphasizing her eyes and lips. She is dressed in a black top. The background appears to be an urban setting with a building facade, and the sunlight casts a warm glow on her face.",
111
+ "anime art of a steampunk inventor in their workshop, surrounded by gears, gadgets, and steam. He is holding a blue potion and a red potion, one in each hand",
112
+ "photo of picturesque scene of a road surrounded by lush green trees and shrubs. The road is wide and smooth, leading into the distance. On the right side of the road, there's a blue sports car parked with the license plate spelling \"FLUX\". The sky above is partly cloudy, suggesting a pleasant day. The trees have a mix of green and brown foliage. There are no people visible in the image. The overall composition is balanced, with the car serving as a focal point.",
113
+ "photo of young man in a black suit, white shirt, and black tie. He has a neatly styled haircut and is looking directly at the camera with a neutral expression. The background consists of a textured wall with horizontal lines. The photograph is in black and white, emphasizing contrasts and shadows. The man appears to be in his late twenties or early thirties, with fair skin and short, dark hair.",
114
+ "photo of a woman on the beach, shot from above. She is facing the sea, while wearing a white dress. She has long blonde hair"
115
+ ]
116
+
117
+
118
+
119
+ # Gradio Interface
120
+
121
+ with gr.Blocks(css=CSS, js=JS, theme="soft") as demo:
122
+ gr.HTML("<h1><center>Flux Dev Quanto</center></h1>")
123
+ gr.HTML("<p><center><a href='https://huggingface.co/black-forest-labs/FLUX.1-dev'>FLUX.1 DEV</a> with <a href='https://huggingface.co/blog/quanto-diffusers'>Quanto</a></center></p>")
124
+ with gr.Row():
125
+ with gr.Column(scale=4):
126
+ img = gr.Gallery(label='flux Generated Image', columns = 1, preview=True, height=600)
127
+ with gr.Row():
128
+ prompt = gr.Textbox(label='Enter Your Prompt (Multi-Languages)', placeholder="Enter prompt...", scale=6)
129
+ sendBtn = gr.Button(scale=1, variant='primary')
130
+ with gr.Accordion("Advanced Options", open=True):
131
+ with gr.Column(scale=1):
132
+ width = gr.Slider(
133
+ label="Width",
134
+ minimum=512,
135
+ maximum=1280,
136
+ step=8,
137
+ value=1024,
138
+ )
139
+ height = gr.Slider(
140
+ label="Height",
141
+ minimum=512,
142
+ maximum=1280,
143
+ step=8,
144
+ value=1024,
145
+ )
146
+ scales = gr.Slider(
147
+ label="Guidance",
148
+ minimum=3.5,
149
+ maximum=7,
150
+ step=0.1,
151
+ value=3.5,
152
+ )
153
+ steps = gr.Slider(
154
+ label="Steps",
155
+ minimum=1,
156
+ maximum=100,
157
+ step=1,
158
+ value=30,
159
+ )
160
+ seed = gr.Slider(
161
+ label="Seeds",
162
+ minimum=-1,
163
+ maximum=MAX_SEED,
164
+ step=1,
165
+ value=-1,
166
+ scale=2,
167
+ )
168
+ nums = gr.Slider(
169
+ label="Image Numbers",
170
+ minimum=1,
171
+ maximum=4,
172
+ step=1,
173
+ value=1,
174
+ scale=1,
175
+ )
176
+ gr.Examples(
177
+ examples=examples,
178
+ inputs=prompt,
179
+ outputs=[img, seed],
180
+ fn=generate_image,
181
+ cache_examples="lazy",
182
+ examples_per_page=4,
183
+ )
184
+
185
+ sendBtn.click(fn=generate_image,
186
+ inputs=[prompt, width, height, scales, steps, seed, nums],
187
+ outputs=[img, seed],
188
+ )
189
+ prompt.submit(fn=generate_image,
190
+ inputs=[prompt, width, height, scales, steps, seed, nums],
191
+ outputs=[img, seed],
192
+ )
193
+
194
+
195
  demo.queue().launch()