sab commited on
Commit
966325b
1 Parent(s): c3839fc

test with flux

Browse files
Files changed (1) hide show
  1. app_v2.py +167 -0
app_v2.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import random
4
+ import spaces
5
+ import torch
6
+ from diffusers import DiffusionPipeline, 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
+ import requests
10
+ import base64
11
+ import os
12
+ from PIL import Image
13
+ from io import BytesIO
14
+ from gradio_imageslider import ImageSlider # Assicurati di avere questa libreria installata
15
+ from loadimg import load_img # Assicurati che questa funzione sia disponibile
16
+ from dotenv import load_dotenv
17
+
18
+ # Carica le variabili di ambiente dal file .env
19
+ load_dotenv()
20
+
21
+ dtype = torch.bfloat16
22
+ device = "cuda" if torch.cuda.is_available() else "cpu"
23
+ taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
24
+ good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=dtype).to(device)
25
+ pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=dtype, vae=taef1).to(device)
26
+ torch.cuda.empty_cache()
27
+
28
+ MAX_SEED = np.iinfo(np.int32).max
29
+ MAX_IMAGE_SIZE = 2048
30
+
31
+ pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
32
+
33
+ output_folder = 'output_images'
34
+ if not os.path.exists(output_folder):
35
+ os.makedirs(output_folder)
36
+
37
+
38
+ def numpy_to_pil(image):
39
+ """Convert a numpy array to a PIL Image."""
40
+ if image.dtype == np.uint8: # Most common case
41
+ mode = "RGB"
42
+ else:
43
+ mode = "F" # Floating point
44
+ return Image.fromarray(image.astype('uint8'), mode)
45
+
46
+
47
+ def process_image(image):
48
+ image = numpy_to_pil(image) # Convert numpy array to PIL Image
49
+ buffered = BytesIO()
50
+ image.save(buffered, format="PNG")
51
+ img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
52
+ response = requests.post(
53
+ os.getenv('BACKEND_URL'),
54
+ files={"file": ("image.png", base64.b64decode(img_str), "image/png")}
55
+ )
56
+ result = response.json()
57
+ processed_image_b64 = result["processed_image"]
58
+ processed_image = Image.open(BytesIO(base64.b64decode(processed_image_b64)))
59
+ image_path = os.path.join(output_folder, "no_bg_image.png")
60
+ processed_image.save(image_path)
61
+ return (processed_image, image), image_path
62
+
63
+
64
+ @spaces.GPU(duration=75)
65
+ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=3.5, num_inference_steps=28,
66
+ progress=gr.Progress(track_tqdm=True)):
67
+ if randomize_seed:
68
+ seed = random.randint(0, MAX_SEED)
69
+ generator = torch.Generator().manual_seed(seed)
70
+ for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
71
+ prompt=prompt,
72
+ guidance_scale=guidance_scale,
73
+ num_inference_steps=num_inference_steps,
74
+ width=width,
75
+ height=height,
76
+ generator=generator,
77
+ output_type="pil",
78
+ good_vae=good_vae,
79
+ ):
80
+ img_np = np.array(img)
81
+ processed_images, image_path = process_image(img_np)
82
+ yield processed_images[0], seed, processed_images[1], image_path
83
+
84
+
85
+ examples = [
86
+ "a tiny astronaut hatching from an egg on the moon",
87
+ "a cat holding a sign that says hello world",
88
+ "an anime illustration of a wiener schnitzel",
89
+ ]
90
+
91
+ css = """
92
+ #col-container {
93
+ margin: 0 auto;
94
+ max-width: 520px;
95
+ }
96
+ """
97
+
98
+ with gr.Blocks(css=css) as demo:
99
+ with gr.Column(elem_id="col-container"):
100
+ gr.Markdown(f"""# FLUX.1 [dev]
101
+ 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/) [[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)]
102
+ """)
103
+ with gr.Row():
104
+ prompt = gr.Text(
105
+ label="Prompt",
106
+ show_label=False,
107
+ max_lines=1,
108
+ placeholder="Enter your prompt",
109
+ container=False,
110
+ )
111
+ run_button = gr.Button("Run", scale=0)
112
+ result = gr.Image(label="Generated Image", show_label=False)
113
+ output_slider = ImageSlider(label="Processed Photo", type="pil")
114
+ output_file = gr.File(label="Output PNG file")
115
+ with gr.Accordion("Advanced Settings", open=False):
116
+ seed = gr.Slider(
117
+ label="Seed",
118
+ minimum=0,
119
+ maximum=MAX_SEED,
120
+ step=1,
121
+ value=0,
122
+ )
123
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
124
+ with gr.Row():
125
+ width = gr.Slider(
126
+ label="Width",
127
+ minimum=256,
128
+ maximum=MAX_IMAGE_SIZE,
129
+ step=32,
130
+ value=1024,
131
+ )
132
+ height = gr.Slider(
133
+ label="Height",
134
+ minimum=256,
135
+ maximum=MAX_IMAGE_SIZE,
136
+ step=32,
137
+ value=1024,
138
+ )
139
+ with gr.Row():
140
+ guidance_scale = gr.Slider(
141
+ label="Guidance Scale",
142
+ minimum=1,
143
+ maximum=15,
144
+ step=0.1,
145
+ value=3.5,
146
+ )
147
+ num_inference_steps = gr.Slider(
148
+ label="Number of inference steps",
149
+ minimum=1,
150
+ maximum=50,
151
+ step=1,
152
+ value=28,
153
+ )
154
+ gr.Examples(
155
+ examples=examples,
156
+ fn=infer,
157
+ inputs=[prompt],
158
+ outputs=[result, seed, output_slider, output_file],
159
+ cache_examples="lazy"
160
+ )
161
+ gr.on(
162
+ triggers=[run_button.click, prompt.submit],
163
+ fn=infer,
164
+ inputs=[prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
165
+ outputs=[result, seed, output_slider, output_file]
166
+ )
167
+ demo.launch()