web / app.py
Khalil04's picture
Update app.py
1b6b50c verified
Raw History Blame Contribute Delete
9.34 kB
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()