onnew commited on
Commit
18a64af
·
verified ·
1 Parent(s): 4d8efef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -37
app.py CHANGED
@@ -1,44 +1,143 @@
1
  import gradio as gr
2
  import numpy as np
3
- from PIL import Image, ImageDraw, ImageFont
4
-
5
- # Função para gerar a imagem
6
- def generate_image():
7
- # Criar uma imagem em branco
8
- img = Image.new("RGB", (512, 512), color=(255, 255, 255))
9
- draw = ImageDraw.Draw(img)
10
-
11
- # Definir gradiente de amarelo para rosa
12
- gradient = np.zeros((512, 512, 3), dtype=np.uint8)
13
- for i in range(512):
14
- for j in range(512):
15
- r = int((i / 512) * 255) # Gradiente de vermelho
16
- g = int((i / 512) * 255) # Gradiente de verde
17
- b = int(255 - (i / 512) * 255) # Gradiente de azul
18
- gradient[i, j] = [r, g, b]
19
-
20
- # Converter o gradiente para uma imagem PIL
21
- gradient_img = Image.fromarray(gradient)
22
- img.paste(gradient_img, (0, 0))
23
-
24
- # Adicionar o título na imagem
25
- font = ImageFont.load_default()
26
- draw.text((20, 20), "FLUX.1 [dev] 🖥️", font=font, fill=(0, 0, 0))
27
-
28
- return img
29
-
30
- # Definir a interface Gradio
31
- with gr.Blocks() as demo:
32
- with gr.Row():
33
- gr.Markdown("### FLUX.1 [dev] 🖥️")
34
- gr.Markdown(
35
- "This is a Gradio app using FLUX.1. The app generates an image with a yellow to pink gradient."
36
- )
37
- result = gr.Image(label="Generated Image")
38
 
39
- gr.Button("Generate Image").click(generate_image, outputs=[result])
 
 
40
 
41
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
 
 
 
 
 
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
 
1
  import gradio as gr
2
  import numpy as np
3
+ import random
4
+ import torch
5
+ from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL
6
+ from transformers import CLIPTextModel, CLIPTokenizer
7
+ from live_preview_helpers import flux_pipe_call_that_returns_an_iterable_of_images
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # Definindo variáveis e carregando modelos
10
+ dtype = torch.float16 # Usando float16 para melhorar a performance
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
+ pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
17
+
18
+ torch.cuda.empty_cache()
19
+
20
+ MAX_SEED = np.iinfo(np.int32).max
21
+ MAX_IMAGE_SIZE = 2048
22
+
23
+ # Função de inferência otimizada
24
+ @torch.inference_mode() # Desabilitando cálculo de gradientes para acelerar a inferência
25
+ @spaces.GPU(duration=75)
26
+ 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)):
27
+ if randomize_seed:
28
+ seed = random.randint(0, MAX_SEED)
29
+
30
+ generator = torch.Generator(device).manual_seed(seed)
31
+
32
+ # Usando autograd em precisão reduzida (float16) para acelerar a inferência
33
+ with torch.autocast("cuda", dtype=torch.float16):
34
+ for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
35
+ prompt=prompt,
36
+ guidance_scale=guidance_scale,
37
+ num_inference_steps=num_inference_steps,
38
+ width=width,
39
+ height=height,
40
+ generator=generator,
41
+ output_type="pil",
42
+ good_vae=good_vae,
43
+ ):
44
+ yield img, seed
45
+
46
+ torch.cuda.empty_cache() # Limpar a memória após a inferência para liberar recursos
47
 
48
+ # Exemplos
49
+ examples = [
50
+ "a tiny astronaut hatching from an egg on the moon",
51
+ "a cat holding a sign that says hello world",
52
+ "an anime illustration of a wiener schnitzel",
53
+ ]
54
 
55
+ css = """
56
+ #col-container {
57
+ margin: 0 auto;
58
+ max-width: 520px;
59
+ }
60
+ """
61
+
62
+ # Interface Gradio
63
+ with gr.Blocks(css=css) as demo:
64
+ with gr.Column(elem_id="col-container"):
65
+ gr.Markdown(f"""# FLUX.1 [dev]
66
+ 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/)
67
+ [[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)]
68
+ """)
69
+
70
+ with gr.Row():
71
+ prompt = gr.Text(
72
+ label="Prompt",
73
+ show_label=False,
74
+ max_lines=1,
75
+ placeholder="Enter your prompt",
76
+ container=False,
77
+ )
78
+ run_button = gr.Button("Run", scale=0)
79
+
80
+ result = gr.Image(label="Result", show_label=False)
81
+
82
+ with gr.Accordion("Advanced Settings", open=False):
83
+ seed = gr.Slider(
84
+ label="Seed",
85
+ minimum=0,
86
+ maximum=MAX_SEED,
87
+ step=1,
88
+ value=0,
89
+ )
90
+
91
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
92
+
93
+ with gr.Row():
94
+ width = gr.Slider(
95
+ label="Width",
96
+ minimum=256,
97
+ maximum=MAX_IMAGE_SIZE,
98
+ step=32,
99
+ value=1024,
100
+ )
101
+
102
+ height = gr.Slider(
103
+ label="Height",
104
+ minimum=256,
105
+ maximum=MAX_IMAGE_SIZE,
106
+ step=32,
107
+ value=1024,
108
+ )
109
+
110
+ with gr.Row():
111
+ guidance_scale = gr.Slider(
112
+ label="Guidance Scale",
113
+ minimum=1,
114
+ maximum=15,
115
+ step=0.1,
116
+ value=3.5,
117
+ )
118
+
119
+ num_inference_steps = gr.Slider(
120
+ label="Number of inference steps",
121
+ minimum=1,
122
+ maximum=50,
123
+ step=1,
124
+ value=28,
125
+ )
126
+
127
+ gr.Examples(
128
+ examples=examples,
129
+ fn=infer,
130
+ inputs=[prompt],
131
+ outputs=[result, seed],
132
+ cache_examples="lazy"
133
+ )
134
+
135
+ gr.on(
136
+ triggers=[run_button.click, prompt.submit],
137
+ fn=infer,
138
+ inputs=[prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
139
+ outputs=[result, seed]
140
+ )
141
+
142
+ demo.launch()
143