File size: 9,338 Bytes
1b6b50c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
431b1a3
1b6b50c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
431b1a3
1b6b50c
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
from functools import lru_cache

import gradio as gr
from gradio_client import Client


MODEL_SPACE = "black-forest-labs/FLUX.1-schnell"
DEFAULT_PROMPT = (
    "A highly realistic photograph of a peaceful working farm in the Canadian "
    "countryside at golden hour, a red wooden barn, green crop fields, a tractor, "
    "a few cows grazing behind a wooden fence, warm natural light, true-to-life "
    "colors, detailed textures, photorealistic, no text, no logo"
)


@lru_cache(maxsize=1)
def flux_client() -> Client:
    """Reuse one connection to the official FLUX.1-schnell Space."""
    # ZeroGPU Spaces can have a queue. A generous timeout prevents the request
    # from failing while it waits for an available GPU.
    return Client(MODEL_SPACE, httpx_kwargs={"timeout": 180.0})


def generate_image(
    prompt: str,
    seed: int,
    randomize_seed: bool,
    width: int,
    height: int,
    steps: int,
):
    prompt = prompt.strip()
    if not prompt:
        raise gr.Error("Veuillez écrire une description de l’image.")

    try:
        result = flux_client().predict(
            prompt=prompt,
            seed=int(seed),
            randomize_seed=bool(randomize_seed),
            width=int(width),
            height=int(height),
            num_inference_steps=int(steps),
            api_name="/infer",
        )
    except Exception as exc:
        raise gr.Error(
            "La génération FLUX.1 est momentanément indisponible. "
            "Veuillez réessayer dans quelques instants."
        ) from exc

    if isinstance(result, (tuple, list)):
        image = result[0]
        used_seed = result[1] if len(result) > 1 else seed
    else:
        image = result
        used_seed = seed

    if isinstance(image, dict):
        image = image.get("path") or image.get("url")

    return image, int(used_seed)


with gr.Blocks(title="Générateur réaliste FLUX.1") as demo:
    gr.Markdown(
        """
        # Générateur d’images réalistes FLUX.1

        Décrivez l’image souhaitée, ajustez les paramètres si nécessaire,
        puis cliquez sur **Générer l’image**.
        """
    )

    with gr.Row():
        with gr.Column(scale=2):
            prompt_input = gr.Textbox(
                label="Description de l’image",
                value=DEFAULT_PROMPT,
                lines=7,
                placeholder="Exemple : une ferme réaliste au coucher du soleil…",
            )

            with gr.Accordion("Paramètres avancés", open=False):
                seed_input = gr.Slider(
                    minimum=0,
                    maximum=2_147_483_647,
                    value=18_374_629,
                    step=1,
                    label="Graine",
                )
                randomize_seed_input = gr.Checkbox(
                    value=True,
                    label="Utiliser une nouvelle graine à chaque génération",
                )
                with gr.Row():
                    width_input = gr.Slider(
                        minimum=256,
                        maximum=1536,
                        value=1024,
                        step=32,
                        label="Largeur",
                    )
                    height_input = gr.Slider(
                        minimum=256,
                        maximum=1536,
                        value=768,
                        step=32,
                        label="Hauteur",
                    )
                steps_input = gr.Slider(
                    minimum=1,
                    maximum=8,
                    value=4,
                    step=1,
                    label="Nombre d’étapes",
                )

            generate_button = gr.Button("Générer l’image", variant="primary")

        with gr.Column(scale=3):
            image_output = gr.Image(label="Image générée", type="filepath")
            seed_output = gr.Number(label="Graine utilisée", precision=0)

    generate_button.click(
        fn=generate_image,
        inputs=[
            prompt_input,
            seed_input,
            randomize_seed_input,
            width_input,
            height_input,
            steps_input,
        ],
        outputs=[image_output, seed_output],
        api_name="generate",
    )

    prompt_input.submit(
        fn=generate_image,
        inputs=[
            prompt_input,
            seed_input,
            randomize_seed_input,
            width_input,
            height_input,
            steps_input,
        ],
        outputs=[image_output, seed_output],
    )


