onnew commited on
Commit
8e1a648
·
verified ·
1 Parent(s): c490090

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -136
app.py CHANGED
@@ -1,141 +1,34 @@
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
- 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)):
26
- if randomize_seed:
27
- seed = random.randint(0, MAX_SEED)
28
-
29
- generator = torch.Generator(device).manual_seed(seed)
30
-
31
- # Usando autograd em precisão reduzida (float16) para acelerar a inferência
32
- with torch.autocast("cuda", dtype=torch.float16):
33
- for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
34
- prompt=prompt,
35
- guidance_scale=guidance_scale,
36
- num_inference_steps=num_inference_steps,
37
- width=width,
38
- height=height,
39
- generator=generator,
40
- output_type="pil",
41
- good_vae=good_vae,
42
- ):
43
- yield img, seed
44
 
45
- torch.cuda.empty_cache() # Limpar a memória após a inferência para liberar recursos
46
-
47
- # Exemplos
48
- examples = [
49
- "a tiny astronaut hatching from an egg on the moon",
50
- "a cat holding a sign that says hello world",
51
- "an anime illustration of a wiener schnitzel",
52
- ]
53
-
54
- css = """
55
- #col-container {
56
- margin: 0 auto;
57
- max-width: 520px;
58
- }
59
- """
60
-
61
- # Interface Gradio
62
- with gr.Blocks(css=css) as demo:
63
- with gr.Column(elem_id="col-container"):
64
- gr.Markdown(f"""# FLUX.1 [dev]
65
- 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/)
66
- [[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)]
67
- """)
68
-
69
- with gr.Row():
70
- prompt = gr.Textbox(
71
- label="Prompt",
72
- show_label=False,
73
- max_lines=1,
74
- placeholder="Enter your prompt",
75
- container=False,
76
- )
77
- run_button = gr.Button("Run", scale=0)
78
 
79
- result = gr.Image(label="Result", show_label=False)
80
-
81
- with gr.Accordion("Advanced Settings", open=False):
82
- seed = gr.Slider(
83
- label="Seed",
84
- minimum=0,
85
- maximum=MAX_SEED,
86
- step=1,
87
- value=0,
88
- )
89
-
90
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
91
-
92
- with gr.Row():
93
- width = gr.Slider(
94
- label="Width",
95
- minimum=256,
96
- maximum=MAX_IMAGE_SIZE,
97
- step=32,
98
- value=1024,
99
- )
100
-
101
- height = gr.Slider(
102
- label="Height",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=1024,
107
- )
108
-
109
- with gr.Row():
110
- guidance_scale = gr.Slider(
111
- label="Guidance Scale",
112
- minimum=1,
113
- maximum=15,
114
- step=0.1,
115
- value=3.5,
116
- )
117
-
118
- num_inference_steps = gr.Slider(
119
- label="Number of inference steps",
120
- minimum=1,
121
- maximum=50,
122
- step=1,
123
- value=28,
124
- )
125
-
126
- gr.Examples(
127
- examples=examples,
128
- fn=infer,
129
- inputs=[prompt],
130
- outputs=[result, seed],
131
- cache_examples="lazy"
132
- )
133
-
134
- gr.Button.click(
135
- fn=infer,
136
- inputs=[prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
137
- outputs=[result, seed],
138
- )
139
 
140
- demo.launch()
141
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
+
4
+ # Carregar o pipeline de geração de imagens
5
+ pipe = pipeline("image-generation", model="stabilityai/stable-diffusion-2-1")
6
+
7
+ def generate_image(prompt):
8
+ """
9
+ Gera uma imagem com base em um prompt textual usando o modelo.
10
+ """
11
+ try:
12
+ # Gera a imagem
13
+ image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5)[0]["image"]
14
+ return image
15
+ except Exception as e:
16
+ return f"Erro ao gerar imagem: {str(e)}"
17
+
18
+ # Configurar a interface do Gradio
19
+ with gr.Blocks() as demo:
20
+ gr.Markdown("## Gerador de Imagens com Texto - Stable Diffusion")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ with gr.Row():
23
+ with gr.Column():
24
+ prompt = gr.Textbox(label="Texto (Prompt)", placeholder="Descreva a imagem que deseja gerar...")
25
+ submit_button = gr.Button("Gerar Imagem")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ with gr.Column():
28
+ output_image = gr.Image(label="Imagem Gerada")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ submit_button.click(fn=generate_image, inputs=prompt, outputs=output_image)
31
 
32
+ # Executar o app
33
+ if __name__ == "__main__":
34
+ demo.launch(server_name="0.0.0.0", server_port=7860)