if __name__ == "__main__":
    demo.queue(default_concurrency_limit=2).launch()
app.py


from functools import lru_cache

import gradio as gr
from gradio_client import Client


MODEL_SPACE = "black-forest-labs/FLUX.1-schnell"
DEFAULT_PROMPT = (
    "A highly realistic photograph of a peaceful working farm in the Canadian "
    "countryside at golden hour, a red wooden barn, green crop fields, a tractor, "
    "a few cows grazing behind a wooden fence, warm natural light, true-to-life "
    "colors, detailed textures, photorealistic, no text, no logo"
)


@lru_cache(maxsize=1)
def flux_client() -> Client:
    """Reuse one connection to the official FLUX.1-schnell Space."""
    # ZeroGPU Spaces can have a queue. A generous timeout prevents the request
    # from failing while it waits for an available GPU.
    return Client(MODEL_SPACE, httpx_kwargs={"timeout": 180.0})


def generate_image(
    prompt: str,
    seed: int,
    randomize_seed: bool,
    width: int,
    height: int,
    steps: int,
):
    prompt = prompt.strip()
    if not prompt:
        raise gr.Error("Veuillez écrire une description de l’image.")

    try:
        result = flux_client().predict(
            prompt=prompt,
            seed=int(seed),
            randomize_seed=bool(randomize_seed),
            width=int(width),
            height=int(height),
            num_inference_steps=int(steps),
            api_name="/infer",
        )
    except Exception as exc:
        raise gr.Error(
            "La génération FLUX.1 est momentanément indisponible. "
            "Veuillez réessayer dans quelques instants."
        ) from exc

    if isinstance(result, (tuple, list)):
        image = result[0]
        used_seed = result[1] if len(result) > 1 else seed
    else:
        image = result
        used_seed = seed

    if isinstance(image, dict):
        image = image.get("path") or image.get("url")

    return image, int(used_seed)


with gr.Blocks(title="Générateur réaliste FLUX.1") as demo:
    gr.Markdown(
        """
        # Générateur d’images réalistes FLUX.1

        Décrivez l’image souhaitée, ajustez les paramètres si nécessaire,
        puis cliquez sur **Générer l’image**.
        """
    )

    with gr.Row():
        with gr.Column(scale=2):
            prompt_input = gr.Textbox(
                label="Description de l’image",
                value=DEFAULT_PROMPT,
                lines=7,
                placeholder="Exemple : une ferme réaliste au coucher du soleil…",
            )

            with gr.Accordion("Paramètres avancés", open=False):
                seed_input = gr.Slider(
                    minimum=0,
                    maximum=2_147_483_647,
                    value=18_374_629,
                    step=1,
                    label="Graine",
                )
                randomize_seed_input = gr.Checkbox(
                    value=True,
                    label="Utiliser une nouvelle graine à chaque génération",
                )
                with gr.Row():
                    width_input = gr.Slider(
                        minimum=256,
                        maximum=1536,
                        value=1024,
                        step=32,
                        label="Largeur",
                    )
                    height_input = gr.Slider(
                        minimum=256,
                        maximum=1536,
                        value=768,
                        step=32,
                        label="Hauteur",
                    )
                steps_input = gr.Slider(
                    minimum=1,
                    maximum=8,
                    value=4,
                    step=1,
                    label="Nombre d’étapes",
                )

            generate_button = gr.Button("Générer l’image", variant="primary")

        with gr.Column(scale=3):
            image_output = gr.Image(label="Image générée", type="filepath")
            seed_output = gr.Number(label="Graine utilisée", precision=0)

    generate_button.click(
        fn=generate_image,
        inputs=[
            prompt_input,
            seed_input,
            randomize_seed_input,
            width_input,
            height_input,
            steps_input,
        ],
        outputs=[image_output, seed_output],
        api_name="generate",
    )

    prompt_input.submit(
        fn=generate_image,
        inputs=[
            prompt_input,
            seed_input,
            randomize_seed_input,
            width_input,
            height_input,
            steps_input,
        ],
        outputs=[image_output, seed_output],
    )


if __name__ == "__main__":
    demo.queue(default_concurrency_limit=2).launch()